Compare commits

..

5 Commits
dev ... main

Author SHA1 Message Date
mula.liu 37658ed61d Release Squid 0.1.10 with flat icons and tabbed settings 2026-11-20 03:53:28 +08:00
mula.liu cea60cc6c1 Release Squid 0.1.9 with low-CPU desktop monitor
Merge the dev monitor optimizations on top of the unreleased 0.1.8 desktop work: shared light snapshots, visibility-aware polling, CPU history/per-core panel, and a resize/redock guard that stops the widget IPC loop.

Also carries the desktop widget, permissions/security, storage-volume fixes, update-installer cleanup category, tray template icon, and Windows Recycle Bin wording.
2026-11-19 10:21:43 +08:00
mula.liu 8490f9213c Release Squid 0.1.7 with redesigned overview and corrected system metrics 2026-11-08 10:09:13 +08:00
mula.liu eb8f899fe0 Release Squid 0.1.6 with malware scanning and startup management
Adds the Protection half of the app: a Security page (quick / full / custom
scans, findings by confidence, quarantine and restore) and a Startup items
page (LaunchAgents, login items, registry Run, scheduled tasks, services),
plus a Processes tab on the real-time monitor that joins a running process to
the entry that launched it. XProtect and Defender stay the real-time
protection — Squid only reads what they report, uploads nothing, and installs
no daemon, kext or privileged helper.

On the interface, the two new screens reuse the vocabulary the older screens
already had instead of starting a second one: `.panel`, `.status-chip`,
`.search-field`, `.icon-button`, `.text-button`, `.metric-icon` with `tone-*`,
`.settings-row`. Findings, startup entries and quarantined files share one row
shape, so a row is one definition for three screens. Explanatory copy was cut to
one sentence per screen and per control, and a count now sits on the filter that
produces it rather than also in a summary line above.

Two defects fixed on the way:

- `src-tauri` is excluded from the root workspace and had no `[profile.release]`
  of its own, so no desktop build had ever been stripped; the universal binary
  is 20.6 MiB smaller now. `panic` stays unwind — turning a failed request into
  a dead app is not a change this release should be making.
- The schedule note was built in Rust as an English string, so a Chinese
  interface showed "squid only scans when you ask." beside everything else in
  Chinese. The schedule is now described once, in the frontend, in both
  languages.
2026-11-07 11:09:37 +08:00
mula.liu 6d9db8b700 Release Squid 0.1.5 with language and startup controls 2026-11-05 23:39:38 +08:00
192 changed files with 27268 additions and 7339 deletions

12
.gitignore vendored
View File

@ -59,11 +59,17 @@ __pycache__/
!.env.example !.env.example
*.local *.local
# 输入法/软件在 cwd 落的调试日志(sogou 等)
debug.log
# ── 显式纳管的发布产物 ─────────────────────────────────────────────── # ── 显式纳管的发布产物 ───────────────────────────────────────────────
!release/0.1.3/Squid-0.1.3-macOS-universal.dmg !release/0.1.3/Squid-0.1.3-macOS-universal.dmg
!release/0.1.3/Squid-Setup-0.1.3-win-x64.exe !release/0.1.3/Squid-Setup-0.1.3-win-x64.exe
!release/0.1.4/Squid-0.1.4-macOS-universal.dmg !release/0.1.4/Squid-0.1.4-macOS-universal.dmg
!release/0.1.4/Squid-Setup-0.1.4-win-x64.exe !release/0.1.4/Squid-Setup-0.1.4-win-x64.exe
!release/0.1.5/Squid-0.1.5-macOS-universal.dmg
# 输入法/软件在 cwd 落的调试日志(sogou 等) !release/0.1.5/Squid-Setup-0.1.5-win-x64.exe
debug.log !release/0.1.6/Squid-0.1.6-macOS-universal.dmg
!release/0.1.6/Squid-Setup-0.1.6-win-x64.exe
!release/0.1.7/Squid-0.1.7-macOS-universal.dmg
!release/0.1.7/Squid-Setup-0.1.7-win-x64.exe

View File

@ -18,7 +18,7 @@ default:
rust-lint-test: rust-lint-test:
stage: check stage: check
image: rust:1.85 image: rust:1.95
cache: cache:
key: key:
files: [Cargo.lock] files: [Cargo.lock]
@ -31,7 +31,7 @@ rust-lint-test:
windows-cross-check: windows-cross-check:
stage: check stage: check
image: rust:1.85 image: rust:1.95
cache: cache:
key: key:
files: [Cargo.lock] files: [Cargo.lock]
@ -74,7 +74,7 @@ desktop-frontend:
desktop-rust-check: desktop-rust-check:
stage: check stage: check
image: rust:1.85 image: rust:1.95
needs: needs:
- job: desktop-frontend - job: desktop-frontend
artifacts: true artifacts: true

3552
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@ exclude = ["src-tauri"]
[workspace.package] [workspace.package]
version = "0.1.10" version = "0.1.10"
edition = "2021" edition = "2021"
rust-version = "1.80" rust-version = "1.95"
license = "GPL-3.0-only" license = "GPL-3.0-only"
authors = ["squid contributors"] authors = ["squid contributors"]
repository = "https://github.com/nexdev/squid" repository = "https://github.com/nexdev/squid"
@ -18,6 +18,7 @@ squid-platform = { path = "crates/squid-platform" }
squid-rules = { path = "crates/squid-rules" } squid-rules = { path = "crates/squid-rules" }
squid-engine = { path = "crates/squid-engine" } squid-engine = { path = "crates/squid-engine" }
squid-stats = { path = "crates/squid-stats" } squid-stats = { path = "crates/squid-stats" }
squid-guard = { path = "crates/squid-guard" }
squid-tui = { path = "crates/squid-tui" } squid-tui = { path = "crates/squid-tui" }
anyhow = "1" anyhow = "1"
@ -33,9 +34,9 @@ dirs = "6"
libc = "0.2" libc = "0.2"
plist = "1" plist = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk"] } sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk", "user"] }
crossterm = "0.28" crossterm = "0.28"
ratatui = "0.29" ratatui = "0.30"
unicode-width = "0.2" unicode-width = "0.2"
clap = { version = "4.5", features = ["derive", "env", "wrap_help"] } clap = { version = "4.5", features = ["derive", "env", "wrap_help"] }

333
README.en.md 100644
View File

@ -0,0 +1,333 @@
# Squid
[简体中文](README.zh-CN.md) · [Bilingual home](README.md)
**Give your computer a bath.**
Squid is a local system-care app for macOS and Windows. It cleans rebuildable caches and system junk, uninstalls apps with their leftovers, removes project build artefacts, maps disk usage, shows live system health, and scans for malware with reversible quarantine.
The desktop app, CLI, and TUI share one Rust scan-and-delete engine. Cleaning rules, safety boundaries, the deletion ledger, and settings live in one place. Squid requires no cloud service and no root access.
## Product surfaces
| Surface | Stack | Binary |
| --- | --- | --- |
| Desktop app | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
| CLI | Rust + clap | `squid` |
| TUI | Rust + ratatui + crossterm | `squid state` |
The desktop app supports macOS 12+ and Windows 10/11 x64. The CLI and TUI share the same Rust workspace.
## Features
| Feature | Description |
| --- | --- |
| Overview | Disk health, common actions, and CPU, memory, and storage summaries |
| Daily cleanup | 38 built-in rules on macOS and 30 on Windows, covering app and browser caches, logs, crash reports, developer caches, Trash, and more |
| Uninstall apps | Finds an app by name and builds one plan containing the app bundle plus preferences, caches, containers, or AppData leftovers |
| Deep Clean | Finds rebuildable build output such as `node_modules`, disk images, installers, and stale downloads while protecting recently used projects |
| Storage | Measures folders level by level, with the largest children and files |
| Real-time monitor | Samples CPU, memory, network, disk, battery, volumes, and high-usage processes every two seconds. The Processes tab lists every process with its signature and startup entry, and ends them after confirmation |
| Security | Reports XProtect or Defender status, scans for malware by hash, YARA rule and heuristic, grades findings confirmed / suspicious / advisory, and quarantines them reversibly |
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; the ones the current user owns can be disabled and re-enabled |
| Permissions (Windows) | Registry Run keys, startup folders and scheduled tasks, shell context-menu handlers, popup-window rules and a background watcher |
| Desktop widget | A borderless board pinned from Real-time monitor, with CPU / memory / GPU rings, network and disk curves, and storage bars; all settings open from the top of the widget |
| History and undo | Every real deletion is recorded in a local ledger; items still in Trash or the Recycle Bin can be restored |
| System updates | Checks, verifies, downloads, and installs new versions from the release channel |
Language settings offer only Simplified Chinese and English, with the current system language selected by default. A manual choice is saved as the interface language for this computer.
## Desktop app
### Sidebar
- **Maintenance**: Overview, Daily cleanup, Uninstall apps, Deep Clean, Permissions (Windows only)
- **Protection**: Security, Startup items
- **Insights**: Storage, Real-time monitor
- **Bottom**: History, Settings
Use `⌘1`–`⌘8` on macOS or `Ctrl+1`–`Ctrl+9` on Windows to switch pages, in the
sidebar order. Windows maps `1`–`9` to Overview, Daily cleanup, Uninstall apps,
Deep Clean, Permissions, Storage, Real-time monitor, Security and Startup items.
macOS hides the Windows-only Permissions screen, so the later pages shift up by
one.
### Menu bar / tray
Closing the main window only hides it; Squid keeps running. The tray menu offers:
- Open Squid
- Protection status (a read-only status line)
- Scan for malware
- Manage startup items
- Daily cleanup
- Uninstall apps
- Deep Clean
- Show / hide desktop widget
- Quit Squid
The tray mark is transparent and monochrome: macOS receives it as a template
image, so the system tints it correctly for light and dark menu bars; Windows and
Linux show the same silhouette in gray.
The tray follows the active interface language. Reopening the app, double-clicking the app icon, or triggering the single-instance handler restores and focuses the main window. Only **Quit Squid** ends the process.
### Desktop widget
The desktop widget is switched on from Real-time monitor. It is a separate
borderless Tauri window, not a WidgetKit extension. It shares the Real-time
monitor sampler, refreshes at 2 / 5 / 10 seconds, and pauses while hidden.
- Every setting lives in the widget: click the gear at its top to open panel
switches, refresh rate, dock corner, fold memory and opacity.
- Up to four cards: status (CPU, memory and GPU when the OS exposes it), network,
disk I/O and storage volumes.
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
non-focusable with `accept_first_mouse`, so it stays beside the desktop without
taking keyboard focus from the current app.
- On Windows it sits on the desktop layer through
`SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)`.
- The master switch is shared with the tray item; opacity is capped at 90–100%
and settings persist in `widget.json`.
### Software updates
- The system information panel always shows the current OS version, architecture, and Squid version.
- Version changes, release notes, and actions appear only when a newer version exists; there is no duplicate "up to date" message.
- After a verified download, install and restart, or use the neutral outlined **Discard** button that matches Shift to remove the downloaded file.
- Automatic checks are enabled by default and run at most once per day.
- Installers must match the manifest's size and SHA256. Builds with a release public key also verify the manifest's Ed25519 signature.
### Permissions and privacy
- On first launch, Squid shows a security-readiness card once: system protection, scan
access, notifications, launch at login and rule updates. Every item is optional, no
permission is requested that you did not ask for, and closing the card changes nothing.
- Full Disk Access stays optional. Without it, protected folders are skipped and the
Security page reports the coverage as limited rather than clean.
- **Settings → System permissions** provides a status check and a shortcut to **System Settings → Privacy & Security → Full Disk Access**.
- Without Full Disk Access, TCC-protected locations are skipped and every other feature remains available.
- Storage analysis and Deep Clean read only user-selected or configured folders; file contents are never uploaded.
- The app makes no network requests other than update checks, installer downloads and
rule-pack downloads. **Nothing is ever uploaded**: no file name, hash, finding or
quarantined file leaves the machine.
- Security scanning does not install a daemon, kernel extension or privileged helper.
XProtect and Defender stay the real-time protection; Squid reads their state, never
turns them off, and never calls `xprotect update` on your behalf.
### Launch at login
**Settings → Startup** includes a launch-at-login switch. When enabled, Squid starts automatically after the current user signs in and keeps its tray entry available. The setting is user-level and requires no administrator access.
See [`docs/DESKTOP.md`](docs/DESKTOP.md) for details.
## Quick start
### Desktop development
Requirements:
- Node.js 20+ and pnpm
- Stable Rust
- macOS: Xcode Command Line Tools
- Windows: MSVC Build Tools and WebView2 Runtime
```bash
pnpm install
pnpm desktop:dev
```
A plain Vite page cannot call Tauri commands. Use `pnpm desktop:dev` when testing scans, deletion, system data, or updates.
### CLI / TUI
```bash
cargo install --path crates/squid-cli
# or
cargo build --release -p squid-cli
squid state # TUI
squid status # system snapshot
squid clean --dry-run # preview cleanable items
squid uninstall --list # installed apps
squid purge ~/code # project build artefacts
squid analyze ~/Library/Caches # storage analysis
squid history # deletion ledger
squid undo # restore the latest Trash session
```
Common commands:
| Command | Purpose |
| --- | --- |
| `clean` | Clean caches, logs, browser and developer junk, crash reports, and Trash by rule |
| `uninstall [NAME]` | Locate an app and build an app-plus-leftovers uninstall plan |
| `purge [PATHS…]` | Remove project build folders, disk images, installers, and stale downloads |
| `state` | Open the TUI with cleanup, uninstall, deep clean, storage, system, and history panels |
| `status` | Print a CPU, memory, network, disk, battery, and process snapshot |
| `analyze [PATH]` | Print a directory-size tree and the largest files |
| `history` / `undo [ID]` | Review history or restore a Trash session |
| `whitelist add\|list\|remove` | Maintain protected paths that are never selected |
| `rules` | List active rules |
| `doctor` | Check permissions, configuration, history, and effective paths |
| `guard status` | Report XProtect or Defender state, rule-pack version, startup counts and quarantine size |
| `guard scan [PATHS…]` | Scan for malware. No paths uses the quick range; `--full`, `--json`, `-y` to auto-quarantine confirmed |
| `guard startup` | List login/startup entries; `--all` includes the operating system's own, `--risky` filters |
| `guard quarantine <ID>` / `restore <ID>` | Act on a finding id a scan printed, or put a quarantined file back |
| `guard held` | List what the quarantine holds, and why |
Every delete command supports `--dry-run`; non-interactive environments require `-y/--yes`. Run `squid <command> --help` for complete options.
## Architecture
```text
crates/
├── squid-core models, paths, safety policy, settings, deletion ledger, progress, cancellation
├── squid-platform macOS / Linux / Windows adapters: apps, leftovers, volumes, Trash, processes
├── squid-rules TOML rule engine: expansion, anchors, protection, age, and risk flags
├── squid-stats sysinfo sampling, trends, battery, network, and disk activity
├── squid-guard malware scanning, YARA and hash rules, startup trust, reversible quarantine
├── squid-engine clean / uninstall / purge / analyze and the single deletion path
├── squid-tui ratatui terminal interface
└── squid-cli clap command-line entry point
src/ React desktop interface
src-tauri/ Tauri shell, commands, tray, permission checks, and updater
scripts/ development, verification, and dual-platform release scripts
docs/ architecture, design, desktop, and release specifications
```
`src-tauri` is separate from the root Cargo workspace, but depends directly on `squid-core`, `squid-platform`, `squid-guard`, `squid-stats`, and `squid-engine`. The desktop app does not maintain a second cleanup implementation.
See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for architecture details and [`docs/DESIGN.md`](docs/DESIGN.md) for the shared Nex color, typography, component, and language rules.
## Safety model
1. **Index-based deletion**: the desktop UI can only submit indexes from a scan, never arbitrary paths.
2. **Revalidation before execution**: the Rust layer rebuilds each item and rechecks ownership, safety anchors, protected locations, the whitelist, and lock state.
3. **Trash by default**: deletion mode defaults to `trash`; files are removed directly only when permanent deletion is explicitly selected.
4. **Hard boundaries**: system roots, `/usr`, `/System`, `/Applications`, and similar locations cannot be recursively deleted. Symlinks are never followed.
5. **Rule brakes**: rules support `protect`, `min_age_days`, `skip_if_running`, and `risky`.
6. **Ledger and undo**: real deletions are recorded in a local JSON ledger; files still in Trash can be restored.
7. **Process protection**: the process is sampled again before termination; Squid itself, PID 1, and critical system processes are refused.
The GUI and CLI use the same `squid-engine::delete` path, so behavior, locks, and audit results stay consistent.
## Data and configuration
| Purpose | macOS | Windows |
| --- | --- | --- |
| Configuration and rules | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
| History ledger | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
| Delete destination | `~/.Trash` or permanent deletion | Recycle Bin or permanent deletion |
Linux uses XDG directories. The desktop app and CLI/TUI share configuration and history, so a cleanup from either surface is visible in the other.
Common configuration:
```toml
delete_mode = "trash"
history_keep = 60
purge_min_age_days = 7
purge_max_entries = 200000
show_allocated = true
# Empty or omitted means "follow system"; set "en" or "zh" to override
language = ""
whitelist = ["~/Library/Caches/ImportantApp"]
disabled_rules = ["user-trash"]
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
```
Main environment variables:
| Variable | Purpose |
| --- | --- |
| `SQUID_CONFIG_DIR` | Override the configuration directory |
| `SQUID_STATE_DIR` | Override the state and history directory |
| `SQUID_LANG` | Force the CLI/TUI language to `zh` or `en` |
| `SQUID_UPDATE_URL` | Override the desktop update manifest URL for staging |
| `SQUID_TRUECOLOR` / `NO_COLOR` | Control TUI color |
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | Diagnose Windows console character width and layout |
`SQUID_LANG` is a CLI override. The desktop app's default language comes from the system and can be changed in the app.
## Development and verification
Frontend:
```bash
pnpm check
pnpm build
```
Rust workspace:
```bash
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --no-fail-fast
```
Tauri:
```bash
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
cargo test --manifest-path src-tauri/Cargo.toml --lib
```
The TUI uses a real-pty smoke test; Windows consoles also have a capture, replay, and frame-check test:
```bash
python3 -m pip install --user pyte
python3 scripts/tui_smoke.py
python3 scripts/tui-frame-check.py --selftest
```
CI runs workspace tests, an MSVC target cross-check, the desktop frontend build, and the Tauri Rust check.
## Build and release
Keep the version identical in all four places:
- `Cargo.toml` workspace version
- `src-tauri/Cargo.toml`
- `src-tauri/tauri.conf.json`
- `package.json`
Build installers:
```bash
scripts/build-macos-release.sh
scripts/build-windows-release.sh
```
Artifacts:
```text
artifacts/Squid-<version>-macOS-universal.dmg
artifacts/Squid-Setup-<version>-win-x64.exe
artifacts/SHA256SUMS.txt
```
Publish to the update channel:
```bash
scripts/publish-release.sh --notes /path/to/release-notes.md
```
The publish script rebuilds the `releases` branch with `squid-update.json`, both installers, and an optional `squid-update.sig`. The manifest records exact size and SHA256, which the client verifies again after download.
See [`docs/RELEASE.md`](docs/RELEASE.md) for the full release, signing, and manifest process.
## Platform status
| Platform | Status |
| --- | --- |
| macOS | Full desktop and CLI/TUI support; universal DMG |
| Windows x64 | Desktop and CLI/TUI support; NSIS installer |
| Linux | Platform layer and basic CLI/TUI support; built-in rules and desktop installers are not yet provided |
## License
Squid is licensed under **GNU General Public License v3.0 only** (`GPL-3.0-only`). See [`LICENSE`](LICENSE).

284
README.md
View File

@ -1,279 +1,53 @@
# Squid # Squid
**给你的电脑洗个澡。** **给你的电脑洗个澡。** · **Give your computer a bath.**
Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建的缓存与系统垃圾、卸载应用并处理残留、清理项目构建产物、分析磁盘占用,以及实时查看系统状态。 [简体中文](README.zh-CN.md) · [English](README.en.md)
桌面端、命令行与 TUI 共用同一套 Rust 扫描和删除引擎。清理规则、安全边界、删除账本与配置只维护一份,不依赖云端服务,也不需要 root。 Squid is a local system-care app for macOS and Windows. It cleans rebuildable caches and system junk, uninstalls apps with their leftovers, removes project build artefacts, maps disk usage, and monitors live system health.
## 产品组成 Squid 是面向 macOS 与 Windows 的本地系统维护工具。桌面端、CLI 与 TUI 共用同一套 Rust 扫描和删除引擎,不依赖云端服务,也不需要 root。
| 入口 | 技术栈 | 二进制 | ## Highlights / 功能
| --- | --- | --- |
| 桌面应用 | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
| 命令行 | Rust + clap | `squid` |
| 终端界面 | Rust + ratatui + crossterm | `squid state` |
桌面端支持 macOS 12+ 与 Windows 10/11 x64;CLI/TUI 使用同一个 Rust workspace。 - **Daily cleanup / 日常清理** — 38 macOS rules and 30 Windows rules for caches, logs, crash reports, developer data, and Trash.
- **Uninstall apps / 应用卸载** — One plan for the app and its preferences, caches, containers, or AppData leftovers.
- **Deep Clean / 深度清理** — Rebuildable build output, disk images, installers, and stale downloads with project-age protection.
- **Storage & monitor / 存储与监控** — Folder-level disk analysis, live CPU, memory, network, disk, battery, and process views.
- **Security / 安全** — XProtect and Defender status, malware scanning with confirmed / suspicious / advisory findings, and reversible quarantine. No daemon, no kernel extension, no upload.
- **Startup items / 启动项** — LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable the ones you own.
- **Desktop widget / 桌面小工具** — Pin the Real-time monitor to the desktop as a focus-free board, with every setting in a dropdown at the top of the widget.
- **Permissions (Windows) / 权限管理** — Startup entries, shell context menus and popup-window blocking, with a background watcher.
- **History & updates / 历史与更新** — Restorable Trash sessions and a size- and SHA256-verified update channel.
## 功能 The interface follows the system language by default and can be switched to Simplified Chinese or English in Settings.
| 功能 | 说明 | 界面默认跟随系统语言,可在设置中切换简体中文或 English。
| --- | --- |
| 电脑概览 | 磁盘健康、常用操作入口与 CPU、内存、存储摘要 |
| 日常清理 | macOS 38 条 / Windows 30 条内置规则,覆盖应用与浏览器缓存、日志、崩溃报告、开发缓存与废纸篓等 |
| 应用卸载 | 按名称定位应用,把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划 |
| 深度清理 | 查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载,并保护近期仍在使用的项目 |
| 存储空间 | 逐层测量目录、查看最大子项与最大文件 |
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程 |
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
界面支持中文和英文,跟随 Squid 的语言设置与系统语言。 ## Start / 开始
## 桌面应用
### 左侧菜单
- **维护**:电脑概览、日常清理、应用卸载、深度清理
- **洞察**:存储空间、实时监控
- **底部**:历史记录、设置
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+8`(Windows)可以直接切换页面。
### 常驻托盘
关闭主窗口只会隐藏窗口,Squid 进程继续运行。托盘菜单提供:
- 打开 Squid
- 日常清理
- 应用卸载
- 深度清理
- 退出 Squid
再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。
### 软件更新
- 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。
- 只有检测到更高版本时,才显示版本变化和更新说明;已经是最新版本时不显示额外提示。
- 自动检查默认开启,每天最多检查一次。
- 安装包必须通过 SHA256 与文件大小校验;带发布公钥的构建还会校验清单的 Ed25519 签名。
### 权限与隐私
- 首次启动会显示一次可选的全盘访问检查,不会强制弹出 macOS 权限窗口,也不会阻止应用启动。
- “设置 → 系统权限”提供权限状态检查和打开“系统设置 → 隐私与安全性 → 全盘访问”的入口。
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用。
- 存储分析与深度清理只在用户选择或配置目录后读取;文件内容不会上传。
- 除更新检查和安装包下载外,应用不发起网络请求。
完整说明见 [`docs/DESKTOP.md`](docs/DESKTOP.md)。
## 快速开始
### 桌面端开发
环境要求:
- Node.js 20+ 与 pnpm
- Rust stable
- macOS:Xcode Command Line Tools
- Windows:MSVC Build Tools 与 WebView2 Runtime
```bash ```bash
pnpm install pnpm install
pnpm desktop:dev pnpm desktop:dev
``` ```
仅运行 Vite 页面时无法调用 Tauri 命令;需要验证扫描、删除、系统数据或更新流程时请使用 `pnpm desktop:dev`。 CLI / TUI:
### CLI / TUI
```bash ```bash
cargo install --path crates/squid-cli cargo install --path crates/squid-cli
# 或 squid state
cargo build --release -p squid-cli squid clean --dry-run
squid state # TUI
squid status # 系统快照
squid clean --dry-run # 预览可清理内容
squid uninstall --list # 已安装应用
squid purge ~/code # 深度清理项目构建产物
squid analyze ~/Library/Caches # 存储分析
squid history # 历史账本
squid undo # 还原最近一次废纸篓会话
``` ```
常用命令: ## Documentation / 文档
| 命令 | 作用 | - [中文完整说明](README.zh-CN.md)
| --- | --- | - [Full English guide](README.en.md)
| `clean` | 按规则清理缓存、日志、浏览器与开发者垃圾、崩溃报告和废纸篓 | - [Architecture / 架构](docs/ARCHITECTURE.md)
| `uninstall [NAME]` | 定位应用并生成“本体 + 残留”卸载计划 | - [Nex design standard / 设计规范](docs/DESIGN.md)
| `purge [PATHS…]` | 清理项目构建目录、磁盘镜像、安装包与陈旧下载 | - [Desktop / 桌面端](docs/DESKTOP.md)
| `state` | 打开包含清理、卸载、深度清理、存储、系统和历史面板的 TUI | - [Release and updates / 发布与更新](docs/RELEASE.md)
| `status` | 输出 CPU、内存、网络、磁盘、电池与进程快照 |
| `analyze [PATH]` | 输出目录体积树与最大文件 |
| `history` / `undo [ID]` | 查看历史或还原废纸篓会话 |
| `whitelist add\|list\|remove` | 维护永不选中的保护路径 |
| `rules` | 列出当前生效的规则 |
| `doctor` | 检查权限、配置、历史文件和生效路径 |
所有删除命令都支持 `--dry-run`;非交互环境必须使用 `-y/--yes`。完整参数请运行 `squid <command> --help`。 ## License / 许可证
## 架构 **GNU General Public License v3.0 only** (`GPL-3.0-only`). See [`LICENSE`](LICENSE).
```text
crates/
├── squid-core 模型、路径、安全策略、设置、删除账本、进度与取消
├── squid-platform macOS / Linux / Windows 平台适配:应用、残留、卷、回收站、进程
├── squid-rules TOML 规则引擎:模式展开、锚点、保护、年龄与风险标记
├── squid-stats sysinfo 采样、趋势、电池、网络与磁盘活动
├── squid-engine clean / uninstall / purge / analyze 与唯一删除通道
├── squid-tui ratatui 终端界面
└── squid-cli clap 命令行入口
src/ React 桌面界面
src-tauri/ Tauri 壳、命令适配、托盘、权限检查与更新器
scripts/ 开发、验证与双平台发布脚本
docs/ 架构、设计、桌面与发布规范
```
核心依赖方向:
```text
squid-core → squid-platform → squid-rules → squid-stats → squid-engine → squid-tui → squid-cli
```
`src-tauri` 独立于根 Cargo workspace,但直接依赖 `squid-core`、`squid-platform`、`squid-stats` 与 `squid-engine`,桌面端不维护第二套清理实现。
更多设计见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md);Nex 系列统一颜色、字体和组件常量见 [`docs/DESIGN.md`](docs/DESIGN.md)。
## 安全模型
1. **索引式删除**:桌面界面只能提交扫描结果中的索引,不能提交任意待删除路径。
2. **执行前复验**:Rust 层重新构造扫描条目,并检查路径所有权、安全锚点、保护列表、白名单与锁定状态。
3. **默认进废纸篓**:删除模式默认是 `trash`;只有显式选择永久删除才直接移除。
4. **硬性禁区**:系统根目录、`/usr`、`/System`、`/Applications` 等位置不能被递归删除;符号链接不会被跟随。
5. **规则刹车**:规则支持 `protect`、`min_age_days`、`skip_if_running` 与 `risky` 标记。
6. **账本与撤销**:真实删除记录到本地 JSON 账本,仍在废纸篓中的文件可以还原。
7. **进程保护**:结束进程前重新采样并核对名称,拒绝 Squid 自身、系统首进程和关键系统进程。
GUI 和 CLI 使用同一个 `squid-engine::delete` 通道,因此行为、锁定和审计结果一致。
## 数据与配置
| 用途 | macOS | Windows |
| --- | --- | --- |
| 配置与规则 | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
| 历史账本 | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
| 删除去向 | `~/.Trash` 或永久删除 | 回收站或永久删除 |
Linux 使用 XDG 目录。桌面端与 CLI/TUI 共用配置和历史,因此任一端产生的清理记录都能在另一端查看。
常用配置:
```toml
delete_mode = "trash"
history_keep = 60
purge_min_age_days = 7
purge_max_entries = 200000
show_allocated = true
language = "zh" # en | zh
whitelist = ["~/Library/Caches/ImportantApp"]
disabled_rules = ["user-trash"]
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
```
主要环境变量:
| 变量 | 作用 |
| --- | --- |
| `SQUID_CONFIG_DIR` | 覆盖配置目录 |
| `SQUID_STATE_DIR` | 覆盖状态与历史目录 |
| `SQUID_LANG` | 强制 `zh` 或 `en` |
| `SQUID_UPDATE_URL` | 覆盖桌面端更新清单地址,适合测试发布通道 |
| `SQUID_TRUECOLOR` / `NO_COLOR` | 控制 TUI 颜色 |
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | 排查 Windows 控制台字符宽度与排版 |
## 开发与验证
前端:
```bash
pnpm check
pnpm build
```
Rust workspace:
```bash
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
```
Tauri:
```bash
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
cargo test --manifest-path src-tauri/Cargo.toml --lib
```
TUI 使用真实 pty 冒烟测试;Windows 控制台另有“抓帧、复放、量框”验证:
```bash
python3 -m pip install --user pyte
python3 scripts/tui_smoke.py
python3 scripts/tui-frame-check.py --selftest
```
CI 同时执行 workspace 测试、MSVC 目标交叉检查、桌面前端构建和 Tauri Rust 检查。
## 打包与发布
版本必须同时写入以下四处:
- `Cargo.toml` workspace 版本
- `src-tauri/Cargo.toml`
- `src-tauri/tauri.conf.json`
- `package.json`
构建安装包:
```bash
scripts/build-macos-release.sh
scripts/build-windows-release.sh
```
产物:
```text
artifacts/Squid-<version>-macOS-universal.dmg
artifacts/Squid-Setup-<version>-win-x64.exe
artifacts/SHA256SUMS.txt
```
发布到更新通道:
```bash
scripts/publish-release.sh --notes /path/to/release-notes.md
```
发布脚本会重建 `releases` 分支,写入 `squid-update.json`、两个安装包和可选的 `squid-update.sig`。清单包含精确大小与 SHA256,客户端下载后再次校验。
完整发布流程、签名和清单格式见 [`docs/RELEASE.md`](docs/RELEASE.md)。
## 平台状态
| 平台 | 状态 |
| --- | --- |
| macOS | 桌面端与 CLI/TUI 完整支持,发布通用 DMG |
| Windows x64 | 桌面端与 CLI/TUI 支持,发布 NSIS 安装包 |
| Linux | 平台层与 CLI/TUI 基础实现;尚未提供内置 Linux 规则和桌面安装包 |
## 许可证
Squid 使用 **GNU General Public License v3.0 only**(`GPL-3.0-only`)。完整条款见 [`LICENSE`](LICENSE)。

313
README.zh-CN.md 100644
View File

@ -0,0 +1,313 @@
# Squid
[English](README.en.md) · [返回双语首页](README.md)
**给你的电脑洗个澡。**
Squid 是面向 macOS 与 Windows 的本地系统维护工具:清理可重建的缓存与系统垃圾、卸载应用并处理残留、清理项目构建产物、分析磁盘占用,以及实时查看系统状态。
桌面端、命令行与 TUI 共用同一套 Rust 扫描和删除引擎。清理规则、安全边界、删除账本与配置只维护一份,不依赖云端服务,也不需要 root。
## 产品组成
| 入口 | 技术栈 | 二进制 |
| --- | --- | --- |
| 桌面应用 | Tauri 2 + React 19 + TypeScript + Vite 6 | `squid-desktop` |
| 命令行 | Rust + clap | `squid` |
| 终端界面 | Rust + ratatui + crossterm | `squid state` |
桌面端支持 macOS 12+ 与 Windows 10/11 x64;CLI/TUI 使用同一个 Rust workspace。
## 功能
| 功能 | 说明 |
| --- | --- |
| 概览 | 磁盘健康、常用操作入口与 CPU、内存、存储摘要 |
| 日常清理 | macOS 38 条 / Windows 30 条内置规则,覆盖应用与浏览器缓存、日志、崩溃报告、开发缓存与废纸篓等 |
| 应用卸载 | 按名称定位应用,把应用本体与偏好、缓存、容器或 AppData 残留组成同一个卸载计划 |
| 深度清理 | 查找 `node_modules` 等可重建构建产物、磁盘镜像、安装包和陈旧下载,并保护近期仍在使用的项目 |
| 存储空间 | 逐层测量目录、查看最大子项与最大文件 |
| 实时监控 | 每两秒采样 CPU、内存、网络、磁盘、电池、卷和高占用进程,可确认后结束进程。「进程」页签列出全部进程及其签名与启动项来源 |
| 安全 | 读取 XProtect / Defender 状态,按哈希、YARA 规则与启发式扫描恶意软件,分「已确认 / 可疑 / 提示」三级,并可逆隔离 |
| 启动项 | LaunchAgent、LaunchDaemon、登录项、注册表 Run、启动文件夹、计划任务与服务;当前用户拥有的条目可停用与恢复 |
| 权限管理(Windows) | 注册表 Run、启动文件夹与计划任务,右键菜单扩展,弹窗窗口规则与后台监听 |
| 桌面小工具 | 在实时监控中一键固定到桌面的无边框看板:CPU / 内存 / GPU 圆环、网络与磁盘曲线、存储空间;设置从小工具顶部下拉打开 |
| 历史与撤销 | 每次真实删除写入本地账本;仍在废纸篓或回收站中的内容可以还原 |
| 系统更新 | 从发布分支检查、校验、下载并安装新版本 |
语言设置只提供简体中文与 English 两项,首次使用时默认选中当前系统语言。手动选择会保存为该电脑上的界面语言。
## 桌面应用
### 左侧菜单
- **维护**:概览、日常清理、应用卸载、深度清理、权限管理(仅 Windows)
- **保护**:安全、启动项
- **洞察**:存储空间、实时监控
- **底部**:历史记录、设置
`⌘1`–`⌘8`(macOS)或 `Ctrl+1`–`Ctrl+9`(Windows)按上面的侧栏顺序切换页面。
Windows 上 `1`–`9` 依次是概览、日常清理、应用卸载、深度清理、权限管理、存储空间、实时监控、安全、启动项;macOS 隐藏 Windows 专属的权限管理,后续页面顺延。
### 常驻托盘
关闭主窗口只会隐藏窗口,Squid 进程继续运行。托盘菜单提供:
- 打开 Squid
- 保护状态(只读状态行)
- 扫描恶意软件
- 管理启动项
- 日常清理
- 应用卸载
- 深度清理
- 显示/隐藏桌面小工具
- 退出 Squid
托盘图标是透明单色素材:macOS 使用模板图标,由系统按浅色/深色菜单栏自动着色;Windows 与 Linux 显示同一轮廓的灰色图标。
托盘菜单跟随当前界面语言。再次打开应用、双击应用图标或通过单实例唤起时,会恢复并聚焦主窗口。只有选择“退出 Squid”才会结束进程。
### 桌面小工具
桌面小工具由“实时监控”页面统一开关,是一个独立的无边框 Tauri 窗口,不是 WidgetKit 扩展。它复用实时监控的采样器,按 2 / 5 / 10 秒节奏刷新,隐藏时暂停采样。
- 设置全部位于小工具本身:点击顶部齿轮即可下拉打开面板、更新频率、边角停靠、折叠记忆与面板开关。
- 最多四张卡片:运行状态(CPU、内存、系统暴露的 GPU 占用)、网络、存储读写、存储空间。
- macOS 上使用 `BelowNormal` 窗口层级、出现在所有 Space,并设置为不可获得焦点且接受首次点击,因此贴着桌面显示、不会抢走当前应用的键盘焦点。
- Windows 上通过 `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` 停在桌面层。
- 总开关与托盘菜单同步;不透明度限制在 90–100%,配置保存在 `widget.json`。
### 软件更新
- 设置中的系统信息面板始终显示当前系统版本、架构与 Squid 版本。
- 只有检测到更高版本时,才显示版本变化、更新说明和操作按钮;已经是最新版本时不显示额外提示。
- 下载完成后可安装并重启,或用与 Shift 一致的中性描边“放弃”按钮清除已下载文件。
- 自动检查默认开启,每天最多检查一次。
- 安装包必须通过 SHA256 与文件大小校验;带发布公钥的构建还会校验清单的 Ed25519 签名。
### 权限与隐私
- 首次启动会显示一次可选的全盘访问检查,不会强制弹出 macOS 权限窗口,也不会阻止应用启动。
- “设置 → 系统权限”提供权限状态检查和打开“系统设置 → 隐私与安全性 → 全盘访问”的入口。
- 没有全盘访问时,受 TCC 保护的位置会被跳过,其余功能仍然可用;安全页会把覆盖范围标为「受限」,不会显示成干净。
- 存储分析与深度清理只在用户选择或配置目录后读取;文件内容不会上传。
- 除更新检查、安装包下载与规则包下载外,应用不发起网络请求。**任何内容都不会上传**:
文件名、哈希、扫描结果与被隔离的文件都不会离开这台电脑。
- 安全扫描不安装 daemon、内核扩展或特权 helper。实时防护仍由 XProtect / Defender 承担,
Squid 只读取它们的状态,不会替你关闭,也不会替你调用 `xprotect update`。
### 开机自启
“设置 → 启动”提供开机自启开关。启用后 Squid 会在当前用户登录时自动启动并保留托盘入口;该设置只写入当前用户级启动项,不需要管理员权限。
完整说明见 [`docs/DESKTOP.md`](docs/DESKTOP.md)。
## 快速开始
### 桌面端开发
环境要求:
- Node.js 20+ 与 pnpm
- Rust stable
- macOS:Xcode Command Line Tools
- Windows:MSVC Build Tools 与 WebView2 Runtime
```bash
pnpm install
pnpm desktop:dev
```
仅运行 Vite 页面时无法调用 Tauri 命令;需要验证扫描、删除、系统数据或更新流程时请使用 `pnpm desktop:dev`。
### CLI / TUI
```bash
cargo install --path crates/squid-cli
# 或
cargo build --release -p squid-cli
squid state # TUI
squid status # 系统快照
squid clean --dry-run # 预览可清理内容
squid uninstall --list # 已安装应用
squid purge ~/code # 深度清理项目构建产物
squid analyze ~/Library/Caches # 存储分析
squid history # 历史账本
squid undo # 还原最近一次废纸篓会话
```
常用命令:
| 命令 | 作用 |
| --- | --- |
| `clean` | 按规则清理缓存、日志、浏览器与开发者垃圾、崩溃报告和废纸篓 |
| `uninstall [NAME]` | 定位应用并生成“本体 + 残留”卸载计划 |
| `purge [PATHS…]` | 清理项目构建目录、磁盘镜像、安装包与陈旧下载 |
| `state` | 打开包含清理、卸载、深度清理、存储、系统和历史面板的 TUI |
| `status` | 输出 CPU、内存、网络、磁盘、电池与进程快照 |
| `analyze [PATH]` | 输出目录体积树与最大文件 |
| `history` / `undo [ID]` | 查看历史或还原废纸篓会话 |
| `whitelist add\|list\|remove` | 维护永不选中的保护路径 |
| `rules` | 列出当前生效的规则 |
| `doctor` | 检查权限、配置、历史文件和生效路径 |
| `guard status` | 报告 XProtect / Defender 状态、规则包版本、启动项数量与隔离区占用 |
| `guard scan [PATHS…]` | 扫描恶意软件。不给路径即快速范围;`--full`、`--json`、`-y` 自动隔离已确认项 |
| `guard startup` | 列出登录/启动条目;`--all` 含系统自带,`--risky` 只看需注意的 |
| `guard quarantine <ID>` / `restore <ID>` | 对扫描输出的发现 id 执行隔离或恢复 |
| `guard held` | 列出隔离区里有什么、以及当初为什么进来 |
所有删除命令都支持 `--dry-run`;非交互环境必须使用 `-y/--yes`。完整参数请运行 `squid <command> --help`。
## 架构
```text
crates/
├── squid-core 模型、路径、安全策略、设置、删除账本、进度与取消
├── squid-platform macOS / Linux / Windows 平台适配:应用、残留、卷、回收站、进程
├── squid-rules TOML 规则引擎:模式展开、锚点、保护、年龄与风险标记
├── squid-stats sysinfo 采样、趋势、电池、网络与磁盘活动
├── squid-engine clean / uninstall / purge / analyze 与唯一删除通道
├── squid-tui ratatui 终端界面
└── squid-cli clap 命令行入口
src/ React 桌面界面
src-tauri/ Tauri 壳、命令适配、托盘、权限检查与更新器
scripts/ 开发、验证与双平台发布脚本
docs/ 架构、设计、桌面与发布规范
```
`src-tauri` 独立于根 Cargo workspace,但直接依赖 `squid-core`、`squid-platform`、`squid-stats` 与 `squid-engine`,桌面端不维护第二套清理实现。
更多设计见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md);Nex 系列统一颜色、字体、组件和语言规范见 [`docs/DESIGN.md`](docs/DESIGN.md)。
## 安全模型
1. **索引式删除**:桌面界面只能提交扫描结果中的索引,不能提交任意待删除路径。
2. **执行前复验**:Rust 层重新构造扫描条目,并检查路径所有权、安全锚点、保护列表、白名单与锁定状态。
3. **默认进废纸篓**:删除模式默认是 `trash`;只有显式选择永久删除才直接移除。
4. **硬性禁区**:系统根目录、`/usr`、`/System`、`/Applications` 等位置不能被递归删除;符号链接不会被跟随。
5. **规则刹车**:规则支持 `protect`、`min_age_days`、`skip_if_running` 与 `risky` 标记。
6. **账本与撤销**:真实删除记录到本地 JSON 账本,仍在废纸篓中的文件可以还原。
7. **进程保护**:结束进程前重新采样并核对名称,拒绝 Squid 自身、系统首进程和关键系统进程。
GUI 和 CLI 使用同一个 `squid-engine::delete` 通道,因此行为、锁定和审计结果一致。
## 数据与配置
| 用途 | macOS | Windows |
| --- | --- | --- |
| 配置与规则 | `~/Library/Application Support/squid/` | `%APPDATA%\squid\` |
| 历史账本 | `~/Library/Application Support/squid/history/` | `%APPDATA%\squid\history\` |
| 删除去向 | `~/.Trash` 或永久删除 | 回收站或永久删除 |
Linux 使用 XDG 目录。桌面端与 CLI/TUI 共用配置和历史,因此任一端产生的清理记录都能在另一端查看。
常用配置:
```toml
delete_mode = "trash"
history_keep = 60
purge_min_age_days = 7
purge_max_entries = 200000
show_allocated = true
# language 留空或删除表示跟随系统;也可手动设为 "en" 或 "zh"
language = ""
whitelist = ["~/Library/Caches/ImportantApp"]
disabled_rules = ["user-trash"]
purge_roots = ["~/code", "~/Projects", "~/Desktop"]
```
主要环境变量:
| 变量 | 作用 |
| --- | --- |
| `SQUID_CONFIG_DIR` | 覆盖配置目录 |
| `SQUID_STATE_DIR` | 覆盖状态与历史目录 |
| `SQUID_LANG` | 强制 CLI/TUI 使用 `zh` 或 `en` |
| `SQUID_UPDATE_URL` | 覆盖桌面端更新清单地址,适合测试发布通道 |
| `SQUID_TRUECOLOR` / `NO_COLOR` | 控制 TUI 颜色 |
| `SQUID_SYMBOL_CELLS` / `SQUID_CONSOLE_TRACE` | 排查 Windows 控制台字符宽度与排版 |
`SQUID_LANG` 是命令行覆盖项;桌面界面的默认语言来自系统设置,并可在应用内修改。
## 开发与验证
前端:
```bash
pnpm check
pnpm build
```
Rust workspace:
```bash
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --no-fail-fast
```
Tauri:
```bash
cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
cargo test --manifest-path src-tauri/Cargo.toml --lib
```
TUI 使用真实 pty 冒烟测试;Windows 控制台另有“抓帧、复放、量框”验证:
```bash
python3 -m pip install --user pyte
python3 scripts/tui_smoke.py
python3 scripts/tui-frame-check.py --selftest
```
CI 同时执行 workspace 测试、MSVC 目标交叉检查、桌面前端构建和 Tauri Rust 检查。
## 打包与发布
版本必须同时写入以下四处:
- `Cargo.toml` workspace 版本
- `src-tauri/Cargo.toml`
- `src-tauri/tauri.conf.json`
- `package.json`
构建安装包:
```bash
scripts/build-macos-release.sh
scripts/build-windows-release.sh
```
产物:
```text
artifacts/Squid-<version>-macOS-universal.dmg
artifacts/Squid-Setup-<version>-win-x64.exe
artifacts/SHA256SUMS.txt
```
发布到更新通道:
```bash
scripts/publish-release.sh --notes /path/to/release-notes.md
```
发布脚本会重建 `releases` 分支,写入 `squid-update.json`、两个安装包和可选的 `squid-update.sig`。清单包含精确大小与 SHA256,客户端下载后再次校验。
完整发布流程、签名和清单格式见 [`docs/RELEASE.md`](docs/RELEASE.md)。
## 平台状态
| 平台 | 状态 |
| --- | --- |
| macOS | 桌面端与 CLI/TUI 完整支持,发布通用 DMG |
| Windows x64 | 桌面端与 CLI/TUI 支持,发布 NSIS 安装包 |
| Linux | 平台层与 CLI/TUI 基础实现;尚未提供内置 Linux 规则和桌面安装包 |
## 许可证
Squid 使用 **GNU General Public License v3.0 only**(`GPL-3.0-only`)。完整条款见 [`LICENSE`](LICENSE)。

View File

@ -17,6 +17,7 @@ squid-engine.workspace = true
squid-platform.workspace = true squid-platform.workspace = true
squid-rules.workspace = true squid-rules.workspace = true
squid-stats.workspace = true squid-stats.workspace = true
squid-guard.workspace = true
squid-tui.workspace = true squid-tui.workspace = true
anyhow.workspace = true anyhow.workspace = true
clap.workspace = true clap.workspace = true

View File

@ -0,0 +1,638 @@
//! `squid guard` — the security half of the command line.
//!
//! Three verbs carry the roadmap's CLI contract: `status` says what protects
//! this machine and what squid can see, `scan` finds things, `quarantine` acts on
//! a finding. The rest (`startup`, `held`, `restore`, `unignore`) exists because
//! a person reading a finding in a terminal needs the same follow-up the desktop
//! app offers, and it is all the same code underneath.
//!
//! The one asymmetry worth stating: `quarantine` takes a finding id, not a path.
//! A finding records the hash and size the scan saw, and the quarantine refuses
//! a file that has changed since. Taking a path from the command line would throw
//! that away, so the CLI re-runs the scan to find the id again instead.
use crate::{bullet, clip, heading, human_stream_is_tty, live, paint, shout, shrink};
use anyhow::Result;
use clap::{Args, Subcommand};
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{paths, Bytes, Settings};
use squid_guard::quarantine::Quarantine;
use squid_guard::scan::{Guard, ScanTarget};
use squid_guard::Confidence;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
#[derive(Args, Debug)]
pub struct GuardArgs {
#[command(subcommand)]
pub action: GuardAction,
}
#[derive(Subcommand, Debug)]
pub enum GuardAction {
/// What protects this machine right now, and what squid can see
Status {
#[arg(long)]
json: bool,
},
/// Scan for malware. With no paths, the quick-scan range is used.
Scan(ScanArgs),
/// What starts when this machine logs in
Startup(StartupArgs),
/// Move one finding into the quarantine, by the id a scan printed
Quarantine { id: String },
/// Put a quarantined file back where it came from
Restore { id: String },
/// What squid is holding, and why
Held {
#[arg(long)]
json: bool,
},
/// Stop ignoring a finding so future scans report it again
Unignore { fingerprint: String },
}
#[derive(Args, Debug)]
pub struct ScanArgs {
/// Paths to scan instead of the quick-scan range
paths: Vec<String>,
/// Also walk the folders a payload rarely lives in
#[arg(long)]
full: bool,
/// Machine-readable output with every finding and its evidence
#[arg(long)]
json: bool,
/// Quarantine confirmed findings without asking
#[arg(long, short = 'y')]
yes: bool,
}
#[derive(Args, Debug)]
pub struct StartupArgs {
/// Include the entries the operating system owns
#[arg(long)]
all: bool,
/// Only the entries that deserve a second look
#[arg(long)]
risky: bool,
#[arg(long)]
json: bool,
}
pub fn run(args: GuardArgs, json: bool) -> Result<i32> {
match args.action {
GuardAction::Status { json: as_json } => status(as_json || json),
GuardAction::Scan(args) => scan(args, json),
GuardAction::Startup(args) => startup(args),
GuardAction::Quarantine { id } => quarantine(&id),
GuardAction::Restore { id } => restore(&id),
GuardAction::Held { json: as_json } => held(as_json || json),
GuardAction::Unignore { fingerprint } => unignore(&fingerprint),
}
}
/// A guard with the user's exclusions applied. Built once per command so what
/// `status` reports and what `scan` uses cannot disagree.
fn context() -> Guard {
let (settings, errors) = Settings::load();
for error in errors {
shout("33", &format!("config: {error}"));
}
Guard::new(settings.security.exclusion_paths())
}
fn status(as_json: bool) -> Result<i32> {
let protection = squid_platform::protection::status();
let intel = squid_guard::intel::status();
let startup = squid_platform::startup::inventory();
let mut held = Quarantine::new();
let held_items = held.entries().len();
let held_size = held.total_size();
if as_json {
println!(
"{}",
serde_json::to_string_pretty(&serde_json::json!({
"protection": protection,
"rules": intel,
"startup": {
"total": startup.items.len(),
"user": startup.user_count(),
"system": startup.system_count(),
"disabled": startup.disabled_count(),
"notes": startup.notes,
},
"quarantine": { "items": held_items, "size": held_size },
}))?
);
return Ok(0);
}
heading("Protection");
let state = match protection.is_healthy() {
Some(true) => paint("32", "active"),
Some(false) => paint("31", "needs attention"),
None => paint("33", "unknown"),
};
let product = if protection.product_name.is_empty() {
protection.provider.as_str()
} else {
protection.product_name.as_str()
};
println!(
"{}",
crate::priced(&format!(
" {:<12} {} ({})",
paint("90", "system"),
state,
product
))
);
if !protection.definitions.is_empty() {
println!(
"{}",
crate::priced(&format!(
" {:<12} {}{}",
paint("90", "definitions"),
protection.definitions,
if protection.definitions_date.is_empty() {
String::new()
} else {
format!(" · from {}", protection.definitions_date)
}
))
);
}
let flag = |value: Option<bool>| match value {
Some(true) => paint("32", "on"),
Some(false) => paint("31", "off"),
None => paint("33", "unknown"),
};
for (label, value) in [
("background", protection.background_scans),
("at launch", protection.launch_scans),
("gatekeeper", protection.gatekeeper),
] {
if value.is_some() {
println!(
"{}",
crate::priced(&format!(" {:<12} {}", paint("90", label), flag(value)))
);
}
}
for note in &protection.notes {
shout("33", &format!(" ! {note}"));
}
heading("Squid");
let rules = if intel.source == "builtin" {
format!(
"{} built-in rules (no pack downloaded)",
intel.builtin_rules
)
} else {
format!(
"{} rules from pack r{}, {} built-in",
intel.installed_rules, intel.revision, intel.builtin_rules
)
};
for (label, value) in [
("rules", rules),
(
"startup",
format!(
"{} user · {} system · {} disabled",
startup.user_count(),
startup.system_count(),
startup.disabled_count()
),
),
(
"quarantine",
format!("{} items · {}", held_items, Bytes(held_size).human_long()),
),
] {
println!(
"{}",
crate::priced(&format!(" {:<12} {}", paint("90", label), value))
);
}
shout(
"90",
" squid reads the protection above; it does not replace it",
);
for note in &startup.notes {
shout("33", &format!(" ! {note}"));
}
println!();
shout("90", " squid guard scan · squid guard startup");
Ok(if protection.is_healthy() == Some(false) {
2
} else {
0
})
}
fn scan(args: ScanArgs, json: bool) -> Result<i32> {
let target = if !args.paths.is_empty() {
ScanTarget::Paths(args.paths.clone())
} else if args.full {
ScanTarget::Full
} else {
ScanTarget::Quick
};
let mode = target.mode();
shout(
"90",
&format!(" {} scan — {}", mode.as_str(), mode.estimate()),
);
let mut guard = context();
let started = std::time::Instant::now();
let report = with_progress("scan", &mut guard, move |guard, progress, cancel| {
guard.scan(&target, progress, cancel)
})?;
// Recording happens before anything is printed, so an interrupted report
// still leaves a finding id the next command can act on.
let mut store = squid_guard::store::Store::new();
store.set_scan(squid_guard::store::StoredScan::record(&report));
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
return Ok(if report.confirmed() > 0 { 2 } else { 0 });
}
heading(&format!("Security · {}", mode.as_str()));
if report.cancelled {
shout("33", " cancelled — this scan did not finish");
}
if report.findings.is_empty() {
if report.clean_and_complete() {
shout("32", " ✓ nothing found in the range this scan covers");
} else {
shout("33", " nothing found in what could be read");
}
}
for finding in &report.findings {
let dot = match finding.confidence {
Confidence::Confirmed => paint("31", "●"),
Confidence::Suspicious => paint("33", "●"),
Confidence::Advisory => paint("90", "○"),
};
shout(
"0",
&format!(
" {} {} {}",
dot,
paint("1", &shrink(&finding.name, 32)),
paint(
"90",
&shrink(finding.display_path.as_deref().unwrap_or(""), 54)
)
),
);
shout(
"0",
&format!(" {} {}", paint("90", "→"), shrink(&finding.title, 88)),
);
for item in finding.evidence.iter().take(3) {
shout("90", &format!(" {}", shrink(&item.summary(), 92)));
}
shout("36", &format!(" {}", finding.id));
}
for advisory in &report.system_advisories {
shout("90", &format!(" ○ {}", shrink(&advisory.description, 96)));
}
if !report.coverage.complete() {
shout("33", " coverage was limited:");
for gap in report.coverage.gaps() {
shout(
"33",
&format!(
" {} — {}",
gap.display_path,
gap.reason.as_deref().unwrap_or(gap.outcome.as_str())
),
);
}
}
shout(
"90",
&format!(
" {} files checked · {} reused · {} skipped · {:.1}s",
squid_core::bytes::format_thousands(report.examined as u64),
squid_core::bytes::format_thousands(report.cached as u64),
squid_core::bytes::format_thousands(report.skipped as u64),
started.elapsed().as_secs_f64()
),
);
// 2 means "this scan has something to act on", which covers a suspicious
// finding as well as one that never finished: a script should check the
// report, not infer safety from an exit code.
let incomplete = report.cancelled || !report.coverage.complete();
let (settings, _) = Settings::load();
let confirmed: Vec<_> = report
.findings
.iter()
.filter(|finding| finding.confidence == Confidence::Confirmed)
.collect();
if confirmed.is_empty() {
let outstanding = report.confirmed() + report.suspicious();
return Ok(if outstanding > 0 || incomplete { 2 } else { 0 });
}
if args.yes || settings.security.auto_quarantine {
let mut held = Quarantine::new();
for finding in confirmed {
match held.quarantine(finding) {
Ok(entry) => shout(
"32",
&format!(" quarantined {} ({})", entry.display_path, entry.id),
),
Err(error) => shout(
"31",
&format!(
" could not quarantine {}: {error}",
finding.display_path.clone().unwrap_or_default()
),
),
}
}
} else {
shout(
"90",
" nothing was moved — squid guard quarantine <id> acts on one finding",
);
}
Ok(2)
}
fn startup(args: StartupArgs) -> Result<i32> {
let inventory = squid_platform::startup::inventory();
if args.json {
println!("{}", serde_json::to_string_pretty(&inventory)?);
return Ok(0);
}
heading("Startup items");
let mut shown = 0_usize;
for item in &inventory.items {
if !args.all && item.system_vendor {
continue;
}
if args.risky && item.risks.is_empty() {
continue;
}
shown += 1;
let scope = match item.scope {
squid_platform::startup::StartupScope::User => paint("36", "user"),
squid_platform::startup::StartupScope::System => paint("90", "sys "),
};
let state = if item.disabled {
paint("33", "off")
} else if item.modifiable {
paint("32", "on ")
} else {
paint("90", "ro ")
};
shout(
"0",
&format!(
" {scope} {state} {} {}",
paint("1", &shrink(&item.name, 28)),
paint("90", &shrink(item.source.as_str(), 15))
),
);
shout("90", &format!(" {}", shrink(&item.command, 96)));
let mut marks: Vec<String> = item
.risks
.iter()
.map(|risk| format!("{risk:?}").to_lowercase().replace('_', "-"))
.collect();
if let Some(publisher) = &item.publisher {
marks.push(format!("signed: {publisher}"));
} else if !item.signed {
marks.push("unsigned".into());
}
if !marks.is_empty() {
shout("33", &format!(" {}", shrink(&marks.join(" · "), 96)));
}
}
println!();
shout(
"90",
&format!(
" {shown} of {} entries · {} belong to the operating system",
inventory.items.len(),
inventory
.items
.iter()
.filter(|item| item.system_vendor)
.count()
),
);
for note in &inventory.notes {
shout("33", &format!(" ! {note}"));
}
Ok(0)
}
fn quarantine(id: &str) -> Result<i32> {
let store = squid_guard::store::Store::new();
let Some(found) = store.finding(id) else {
shout(
"31",
&format!(" no finding {id} — run `squid guard scan` and use an id it printed"),
);
return Ok(1);
};
let finding = found.clone();
let mut held = Quarantine::new();
match held.quarantine(&finding) {
Ok(entry) => {
shout("32", &format!(" quarantined {}", entry.display_path));
shout("90", &format!(" squid guard restore {}", entry.id));
let mut store = squid_guard::store::Store::new();
store.update_scan(|scan| {
if let Some(tracked) = scan.findings.iter_mut().find(|f| f.id == id) {
tracked.quarantined = true;
}
});
Ok(0)
}
Err(error) => {
shout("31", &format!(" refused: {error}"));
Ok(1)
}
}
}
fn restore(id: &str) -> Result<i32> {
let mut held = Quarantine::new();
match held.restore(id) {
Ok(path) => {
shout("32", &format!(" restored {}", paths::pretty(&path)));
// The finding is live again on disk, so the next scan must be able
// to report it; clearing the flag keeps the stored scan honest.
let mut store = squid_guard::store::Store::new();
store.update_scan(|scan| {
for finding in &mut scan.findings {
if finding
.path
.as_ref()
.is_some_and(|candidate| paths::same_path(candidate, &path))
{
finding.quarantined = false;
}
}
});
Ok(0)
}
Err(error) => {
shout("31", &format!(" refused: {error}"));
Ok(1)
}
}
}
fn held(as_json: bool) -> Result<i32> {
let mut held = Quarantine::new();
if as_json {
println!("{}", serde_json::to_string_pretty(held.entries())?);
return Ok(0);
}
heading("Quarantine");
if held.entries().is_empty() {
shout("90", " empty — nothing has been moved out of the way");
return Ok(0);
}
for entry in held.entries() {
shout(
"0",
&format!(
" {} {} {}",
paint("33", "◆"),
paint("1", &shrink(&entry.display_path, 58)),
paint("90", &Bytes(entry.size).human_long())
),
);
shout(
"90",
&format!(" {} · {}", shrink(&entry.title, 58), entry.id),
);
}
println!();
shout(
"90",
&format!(
" {} items · {} · restore puts one back, the folder is the last copy",
held.entries().len(),
Bytes(held.total_size()).human_long()
),
);
shout(
"90",
&format!(
" {}",
paths::pretty(&squid_guard::coverage::quarantine_root())
),
);
Ok(0)
}
fn unignore(fingerprint: &str) -> Result<i32> {
let (mut settings, errors) = Settings::load();
for error in errors {
shout("33", &format!("config: {error}"));
}
if settings.security.unignore(fingerprint) {
let path = settings.save()?;
shout("32", &format!(" {fingerprint} will be reported again"));
shout("90", &format!(" saved {}", paths::pretty(&path)));
} else {
shout("90", &format!(" {fingerprint} was not ignored"));
}
Ok(0)
}
/// The same progress rendering the cleanup commands use, driven by a guard scan
/// rather than an `Engine`.
fn with_progress<T>(
label: &str,
guard: &mut Guard,
work: impl FnOnce(&mut Guard, &Progress, &CancelToken) -> squid_core::Result<T>,
) -> squid_core::Result<T> {
let label = label.to_owned();
let progress = Progress::new();
let cancel = CancelToken::new();
let printer = progress.clone();
let stop = Arc::new(AtomicBool::new(false));
let printer_stop = stop.clone();
let printer_thread = std::thread::spawn(move || {
let mut frames = label.chars();
loop {
let stop_now = printer_stop.load(Ordering::Relaxed);
for event in printer.drain() {
match event {
Event::Phase { phase, detail } => {
shout("36", &format!(" {} {phase} — {detail}", bullet()));
}
Event::Tick {
done,
total,
subject,
} => {
if human_stream_is_tty() {
let glyph = frames
.next()
.unwrap_or_else(|| label.chars().next().unwrap_or('#'));
let text = match total {
Some(total) if total > 0 => format!(
" {glyph} {done}/{}",
squid_core::bytes::format_thousands(total)
),
_ => format!(
" {glyph} {}",
squid_core::bytes::format_thousands(done)
),
};
let tail = subject
.as_ref()
.map(|path| shrink(&paths::pretty(path), 40))
.unwrap_or_default();
live(Some(&format!(
"{} {}",
paint("36", &text),
paint("90", &tail)
)));
}
}
Event::Warning(text) => shout("33", &format!(" ! {}", clip(&text, 100))),
Event::Note(text) => shout("90", &format!(" · {}", clip(&text, 100))),
Event::Deleted { path, freed } => shout(
"90",
&format!(
" ✓ {} ({})",
shrink(&paths::pretty(&path), 70),
freed.human()
),
),
Event::Bucket { .. } | Event::Done(_) => {}
}
}
if stop_now {
if human_stream_is_tty() {
live(None);
}
break;
}
std::thread::sleep(Duration::from_millis(40));
}
});
let result = work(guard, &progress, &cancel);
stop.store(true, Ordering::Relaxed);
let _ = printer_thread.join();
result
}

View File

@ -6,6 +6,8 @@
//! and the ledger. This file only parses arguments, shows progress and asks for //! and the ledger. This file only parses arguments, shows progress and asks for
//! confirmation. //! confirmation.
mod guard;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand}; use clap::{Args, Parser, Subcommand};
use crossterm::tty::IsTty; use crossterm::tty::IsTty;
@ -80,6 +82,8 @@ enum Command {
Rules, Rules,
/// Report permissions, settings and ledger health /// Report permissions, settings and ledger health
Doctor, Doctor,
/// Malware scan, login-item inventory and quarantine
Guard(guard::GuardArgs),
} }
#[derive(Args, Debug)] #[derive(Args, Debug)]
@ -231,7 +235,7 @@ fn change() -> &'static Exchange {
/// a console: whatever glass reads it tomorrow may well be able to afford the /// a console: whatever glass reads it tomorrow may well be able to afford the
/// `█`, and an archive of `#` is a worse record for the sake of a screen that /// `█`, and an archive of `#` is a worse record for the sake of a screen that
/// was never looking. Only a screen is offered the exchange. /// was never looking. Only a screen is offered the exchange.
fn priced(text: &str) -> String { pub(crate) fn priced(text: &str) -> String {
if !human_stream_is_tty() { if !human_stream_is_tty() {
return text.to_string(); return text.to_string();
} }
@ -288,7 +292,7 @@ fn say(text: &str) {
/// overwritten. Chrome may only be exchanged for ASCII when somebody is looking /// overwritten. Chrome may only be exchanged for ASCII when somebody is looking
/// at the console that cannot afford it — because that is the only place the /// at the console that cannot afford it — because that is the only place the
/// exchange is an improvement rather than a loss. /// exchange is an improvement rather than a loss.
fn human_stream_is_tty() -> bool { pub(crate) fn human_stream_is_tty() -> bool {
if DIAG_STDERR.load(Ordering::Relaxed) { if DIAG_STDERR.load(Ordering::Relaxed) {
std::io::stderr().is_tty() std::io::stderr().is_tty()
} else { } else {
@ -297,7 +301,7 @@ fn human_stream_is_tty() -> bool {
} }
/// Rewrite the live progress line, or clear it when `text` is `None`. /// Rewrite the live progress line, or clear it when `text` is `None`.
fn live(text: Option<&str>) { pub(crate) fn live(text: Option<&str>) {
let line = match text { let line = match text {
Some(text) => format!("\r\x1b[K{}", priced(text)), Some(text) => format!("\r\x1b[K{}", priced(text)),
None => "\r\x1b[K".to_string(), None => "\r\x1b[K".to_string(),
@ -381,12 +385,13 @@ fn run() -> Result<i32> {
Some(Command::Whitelist(args)) => cmd_whitelist(args), Some(Command::Whitelist(args)) => cmd_whitelist(args),
Some(Command::Rules) => cmd_rules(cli.json), Some(Command::Rules) => cmd_rules(cli.json),
Some(Command::Doctor) => cmd_doctor(), Some(Command::Doctor) => cmd_doctor(),
Some(Command::Guard(args)) => guard::run(args, cli.json),
} }
} }
// ---------------------------------------------------------------------- output // ---------------------------------------------------------------------- output
fn paint(code: &str, text: &str) -> String { pub(crate) fn paint(code: &str, text: &str) -> String {
if COLOR.load(Ordering::Relaxed) { if COLOR.load(Ordering::Relaxed) {
format!("\x1b[{code}m{text}\x1b[0m") format!("\x1b[{code}m{text}\x1b[0m")
} else { } else {
@ -394,13 +399,13 @@ fn paint(code: &str, text: &str) -> String {
} }
} }
fn shout(code: &str, text: &str) { pub(crate) fn shout(code: &str, text: &str) {
if !QUIET.load(Ordering::Relaxed) || code == "31" { if !QUIET.load(Ordering::Relaxed) || code == "31" {
diag(code, text); diag(code, text);
} }
} }
fn heading(text: &str) { pub(crate) fn heading(text: &str) {
if QUIET.load(Ordering::Relaxed) { if QUIET.load(Ordering::Relaxed) {
return; return;
} }
@ -409,7 +414,7 @@ fn heading(text: &str) {
diag("90", &"─".repeat(text.chars().count().min(64))); diag("90", &"─".repeat(text.chars().count().min(64)));
} }
fn shrink(text: &str, width: usize) -> String { pub(crate) fn shrink(text: &str, width: usize) -> String {
use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthChar;
if text.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>() <= width { if text.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>() <= width {
return text.to_string(); return text.to_string();
@ -430,7 +435,7 @@ fn shrink(text: &str, width: usize) -> String {
format!("...{out}") format!("...{out}")
} }
fn clip(text: &str, width: usize) -> String { pub(crate) fn clip(text: &str, width: usize) -> String {
use unicode_width::UnicodeWidthChar; use unicode_width::UnicodeWidthChar;
if text.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>() <= width { if text.chars().map(|c| c.width().unwrap_or(0)).sum::<usize>() <= width {
return text.to_string(); return text.to_string();
@ -594,7 +599,7 @@ fn with_progress<T>(
), ),
); );
} }
Event::Bucket { .. } | Event::Metered { .. } | Event::Done(_) => {} Event::Bucket { .. } | Event::Done(_) => {}
} }
} }
if stop_now { if stop_now {
@ -612,7 +617,7 @@ fn with_progress<T>(
result result
} }
fn bullet() -> String { pub(crate) fn bullet() -> String {
if COLOR.load(Ordering::Relaxed) { if COLOR.load(Ordering::Relaxed) {
"●".to_string() "●".to_string()
} else { } else {

View File

@ -23,6 +23,7 @@ rayon.workspace = true
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows = { version = "0.58", features = [ windows = { version = "0.58", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_Globalization",
"Win32_Security", "Win32_Security",
"Win32_Storage_FileSystem", "Win32_Storage_FileSystem",
"Win32_System_Com", "Win32_System_Com",

View File

@ -17,7 +17,7 @@ pub fn format_thousands(value: u64) -> String {
let digits = value.to_string(); let digits = value.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3); let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (idx, ch) in digits.chars().enumerate() { for (idx, ch) in digits.chars().enumerate() {
if idx > 0 && (digits.len() - idx) % 3 == 0 { if idx > 0 && (digits.len() - idx).is_multiple_of(3) {
out.push(','); out.push(',');
} }
out.push(ch); out.push(ch);

View File

@ -30,8 +30,6 @@ pub struct SizeInfo {
pub files: u64, pub files: u64,
pub dirs: u64, pub dirs: u64,
pub unreadable: u32, pub unreadable: u32,
/// Newest last-modified seen while walking (unix seconds). `0` = unknown.
pub newest_write: u64,
} }
impl SizeInfo { impl SizeInfo {
@ -58,7 +56,6 @@ impl SizeInfo {
self.files += other.files; self.files += other.files;
self.dirs += other.dirs; self.dirs += other.dirs;
self.unreadable += other.unreadable; self.unreadable += other.unreadable;
self.newest_write = self.newest_write.max(other.newest_write);
} }
/// "12,431 files" style annotation for detail rows. /// "12,431 files" style annotation for detail rows.
@ -210,7 +207,6 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
if meta.file_type().is_symlink() { if meta.file_type().is_symlink() {
info.files += 1; info.files += 1;
info.logical += Bytes(meta.len()); info.logical += Bytes(meta.len());
info.newest_write = mtime_secs(&meta);
return info; return info;
} }
match kind { match kind {
@ -218,7 +214,6 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info.files += 1; info.files += 1;
info.logical += Bytes(meta.len()); info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(path, &meta)); info.allocated += Bytes(allocated_bytes(path, &meta));
info.newest_write = mtime_secs(&meta);
return info; return info;
} }
ItemKind::Path | ItemKind::Contents => {} ItemKind::Path | ItemKind::Contents => {}
@ -227,7 +222,6 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info.files += 1; info.files += 1;
info.logical += Bytes(meta.len()); info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(path, &meta)); info.allocated += Bytes(allocated_bytes(path, &meta));
info.newest_write = mtime_secs(&meta);
return info; return info;
} }
@ -257,7 +251,6 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info.files += 1; info.files += 1;
info.logical += Bytes(meta.len()); info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(entry.path(), &meta)); info.allocated += Bytes(allocated_bytes(entry.path(), &meta));
info.newest_write = info.newest_write.max(mtime_secs(&meta));
} }
Err(_) => info.unreadable += 1, Err(_) => info.unreadable += 1,
} }
@ -268,14 +261,6 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info info
} }
/// Last-modified as unix seconds; 0 when the platform withholds it.
fn mtime_secs(meta: &Metadata) -> u64 {
meta.modified()
.ok()
.and_then(|when| when.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |age| age.as_secs())
}
/// Measure many paths in parallel. `progress` receives completed units. /// Measure many paths in parallel. `progress` receives completed units.
/// `Path` for folders (and anything that should be removed recursively), /// `Path` for folders (and anything that should be removed recursively),
/// `File` for plain files and symlinks. /// `File` for plain files and symlinks.
@ -295,7 +280,7 @@ pub fn kind_of(path: &Path) -> crate::model::ItemKind {
pub fn measure_all( pub fn measure_all(
targets: &[(PathBuf, ItemKind)], targets: &[(PathBuf, ItemKind)],
cancel: &CancelToken, cancel: &CancelToken,
on_unit: impl Fn(usize, usize, &SizeInfo) + Send + Sync, on_unit: impl Fn(usize, &SizeInfo) + Send + Sync,
) -> Vec<SizeInfo> { ) -> Vec<SizeInfo> {
let pool = rayon::ThreadPoolBuilder::new() let pool = rayon::ThreadPoolBuilder::new()
.num_threads(measure_threads()) .num_threads(measure_threads())
@ -312,18 +297,14 @@ pub fn measure_all(
let results: Vec<SizeInfo> = pool.install(|| { let results: Vec<SizeInfo> = pool.install(|| {
targets targets
.par_iter() .par_iter()
.enumerate() .map(|(path, kind)| {
.map(|(index, (path, kind))| {
if cancel.is_cancelled() { if cancel.is_cancelled() {
cancelled.store(true, Ordering::Relaxed); cancelled.store(true, Ordering::Relaxed);
return SizeInfo::default(); return SizeInfo::default();
} }
let info = measure(path, *kind); let info = measure(path, *kind);
let completed = done.fetch_add(1, Ordering::Relaxed) as usize + 1; let idx = done.fetch_add(1, Ordering::Relaxed) as usize;
// (target index, completed count): index identifies the unit — emit(idx, &info);
// callbacks arrive in completion order under rayon — while the
// count drives monotonic progress bars.
emit(index, completed, &info);
info info
}) })
.collect() .collect()
@ -388,7 +369,6 @@ pub fn remove_item_with(
files: 0, files: 0,
dirs: 0, dirs: 0,
unreadable: 0, unreadable: 0,
newest_write: 0,
}; };
Ok(freed.on_disk().max(Bytes::ZERO)) Ok(freed.on_disk().max(Bytes::ZERO))
} }

View File

@ -165,21 +165,6 @@ pub struct CleanupItem {
/// stale or hand-edited item can never escape its sandbox. /// stale or hand-edited item can never escape its sandbox.
#[serde(default)] #[serde(default)]
pub anchors: Vec<PathBuf>, pub anchors: Vec<PathBuf>,
/// Seconds since the *most recent* last-write inside the item (Mole's
/// decision aid: 1.2 GB alone is not actionable, "untouched for 3 months"
/// is — and a low value flags a live, working directory). Unknown until
/// measurement; `None` for unreadable paths.
#[serde(default)]
pub last_write_secs: Option<u64>,
/// File count from measurement — lets the UI say "12 files · 5 folders".
#[serde(default)]
pub file_count: u64,
/// Machine-readable judgement tokens (Mole's evidence chain, made
/// visible): `lock:<file>`, `record:<file>`, `record-missing`,
/// `modified:<n>`, `git:ignored|untracked|none|tracked`, `age:<days>`,
/// `busy`. The UI renders each token as a ✓/! line in a detail panel.
#[serde(default)]
pub evidence: Vec<String>,
} }
impl CleanupItem { impl CleanupItem {
@ -202,9 +187,6 @@ impl CleanupItem {
lock: lock_default(kind), lock: lock_default(kind),
note: None, note: None,
anchors: Vec::new(), anchors: Vec::new(),
last_write_secs: None,
file_count: 0,
evidence: Vec::new(),
} }
} }
@ -384,6 +366,10 @@ pub struct AppInfo {
pub name: String, pub name: String,
pub bundle_id: Option<String>, pub bundle_id: Option<String>,
pub path: PathBuf, pub path: PathBuf,
/// The file or bundle the desktop icon is read from. `path` may be an
/// install directory or an uninstall helper, neither of which carries the
/// icon the user recognises.
pub icon_source: Option<PathBuf>,
pub version: Option<String>, pub version: Option<String>,
pub size: Bytes, pub size: Bytes,
/// Where the app was found: /Applications, ~/Applications, Homebrew Cask… /// Where the app was found: /Applications, ~/Applications, Homebrew Cask…

View File

@ -178,6 +178,31 @@ pub fn normalized(path: &Path) -> PathBuf {
out out
} }
/// A path reduced to one comparable string.
///
/// This is [`same_path`] made cheap enough to index a table with. `same_path` is
/// correct but builds a `Vec` of lowercased components per call, which is fine for
/// a dozen comparisons and quadratic when a scan asks one per cached file: a
/// 15,000-file security scan spent most of ten minutes doing nothing but
/// re-comparing paths.
///
/// The two must agree, because a key that matched where `same_path` would not let
/// a cached verdict be reused for the wrong file. Both fold case unconditionally —
/// the rule [`keys_match`] already applies on every platform — and a test asserts
/// the agreement rather than trusting this wording.
pub fn canonical_key(path: &Path) -> String {
let parts: Vec<String> = parts(path).into_iter().map(|(key, _)| key).collect();
// `parts` keeps the root as its own component so that an absolute path cannot
// collide with a relative one, which would let a cached verdict be reused for
// the wrong file. Joining them verbatim reads as `//a/b`, so the root is put
// back as a prefix instead: same uniqueness, and the cache file on disk stays
// legible to whoever opens it.
match parts.first().map(String::as_str) {
Some("/") => format!("/{}", parts[1..].join("/")),
_ => parts.join("/"),
}
}
/// Name that survives being shown in a one-line row: deepest meaningful label. /// Name that survives being shown in a one-line row: deepest meaningful label.
pub fn label_for(path: &Path) -> String { pub fn label_for(path: &Path) -> String {
path.file_name() path.file_name()
@ -189,6 +214,59 @@ pub fn label_for(path: &Path) -> String {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn a_canonical_key_agrees_with_same_path() {
let cases: [(&str, &str, bool); 7] = [
("/a/b/c", "/a/b/c", true),
("/a/b/../b/c", "/a/b/c", true),
("/a/./b/c", "/a/b/c", true),
("/a/b/c", "/a/b/d", false),
("/a/b/c", "/a/b", false),
("/a/b/c", "/a/b/c/d", false),
("/A/b", "/a/b", true),
];
for (left, right, same) in cases {
let (a, b) = (Path::new(left), Path::new(right));
assert_eq!(
same_path(a, b),
canonical_key(a) == canonical_key(b),
"same_path and canonical_key disagree about {left} and {right}"
);
assert_eq!(
same,
same_path(a, b),
"unexpected same_path for {left} and {right}"
);
}
}
#[test]
fn every_spelling_of_one_file_gives_one_key() {
// A cache keyed by this must not answer "never seen it" to a file it has
// already judged, or every scan re-reads the disk and the cache is a lie.
for spelling in ["/a/b/c", "/a/b/c/", "/a/./b/c", "/a/b/../b/c"] {
assert_eq!(
canonical_key(Path::new(spelling)),
canonical_key(Path::new("/a/b/c")),
"{spelling} is the same file as /a/b/c"
);
}
}
#[test]
fn a_canonical_key_is_usable_as_a_hash_key() {
// Two spellings of one file must land on one slot, or a cache lookup
// would answer "never seen it" and re-hash the whole disk every scan.
assert_eq!(
canonical_key(Path::new("/Users/Tester/Library/Caches")),
canonical_key(Path::new("/Users/Tester/./Library/Caches"))
);
assert_ne!(
canonical_key(Path::new("/a/b")),
canonical_key(Path::new("/a/b/c"))
);
}
#[test] #[test]
fn expands_home() { fn expands_home() {
let home = Path::new("/Users/tester"); let home = Path::new("/Users/tester");

View File

@ -30,12 +30,6 @@ pub enum Event {
total: Bytes, total: Bytes,
count: usize, count: usize,
}, },
/// Cumulative measurement counters, streamed while sizes are computed
/// (Mole's "Scanning: 128,431 files · 38.2 GB" live status line).
Metered {
files: u64,
bytes: Bytes,
},
Deleted { Deleted {
path: PathBuf, path: PathBuf,
freed: Bytes, freed: Bytes,

View File

@ -36,6 +36,131 @@ pub struct Settings {
/// Whether the desktop app's first-run permission card has been dismissed. /// Whether the desktop app's first-run permission card has been dismissed.
/// Older configs have no such field and therefore see the card once. /// Older configs have no such field and therefore see the card once.
pub desktop_setup_reviewed: bool, pub desktop_setup_reviewed: bool,
/// Malware scanning and quarantine. A whole section so an old config keeps
/// working: `#[serde(default)]` above fills this in when the file has none.
pub security: SecuritySettings,
}
/// How often squid runs its own scan while the app is open in the tray.
///
/// `OnLaunch` and the intervals only fire while squid is actually running: there
/// is no daemon, and pretending otherwise would promise a watchdog that is not
/// there. `Manual` is the default because a scan that starts by itself is a
/// surprise the user did not ask for.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ScanSchedule {
Manual,
OnLaunch,
Daily,
Weekly,
}
impl ScanSchedule {
pub fn as_str(self) -> &'static str {
match self {
ScanSchedule::Manual => "manual",
ScanSchedule::OnLaunch => "on-launch",
ScanSchedule::Daily => "daily",
ScanSchedule::Weekly => "weekly",
}
}
pub fn parse(value: &str) -> Option<ScanSchedule> {
match value.trim().to_ascii_lowercase().as_str() {
"manual" | "off" | "none" => Some(ScanSchedule::Manual),
"on-launch" | "launch" => Some(ScanSchedule::OnLaunch),
"daily" => Some(ScanSchedule::Daily),
"weekly" => Some(ScanSchedule::Weekly),
_ => None,
}
}
/// How long a scan of this kind must wait before running again, or `None`
/// when it never runs by itself.
pub fn interval_secs(self) -> Option<i64> {
match self {
ScanSchedule::Manual => None,
ScanSchedule::OnLaunch => Some(0),
ScanSchedule::Daily => Some(24 * 60 * 60),
ScanSchedule::Weekly => Some(7 * 24 * 60 * 60),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct SecuritySettings {
pub scan_schedule: ScanSchedule,
/// Notify through the operating system when a scan finds something. The
/// in-app banner and the tray state work without this.
pub notify_on_findings: bool,
/// Move confirmed findings into the quarantine without asking. Suspicious
/// ones are never moved automatically, whatever this is set to.
pub auto_quarantine: bool,
/// Download signed rule packs. Off means squid uses only what it shipped with.
pub update_rules: bool,
/// Paths the scan must not read. Separate from `whitelist` on purpose: a
/// folder a person protects from *cleaning* must not silently stop a
/// malware finding from being reported.
pub scan_exclusions: Vec<String>,
/// Findings the user dismissed, as `confidence|path` fingerprints.
pub ignored_findings: Vec<String>,
}
impl Default for SecuritySettings {
fn default() -> Self {
SecuritySettings {
scan_schedule: ScanSchedule::Manual,
notify_on_findings: true,
// Off by default: a security tool that moves files on its own has to
// earn that right first.
auto_quarantine: false,
update_rules: true,
scan_exclusions: Vec::new(),
ignored_findings: Vec::new(),
}
}
}
impl SecuritySettings {
pub fn exclude(&mut self, path: impl Into<String>) {
let path = path.into();
if !self.scan_exclusions.contains(&path) {
self.scan_exclusions.push(path);
}
}
pub fn remove_exclusion(&mut self, path: &str) -> bool {
let before = self.scan_exclusions.len();
self.scan_exclusions.retain(|kept| kept != path);
self.scan_exclusions.len() != before
}
/// Expanded, existing paths, ready to hand a scan.
pub fn exclusion_paths(&self) -> Vec<PathBuf> {
self.scan_exclusions
.iter()
.map(|raw| paths::expand(raw))
.collect()
}
pub fn ignore(&mut self, fingerprint: impl Into<String>) {
let fingerprint = fingerprint.into();
if !self.ignored_findings.contains(&fingerprint) {
self.ignored_findings.push(fingerprint);
}
}
pub fn is_ignored(&self, fingerprint: &str) -> bool {
self.ignored_findings.iter().any(|kept| kept == fingerprint)
}
pub fn unignore(&mut self, fingerprint: &str) -> bool {
let before = self.ignored_findings.len();
self.ignored_findings.retain(|kept| kept != fingerprint);
self.ignored_findings.len() != before
}
} }
impl Default for Settings { impl Default for Settings {
@ -67,6 +192,7 @@ impl Default for Settings {
language: None, language: None,
history_keep: 60, history_keep: 60,
desktop_setup_reviewed: false, desktop_setup_reviewed: false,
security: SecuritySettings::default(),
} }
} }
} }
@ -161,13 +287,6 @@ impl Settings {
.collect() .collect()
} }
/// One raw whitelist line as a matcher — the shape the audit layer
/// needs when it must answer about a single pattern, not the list.
pub fn whitelist_matcher_for(raw: &str) -> Option<GlobMatcher> {
let expanded = paths::expand(raw).to_string_lossy().into_owned();
Glob::new(&expanded).ok().map(|g| g.compile_matcher())
}
pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool { pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool {
if self.whitelist.is_empty() { if self.whitelist.is_empty() {
return false; return false;
@ -345,13 +464,34 @@ fn system_locale() -> Option<Locale> {
None None
} }
#[cfg(not(target_os = "macos"))] #[cfg(target_os = "windows")]
fn system_locale() -> Option<Locale> { fn system_locale() -> Option<Locale> {
// Linux and Windows describe the language through the environment only, use windows::Win32::Globalization::GetUserDefaultUILanguage;
// and step 3 of `detect` has already read every bit of it.
// The environment is not a reliable proxy for the Windows display
// language: Explorer and the Store may run under a different UI locale.
let langid = unsafe { GetUserDefaultUILanguage() };
Some(locale_from_langid(langid))
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
fn system_locale() -> Option<Locale> {
// Linux describes the language through the environment, already read by
// step 3 of `detect`.
None None
} }
/// Windows LANGIDs pack a primary language in the low ten bits.
#[cfg(any(target_os = "windows", test))]
fn locale_from_langid(langid: u16) -> Locale {
const PRIMARY_CHINESE: u16 = 0x04;
if langid & 0x03ff == PRIMARY_CHINESE {
Locale::Zh
} else {
Locale::En
}
}
/// Convenience for reports that want the "freed" number in display units. /// Convenience for reports that want the "freed" number in display units.
pub fn display_size(settings: &Settings, logical: Bytes, allocated: Bytes) -> Bytes { pub fn display_size(settings: &Settings, logical: Bytes, allocated: Bytes) -> Bytes {
if settings.show_allocated && !allocated.is_zero() { if settings.show_allocated && !allocated.is_zero() {
@ -461,6 +601,16 @@ mod tests {
); );
} }
#[test]
fn windows_langid_uses_the_primary_language() {
assert_eq!(locale_from_langid(0x0004), Locale::Zh);
assert_eq!(locale_from_langid(0x0804), Locale::Zh, "zh-CN");
assert_eq!(locale_from_langid(0x0404), Locale::Zh, "zh-TW");
assert_eq!(locale_from_langid(0x0409), Locale::En, "en-US");
assert_eq!(locale_from_langid(0x0809), Locale::En, "en-GB");
assert_eq!(locale_from_langid(0x0411), Locale::En, "ja-JP fallback");
}
#[test] #[test]
fn squid_lang_beats_the_desktop_locale() { fn squid_lang_beats_the_desktop_locale() {
assert_eq!( assert_eq!(

View File

@ -16,7 +16,6 @@ use std::path::{Path, PathBuf};
const CHILD_CAP: usize = 512; const CHILD_CAP: usize = 512;
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Node { pub struct Node {
pub path: PathBuf, pub path: PathBuf,
pub logical: Bytes, pub logical: Bytes,
@ -197,9 +196,9 @@ pub fn expand(
}) })
.collect(); .collect();
progress.tick(0, Some(targets.len() as u64), None); progress.tick(0, Some(targets.len() as u64), None);
let sizes = fs::measure_all(&targets, cancel, |index, completed, _info| { let sizes = fs::measure_all(&targets, cancel, |index, _info| {
progress.tick( progress.tick(
completed as u64, index as u64 + 1,
Some(targets.len() as u64), Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()), targets.get(index).map(|(path, _)| path.clone()),
); );
@ -257,7 +256,7 @@ pub fn largest_files(
return Err(squid_core::SquidError::Cancelled); return Err(squid_core::SquidError::Cancelled);
} }
visited += 1; visited += 1;
if visited % 64 == 0 { if visited.is_multiple_of(64) {
progress.tick(visited as u64, None, Some(dir.clone())); progress.tick(visited as u64, None, Some(dir.clone()));
} }
if visited > 500_000 { if visited > 500_000 {

View File

@ -1,190 +0,0 @@
//! User-asset recognition — the Mole `app_protection` lesson for Windows.
//!
//! Some directories look exactly like caches but hold the user's own work:
//! chat files inside an IM data folder, PWA offline documents in a browser
//! profile's IndexedDB,输入法词库. A broad rule (or an eager user) must never
//! sweep them away, so they are pinned here: the scan lists them as locked,
//! visibly-explained rows, and the delete layer refuses them even when a
//! stale report still claims they are removable.
use squid_core::{Category, CleanupItem, ItemKind};
use std::path::Path;
/// Lower-cased path fragment → human reason. Matching is on the *normalised*
/// (lower-case, `/`→`\`) path so one table covers every drive letter and user.
const ASSET_MARKERS: &[(&str, &str)] = &[
(
"\\appdata\\roaming\\texact\\",
"腾讯 QQ 数据目录(聊天记录与文件)",
),
(
"\\appdata\\roaming\\tencent\\",
"腾讯通用数据目录(聊天文件与配置)",
),
(
"\\documents\\weixin files\\filestorage",
"微信聊天文件与下载文档",
),
(
"\\appdata\\roaming\\weixin\\filestorage",
"微信聊天文件与下载文档",
),
("\\appdata\\roaming\\txdnd\\", "腾讯游戏数据目录"),
("\\sogouexplorer\\", "搜狗输入法词库与用户习惯"),
(
"\\appdata\\roaming\\sogouinput\\",
"搜狗输入法词库与用户习惯",
),
];
/// Browser profile storage that holds PWA / offline web app documents —
/// Mole's `PROTECTED_SW_DOMAINS` equivalent. An `IndexedDB` folder inside a
/// Chromium-family browser profile is user work data (Figma / 剪映网页版 save
/// there), unlike `Cache` which is pure rebuildable bytes.
const CHROMIUM_PROFILE_MARKERS: &[&str] = &[
"\\microsoft\\edge\\user data\\",
"\\google\\chrome\\user data\\",
"\\chromium\\application\\user data\\",
];
fn normalise(path: &Path) -> String {
path.to_string_lossy().to_lowercase().replace('/', "\\")
}
/// Why this path is untouchable user property, if it is. The note lands in
/// the UI lock chip's explanation, mirroring 电脑管家's "创建者" honesty.
pub fn asset_reason(path: &Path) -> Option<&'static str> {
let lower = normalise(path);
// Deeper profile sub-paths (…\IndexedDB\foo) stay protected too: match
// the marker as a path prefix at a separator boundary.
if lower.contains("\\indexeddb")
&& CHROMIUM_PROFILE_MARKERS
.iter()
.any(|marker| lower.starts_with(marker) || lower.contains(marker))
{
return Some("可能含离线应用数据(Figma / 剪映网页版等工作文件)");
}
ASSET_MARKERS
.iter()
.find(|(marker, _)| segment_match(&lower, marker))
.map(|(_, reason)| *reason)
}
/// True when `marker` appears inside `lower` at path segment boundaries.
/// Markers ending with a separator carry their own trailing boundary, so
/// `TencentGame\cache` must not match `\tencent\`.
fn segment_match(lower: &str, marker: &str) -> bool {
if marker.ends_with('\\') {
return lower.contains(marker);
}
lower.match_indices(marker).any(|(index, _)| {
// A marker that opens with `\` carries its own left boundary; a bare
// marker needs a separator (or drive colon) before it.
let before_ok = index == 0
|| marker.starts_with('\\')
|| matches!(lower.as_bytes()[index - 1], b'\\' | b':');
let after = index + marker.len();
let after_ok = lower.len() == after || lower.as_bytes().get(after) == Some(&b'\\');
before_ok && after_ok
})
}
/// Asset rows to surface in the 空间清理 list — existence checked, one row
/// per top-level asset. Rows anchor at their own parent: they are display
/// only (locked), and anchoring at the folder itself would make
/// `block_reason` deny the row's own deletion check.
pub fn known_asset_rows() -> Vec<CleanupItem> {
const SPECS: [(&str, &str); 6] = [
(
r"AppData\Roaming\Tencent",
"腾讯(QQ/微信旧版)数据目录(聊天记录与文件)",
),
(
r"Documents\WeChat Files",
"微信聊天文件与下载文档(旧版目录)",
),
(
r"Documents\Weixin Files\FileStorage",
"微信聊天文件与下载文档",
),
(r"AppData\Roaming\SogouInput", "搜狗输入法词库与用户习惯"),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB",
"可能含离线应用数据(Figma / 剪映网页版等工作文件)",
),
(
r"AppData\Local\Google\Chrome\User Data\Default\IndexedDB",
"可能含离线应用数据(Figma / 剪映网页版等工作文件)",
),
];
let Ok(home) = std::env::var("USERPROFILE") else {
return Vec::new();
};
let home = Path::new(&home);
let mut rows = Vec::new();
for (tail, reason) in SPECS {
let path = home.join(tail);
if !path.is_dir() {
continue;
}
let label = format!("🔒 {}", asset_label(&path));
let parent = path
.parent()
.map(|dir| dir.to_path_buf())
.unwrap_or_else(|| path.clone());
let item = CleanupItem::new(path, ItemKind::Path, Category::AppCaches, label)
.with_rule("user-assets")
.with_anchors(std::iter::once(parent))
.locked(squid_core::LockReason::Protected)
.with_note(reason);
rows.push(item);
}
rows
}
fn asset_label(path: &Path) -> String {
let text = squid_core::paths::pretty(path);
text.rsplit(['\\', '/'])
.next()
.filter(|leaf| !leaf.is_empty())
.unwrap_or(&text)
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn im_data_dirs_refuse_deletion_with_a_reason() {
let path = PathBuf::from(r"C:\Users\me\AppData\Roaming\Tencent\WeChat\111\msg");
let reason = asset_reason(&path).expect("QQ tree must be protected");
assert!(reason.contains("聊天"));
}
#[test]
fn wechat_file_storage_is_protected_but_cache_paths_are_not() {
let storage = PathBuf::from(r"D:\Users\me\Documents\Weixin Files\FileStorage\File\2026-01");
assert!(asset_reason(&storage).is_some());
let edge_cache =
PathBuf::from(r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\Cache");
assert!(asset_reason(&edge_cache).is_none());
}
#[test]
fn profile_indexeddb_counts_as_offline_app_data() {
let pwa = PathBuf::from(
r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB\figma_0.indexeddb.leveldb",
);
let reason = asset_reason(&pwa).expect("PWA data must be protected");
assert!(reason.contains("离线应用"));
}
#[test]
fn markers_match_only_at_segment_boundaries() {
// A folder that merely *starts* with the marker text is not the asset.
let sneaky = PathBuf::from(r"C:\Users\me\AppData\Roaming\TencentGame\cache");
assert!(asset_reason(&sneaky).is_none());
}
}

View File

@ -172,20 +172,6 @@ pub fn scan(
} }
} }
// User-asset rows (B4): pinned directories shown as locked, explained
// rows so "why can't I clean my WeChat files?" never becomes a mystery.
let assets_wanted =
options.categories.is_empty() || options.categories.contains(&Category::AppCaches);
if assets_wanted {
for item in crate::assets::known_asset_rows() {
if seen.contains_key(&item.path) {
continue;
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
if !options.fast { if !options.fast {
measure(engine, &mut report, progress, cancel)?; measure(engine, &mut report, progress, cancel)?;
} }
@ -215,7 +201,7 @@ fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec<PreparedRule>
rules.into_iter().map(PreparedRule::new).collect() rules.into_iter().map(PreparedRule::new).collect()
} }
pub fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> { fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
if rule.skip_if_running.is_empty() { if rule.skip_if_running.is_empty() {
return None; return None;
} }
@ -348,42 +334,15 @@ fn measure(
.iter() .iter()
.map(|item| (item.path.clone(), item.kind)) .map(|item| (item.path.clone(), item.kind))
.collect(); .collect();
let total = targets.len() as u64; progress.tick(0, Some(targets.len() as u64), None);
progress.tick(0, Some(total), None);
// Cumulative counters for the live status line; the callback runs on let results: Vec<squid_core::fs::SizeInfo> = measure_all(&targets, cancel, |index, _info| {
// rayon worker threads, hence the mutex. Emissions are throttled to progress.tick(
// ~10/s so the IPC stays a whisper while the walk screams. index as u64 + 1,
let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now())); Some(targets.len() as u64),
let results: Vec<squid_core::fs::SizeInfo> = targets.get(index).map(|(path, _)| path.clone()),
measure_all(&targets, cancel, |index, completed, info| { );
let emit_line = { });
let mut guard = meter
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
guard.0 += info.files;
guard.1 += info.on_disk().as_u64();
if completed as u64 == total
|| guard.2.elapsed() >= std::time::Duration::from_millis(90)
{
guard.2 = std::time::Instant::now();
Some((guard.0, guard.1))
} else {
None
}
};
if let Some((files, bytes)) = emit_line {
progress.publish(Event::Metered {
files,
bytes: Bytes(bytes),
});
}
progress.tick(
completed as u64,
Some(total),
targets.get(index).map(|(path, _)| path.clone()),
);
});
if results.len() != report.items.len() { if results.len() != report.items.len() {
return Err(SquidError::Other( return Err(SquidError::Other(
"measurement returned an unexpected number of results".into(), "measurement returned an unexpected number of results".into(),
@ -392,17 +351,6 @@ fn measure(
for (item, info) in report.items.iter_mut().zip(results) { for (item, info) in report.items.iter_mut().zip(results) {
item.size = info.logical; item.size = info.logical;
item.allocated = info.allocated; item.allocated = info.allocated;
item.file_count = info.files;
// "Untouched for X" is the actionable half of a size figure; derived
// from the newest last-write seen during the walk we just did.
item.last_write_secs = if info.newest_write == 0 {
None
} else {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
Some(now.saturating_sub(info.newest_write))
};
if info.unreadable > 0 && item.note.is_none() { if info.unreadable > 0 && item.note.is_none() {
item.note = Some(format!("{} entries unreadable", info.unreadable)); item.note = Some(format!("{} entries unreadable", info.unreadable));
} else if info.files > 0 && item.note.is_none() { } else if info.files > 0 && item.note.is_none() {

View File

@ -1,197 +0,0 @@
//! Hidden-space insights (Mole's `cmd/analyze` overview idiom).
//!
//! The disk analyzer answers "what is big"; this answers "what is big *and*
//! actionable" — curated Windows space hogs with a one-line explanation and
//! the action that actually frees them. Existence-gated: a row appears only
//! when the underlying path (or state) is really on this machine.
use serde::Serialize;
use squid_core::fs;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Insight {
/// Stable id for the UI (icon/translation lookup).
pub id: String,
pub title: String,
pub path: String,
pub size: u64,
/// "cleanable" — 空间清理 covers it; "command" — needs the given command;
/// "external" — system tool territory; "info" — informational.
pub action: String,
/// Command to run (elevated) when action == "command".
pub command: Option<String>,
pub hint: String,
}
fn home() -> Option<PathBuf> {
std::env::var("USERPROFILE")
.ok()
.map(PathBuf::from)
.filter(|path| path.is_dir())
}
fn dir_size(path: &Path) -> u64 {
if !path.is_dir() {
return 0;
}
fs::measure(path, squid_core::ItemKind::Path)
.on_disk()
.as_u64()
}
fn file_size(path: &Path) -> u64 {
std::fs::metadata(path).map_or(0, |meta| meta.len())
}
/// All insights that currently exist on this machine, biggest-effect first
/// ordering is left to the UI.
pub fn collect() -> Vec<Insight> {
let mut out = Vec::new();
let Some(home) = home() else {
return out;
};
let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
let system = PathBuf::from(system);
// 1. Windows Update download cache — the classic 5-20 GB surprise.
let updates = system.join(r"SoftwareDistribution\Download");
let size = dir_size(&updates);
if size > 256 * 1024 * 1024 {
out.push(Insight {
id: "update-cache".into(),
title: "Windows 更新缓存".into(),
path: updates.display().to_string(),
size,
action: "cleanable".into(),
command: None,
hint: "已安装的更新包,Windows 需要时会重新下载;空间清理的「系统垃圾」覆盖此目录"
.into(),
});
}
// 2. Hibernation file — freed by turning hibernation off.
let hiber = system.join("..\\hiberfil.sys");
let size = file_size(&hiber);
if size > 0 {
out.push(Insight {
id: "hiberfil".into(),
title: "休眠文件 hiberfil.sys".into(),
path: hiber.display().to_string(),
size,
action: "command".into(),
command: Some("powercfg /h off".into()),
hint: "关闭休眠后系统自动删除;睡眠不受影响".into(),
});
}
// 3. Pagefile — visible but rarely worth touching; info only.
let page = system.join("..\\pagefile.sys");
let size = file_size(&page);
if size > 0 {
out.push(Insight {
id: "pagefile".into(),
title: "虚拟内存 pagefile.sys".into(),
path: page.display().to_string(),
size,
action: "info".into(),
command: None,
hint: "系统正在使用的虚拟内存,不建议手动删除;可在系统设置改到别的盘".into(),
});
}
// 4. Component store (WinSxS) — needs DISM, never raw deletion.
// Walking 100k+ files just to print a number is not worth it here;
// the UI shows "several GB" and the DISM command does the rest.
let winsxs = system.join("WinSxS");
if winsxs.is_dir() {
out.push(Insight {
id: "winsxs".into(),
title: "组件存储 WinSxS".into(),
path: winsxs.display().to_string(),
size: 0,
action: "command".into(),
command: Some("Dism.exe /online /Cleanup-Image /StartComponentCleanup".into()),
hint: "系统组件仓库,通常 5~10 GB;只能由 DISM 收缩,直接删会破坏系统".into(),
});
}
// 5. Phone backups (Apple MobileSync / third-party Android tools).
for (tail, title) in [
(r"Apple\MobileSync\Backup", "iPhone 备份"),
(r"Apple Computer\MobileSync\Backup", "iPhone 备份"),
] {
let backups = home.join(tail);
let size = dir_size(&backups);
if size > 256 * 1024 * 1024 {
out.push(Insight {
id: "phone-backup".into(),
title: title.into(),
path: backups.display().to_string(),
size,
action: "external".into(),
command: None,
hint: "整机备份体积大;确认 iCloud 或新备份完成后,在 iTunes/Finder 里删除旧备份"
.into(),
});
break;
}
}
// 6. Downloads older than 90 days (Mole's "Old Downloads" insight).
let downloads = home.join("Downloads");
if downloads.is_dir() {
let cutoff = std::time::SystemTime::now() - std::time::Duration::from_secs(90 * 24 * 3600);
let mut size = 0u64;
let mut stale = 0usize;
if let Ok(entries) = std::fs::read_dir(&downloads) {
for entry in entries.flatten() {
let meta = match entry.metadata() {
Ok(meta) => meta,
Err(_) => continue,
};
let modified = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
if modified < cutoff {
size += if meta.is_dir() {
dir_size(&entry.path())
} else {
meta.len()
};
stale += 1;
}
}
}
if size > 256 * 1024 * 1024 {
out.push(Insight {
id: "old-downloads".into(),
title: "下载文件夹(90 天以上)".into(),
path: downloads.display().to_string(),
size,
action: "external".into(),
command: None,
hint: format!("{stale} 个条目三个月没动过;确认不再需要后手动清理"),
});
}
}
out.sort_by_key(|row| std::cmp::Reverse(row.size));
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collect_never_panics_on_a_live_machine() {
// Pure smoke: whatever exists, ids are unique and sizes sane.
let rows = collect();
for (index, row) in rows.iter().enumerate() {
assert!(!row.id.is_empty());
assert!(!rows[..index]
.iter()
.any(|earlier| earlier.id == row.id && row.id != "phone-backup"));
}
}
}

View File

@ -12,17 +12,15 @@
//! and the safety net impossible to bypass. //! and the safety net impossible to bypass.
pub mod analyze; pub mod analyze;
pub mod assets;
pub mod clean; pub mod clean;
pub mod delete; pub mod delete;
pub mod insights;
pub mod purge; pub mod purge;
pub mod uninstall; pub mod uninstall;
pub mod updates; pub mod updates;
use globset::GlobMatcher; use globset::GlobMatcher;
use squid_core::settings::Settings; use squid_core::settings::Settings;
use squid_core::{CleanupItem, SafetyPolicy, ScanReport}; use squid_core::{CleanupItem, SafetyPolicy};
use squid_platform::Platform; use squid_platform::Platform;
use squid_rules::RuleSet; use squid_rules::RuleSet;
use std::path::Path; use std::path::Path;
@ -123,13 +121,6 @@ impl Engine {
/// Why this item cannot be deleted, if it cannot. Rules pass the anchor they /// Why this item cannot be deleted, if it cannot. Rules pass the anchor they
/// declared; everything else falls back to the default anchors. /// declared; everything else falls back to the default anchors.
pub fn block_reason(&self, item: &CleanupItem) -> Option<String> { pub fn block_reason(&self, item: &CleanupItem) -> Option<String> {
// Mole's lesson: some directories *look* like caches but hold the
// user's own work — chat files, PWA offline data, IME dictionaries.
// They are refused even when a broad rule matched them, with the
// reason shown verbatim in the UI lock chip.
if let Some(reason) = crate::assets::asset_reason(&item.path) {
return Some(reason.to_string());
}
let anchors = if item.anchors.is_empty() { let anchors = if item.anchors.is_empty() {
squid_core::fs::default_anchors() squid_core::fs::default_anchors()
} else { } else {
@ -140,107 +131,6 @@ impl Engine {
} }
self.safety.denies(&item.path, &anchors) self.safety.denies(&item.path, &anchors)
} }
/// Mole's "re-verify at the last second" made visible: re-run every
/// deletion gate against the *current* item set and report what changed
/// since the scan. The confirm dialog shows the summary, so surprises
/// ("your app just started, we dropped 3 items") appear before the run,
/// not inside the results.
pub fn preflight(&self, report: &ScanReport, indexes: &[usize]) -> Preflight {
let running = self.platform().running_executables();
let mut out = Preflight {
checked: indexes.len(),
blocked: Vec::new(),
};
for &index in indexes {
let Some(item) = report.items.get(index) else {
continue;
};
if item.lock.is_some() {
continue;
}
if let Some(reason) = self.block_reason(item) {
out.blocked.push((item.display_path(), reason));
continue;
}
if let Some(path) = gone_path(item) {
out.blocked.push((
item.display_path(),
format!("{} 已不存在", squid_core::paths::pretty(&path)),
));
}
}
// Apps started since the scan: re-check running conflicts per rule.
for (index, item) in report.items.iter().enumerate() {
if item.lock.is_some() || !indexes.contains(&index) {
continue;
}
if let Some(rule) = self
.rules()
.rules()
.iter()
.find(|rule| rule.id == item.rule_id)
{
if let Some(conflict) = crate::clean::rule_running_conflict(rule, &running) {
if !out
.blocked
.iter()
.any(|(path, _)| *path == item.display_path())
{
out.blocked.push((item.display_path(), conflict));
}
}
}
}
out
}
/// Which whitelist patterns actually *do something* (Mole's #458: a
/// protection line nobody ever hits is a fake protection). A pattern is
/// "live" when it matches a path the current rule set finds on this
/// machine — the user learns their glob protects a real thing, or that
/// it protects nothing at all.
pub fn audit_whitelist(&self) -> Vec<(String, bool)> {
let known: Vec<std::path::PathBuf> = self
.rules()
.rules()
.iter()
.filter(|rule| rule.applies_to_current_os())
.flat_map(|rule| {
squid_rules::PreparedRule::new((*rule).clone())
.matches()
.into_iter()
.map(|matched| matched.path)
})
.collect();
// Same expansion the delete layer uses (settings.whitelist_matchers
// shape), rebuilt per pattern so an invalid line cannot shift the
// index pairing — the audit answers "does THIS pattern protect
// anything".
self.settings
.whitelist
.iter()
.map(|pattern| {
let live = Settings::whitelist_matcher_for(pattern).is_some_and(|matcher| {
known.iter().any(|path| matcher.is_match(path.as_path()))
});
(pattern.clone(), live)
})
.collect()
}
}
/// Result of [`Engine::preflight`].
#[derive(Clone, Debug, Default)]
pub struct Preflight {
pub checked: usize,
/// (display path, reason) for items that can no longer be deleted.
pub blocked: Vec<(String, String)>,
}
fn gone_path(item: &squid_core::CleanupItem) -> Option<std::path::PathBuf> {
(!item.path.exists() && !std::fs::symlink_metadata(&item.path).is_ok())
.then(|| item.path.clone())
} }
/// True when the process may touch system-owned paths. /// True when the process may touch system-owned paths.

View File

@ -222,13 +222,11 @@ pub fn scan(
); );
let mut item = item_for(candidate); let mut item = item_for(candidate);
// Evidence chain (B3): remember the git verdict + project root + age
// while checking, then attach machine tokens for the UI panel.
let evidence_project =
project_with_git(&candidate.path).unwrap_or_else(|| candidate.project.clone());
let evidence_age = age_days(&candidate.path);
if !options.force { if !options.force {
let project_root = evidence_project.clone(); let project_root = match project_with_git(&candidate.path) {
Some(dir) => dir,
None => candidate.project.clone(),
};
let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) { let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) {
Some((_, state)) => *state, Some((_, state)) => *state,
None => { None => {
@ -239,22 +237,14 @@ pub fn scan(
}; };
match state { match state {
GitState::Tracked => { GitState::Tracked => {
item.evidence.push("git:tracked".into());
item = item item = item
.locked(LockReason::Protected) .locked(LockReason::Protected)
.with_note("tracked by git — pass --all to delete anyway"); .with_note("tracked by git — pass --all to delete anyway");
} }
GitState::Ignored => { GitState::Ignored => item.note = Some("git-ignored build output".into()),
item.evidence.push("git:ignored".into()); GitState::Untracked => item.note = Some("untracked by git".into()),
item.note = Some("git-ignored build output".into());
}
GitState::Untracked => {
item.evidence.push("git:untracked".into());
item.note = Some("untracked by git".into());
}
GitState::Unknown => { GitState::Unknown => {
item.evidence.push("git:none".into()); let age = age_days(&candidate.path);
let age = evidence_age;
match age { match age {
Some(age) if age >= min_age as f64 => { Some(age) if age >= min_age as f64 => {
item.note = Some(format!("no git repo · {:.0} days old", age)); item.note = Some(format!("no git repo · {:.0} days old", age));
@ -298,7 +288,6 @@ pub fn scan(
.locked(LockReason::NotOwned) .locked(LockReason::NotOwned)
.with_note("owned by another user"); .with_note("owned by another user");
} }
collect_evidence(&mut item, &evidence_project, evidence_age);
report.items.push(item); report.items.push(item);
} }
@ -321,77 +310,6 @@ pub fn scan(
Ok(report) Ok(report)
} }
/// Mole's node_modules evidence chain, made visible (B3):
/// a lockfile proves the tree is *reinstallable*; the package manager's
/// install record inside the artefact proves nobody hand-edited it since —
/// any file newer than the record smells like patched code, so we count it.
/// Returns machine tokens for the UI detail panel; empty = not a node tree.
fn node_evidence(project: &Path, artifact: &Path) -> Vec<String> {
const LOCKS: [(&str, &str); 3] = [
("package-lock.json", ".package-lock.json"),
("pnpm-lock.yaml", ".modules.yaml"),
("yarn.lock", ".yarn-integrity"),
];
let mut out = Vec::new();
let Some((lock, record)) = LOCKS.iter().find(|(lock, _)| project.join(lock).is_file()) else {
return out;
};
out.push(format!("lock:{lock}"));
let record_path = artifact.join(record);
let Ok(meta) = std::fs::metadata(&record_path) else {
out.push("record-missing".into());
return out;
};
out.push(format!("record:{record}"));
let Ok(stamp) = meta.modified() else {
return out;
};
let mut modified = 0u32;
let mut seen = 0u32;
for entry in walkdir::WalkDir::new(artifact)
.follow_links(false)
.max_depth(8)
.into_iter()
.filter_map(Result::ok)
{
if !entry.file_type().is_file() {
continue;
}
seen += 1;
if entry
.metadata()
.ok()
.and_then(|file| file.modified().ok())
.is_some_and(|when| when > stamp)
{
modified += 1;
if modified > 50 {
break;
}
}
if seen >= 40_000 {
break;
}
}
out.push(format!("modified:{modified}"));
out
}
/// Collect the evidence tokens for one candidate after its checks ran.
fn collect_evidence(item: &mut CleanupItem, project: &Path, age: Option<f64>) {
if let Some(age) = age {
item.evidence.push(format!("age:{}", age.floor() as u64));
}
let name = item
.path
.file_name()
.map(|name| name.to_string_lossy().to_lowercase())
.unwrap_or_default();
if name == "node_modules" {
item.evidence.extend(node_evidence(project, &item.path));
}
}
fn item_for(candidate: &Candidate) -> CleanupItem { fn item_for(candidate: &Candidate) -> CleanupItem {
let category = if candidate.name.eq_ignore_ascii_case("DerivedData") { let category = if candidate.name.eq_ignore_ascii_case("DerivedData") {
Category::Developer Category::Developer
@ -423,20 +341,12 @@ fn item_for(candidate: &Candidate) -> CleanupItem {
/// (shallow) so a project in an unexpected place is still found. /// (shallow) so a project in an unexpected place is still found.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<PathBuf> { fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<PathBuf> {
if !options.roots.is_empty() { if !options.roots.is_empty() {
let chosen: Vec<PathBuf> = options return options
.roots .roots
.iter() .iter()
.map(|root| squid_core::paths::expand(&root.to_string_lossy())) .map(|root| squid_core::paths::expand(&root.to_string_lossy()))
.filter(|path| path.is_dir()) .filter(|path| path.is_dir())
.collect(); .collect();
// All the caller's paths are dead (classic case: the default roots
// are macOS-flavoured ~/code-style folders that never exist on
// Windows). Falling through to settings + home beats a scan that
// refuses to run and tells the user to pick a folder that is
// already in the box.
if !chosen.is_empty() {
return chosen;
}
} }
let mut roots = engine.settings().purge_root_paths(); let mut roots = engine.settings().purge_root_paths();
let home = squid_core::paths::home_dir(); let home = squid_core::paths::home_dir();
@ -636,31 +546,9 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
return; return;
} }
progress.phase("measure", "measuring artefacts"); progress.phase("measure", "measuring artefacts");
let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now())); let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, info| {
let emit_line = {
let mut guard = meter
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
guard.0 += info.files;
guard.1 += info.on_disk().as_u64();
if completed as u64 == targets.len() as u64
|| guard.2.elapsed() >= std::time::Duration::from_millis(90)
{
guard.2 = std::time::Instant::now();
Some((guard.0, guard.1))
} else {
None
}
};
if let Some((files, bytes)) = emit_line {
progress.publish(squid_core::progress::Event::Metered {
files,
bytes: Bytes(bytes),
});
}
progress.tick( progress.tick(
completed as u64, index as u64 + 1,
Some(targets.len() as u64), Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()), targets.get(index).map(|(path, _)| path.clone()),
); );
@ -668,15 +556,6 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
for (item, info) in report.items.iter_mut().zip(sizes) { for (item, info) in report.items.iter_mut().zip(sizes) {
item.size = info.logical; item.size = info.logical;
item.allocated = info.allocated; item.allocated = info.allocated;
item.file_count = info.files;
item.last_write_secs = if info.newest_write == 0 {
None
} else {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
Some(now.saturating_sub(info.newest_write))
};
if info.unreadable > 0 { if info.unreadable > 0 {
let suffix = format!("{} entries unreadable", info.unreadable); let suffix = format!("{} entries unreadable", info.unreadable);
item.note = Some(match item.note.take() { item.note = Some(match item.note.take() {

View File

@ -248,9 +248,9 @@ fn measure(
.iter() .iter()
.map(|item| (item.path.clone(), item.kind)) .map(|item| (item.path.clone(), item.kind))
.collect(); .collect();
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, _info| { let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
progress.tick( progress.tick(
completed as u64, index as u64 + 1,
Some(targets.len() as u64), Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()), targets.get(index).map(|(path, _)| path.clone()),
); );
@ -464,6 +464,7 @@ mod tests {
name: "Demo".into(), name: "Demo".into(),
bundle_id: Some("com.example.Demo".into()), bundle_id: Some("com.example.Demo".into()),
path: PathBuf::from(path), path: PathBuf::from(path),
icon_source: None,
version: Some("1.0".into()), version: Some("1.0".into()),
size: Bytes(1_000), size: Bytes(1_000),
source: source.into(), source: source.into(),

View File

@ -0,0 +1,21 @@
[package]
name = "squid-guard"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Malware scanning, detection rules and reversible quarantine for squid"
[dependencies]
squid-core.workspace = true
squid-platform.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2 = "0.10"
hex = "0.4"
walkdir.workspace = true
yara-x = { version = "1.23", default-features = false, features = ["string-module","math-module","hash-module","time-module","macho-module","pe-module","constant-folding","exact-atoms","fast-regexp"] }
chrono.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
plist.workspace = true

View File

@ -0,0 +1,231 @@
//! Which parts of the machine a scan actually looked at.
//!
//! A cleaner can be vague about coverage because missing a cache costs nothing.
//! A security scan cannot: "no threats found" that quietly skipped
//! `~/Library/Mail` for lack of Full Disk Access is worse than no answer at all.
//! So every root records what happened to it, and the report is only allowed to
//! say "clean" for the roots that were walked.
//!
//! Nothing here asks the operating system for permission and nothing here
//! retries a refusal. A denied directory is a fact about this run, reported as
//! one, and the person using squid decides whether to grant access and rescan.
use serde::{Deserialize, Serialize};
use squid_core::paths;
use std::path::{Path, PathBuf};
/// What happened to one root during a scan.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RootOutcome {
/// Every readable entry beneath it was offered to the detectors.
Walked,
/// The root itself could not be opened — usually a privacy permission.
Denied,
/// It was not there, which is not a gap in coverage.
Absent,
/// The user or a rule excluded it on purpose.
Excluded,
/// Deliberately not part of this scan mode.
OutOfScope,
/// Stopped early: cancelled, or the entry budget ran out.
Partial,
}
impl RootOutcome {
pub fn counts_as_gap(self) -> bool {
matches!(self, RootOutcome::Denied | RootOutcome::Partial)
}
pub fn as_str(self) -> &'static str {
match self {
RootOutcome::Walked => "walked",
RootOutcome::Denied => "denied",
RootOutcome::Absent => "absent",
RootOutcome::Excluded => "excluded",
RootOutcome::OutOfScope => "out-of-scope",
RootOutcome::Partial => "partial",
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RootRecord {
pub path: PathBuf,
pub display_path: String,
pub outcome: RootOutcome,
pub reason: Option<String>,
pub files: usize,
pub scanned: usize,
pub skipped: usize,
}
/// The whole coverage statement for one scan.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Coverage {
pub roots: Vec<RootRecord>,
}
impl Coverage {
pub fn push(&mut self, mut record: RootRecord) {
if record.display_path.is_empty() {
record.display_path = paths::pretty(&record.path);
}
self.roots.push(record);
}
/// True when the scan saw everything it meant to see. This is the only
/// condition under which the UI is allowed to say "nothing found" without a
/// qualifier next to it.
pub fn complete(&self) -> bool {
!self.roots.iter().any(|root| root.outcome.counts_as_gap())
}
pub fn gaps(&self) -> Vec<&RootRecord> {
self.roots
.iter()
.filter(|root| root.outcome.counts_as_gap())
.collect()
}
pub fn walked_files(&self) -> usize {
self.roots.iter().map(|root| root.scanned).sum()
}
pub fn skipped_files(&self) -> usize {
self.roots.iter().map(|root| root.skipped).sum()
}
/// Record the outcome of walking one root, folding in the entry count.
pub fn record_walk(
&mut self,
root: &Path,
outcome: RootOutcome,
reason: Option<String>,
files: usize,
scanned: usize,
) {
self.push(RootRecord {
path: root.to_path_buf(),
display_path: String::new(),
outcome,
reason,
files,
scanned,
skipped: files.saturating_sub(scanned),
});
}
}
/// Decide what happened to a root from the error reading it, so a missing
/// `~/Applications` is not reported as a coverage gap while a refused
/// `~/Library/Mail` is.
pub fn outcome_for_error(error: &std::io::Error) -> RootOutcome {
use std::io::ErrorKind;
match error.kind() {
ErrorKind::NotFound => RootOutcome::Absent,
ErrorKind::PermissionDenied => RootOutcome::Denied,
_ => RootOutcome::Denied,
}
}
/// A path the scan should never descend into, wherever it appears.
pub fn is_never_scanned(path: &Path) -> bool {
const SKIP_DIRS: [&str; 8] = [
".git",
"node_modules",
".Trash",
".Trashes",
"$RECYCLE.BIN",
"System Volume Information",
".Spotlight-V100",
".fseventsd",
];
// The quarantine holds files this crate moved deliberately; scanning it
// would report the same finding forever.
if path.starts_with(quarantine_root()) {
return true;
}
path.ancestors()
.filter_map(|ancestor| ancestor.file_name())
.any(|name| SKIP_DIRS.iter().any(|skip| name.eq(*skip)))
}
/// Where quarantined files live. One place, inside the state directory, so the
/// user can always find and empty it.
pub fn quarantine_root() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("quarantine")
}
/// Where rule packs and the hash cache live.
pub fn intel_root() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("intel")
}
/// Where startup-item backups are kept before a change.
pub fn startup_backup_root() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("startup-backups")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_folder_is_not_a_coverage_gap() {
let error = std::io::Error::from(std::io::ErrorKind::NotFound);
assert_eq!(outcome_for_error(&error), RootOutcome::Absent);
assert!(!RootOutcome::Absent.counts_as_gap());
let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
assert_eq!(outcome_for_error(&denied), RootOutcome::Denied);
assert!(RootOutcome::Denied.counts_as_gap());
}
#[test]
fn coverage_is_only_complete_without_denials() {
let mut coverage = Coverage::default();
coverage.record_walk(Path::new("/a"), RootOutcome::Walked, None, 10, 10);
coverage.record_walk(Path::new("/b"), RootOutcome::Absent, None, 0, 0);
assert!(coverage.complete());
coverage.record_walk(
Path::new("/c"),
RootOutcome::Denied,
Some("Full Disk Access".into()),
0,
0,
);
assert!(!coverage.complete());
assert_eq!(coverage.gaps().len(), 1);
assert_eq!(coverage.walked_files(), 10);
assert_eq!(coverage.skipped_files(), 0);
}
#[test]
fn vendored_and_recycle_directories_are_never_walked() {
assert!(is_never_scanned(Path::new(
"/Users/x/proj/node_modules/left-pad"
)));
assert!(is_never_scanned(Path::new(
"/Volumes/Data/.Trash/thing.app"
)));
assert!(is_never_scanned(&quarantine_root().join("payload.bin")));
assert!(!is_never_scanned(Path::new("/Applications/Calculator.app")));
}
#[test]
fn quarantine_lives_in_the_state_directory() {
assert!(
quarantine_root().ends_with("security/quarantine")
|| quarantine_root()
.to_string_lossy()
.replace('\\', "/")
.ends_with("security/quarantine")
);
}
}

View File

@ -0,0 +1,183 @@
//! What a scan decided about one file, and how it knows.
//!
//! The three levels are not a severity dial. They answer different questions,
//! and the difference is the contract the UI relies on:
//!
//! - [`Confidence::Confirmed`] means a specific published rule or hash says this
//! exact file is bad. It may be quarantined automatically if the user opted in.
//! - [`Confidence::Suspicious`] means the file has properties that a careful
//! person would check, with nothing published to point at. Alert, never move.
//! - [`Confidence::Advisory`] is not about the file at all — it is about the
//! machine: protection switched off, definitions old, a directory that could
//! not be read. Nothing to quarantine, something to say.
//!
//! Every finding carries [`Evidence`], and the UI shows that evidence rather
//! than a score. "SHA-256 is on the known-bad list" is checkable; "risk 72" is
//! not.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Confidence {
Advisory,
Suspicious,
Confirmed,
}
impl Confidence {
pub fn as_str(self) -> &'static str {
match self {
Confidence::Advisory => "advisory",
Confidence::Suspicious => "suspicious",
Confidence::Confirmed => "confirmed",
}
}
/// Only confirmed findings may be moved without asking again, and only this
/// method decides that — the UI cannot widen it.
pub fn auto_quarantinable(self) -> bool {
self == Confidence::Confirmed
}
}
/// One reason a file was reported. A finding may hold several: a binary that
/// matches a family rule *and* starts at login *and* is unsigned is three
/// statements, and a person reading the row deserves all three.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Evidence {
/// The SHA-256 of the file is on the known-bad list.
DeniedHash { sha256: String, threat: String },
/// A YARA-X rule fired.
YaraRule {
rule: String,
description: String,
family: String,
},
/// A published allow-list entry does not cover a file that claims to be it.
Impersonation { claimed: String, path: PathBuf },
/// Where this entry is started from.
StartsAtLogin { entry: String, source: String },
/// No usable code signature.
Unsigned { path: PathBuf, note: Option<String> },
/// Runs from a location every normal user of this machine can rewrite.
WritableLocation { path: PathBuf },
/// The file the entry points at is gone.
MissingTarget { path: PathBuf },
/// An advisory about the machine rather than a file.
SystemState { key: String, detail: String },
/// Part of the scan could not be checked.
Coverage { path: PathBuf, reason: String },
}
impl Evidence {
/// Stable identity for de-duplication across scans, so an ignored finding
/// stays ignored after a rescan rather than reappearing under a new row.
pub fn key(&self) -> String {
match self {
Evidence::DeniedHash { sha256, threat } => format!("hash:{sha256}:{threat}"),
Evidence::YaraRule { rule, .. } => format!("yara:{rule}"),
Evidence::Impersonation { claimed, .. } => format!("impersonation:{claimed}"),
Evidence::StartsAtLogin { entry, .. } => format!("startup:{entry}"),
Evidence::Unsigned { path, .. } => format!("unsigned:{}", path.display()),
Evidence::WritableLocation { path } => format!("writable:{}", path.display()),
Evidence::MissingTarget { path } => format!("missing:{}", path.display()),
Evidence::SystemState { key, .. } => format!("state:{key}"),
Evidence::Coverage { path, reason } => {
format!("coverage:{}:{reason}", path.display())
}
}
}
/// One line for a table cell. The full evidence stays available in details.
pub fn summary(&self) -> String {
match self {
Evidence::DeniedHash { threat, .. } => format!("known-bad hash: {threat}"),
Evidence::YaraRule { rule, family, .. } => {
if family.is_empty() {
format!("matches rule {rule}")
} else {
format!("matches rule {rule} ({family})")
}
}
Evidence::Impersonation { claimed, .. } => {
format!("claims to be {claimed} but is not where {claimed} lives")
}
Evidence::StartsAtLogin { entry, source } => {
format!("starts at login via {source} ({entry})")
}
Evidence::Unsigned { note, .. } => match note {
Some(note) => format!("not signed: {note}"),
None => "not signed".into(),
},
Evidence::WritableLocation { path } => {
format!("runs from a user-writable location: {}", path.display())
}
Evidence::MissingTarget { path } => {
format!("target is gone: {}", path.display())
}
Evidence::SystemState { detail, .. } => detail.clone(),
Evidence::Coverage { path, reason } => {
format!("not checked ({}): {reason}", path.display())
}
}
}
pub fn path(&self) -> Option<&PathBuf> {
match self {
Evidence::Impersonation { path, .. }
| Evidence::Unsigned { path, .. }
| Evidence::WritableLocation { path }
| Evidence::MissingTarget { path }
| Evidence::Coverage { path, .. } => Some(path),
_ => None,
}
}
}
/// One reported file or machine state.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Finding {
/// Backend-issued. The frontend sends this back to quarantine; it never
/// sends a path.
pub id: String,
pub confidence: Confidence,
/// The file the finding is about. `None` for machine-state advisories.
pub path: Option<PathBuf>,
pub display_path: Option<String>,
/// What the thing is called in a list: file name, or the advisory subject.
pub name: String,
/// Human-readable statement of the threat or the reason.
pub title: String,
pub description: String,
pub evidence: Vec<Evidence>,
pub size: u64,
pub sha256: Option<String>,
pub signed: bool,
pub publisher: Option<String>,
pub found_at_ms: u64,
/// Set once the file has been quarantined, from the ledger.
pub quarantined: bool,
/// The user dismissed this finding for this scan only.
pub ignored: bool,
}
impl Finding {
pub fn confirmed(&self) -> bool {
self.confidence == Confidence::Confirmed
}
/// De-duplication identity: the same file reported by two detectors is one
/// row with two pieces of evidence.
pub fn fingerprint(&self) -> String {
let path = self
.path
.as_ref()
.map(|path| path.to_string_lossy().into_owned())
.unwrap_or_else(|| "-".into());
format!("{}|{}", self.confidence.as_str(), path)
}
}

View File

@ -0,0 +1,445 @@
//! Judgement calls that no published signature makes for you.
//!
//! These rules describe conditions a person would want to know about, not
//! threats. Each one produces [`Evidence`] and a ceiling, and the ceiling is the
//! important part: heuristics stop at `suspicious`, so a machine with an
//! unsigned updater in `~/Library/Application Support` gets a row to read, not a
//! file moved behind its back.
//!
//! Two properties do most of the work. **Who can rewrite the file**: a binary
//! that starts at login from a folder the current user owns can be replaced by
//! anything the current user runs, which is how persistence malware survives an
//! update. **What claims to be true**: a file named like a system component, or
//! launched by an entry whose target has vanished, is a mismatch between the
//! story and the facts.
use crate::findings::{Confidence, Evidence};
use squid_platform::startup::{StartupItem, StartupRisk, StartupScope, StartupSource};
use std::path::{Path, PathBuf};
/// What the scanner knows about one candidate file when it asks for a judgement.
pub struct Candidate<'a> {
pub path: &'a Path,
/// The login/startup entry that launches this file, when there is one.
pub startup: Option<&'a StartupItem>,
/// True when any user of this machine can replace the file.
pub world_writable: bool,
/// Whether the file carries a signature blob, from
/// [`squid_platform::trust::has_signature_blob`]. The caller answers this
/// because it decides what the question is worth: asking the operating
/// system to *validate* a signature costs a subprocess on macOS and a
/// certificate-chain walk on Windows, which is affordable for the few files
/// a scan is already reporting and ruinous for the thousands it is only
/// filtering.
pub signed: bool,
}
/// Judge one candidate. Returns evidence; the caller combines it with whatever
/// the published detectors found and takes the strongest level.
pub fn judge(candidate: &Candidate) -> Vec<Evidence> {
let mut evidence = Vec::new();
if let Some(item) = candidate.startup {
evidence.push(Evidence::StartsAtLogin {
entry: item.name.clone(),
source: item.source.as_str().to_string(),
});
if item.risks.contains(&StartupRisk::MissingTarget) {
evidence.push(Evidence::MissingTarget {
path: item
.program
.clone()
.unwrap_or_else(|| candidate.path.to_path_buf()),
});
}
if item.scope == StartupScope::System {
// A system-scope entry pointed at a user-writable file is the
// classic privilege hop: root runs something an unqualified user may
// overwrite.
if candidate.world_writable || starts_in_user_space(candidate.path) {
evidence.push(Evidence::WritableLocation {
path: candidate.path.to_path_buf(),
});
}
}
}
if !candidate.signed {
evidence.push(Evidence::Unsigned {
path: candidate.path.to_path_buf(),
note: None,
});
}
if starts_in_user_space(candidate.path) && candidate.startup.is_some() {
evidence.push(Evidence::WritableLocation {
path: candidate.path.to_path_buf(),
});
}
if let Some(claimed) =
impersonated_component(candidate.path).or_else(|| windows_lookalike(candidate.path))
{
evidence.push(Evidence::Impersonation {
claimed: claimed.to_string(),
path: candidate.path.to_path_buf(),
});
}
dedupe(&mut evidence);
evidence
}
/// The ceiling these heuristics can support: suspicious, never confirmed.
pub const CEILING: Confidence = Confidence::Suspicious;
/// Level for a set of heuristic findings alone.
///
/// One weak signal is a note; two that point the same way are a finding. A binary
/// with no signature is ordinary — squid itself is one — but a binary with no
/// signature *that starts at login* is the shape persistence malware takes, and a
/// file that claims to be a system component while sitting somewhere else is
/// suspicious on its own because nothing honest does that.
///
/// The alternative, which this used to be, was to call any single signal
/// suspicious. On a real machine that produced nine hundred rows next to a
/// download folder, and a list that long is read as noise and then ignored, which
/// is worse than not reporting it.
pub fn confidence(evidence: &[Evidence]) -> Confidence {
let mut weight = 0_u8;
for item in evidence {
match item {
// The one signal strong enough to stand alone.
Evidence::Impersonation { .. } => return Confidence::Suspicious,
Evidence::StartsAtLogin { .. }
| Evidence::Unsigned { .. }
| Evidence::WritableLocation { .. } => weight += 1,
// "The file it points at is gone" is housekeeping. It explains a
// finding and is worth showing beside one, but on its own it has
// never hurt anybody.
Evidence::MissingTarget { .. } => {}
// Everything else is not a heuristic's verdict at all. A denied hash
// or a YARA match is graded by the detector that produced it, and
// counting it here would let a published hit lend false
// corroboration to a weak heuristic sitting next to it.
_ => {}
}
}
if weight >= 2 {
Confidence::Suspicious
} else {
Confidence::Advisory
}
}
/// Locations every user of this machine can write to, and therefore locations
/// where a file that runs at login can be swapped without asking anybody.
fn starts_in_user_space(path: &Path) -> bool {
let home = squid_platform::startup::home_dir();
let text = path.to_string_lossy().to_lowercase();
if path.starts_with(&home) {
return true;
}
const WRITABLE: [&str; 4] = ["/users/shared/", "/tmp/", "/private/tmp/", "/var/folders/"];
WRITABLE.iter().any(|prefix| text.starts_with(prefix))
}
/// Names that belong to the operating system, so a file wearing one somewhere
/// else is worth a look. Matched on the whole stem, never a substring, because
/// `SpotlightHelper.app` in a legit vendor's folder is not claiming to be Apple's.
const LOOKALIKES: [(&str, &str); 8] = [
(
"Activity Monitor",
"/System/Applications/Utilities/Activity Monitor.app",
),
("Dock", "/System/Library/CoreServices/Dock.app"),
(
"ControlCenter",
"/System/Library/CoreServices/ControlCenter.app",
),
(
"WindowServer",
"/System/Library/PrivateFrameworks/SkyLight.framework",
),
("kernel_task", "the kernel"),
("launchd", "/sbin/launchd"),
(
"loginwindow",
"/System/Library/CoreServices/loginwindow.app",
),
(
"UserNotificationCenter",
"/System/Library/CoreServices/UserNotificationCenter.app",
),
];
fn impersonated_component(path: &Path) -> Option<&'static str> {
let file_name = path.file_name()?.to_string_lossy().into_owned();
let stem = file_name
.trim_end_matches(".app")
.trim_end_matches(".plist")
.to_string();
let (name, real_home) = LOOKALIKES
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(&stem))?;
// Apple's own copy living in its own place is not impersonating anything,
// and neither is anything Apple ships inside /System.
if path.starts_with("/System") || path.starts_with("/usr/libexec") {
return None;
}
let _ = real_home;
Some(*name)
}
/// Windows keeps its own set of names that people recognise and malware borrows.
#[cfg(windows)]
const WINDOWS_LOOKALIKES: [(&str, &str); 4] = [
("svchost", "%SystemRoot%\\System32\\svchost.exe"),
("explorer", "%SystemRoot%\\explorer.exe"),
("lsass", "%SystemRoot%\\System32\\lsass.exe"),
("taskhostw", "%SystemRoot%\\System32\\taskhostw.exe"),
];
#[cfg(windows)]
fn windows_lookalike(path: &Path) -> Option<&'static str> {
let file_name = path.file_name()?.to_string_lossy().into_owned();
let stem = file_name.trim_end_matches(".exe").to_string();
let system = std::env::var("SystemRoot").unwrap_or_default();
let (name, real) = WINDOWS_LOOKALIKES
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(&stem))?;
if !system.is_empty() && path.starts_with(&system) {
return None;
}
let _ = real;
Some(*name)
}
#[cfg(not(windows))]
fn windows_lookalike(_path: &Path) -> Option<&'static str> {
None
}
pub fn dedupe(evidence: &mut Vec<Evidence>) {
let mut seen: Vec<String> = Vec::with_capacity(evidence.len());
evidence.retain(|item| {
let key = item.key();
if seen.contains(&key) {
return false;
}
seen.push(key);
true
});
}
/// Startup entries whose own risk flags deserve a row in the findings list, even
/// though there is no file to quarantine. These are advisories about the
/// machine's persistence, and they are how a person finds an entry whose target
/// was deleted by hand and left behind.
pub fn startup_advisories(
items: &[StartupItem],
) -> Vec<(PathBuf, String, Confidence, Vec<Evidence>)> {
let mut out = Vec::new();
for item in items {
if item.system_vendor {
continue;
}
let mut evidence = Vec::new();
if item.risks.contains(&StartupRisk::MissingTarget) {
evidence.push(Evidence::MissingTarget {
path: item.program.clone().unwrap_or_default(),
});
}
if item.risks.contains(&StartupRisk::InTempDir)
|| item.risks.contains(&StartupRisk::HiddenHomeDirectory)
{
evidence.push(Evidence::WritableLocation {
path: item.program.clone().unwrap_or_default(),
});
}
if item.risks.contains(&StartupRisk::ScriptInterpreter) {
evidence.push(Evidence::StartsAtLogin {
entry: item.name.clone(),
source: format!("{} via script interpreter", item.source.as_str()),
});
}
if item.source == StartupSource::LoginItem {
continue;
}
if evidence.is_empty() {
continue;
}
let level = if item.risks.contains(&StartupRisk::MissingTarget) {
Confidence::Advisory
} else {
Confidence::Suspicious
};
out.push((
item.program
.clone()
.unwrap_or_else(|| PathBuf::from(&item.id)),
item.name.clone(),
level,
evidence,
));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use squid_platform::startup::{StartupScope, StartupSource};
fn item(path: &Path, source: StartupSource, scope: StartupScope) -> StartupItem {
let mut item = StartupItem::new(path.to_string_lossy(), "probe", source, scope);
item.program = Some(path.to_path_buf());
item
}
fn candidate<'a>(path: &'a Path, startup: Option<&'a StartupItem>) -> Candidate<'a> {
Candidate {
path,
startup,
world_writable: false,
// The probes below are plain text written by the test, so this is
// the honest answer for those files rather than a stub.
signed: false,
}
}
#[test]
fn a_home_folder_file_is_user_writable() {
let home = squid_platform::startup::home_dir();
assert!(starts_in_user_space(
&home.join("Library/Application Support/Thing/thing")
));
assert!(starts_in_user_space(Path::new("/tmp/thing")));
assert!(!starts_in_user_space(Path::new("/usr/libexec/thing")));
}
#[test]
fn an_app_named_like_a_system_component_outside_its_home_is_flagged() {
assert_eq!(
impersonated_component(Path::new(
"/Users/tester/Library/Application Support/Dock/Dock.app"
)),
Some("Dock")
);
// The real one is not impersonating itself.
assert_eq!(
impersonated_component(Path::new("/System/Library/CoreServices/Dock.app")),
None
);
// A vendor app whose name merely contains the word is not a claim.
assert_eq!(
impersonated_component(Path::new("/Applications/DockFinder.app")),
None
);
}
#[test]
fn heuristics_never_claim_confirmation() {
let path = squid_platform::startup::home_dir()
.join("Library/Application Support/guard-probe/updater");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"#!/bin/sh\necho probe\n").unwrap();
let entry = item(&path, StartupSource::LaunchAgent, StartupScope::User);
let evidence = judge(&candidate(&path, Some(&entry)));
assert!(
!evidence.is_empty(),
"an unsigned login agent should say something"
);
assert_eq!(confidence(&evidence), Confidence::Suspicious);
assert!(confidence(&evidence) != Confidence::Confirmed);
let _ = std::fs::remove_file(path);
}
#[test]
fn a_lone_missing_target_is_housekeeping_not_a_threat() {
let evidence = vec![
Evidence::StartsAtLogin {
entry: "ghost".into(),
source: "launch-agent".into(),
},
Evidence::MissingTarget {
path: PathBuf::from("/Users/tester/gone"),
},
];
assert_eq!(confidence(&evidence), Confidence::Advisory);
}
#[test]
fn one_weak_signal_is_a_note_and_two_are_a_finding() {
let unsigned = || Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
};
let login = || Evidence::StartsAtLogin {
entry: "thing".into(),
source: "launch-agent".into(),
};
// The whole machine is unsigned. Saying so once per file is noise.
assert_eq!(confidence(&[unsigned()]), Confidence::Advisory);
assert_eq!(confidence(&[]), Confidence::Advisory);
// Unsigned *and* started at login is the persistence shape.
assert_eq!(
confidence(&[unsigned(), login()]),
Confidence::Suspicious,
"corroborating signals have to outrank one lonely signal"
);
// Wearing a system component's name is enough on its own.
assert_eq!(
confidence(&[Evidence::Impersonation {
claimed: "Dock".into(),
path: PathBuf::from("/Users/tester/Dock"),
}]),
Confidence::Suspicious
);
// …and heuristics still cannot reach confirmed, whatever the combination.
assert_ne!(
confidence(&[unsigned(), login()]),
Confidence::Confirmed,
"no heuristic may claim certainty"
);
}
#[test]
fn a_published_hit_does_not_make_a_weak_heuristic_look_stronger() {
// One unsigned file plus one confirmed hash hit. The hash decides the
// level; the heuristic half must still say "one weak signal", or the
// ceiling that keeps heuristics out of `confirmed` would be grading the
// detector's evidence rather than its own.
let evidence = vec![
Evidence::DeniedHash {
sha256: "aa".into(),
threat: "known bad".into(),
},
Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
},
];
assert_eq!(confidence(&evidence), Confidence::Advisory);
}
#[test]
fn evidence_is_not_reported_twice() {
let mut evidence = vec![
Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
},
Evidence::Unsigned {
path: PathBuf::from("/a"),
note: None,
},
Evidence::Unsigned {
path: PathBuf::from("/b"),
note: None,
},
];
dedupe(&mut evidence);
assert_eq!(evidence.len(), 2);
}
}

View File

@ -0,0 +1,627 @@
//! Rule packs: the on-disk format, its verification, and the fallback that keeps
//! a bad download from leaving the machine unguarded.
//!
//! A pack is YARA source plus a JSON manifest, published beside the installers
//! on the same git-backed channel the app update uses. Two keys are involved and
//! they are deliberately different: the release key signs installers, and the
//! intel key signs rules. Rotating one should not have to move the other, and a
//! leaked installer key must not become a rule-injection path.
//!
//! Nothing is uploaded. The client fetches a manifest and, if newer, a pack; no
//! filename, hash, or scan result ever leaves the machine. That is a property of
//! this module, not of the caller's good intentions — there is no function here
//! that takes a path from the local disk and sends it anywhere.
use crate::rules::RuleLevel;
use crate::rules::RuleMeta;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
pub const MANIFEST_FILE: &str = "squid-intel.json";
pub const SIGNATURE_FILE: &str = "squid-intel.sig";
const SUPPORTED_SCHEMA: u32 = 1;
/// Parsers are the first thing a hostile input breaks, so the size gate is not
/// about disk space.
const MAX_PACK_BYTES: u64 = 8 * 1024 * 1024;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntelManifest {
pub schema: u32,
/// Monotonic pack revision. Compared as a number, not a date, so a re-issue
/// on the same day still wins.
pub revision: u64,
pub date: String,
pub pack: String,
pub sha256: String,
pub size: u64,
pub rules: Vec<RuleMeta>,
}
/// How the bytes reached us, which is a different fact from *what* they are.
///
/// Both variants mean the pack's SHA-256 and byte length matched its manifest and
/// that YARA accepted the source. Only `Verified` means a key this build knows
/// about signed the manifest.
///
/// The distinction exists because the release key is baked in at build time, so a
/// build from source has none. Refusing to update then would make rule packs a
/// feature only the release build can use; accepting silently would let the UI
/// print "signed" about a manifest nothing checked. So an unbaked key is accepted
/// and remembered as unverified, and the interface says so. A build that *does*
/// have a key and fails to verify it is an error, not a fallback.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Provenance {
/// A baked public key verified the manifest's Ed25519 signature.
Verified,
/// Integrity came from the manifest's SHA-256 alone: this build has no key.
Unverified,
}
/// A pack that has been read, verified, and compiled.
#[derive(Clone, Debug)]
pub struct Pack {
pub manifest: IntelManifest,
pub source: String,
pub provenance: Provenance,
}
impl Pack {
pub fn rule_count(&self) -> usize {
self.manifest.rules.len()
}
}
/// Where packs live: `current` is what the next scan uses, `previous` is what a
/// failed update falls back to. Keeping both is what makes a bad pack survivable.
pub fn intel_dir() -> PathBuf {
crate::coverage::intel_root()
}
fn current_pack_path() -> PathBuf {
intel_dir().join("current.json")
}
fn previous_pack_path() -> PathBuf {
intel_dir().join("previous.json")
}
/// Validate a parsed manifest before anything reads its fields.
pub fn validate_manifest(manifest: &IntelManifest) -> Result<(), String> {
if manifest.schema > SUPPORTED_SCHEMA {
return Err(format!(
"This rule pack needs intel schema {}, which Squid {} cannot read",
manifest.schema,
env!("CARGO_PKG_VERSION")
));
}
if !is_hex(manifest.sha256.as_bytes(), 64) {
return Err("The rule pack manifest does not carry a SHA-256.".into());
}
if manifest.size == 0 || manifest.size > MAX_PACK_BYTES {
return Err(format!(
"The rule pack size ({} bytes) is outside what Squid will read.",
manifest.size
));
}
let file = Path::new(&manifest.pack)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
if file.is_empty() || file != manifest.pack || manifest.pack.contains("..") {
return Err("The rule pack names a file outside its own folder.".into());
}
if !file.ends_with(".json") {
return Err("The rule pack file must be a .json pack.".into());
}
if manifest.rules.is_empty() {
return Err("The rule pack declares no rules.".into());
}
for rule in &manifest.rules {
if rule.name.is_empty()
|| !rule
.name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return Err(format!(
"Rule name {:?} is not a YARA identifier.",
rule.name
));
}
}
Ok(())
}
pub fn parse_manifest(text: &str) -> Result<IntelManifest, String> {
let manifest: IntelManifest = serde_json::from_str(text)
.map_err(|error| format!("The rule manifest is not readable: {error}"))?;
validate_manifest(&manifest)?;
Ok(manifest)
}
/// Read a downloaded pack and check it against the manifest the caller verified.
/// Signature verification happens where the public key lives (the desktop
/// layer), so this takes the manifest as given and proves only that *these
/// bytes* are the pack that manifest describes.
pub fn read_pack(
dir: &Path,
manifest: &IntelManifest,
provenance: Provenance,
) -> Result<Pack, String> {
let path = dir.join(&manifest.pack);
let metadata = std::fs::metadata(&path)
.map_err(|error| format!("Could not read the rule pack: {error}"))?;
if metadata.len() != manifest.size {
return Err(format!(
"{} is {} bytes, the manifest says {}.",
manifest.pack,
metadata.len(),
manifest.size
));
}
let bytes = std::fs::read(&path).map_err(|error| error.to_string())?;
let actual = digest(&bytes);
if !actual.eq_ignore_ascii_case(&manifest.sha256) {
return Err(format!(
"The rule pack hash does not match the manifest ({}).",
short(&actual)
));
}
let parsed: PackFile = serde_json::from_slice(&bytes)
.map_err(|error| format!("The rule pack is not readable: {error}"))?;
if parsed.revision != manifest.revision {
return Err("The rule pack revision does not match the manifest.".into());
}
// Compile before accepting: a pack YARA rejects must never become
// `current`, because the next scan would fail at the worst moment.
crate::rules::Detector::from_source_for_pack(&parsed.source, &manifest.rules)?;
Ok(Pack {
manifest: manifest.clone(),
source: parsed.source,
provenance,
})
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct PackFile {
revision: u64,
source: String,
}
/// What squid keeps on disk: the pack, together with the manifest that was
/// verified when it was installed. One file, so no later read can pair a pack
/// with the wrong manifest.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct PackRecord {
manifest: IntelManifest,
revision: u64,
source: String,
/// Recorded at install so the UI can still say, after a restart and with no
/// network, whether what it is running was ever signature-verified.
/// Defaults to the honest pessimistic answer for a record written before this
/// field existed: nothing is claimed about the signature.
#[serde(default = "Provenance::unverified")]
provenance: Provenance,
}
impl Provenance {
const fn unverified() -> Provenance {
Provenance::Unverified
}
}
/// Build the pack file that gets published, so a pack is produced by the same
/// code that reads one.
pub fn pack_file(revision: u64, source: &str) -> Vec<u8> {
let file = PackFile {
revision,
source: source.to_string(),
};
serde_json::to_vec_pretty(&file).expect("a pack file always serialises")
}
/// Install a verified pack, keeping the record it replaces for rollback.
pub fn install_pack(pack: &Pack) -> Result<(), String> {
let dir = intel_dir();
std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
let current = current_pack_path();
if current.is_file() {
let text = std::fs::read_to_string(&current).map_err(|error| error.to_string())?;
std::fs::write(previous_pack_path(), text).map_err(|error| error.to_string())?;
}
let record = PackRecord {
manifest: pack.manifest.clone(),
revision: pack.manifest.revision,
source: pack.source.clone(),
provenance: pack.provenance,
};
let bytes = serde_json::to_vec_pretty(&record).map_err(|error| error.to_string())?;
std::fs::write(&current, bytes).map_err(|error| error.to_string())
}
/// The best installed pack, falling back to the previous record when `current`
/// has been corrupted or truncated since it was written.
pub fn installed_pack() -> Option<Pack> {
for path in [current_pack_path(), previous_pack_path()] {
if let Some(pack) = read_record(&path) {
return Some(pack);
}
}
None
}
/// Read one stored record and re-prove it: the hash against its own manifest,
/// and the source against the rule table. A record that fails either is treated
/// as absent, because half a rule set is how a bad pack becomes a false sense of
/// safety.
pub fn read_record(path: &Path) -> Option<Pack> {
let text = std::fs::read_to_string(path).ok()?;
let record: PackRecord = serde_json::from_str(&text).ok()?;
validate_manifest(&record.manifest).ok()?;
let bytes = pack_file(record.revision, &record.source);
if bytes.len() as u64 != record.manifest.size {
return None;
}
if !digest(&bytes).eq_ignore_ascii_case(&record.manifest.sha256) {
return None;
}
if crate::rules::Detector::from_source_for_pack(&record.source, &record.manifest.rules).is_err()
{
return None;
}
Some(Pack {
manifest: record.manifest,
source: record.source,
provenance: record.provenance,
})
}
fn digest(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(bytes))
}
/// Everything the UI shows about the installed rules, without touching the
/// network. `builtin` is the floor: a machine that never downloaded a pack is
/// still guarded by the compiled-in rules.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntelStatus {
pub builtin_rules: usize,
pub installed_rules: usize,
pub revision: u64,
pub published: String,
/// Compiled-in rules are as trusted as the binary itself; a downloaded pack is
/// `true` only when a key this build knows about signed its manifest.
pub signed: bool,
pub source: String,
pub path: String,
pub fallback_available: bool,
}
pub fn status() -> IntelStatus {
let builtin = crate::rules::builtin_meta().len();
match installed_pack() {
Some(pack) => IntelStatus {
builtin_rules: builtin,
installed_rules: pack.rule_count(),
revision: pack.manifest.revision,
published: pack.manifest.date.clone(),
signed: pack.provenance == Provenance::Verified,
source: "pack".into(),
path: current_pack_path().to_string_lossy().into_owned(),
fallback_available: previous_pack_path().is_file(),
},
None => IntelStatus {
builtin_rules: builtin,
installed_rules: builtin,
revision: 0,
published: String::new(),
signed: true,
source: "builtin".into(),
path: intel_dir().to_string_lossy().into_owned(),
fallback_available: false,
},
}
}
/// Roll back one step, used when a scan reports that the newest pack misbehaves.
pub fn rollback() -> Result<(), String> {
let previous = previous_pack_path();
let text = std::fs::read_to_string(&previous)
.map_err(|_| "There is no previous rule pack to fall back to.".to_string())?;
std::fs::write(current_pack_path(), text).map_err(|error| error.to_string())?;
let _ = std::fs::remove_file(previous);
Ok(())
}
/// The path of the installed record, for the UI that shows where rules came from.
pub fn current_pack_record() -> PathBuf {
current_pack_path()
}
fn is_hex(bytes: &[u8], length: usize) -> bool {
bytes.len() == length && bytes.iter().all(|byte| byte.is_ascii_hexdigit())
}
fn short(value: &str) -> String {
value.chars().take(12).collect()
}
/// Rule levels as the pack spells them, checked against what the scanner will
/// accept. A pack cannot invent a level, and cannot promote itself to
/// `signature` for a rule the client has never seen before without saying so.
pub fn level_is_known(level: &RuleLevel) -> bool {
matches!(level, RuleLevel::Signature | RuleLevel::Behaviour)
}
#[cfg(test)]
mod tests {
use super::*;
/// The manifest that honestly describes one pack source.
fn manifest_for(revision: u64, rule: &str, source: &str) -> IntelManifest {
let bytes = pack_file(revision, source);
IntelManifest {
schema: SUPPORTED_SCHEMA,
revision,
date: "2026-11-06".into(),
pack: "squid-rules.json".into(),
sha256: digest(&bytes),
size: bytes.len() as u64,
rules: vec![RuleMeta {
name: rule.into(),
description: "only in the pack".into(),
family: "pack".into(),
level: RuleLevel::Signature,
}],
}
}
fn manifest(revision: u64) -> IntelManifest {
let source = r#"rule PackOnly { strings: $a = "pack-marker-only" condition: $a }"#;
let bytes = pack_file(revision, source);
IntelManifest {
schema: SUPPORTED_SCHEMA,
revision,
date: "2026-11-06".into(),
pack: "squid-rules.json".into(),
sha256: write_and_hash(&bytes),
size: bytes.len() as u64,
rules: vec![RuleMeta {
name: "PackOnly".into(),
description: "only in the pack".into(),
family: "pack".into(),
level: RuleLevel::Signature,
}],
}
}
fn write_and_hash(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(bytes))
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("squid-intel-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let _ = std::fs::remove_file(dir.join("squid-rules.json"));
dir
}
#[test]
fn a_pack_round_trips_through_its_manifest() {
let dir = temp_dir("round-trip");
let manifest = manifest(7);
std::fs::write(
dir.join(&manifest.pack),
pack_file(
7,
r#"rule PackOnly { strings: $a = "pack-marker-only" condition: $a }"#,
),
)
.unwrap();
let manifest = {
let bytes = std::fs::read(dir.join(&manifest.pack)).unwrap();
IntelManifest {
sha256: write_and_hash(&bytes),
size: bytes.len() as u64,
..manifest
}
};
let pack =
read_pack(&dir, &manifest, Provenance::Verified).expect("the pack should read back");
assert_eq!(pack.rule_count(), 1);
assert_eq!(pack.manifest.revision, 7);
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn a_truncated_pack_is_refused_before_it_is_used() {
let dir = temp_dir("truncated");
let manifest = manifest(8);
std::fs::write(dir.join(&manifest.pack), b"half a file").unwrap();
let error = read_pack(&dir, &manifest, Provenance::Verified)
.expect_err("size must match the manifest");
assert!(error.contains("bytes"), "{error}");
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn a_pack_that_yara_rejects_never_installs() {
let dir = temp_dir("broken-yara");
let bytes = pack_file(9, "rule {{{ not yara");
std::fs::write(dir.join("squid-rules.json"), &bytes).unwrap();
let manifest = IntelManifest {
schema: SUPPORTED_SCHEMA,
revision: 9,
date: "2026-11-06".into(),
pack: "squid-rules.json".into(),
sha256: write_and_hash(&bytes),
size: bytes.len() as u64,
rules: vec![RuleMeta {
name: "Whatever".into(),
description: String::new(),
family: "pack".into(),
level: RuleLevel::Behaviour,
}],
};
assert!(
read_pack(&dir, &manifest, Provenance::Verified).is_err(),
"a pack YARA rejects must not be installable"
);
}
#[test]
fn an_unsigned_pack_survives_the_round_trip_as_unsigned() {
// A build with no baked key can still take updates, but must not end up
// claiming afterwards that something verified them.
let _guard = crate::state_guard("provenance");
let pack = Pack {
manifest: manifest_for(7, "ProvOnly", r#"rule ProvOnly { condition: false }"#),
source: r#"rule ProvOnly { condition: false }"#.to_string(),
provenance: Provenance::Unverified,
};
install_pack(&pack).unwrap();
let status = status();
assert_eq!(status.source, "pack");
assert!(
!status.signed,
"the UI has to be able to tell an unverified pack from a signed one"
);
assert_eq!(installed_pack().unwrap().provenance, Provenance::Unverified);
}
#[test]
fn a_record_from_before_provenance_existed_is_not_assumed_signed() {
// An old `current.json` has no provenance field. Reading it as
// `Verified` would print a green "signed" for a pack nobody checked.
let _guard = crate::state_guard("provenance-old");
let pack = published_pack(8, "OldOnly", r#"rule OldOnly { condition: false }"#);
install_pack(&pack).unwrap();
let path = current_pack_path();
let text = std::fs::read_to_string(&path).unwrap();
// The field is last in the pretty-printed object, so the comma to remove
// is the one before it.
let stripped = text.replace(",\n \"provenance\": \"verified\"", "");
assert_ne!(text, stripped, "the fixture must actually carry the field");
std::fs::write(&path, stripped).unwrap();
let read = read_record(&path).expect("a record missing one field still reads");
assert_eq!(read.provenance, Provenance::Unverified);
}
#[test]
fn a_rejected_pack_is_never_installed_even_when_the_hash_matches() {
let dir = std::env::temp_dir().join("squid-intel-yara");
std::fs::create_dir_all(&dir).unwrap();
let source = "rule Broken { condition: this is not yara ((( }";
let manifest = manifest_for(9, "Broken", source);
std::fs::write(dir.join(&manifest.pack), pack_file(9, source)).unwrap();
assert!(
read_pack(&dir, &manifest, Provenance::Verified).is_err(),
"a pack YARA cannot compile must be refused"
);
std::fs::remove_dir_all(dir).ok();
}
#[test]
fn a_manifest_cannot_escape_its_folder_or_lie_about_size() {
for escape in ["../evil.json", "/etc/passwd", "sub/dir/rules.json"] {
let base = manifest(1);
let dodgy = IntelManifest {
pack: escape.into(),
..base
};
assert!(
validate_manifest(&dodgy).is_err(),
"{escape} should be refused"
);
}
let huge = IntelManifest {
size: MAX_PACK_BYTES + 1,
..manifest(1)
};
assert!(validate_manifest(&huge).is_err());
let no_hash = IntelManifest {
sha256: "deadbeef".into(),
..manifest(1)
};
assert!(validate_manifest(&no_hash).is_err());
let empty = IntelManifest {
rules: Vec::new(),
..manifest(1)
};
assert!(validate_manifest(&empty).is_err());
}
#[test]
fn a_newer_schema_is_refused_rather_than_misread() {
let newer = IntelManifest {
schema: SUPPORTED_SCHEMA + 1,
..manifest(1)
};
let error = validate_manifest(&newer).expect_err("schema must be checked");
assert!(error.contains("schema"), "{error}");
}
#[test]
fn rule_names_must_be_yara_identifiers() {
let dodgy = IntelManifest {
rules: vec![RuleMeta {
name: "not a rule name".into(),
description: String::new(),
family: String::new(),
level: RuleLevel::Behaviour,
}],
..manifest(1)
};
assert!(validate_manifest(&dodgy).is_err());
}
#[test]
fn the_builtin_pack_reports_itself_without_any_download() {
let _guard = crate::state_guard("builtin");
let status = status();
assert_eq!(status.source, "builtin");
assert_eq!(status.revision, 0);
assert!(status.installed_rules >= status.builtin_rules);
assert!(
status.signed,
"compiled-in rules are as trusted as the binary"
);
}
#[test]
fn installing_a_pack_keeps_the_previous_one_and_can_roll_back() {
let _guard = crate::state_guard("rollback");
let first = published_pack(10, "PackOnly", r#"rule PackOnly { condition: false }"#);
let second = published_pack(
11,
"PackOnlyTwo",
r#"rule PackOnlyTwo { condition: false }"#,
);
install_pack(&first).unwrap();
install_pack(&second).unwrap();
assert!(
previous_pack_path().is_file(),
"the record it replaced is kept"
);
assert_eq!(installed_pack().unwrap().manifest.revision, 11);
rollback().unwrap();
let back = installed_pack().expect("rollback restores the older pack");
assert_eq!(back.manifest.revision, 10);
}
/// Build a pack the way an update does: the source first, then a manifest
/// that honestly describes those exact bytes.
fn published_pack(revision: u64, rule: &str, source: &str) -> Pack {
Pack {
manifest: manifest_for(revision, rule, source),
source: source.to_string(),
provenance: Provenance::Verified,
}
}
}

View File

@ -0,0 +1,60 @@
//! squid-guard — the security half of squid.
//!
//! Position matters more than ambition here. XProtect (macOS) and Defender
//! (Windows) remain the real-time protection of this machine; squid does not
//! replace them, does not copy their rules, and does not install anything that
//! runs before execve. What this crate adds is the part those engines leave to
//! the owner of the machine: an inventory of *what* starts at login, an
//! evidence-grade scan of the files behind that inventory and the obvious
//! user-writable run locations, and a reversible quarantine that never deletes.
//!
//! Two rules keep the crate honest:
//!
//! 1. A scan never removes anything. It produces [`finding::Finding`]s with
//! evidence, and only an explicit user decision (or the opt-in automatic
//! quarantine, confirmed-level only) moves a file.
//! 2. Findings are addressed by backend-issued id, never by path. The caller
//! cannot quarantine a file the scan never reported.
//!
//! Detection is layered so a weak layer can never masquerade as a strong one:
//!
//! - a SHA-256 blacklist answers "is this exact file known bad" (`confirmed`);
//! - YARA-X rules answer "does this file match a known family" (`confirmed` for
//! high-confidence rules, `suspicious` otherwise);
//! - heuristics answer "would a careful person look at this twice"
//! (`suspicious`/`advisory`) and never quarantine on their own.
pub mod coverage;
pub mod findings;
pub mod heuristics;
pub mod intel;
pub mod quarantine;
pub mod rules;
pub mod scan;
pub mod store;
pub use findings::{Confidence, Evidence, Finding};
pub use quarantine::{QuarantineEntry, QuarantineLedger};
pub use scan::{ScanMode, ScanReport as GuardReport, ScanTarget};
pub use store::Store;
/// Crate version tag written into the quarantine ledger, mirroring the
/// cleanup ledger's habit of stamping the format it was written by.
pub const LEDGER_TAG: &str = concat!("squid-guard/", env!("CARGO_PKG_VERSION"));
/// Tests that touch on-disk state share one lock, because the state directory is
/// chosen by a process-wide environment variable. Without it, a quarantine test
/// can reopen its ledger in whatever directory an intel test pointed the process
/// at a moment earlier.
#[cfg(test)]
pub(crate) fn state_guard(tag: &str) -> std::sync::MutexGuard<'static, ()> {
static GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
let guard = GUARD
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let dir = std::env::temp_dir().join(format!("squid-guard-state-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("a test can create its own state directory");
std::env::set_var("SQUID_STATE_DIR", &dir);
guard
}

View File

@ -0,0 +1,682 @@
//! The quarantine: files squid moved out of the way, and the record that lets
//! them go back.
//!
//! Three properties are worth stating because they are what distinguishes this
//! from "delete" and from the system Trash:
//!
//! - **Reversible until told otherwise.** Each object keeps its original path,
//! mode and timestamps, so `restore` can put it back where it came from.
//! - **Inert.** Files land in squid's own state folder with the execute bit
//! cleared and owner-only permissions, so a quarantined login item cannot run
//! again while it waits there.
//! - **Owned by squid.** The Trash is the operating system's, and sending a
//! suspected binary there means the user has to remember to empty it. Here the
//! ledger and the objects sit together, and the UI can say exactly what is in
//! the way.
//!
//! The ledger is the authority. A file is quarantined because the ledger says
//! so, and every operation re-reads the ledger before touching the disk, so a
//! half-finished move on a full disk shows up as an honest error rather than a
//! file in two places.
use crate::coverage::quarantine_root;
use crate::findings::{Evidence, Finding};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use squid_core::paths;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// One quarantined object, as recorded before anything was moved.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuarantineEntry {
pub id: String,
/// Where the file lived. Kept for restore, never trusted as-is.
pub original_path: PathBuf,
pub display_path: String,
/// Relative name inside the quarantine folder.
pub stored: String,
pub size: u64,
pub sha256: String,
/// Unix mode, or the Windows read-only flag folded into it.
pub mode: u32,
pub modified_ms: u64,
pub quarantined_ms: u64,
/// Why it was moved, kept so the list can explain itself a month later.
pub title: String,
pub confidence: String,
pub evidence: Vec<Evidence>,
}
/// The quarantine folder's own ledger. Written beside the objects so the whole
/// thing can be inspected, copied or deleted by hand.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QuarantineLedger {
pub version: u32,
pub entries: Vec<QuarantineEntry>,
}
impl QuarantineLedger {
fn load(path: &Path) -> QuarantineLedger {
std::fs::read_to_string(path)
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or(QuarantineLedger {
version: 1,
entries: Vec::new(),
})
}
fn save(&self, path: &Path) -> Result<(), String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
let text = serde_json::to_string_pretty(self).map_err(|error| error.to_string())?;
std::fs::write(path, text).map_err(|error| error.to_string())
}
}
fn ledger_path() -> PathBuf {
quarantine_root().join("ledger.json")
}
fn objects_dir() -> PathBuf {
quarantine_root().join("objects")
}
/// The quarantine, opened for one session of the app.
#[derive(Default)]
pub struct Quarantine {
ledger: QuarantineLedger,
loaded: bool,
}
impl Quarantine {
pub fn new() -> Quarantine {
Quarantine::default()
}
fn ensure_loaded(&mut self) {
if !self.loaded {
self.ledger = QuarantineLedger::load(&ledger_path());
self.loaded = true;
}
}
/// Everything the ledger recorded. Reading the list is what loads the
/// ledger, so a freshly opened quarantine describes what is on disk rather
/// than an empty list that would offer "quarantine" for a file already moved.
pub fn entries(&mut self) -> &[QuarantineEntry] {
self.ensure_loaded();
&self.ledger.entries
}
pub fn find(&mut self, id: &str) -> Option<&QuarantineEntry> {
self.ensure_loaded();
self.ledger.entries.iter().find(|entry| entry.id == id)
}
/// Move one finding into the quarantine.
///
/// The finding is what the scan reported; nothing here accepts a bare path.
/// Before moving, the file is re-hashed and compared with the value recorded
/// at scan time, so a file that changed between "found" and "quarantine" is
/// reported rather than moved: the bytes the user decided about are not the
/// bytes on disk.
pub fn quarantine(&mut self, finding: &Finding) -> Result<QuarantineEntry, String> {
self.ensure_loaded();
let path = finding
.path
.as_ref()
.ok_or_else(|| "This finding has no file to quarantine.".to_string())?;
let refused = refusal(path)?;
if let Some(reason) = refused {
return Err(reason);
}
let metadata = std::fs::symlink_metadata(path).map_err(|error| error.to_string())?;
if !metadata.is_file() {
return Err(
"Only single files can be quarantined — a folder needs the uninstaller.".into(),
);
}
let is_link = metadata.file_type().is_symlink();
if is_link {
return Err("A symbolic link is not the file that was scanned.".into());
}
if metadata.len() != finding.size {
return Err(format!(
"{} changed size since the scan. Run the scan again.",
paths::pretty(path)
));
}
let hash = hash_file(path)?;
if let Some(expected) = finding.sha256.as_deref() {
if !expected.eq_ignore_ascii_case(&hash) {
return Err(format!(
"{} changed since the scan. Run the scan again.",
paths::pretty(path)
));
}
}
let id = new_id(path, &hash);
if self.ledger.entries.iter().any(|entry| entry.id == id) {
return Err("This file is already in the quarantine.".into());
}
// Two scans of the same bytes in different places get different ids,
// because the original path is part of what restore needs.
let stored = format!("{id}.bin");
let destination = objects_dir().join(&stored);
if destination.exists() {
return Err("The quarantine already holds an object with this name.".into());
}
// Read the mode before anything else happens to the file: the stored
// copy is deliberately made inert below, and restore has to hand back
// what the file was, not what the quarantine keeps it as.
let mode = current_mode(path);
std::fs::create_dir_all(objects_dir()).map_err(|error| error.to_string())?;
std::fs::rename(path, &destination).or_else(|rename_error| {
// Renaming fails across volumes, which is normal for an external
// disk or a DMG that is still mounted.
std::fs::copy(path, &destination)
.map_err(|copy_error| {
format!(
"Could not move the file into the quarantine: {rename_error}; copy failed: {copy_error}"
)
})
.and_then(|_| std::fs::remove_file(path).map_err(|error| error.to_string()))
})?;
// Make the object inert while it waits: no execute, readable only by the
// owner who chose to quarantine it.
restrict_permissions(&destination);
let entry = QuarantineEntry {
id: id.clone(),
original_path: path.clone(),
display_path: paths::pretty(path),
stored,
size: metadata.len(),
sha256: hash,
mode,
modified_ms: metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|since| since.as_millis() as u64)
.unwrap_or_default(),
quarantined_ms: now_ms(),
title: finding.title.clone(),
confidence: finding.confidence.as_str().to_string(),
evidence: finding.evidence.clone(),
};
self.ledger.entries.push(entry.clone());
if let Err(error) = self.ledger.save(&ledger_path()) {
// The file is already in place, so undo the move rather than leave a
// file the ledger does not know about.
let _ = std::fs::rename(&destination, path);
self.ledger.entries.retain(|kept| kept.id != id);
return Err(format!("Could not record the quarantine: {error}"));
}
Ok(entry)
}
/// Put one object back where it came from.
pub fn restore(&mut self, id: &str) -> Result<PathBuf, String> {
self.ensure_loaded();
let index = self
.ledger
.entries
.iter()
.position(|entry| entry.id == id)
.ok_or_else(|| "That object is not in the quarantine.".to_string())?;
let entry = self.ledger.entries[index].clone();
let stored = objects_dir().join(&entry.stored);
if !stored.is_file() {
return Err(format!(
"The quarantined copy of {} is gone from disk.",
entry.display_path
));
}
if entry.original_path.exists() {
return Err(format!(
"{} is there again. Squid will not overwrite it.",
entry.display_path
));
}
if let Some(parent) = entry.original_path.parent() {
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
}
std::fs::rename(&stored, &entry.original_path).or_else(|error| {
std::fs::copy(&stored, &entry.original_path)
.map_err(|copy| format!("Could not restore the file: {error}; {copy}"))
.and_then(|_| std::fs::remove_file(&stored).map_err(|error| error.to_string()))
})?;
restore_permissions(&entry.original_path, entry.mode);
// A byte-for-byte check is the only proof that restore worked: the file
// is back, in one place, with the content that was taken out.
let restored_hash = hash_file(&entry.original_path)?;
if !restored_hash.eq_ignore_ascii_case(&entry.sha256) {
return Err(format!(
"{} came back with different bytes; the quarantine copy was kept.",
entry.display_path
));
}
self.ledger.entries.remove(index);
self.ledger.save(&ledger_path())?;
Ok(entry.original_path)
}
/// Throw one object away for real. This is the only place in the security
/// half of squid that destroys user data, so it is only reachable from the
/// quarantine list, never from a scan.
pub fn purge(&mut self, id: &str) -> Result<(), String> {
self.ensure_loaded();
let index = self
.ledger
.entries
.iter()
.position(|entry| entry.id == id)
.ok_or_else(|| "That object is not in the quarantine.".to_string())?;
let entry = self.ledger.entries.remove(index);
let stored = objects_dir().join(&entry.stored);
let result = match std::fs::remove_file(&stored) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
};
match result {
Ok(()) => self.ledger.save(&ledger_path()),
Err(error) => {
self.ledger.entries.insert(index, entry);
Err(format!("Could not delete the quarantined copy: {error}"))
}
}
}
/// Reconcile the ledger with the folder. Deleting objects by hand, or an
/// interrupted release upgrade, can leave entries whose file is gone; the UI
/// must not offer "restore" for something that is not there.
pub fn reconcile(&mut self) -> Vec<String> {
self.ensure_loaded();
let mut lost = Vec::new();
self.ledger.entries.retain(|entry| {
let present = objects_dir().join(&entry.stored).is_file();
if !present {
lost.push(entry.id.clone());
}
present
});
if !lost.is_empty() {
let _ = self.ledger.save(&ledger_path());
}
lost
}
pub fn total_size(&mut self) -> u64 {
self.ledger.entries.iter().map(|entry| entry.size).sum()
}
}
/// The paths a quarantine must never touch, whatever a scan claimed. Checked at
/// move time rather than trusted from the scan, because the scan is a snapshot
/// of an opinion and this is the moment data actually moves.
fn refusal(path: &Path) -> Result<Option<String>, String> {
const PROTECTED: [&str; 6] = [
"/System",
"/usr",
"/bin",
"/sbin",
"/Library/Apple",
"/Applications/Utilities",
];
if PROTECTED.iter().any(|prefix| path.starts_with(prefix)) {
return Ok(Some(
"Squid does not quarantine files inside the operating system.".into(),
));
}
#[cfg(windows)]
if let Ok(system) = std::env::var("SystemRoot") {
if path.starts_with(system) {
return Ok(Some(
"Squid does not quarantine files inside Windows.".into(),
));
}
}
if path.starts_with(quarantine_root()) {
return Ok(Some("That file is already in the quarantine.".into()));
}
if path.starts_with(squid_core::Settings::state_dir())
|| path.starts_with(squid_core::Settings::config_dir())
{
return Ok(Some("That file belongs to Squid itself.".into()));
}
if is_own_binary(path) {
return Ok(Some("That is the app you are using right now.".into()));
}
if !std::fs::symlink_metadata(path).is_ok() {
return Ok(Some("The file is not there any more.".into()));
}
// The current user has to own it, or be able to write its folder: without
// that, moving the file needs rights this release does not ask for.
if !squid_platform::is_user_writable(path.parent().unwrap_or(path)) {
return Ok(Some(
"You do not have permission to move a file from that folder.".into(),
));
}
Ok(None)
}
fn is_own_binary(path: &Path) -> bool {
let Ok(current) = std::env::current_exe() else {
return false;
};
paths::same_path(&current, path)
|| current
.ancestors()
.zip(path.ancestors())
.all(|(a, b)| a == b)
&& path.starts_with(current.parent().unwrap_or(Path::new("/")))
}
fn hash_file(path: &Path) -> Result<String, String> {
let mut file = std::fs::File::open(path).map_err(|error| error.to_string())?;
let mut digest = Sha256::new();
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = file.read(&mut buffer).map_err(|error| error.to_string())?;
if read == 0 {
break;
}
digest.update(&buffer[..read]);
}
Ok(hex::encode(digest.finalize()))
}
fn new_id(path: &Path, hash: &str) -> String {
let mut digest = Sha256::new();
digest.update(path.to_string_lossy().as_bytes());
digest.update(hash.as_bytes());
let full = hex::encode(digest.finalize());
full[..20].to_string()
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
#[cfg(unix)]
fn restrict_permissions(path: &Path) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
#[cfg(windows)]
fn restrict_permissions(path: &Path) {
if let Ok(metadata) = std::fs::metadata(path) {
let mut permissions = metadata.permissions();
permissions.set_readonly(true);
let _ = std::fs::set_permissions(path, permissions);
}
}
#[cfg(not(any(unix, windows)))]
fn restrict_permissions(_path: &Path) {}
#[cfg(unix)]
fn current_mode(path: &Path) -> u32 {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path)
.map(|metadata| metadata.permissions().mode())
.unwrap_or(0o644)
}
#[cfg(not(unix))]
fn current_mode(_path: &Path) -> u32 {
0o644
}
#[cfg(unix)]
fn restore_permissions(path: &Path, mode: u32) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
}
#[cfg(not(unix))]
fn restore_permissions(path: &Path, mode: u32) {
if let Ok(metadata) = std::fs::metadata(path) {
let mut permissions = metadata.permissions();
permissions.set_readonly(mode & 0o200 == 0);
let _ = std::fs::set_permissions(path, permissions);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::findings::Confidence;
use std::io::Write;
fn finding_for(path: &Path) -> Finding {
let hash = hash_file(path).unwrap();
Finding {
id: "f1".into(),
confidence: Confidence::Confirmed,
path: Some(path.to_path_buf()),
display_path: Some(paths::pretty(path)),
name: "probe".into(),
title: "test finding".into(),
description: String::new(),
evidence: vec![Evidence::DeniedHash {
sha256: hash.clone(),
threat: "probe".into(),
}],
size: std::fs::metadata(path).unwrap().len(),
sha256: Some(hash),
signed: false,
publisher: None,
found_at_ms: now_ms(),
quarantined: false,
ignored: false,
}
}
fn probe(name: &str, bytes: &[u8]) -> PathBuf {
let dir = std::env::temp_dir().join(format!("squid-quarantine-{name}"));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("payload.bin");
let mut file = std::fs::File::create(&path).unwrap();
file.write_all(bytes).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
path
}
/// Quarantine paths come from `Settings::state_dir()`, which honours
/// `SQUID_STATE_DIR`. Every test that touches the ledger takes this lock and
/// points the state directory at its own folder, so the suite neither sees
/// the real quarantine nor leaves debris in it.
/// Quarantine paths come from `Settings::state_dir()`, which honours
/// `SQUID_STATE_DIR`, and that variable is process-wide. So each ledger test
/// holds one lock for its whole body and gets a freshly emptied directory of
/// its own: no test sees another's entries, and none of them touch the real
#[test]
fn quarantine_and_restore_round_trip_is_byte_identical() {
let _guard = crate::state_guard("round-trip");
let path = probe("round-trip", b"the payload that has to come back");
let before = std::fs::metadata(&path).unwrap();
let mut quarantine = Quarantine::new();
let entry = quarantine
.quarantine(&finding_for(&path))
.expect("quarantine should accept a file the test owns");
assert!(!path.exists(), "the file should have moved");
assert!(!entry.stored.is_empty());
let restored = quarantine.restore(&entry.id).expect("restore");
assert_eq!(restored, path);
assert_eq!(
std::fs::read(&path).unwrap(),
b"the payload that has to come back"
);
assert_eq!(
std::fs::metadata(&path).unwrap().len(),
before.len(),
"the file should be back at its original size"
);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn restoring_restores_the_execute_bit() {
let _guard = crate::state_guard("execute-bit");
let path = probe("execute-bit", b"#!/bin/sh\n");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_ne!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
0,
"the probe should start executable"
);
}
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let stored = objects_dir().join(&entry.stored);
assert_eq!(
std::fs::metadata(stored).unwrap().permissions().mode() & 0o111,
0,
"a quarantined file must not be executable"
);
}
quarantine.restore(&entry.id).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_ne!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o111,
0,
"restore should hand the execute bit back"
);
}
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn a_file_that_changed_after_the_scan_is_not_moved() {
let _guard = crate::state_guard("changed");
let path = probe("changed", b"original bytes");
let finding = finding_for(&path);
std::fs::write(&path, b"somebody else rewrote this file").unwrap();
let error = Quarantine::new()
.quarantine(&finding)
.expect_err("the file no longer matches the scan");
assert!(
error.contains("changed"),
"the message should say the file changed: {error}"
);
assert!(path.exists(), "a refused quarantine must not move anything");
let finding = finding_for(&path);
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding).expect("a fresh scan works");
quarantine.restore(&entry.id).unwrap();
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_system_and_squid_itself_are_never_quarantined() {
let _guard = crate::state_guard("protected");
let mut quarantine = Quarantine::new();
for path in [
Path::new("/System/Library/CoreServices/Finder.app/Contents/MacOS/Finder"),
Path::new("/usr/bin/true"),
] {
if !path.is_file() {
continue;
}
let error = quarantine
.quarantine(&finding_for(path))
.expect_err("an OS file must be refused");
assert!(error.contains("operating system"), "{path:?}: {error}");
assert!(path.is_file(), "{path:?} must still be where it was");
}
}
#[test]
fn purging_deletes_only_the_quarantined_copy() {
let _guard = crate::state_guard("purge");
let path = probe("purge", b"this one is thrown away");
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
assert!(!path.exists());
quarantine.purge(&entry.id).unwrap();
assert!(!objects_dir().join(&entry.stored).exists());
assert!(quarantine.entries().iter().all(|kept| kept.id != entry.id));
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_ledger_survives_a_new_session_and_notices_lost_objects() {
let _guard = crate::state_guard("ledger");
let path = probe("ledger", b"survive the restart");
let mut session = Quarantine::new();
let entry = session.quarantine(&finding_for(&path)).unwrap();
drop(session);
let mut reopened = Quarantine::new();
assert!(
reopened.find(&entry.id).is_some(),
"the ledger must describe the quarantine after a restart"
);
let stored = objects_dir().join(&entry.stored);
std::fs::remove_file(&stored).unwrap();
let mut third = Quarantine::new();
let lost = third.reconcile();
assert_eq!(lost, vec![entry.id.clone()]);
assert!(third.find(&entry.id).is_none());
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn restore_refuses_to_overwrite_a_file_that_came_back() {
let _guard = crate::state_guard("collision");
let path = probe("collision", b"moved away then reappeared");
let mut quarantine = Quarantine::new();
let entry = quarantine.quarantine(&finding_for(&path)).unwrap();
std::fs::write(&path, b"the app re-created itself").unwrap();
let error = quarantine
.restore(&entry.id)
.expect_err("restoring over a live file would lose data");
assert!(error.contains("again"), "{error}");
assert_eq!(std::fs::read(&path).unwrap(), b"the app re-created itself");
quarantine.purge(&entry.id).unwrap();
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_same_id_names_the_same_file_and_bytes() {
let a = new_id(Path::new("/tmp/x"), "aa");
assert_eq!(a, new_id(Path::new("/tmp/x"), "aa"));
assert_ne!(a, new_id(Path::new("/tmp/x"), "bb"));
assert_ne!(a, new_id(Path::new("/tmp/y"), "aa"));
assert_eq!(a.len(), 20);
}
}

View File

@ -0,0 +1,922 @@
//! The two published detectors: a SHA-256 blacklist and a YARA-X rule set.
//!
//! Both are compiled once per scan and shared across workers. The YARA set is
//! built into the binary so a scan works with the network off and before any
//! rule pack has been downloaded, and an external pack can add to it; the pack
//! format and its signature live in [`crate::intel`].
//!
//! What is *not* here matters as much as what is. Apple's XProtect signatures
//! are not redistributed — macOS applies them itself, and squid reports that
//! fact instead of borrowing Apple's authority. The built-in set is therefore
//! small, explicit, and self-contained: the EICAR test file, so "the pipeline
//! works" is testable on any machine, plus a handful of behaviour rules that
//! describe what the scanner can actually see in a startup item or a browser
//! extension. Every rule states the level it can support, and a behaviour rule
//! can only ever support `suspicious`.
use crate::findings::{Confidence, Evidence};
use serde::{Deserialize, Serialize};
use std::path::Path;
/// One compiled YARA rule plus the squid-side metadata YARA itself does not
/// carry: how much weight a match deserves.
pub struct Detector {
pub rules: yara_x::Rules,
/// Rule name → (description, family, level).
pub meta: Vec<RuleMeta>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RuleMeta {
pub name: String,
pub description: String,
pub family: String,
pub level: RuleLevel,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleLevel {
/// A published signature for a named threat: enough to call it confirmed.
Signature,
/// A behaviour or structure pattern: worth a look, never a verdict.
Behaviour,
}
/// The built-in source. Rule metadata is mirrored in `meta()` because YARA's
/// own `meta` block is typed loosely and squid wants the level to be a type.
const BUILTIN_YARA: &str = r#"
import "macho"
import "pe"
rule Eicar_Test_File
{
meta:
description = "The EICAR anti-malware test string"
family = "EICAR-Test-File"
strings:
$a = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" ascii wide
condition:
$a
}
rule ShellPayloadInUserData
{
meta:
description = "Shell commands that pipe a download straight into an interpreter"
family = "behaviour"
strings:
$curl = /curl[ \t]+-s[^\n]{0,80}\|[ \t]*(ba)?sh/ ascii wide
$wget = /wget[ \t]+-q[^\n]{0,80}\|[ \t]*(ba)?sh/ ascii wide
$osascript = "osascript -e" ascii wide
$eval = "eval $(curl" ascii wide
condition:
filesize < 2MB and 2 of them
}
rule LoginItemPointsAtTemp
{
meta:
description = "A launch plist whose program lives in a temporary directory"
family = "behaviour"
strings:
$var = "/var/folders/" ascii wide
$tmp = "/tmp/" ascii wide
$prog1 = "<key>Program</key>" ascii wide
$prog2 = "<key>ProgramArguments</key>" ascii wide
condition:
filesize < 256KB and ($prog1 or $prog2) and ($var or $tmp)
}
rule ExtensionHostsPermission
{
meta:
description = "A browser extension manifest that asks to read every site it visits"
family = "behaviour"
strings:
$host = "\"<all_urls>\"" ascii wide
$tabs = "\"tabs\"" ascii wide
$debug = "\"debugger\"" ascii wide
$name = "\"manifest_version\"" ascii wide
condition:
filesize < 64KB and $name and $host and ($tabs or $debug)
}
rule ScriptedOfficeMacro
{
meta:
description = "A document carrying an auto-run macro that starts a program"
family = "behaviour"
strings:
$a = "AutoOpen" ascii wide
$b = "AutoExec" ascii wide
$c = "Shell(" ascii wide
$d = "MacScript" ascii wide
condition:
filesize < 32MB and 3 of them
}
rule MachoDylibFromWritablePath
{
meta:
description = "A binary that loads a library from a folder the user can rewrite"
family = "behaviour"
condition:
macho.number_of_segments > 0
and for any d in macho.dylibs : (
d.name matches /^\/(Users|tmp|private\/tmp|var\/folders)\//
)
}
rule PeWithoutVersionInfo
{
meta:
description = "A Windows binary that names nobody in its version resource"
family = "behaviour"
condition:
pe.number_of_sections > 1 and pe.number_of_version_infos == 0
}
rule PeUnnamedSection
{
meta:
description = "A Windows binary with a section packers leave nameless"
family = "behaviour"
condition:
pe.number_of_sections > 0
and for any s in pe.sections : ( s.name == "" )
}
"#;
/// The metadata table for the source above. A rule that matches is only as
/// strong as the level stated here, and behaviour rules can never reach
/// `confirmed` no matter how many of them fire at once.
pub fn builtin_meta() -> Vec<RuleMeta> {
let behaviour = |name: &str, description: &str| RuleMeta {
name: name.into(),
description: description.into(),
family: "behaviour".into(),
level: RuleLevel::Behaviour,
};
vec![
RuleMeta {
name: "Eicar_Test_File".into(),
description: "The standard anti-malware test string".into(),
family: "EICAR-Test-File".into(),
level: RuleLevel::Signature,
},
behaviour(
"ShellPayloadInUserData",
"Shell commands that pipe a download straight into an interpreter",
),
behaviour(
"LoginItemPointsAtTemp",
"A launch plist whose program lives in a temporary directory",
),
behaviour(
"ExtensionHostsPermission",
"A browser extension manifest that asks to read every site it visits",
),
behaviour(
"ScriptedOfficeMacro",
"A document carrying an auto-run macro that starts a program",
),
behaviour(
"MachoDylibFromWritablePath",
"A binary that loads a library from a folder the user can rewrite",
),
behaviour(
"PeWithoutVersionInfo",
"A Windows binary that names nobody in its version resource",
),
behaviour(
"PeUnnamedSection",
"A Windows binary with a section packers leave nameless",
),
]
}
impl Detector {
/// Compile the built-in rules. A failure here is a build bug, not a runtime
/// condition, so it surfaces as an error the caller reports rather than a
/// silently empty detector.
pub fn builtin() -> Result<Detector, String> {
Self::from_source(BUILTIN_YARA, builtin_meta())
}
/// Built-in rules plus an external pack. If the pack fails to compile, the
/// caller decides whether to fall back; this function does not hide that.
pub fn with_extra(extra_sources: &[(String, Vec<RuleMeta>)]) -> Result<Detector, String> {
let mut source = String::from(BUILTIN_YARA);
let mut meta = builtin_meta();
for (text, pack_meta) in extra_sources {
source.push('\n');
source.push_str(text);
meta.extend(pack_meta.iter().cloned());
}
Self::from_source(&source, meta)
}
/// Compile a downloaded pack against the metadata the pack itself declares.
/// Used by [`crate::intel`] as the acceptance test before a pack becomes
/// `current`.
pub fn from_source_for_pack(source: &str, meta: &[RuleMeta]) -> Result<Detector, String> {
Self::from_source(source, meta.to_vec())
}
fn from_source(source: &str, meta: Vec<RuleMeta>) -> Result<Detector, String> {
let rules = yara_x::compile(source).map_err(|error| format!("{error}"))?;
Ok(Detector { rules, meta })
}
pub fn rule_count(&self) -> usize {
self.rules.iter().count()
}
/// Scan one buffer. Returns evidence for every rule that fired, at the
/// level its metadata allows.
pub fn scan_buffer(&self, data: &[u8]) -> Vec<Evidence> {
let mut scanner = yara_x::Scanner::new(&self.rules);
let Ok(results) = scanner.scan(data) else {
return Vec::new();
};
results
.matching_rules()
.filter_map(|matched| {
let name = matched.identifier();
let meta = self.meta.iter().find(|entry| entry.name == name)?;
Some(Evidence::YaraRule {
rule: name.to_string(),
description: meta.description.clone(),
family: meta.family.clone(),
})
})
.collect()
}
/// Level a matching rule can support. Rules with no metadata entry are
/// treated as behaviour, which is the weaker answer.
pub fn level_of(&self, rule: &str) -> RuleLevel {
self.meta
.iter()
.find(|entry| entry.name == rule)
.map(|entry| entry.level)
.unwrap_or(RuleLevel::Behaviour)
}
pub fn confidence_for(&self, evidence: &[Evidence]) -> Confidence {
evidence
.iter()
.filter_map(|item| match item {
Evidence::YaraRule { rule, .. } => Some(self.level_of(rule)),
_ => None,
})
.map(|level| match level {
RuleLevel::Signature => Confidence::Confirmed,
RuleLevel::Behaviour => Confidence::Suspicious,
})
.max()
.unwrap_or(Confidence::Advisory)
}
/// Scan one file. Large files are mapped when possible, so a 4 GB disk
/// image in Downloads does not become a 4 GB allocation, and a read failure
/// is an empty answer rather than an error: unreadable files are already
/// reported through coverage.
pub fn scan_file(&self, path: &Path) -> Vec<Evidence> {
let Ok(metadata) = std::fs::symlink_metadata(path) else {
return Vec::new();
};
if !metadata.is_file() {
return Vec::new();
}
// YARA needs the bytes in memory. Above this, only the head and tail
// are offered, and the finding says nothing about the middle.
const FULL_LIMIT: u64 = 64 * 1024 * 1024;
const WINDOW: usize = 4 * 1024 * 1024;
let read = |offset: u64, length: usize| -> Vec<u8> {
use std::io::{Read, Seek, SeekFrom};
let mut file = match std::fs::File::open(path) {
Ok(file) => file,
Err(_) => return Vec::new(),
};
if file.seek(SeekFrom::Start(offset)).is_err() {
return Vec::new();
}
let mut buffer = Vec::with_capacity(length.min(16 * 1024 * 1024));
let _ = file.by_ref().take(length as u64).read_to_end(&mut buffer);
buffer
};
if metadata.len() <= FULL_LIMIT {
return self.scan_buffer(&read(0, metadata.len() as usize));
}
let mut evidence = self.scan_buffer(&read(0, WINDOW));
let tail = metadata.len().saturating_sub(WINDOW as u64);
for item in self.scan_buffer(&read(tail, WINDOW)) {
if !evidence.iter().any(|kept| kept.key() == item.key()) {
evidence.push(item);
}
}
evidence
}
}
/// The SHA-256 blacklist. A hash match is the only detector that can call a
/// file confirmed on its own, because it says "this exact sequence of bytes was
/// published as bad".
#[derive(Clone, Debug, Default)]
pub struct HashIndex {
entries: Vec<DeniedHash>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DeniedHash {
pub sha256: String,
pub threat: String,
#[serde(default)]
pub family: String,
}
impl HashIndex {
/// Built-in list. EICAR is here as well as in the rules, because the test
/// file is how a person verifies that scanning works at all.
pub fn builtin() -> HashIndex {
HashIndex {
entries: vec![
// The test string as published (CRLF), as a text editor would
// save it (LF), and bare. Which terminator survives a download
// depends on the tool that wrote the file, and a test file that
// matches only sometimes is worse than none: it makes a working
// scanner look broken.
DeniedHash {
sha256: "8b3f191819931d1f2cef7289239b5f77c00b079847b9c2636e56854d1e5eff71"
.into(),
threat: "EICAR test file".into(),
family: "EICAR-Test-File".into(),
},
DeniedHash {
sha256: "131f95c51cc819465fa1797f6ccacf9d494aaaff46fa3eac73ae63ffbdfd8267"
.into(),
threat: "EICAR test file".into(),
family: "EICAR-Test-File".into(),
},
DeniedHash {
sha256: "275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f"
.into(),
threat: "EICAR test file".into(),
family: "EICAR-Test-File".into(),
},
],
}
}
pub fn from_entries(entries: Vec<DeniedHash>) -> HashIndex {
HashIndex { entries }
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn lookup(&self, sha256: &str) -> Option<&DeniedHash> {
let needle = sha256.to_ascii_lowercase();
self.entries
.iter()
.find(|entry| entry.sha256.eq_ignore_ascii_case(&needle))
}
pub fn check(&self, sha256: &str) -> Option<Evidence> {
self.lookup(sha256).map(|entry| Evidence::DeniedHash {
sha256: entry.sha256.clone(),
threat: entry.threat.clone(),
})
}
}
/// SHA-256 of a file, streamed. Returns `None` for anything that is not a
/// regular file or cannot be opened.
pub fn sha256_of(path: &Path) -> Option<String> {
use sha2::{Digest, Sha256};
let metadata = std::fs::symlink_metadata(path).ok()?;
if !metadata.is_file() {
return None;
}
let mut file = std::fs::File::open(path).ok()?;
let mut digest = Sha256::new();
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = std::io::Read::read(&mut file, &mut buffer).ok()?;
if read == 0 {
break;
}
digest.update(&buffer[..read]);
}
Some(hex::encode(digest.finalize()))
}
/// The cheap half of the gate: can this name possibly be something that runs?
///
/// Used while walking, where only the path is free. It is deliberately
/// over-inclusive — an extensionless name always passes — because the answer it
/// avoids is expensive, and the file's `stat` data settles it a moment later in
/// [`worth_scanning`].
/// `assume_payload_location` widens the name gate for a scan the user pointed at
/// a folder of their own, where nothing about the location can be assumed.
pub fn plausible_by_name_in(path: &Path, assume_payload_location: bool) -> bool {
let Some(name) = path.file_name() else {
return false;
};
let name = name.to_string_lossy().to_ascii_lowercase();
match name.rsplit_once('.') {
// `thing.dylib`, `com.foo.plist`, and a dotted name whose tail is not an
// extension at all (`v2ray-core`, `a.b.c`) all fall through to the
// extensionless branch, which is the safe direction.
Some((_, extension))
if !extension.contains('.') && EXTENSION_GATED.contains(&extension) =>
{
true
}
Some(_) | None => assume_payload_location || extensionless_may_run(path),
}
}
/// Extensions that are only ever worth a look where a payload is expected.
/// Plists are the launchd configuration itself, and are the single most common
/// place a persistence mechanism is written, so they are judged by name alone.
const EXTENSION_GATED: [&str; 3] = ["plist", "mobileconfig", "crx"];
/// Extensions that mean "this runs" anywhere on the machine.
///
/// PowerShell, batch and HTA are on the list because they are the most common way
/// a Windows machine is actually infected, and they are kilobytes of text each.
/// Not on it: `.js`, `.json`, `.html`, `.lnk`. Those are everywhere — 35,000 files
/// and 1.3 GB in the quick-scan range of an ordinary developer's Mac — and a scan
/// that reads all of them to find the occasional malicious one is a scan nobody
/// runs. A custom scan still sees them, because there the name is not trusted.
const EXECUTABLE_EXTENSIONS: [&str; 23] = [
"dylib", "so", "xpc", "bundle", "exe", "dll", "sys", "ocx", "msi", "appx", "dmg", "pkg", "jar",
"sh", "bash", "command", "scpt", "vbs", "ps1", "psm1", "bat", "cmd", "hta",
];
/// An extensionless name passes the cheap gate only where something extensionless
/// can plausibly live: inside an app bundle's own executable folder, in a
/// launchd directory, or in the folders a browser writes to. Everywhere else the
/// name alone cannot tell a Mach-O from a cache file, and `~/Library` holds
/// hundreds of thousands of the latter.
fn extensionless_may_run(path: &Path) -> bool {
let location = layout_of(path);
matches!(
location,
Layout::AppBundle | Layout::Launchd | Layout::DropZone | Layout::Browser
)
}
/// Whether one file is worth opening, decided from the name and the `stat` data
/// the scan already has.
///
/// The gate has to be cheap *and* structural, because the folders a scan walks
/// hold about a million files and almost none of them can run. An extension list
/// alone fails in both directions: it misses the extensionless Mach-O a
/// dropper leaves in `~/Downloads`, and — taken the other way, as "extensionless
/// might be a binary" — it turns every cache, database and `*.dat` resource in
/// `~/Library` into a candidate, which is what made a full scan read the whole
/// disk before it found anything.
///
/// So the decision is made of three cheap questions, in this order: how big is it
/// (nothing under 64 bytes is a program, and a scan will not read a disk image),
/// can it be executed at all (the mode bits, which is what separates a real
/// binary from a cache file wearing no extension), and does the name or the header
/// say code. The header is read only for the few files the first two questions
/// leave ambiguous.
pub fn worth_scanning(path: &Path, metadata: &std::fs::Metadata) -> bool {
worth_scanning_in(path, metadata, false)
}
/// `assume_payload_location` lifts the location test. A custom scan is asked
/// about the folder the user named, and a file they dropped there may be a
/// Mach-O with no extension, no execute bit and an unhelpful suffix, so the
/// header has to be consulted wherever the file happens to be.
pub fn worth_scanning_in(
path: &Path,
metadata: &std::fs::Metadata,
assume_payload_location: bool,
) -> bool {
if !metadata.is_file() {
return false;
}
let size = metadata.len();
if !(MIN_PROGRAM_BYTES..=SCAN_FILE_LIMIT).contains(&size) {
return false;
}
let extension = path
.extension()
.map(|ext| ext.to_string_lossy().to_ascii_lowercase())
.unwrap_or_default();
if EXECUTABLE_EXTENSIONS.contains(&extension.as_str())
|| EXTENSION_GATED.contains(&extension.as_str())
{
return true;
}
// A folder the user named is asked about by content, not by name: what lands
// there is theirs to ask about, a signature can sit in an ordinary text file,
// and the suffix of a dropper's handiwork argues with itself. The size limits
// above still apply, so the cost is bounded by the folder they chose.
if assume_payload_location {
return true;
}
// Elsewhere, a name that says what it is gets believed. `.svg`, `.class`,
// `.zip` and `.docx` are not programs whatever the mode bits claim, and the
// mode bits routinely *do* claim it: unpacking an archive marks everything
// inside it executable, which is how a scan of a clean machine reported nine
// hundred "unsigned binary" findings that were stylesheets and class files.
if !extension.is_empty() {
return false;
}
// No extension, so the execute bit is the only thing to go on. It separates
// the few thousand launchable extensionless files in a home folder from the
// hundreds of thousands of extensionless cache entries, and costs nothing.
if is_executable(metadata) {
return true;
}
// A browser can hand over a Mach-O with no extension and no execute bit, and
// a dropper may run one through `/bin/sh`. In the folders where that happens
// the first bytes are consulted, and only there.
matches!(layout_of(path), Layout::DropZone | Layout::Browser) && looks_executable(path)
}
/// Below this a file cannot say anything about itself. `#!/bin/sh` plus one line
/// is the shortest payload that can actually run something, and it is a little
/// over twenty bytes; anything smaller is a stub, and the startup inventory
/// reports what points at it anyway.
const MIN_PROGRAM_BYTES: u64 = 24;
/// Where a path sits, in terms a scan cares about. Computed from the string
/// because it is asked for every walked entry and a `metadata` call per entry
/// would cost more than the walk itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layout {
/// Inside `Foo.app/Contents`, at any depth.
AppBundle,
/// A launchd directory, whose plists *are* the persistence mechanism.
Launchd,
/// Where a browser writes what it downloads.
DropZone,
/// A browser's own support folders, where an extension lives.
Browser,
/// Somewhere else entirely.
Other,
}
pub fn layout_of(path: &Path) -> Layout {
let text = path.to_string_lossy().to_ascii_lowercase();
let home = squid_platform::startup::home_dir();
let home = home.to_string_lossy().to_ascii_lowercase();
if text.contains("/contents/") || text.ends_with(".app") {
return Layout::AppBundle;
}
if text.contains("/library/launchagents/")
|| text.contains("/library/launchdaemons/")
|| text.ends_with("/library/launchagents")
|| text.ends_with("/library/launchdaemons")
{
return Layout::Launchd;
}
if text.starts_with(&format!("{home}/downloads"))
|| text.starts_with(&format!("{home}/desktop"))
{
return Layout::DropZone;
}
const BROWSERS: [&str; 6] = [
"/google/chrome",
"/google/chrome canary",
"/microsoft/edge",
"/mozilla/firefox",
"/webkit/",
"/extensions/",
];
if BROWSERS.iter().any(|hint| text.contains(hint)) {
return Layout::Browser;
}
Layout::Other
}
/// The execute bit, for any owner. On Windows the notion does not exist and the
/// read-only flag is the nearest thing, so the name and header carry the decision
/// there instead.
#[cfg(unix)]
fn is_executable(metadata: &std::fs::Metadata) -> bool {
use std::os::unix::fs::PermissionsExt;
metadata.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
fn is_executable(_metadata: &std::fs::Metadata) -> bool {
false
}
/// The largest file a scan will read. Above this a file is reported by its size
/// and left alone: a disk image or a game archive is not what a startup payload
/// looks like, and reading one can cost more than the rest of the scan together.
pub const SCAN_FILE_LIMIT: u64 = 256 * 1024 * 1024;
/// Read the first bytes and decide whether anything could ever execute them.
fn looks_executable(path: &Path) -> bool {
use std::io::Read;
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut head = [0_u8; 8];
let Ok(read) = file.read(&mut head) else {
return false;
};
if read < 4 {
return false;
}
is_macho_magic(&head)
|| head.starts_with(b"MZ")
|| head.starts_with(b"#!")
|| head.starts_with(b"PK")
}
/// Mach-O in either byte order, 32-bit, 64-bit, or as a fat archive.
fn is_macho_magic(head: &[u8]) -> bool {
const MACHOS: [[u8; 4]; 6] = [
[0xcf, 0xfa, 0xed, 0xfe],
[0xce, 0xfa, 0xed, 0xfe],
[0xca, 0xfe, 0xba, 0xbe],
[0xfe, 0xed, 0xfa, 0xcf],
[0xfe, 0xed, 0xfa, 0xce],
[0xbe, 0xba, 0xfe, 0xca],
];
MACHOS.iter().any(|magic| head.starts_with(magic))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn temp_file(name: &str, bytes: &[u8]) -> std::path::PathBuf {
let path = std::env::temp_dir().join(format!("squid-guard-{name}"));
let mut file = std::fs::File::create(&path).expect("temp file");
file.write_all(bytes).expect("write temp file");
path
}
const EICAR: &str = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*\r\n";
#[test]
fn the_builtin_ruleset_compiles() {
let detector = Detector::builtin().expect("built-in rules must compile");
assert_eq!(detector.rule_count(), builtin_meta().len());
for entry in builtin_meta() {
assert!(
detector
.rules
.iter()
.any(|rule| rule.identifier() == entry.name),
"{} is declared in metadata but not compiled",
entry.name
);
}
}
#[test]
fn eicar_is_found_by_both_detectors() {
let detector = Detector::builtin().unwrap();
let path = temp_file("eicar", EICAR.as_bytes());
let evidence = detector.scan_file(&path);
assert!(
evidence
.iter()
.any(|item| item.key() == "yara:Eicar_Test_File"),
"the YARA rule did not fire: {evidence:?}"
);
let hash = sha256_of(&path).expect("hash");
let index = HashIndex::builtin();
let denied = index
.check(&hash)
.expect("the hash blacklist should know EICAR");
assert!(matches!(denied, Evidence::DeniedHash { .. }));
std::fs::remove_file(path).ok();
}
#[test]
fn a_signature_rule_is_confirmed_and_a_behaviour_rule_is_not() {
let detector = Detector::builtin().unwrap();
assert_eq!(detector.level_of("Eicar_Test_File"), RuleLevel::Signature);
assert_eq!(
detector.level_of("ShellPayloadInUserData"),
RuleLevel::Behaviour
);
assert_eq!(
detector.confidence_for(&[Evidence::YaraRule {
rule: "Eicar_Test_File".into(),
description: String::new(),
family: String::new(),
}]),
Confidence::Confirmed
);
assert_eq!(
detector.confidence_for(&[Evidence::YaraRule {
rule: "ShellPayloadInUserData".into(),
description: String::new(),
family: String::new(),
}]),
Confidence::Suspicious
);
// A rule nobody described is assumed to be the weak kind.
assert_eq!(detector.level_of("Made_Up"), RuleLevel::Behaviour);
}
#[test]
fn behaviour_rule_needs_evidence_not_a_single_string() {
let detector = Detector::builtin().unwrap();
let path = temp_file(
"pipe-sh",
b"#!/bin/sh\ncurl -sS https://example.test/install | sh\nwget -qO- https://example.test/x | bash\n",
);
let evidence = detector.scan_file(&path);
assert!(
evidence
.iter()
.any(|item| item.key() == "yara:ShellPayloadInUserData"),
"two piped-shell lines should fire: {evidence:?}"
);
// One line alone is how documentation and install instructions read.
let quiet = temp_file(
"pipe-sh-quiet",
b"curl -sS https://example.test/install | sh\n",
);
assert!(detector.scan_file(&quiet).is_empty());
std::fs::remove_file(path).ok();
std::fs::remove_file(quiet).ok();
}
#[test]
fn a_clean_binary_reports_nothing() {
let detector = Detector::builtin().unwrap();
let path = temp_file("clean", b"\x7fELF this file is deliberately uninteresting");
assert!(detector.scan_file(&path).is_empty());
std::fs::remove_file(path).ok();
}
#[test]
fn hashing_skips_directories_and_refusals() {
assert!(sha256_of(std::path::Path::new("/")).is_none());
assert!(sha256_of(std::path::Path::new("/definitely/not/here")).is_none());
}
#[test]
fn only_executable_shaped_files_are_worth_reading() {
// The gate is decided from real `stat` data, so the fixture has to be
// real files: a cache file and a binary are the same name shape and
// differ only in their mode bits.
let dir = std::env::temp_dir().join("squid-gate");
std::fs::create_dir_all(&dir).expect("temp dir");
let made = |name: &str, executable: bool| -> std::path::PathBuf {
let path = dir.join(name);
std::fs::write(&path, [0x90_u8; 512]).expect("write");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = if executable { 0o755 } else { 0o644 };
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
.expect("mode");
}
#[cfg(not(unix))]
let _ = executable;
path
};
let keep = |name: &str, executable: bool| {
let path = made(name, executable);
let metadata = std::fs::metadata(&path).expect("metadata");
let kept = worth_scanning(&path, &metadata);
std::fs::remove_file(&path).ok();
kept
};
let keep_size = |name: &str, executable: bool, bytes: usize| {
let path = dir.join(name);
std::fs::write(&path, vec![0x90_u8; bytes]).expect("write");
let metadata = std::fs::metadata(&path).expect("metadata");
let kept = worth_scanning(&path, &metadata);
std::fs::remove_file(&path).ok();
let _ = executable;
kept
};
assert!(keep("install.sh", false), "a script is a payload");
assert!(keep("thing.dylib", false), "a library is a payload");
assert!(
keep("com.tester.agent.plist", false),
"an agent is persistence"
);
assert!(!keep("notes.txt", false), "a text file is not a program");
assert!(!keep("photo.jpg", false), "an image is not a program");
assert!(
!keep_size("stub", false, 8),
"under the floor a file cannot say anything about itself"
);
// The execute bit is a POSIX notion; Windows has no equivalent, which is
// why the name and the header carry the decision there instead.
if cfg!(unix) {
assert!(keep("runner", true), "an extensionless binary is a payload");
assert!(
!keep("runner-copy", false),
"an extensionless file nobody can execute is data"
);
// Unpacking an archive marks everything inside it executable, so on a
// machine with a few downloaded source trees the mode bit alone reports
// hundreds of "unsigned binary" findings that are stylesheets. A name
// that says what the file is beats a mode bit that does not.
assert!(
!keep("notes.txt", true),
"an executable text file is still a text file"
);
assert!(
!keep("styles.scss", true),
"the exec bit does not turn a stylesheet into a payload"
);
}
std::fs::remove_dir(&dir).ok();
}
#[test]
fn a_folder_the_user_named_is_judged_by_content_not_by_name() {
// A signature can live in an ordinary text file, and the suffix of a
// dropper's handiwork argues with itself, so a scan pointed at one folder
// asks about anything large enough to hold a payload. The same file found
// while walking `~/Library` is taken at its word.
let path = temp_file("payload", b"eicar-shaped text that a rule can match");
let metadata = std::fs::metadata(&path).expect("metadata");
assert!(
worth_scanning_in(&path, &metadata, true),
"inside a folder the user named, the name does not decide"
);
assert!(
!worth_scanning(&path, &metadata),
"the same file elsewhere is a text file, and a scan says so"
);
std::fs::remove_file(path).ok();
}
#[test]
fn the_layouts_a_quick_scan_trusts_are_the_ones_that_can_run() {
assert_eq!(
layout_of(std::path::Path::new(
"/Applications/Thing.app/Contents/MacOS/Thing"
)),
Layout::AppBundle
);
assert_eq!(
layout_of(std::path::Path::new("/Library/LaunchAgents/x.plist")),
Layout::Launchd
);
assert_eq!(
layout_of(std::path::Path::new("/Applications/Other.txt")),
Layout::Other,
"/Applications on its own is not a bundle"
);
assert!(plausible_by_name_in(
std::path::Path::new("/a/b/com.tester.agent.plist"),
false
));
assert!(!plausible_by_name_in(
std::path::Path::new("/Users/tester/Documents/notes.txt"),
false
));
}
#[test]
fn an_extra_pack_adds_rules_without_losing_the_builtin_ones() {
let extra = vec![(
"rule PackProbe { strings: $a = \"pack-marker\" condition: $a }".to_string(),
vec![RuleMeta {
name: "PackProbe".into(),
description: "from the pack".into(),
family: "pack".into(),
level: RuleLevel::Signature,
}],
)];
let detector = Detector::with_extra(&extra).expect("the pack should compile");
assert_eq!(detector.rule_count(), builtin_meta().len() + 1);
assert_eq!(detector.level_of("PackProbe"), RuleLevel::Signature);
assert!(detector
.scan_buffer(b"prefix pack-marker suffix")
.iter()
.any(|item| item.key() == "yara:PackProbe"));
}
#[test]
fn a_broken_pack_is_reported_not_swallowed() {
let broken = vec![("rule {{{ not yara".to_string(), Vec::new())];
assert!(Detector::with_extra(&broken).is_err());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,686 @@
//! Two kinds of memory, both on disk, neither in a database.
//!
//! [`ScanCache`] remembers the verdict for a file identity — path, size,
//! modification time and file id — so a second scan does not re-hash a file that
//! has not moved. Identity rather than content sampling, because the whole point
//! is to be able to say "this exact file, unchanged" without reading it.
//!
//! [`Store`] keeps the scan the user is looking at plus the recent-activity list
//! the Security page shows. Findings live here precisely so quarantine can take
//! an id: the frontend never gets to name a path, and a stale id is an error
//! rather than a surprise move.
//!
//! Both files are bounded. A cleaner that grows its own state forever is its own
//! kind of junk, so the cache drops its oldest half when it doubles past the
//! limit, and the activity list keeps a fixed number of entries.
use crate::findings::{Confidence, Evidence, Finding};
use serde::{Deserialize, Serialize};
use squid_core::paths;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// The three facts that make a file the same file: where it is, how big it is,
/// and when it last changed. Anything else would mean reading it again.
pub struct FileIdentity {
pub path: PathBuf,
pub size: u64,
pub modified_ms: u64,
pub file_id: u64,
}
impl FileIdentity {
pub fn of(path: &Path, metadata: &std::fs::Metadata) -> FileIdentity {
FileIdentity {
path: path.to_path_buf(),
size: metadata.len(),
modified_ms: modified_ms(metadata),
file_id: file_id(metadata),
}
}
}
/// A reusable answer for one file identity.
#[derive(Clone)]
pub struct Hit {
pub evidence: Vec<Evidence>,
pub sha256: Option<String>,
pub signed: bool,
}
/// One remembered verdict, and when a scan last asked for it.
///
/// `path` is stored as the canonical key rather than the original spelling, which
/// is what lets the map below be keyed by it. Nothing displays that field: it is
/// there so a person opening `verdicts.json` can see which file a verdict is about.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct CachedVerdict {
path: String,
size: u64,
modified_ms: u64,
#[serde(default)]
file_id: u64,
evidence: Vec<Evidence>,
sha256: Option<String>,
signed: bool,
/// Scan counter, not a clock: only the order matters, and a clock would make a
/// test depend on how fast the machine is.
#[serde(default)]
used: u64,
}
/// The file on disk. A list, so the format stays readable and diffable, even
/// though the cache is a map in memory.
#[derive(Default, Serialize, Deserialize)]
struct CacheFile {
version: u32,
entries: Vec<CachedVerdict>,
}
/// Verdicts keyed by file identity rather than by path alone: a file that was
/// replaced between scans has a different mtime, and reusing the old answer would
/// report the wrong bytes.
///
/// The map is the point. A scan offers thousands of files, and looking each one up
/// in a list costs one path comparison per cached entry per file — which is
/// quadratic, and was measured at several minutes of CPU on a quick scan whose
/// entire budget is a few seconds. Trimming needs an ordering, so each entry keeps
/// the scan number it was last used at and the list is only sorted when it is
/// written.
pub struct ScanCache {
entries: HashMap<String, CachedVerdict>,
/// Counts lookups and stores, to order the cache by recency without a clock.
clock: u64,
dirty: bool,
loaded: bool,
misses: usize,
}
impl Default for ScanCache {
fn default() -> Self {
Self::new()
}
}
impl ScanCache {
pub fn new() -> ScanCache {
ScanCache {
entries: HashMap::new(),
clock: 0,
dirty: false,
loaded: false,
misses: 0,
}
}
fn path() -> PathBuf {
cache_dir().join("verdicts.json")
}
fn load(&mut self) {
if self.loaded {
return;
}
self.entries = std::fs::read(Self::path())
.ok()
.and_then(|bytes| serde_json::from_slice::<CacheFile>(&bytes).ok())
.map(|file| {
file.entries
.into_iter()
.map(|entry| (entry.path.clone(), entry))
.collect()
})
.unwrap_or_default();
self.loaded = true;
}
/// The remembered verdict for a file that has not changed since.
pub fn verdict(&mut self, identity: &FileIdentity) -> Option<Hit> {
self.load();
self.clock += 1;
let used = self.clock;
let found = self
.entries
.get_mut(&paths::canonical_key(&identity.path))?;
if found.size != identity.size
|| found.modified_ms != identity.modified_ms
|| found.file_id != identity.file_id
{
// The same path holding different bytes. Re-hash it: "you already
// looked at this" is the one answer a scan may not give wrongly.
self.misses += 1;
return None;
}
found.used = used;
Some(Hit {
evidence: found.evidence.clone(),
sha256: found.sha256.clone(),
signed: found.signed,
})
}
/// Remember what this scan decided. Called for every file a scan looked at, so
/// a re-scan of an unchanged tree is a sequence of hits rather than a re-read.
pub fn remember(&mut self, identity: &FileIdentity, verdict: Hit) {
self.load();
self.clock += 1;
let key = paths::canonical_key(&identity.path);
// One row per path: a re-scan replaces the answer rather than leaving the
// file with two verdicts, one of which is stale and might win.
self.entries.insert(
key.clone(),
CachedVerdict {
path: key,
size: identity.size,
modified_ms: identity.modified_ms,
file_id: identity.file_id,
evidence: verdict.evidence,
sha256: verdict.sha256,
signed: verdict.signed,
used: self.clock,
},
);
self.dirty = true;
}
/// Write the cache, trimming the least recently used half when it outgrows its
/// budget. A cleaner that grows its own state forever is its own kind of junk.
pub fn commit(&mut self) {
self.load();
if !self.dirty {
return;
}
const LIMIT: usize = 40_000;
let mut entries: Vec<CachedVerdict> = self.entries.values().cloned().collect();
entries.sort_by_key(|entry| entry.used);
if entries.len() > LIMIT * 2 {
let drop = entries.len() - LIMIT;
entries.drain(0..drop);
}
let file = CacheFile {
version: 1,
entries,
};
if let Some(parent) = Self::path().parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(bytes) = serde_json::to_vec(&file) {
let _ = std::fs::write(Self::path(), bytes);
}
self.dirty = false;
}
pub fn entries(&self) -> usize {
self.entries.len()
}
pub fn misses(&self) -> usize {
self.misses
}
/// Forget everything. Offered when the rule pack changes, because a verdict
/// recorded by the old rules is not an answer the new rules gave.
pub fn invalidate(&mut self) {
self.entries.clear();
self.dirty = true;
self.commit();
}
}
/// The scan the user is looking at, plus the activity list.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivityEntry {
pub at_ms: u64,
pub kind: String,
pub detail: String,
pub path: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredScan {
pub scan_id: String,
pub mode: String,
pub finished_ms: u64,
pub elapsed_ms: u64,
pub cancelled: bool,
pub examined: usize,
pub cached: usize,
pub skipped: usize,
pub coverage_complete: bool,
pub gaps: Vec<(String, String)>,
pub findings: Vec<Finding>,
}
impl StoredScan {
/// How many findings at each level still need a decision: not ignored, and
/// not already sitting in the quarantine.
///
/// This is the definition the badge, the tray line and the page header all
/// count, so it is one function on the record itself. When it was written
/// twice — once here, once in the desktop layer — the tray and the Security
/// page could disagree after a restart while both looked correct.
pub fn counts(&self) -> (usize, usize, usize) {
let actionable = |level: Confidence| {
self.findings
.iter()
.filter(|finding| {
finding.confidence == level && !finding.ignored && !finding.quarantined
})
.count()
};
(
actionable(Confidence::Confirmed),
actionable(Confidence::Suspicious),
actionable(Confidence::Advisory),
)
}
/// Freeze one finished scan for storage. The coverage is kept as a boolean
/// plus the list of gaps, because that is everything the next session needs
/// in order to refuse to say a plain "clean".
pub fn record(report: &crate::scan::ScanReport) -> StoredScan {
StoredScan {
scan_id: report.scan_id.clone(),
mode: report.mode.as_str().to_string(),
finished_ms: report.finished_ms,
elapsed_ms: report.elapsed_ms,
cancelled: report.cancelled,
examined: report.examined,
cached: report.cached,
skipped: report.skipped,
coverage_complete: report.coverage.complete(),
gaps: report
.coverage
.gaps()
.into_iter()
.map(|gap| {
(
gap.display_path.clone(),
gap.reason
.clone()
.unwrap_or_else(|| gap.outcome.as_str().into()),
)
})
.collect(),
findings: report.findings.clone(),
}
}
}
/// In-memory state for one app session, persisted where it helps the next one.
pub struct Store {
last_scan: Option<StoredScan>,
activity: Vec<ActivityEntry>,
}
impl Default for Store {
fn default() -> Self {
Self::new()
}
}
impl Store {
pub fn new() -> Store {
let activity = read_activity();
Store {
last_scan: read_last_scan(),
activity,
}
}
pub fn set_scan(&mut self, scan: StoredScan) {
write_last_scan(&scan);
self.last_scan = Some(scan);
}
pub fn scan(&self) -> Option<&StoredScan> {
self.last_scan.as_ref()
}
/// Apply one change to the stored scan and write it back. Findings are
/// mutable state — quarantined, restored, ignored — and the file is the
/// record of that state, so every mutation goes through here rather than
/// editing `self.last_scan` and hoping something saves it later.
pub fn update_scan(&mut self, change: impl FnOnce(&mut StoredScan)) {
let Some(scan) = self.last_scan.as_mut() else {
return;
};
change(scan);
write_last_scan(scan);
}
/// The finding behind an id. This is the only way a caller reaches a path in
/// the quarantine path, and it fails loudly when the id is unknown.
pub fn finding(&self, id: &str) -> Option<&Finding> {
self.last_scan
.as_ref()
.and_then(|scan| scan.findings.iter().find(|finding| finding.id == id))
}
pub fn finding_mut(&mut self, id: &str) -> Option<&mut Finding> {
self.last_scan
.as_mut()
.and_then(|scan| scan.findings.iter_mut().find(|finding| finding.id == id))
}
pub fn note(&mut self, kind: &str, detail: impl Into<String>, path: Option<PathBuf>) {
self.activity.push(ActivityEntry {
at_ms: now_ms(),
kind: kind.into(),
detail: detail.into(),
path: path.map(|path| paths::pretty(&path)),
});
const KEEP: usize = 200;
if self.activity.len() > KEEP {
let drop = self.activity.len() - KEEP;
self.activity.drain(0..drop);
}
write_activity(&self.activity);
}
pub fn activity(&self) -> &[ActivityEntry] {
&self.activity
}
/// Most recent first, which is how a log is read.
pub fn recent_activity(&self, limit: usize) -> Vec<ActivityEntry> {
self.activity.iter().rev().take(limit).cloned().collect()
}
/// Fold the quarantine ledger into the displayed findings, so a file that
/// has been dealt with stops being offered as actionable.
pub fn mark_quarantined(&mut self, quarantined: &[(String, PathBuf)]) {
let Some(scan) = self.last_scan.as_mut() else {
return;
};
for finding in &mut scan.findings {
if let Some(path) = finding.path.as_ref() {
if quarantined
.iter()
.any(|(_, stored)| paths::same_path(stored, path))
{
finding.quarantined = true;
}
}
}
}
pub fn counts(&self) -> (usize, usize, usize) {
self.last_scan
.as_ref()
.map(StoredScan::counts)
.unwrap_or((0, 0, 0))
}
}
fn cache_dir() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("cache")
}
fn activity_path() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("activity.json")
}
/// The last finished scan, kept so a finding id outlives the process that
/// produced it. `squid guard scan` and `squid guard quarantine` are two runs of
/// one conversation, and the Security page reopening after a restart should say
/// what the last scan found rather than "never scanned".
fn last_scan_path() -> PathBuf {
squid_core::Settings::state_dir()
.join("security")
.join("last-scan.json")
}
fn read_last_scan() -> Option<StoredScan> {
std::fs::read_to_string(last_scan_path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
}
fn write_last_scan(scan: &StoredScan) {
let path = last_scan_path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(text) = serde_json::to_string_pretty(scan) {
let _ = std::fs::write(path, text);
}
}
fn read_activity() -> Vec<ActivityEntry> {
std::fs::read_to_string(activity_path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
fn write_activity(entries: &[ActivityEntry]) {
let path = activity_path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(text) = serde_json::to_string_pretty(entries) {
let _ = std::fs::write(path, text);
}
}
fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
/// inode on unix, file index on Windows; the part of the identity that survives a
/// rename and catches a replacement in place.
fn file_id(metadata: &std::fs::Metadata) -> u64 {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
metadata.ino()
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
metadata.creation_time()
}
#[cfg(not(any(unix, windows)))]
{
let _ = metadata;
0
}
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn state_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("squid-store-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn probe(tag: &str, bytes: &[u8]) -> PathBuf {
let dir = state_dir(tag);
let path = dir.join("payload");
let mut file = std::fs::File::create(&path).unwrap();
file.write_all(bytes).unwrap();
path
}
fn hit(evidence: &[Evidence], sha256: Option<&str>, signed: bool) -> Hit {
Hit {
evidence: evidence.to_vec(),
sha256: sha256.map(str::to_string),
signed,
}
}
fn evidence() -> Vec<Evidence> {
vec![Evidence::DeniedHash {
sha256: "a".repeat(64),
threat: "probe".into(),
}]
}
#[test]
fn a_verdict_is_reused_only_while_the_file_is_unchanged() {
let path = probe("reuse", b"the bytes that were judged");
let metadata = std::fs::metadata(&path).unwrap();
let identity = FileIdentity::of(&path, &metadata);
let mut cache = ScanCache::new();
assert!(
cache.verdict(&identity).is_none(),
"an empty cache cannot know this file"
);
cache.remember(&identity, hit(&evidence(), None, false));
let stored = cache.verdict(&identity).expect("the file has not changed");
assert_eq!(stored.evidence.len(), 1);
// Different size, different answer: the file was replaced.
let bigger = FileIdentity {
size: identity.size + 1,
..identity
};
assert!(cache.verdict(&bigger).is_none());
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn a_replaced_file_loses_its_cached_verdict() {
let path = probe("replaced", b"first content");
let before = std::fs::metadata(&path).unwrap();
let mut cache = ScanCache::new();
cache.remember(
&FileIdentity::of(&path, &before),
hit(&evidence(), None, false),
);
std::fs::write(&path, b"a longer second content").unwrap();
let after = std::fs::metadata(&path).unwrap();
assert_ne!(before.len(), after.len());
assert!(
cache.verdict(&FileIdentity::of(&path, &after)).is_none(),
"the new bytes must not inherit the old verdict"
);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn the_cache_survives_a_restart_and_can_be_invalidated() {
let _guard = crate::state_guard("cache-persist");
let path = probe("persist", b"remembered across sessions");
let metadata = std::fs::metadata(&path).unwrap();
let identity = FileIdentity::of(&path, &metadata);
{
let mut cache = ScanCache::new();
cache.remember(&identity, hit(&evidence(), Some("beef"), false));
cache.commit();
}
let mut reopened = ScanCache::new();
let stored = reopened.verdict(&identity).expect("the cache is on disk");
assert_eq!(stored.sha256.as_deref(), Some("beef"));
reopened.invalidate();
assert!(
ScanCache::new().verdict(&identity).is_none(),
"invalidating must forget everything, because the rules changed"
);
std::fs::remove_dir_all(path.parent().unwrap()).ok();
}
#[test]
fn findings_are_reachable_by_id_and_only_by_id() {
let scan = StoredScan {
scan_id: "s1".into(),
findings: vec![
finding("s1#0", Confidence::Confirmed, "/tmp/one"),
finding("s1#1", Confidence::Suspicious, "/tmp/two"),
],
..Default::default()
};
let mut store = Store::new();
store.set_scan(scan);
assert_eq!(
store.finding("s1#1").unwrap().confidence,
Confidence::Suspicious
);
assert!(store.finding("/tmp/one").is_none(), "a path is not an id");
assert!(store.finding("s1#9").is_none());
let (confirmed, suspicious, _) = store.counts();
assert_eq!((confirmed, suspicious), (1, 1));
}
#[test]
fn quarantining_a_file_stops_it_being_offered_again() {
let mut scan = StoredScan {
scan_id: "s2".into(),
findings: vec![finding("s2#0", Confidence::Confirmed, "/tmp/x")],
..Default::default()
};
scan.findings[0].path = Some(PathBuf::from("/tmp/x"));
let mut store = Store::new();
store.set_scan(scan);
assert_eq!(store.counts().0, 1);
store.mark_quarantined(&[("q1".into(), PathBuf::from("/tmp/x"))]);
assert_eq!(
store.counts().0,
0,
"a dealt-with finding is not outstanding"
);
assert!(store.finding("s2#0").unwrap().quarantined);
}
#[test]
fn the_activity_list_is_bounded_and_newest_first() {
let _guard = crate::state_guard("activity");
let mut store = Store::new();
for index in 0..250 {
store.note("scan", format!("run {index}"), None);
}
assert!(store.activity().len() <= 200, "the log must stop growing");
let recent = store.recent_activity(3);
assert_eq!(recent.len(), 3);
assert_eq!(recent[0].detail, "run 249", "newest first");
assert!(
activity_path().is_file(),
"the log is written for the next session"
);
}
fn finding(id: &str, confidence: Confidence, path: &str) -> Finding {
Finding {
id: id.into(),
confidence,
path: Some(PathBuf::from(path)),
display_path: Some(path.into()),
name: "probe".into(),
title: "probe".into(),
description: String::new(),
evidence: evidence(),
size: 1,
sha256: None,
signed: false,
publisher: None,
found_at_ms: 0,
quarantined: false,
ignored: false,
}
}
}

View File

@ -15,12 +15,31 @@ walkdir.workspace = true
plist.workspace = true plist.workspace = true
rayon.workspace = true rayon.workspace = true
unicode-width.workspace = true unicode-width.workspace = true
sysinfo.workspace = true
serde_json.workspace = true
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc.workspace = true libc.workspace = true
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
winreg = "0.52" winreg = "0.52"
sysinfo.workspace = true windows-sys = { version = "0.59", features = [
"Win32_System_Console",
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_Security",
"Win32_Security_Cryptography",
"Win32_Security_WinTrust",
"Win32_System_Threading",
"Win32_System_Registry",
"Win32_Globalization",
"Win32_UI_WindowsAndMessaging",
"Win32_UI_Shell",
"Win32_Graphics_Gdi",
"Win32_System_SystemInformation",
"Win32_System_IO",
] }
[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies]
file_icon_provider = "1.0.2"
png = "0.17" 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"] }

View File

@ -111,6 +111,7 @@ pub fn app_from_bundle(
name, name,
bundle_id: bundle.bundle_id.clone(), bundle_id: bundle.bundle_id.clone(),
path: path.clone(), path: path.clone(),
icon_source: Some(path.clone()),
version: bundle version: bundle
.short_version .short_version
.clone() .clone()
@ -143,6 +144,32 @@ pub fn app_from_bundle(
Some(app) Some(app)
} }
/// Render an application's system icon as PNG bytes.
///
/// macOS and Windows let the file manager do the work, so the result is the
/// same icon Finder or Explorer shows, including HiDPI-safe source artwork.
/// Linux has no equivalent without a GTK dependency; the desktop falls back to
/// the app's initial.
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub fn icon_png(app: &AppInfo, size: u16) -> Option<Vec<u8>> {
let source = app.icon_source.as_ref()?;
let icon = file_icon_provider::get_file_icon(source, size).ok()?;
let mut output = Vec::new();
{
let mut encoder = png::Encoder::new(&mut output, icon.width, icon.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().ok()?;
writer.write_image_data(&icon.pixels).ok()?;
}
Some(output)
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub fn icon_png(_app: &AppInfo, _size: u16) -> Option<Vec<u8>> {
None
}
/// Match "is this app running" against the process executable list. /// Match "is this app running" against the process executable list.
pub fn is_running(dir_name: &str, executable: Option<&str>, running: &[String]) -> bool { pub fn is_running(dir_name: &str, executable: Option<&str>, running: &[String]) -> bool {
let mut candidates: Vec<String> = Vec::with_capacity(3); let mut candidates: Vec<String> = Vec::with_capacity(3);
@ -168,3 +195,20 @@ pub fn stem_lower(path: &Path) -> String {
.map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase()) .map(|n| n.to_string_lossy().trim_end_matches(".app").to_lowercase())
.unwrap_or_default() .unwrap_or_default()
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn a_system_icon_is_encoded_as_png() {
let app = AppInfo {
name: "Squid".into(),
icon_source: std::env::current_exe().ok(),
..Default::default()
};
let png = icon_png(&app, 32).expect("the running executable has a system icon");
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
}
}

View File

@ -16,6 +16,10 @@ pub mod currency;
pub mod leftovers; pub mod leftovers;
pub mod permissions; pub mod permissions;
pub mod process; pub mod process;
pub mod process_table;
pub mod protection;
pub mod startup;
pub mod trust;
#[cfg(unix)] #[cfg(unix)]
pub mod volumes; pub mod volumes;
@ -105,6 +109,10 @@ pub trait Platform: Send + Sync {
fn display_name(&self) -> String; fn display_name(&self) -> String;
fn os_version(&self) -> String; fn os_version(&self) -> String;
fn hardware_model(&self) -> String; fn hardware_model(&self) -> String;
/// Display adapter(s), when the platform exposes a stable name.
fn graphics_adapter(&self) -> String {
String::new()
}
/// Directories to scan for installed applications. /// Directories to scan for installed applications.
fn app_sources(&self) -> Vec<AppSource>; fn app_sources(&self) -> Vec<AppSource>;

View File

@ -112,6 +112,29 @@ impl Platform for Linux {
.to_string() .to_string()
} }
fn graphics_adapter(&self) -> String {
run("lspci", &[])
.map(|text| {
text.lines()
.filter(|line| {
line.contains("VGA compatible controller")
|| line.contains("3D controller")
|| line.contains("Display controller")
})
.filter_map(|line| line.split_once(": ").map(|(_, value)| value.trim()))
.map(|value| {
value
.split_once(": ")
.map(|(_, name)| name.trim())
.unwrap_or(value)
.to_string()
})
.collect::<Vec<_>>()
.join(" · ")
})
.unwrap_or_default()
}
fn app_sources(&self) -> Vec<AppSource> { fn app_sources(&self) -> Vec<AppSource> {
[ [
("/usr/share/applications", "System", 1, true), ("/usr/share/applications", "System", 1, true),
@ -193,6 +216,7 @@ impl Platform for Linux {
name: desktop.name.clone(), name: desktop.name.clone(),
bundle_id: Some(id.clone()), bundle_id: Some(id.clone()),
path: path.clone(), path: path.clone(),
icon_source: None,
version: None, version: None,
size: Bytes::ZERO, size: Bytes::ZERO,
source: source.label.clone(), source: source.label.clone(),
@ -223,6 +247,7 @@ impl Platform for Linux {
.unwrap_or_else(|| id.to_string()), .unwrap_or_else(|| id.to_string()),
bundle_id: Some(id.to_string()), bundle_id: Some(id.to_string()),
path: PathBuf::from(format!("flatpak:{id}")), path: PathBuf::from(format!("flatpak:{id}")),
icon_source: None,
version: None, version: None,
size: cols size: cols
.get(2) .get(2)

View File

@ -74,6 +74,25 @@ impl Platform for MacOs {
parts.join(" · ") parts.join(" · ")
} }
fn graphics_adapter(&self) -> String {
run(
"/usr/sbin/system_profiler",
&["SPDisplaysDataType", "-detailLevel", "mini"],
)
.map(|text| {
text.lines()
.filter_map(|line| {
line.trim()
.strip_prefix("Chipset Model:")
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
})
.collect::<Vec<_>>()
.join(" · ")
})
.unwrap_or_default()
}
fn app_sources(&self) -> Vec<AppSource> { fn app_sources(&self) -> Vec<AppSource> {
let mut sources = vec![ let mut sources = vec![
AppSource { AppSource {

View File

@ -266,104 +266,21 @@ mod windows {
list: &str, list: &str,
value_name: &str, value_name: &str,
enabled: bool, enabled: bool,
) -> std::io::Result<()> { ) -> Result<(), String> {
let hive = RegKey::predef(if machine { let hive = RegKey::predef(if machine {
HKEY_LOCAL_MACHINE HKEY_LOCAL_MACHINE
} else { } else {
HKEY_CURRENT_USER HKEY_CURRENT_USER
}); });
// Minimal rights only: several security suites (and locked-down let (key, _) = hive
// profiles) deny KEY_ALL_ACCESS-style opens on the startup trees even .create_subkey(format!(r"{base}\Explorer\StartupApproved\{list}"))
// for the key's own owner, which used to make every toggle fail. .map_err(registry_error)?;
let (key, _) = hive.create_subkey_with_flags(
format!(r"{base}\Explorer\StartupApproved\{list}"),
KEY_READ | KEY_WRITE,
)?;
let marker = winreg::RegValue { let marker = winreg::RegValue {
bytes: approved_marker(enabled), bytes: approved_marker(enabled),
vtype: RegType::REG_BINARY, vtype: RegType::REG_BINARY,
}; };
key.set_raw_value(value_name, &marker) key.set_raw_value(value_name, &marker)
} .map_err(registry_error)
/// Task Manager's marker rendered for `reg.exe` (12 bytes, hex).
fn approved_marker_hex(enabled: bool) -> String {
let mut hex = String::from(if enabled { "02" } else { "03" });
hex.push_str(&"0".repeat(22));
hex
}
/// Flip an approval marker, escalating through a one-shot UAC prompt when
/// the direct write is denied (machine-scope keys, protected hives). The
/// result is verified against the registry itself, so a cancelled prompt
/// reports failure instead of a silently dead switch.
fn flip_approved(
machine: bool,
base: &str,
list: &str,
value_name: &str,
enabled: bool,
) -> Result<(), String> {
if let Err(why) = write_approved(machine, base, list, value_name, enabled) {
if why.kind() != std::io::ErrorKind::PermissionDenied {
return Err(registry_error(why));
}
let hive_label = if machine { "HKLM" } else { "HKCU" };
run_elevated(
"reg.exe",
&[
"add".to_string(),
format!(r"{hive_label}\{base}\Explorer\StartupApproved\{list}"),
"/v".to_string(),
value_name.to_string(),
"/t".to_string(),
"REG_BINARY".to_string(),
"/d".to_string(),
approved_marker_hex(enabled),
"/f".to_string(),
],
)?;
let hive = RegKey::predef(if machine {
HKEY_LOCAL_MACHINE
} else {
HKEY_CURRENT_USER
});
if approved_enabled(&hive, base, list, value_name) != enabled {
return Err("提权写入后状态仍未改变".to_string());
}
}
Ok(())
}
/// Single-quote one argument for a PowerShell -ArgumentList list.
fn quote_ps(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
/// Run `program args…` elevated through `Start-Process -Verb RunAs`.
/// PowerShell's own exit code reports a cancelled or refused prompt.
fn run_elevated(program: &str, args: &[String]) -> Result<(), String> {
use std::os::windows::process::CommandExt;
let arglist = args
.iter()
.map(|arg| quote_ps(arg))
.collect::<Vec<_>>()
.join(",");
let script = format!(
"$ErrorActionPreference='Stop'; Start-Process -FilePath {} -ArgumentList {} -Verb RunAs -WindowStyle Hidden -Wait",
quote_ps(program),
arglist
);
let status = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", &script])
.creation_flags(0x0800_0000)
.status()
.map_err(|error| format!("无法启动提权助手:{error}"))?;
if status.success() {
Ok(())
} else {
Err("管理员授权被取消,未做修改".to_string())
}
} }
fn display_name(command: &str) -> String { fn display_name(command: &str) -> String {
@ -522,7 +439,6 @@ mod windows {
/// Resolve `display_name` (and the software icon) for every scanned /// Resolve `display_name` (and the software icon) for every scanned
/// entry, once per binary. /// entry, once per binary.
fn decorate_display_names(entries: &mut [StartupEntry]) { fn decorate_display_names(entries: &mut [StartupEntry]) {
let vendors = vendor_icon_map();
let mut cache: std::collections::HashMap<String, SoftwareInfo> = Default::default(); let mut cache: std::collections::HashMap<String, SoftwareInfo> = Default::default();
for entry in entries { for entry in entries {
let Some(exe) = exe_from_command(&entry.command) else { let Some(exe) = exe_from_command(&entry.command) else {
@ -537,10 +453,10 @@ mod windows {
probed probed
}; };
let (description, product, icon) = cache let (description, product, icon) = cache
.entry(probed.clone()) .entry(exe)
.or_insert_with(|| { .or_insert_with(|| {
let (description, product, _company) = version_strings(&probed); let (description, product, _company) = version_strings(&probed);
(description, product, software_icon(&probed, &vendors)) (description, product, exe_icon_png(&probed, 0))
}) })
.clone(); .clone();
entry.display_name = entry.display_name =
@ -549,181 +465,6 @@ mod windows {
} }
} }
/// Whether a PE/ICO file ships *real* icon resources. Service stubs such
/// as `qmbsrv.exe` or Edge's `elevation_service.exe` embed none, and
/// `ExtractAssociatedIconW` then silently returns the generic Windows
/// app tile — the cause of whole columns of 权限管理 rows looking alike.
fn has_icon_resources(path: &str) -> bool {
use windows_sys::Win32::UI::Shell::ExtractIconExW;
let wide: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
// SAFETY: NUL-terminated buffer; null handle arrays only ask for the
// count of icons the module carries.
(unsafe {
ExtractIconExW(
wide.as_ptr(),
-1,
std::ptr::null_mut(),
std::ptr::null_mut(),
0,
)
}) > 0
}
/// `App Paths` is the canonical "where does this tool really live" answer:
/// `SpaceAgent.exe` registers the product binary even when the row points
/// at a stripped-down service stub. Returns an (icon path, index) pair
/// that differs from `except` and exists on disk.
fn app_paths_icon_spec(exe_name: &str, except: &str) -> Option<(String, u16)> {
const APP_PATHS: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths";
const APP_PATHS_WOW: &str =
r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths";
let candidates = [
(HKEY_LOCAL_MACHINE, APP_PATHS),
(HKEY_LOCAL_MACHINE, APP_PATHS_WOW),
(HKEY_CURRENT_USER, APP_PATHS),
];
for (hive, base) in candidates {
let Ok(root) = RegKey::predef(hive).open_subkey_with_flags(base, KEY_READ) else {
continue;
};
let Ok(app) = root.open_subkey_with_flags(exe_name, KEY_READ) else {
continue;
};
let default: String = app.get_value("").unwrap_or_default();
let icon: String = app
.open_subkey_with_flags("DefaultIcon", KEY_READ)
.and_then(|key| key.get_value(""))
.unwrap_or_default();
let spec = if icon.trim().is_empty() {
&default
} else {
&icon
};
let (path, index) = parse_display_icon(spec)?;
if path.eq_ignore_ascii_case(except.trim_matches('"')) {
continue;
}
if Path::new(&path).exists() {
return Some((path, index));
}
}
None
}
/// A sibling in the same folder that does ship an icon: vendors park
/// `Workspace.ico` next to the stub (H3C) or the full binary sits one
/// directory entry away (Edge). `.ico` files win; otherwise the largest
/// `.exe` with real icon resources — the main product binary.
fn sibling_icon_spec(dir: &Path) -> Option<(String, u16)> {
let Ok(read_dir) = std::fs::read_dir(dir) else {
return None;
};
let mut files: Vec<PathBuf> = read_dir.filter_map(Result::ok).map(|f| f.path()).collect();
files.sort();
for path in &files {
let is_ico = path
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| e.eq_ignore_ascii_case("ico"));
if is_ico {
return Some((path.to_string_lossy().into_owned(), 0));
}
}
let mut best: Option<(u64, String)> = None;
for path in &files {
let is_exe = path
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| e.eq_ignore_ascii_case("exe"));
if !is_exe || !has_icon_resources(&path.to_string_lossy()) {
continue;
}
let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
if best.as_ref().map_or(true, |(known, _)| size > *known) {
best = Some((size, path.to_string_lossy().into_owned()));
}
}
best.map(|(_, path)| (path, 0))
}
/// Directory → `DisplayIcon` from the uninstall registry — the authoritative
/// "this folder belongs to product X, and X's icon is here" table. Edge,
/// 电脑管家 and SpaceAgent all register one whose parent is exactly the
/// folder holding their icon-less service stubs. Built once per scan.
fn vendor_icon_map() -> std::collections::HashMap<String, (String, u16)> {
const UNINSTALLS: [&str; 3] = [
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
r"Software\Microsoft\Windows\CurrentVersion\Uninstall",
];
let mut map: std::collections::HashMap<String, (String, u16)> = Default::default();
for hive in [HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER] {
for base in UNINSTALLS {
let Ok(root) = RegKey::predef(hive).open_subkey_with_flags(base, KEY_READ) else {
continue;
};
for name in root.enum_keys().filter_map(Result::ok) {
let Ok(app) = root.open_subkey_with_flags(&name, KEY_READ) else {
continue;
};
let Some(spec): Option<String> = app.get_value("DisplayIcon").ok() else {
continue;
};
let Some((path, index)) = parse_display_icon(&spec) else {
continue;
};
let Some(dir) = Path::new(&path).parent() else {
continue;
};
let dir = dir
.to_string_lossy()
.to_lowercase()
.trim_end_matches('\\')
.to_string();
if !dir.is_empty() && !map.contains_key(&dir) && Path::new(&path).exists() {
map.insert(dir, (path, index));
}
}
}
}
map
}
/// Startup-list icon with the vendor fallbacks the generic extraction
/// lacks: real resources first, then App Paths, then the uninstall
/// registry's DisplayIcon for the same folder, then a sibling file.
/// `None` (a neutral placeholder in the UI) beats a misleading tile.
fn software_icon(
path: &str,
vendors: &std::collections::HashMap<String, (String, u16)>,
) -> Option<Vec<u8>> {
if has_icon_resources(path) {
return exe_icon_png(path, 0);
}
let file = Path::new(path);
let name = file.file_name()?.to_string_lossy().to_string();
if let Some((spec, index)) = app_paths_icon_spec(&name, path) {
if let Some(icon) = exe_icon_png(&spec, index) {
return Some(icon);
}
}
let dir_key = file
.parent()
.map(|dir| dir.to_string_lossy().to_lowercase())
.unwrap_or_default();
if let Some((spec, index)) = vendors.get(dir_key.trim_end_matches('\\')) {
if let Some(icon) = exe_icon_png(spec, *index) {
return Some(icon);
}
}
if let Some((spec, index)) = file.parent().and_then(sibling_icon_spec) {
if let Some(icon) = exe_icon_png(&spec, index) {
return Some(icon);
}
}
None
}
/// ImagePath entries sometimes carry `"` around paths with spaces even /// ImagePath entries sometimes carry `"` around paths with spaces even
/// mid-command; strip and resolve to something `GetFileVersionInfo` likes. /// mid-command; strip and resolve to something `GetFileVersionInfo` likes.
fn exe_to_existing_path(exe: &str) -> String { fn exe_to_existing_path(exe: &str) -> String {
@ -1538,7 +1279,7 @@ mod windows {
} else { } else {
name.to_string() name.to_string()
}; };
flip_approved(machine, &base, list, &marker, enabled) write_approved(machine, &base, list, &marker, enabled)
} }
"folder" => { "folder" => {
let file = Path::new(rest) let file = Path::new(rest)
@ -1546,7 +1287,7 @@ mod windows {
.map(|n| n.to_string_lossy().to_string()) .map(|n| n.to_string_lossy().to_string())
.ok_or_else(|| "启动文件夹项目路径无效".to_string())?; .ok_or_else(|| "启动文件夹项目路径无效".to_string())?;
let machine = rest.contains("ProgramData"); let machine = rest.contains("ProgramData");
flip_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled) write_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled)
} }
"task" => { "task" => {
use std::os::windows::process::CommandExt; use std::os::windows::process::CommandExt;
@ -1561,79 +1302,23 @@ mod windows {
.output() .output()
.map_err(|error| format!("无法调用 schtasks:{error}"))?; .map_err(|error| format!("无法调用 schtasks:{error}"))?;
if output.status.success() { if output.status.success() {
return Ok(()); Ok(())
} } else {
let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase(); Err(format!(
// schtasks reports "task not ready", missing tasks, etc. —
// only a plain access denial justifies a UAC round-trip.
let denied = stderr.contains("access is denied")
|| stderr.contains("access denied")
|| stderr.contains("拒绝访问");
if !denied {
return Err(format!(
"计划任务修改失败:{}", "计划任务修改失败:{}",
String::from_utf8_lossy(&output.stderr).trim() String::from_utf8_lossy(&output.stderr).trim()
)); ))
} }
run_elevated(
"schtasks.exe",
&[
"/Change".to_string(),
"/TN".to_string(),
rest.to_string(),
if enabled { "/Enable" } else { "/Disable" }.to_string(),
],
)?;
Ok(())
} }
"svc" => { "svc" => {
// 开 = Automatic(2),关 = Manual(3):保留按需启动能力, // 开 = Automatic(2),关 = Manual(3):保留按需启动能力,
// 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。 // 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。
let start = if enabled { 2u32 } else { 3u32 }; let key = RegKey::predef(HKEY_LOCAL_MACHINE)
let key_path = format!(r"{SERVICES_KEY}\{rest}"); .open_subkey_with_flags(format!(r"{SERVICES_KEY}\{rest}"), KEY_READ | KEY_WRITE)
let direct = (|| -> std::io::Result<()> { .map_err(registry_error)?;
let key = RegKey::predef(HKEY_LOCAL_MACHINE) key.set_value("Start", &(if enabled { 2u32 } else { 3u32 }))
.open_subkey_with_flags(&key_path, KEY_READ | KEY_WRITE)?; .map_err(registry_error)?;
key.set_value("Start", &start) let _ = service_control(rest, if enabled { "auto" } else { "demand" });
})();
if let Err(why) = direct {
if why.kind() != std::io::ErrorKind::PermissionDenied {
return Err(registry_error(why));
}
run_elevated(
"reg.exe",
&[
"add".to_string(),
format!(r"HKLM\{key_path}"),
"/v".to_string(),
"Start".to_string(),
"/t".to_string(),
"REG_DWORD".to_string(),
"/d".to_string(),
start.to_string(),
"/f".to_string(),
],
)?;
let live = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(&key_path, KEY_READ)
.map(|key| key.get_value::<u32, _>("Start").ok())
.ok()
.flatten();
if live != Some(start) {
return Err("提权写入后服务状态仍未改变".to_string());
}
}
if service_control(rest, if enabled { "auto" } else { "demand" }).is_err() {
let _ = run_elevated(
"sc.exe",
&[
"config".to_string(),
rest.to_string(),
"start=".to_string(),
if enabled { "auto" } else { "demand" }.to_string(),
],
);
}
Ok(()) Ok(())
} }
_ => Err("未知的启动项来源".to_string()), _ => Err("未知的启动项来源".to_string()),
@ -2052,56 +1737,9 @@ mod windows {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{ use super::{
approved_enabled, clean_module_path, exe_from_command, friendly_program_name, has_cjk, clean_module_path, exe_from_command, friendly_program_name, has_cjk,
is_placeholder_label, module_folder_name, parse_csv_line, split_run_path, is_placeholder_label, module_folder_name, parse_csv_line, task_settings_enabled,
task_settings_enabled, write_approved, CURRENT_VERSION,
}; };
use winreg::RegKey;
#[test]
fn toggle_round_trips_through_the_approved_marker() {
// The exact pair the UI toggle relies on: write_approved stores a
// marker, the rescan reads it back. If these ever drift, every
// startup switch silently snaps back — the "button is dead" bug.
let list = format!("squidTest{}", std::process::id());
let hive = RegKey::predef(winreg::enums::HKEY_CURRENT_USER);
let key_path = format!(r"{CURRENT_VERSION}\Explorer\StartupApproved\{list}");
for name in ["squid-off", "squid-on"] {
let want = name.ends_with("on");
if let Err(why) = write_approved(false, CURRENT_VERSION, &list, name, want) {
// Sandboxed CI runners deny registry writes; the marker
// round-trip cannot be proven here, so say so instead of
// failing a correct build.
eprintln!("skipping marker round-trip: registry write denied ({why})");
return;
}
assert_eq!(
approved_enabled(&hive, CURRENT_VERSION, &list, name),
want,
"{name} must read back as written"
);
}
let _ = hive.delete_subkey_all(&key_path);
}
#[test]
fn run_path_split_round_trips_hive_and_list() {
// set_startup_enabled re-derives (machine, base, list) from the
// id scan produced; a mismatch writes the marker to the wrong key
// and the rescan then shows the old state.
let wow_run = r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run".to_string();
let (machine, base, list, prefix32) = split_run_path("HKLM", &wow_run);
assert!(machine);
assert_eq!(list, "Run");
assert!(prefix32);
assert!(base.contains("WOW6432Node"));
let (machine, base, list, prefix32) =
split_run_path("HKCU", &format!(r"{CURRENT_VERSION}\RunOnce"));
assert!(!machine);
assert_eq!(list, "RunOnce");
assert!(!prefix32);
assert_eq!(base, CURRENT_VERSION);
}
#[test] #[test]
fn command_paths_survive_quotes_and_arguments() { fn command_paths_survive_quotes_and_arguments() {

View File

@ -0,0 +1,242 @@
//! The full process table, as opposed to the twelve busiest rows the meters
//! panel draws.
//!
//! `squid-stats` samples every couple of seconds and must stay cheap, so it
//! reports names and percentages. Answering "what is this thing, who started it
//! and did anybody sign it" is a different question, asked when a person opens
//! the Processes tab, and it tolerates a slower path: one refresh of the table
//! plus a signature lookup for the executables actually on screen.
//!
//! The table is deliberately read-only here. Deciding whether a pid may be
//! stopped is the job of [`crate::process`], which refuses squid itself and the
//! processes a boot rests on; this module only describes what is running.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System, Users};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessRow {
pub pid: u32,
pub parent: Option<u32>,
pub name: String,
pub command: String,
pub program: Option<PathBuf>,
pub working_directory: Option<PathBuf>,
pub user: String,
pub cpu: f32,
pub memory: u64,
pub started_ms: Option<u64>,
/// Set later by the desktop layer, which owns the startup inventory: a
/// process started by a login item is a different kind of thing than one
/// the person launched themselves.
pub startup_item: Option<String>,
pub signed: bool,
pub publisher: Option<String>,
/// False for processes owned by somebody else, which squid must not stop.
pub owned: bool,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ProcessTable {
pub rows: Vec<ProcessRow>,
pub taken_at_ms: u64,
}
/// Snapshot the table. `with_trust` asks the operating system about each
/// distinct executable once, which is the expensive part and is only wanted
/// when the signature column is actually on screen.
pub fn snapshot(with_trust: bool) -> ProcessTable {
let mut system =
System::new_with_specifics(RefreshKind::nothing().with_processes(process_kind()));
system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind());
snapshot_from(&system, with_trust)
}
fn process_kind() -> ProcessRefreshKind {
ProcessRefreshKind::nothing()
.with_cmd(sysinfo::UpdateKind::Always)
.with_exe(sysinfo::UpdateKind::Always)
.with_cwd(sysinfo::UpdateKind::Always)
.with_memory()
.with_cpu()
.with_user(sysinfo::UpdateKind::Always)
}
fn snapshot_from(system: &System, with_trust: bool) -> ProcessTable {
let users = Users::new_with_refreshed_list();
let current_user = current_user_name();
let mut cache: std::collections::HashMap<PathBuf, crate::trust::Trust> =
std::collections::HashMap::new();
let mut rows: Vec<ProcessRow> = system
.processes()
.values()
.map(|process| {
let program = process.exe().map(|path| path.to_path_buf());
let command = process
.cmd()
.iter()
.map(|part| part.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" ");
let user = process
.user_id()
.and_then(|id| users.get_user_by_id(id))
.map(|user| user.name().to_string())
.unwrap_or_default();
let mut row = ProcessRow {
pid: process.pid().as_u32(),
parent: process.parent().map(|pid| pid.as_u32()),
name: name_of(process.name()),
command,
started_ms: start_time_ms(process.start_time()),
program,
working_directory: process.cwd().map(|path| path.to_path_buf()),
user,
cpu: process.cpu_usage().min(4_000.0),
memory: process.memory(),
startup_item: None,
signed: false,
publisher: None,
owned: true,
};
row.owned = row.user.is_empty()
|| current_user.is_empty()
|| row.user.eq_ignore_ascii_case(&current_user);
if with_trust {
if let Some(program) = row.program.as_deref() {
let trust = cache.entry(program.to_path_buf()).or_insert_with(|| {
if crate::trust::might_be_executable(program) {
crate::trust::assess(program)
} else {
Default::default()
}
});
row.signed = trust.signed;
row.publisher = trust.signer.clone();
}
}
row
})
.collect();
rows.sort_by(|a, b| b.memory.cmp(&a.memory).then_with(|| a.pid.cmp(&b.pid)));
ProcessTable {
rows,
taken_at_ms: now_ms(),
}
}
/// One row, re-read right now. The desktop layer asks this before it stops
/// anything, so the name the person clicked is checked against the pid that
/// answers to that number today.
pub fn row_of(pid: u32) -> Option<ProcessRow> {
let mut system = System::new_with_specifics(RefreshKind::nothing());
system.refresh_processes_specifics(
ProcessesToUpdate::Some(&[sysinfo::Pid::from_u32(pid)]),
true,
process_kind(),
);
let process = system.process(sysinfo::Pid::from_u32(pid))?;
Some(ProcessRow {
pid,
parent: process.parent().map(|pid| pid.as_u32()),
name: name_of(process.name()),
command: process
.cmd()
.iter()
.map(|part| part.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" "),
program: process.exe().map(|path| path.to_path_buf()),
working_directory: process.cwd().map(|path| path.to_path_buf()),
user: String::new(),
cpu: process.cpu_usage(),
memory: process.memory(),
started_ms: start_time_ms(process.start_time()),
startup_item: None,
signed: false,
publisher: None,
owned: true,
})
}
fn name_of(name: &std::ffi::OsStr) -> String {
name.to_string_lossy()
.split(['/', '\\'])
.next_back()
.filter(|part| !part.is_empty())
.unwrap_or("?")
.to_string()
}
/// sysinfo reports Unix start times as seconds since boot; Windows and newer
/// sysinfo releases report seconds since the epoch. Anything that already looks
/// like an epoch passes through, so a wrong guess cannot turn into a date in
/// 1970 on every row.
fn start_time_ms(raw: u64) -> Option<u64> {
if raw == 0 {
return None;
}
let uptime = System::uptime();
let now = now_ms() / 1_000;
if raw > 1_000_000_000 && raw <= now {
return Some(raw.saturating_mul(1_000));
}
if raw <= uptime {
return Some(now.saturating_sub(raw).saturating_mul(1_000));
}
None
}
/// The account squid runs as. Ownership is compared by name because a process
/// reports a uid/SID and the user table is the only thing that turns either one
/// into the name a person recognises — the same source `HostInfo` prints.
fn current_user_name() -> String {
std::env::var("USER")
.or_else(|_| std::env::var("USERNAME"))
.unwrap_or_default()
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snapshot_describes_the_test_process() {
let table = snapshot(false);
assert!(
table.rows.iter().any(|row| row.pid == std::process::id()),
"the process running this test is missing from the table"
);
}
#[test]
fn a_row_can_be_re_read_by_pid() {
let here = std::process::id();
let row = row_of(here).expect("this process is running");
assert_eq!(row.pid, here);
assert!(!row.name.is_empty());
assert!(row_of(u32::MAX).is_none());
}
#[test]
fn sysinfo_start_times_are_normalised_to_millis() {
// Seconds since boot, which is what sysinfo gives on unix.
assert!(start_time_ms(10).is_some());
// Seconds since the epoch, which is what it gives on Windows.
let epoch = 1_700_000_000;
assert_eq!(start_time_ms(epoch), Some(epoch * 1_000));
assert_eq!(start_time_ms(0), None);
}
}

View File

@ -0,0 +1,313 @@
//! What the operating system's own protection says about itself.
//!
//! Squid reads this and never writes it. `xprotect status` and `xprotect
//! version` are queried, `xprotect update` deliberately is not: that command
//! contacts Apple's servers on the machine's behalf, and a third-party app
//! starting downloads it did not pay for is not squid's to decide. The same
//! restraint applies to Defender.
//!
//! The reason to show any of it is honesty about coverage. XProtect runs with or
//! without squid, and a user who sees "background scanning: off" can act on that
//! in System Settings. A user who sees nothing assumes it is on.
use serde::{Deserialize, Serialize};
/// The state of the protection the operating system provides itself.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProtectionStatus {
/// `xprotect`, `defender`, `third-party`, `unknown`.
pub provider: String,
/// Whether the state above was actually read, as opposed to assumed.
pub known: bool,
/// Signature/definition version, in whatever notation the platform uses.
pub definitions: String,
/// When those definitions were installed or last refreshed.
pub definitions_date: String,
pub realtime: Option<bool>,
pub background_scans: Option<bool>,
pub launch_scans: Option<bool>,
/// Gatekeeper (`spctl`) or the Windows Defender engine state.
pub gatekeeper: Option<bool>,
pub last_scan_date: String,
/// Anything that could not be determined, in plain words.
pub notes: Vec<String>,
pub product_name: String,
}
impl ProtectionStatus {
/// Unknown must never be rendered as healthy. This is the guard against a
/// probe that fails on a clean machine and reports green.
pub fn is_healthy(&self) -> Option<bool> {
if !self.known {
return None;
}
match self.provider.as_str() {
"xprotect" => Some(
self.realtime.unwrap_or(true)
&& self.background_scans.unwrap_or(true)
&& self.launch_scans.unwrap_or(true),
),
"defender" | "third-party" => Some(self.realtime.unwrap_or(false)),
_ => None,
}
}
}
/// Ask the operating system. Never fails; a platform with nothing to report says
/// so through `known: false` and a note.
pub fn status() -> ProtectionStatus {
#[cfg(target_os = "macos")]
{
macos::status()
}
#[cfg(windows)]
{
windows::status()
}
#[cfg(not(any(target_os = "macos", windows)))]
{
ProtectionStatus {
provider: "unknown".into(),
known: false,
notes: vec!["this platform has no protection status that Squid can read".into()],
..Default::default()
}
}
}
#[cfg(target_os = "macos")]
mod macos {
use super::*;
fn run(program: &str, args: &[&str]) -> Option<String> {
let output = std::process::Command::new(program)
.args(args)
.output()
.ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
None
}
}
pub fn status() -> ProtectionStatus {
let mut status = ProtectionStatus {
provider: "xprotect".into(),
product_name: "XProtect".into(),
..Default::default()
};
match run("/usr/bin/xprotect", &["status", "--json"]) {
Some(json) => match serde_json::from_str::<serde_json::Value>(&json) {
Ok(value) => {
status.known = true;
status.background_scans = value
.get("xprotect_background_scans")
.and_then(|value| value.as_bool());
status.launch_scans = value
.get("xprotect_launch_scans")
.and_then(|value| value.as_bool());
status.realtime = status.launch_scans;
}
Err(error) => status
.notes
.push(format!("XProtect status was unreadable: {error}")),
},
None => status.notes.push(
"XProtect did not report its state. macOS 13 and later answer this query.".into(),
),
}
if let Some(json) = run("/usr/bin/xprotect", &["version", "--json"]) {
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&json) {
if let Some(version) = value
.get("xprotect_bundle_version")
.and_then(|v| v.as_str())
{
status.definitions = version.to_string();
}
if let Some(date) = value
.get("xprotect_bundle_install_date")
.and_then(|value| value.as_str())
{
status.definitions_date = date.to_string();
}
}
}
// Gatekeeper answers for whether a downloaded app can run at all.
match run("/usr/sbin/spctl", &["--status"]) {
Some(text) => status.gatekeeper = Some(text.contains("assessments enabled")),
None => status
.notes
.push("Gatekeeper status could not be read.".into()),
}
if !status.known {
status.provider = "unknown".into();
}
status
}
}
#[cfg(windows)]
mod windows {
use super::*;
use std::os::windows::process::CommandExt;
use std::process::Command;
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY};
use winreg::RegKey;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// Defender's own registry view answers without a WMI round trip: the
/// product-registration key names the active antivirus, and the
/// `CurrentReputation`/`Signature` keys carry the definition version.
pub fn status() -> ProtectionStatus {
let mut status = ProtectionStatus {
provider: "unknown".into(),
..Default::default()
};
let base = match RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SOFTWARE\Microsoft\Windows Defender",
KEY_READ | KEY_WOW64_64KEY,
) {
Ok(base) => base,
Err(_) => {
status
.notes
.push("Windows Defender is not registered on this machine.".into());
return status;
}
};
let disabled = base.get_value::<u32, _>("DisableAntiSpyware").unwrap_or(0) != 0;
if let Ok(signatures) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SOFTWARE\Microsoft\Windows Defender\Signature Updates",
KEY_READ | KEY_WOW64_64KEY,
) {
if let Some(version) = signatures
.get_value::<String, _>("SignatureDefinitionVersion")
.ok()
.or_else(|| signatures.get_value::<String, _>("AMRunVersion").ok())
{
status.definitions = version;
}
if let Ok(days) = signatures.get_value::<u32, _>("LastSignatureUpdateAge") {
status.definitions_date = format!("{days} days ago");
}
status.known = true;
}
// A third-party product that registered itself replaces Defender.
let registered = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SOFTWARE\Microsoft\Windows Defender\FeatureManagement",
KEY_READ | KEY_WOW64_64KEY,
);
let _ = registered;
match active_antivirus() {
Some(name) if !name.is_empty() => {
status.product_name = name.clone();
status.provider = if name.contains("Windows Defender") || name.contains("Defender")
{
"defender".into()
} else {
"third-party".into()
};
status.known = true;
}
_ => {
status.provider = if disabled {
"unknown".into()
} else {
"defender".into()
};
status.product_name = "Microsoft Defender Antivirus".into();
status.realtime = Some(!disabled);
}
}
if !status.known {
status
.notes
.push("Windows Security Center did not report an antivirus product.".into());
}
status
}
/// Security Center's registration list, via WMI. One subprocess, no service.
fn active_antivirus() -> Option<String> {
let script = "Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct | Select-Object -ExpandProperty displayName";
let output = Command::new("powershell.exe")
.creation_flags(CREATE_NO_WINDOW)
.args([
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
script,
])
.spawn()
.ok()?
.wait_with_output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.find(|line| !line.is_empty())?
.to_string();
Some(text)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_is_never_reported_as_healthy() {
let unknown = ProtectionStatus {
provider: "unknown".into(),
known: false,
..Default::default()
};
assert_eq!(unknown.is_healthy(), None);
let xprotect = ProtectionStatus {
provider: "xprotect".into(),
known: true,
background_scans: Some(true),
launch_scans: Some(true),
realtime: Some(true),
..Default::default()
};
assert_eq!(xprotect.is_healthy(), Some(true));
let off = ProtectionStatus {
provider: "defender".into(),
known: true,
realtime: Some(false),
..Default::default()
};
assert_eq!(off.is_healthy(), Some(false));
}
#[cfg(target_os = "macos")]
#[test]
fn the_real_machine_answers_the_query() {
let status = status();
// Whether or not protection is on, the probe must produce something a
// person can read rather than an empty card.
assert!(
status.known || !status.notes.is_empty(),
"the probe said nothing at all: {status:?}"
);
assert!(!status.product_name.is_empty());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,748 @@
//! Who signed this file, as far as the operating system will say.
//!
//! The answer is used in two places: the startup list colours an entry that
//! nobody vouches for, and the scanner treats "unsigned binary in a user-writable
//! path that runs at login" as evidence. It is deliberately not treated as a
//! verdict. An unsigned file is ordinary for anything a person built themselves,
//! and a signed file is ordinary for adware that bought a certificate, so the
//! UI says *unsigned* rather than *suspicious* and leaves the reasoning to the
//! reader.
//!
//! macOS asks `codesign`, which is the same tool the release scripts use, so the
//! app and the release check cannot disagree about what "ad-hoc signed" means.
//! Windows asks the Authenticode API directly, because the PowerShell equivalent
//! costs a second to start and the process table asks this question per row.
use serde::{Deserialize, Serialize};
use std::path::Path;
/// What the signature says about one file.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Trust {
/// A signature exists and the operating system considers it intact.
pub signed: bool,
/// Ad-hoc / link-time signature: bytes are sealed, but nobody is named.
pub ad_hoc: bool,
/// Authenticode is present but chain validation failed (expired, unknown CA).
pub untrusted: bool,
/// Vendor named by the leaf certificate.
pub signer: Option<String>,
/// Why there is no signature, when that is worth saying.
pub note: Option<String>,
}
impl Trust {
/// One word for a table column.
pub fn state(&self) -> &'static str {
if self.signed && !self.ad_hoc && !self.untrusted {
"trusted"
} else if self.signed {
"adhoc"
} else if self.untrusted {
"untrusted"
} else {
"unsigned"
}
}
}
/// Ask the operating system about one file. Never fails: no answer is a normal
/// answer, and the caller decides whether silence is worth showing.
///
/// Answers are remembered for the life of the process, keyed by path plus the
/// file's size and modification time, because both callers ask in bulk: the
/// startup list asks once per entry and the process table once per distinct
/// executable on screen. The question itself costs a subprocess on macOS and a
/// certificate-chain walk on Windows, so one refresh of the process tab would be
/// hundreds of them. A file that changes is looked up again, which is why the
/// identity is part of the key and not the path alone.
pub fn assess(path: &Path) -> Trust {
let Some(key) = identity(path) else {
// Nothing to key on. Asking anyway is what turns "the file is not there"
// into an answer instead of a cached guess.
return assess_uncached(path);
};
if let Some(found) = cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(&key)
.cloned()
{
return found;
}
// Asked with no lock held: the question costs a subprocess, so holding the
// cache across it would make every bulk caller take these one at a time.
let trust = assess_uncached(path);
let mut cache = cache()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
// Bounded, because a utility that grows its own footprint to answer a
// display question is its own kind of junk. Half is dropped rather than all,
// so a table that is still on screen keeps the answers it is showing.
if cache.len() > 4_000 {
let stale: Vec<_> = cache.keys().take(cache.len() / 2).cloned().collect();
for stale in stale {
cache.remove(&stale);
}
}
cache.insert(key, trust.clone());
trust
}
type CacheKey = (std::path::PathBuf, u64, u128);
fn identity(path: &Path) -> Option<CacheKey> {
let metadata = std::fs::symlink_metadata(path).ok()?;
let modified = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|since| since.as_nanos())
.unwrap_or(0);
Some((path.to_path_buf(), metadata.len(), modified))
}
fn cache() -> &'static std::sync::Mutex<std::collections::HashMap<CacheKey, Trust>> {
static CACHE: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<CacheKey, Trust>>,
> = std::sync::OnceLock::new();
CACHE.get_or_init(Default::default)
}
fn assess_uncached(path: &Path) -> Trust {
#[cfg(target_os = "macos")]
{
macos::assess(path)
}
#[cfg(windows)]
{
windows::assess(path)
}
#[cfg(not(any(target_os = "macos", windows)))]
{
let _ = path;
Trust::default()
}
}
/// Whether the file carries a signature *blob*, without asking the operating
/// system to validate it.
///
/// This is the cheap sibling of [`assess`]: it reads the Mach-O load commands or
/// the PE certificate directory and stops, so it can run over every row of a
/// process table or every candidate in a full scan. What it cannot tell you is
/// whether that signature is trusted, which is exactly the difference a person
/// needs when they open the row — and that is why the detail view still asks
/// `assess` and this result is only ever shown as "signed by somebody" or "no
/// signature at all".
pub fn has_signature_blob(path: &Path) -> bool {
#[cfg(target_os = "macos")]
{
macho_has_signature(path)
}
#[cfg(windows)]
{
pe_has_certificate(path)
}
#[cfg(not(any(target_os = "macos", windows)))]
{
let _ = path;
false
}
}
/// Scan the load commands for `LC_CODE_SIGNATURE` (0x1D), in either endianness,
/// and into each slice of a fat binary.
#[cfg(target_os = "macos")]
fn macho_has_signature(path: &Path) -> bool {
// Only the head of the image is ever consulted: a Mach-O header plus a
// thousand load commands is a few tens of kilobytes, and a fat binary keeps
// its first slice within the first megabyte. Reading a four-gigabyte disk
// image whole to answer one yes/no question is the kind of cost that gets a
// scanner switched off.
const WINDOW: u64 = 2 * 1024 * 1024;
let Ok(length) = std::fs::metadata(path).map(|metadata| metadata.len()) else {
return false;
};
if length < 32 {
return false;
}
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut bytes = Vec::with_capacity((WINDOW).min(length) as usize);
{
use std::io::Read;
if Read::by_ref(&mut file)
.take(WINDOW)
.read_to_end(&mut bytes)
.is_err()
{
return false;
}
}
if bytes.len() < 32 {
return false;
}
let word = |bytes: &[u8], offset: usize, big: bool| -> Option<u32> {
let window = bytes.get(offset..offset + 4)?;
Some(if big {
u32::from_be_bytes(window.try_into().ok()?)
} else {
u32::from_le_bytes(window.try_into().ok()?)
})
};
let head = [bytes[0], bytes[1], bytes[2], bytes[3]];
const FAT_32: [u8; 4] = [0xCA, 0xFE, 0xBA, 0xBE];
const FAT_SWAPPED: [u8; 4] = [0xBE, 0xBA, 0xFE, 0xCA];
if head == FAT_32 || head == FAT_SWAPPED {
// The fat header is always big-endian in practice; the spelling of its
// magic says which order it was actually written in, and that governs
// only the table below — each slice re-declares its own endianness.
let big = head == FAT_32;
let count = word(&bytes, 4, big).unwrap_or(0).min(32) as usize;
for index in 0..count {
// fat_arch: cputype, cpusubtype, offset, size, align.
let Some(offset) = word(&bytes, 8 + index * 20 + 8, big) else {
continue;
};
// Each slice carries its own magic, and therefore its own
// endianness: a fat header written big-endian normally contains
// little-endian arm64 and x86_64 images.
if macho_slice_signed(&bytes, offset as usize, &word) {
return true;
}
}
return false;
}
macho_slice_signed(&bytes, 0, &word)
}
/// Walk one Mach-O header's load commands looking for the signature command.
#[cfg(target_os = "macos")]
fn macho_slice_signed(
bytes: &[u8],
start: usize,
word: &impl Fn(&[u8], usize, bool) -> Option<u32>,
) -> bool {
const LC_CODE_SIGNATURE: u32 = 0x1D;
// A 64-bit little-endian image begins `CF FA ED FE` — the magic 0xFEEDFACF
// read back as little-endian — and a big-endian one begins with the same
// four bytes in reverse. The 32-bit pair differs by one byte. Which spelling
// appeared is the only thing that decides the endianness of every field
// after it, so the table says it directly instead of inferring it from
// wherever this header was reached from.
// Which magic appeared decides two things at once: the endianness of every
// field after it, and whether this is a 64-bit header (32 bytes) or a
// 32-bit one (28 bytes). Getting either wrong reads the load commands from
// the wrong address and reports a signed binary as unsigned.
const THIN: [([u8; 4], bool, usize); 4] = [
([0xCF, 0xFA, 0xED, 0xFE], false, 32), // MH_MAGIC_64, host order
([0xCE, 0xFA, 0xED, 0xFE], false, 28), // MH_MAGIC, host order
([0xFE, 0xED, 0xFA, 0xCF], true, 32), // MH_MAGIC_64, swapped
([0xFE, 0xED, 0xFA, 0xCE], true, 28), // MH_MAGIC, swapped
];
let Some(head) = bytes.get(start..start + 4) else {
return false;
};
let Ok(head): Result<[u8; 4], _> = head.try_into() else {
return false;
};
let Some((_, big, header)) = THIN.iter().find(|(magic, _, _)| *magic == head) else {
return false;
};
let (big, header) = (*big, *header);
// A corrupt fat header can point a slice past what was actually read.
if start + header > bytes.len() {
return false;
}
// mach_header: magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds…
// `ncmds` is the fifth field, at offset 16 — reading 12 instead finds
// `filetype`, which is how every signed binary looks unsigned.
let commands = word(bytes, start + 16, big).unwrap_or(0).min(4096) as usize;
let mut cursor = start + header;
for _ in 0..commands {
let Some(command) = word(bytes, cursor, big) else {
return false;
};
// High bit marks a 64-bit-only command; the number underneath is the same.
if command & 0x7FFF_FFFF == LC_CODE_SIGNATURE {
return true;
}
let Some(size) = word(bytes, cursor + 4, big) else {
return false;
};
if size < 8 {
return false;
}
cursor += size as usize;
if cursor + 8 > bytes.len() {
return false;
}
}
false
}
/// A PE file's certificate table is data directory entry 4: an offset into the
/// file, not a relative virtual address, which makes it a four-byte read once
/// the header has been walked.
#[cfg(windows)]
fn pe_has_certificate(path: &Path) -> bool {
pe_has_certificate_at(path).unwrap_or(false)
}
/// The same walk written against `Option`, so an out-of-range field is a plain
/// "no" rather than a panic. Split out because `?` in the `bool`-returning
/// wrapper above does not compile, and this half only builds on Windows, so the
/// mistake is invisible to a macOS `cargo check`.
#[cfg(windows)]
fn pe_has_certificate_at(path: &Path) -> Option<bool> {
use std::io::Read;
let length = std::fs::metadata(path).ok()?.len();
let mut file = std::fs::File::open(path).ok()?;
let mut head = [0_u8; 4096];
let read = file.read(&mut head).ok()?;
let u32_at = |offset: usize| -> Option<u32> {
let window = head.get(offset..offset + 4)?;
Some(u32::from_le_bytes(window.try_into().ok()?))
};
if read < 64 || &head[0..2] != b"MZ" {
return Some(false);
}
let pe = u32_at(0x3C)? as usize;
if pe + 24 > read || &head[pe..pe + 4] != b"PE\0\0" {
return Some(false);
}
let optional = pe + 24;
let magic = u32_at(optional)? & 0xFFFF;
// Data directories start after the optional header; their offset differs
// between PE32 and PE32+, which is what the magic byte says.
let directories = optional + if magic == 0x20B { 112 } else { 96 };
let entry = u32_at(directories + 4 * 8)?;
let size = u32_at(directories + 4 * 8 + 4)?;
Some(entry != 0 && size != 0 && (entry as u64) < length)
}
/// Cheap gate for a table with hundreds of rows: only Mach-O and PE files can
/// carry a signature, so everything else is answered without a subprocess.
///
/// The header decides, not the name. A macOS privileged helper is called
/// `us.zoom.ZoomDaemon` and a Windows one `com.microsoft.autoupdate.helper`, where
/// the last dot is part of the name rather than an extension; judging by extension
/// never asked about a signed helper whose name happens to contain a dot. Reading
/// eight bytes is close to free next to the subprocess being avoided, and it is the
/// same question the signature actually answers.
pub fn might_be_executable(path: &Path) -> bool {
/// Bundles are signed as a unit, so the directory itself is the question.
const BUNDLES: [&str; 4] = ["app", "framework", "bundle", "xpc"];
let extension = || {
path.extension()
.map(|ext| ext.to_string_lossy().to_lowercase())
.unwrap_or_default()
};
if path.is_dir() {
return BUNDLES.contains(&extension().as_str());
}
match header(path) {
Some(head) => header_is_executable(&head),
// Nothing to read: an executable the current user may run but not open is
// common among root-owned helpers, and `codesign` may still answer for it.
None => {
BUNDLES.contains(&extension().as_str())
|| ["dylib", "so", "exe", "dll", "sys"].contains(&extension().as_str())
|| extension().is_empty()
}
}
}
/// The first eight bytes, or `None` when the file cannot be opened.
fn header(path: &Path) -> Option<[u8; 8]> {
use std::io::Read;
let mut file = std::fs::File::open(path).ok()?;
let mut head = [0_u8; 8];
file.read_exact(&mut head).ok()?;
Some(head)
}
fn header_is_executable(head: &[u8; 8]) -> bool {
// Mach-O 32/64, fat binary, and their byte-swapped forms.
const MACHOS: [[u8; 4]; 6] = [
[0xcf, 0xfa, 0xed, 0xfe],
[0xce, 0xfa, 0xed, 0xfe],
[0xca, 0xfe, 0xba, 0xbe],
[0xfe, 0xed, 0xfa, 0xcf],
[0xfe, 0xed, 0xfa, 0xce],
[0xbe, 0xba, 0xfe, 0xca],
];
if MACHOS.iter().any(|magic| head.starts_with(magic)) {
return true;
}
// PE: `MZ` at the front, `PE\0\0` wherever the header table points.
head.starts_with(b"MZ")
}
#[cfg(target_os = "macos")]
mod macos {
use super::*;
use std::path::PathBuf;
use std::process::Command;
const CODESIGN: &str = "/usr/bin/codesign";
/// Resolves an `.app` to the binary `codesign` should be asked about, since
/// asking about the bundle is what `--verify --deep` would do anyway.
fn executable_of(path: &Path) -> PathBuf {
let candidate = path.join("Contents/MacOS");
let Ok(entries) = std::fs::read_dir(&candidate) else {
return path.to_path_buf();
};
entries
.flatten()
.map(|entry| entry.path())
.find(|path| path.is_file())
.unwrap_or_else(|| path.to_path_buf())
}
pub fn assess(path: &Path) -> Trust {
if !path.exists() {
return Trust {
note: Some("the file is not there".into()),
..Default::default()
};
}
if !super::might_be_executable(path) {
return Trust::default();
}
let target = if path.is_dir() {
executable_of(path)
} else {
path.to_path_buf()
};
let Ok(output) = Command::new(CODESIGN)
.args(["-dvv", &target.display().to_string()])
.output()
else {
return Trust {
note: Some("codesign could not run".into()),
..Default::default()
};
};
// `codesign -dvv` writes its report to stderr and exits non-zero for
// unsigned files, which is an answer rather than a failure.
let report = String::from_utf8_lossy(&output.stderr).into_owned();
if report.contains("code object is not signed at all") || report.is_empty() {
return Trust {
note: (!report.is_empty()).then(|| "not signed".into()),
..Default::default()
};
}
let signer = report
.lines()
.find_map(|line| line.strip_prefix("Authority="))
.map(|name| name.trim().to_string());
let team = report
.lines()
.find_map(|line| line.strip_prefix("TeamIdentifier="))
.map(|value| value.trim().to_string());
let ad_hoc = team.as_deref() == Some("not set") && signer.is_none();
let signed = signer.is_some()
|| report.contains("CodeDirectory") && !ad_hoc
|| report.contains("Signature size");
if ad_hoc {
return Trust {
signed: true,
ad_hoc: true,
note: Some("ad-hoc signed — the bytes are sealed, nobody is named".into()),
..Default::default()
};
}
if !signed {
return Trust {
note: Some("no usable signature".into()),
..Default::default()
};
}
Trust {
signed: true,
signer: signer.or(team),
..Default::default()
}
}
}
#[cfg(windows)]
mod windows {
use super::*;
/// Ask Authenticode through `WinVerifyTrust`. The status codes are read so
/// an expired or unrooted certificate reports as *untrusted* rather than as
/// unsigned: those files were signed by somebody, and a person deciding
/// whether to quarantine them deserves to know that much.
pub fn assess(path: &Path) -> Trust {
if !super::might_be_executable(path) {
return Trust::default();
}
if !path.exists() {
return Trust {
note: Some("the file is not there".into()),
..Default::default()
};
}
match authenticode(path) {
Ok(()) => Trust {
signed: true,
signer: publisher(path),
..Default::default()
},
Err(status) => {
const NO_SIGNATURE: [u32; 2] = [0x800b0100, 0xc0000225];
let present = !NO_SIGNATURE.contains(&status);
Trust {
untrusted: present,
signer: present.then(|| publisher(path)).flatten(),
note: Some(format!("Authenticode reported 0x{status:08x}")),
..Default::default()
}
}
}
}
fn authenticode(path: &Path) -> Result<(), u32> {
use windows_sys::core::GUID;
use windows_sys::Win32::Security::WinTrust::{
WinVerifyTrust, WINTRUST_DATA, WINTRUST_DATA_0, WINTRUST_FILE_INFO, WTD_CHOICE_FILE,
WTD_REVOKE_NONE, WTD_STATEACTION_IGNORE, WTD_UI_NONE,
};
// WINTRUST_ACTION_GENERIC_VERIFY_V2
const ACTION: GUID = GUID::from_u128(0x00aa003c_0000_0000_c000_000000000046);
let wide = wide_path(path);
let mut file_info = WINTRUST_FILE_INFO {
cbStruct: std::mem::size_of::<WINTRUST_FILE_INFO>() as u32,
pcwszFilePath: wide.as_ptr(),
hFile: std::ptr::null_mut(),
pgKnownSubject: std::ptr::null_mut(),
};
let mut data = WINTRUST_DATA {
cbStruct: std::mem::size_of::<WINTRUST_DATA>() as u32,
pPolicyCallbackData: std::ptr::null_mut(),
pSIPClientData: std::ptr::null_mut(),
dwUIChoice: WTD_UI_NONE,
fdwRevocationChecks: WTD_REVOKE_NONE,
dwUnionChoice: WTD_CHOICE_FILE,
Anonymous: WINTRUST_DATA_0 {
pFile: &mut file_info,
},
dwStateAction: WTD_STATEACTION_IGNORE,
hWVTStateData: std::ptr::null_mut(),
pwszURLReference: std::ptr::null_mut(),
dwProvFlags: 0,
dwUIContext: 0,
pSignatureSettings: std::ptr::null_mut(),
};
let status = unsafe {
WinVerifyTrust(
std::ptr::null_mut(),
&mut ACTION.clone() as *mut GUID,
&mut data as *mut _ as *mut std::ffi::c_void,
)
};
if status == 0 {
Ok(())
} else {
Err(status as u32)
}
}
fn wide_path(path: &Path) -> Vec<u16> {
path.to_string_lossy()
.encode_utf16()
.chain(std::iter::once(0))
.collect()
}
/// The `CompanyName` of the version resource: what Task Manager prints as
/// Publisher, and a magnitude cheaper than parsing the certificate chain.
fn publisher(path: &Path) -> Option<String> {
use windows_sys::Win32::Storage::FileSystem::{
GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW,
};
let wide = wide_path(path);
let size = unsafe { GetFileVersionInfoSizeW(wide.as_ptr(), std::ptr::null_mut()) };
if size == 0 {
return None;
}
let mut buffer = vec![0_u8; size as usize];
let ok = unsafe { GetFileVersionInfoW(wide.as_ptr(), 0, size, buffer.as_mut_ptr().cast()) };
if ok == 0 {
return None;
}
let mut pointer: *mut std::ffi::c_void = std::ptr::null_mut();
let mut length = 0_u32;
let translation = wide_str("\\VarFileInfo\\Translation");
let found = unsafe {
VerQueryValueW(
buffer.as_ptr().cast(),
translation.as_ptr(),
&mut pointer,
&mut length,
)
};
let (language, code_page) = if found == 0 || length < 4 {
(0x0409, 1200)
} else {
let pairs = unsafe {
std::slice::from_raw_parts(pointer.cast::<(u16, u16)>(), (length / 4) as usize)
};
pairs.first().copied().unwrap_or((0x0409, 1200))
};
let key = wide_str(&format!("\\StringInfo\\{language:04x}{code_page:04x}"));
let found = unsafe {
VerQueryValueW(
buffer.as_ptr().cast(),
key.as_ptr(),
&mut pointer,
&mut length,
)
};
if found == 0 || length == 0 {
return None;
}
let block =
unsafe { std::slice::from_raw_parts(pointer.cast::<u16>(), (length / 2) as usize) };
string_value(block, "CompanyName")
}
fn wide_str(text: &str) -> Vec<u16> {
text.encode_utf16().chain(std::iter::once(0)).collect()
}
/// The `StringFileInfo` block is `key\0value\0key\0value\0…` in UTF-16,
/// terminated by an empty key.
fn string_value(block: &[u16], wanted: &str) -> Option<String> {
let mut entries: Vec<String> = Vec::new();
let mut current: Vec<u16> = Vec::new();
for unit in block {
if *unit == 0 {
if !current.is_empty() {
let taken: Vec<u16> = std::mem::take(&mut current);
entries.push(String::from_utf16_lossy(&taken));
}
} else {
current.push(*unit);
}
}
for pair in entries.as_chunks::<2>().0 {
if pair[0].eq_ignore_ascii_case(wanted) && !pair[1].is_empty() {
return Some(pair[1].clone());
}
}
None
}
}
#[cfg(all(test, target_os = "macos"))]
mod blob_tests {
use super::*;
/// Apple's own binaries are signed, and these three are on every macOS
/// version this runs on, so the header check has something fixed to point at.
#[test]
fn a_signed_system_binary_reports_its_signature_blob() {
for path in ["/bin/ls", "/bin/cat", "/usr/lib/dyld"] {
let file = std::path::Path::new(path);
if !file.is_file() {
continue;
}
assert!(
has_signature_blob(file),
"{path} is signed, and the load commands say so"
);
}
}
#[test]
fn a_file_that_is_not_a_macho_reports_no_signature() {
let dir = std::env::temp_dir().join(format!("squid-trust-blob-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let plain = dir.join("plain");
std::fs::write(&plain, b"#!/bin/sh\necho not a binary\n").unwrap();
assert!(!has_signature_blob(&plain));
// A Mach-O magic with nothing behind it: the header is too short to hold
// any load commands, and reading past the end must not panic.
let truncated = dir.join("truncated");
std::fs::write(&truncated, [0xCF_u8, 0xFA, 0xED, 0xFE, 0, 0, 0, 1]).unwrap();
assert!(!has_signature_blob(&truncated));
// A fat header that points its only slice past the end of the file.
let lying = dir.join("lying-fat");
let mut bytes = vec![0xCA, 0xFE, 0xBA, 0xBE, 0, 0, 0, 1];
bytes.extend([0_u8; 8]);
bytes.extend((1_u32 << 20).to_be_bytes());
bytes.extend([0_u8; 8]);
std::fs::write(&lying, &bytes).unwrap();
assert!(!has_signature_blob(&lying));
std::fs::remove_dir_all(&dir).ok();
}
/// The strongest form of this test is the same file on both sides of the
/// signature boundary. A freshly linked arm64 binary is already
/// `adhoc, linker-signed`, so "just compiled" cannot prove anything; removing
/// and re-adding the signature shows the answer follows the load command
/// rather than the file's name, size, or the parser's mood.
#[test]
fn the_answer_follows_the_load_command() {
let dir = std::env::temp_dir().join(format!("squid-trust-cc-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let source = dir.join("probe.c");
std::fs::write(&source, "int main(void){return 0;}\n").unwrap();
let binary = dir.join("probe");
let run = |program: &str, args: &[&str]| {
std::process::Command::new(program)
.args(args)
.status()
.map(|status| status.success())
.unwrap_or(false)
};
if !run(
"cc",
&["-o", &binary.to_string_lossy(), &source.to_string_lossy()],
) {
// No compiler here; the shape of the answer is still covered by the
// non-Mach-O test above.
std::fs::remove_dir_all(&dir).ok();
return;
}
if !run(
"codesign",
&["--remove-signature", &binary.to_string_lossy()],
) {
std::fs::remove_dir_all(&dir).ok();
return;
}
assert!(
!has_signature_blob(&binary),
"with the signature command removed, nothing should be reported"
);
assert!(
run("codesign", &["-s", "-", &binary.to_string_lossy()]),
"ad-hoc signing the probe should succeed"
);
assert!(
has_signature_blob(&binary),
"adding the signature command back must flip the answer"
);
std::fs::remove_dir_all(&dir).ok();
}
}

View File

@ -36,6 +36,7 @@ const PSEUDO_FS: &[&str] = &[
"rpc_pipefs", "rpc_pipefs",
"nsfs", "nsfs",
"autofs", "autofs",
"nullfs",
"msdos", "msdos",
"anon:osd", "anon:osd",
"SMB", "SMB",
@ -90,6 +91,16 @@ pub fn volumes_from_mounts(mounts: &[MountEntry]) -> Vec<Volume> {
if text.starts_with("/System/Volumes/Data") && !out.is_empty() { if text.starts_with("/System/Volumes/Data") && !out.is_empty() {
continue; continue;
} }
// Application wrappers (for example an app that mounts its bundle at a
// temporary path) are not disks a person can manage. Finder only shows
// real volumes at `/` and under `/Volumes`.
if cfg!(target_os = "macos")
&& text != "/"
&& !text.starts_with("/Volumes/")
&& !text.starts_with("/System/Volumes/")
{
continue;
}
if let Some((total, free)) = statvfs_for(&mount.mount_point) { if let Some((total, free)) = statvfs_for(&mount.mount_point) {
let key = (total.as_u64(), free.as_u64()); let key = (total.as_u64(), free.as_u64());
if seen_capacity.contains(&key) { if seen_capacity.contains(&key) {
@ -266,4 +277,19 @@ mod tests {
}]; }];
assert!(volumes_from_mounts(&mounts).is_empty()); assert!(volumes_from_mounts(&mounts).is_empty());
} }
#[test]
fn app_wrapper_mounts_are_not_volumes() {
let mount_point = std::env::temp_dir();
let mounts = vec![MountEntry {
mount_point: mount_point.clone(),
device: "/Applications/X.app/Wrapper".into(),
fstype: "nullfs".into(),
}];
assert!(
volumes_from_mounts(&mounts).is_empty(),
"a nullfs app wrapper at {} must not look like a disk",
mount_point.display()
);
}
} }

View File

@ -149,6 +149,26 @@ fn uninstall_program(uninstall_string: &str) -> Option<PathBuf> {
candidate.exists().then_some(candidate) candidate.exists().then_some(candidate)
} }
/// `DisplayIcon` is a path with an optional icon index, usually quoted:
/// `"C:\Program Files\App\app.exe",0`. The file manager accepts the path
/// without the index and returns the application's default icon.
fn display_icon_path(value: Option<String>) -> Option<PathBuf> {
let raw = value?.trim().to_string();
let unquoted = raw
.strip_prefix('"')
.and_then(|value| value.split('"').next())
.unwrap_or(&raw)
.trim();
let without_index = unquoted
.rsplit_once(',')
.filter(|(_, index)| index.trim().parse::<i32>().is_ok())
.map(|(path, _)| path)
.unwrap_or(unquoted)
.trim();
let path = PathBuf::from(without_index);
path.exists().then_some(path)
}
impl Platform for Windows { impl Platform for Windows {
fn id(&self) -> PlatformId { fn id(&self) -> PlatformId {
PlatformId::Windows PlatformId::Windows
@ -189,6 +209,27 @@ impl Platform for Windows {
None => String::new(), None => String::new(),
} }
} }
fn graphics_adapter(&self) -> String {
let Ok(class) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey_with_flags(
r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}",
KEY_READ,
) else {
return String::new();
};
let mut adapters = Vec::new();
for name in class.enum_keys().flatten() {
let Ok(adapter) = class.open_subkey_with_flags(&name, KEY_READ) else {
continue;
};
let Some(description) = str_value(&adapter, "DriverDesc") else {
continue;
};
if !adapters.contains(&description) {
adapters.push(description);
}
}
adapters.join(" · ")
}
fn app_sources(&self) -> Vec<AppSource> { fn app_sources(&self) -> Vec<AppSource> {
let env = |key: &str| std::env::var_os(key).map(PathBuf::from); let env = |key: &str| std::env::var_os(key).map(PathBuf::from);
let mut dirs: Vec<PathBuf> = vec![ let mut dirs: Vec<PathBuf> = vec![
@ -271,6 +312,7 @@ impl Platform for Windows {
name: display_name, name: display_name,
bundle_id: None, bundle_id: None,
path, path,
icon_source: display_icon_path(str_value(&key, "DisplayIcon")),
version: str_value(&key, "DisplayVersion"), version: str_value(&key, "DisplayVersion"),
size, size,
source: source.into(), source: source.into(),

View File

@ -65,6 +65,9 @@ fn macos_battery() -> Option<Battery> {
battery.cycle_count = cycles; battery.cycle_count = cycles;
battery.temperature_c = temp; battery.temperature_c = temp;
} }
if let Some(health) = maximum_capacity() {
battery.health_percent = Some(health);
}
Some(battery) Some(battery)
} }
@ -129,19 +132,77 @@ fn battery_details() -> Option<(Option<u8>, Option<u32>, Option<f32>)> {
.ok() .ok()
.filter(|output| output.status.success())?; .filter(|output| output.status.success())?;
let text = String::from_utf8_lossy(&output.stdout); let text = String::from_utf8_lossy(&output.stdout);
let design = find_number(&text, "DesignCapacity"); let health = health_from_ioreg(&text);
let max = find_number(&text, "MaxCapacity");
let health = match (design, max) {
(Some(design), Some(max)) if design > 0 => {
Some(((max as f64 / design as f64) * 100.0).round() as u8)
}
_ => None,
};
let cycles = find_number(&text, "CycleCount").map(|value| value as u32); let cycles = find_number(&text, "CycleCount").map(|value| value as u32);
let temp = find_number(&text, "Temperature").map(|tenths| tenths as f32 / 100.0); let temp = find_number(&text, "Temperature").map(|tenths| tenths as f32 / 100.0);
Some((health, cycles, temp)) Some((health, cycles, temp))
} }
/// macOS already publishes the same figure it shows in System Settings. Read it
/// once every ten minutes rather than deriving it from `MaxCapacity`, which on
/// Apple Silicon is a percentage rather than a mAh reading.
#[cfg(target_os = "macos")]
fn maximum_capacity() -> Option<u8> {
use std::sync::Mutex;
use std::time::{Duration, Instant};
static CACHE: Mutex<Option<(Instant, Option<u8>)>> = Mutex::new(None);
let stale = CACHE
.lock()
.ok()
.and_then(|guard| *guard)
.map(|(at, _)| at.elapsed() > Duration::from_secs(600))
.unwrap_or(true);
if !stale {
return CACHE
.lock()
.ok()
.and_then(|guard| guard.and_then(|(_, health)| health));
}
let output = std::process::Command::new("/usr/sbin/system_profiler")
.arg("SPPowerDataType")
.output()
.ok()
.filter(|output| output.status.success());
let health = output
.as_ref()
.and_then(|output| parse_maximum_capacity(&String::from_utf8_lossy(&output.stdout)));
if let Ok(mut guard) = CACHE.lock() {
*guard = Some((Instant::now(), health));
}
health
}
#[cfg(target_os = "macos")]
fn parse_maximum_capacity(text: &str) -> Option<u8> {
let line = text
.lines()
.find(|line| line.trim_start().starts_with("Maximum Capacity:"))?;
let value = line.split_once(':')?.1.trim().trim_end_matches('%').trim();
value
.parse::<u8>()
.ok()
.filter(|value| (1..=100).contains(value))
}
#[cfg(target_os = "macos")]
fn health_from_ioreg(text: &str) -> Option<u8> {
let design = find_number(text, "DesignCapacity")?;
if design == 0 {
return None;
}
// `MaxCapacity` is a percentage on Apple Silicon. The raw/nominal fields are
// the actual mAh readings and are the only values that can form a ratio.
let maximum = find_number(text, "AppleRawMaxCapacity")
.filter(|value| *value > 0)
.or_else(|| find_number(text, "NominalChargeCapacity").filter(|value| *value > 0))?;
Some(
((maximum as f64 / design as f64) * 100.0)
.round()
.min(100.0) as u8,
)
}
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn find_number(text: &str, key: &str) -> Option<u64> { fn find_number(text: &str, key: &str) -> Option<u64> {
let (_, after) = text.split_once(&format!("\"{key}\""))?; let (_, after) = text.split_once(&format!("\"{key}\""))?;
@ -228,6 +289,21 @@ mod tests {
assert!(parse_pmset(text).is_none()); assert!(parse_pmset(text).is_none());
} }
#[test]
#[cfg(target_os = "macos")]
fn maximum_capacity_is_read_from_the_os_health_figure() {
let text = " Health Information:\n Cycle Count: 516\n Maximum Capacity: 86%\n";
assert_eq!(parse_maximum_capacity(text), Some(86));
}
#[test]
#[cfg(target_os = "macos")]
fn apple_silicon_health_ignores_the_percentage_in_max_capacity() {
let text =
"\"DesignCapacity\" = 6075\n\"MaxCapacity\" = 100\n\"AppleRawMaxCapacity\" = 4911\n";
assert_eq!(health_from_ioreg(text), Some(81));
}
#[test] #[test]
#[cfg(any(target_os = "macos", target_os = "linux"))] #[cfg(any(target_os = "macos", target_os = "linux"))]
fn hhmm_parsing() { fn hhmm_parsing() {

View File

@ -117,6 +117,7 @@ pub struct HostInfo {
pub os_name: String, pub os_name: String,
pub os_version: String, pub os_version: String,
pub hardware: String, pub hardware: String,
pub gpu: String,
pub hostname: String, pub hostname: String,
pub user: String, pub user: String,
pub arch: String, pub arch: String,
@ -129,6 +130,7 @@ impl HostInfo {
os_name: platform.display_name(), os_name: platform.display_name(),
os_version: platform.os_version(), os_version: platform.os_version(),
hardware: platform.hardware_model(), hardware: platform.hardware_model(),
gpu: platform.graphics_adapter(),
hostname: hostname(), hostname: hostname(),
user: std::env::var("USER") user: std::env::var("USER")
.or_else(|_| std::env::var("USERNAME")) .or_else(|_| std::env::var("USERNAME"))
@ -643,30 +645,13 @@ fn vm_stat_details() -> Option<(Bytes, Bytes)> {
let now = now_ms(); let now = now_ms();
let previous = LAST.swap(now, Ordering::Relaxed); let previous = LAST.swap(now, Ordering::Relaxed);
static CACHE: std::sync::Mutex<Option<(Bytes, Bytes)>> = std::sync::Mutex::new(None); static CACHE: std::sync::Mutex<Option<(Bytes, Bytes)>> = std::sync::Mutex::new(None);
if now - previous > 5_000 || previous == 0 { if now.saturating_sub(previous) > 5_000 || previous == 0 {
let page_size = 4096u64;
let output = std::process::Command::new("/usr/bin/vm_stat") let output = std::process::Command::new("/usr/bin/vm_stat")
.output() .output()
.ok() .ok()
.filter(|out| out.status.success())?; .filter(|out| out.status.success())?;
let text = String::from_utf8_lossy(&output.stdout); let text = String::from_utf8_lossy(&output.stdout);
let mut compressor_pages = 0u64; let value = parse_vm_stat(&text)?;
let mut wired_pages = 0u64;
for line in text.lines() {
let mut parts = line.split(':');
let key = parts.next()?.trim();
let value = parts.next()?.trim().trim_end_matches('.').replace(' ', "");
let pages: u64 = value.parse().unwrap_or(0);
match key {
"Occupied by compressor" => compressor_pages = pages,
"Wired Pages" => wired_pages = pages,
_ => {}
}
}
let value = (
Bytes(compressor_pages * page_size),
Bytes(wired_pages * page_size),
);
if let Ok(mut guard) = CACHE.lock() { if let Ok(mut guard) = CACHE.lock() {
*guard = Some(value); *guard = Some(value);
} }
@ -676,6 +661,42 @@ fn vm_stat_details() -> Option<(Bytes, Bytes)> {
} }
} }
/// Apple Silicon uses 16 KiB pages, Intel Macs use 4 KiB. The header states the
/// size, and the two fields squid reports use different labels than older
/// versions of `vm_stat`; both facts made the previous parser return zero.
fn parse_vm_stat(text: &str) -> Option<(Bytes, Bytes)> {
let header = text.lines().next()?;
let (_, after_size) = header.split_once("page size of ")?;
let page_size: u64 = after_size
.chars()
.take_while(|character| character.is_ascii_digit())
.collect::<String>()
.parse()
.ok()?;
let mut compressor_pages = 0u64;
let mut wired_pages = 0u64;
for line in text.lines().skip(1) {
let Some((key, value)) = line.split_once(':') else {
continue;
};
let pages: u64 = value
.trim()
.trim_end_matches('.')
.replace(' ', "")
.parse()
.unwrap_or(0);
match key.trim().trim_matches('"') {
"Pages occupied by compressor" => compressor_pages = pages,
"Pages wired down" => wired_pages = pages,
_ => {}
}
}
Some((
Bytes(compressor_pages.saturating_mul(page_size)),
Bytes(wired_pages.saturating_mul(page_size)),
))
}
fn net_rates(networks: &Networks, seconds: f64) -> NetRate { fn net_rates(networks: &Networks, seconds: f64) -> NetRate {
let mut rx = 0u64; let mut rx = 0u64;
let mut tx = 0u64; let mut tx = 0u64;
@ -966,6 +987,18 @@ mod tests {
assert_eq!(stats.percent_used(), 100); assert_eq!(stats.percent_used(), 100);
} }
#[test]
fn vm_stat_uses_the_reported_page_size_and_fields() {
let text = "\
Mach Virtual Memory Statistics: (page size of 16384 bytes)\n\
Pages free: 96476.\n\
Pages wired down: 122963.\n\
Pages occupied by compressor: 151882.\n";
let (compressed, wired) = parse_vm_stat(text).expect("vm_stat");
assert_eq!(wired, Bytes(122_963 * 16_384));
assert_eq!(compressed, Bytes(151_882 * 16_384));
}
/// The feature, end to end: a sample that still describes its pid stops it. /// The feature, end to end: a sample that still describes its pid stops it.
#[test] #[test]
fn a_process_stops_when_its_sample_asks_it_to() { fn a_process_stops_when_its_sample_asks_it_to() {

View File

@ -889,7 +889,6 @@ impl App {
}; };
panel.buckets.insert(category, (total, count)); panel.buckets.insert(category, (total, count));
} }
Event::Metered { .. } => {}
Event::Deleted { path, freed } => { Event::Deleted { path, freed } => {
self.push_log(format!( self.push_log(format!(
"removed {} ({})", "removed {} ({})",
@ -2603,6 +2602,7 @@ mod tests {
name: "SquidTest".to_string(), name: "SquidTest".to_string(),
bundle_id: Some("com.nexsquid.test".to_string()), bundle_id: Some("com.nexsquid.test".to_string()),
path: bundle.clone(), path: bundle.clone(),
icon_source: None,
version: Some("1.0".to_string()), version: Some("1.0".to_string()),
size: Bytes(0), size: Bytes(0),
source: "test".to_string(), source: "test".to_string(),
@ -2699,6 +2699,7 @@ mod tests {
name: "SquidTest".into(), name: "SquidTest".into(),
bundle_id: Some("com.example.SquidTest".into()), bundle_id: Some("com.example.SquidTest".into()),
path: path.clone(), path: path.clone(),
icon_source: None,
version: None, version: None,
size: Bytes(0), size: Bytes(0),
source: "test".into(), source: "test".into(),

View File

@ -552,7 +552,7 @@ impl Palette {
if highlight { if highlight {
return Self::selected(); return Self::selected();
} }
let band = if index % 2 == 0 { let band = if index.is_multiple_of(2) {
Self::card_bg() Self::card_bg()
} else { } else {
Self::card_bg_alt() Self::card_bg_alt()

View File

@ -2045,6 +2045,7 @@ mod tests {
name: "Demo".into(), name: "Demo".into(),
bundle_id: Some("com.example.Demo".into()), bundle_id: Some("com.example.Demo".into()),
path: "/Applications/Demo.app".into(), path: "/Applications/Demo.app".into(),
icon_source: None,
version: Some("1.0".into()), version: Some("1.0".into()),
size: Bytes(1 << 20), size: Bytes(1 << 20),
source: "Applications".into(), source: "Applications".into(),
@ -2604,6 +2605,7 @@ mod tests {
.map(|index| AppInfo { .map(|index| AppInfo {
name: format!("Sq{index:02}"), name: format!("Sq{index:02}"),
path: format!("/Applications/Sq{index:02}.app").into(), path: format!("/Applications/Sq{index:02}.app").into(),
icon_source: None,
source: "Applications".into(), source: "Applications".into(),
size: Bytes(1 << 20), size: Bytes(1 << 20),
..Default::default() ..Default::default()

View File

@ -23,25 +23,22 @@
## crate 依赖图 ## crate 依赖图
``` | 层 | crate | 依赖 |
┌──────────────┐ | --- | --- | --- |
│ squid-core │ 模型 / 字节 / 路径 / 安全策略 / 设置 / 账本 / 进度 | 0 | `squid-core` | —(不知道任何其它 crate 的存在)|
└──────┬───────┘ | 1 | `squid-platform` | core |
┌─────────┼──────────┐ | 1 | `squid-rules` | core, platform |
┌──────▼─────┐ ┌─▼────────┐ │ | 1 | `squid-stats` | core, platform |
│ squid- │ │ squid- │ │ ← 只依赖 core | 1 | **`squid-guard`** | core, platform |
│ platform │ │ rules │ │ | 2 | `squid-engine` | core, platform, rules, stats |
└──────┬─────┘ └─┬────────┘ │ | 3 | `squid-tui` | core, platform, rules, stats, engine |
│ │ │ | 4 | `squid-cli` | 以上全部(含 guard)|
┌────▼─────────▼───────┐ │ ┌────────────┐ | — | `src-tauri` | core, platform, guard, engine, stats |
│ squid-engine │◄─┼───┤ squid-stats│ ← 依赖 core 与 platform
└────┬────────────┬────┘ │ └─────┬──────┘
┌───────▼──┐ ┌────▼───────▼──┐ │
│ squid-tui│ │ squid-cli │◄─────┘
└──────────┘ └───────────────┘
```
依赖方向严格单向,`squid-core` 不知道其它任何 crate 的存在。 `squid-guard` 与 `squid-engine` 在第 1 / 第 2 层并列,而不是叠在一起:清理引擎的一切
前提都是「这东西可再生,删了没事」,而隔离的全部难度恰恰在于「这是用户自己的文件,
必须能原样放回去」。所以 guard 只依赖 `core` 与 `platform`,复用 `Progress`、
`CancelToken` 与 `paths`,但不碰删除路径。
### squid-core ### squid-core
@ -142,6 +139,66 @@ ratatui + crossterm。六个面板 `Cleanup / Uninstall / Purge / Storage / Stat
路径列只截断不补齐,因此 `item_row` 末尾还会按显示宽度补一段同色空格,让高亮条一直顶到卡片右边框。 路径列只截断不补齐,因此 `item_row` 末尾还会按显示宽度补一段同色空格,让高亮条一直顶到卡片右边框。
- **一个 widget 只有一套下标**:`ListState::selected` 是 ratatui 用来定位滚动窗口的行号,高亮却由每一行自己画,两者必须数同一批行。卸载列表把「大小/名称/版本」表头(筛选时还多一行 filter chip)和条目一起塞进同一个 `List`,`selected` 就此比样式多算了一两行:第一屏看不出来,列表一超过一页,窗口按「光标上面那一行」定位,高亮行被挤出可视区,用户看到的是「下翻之后没有高亮了」——Mac 与 Windows 同因,因为它跟终端无关。清理面板从不出现这个现象,`ScanPanel::lines` 里只有条目,标题挂在 card 的 block 上。现在的写法把表头和 filter chip 当作 chrome 单独走一段 `Layout`:`Paragraph` 拿上面,`List` 只拿条目。`the_app_under_the_cursor_is_the_row_that_is_on_screen` 遍历每一个光标位置(含筛选态)断言「光标那一行就是屏幕上那一行、且带着强调色与加粗」,因为它无法靠猜某个卡片高度通过。 - **一个 widget 只有一套下标**:`ListState::selected` 是 ratatui 用来定位滚动窗口的行号,高亮却由每一行自己画,两者必须数同一批行。卸载列表把「大小/名称/版本」表头(筛选时还多一行 filter chip)和条目一起塞进同一个 `List`,`selected` 就此比样式多算了一两行:第一屏看不出来,列表一超过一页,窗口按「光标上面那一行」定位,高亮行被挤出可视区,用户看到的是「下翻之后没有高亮了」——Mac 与 Windows 同因,因为它跟终端无关。清理面板从不出现这个现象,`ScanPanel::lines` 里只有条目,标题挂在 card 的 block 上。现在的写法把表头和 filter chip 当作 chrome 单独走一段 `Layout`:`Paragraph` 拿上面,`List` 只拿条目。`the_app_under_the_cursor_is_the_row_that_is_on_screen` 遍历每一个光标位置(含筛选态)断言「光标那一行就是屏幕上那一行、且带着强调色与加粗」,因为它无法靠猜某个卡片高度通过。
### squid-guard
恶意软件扫描、检测规则与可逆隔离。它是唯一一个会**移动用户文件**的新 crate,所以它的
设计重心不是「能找到什么」,而是「在没有 Developer ID 与 Authenticode 的发布方式下,
怎样做到不伤人」。
| 模块 | 职责 |
| --- | --- |
| `scan` | 扫描编排:`ScanTarget::{Quick,Full,Paths}` → 采集 → 判定 → `ScanReport`。`Guard` 装配规则、哈希表、缓存与排除项 |
| `rules` | YARA-X `Detector`、`HashIndex`,以及决定「这个文件值不值得打开」的门(`plausible_by_name_in` / `worth_scanning_in` / `layout_of`)|
| `heuristics` | 无签名 / 世界可写 / 登录项 / 伪装名称,产 `Evidence`;`CEILING = Suspicious`,永远到不了 Confirmed |
| `findings` | `Confidence::{Advisory,Suspicious,Confirmed}`、`Evidence`(带 `key()` 与 `summary()`)、`Finding` |
| `coverage` | 每个 root 的结果:walked / denied / absent。**读不到不等于干净**,二者在报告里是不同的值 |
| `quarantine` | 账本 + 惰性对象 + 字节一致恢复 |
| `intel` | 规则包格式、验签、安装与回退 |
| `store` | 判定缓存(按文件身份)+ 上一次扫描 + 最近活动,落 `<state>/security/` |
`squid-guard` 刻意不依赖 `squid-engine`:清理引擎的一切前提都是「这东西可再生,删了
没事」,而隔离的全部难度恰恰在于「这是用户自己的文件,必须能原样放回去」。它复用
`Progress`、`CancelToken` 与 `paths`,但不复用删除路径。
三条不变量,都有测试钉住:
1. **扫描不删除任何东西。** 唯一会移动文件的是隔离,而隔离只接受后端发出的 finding id。
界面永远不能提交一个路径来要求隔离:`security_quarantine(finding_id)` 查的是后端自己
存下的那份扫描,再核对哈希、大小与文件身份;扫描之后被换过的文件会被拒绝,而不是按
一行过期记录搬走。
2. **只有 `confirmed` 可能被自动隔离**,且默认关闭(`security.auto_quarantine = false`)。
`suspicious` 只报告。级别由两处分别决定后取最大值:已发布探测器(哈希 / YARA)按自己的
等级说话,启发式则要求**两个信号互相印证**——单个「无签名」是提示,「无签名 + 开机启动」
才是可疑。这一条是实测逼出来的:一台干净的 Mac 按旧规则会报出 975 条可疑,其中 951 条
只是「带执行位的文本文件」,而这么长的列表最终的下场是被人整个忽略掉。
3. **不上传。** 这个 crate 里没有任何函数接收本地路径再发出网络请求。规则包只下载。
`xprotect update` 永不被调用:这台机器要不要向 Apple 的服务器取定义,不是第三方 App 能
替用户决定的事。`squid-platform::protection` 只读 `status` / `version` / `spctl`,读不到
就报 `known = false`,界面据此显示「无法确认」而不是绿色。
**门(gate)比规则更决定可用性。** 一次快速扫描会路过约 105 万个文件,其中 34 万个是没有
扩展名的数据文件。判定顺序按代价排列:名字(免费,遍历时已经在手)→ `stat`(大小、执行位)
→ 目录形状(bundle 内部只看主可执行文件与 `Info.plist`,否则光是 `/Applications` 就吃掉
十 GB)→ 只有浏览器下载目录才去读头八个字节。用户自己指名的目录是例外:那里按内容判定,
因为 `eicar.com` 的后缀和它的身份本来就互相矛盾。最终约 1,900 个文件 / 6.2 GB,冷启动
26 秒、命中缓存 9 秒。
一处性能教训值得留在这里:判定缓存与候选去重原本都是 `Vec` 加 `paths::same_path` 线性
查找,而 `same_path` 每次比较都要重建一条路径的组件向量。15,000 个文件下这就是几十亿次
字符串分配——快速扫描跑十分钟、CPU 满核,看着像磁盘慢,其实是纯 CPU。现在两处都按
`paths::canonical_key` 建索引,并且有测试断言 `canonical_key` 与 `same_path` 判定一致:
键和判定不一致,就等于把一份缓存结论用到了另一个文件身上。
隔离区不是废纸篓。对象被放进 Squid 自己的状态目录、清掉执行位、权限收紧到仅属主,账本与
对象放在一起,所以「隔离了一个登录项」意味着它下次开机真的不会起来。恢复按原始路径、模式
与时间戳放回,且恢复前要确认。
规则包与安装包用**不同的密钥**签名:轮换发布密钥不应该顺手改变谁能推规则,泄漏了安装包
密钥也不应该变成一条规则注入路径。包格式把 manifest 与 source 存在同一个文件里,读到什么
就一起验什么,避免「新包配旧 manifest」这种两半漂移。任何一次更新失败都保留上一版可用
规则,并且会清空判定缓存——旧规则给出的结论不是新规则给的结论。
### squid-cli ### squid-cli
clap derive。约定: clap derive。约定:

View File

@ -1,6 +1,6 @@
# Nex 应用视觉规范 # Nex 应用视觉规范
版本:1.0 版本:1.1
状态:Nex 系列应用统一标准 状态:Nex 系列应用统一标准
基准实现:`nex_shift` 的主色系 基准实现:`nex_shift` 的主色系
@ -12,7 +12,8 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
- 主操作、选中态、焦点环和进度使用 Nex 主色。 - 主操作、选中态、焦点环和进度使用 Nex 主色。
- 页面底色、卡片和正文使用暖中性色,不使用冷蓝色底。 - 页面底色、卡片和正文使用暖中性色,不使用冷蓝色底。
- 绿色、红色、黄色只表达成功、危险和警告,不作为品牌主色。 - 绿色、红色、黄色只表达成功、危险和警告,不作为品牌主色。
- 分类色可以保留各自的语义色,但不得替代主操作色。 - 图表、分类和装饰只使用主色、暖中性色或成功/警告/危险状态色。
- 不引入蓝色、紫色、青色、粉色等第二品牌色;状态色也不得用于装饰。
- 新界面必须引用 `src/styles.css` 中的 `--nex-*` 常量,不写新的主色十六进制值。 - 新界面必须引用 `src/styles.css` 中的 `--nex-*` 常量,不写新的主色十六进制值。
## 2. 品牌常量 ## 2. 品牌常量
@ -39,6 +40,19 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
主色高亮需要透明度时使用 `rgba(var(--nex-primary-rgb), α)`,其中 主色高亮需要透明度时使用 `rgba(var(--nex-primary-rgb), α)`,其中
`--nex-primary-rgb` 为 `242, 106, 51`。 `--nex-primary-rgb` 为 `242, 106, 51`。
### 状态色
| 常量 | 值 | 用途 |
| --- | --- | --- |
| `--nex-success` / `-strong` / `-soft` | `#17865F` / `#126D4C` / `#E7F8F1` | 完成、安全、已授权 |
| `--nex-warning` / `-strong` / `-soft` | `#A97729` / `#8C6C40` / `#FFF8E9` | 警告、需要注意 |
| `--nex-danger` / `-strong` / `-soft` | `#C85A62` / `#A64048` / `#FFEDEF` | 错误、危险操作 |
对应的 `--nex-success-rgb`、`--nex-warning-rgb`、`--nex-danger-rgb`
用于状态色透明度。组件通过 `.tone-primary`、`.tone-success`、
`.tone-warning`、`.tone-danger`、`.tone-neutral` 五种语义色调取色,
不新增分类专用色调。
## 3. 图标渐变 ## 3. 图标渐变
应用图标的品牌渐变沿用 Shift: 应用图标的品牌渐变沿用 Shift:
@ -47,7 +61,8 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
- 中段 `#FF6B35` - 中段 `#FF6B35`
- 终点 `#C66BFF` - 终点 `#C66BFF`
图标主体的描边和阴影必须使用暖色,不得保留旧版蓝色。 图标主体允许保留应用图标自身的暖橙渐变与粉色高光;它们属于图标资产,
不得扩展为界面装饰色。图标主体的描边和阴影必须使用暖色,不得保留旧版蓝色。
### 侧栏品牌锁定 ### 侧栏品牌锁定
@ -95,18 +110,26 @@ Squid 以及后续 Nex 应用不得再各自定义蓝色或其它颜色的主操
- 正文不使用纯黑;标题使用 `--nex-ink-strong`。 - 正文不使用纯黑;标题使用 `--nex-ink-strong`。
- 更新面板面向使用者,只展示当前系统版本、版本状态、更新说明、进度与操作; - 更新面板面向使用者,只展示当前系统版本、版本状态、更新说明、进度与操作;
更新地址、安装包文件名和哈希留在后端校验流程中,不进入常规界面。 更新地址、安装包文件名和哈希留在后端校验流程中,不进入常规界面。
- 下载完成后的“放弃”使用中性描边按钮:34px 高、9px 圆角、暖白半透明表面、
`--nex-ink` 文字;悬停仅切换主色描边与白色表面,与 Shift 保持一致。
- 软件更新不再重复显示“已是最新版本”;当前版本只在系统信息面板中展示,
只有发现更新包时才展开版本变化与操作区。
## 6. 旧变量兼容 ## 6. 语言与本地化
现有组件仍引用 `--blue`、`--blue-deep`、`--blue-soft`。这三个变量已经 - 首次启动默认跟随系统语言:macOS 读取 `AppleLocale` / `AppleLanguages`,
分别别名为 `--nex-primary`、`--nex-primary-strong`、`--nex-primary-soft`, Windows 读取 `GetUserDefaultUILanguage`,Linux 读取标准 locale 环境变量。
因此不会再渲染蓝色。新增代码应直接使用 `--nex-*` 常量;迁移旧组件时 - 设置中只提供“简体中文”和“English”两个语言选项;尚未手动选择时,选中项反映当前系统语言。
可以逐步移除 `--blue-*` 别名,但不得改回独立颜色值。 - 手动选择语言会写入 `config.toml` 的 `language`,后续启动继续使用该选择。
- 托盘菜单与主界面使用同一语言,并在切换后立即刷新。
- 当前支持中文与英文,其他系统语言回退到英文。
## 7. 验收 ## 7. 验收
- 全应用不出现蓝色主按钮、蓝色选中态或蓝色焦点环。 - 全应用不出现蓝色、紫色、青色或粉色界面装饰;品牌色只有橙色。
- 状态色只用于成功、警告和危险,不作为卡片或图表的分类装饰色。
- 页面底色为 `#F5EEE7`,面板为暖白,不使用冷蓝渐变。 - 页面底色为 `#F5EEE7`,面板为暖白,不使用冷蓝渐变。
- Settings、首次启动权限卡和更新面板共享同一套主色。 - Settings、首次启动权限卡和更新面板共享同一套主色。
- 应用图标与界面使用同一组暖色品牌常量。 - 应用图标与界面使用同一组暖色品牌常量。
- 正文和标签不小于 11px,标题使用统一字号阶梯,不出现 7–10px 的正文。 - 正文和标签不小于 11px,标题使用统一字号阶梯,不出现 7–10px 的正文。
- 默认语言与系统一致,切换语言后主界面和托盘同步更新。

View File

@ -45,22 +45,119 @@ cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings
| Screen | What it does | | Screen | What it does |
| --- | --- | | --- | --- |
| Computer overview | Smart scan entry, disk health, cleanup result categories and live CPU/memory/storage summaries | | Overview | Security status strip, cleanup scan entry, disk health, cleanup result categories and live CPU/memory/storage summaries |
| Daily cleanup | Runs the normal cleanup rule set, groups results by category, supports per-item and per-category selection, Trash or permanent deletion, then offers undo through History | | Daily cleanup | Runs the normal cleanup rule set, groups results by category, supports per-item and per-category selection, Trash or permanent deletion, then offers undo through History |
| Uninstall apps | Reads installed apps, builds an app-specific removal plan, shows leftover paths and warnings, then uninstalls selected items | | Uninstall apps | Reads installed apps, builds an app-specific removal plan, shows leftover paths and warnings, then uninstalls selected items |
| Deep Clean | Searches chosen project roots for regenerable build artefacts with Git and file-age protections | | Deep Clean | Searches chosen project roots for regenerable build artefacts with Git and file-age protections |
| Permissions (Windows) | Startup entries from Run keys, startup folders and scheduled tasks; shell context-menu handlers; popup-window rules and the popup watcher |
| Security | XProtect / Defender status, scan coverage, findings by confidence, quarantine and restore, recent security activity |
| Startup items | LaunchAgents, LaunchDaemons, login items, registry Run keys, startup folders, scheduled tasks and services; disable and re-enable the ones the current user owns |
| Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files | | Storage | Measures a chosen folder, exposes the largest children, drills down, and finds the largest files |
| Real-time monitor | Live CPU, memory, network, disk, battery, volume and process data; process termination asks for confirmation | | Real-time monitor | Two tabs. **Performance**: live CPU, memory, network, disk, battery, volume and process data, plus the desktop-widget switch. **Processes**: the whole process table with signature and startup-item columns, and process termination after confirmation |
| Desktop widget | A borderless desktop-layer monitor opened from Real-time monitor, with status rings, network and disk curves, storage bars, and all settings in a dropdown at the top of the widget |
| History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin | | History | Lists cleanup sessions, shows the ledger, restores files that are still in Trash/Recycle Bin, and opens the bin |
| Settings | Language, deletion mode, history retention, protected paths, local file locations, and software updates | | Settings | Chinese/English language selection that defaults to the system language, launch at login, the security section (scan schedule, notifications, auto-quarantine, rule-pack updates, scan exclusions), deletion mode, history retention, protected paths, local file locations, and software updates |
`⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+8` on Windows switch screens. `⌘1`–`⌘8` on macOS and `Ctrl+1`–`Ctrl+9` on Windows switch screens, in sidebar
order. On Windows: `1` overview, `2` daily cleanup, `3` uninstall apps,
`4` deep clean, `5` permissions, `6` storage, `7` real-time monitor,
`8` security, `9` startup items. macOS omits the Windows-only Permissions
screen, so `5`–`8` shift up by one.
The sidebar groups these into **Maintenance** (overview, daily cleanup,
uninstall apps, deep clean, and Permissions on Windows), **Protection**
(security, startup items) and **Insights** (storage, real-time monitor), with
History and Settings pinned at the bottom.
The two new screens reuse the interface vocabulary the older screens already
had rather than introducing a second one: `.panel` for a card, `.status-chip` for
a status, `.search-field`, `.icon-button`, `.text-button`, `.metric-icon` with a
`tone-*` class, `.settings-row` for a switch, `.empty-inline` for an empty list.
Findings, startup entries and quarantined files share one row shape
(`.item-row` / `.item-main` / `.item-copy` / `.item-actions`), so a change to how
a row looks is one edit that reaches all three. Copy stays to one sentence per
screen and per control: a count sits on the filter that produces it, not also in
a summary line above it.
## Security page
Squid scans when asked. There is no daemon, no kernel extension and no
privileged helper, so XProtect and Defender remain the real-time protection and
this page only reads what they report.
- **Scan modes.** Quick covers application bundles, login-item targets, browser
extensions and the folders a browser writes to. Full adds the user's Library
and document folders and must be started deliberately. Custom scans the paths
chosen. All three are cancellable.
- **Confidence.** `confirmed` means a published hash or signature rule matched
and is the only level that may ever be moved automatically. `suspicious` needs
two corroborating signals and is report-only. `advisory` is a single weak
signal, such as an unsigned file that does not start at login.
- **Coverage.** A scan that could not read a folder says so. The page never
renders "clean" for a range it did not look at, and unreadable folders are
listed rather than omitted.
- **Nothing is uploaded.** No file name, hash, finding or quarantined file
leaves the machine. Rule packs are downloaded; nothing is sent back.
- **Quarantine is reversible.** Findings are moved by backend-issued id, never
by a path the interface supplies. The file is re-verified against the hash the
scan recorded, stored without the execute bit, and restoring returns the
original bytes, mode and timestamps.
## Tray ## Tray
Squid keeps running after its main window is closed. The tray menu can reopen Squid keeps running after its main window is closed. The tray menu can reopen
the window and jump directly to Daily cleanup, Uninstall apps or Deep Clean. the window, start a malware scan, and jump directly to Security, Startup items,
Use **Quit Squid** in the same menu to stop the background process. Daily cleanup, Uninstall apps, Deep Clean or the desktop widget. One disabled row
states the current protection status — the count of unhandled confirmed findings,
"not scanned yet" before the first scan, and "scanning…" while one is running.
The tray follows the active interface language. Use **Quit Squid** in the same
menu to stop the background process.
The tray mark is a transparent monochrome asset. macOS receives it with
`.icon_as_template(true)`, so the system draws it in the correct menu-bar colour
for light and dark appearances instead of pasting a coloured square onto the
bar. Windows and Linux keep the same silhouette in gray.
## Permissions (Windows)
The Permissions screen is a Windows-only destination and is hidden from the
macOS sidebar, where the Startup items screen already covers LaunchAgents,
LaunchDaemons and login items with the same safety rules. On Windows it lists:
- startup entries from `Run` keys, startup folders and scheduled tasks;
- shell context-menu handlers grouped by file, folder, desktop, drive and
all-object surfaces;
- popup windows with rules to block or allow them and a background watcher.
Every enable/disable action goes through the backend's inventory; the page never
submits a raw registry or filesystem path.
## Desktop widget
The desktop widget is switched on from Real-time monitor and is a separate Tauri
webview window labelled `widget`, not a WidgetKit extension. It shares the live
sampler with the Real-time monitor but polls at its own 2/5/10-second cadence and
pauses while hidden.
- The gear at the top of the widget opens a dropdown containing every setting:
panel switches, opacity, refresh rate, dock corner and fold memory.
- Up to four cards: status rings (CPU, memory, and GPU when the OS exposes a
busy counter), network throughput, disk I/O, and storage volumes.
- The window is borderless, transparent and resizable only by its content. It
docks to a chosen corner and remembers a manual drag position.
- On macOS it uses `BelowNormal` window level, appears on every Space, and is
non-focusable with `accept_first_mouse`, so it sits with the desktop and never
takes keyboard focus from the app you are using.
- On Windows it is parked with `SetWindowPos(HWND_BOTTOM, SWP_NOACTIVATE)` for
the same desktop-layer behaviour.
- Opacity is capped to 90–100% so text stays readable over busy wallpapers.
The master switch and the tray item share one state; settings persist in
`widget.json` beside `manage.json`.
**Settings → Startup** registers the app for the current user only. macOS
uses a user LaunchAgent, Windows uses the current-user Run key, and Linux uses
an XDG autostart desktop entry. Enabling or disabling launch at login does not
require administrator access.
## Safety boundary ## Safety boundary
@ -115,6 +212,8 @@ The update implementation mirrors `nex_shift`:
bytes. bytes.
- The application checks at most once a day when automatic checks are enabled; - The application checks at most once a day when automatic checks are enabled;
the last-check day lives in `updates.json`. the last-check day lives in `updates.json`.
- A verified download can be installed and restarted, or discarded with the
neutral outlined action shared with `nex_shift`.
- macOS mounts the DMG after exit and swaps `Squid.app` with rollback on failure. - macOS mounts the DMG after exit and swaps `Squid.app` with rollback on failure.
- Windows waits for `squid-desktop.exe` to exit, runs the same NSIS installer - Windows waits for `squid-desktop.exe` to exit, runs the same NSIS installer
silently, then relaunches it from `%LOCALAPPDATA%\Programs\Squid`. silently, then relaunches it from `%LOCALAPPDATA%\Programs\Squid`.

1114
docs/ROADMAP.md 100644

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,9 @@ squid 是一个「以删除为职责、以不删错为底线」的工具。它
- squid 以当前用户身份运行,**不需要** root,也不安装任何 launch agent / 服务 / 内核扩展。 - squid 以当前用户身份运行,**不需要** root,也不安装任何 launch agent / 服务 / 内核扩展。
- 非 root 时 `SafetyPolicy::user_only()` 生效,家目录之外的路径一律不删除;只有显式用管理员权限运行时才切换到 `SafetyPolicy::system()`。 - 非 root 时 `SafetyPolicy::user_only()` 生效,家目录之外的路径一律不删除;只有显式用管理员权限运行时才切换到 `SafetyPolicy::system()`。
- 需要管理员权限的规则(`needs_admin`)在普通权限下只报告、不执行;`squid clean --user-only` 可以彻底跳过它们。 - 需要管理员权限的规则(`needs_admin`)在普通权限下只报告、不执行;`squid clean --user-only` 可以彻底跳过它们。
- 不联网:`Cargo.toml` 的依赖树里没有 HTTP 客户端,squid 不上传任何遥测、路径或文件名。 - 默认不联网。清理、卸载、深度清理与实时监控全都在本地完成,代码里没有 HTTP 客户端
(下载规则包与应用更新走 `curl` / `Invoke-WebRequest` 子进程,见下)。**squid 从不上传
任何遥测、路径、哈希、扫描结果或被隔离的文件。**
## Full Disk Access(macOS) ## Full Disk Access(macOS)
@ -41,9 +43,58 @@ squid 是一个「以删除为职责、以不删错为底线」的工具。它
| `brew uninstall --cask --force` | App 由 Homebrew 安装时优先交给 brew 处理 | 是,仅 `squid uninstall` 确认之后,且只在检测到对应 cask 时 | | `brew uninstall --cask --force` | App 由 Homebrew 安装时优先交给 brew 处理 | 是,仅 `squid uninstall` 确认之后,且只在检测到对应 cask 时 |
| `flatpak` / `snap` | Linux 应用清单与卸载建议 | 清单只读;卸载建议以提示形式给出 | | `flatpak` / `snap` | Linux 应用清单与卸载建议 | 清单只读;卸载建议以提示形式给出 |
安全功能新增的外部命令,同一套规则(不经过 shell、参数不来自不可信输入):
| 命令 | 用途 | 是否修改系统 |
| --- | --- | --- |
| `/usr/bin/xprotect status/version`、`spctl --status` | 读取 XProtect 与 Gatekeeper 状态 | 否,只读。**`xprotect update` 永不调用**:那台机器要不要向 Apple 取定义,不是第三方 App 能替用户决定的 |
| `powershell.exe`(Defender / SecurityCenter2 查询)、注册表 `Microsoft\Windows Defender` 的 `Signature Updates` | 读取 Defender / 第三方杀软与定义版本 | 否,只读;不会开启、关闭或更新任何防护 |
| `codesign -dvvv --display` | 读取发布者的签名信息 | 否,只读 |
| `launchctl bootstrap/kickout` | 启用或停用**当前用户**的 LaunchAgent | 是,仅在启动项页确认之后;系统级条目在首版只读 |
| `schtasks /query /v /fo csv` | 列举计划任务 | 否,只读(首版不提供启停)|
| `curl` / `Invoke-WebRequest` | 下载规则包与更新清单 | 否,只下载;见「规则包的下载与验签」|
## 安全功能(guard)的边界
恶意软件扫描是 0.1.6 加入的能力,它的风险模型和「删错东西」不同:**它会移动文件**。
因此下面几条是被测试钉住的硬边界,而不是承诺。
- **扫描本身绝不删除或移动任何东西。** 唯一的移动来自隔离,而隔离必须由用户点下确认,
或由一个默认关闭的开关(`security.auto_quarantine`)触发。
- **隔离只接受后端发出的 finding id。** 前端提交路径的能力被拿掉了:`security_quarantine`
拿 id 去查后端自己存下的那次扫描,再核对哈希、大小与文件身份;扫描之后文件被换过就
拒绝移动。界面伪造一个路径出来,伪造不了一个 id。
- **只有 `confirmed` 可能自动隔离。** 这一级只能由精确 SHA-256 命中或签名级 YARA 规则到达;
启发式(无签名、路径可疑、开机自启)的上限是 `suspicious`,永远自动隔离不到它。
- **隔离是可逆的。** 对象进入 `<state>/security/quarantine/`,去掉执行位、权限收到仅属主,
账本记录原路径、模式、时间戳与哈希;恢复要求原字节、原权限一致,恢复前要确认。
永久删除只能从隔离区发起。
- **不跟随符号链接,不隔离系统目录、XProtect、squid 自身和隔离区自身。**
- **读不到不等于干净。** 每个扫描根的结果都记录在覆盖范围里(walked / denied / absent),
有缺口时界面必须同时列出未检查的范围,不能只显示「安全」。系统防护读不到时显示
「无法确认」,不显示绿色。
- **清理白名单与安全排除项是两份独立配置。** 把一个目录从清理里保护起来,不会让它
从此不被扫描;反过来,`config.toml` 的 `[security] scan_exclusions` 会让里面的威胁
不再被报告,所以新增排除项要二次确认。
## 规则包的下载与验签
- 内置规则离线可用;更新只是**下载**,没有请求携带任何本地信息——没有文件名、没有哈希、
没有扫描结果、没有被隔离的文件。
- 规则包用**独立于安装包的 Ed25519 密钥**签名(`SQUID_INTEL_PUBKEY`)。轮换发布密钥不应该
顺手改变谁能推规则,泄漏了安装包密钥也不应该变成一条规则注入路径。
- 清单必须验签,包必须核对大小与 SHA-256,而且必须在**装进去之前**先编译一遍:一份
YARA 拒绝的规则包永远不能成为 `current`,否则下一次扫描会在最不该失败的时候失败。
- manifest 与规则源码存在同一个文件里,读到什么就一起验什么,避免「新包配旧 manifest」。
- 验签失败、损坏或主动回滚时继续使用上一版可用规则,并且清空判定缓存——旧规则给出的
结论不是新规则给的结论。
- 未配置 feed 的构建(比如从源码直接 `cargo build`)不会联网,只用内置规则。
## 什么不属于安全问题 ## 什么不属于安全问题
- 规则没有覆盖到某个 App 的缓存 → 功能缺口,开 issue 即可。 - 规则没有覆盖到某个 App 的缓存 → 功能缺口,开 issue 即可。
- 某个恶意样本没被扫出来 → squid 不是 XProtect / Defender 的替代品,也不做实时拦截;
它是本地按需扫描 + 可逆隔离 + 启动项与进程的可见性。系统防护仍在做实时那部分。
- 磁盘空间没有你预期释放得多 → 可能是 APFS 快照或 purge 的年龄过滤,先用 `squid analyze` 对照。 - 磁盘空间没有你预期释放得多 → 可能是 APFS 快照或 purge 的年龄过滤,先用 `squid analyze` 对照。
- 需要 Full Disk Access 才能读到的目录 → macOS 的限制,见上。 - 需要 Full Disk Access 才能读到的目录 → macOS 的限制,见上。

View File

@ -17,6 +17,7 @@
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2.12.4", "@tauri-apps/api": "^2.12.4",
"@tauri-apps/plugin-dialog": "^2.8.3", "@tauri-apps/plugin-dialog": "^2.8.3",
"@tauri-apps/plugin-notification": "2",
"@tauri-apps/plugin-opener": "^2.7.2", "@tauri-apps/plugin-opener": "^2.7.2",
"lucide-react": "^0.468.0", "lucide-react": "^0.468.0",
"react": "^19.1.0", "react": "^19.1.0",

View File

@ -11,6 +11,9 @@ dependencies:
'@tauri-apps/plugin-dialog': '@tauri-apps/plugin-dialog':
specifier: ^2.8.3 specifier: ^2.8.3
version: 2.8.3 version: 2.8.3
'@tauri-apps/plugin-notification':
specifier: '2'
version: 2.8.0
'@tauri-apps/plugin-opener': '@tauri-apps/plugin-opener':
specifier: ^2.7.2 specifier: ^2.7.2
version: 2.7.2 version: 2.7.2
@ -849,6 +852,12 @@ packages:
'@tauri-apps/api': 2.12.4 '@tauri-apps/api': 2.12.4
dev: false dev: false
/@tauri-apps/plugin-notification@2.8.0:
resolution: {integrity: sha512-BB9Kk2emiNHyMjIQr3k/ye8RKD2RJeOPCjM5OZLF+4/pO6Kfjl9RtkX4hVCe1vqgbAx5HjHXjf0O8rtdW2F2dw==}
dependencies:
'@tauri-apps/api': 2.12.4
dev: false
/@tauri-apps/plugin-opener@2.7.2: /@tauri-apps/plugin-opener@2.7.2:
resolution: {integrity: sha512-LyybP1VSzTMQiaFYcsbAse47KpivlyXdLZMQzGLEnkgQacGESnpjAfFoQ6h5sqWgAdZDH9szYjPzHMpv0Sz+TQ==} resolution: {integrity: sha512-LyybP1VSzTMQiaFYcsbAse47KpivlyXdLZMQzGLEnkgQacGESnpjAfFoQ6h5sqWgAdZDH9szYjPzHMpv0Sz+TQ==}
dependencies: dependencies:

View File

@ -1,47 +0,0 @@
Squid 0.1.10 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
运行 Squid 才能修改,界面会给出明确提示。
安装
----
1. 运行 Squid-Setup-0.1.10-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
更新
----
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
还会验证清单的 Ed25519 签名。
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.10-win-x64.exe -Algorithm SHA256
提示
----
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
上右键退出),否则安装程序无法替换正在运行的程序文件。
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
按方便程度排序:
1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录
再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效);
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
3) 使用便携包 Squid-0.1.10-portable-win-x64.zip,解压后把 Squid 目录
内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。
- 桌面小工具在安装后默认开启,会出现在屏幕右上角;新版新增 CPU 面板
(总占用曲线 + 每核渐变占用柱),可在主程序「桌面小工具」页开关各面板。
- 清理新增「升级安装包」分类:应用升级后留在 AppData 的安装包(微信、
企业微信、WPS 等),放置超过 7 天才会被找出;删除确认时可一键跳过。

View File

@ -1,91 +0,0 @@
Squid 0.1.10 更新说明
新增
- 空间清理全面对齐专业清理工具的扫描体验(借鉴 Mole):
· 扫描时实时显示「已统计 12.8 万个文件 · 38.2 GB」滚动计数,进度条在真正
完成前最多走到 99%,不再出现「满了但还在转」的错觉;
· 各分类不再干等:哪个分类先算完就先在扫描界面出现(项数 + 大小);
· 清理点与文件行显示「12 个月未使用」休眠标签(超过 90 天没再写入的绿色
标注),配合大小一起帮你决定删不删;
· node_modules 等项目产物新增「可删依据」面板:锁文件 / 安装记录 / 有无
手工修改 / Git 状态 / 目录年龄逐条列出,被手改过的目录会红色警示;
· 低风险清理(≤40 项、不含升级包、复核全部通过)不再弹窗,底部绿色
确认条一步完成(Esc 取消);含升级包或大批量仍走确认对话框,对话框内
新增「刚刚逐路径复核过 N 项」折叠面板,展示删除前的最后一轮锁 / 白名单
/ 应用运行 / 路径消失复核结果;
· 清理完成后新增「有 N 项本次未处理」分组页:按原因(应用正在运行 /
需要管理员 / 已消失 / 白名单 / 受保护)归类,每组给下一步操作按钮;
· 结果列表可一键「导出清单」,生成 Markdown 文件(含每一项路径、大小、
依据与受保护项),方便留档或反馈。
- 存储空间页新增「隐藏的吃空间大户」:Windows 更新缓存、休眠文件、页面文件、
WinSxS 组件库、手机备份、90 天前的下载,逐项给出大小与下一步(查看 /
复制释放命令);同页文件夹测量结果缓存 10 分钟,秒开时标注「缓存数据 ·
上次测量 X 分钟前」并可一键重新测量,删除文件后缓存自动作废。
- 微信 / QQ 聊天文件、浏览器离线应用数据(IndexedDB)、搜狗词库等「看起来像
缓存、实际是你的文件」的目录,现在会以待解锁行出现在扫描结果里并写明原因,
引擎在删除层也强制拒删。
- 设置 → 受保护的位置新增「消费审计」:每条白名单规则标注最近扫描是否命中,
从未命中的过期规则一眼可见。
- 清理新增「升级安装包」分类:找出应用升级完成后留在 AppData 里的安装包
(微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。
只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件
不会被误删;应用正在运行时相关安装包自动锁定。删除确认时会提示升级包数量
与大小,可一键「跳过升级包,只删其余」。
- 桌面小工具新增「CPU」面板:总体占用率历史曲线 + 整行渐变占用柱,一根柱对应
一个逻辑核心;柱色随占用率在绿→黄→橙→红之间连续渐变(含柱内纵向微渐变),
悬停显示「核心 N: xx%」(编号与任务管理器一致从 0 开始);核心较多时柱宽自动
收窄。管理页与桌面设置弹层可独立开关该面板。
优化
- 桌面常驻 CPU 占用大幅下降(实测本机构从约 8.5% 全机总占用降至 0.2%):
小工具改用轻量采样(跳过全机逐进程枚举,那是旧版每秒最贵的一步)、两个
窗口共享同一次采样、小工具折叠或主窗口收进托盘后完全停止采样。实时监控
页打开时才有完整进程表,功能不受影响。
- 修复小工具窗口自身的自适应尺寸回环(尺寸→重锚定→再触发自适应无限循环),
该回环会让主进程与小工具渲染进程空转互叫并频繁写配置文件;修复后小工具
开着时 Squid 全家 CPU 占用接近 0%。
修复
- 权限管理:修复开机启动项开关点了没反应 / 立刻弹回的问题——所有启动项
(当前用户、所有用户、32 位、启动文件夹、服务、计划任务)统一改用最小
注册表权限写入,遇到「拒绝访问」自动发起一次系统管理员授权(UAC)后重试
并回读核实;开关失败时现在有红色气泡提示原因(此前只在页面顶部一闪而过)。
- 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题
出现一次,子行文字与标题对齐)。
- 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有
进入结果列表的派生缓存,点击后视图停留在扫描瞬间);「可选」角标不再
遮挡复选框。
- 权限管理:修复大量启动项/服务显示通用图标的问题——服务壳程序(如微软
Edge 提权服务、电脑管家 qmbsrv、H3C SpaceAgent)自身不含图标资源,
现改为回退读取注册表 App Paths、卸载信息 DisplayIcon 与同目录主程序
图标,让每一行显示真正的软件图标。
- 深度清理:默认检查目录(~/code 等 macOS 风格)在本机全都不存在时不再报
「请先选择目录」,自动回退到用户主目录扫描;「要检查的项目目录」旁新增
「浏览…」按钮可直接多选文件夹;扫描出错信息此前会被静默吞掉,现在会以
红色横幅显示。
- 托盘交互:左键单击/双击图标 = 直接打开主界面,右键 = 弹出菜单(原先
左键也会弹菜单)。
调整
- 空间清理对齐电脑管家的「清理点」粒度:规则类分类(系统垃圾 / 日志 /
浏览器缓存等)展开后先按清理点汇总(如「Windows 更新下载缓存 441 MB ·
1 个位置」),点开清理点才显示具体路径;悬停清理点可「忽略」(加入保护
名单,可随时撤销)或「查看路径」;受安全策略保护、无法删除的项目默认
不再刷屏,折叠为一行说明并提供「仍然显示」;应用正在运行、需要管理员
等可操作锁定仍照常显示原因。「回收站 / 项目产物 / 开发文件」保持平铺。
- 空间清理改版(参照电脑管家布局):取消「分类卡片 + 下方大列表」双层
结构,分类即列表、一屏一层;分「已为你默认勾选 / 需要你手动勾选」两区,
点击分类行展开该分类子项(再点收起),点击子项整行直接在资源管理器中
定位文件位置,只有点小方框才改勾选;顶部常驻「已选中 xxx 可清理文件」
汇总条(取消全选 / 立即清理随时可点)。
- 「日常清理」与「深度清理」合并为一个「空间清理」页:一次扫描同时检查缓存
垃圾与项目构建目录,结果汇总为一份清单。默认只勾选日常清理项,「升级安装
包 / 项目产物 / 开发文件」三类为可选(虚线卡片 + 可选角标),勾选后与日常
项合并成一次清理。深度扫描目录、文件年龄(3/7/30 天)、Git 保护收进页面
顶部设置栏;扫描与删除全程有步骤条与实时进度;侧边栏与托盘菜单同步精简,
快捷键重排(Ctrl+2 = 空间清理)。
- 桌面小工具 Win+D 常驻:按下「显示桌面」后小工具约 2 秒内自动回到桌面
(窗口保持桌面层:在壁纸与图标之上、其他软件窗口之下;自己关闭/折叠
不会把它叫回来)。
- Windows 上所有「废纸篓」文案改为「回收站」(清理、卸载、历史、设置等随系统
名称联动);macOS 仍为「废纸篓」。

View File

@ -1,2 +0,0 @@
1ddd17bd66a982cfdfbf15e187c213ef005619b7f6fee16ffc72dce47f105705 Squid-Setup-0.1.10-win-x64.exe
8e814c57ebb7fb6f887abfd2fd2290ad75ba0b8dc7e9694ff747fb530d19e59e Squid-0.1.10-portable-win-x64.zip

File diff suppressed because one or more lines are too long

View File

@ -1,5 +0,0 @@
@echo off
rem 360/QQPC Manager blocks unsigned installers started from non-system
rem drives when they unpack into TEMP. Copy the setup to %TEMP% on C: first.
copy /Y "%~dp0Squid-Setup-0.1.10-win-x64.exe" "%TEMP%\" >nul
start "" "%TEMP%\Squid-Setup-0.1.10-win-x64.exe"

View File

@ -0,0 +1,27 @@
Squid 0.1.5 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。
安装
----
1. 运行 Squid-Setup-0.1.5-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 卸载请在 Windows“设置 > 应用”中移除 Squid。
更新
----
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
还会验证清单的 Ed25519 签名。
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.5-win-x64.exe -Algorithm SHA256

View File

@ -0,0 +1,9 @@
Squid 0.1.5
- 语言默认跟随系统;macOS、Windows 与 Linux 分别读取对应的系统语言设置。
- 语言设置只保留中文与 English 两项,默认选中当前系统语言;切换后托盘菜单同步更新。
- 设置中新增开机自启开关,使用当前用户级启动项,无需管理员权限。
- 软件更新下载完成后的「放弃」按钮改为与 Shift 一致的中性描边样式。
- 统一 Nex 暖色设计语言:界面只使用橙色主色、暖中性色与成功/警告/危险状态色,移除蓝色、紫色、青色和粉色装饰。
- README 提供双语首页以及完整的简体中文版和英文版。
- macOS 与 Windows 同步发布 0.1.5。

View File

@ -0,0 +1,3 @@
57028b3872a9dbe965752b6451cc06fcec19d6d92b2e40710e5bbd49b2b60bd2 Squid-0.1.5-macOS-universal.dmg
9e85eefc348e066f873f3b91c6202f0e906c166a0c50a8fec4de6db7dc1f907b Squid-Setup-0.1.5-win-x64.exe
2048178675631a41f39961413d6865c462e5366ffeb890431c373cd7cb8440cb README-Windows-x64.txt

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,18 @@
{
"schema": 1,
"version": "0.1.5",
"date": "2026-11-05",
"notes": "Squid 0.1.5\n\n- 语言默认跟随系统;macOS、Windows 与 Linux 分别读取对应的系统语言设置。\n- 语言设置只保留中文与 English 两项,默认选中当前系统语言;切换后托盘菜单同步更新。\n- 设置中新增开机自启开关,使用当前用户级启动项,无需管理员权限。\n- 软件更新下载完成后的「放弃」按钮改为与 Shift 一致的中性描边样式。\n- 统一 Nex 暖色设计语言:界面只使用橙色主色、暖中性色与成功/警告/危险状态色,移除蓝色、紫色、青色和粉色装饰。\n- README 提供双语首页以及完整的简体中文版和英文版。\n- macOS 与 Windows 同步发布 0.1.5。",
"artifacts": {
"macos": {
"file": "Squid-0.1.5-macOS-universal.dmg",
"sha256": "57028b3872a9dbe965752b6451cc06fcec19d6d92b2e40710e5bbd49b2b60bd2",
"size": 10702261
},
"windows": {
"file": "Squid-Setup-0.1.5-win-x64.exe",
"sha256": "9e85eefc348e066f873f3b91c6202f0e906c166a0c50a8fec4de6db7dc1f907b",
"size": 3354754
}
}
}

View File

@ -8,8 +8,6 @@ Squid 0.1.6 - Windows x64
https://developer.microsoft.com/microsoft-edge/webview2/ https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为 - 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。 %LOCALAPPDATA%\Programs\Squid。
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
运行 Squid 才能修改,界面会给出明确提示。
安装 安装
---- ----
@ -27,13 +25,3 @@ Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会
---- ----
PowerShell: PowerShell:
Get-FileHash .\Squid-Setup-0.1.6-win-x64.exe -Algorithm SHA256 Get-FileHash .\Squid-Setup-0.1.6-win-x64.exe -Algorithm SHA256
提示
----
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
上右键退出),否则安装程序无法替换正在运行的程序文件。
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
临时目录,报"NSIS Error - Error writing temporary file"。遇到时请在
管家弹窗中选择"允许",或将安装文件加入信任区后重试;也可改用
便携包 Squid-0.1.6-portable-win-x64.zip 直接覆盖安装目录中的
squid-desktop.exe,效果相同。

View File

@ -1,36 +1,14 @@
Squid 0.1.6 Squid 0.1.6
新增 - 新增「安全」页:恶意软件扫描(快速 / 全盘 / 自定义,都可取消)、按「已确认 / 可疑 / 提示」分级的发现列表、隔离区与恢复。
- 维护组新增「权限管理」页,覆盖开机启动项、软件弹窗拦截、管理右键菜单三大场景。 - 新增「启动项」页:LaunchAgent、LaunchDaemon、登录项、注册表 Run/RunOnce、启动文件夹、计划任务与服务;当前用户拥有的条目可以直接停用与恢复,且可逆。
- 开机启动项聚合注册表 Run/RunOnce(含 32 位)、启动文件夹、计划任务(自动跳过 - 实时监控增加「进程」页签:全量进程表,含签名状态与所属启动项,可结束当前用户的进程,或对已确认恶意的文件「结束并隔离」。
系统任务)、系统服务四类来源,条目与开关状态和任务管理器、腾讯电脑管家对齐; - 系统防护状态只读展示:macOS 读取 XProtect 版本与定义日期、启动/后台扫描与 Gatekeeper;Windows 读取当前杀毒产品、实时保护与定义版本。Squid 不替代 XProtect / Defender 的实时防护。
开关直接读写 StartupApproved,不改动启动配置本身。 - 侧栏新增「保护」分组,入口共 10 个。快捷键调整:`⌘7`/`⌘8` 现为安全与启动项,历史记录与设置顺延到 `⌘9`/`⌘0`。
- 右键菜单扩展按菜单位置分组列出,取消注册立即生效,并在本地保留恢复配方。 - 托盘与系统通知会显示保护状态与待处理发现数量;点击通知直接进入发现列表。
- 弹窗拦截:列出当前可见的顶层窗口,可对任一窗口一键建立拦截规则;常驻观察者 - 可选的定时扫描(登录后 / 每天 / 每周)、「自动隔离已确认项」(默认关闭)与独立于清理白名单的安全排除项。
按间隔自动关闭命中窗口,规则累计拦截次数,支持总开关。 - 规则包:内置规则离线可用;可下载更新,校验大小与 SHA-256,并在构建内无公钥时明确标注「仅校验哈希 · 未验签」,不把未验签说成已验证。
- 启动项与已安装应用显示软件自带的中文名称(优先 ProductName/FileDescription 的 - 不上传任何文件名、哈希、发现或隔离文件;不安装后台服务、内核扩展与常驻特权 helper。
本地化名),启动项按软件分组并显示「n/n 开启」,长描述自动在标点处截断。 - 两个新页面沿用既有界面规范与配色,不新增第二套组件样式。
- 软件名前显示程序真实图标:启动项分组标题与卸载应用列表均从 DisplayIcon、卸载器 - 修复:桌面端二进制此前从未被 strip(`src-tauri` 独立于根 workspace,没有继承 release 配置),现已补上,universal 二进制减少约 20 MiB。
或安装目录主程序提取图标(老式图标按 AND 掩码补全透明通道,.lnk 快捷方式解析 - macOS 与 Windows 同步发布 0.1.6。
真实目标程序)。
- 电脑概览新增「本机配置」:操作系统版本、主板、处理器型号/核数/线程数、内存
容量/品牌/频率、主硬盘品牌/型号/容量/接口、显卡品牌/芯片/显存,全部通过
SMBIOS、存储 IOCTL 与注册表原生读取,无需管理员权限、不额外拉起命令行工具。
改进
- 电脑概览主卡片移除磁盘占用圆环,原位替换为本机配置面板;整页紧凑化,默认
1220×800 窗口内完整显示、无需滚动。
- 存储空间面板列出所有盘符,逐个显示总容量与可用容量。
- 修复 CPU 核数识别:逻辑核/物理核与每核占用采样正确(不再把核数算少)。
- 内存按 1024 进制显示,并标注「硬件保留(含核显)」容量。
- 修复 Windows 版本识别:升级装机注册表 ProductName 停留在 "Windows 10" 的机器,
现按构建号(≥22000 为 Windows 11)与 EditionID 营销名判定,正确显示如
"Windows 11 Pro 26H2"。
- 机器型号过滤 "Default string"、"To be filled by O.E.M." 等占位值。
修复
- 权限管理页签在浅色主题下的激活态文字对比度。
已知限制
- 部分云桌面/虚拟机(SMBIOS 固件表不可用)无法读取内存品牌与频率,此时内存行
只显示容量;物理磁盘总容量在标准用户下可能不可读,此时以硬盘型号标注为准。

View File

@ -1,2 +1,3 @@
5c49e1ea2f37d35218889bf6ad3b917723595c29062c3f13a5cddc11dd57ae2a Squid-Setup-0.1.6-win-x64.exe 859c1f4fcab14fbe1a343a9b5ee190bba6b324a627a7337653dd4b5c62db9761 Squid-0.1.6-macOS-universal.dmg
2e014d6299e963cc14bd51c669a432652d057696fafffea9d58aaed2cfd8bcbc Squid-0.1.6-portable-win-x64.zip 73f4df78c7aae8f975aa67335bfca7148698a4988d6b7d2e20665ec9908ef128 Squid-Setup-0.1.6-win-x64.exe
38da48607f55c64bcbbf6592927fe75a773ac12778701d4e7ce17e122af426d8 README-Windows-x64.txt

Binary file not shown.

View File

@ -1,13 +1,18 @@
{ {
"schema": 1, "schema": 1,
"version": "0.1.6", "version": "0.1.6",
"date": "2026-11-08", "date": "2026-11-07",
"notes": "Squid 0.1.6\n\n新增\n- 维护组新增「权限管理」页,覆盖开机启动项、软件弹窗拦截、管理右键菜单三大场景。\n - 开机启动项聚合注册表 Run/RunOnce(含 32 位)、启动文件夹、计划任务(自动跳过\n 系统任务)、系统服务四类来源,条目与开关状态和任务管理器、腾讯电脑管家对齐;\n 开关直接读写 StartupApproved,不改动启动配置本身。\n - 右键菜单扩展按菜单位置分组列出,取消注册立即生效,并在本地保留恢复配方。\n - 弹窗拦截:列出当前可见的顶层窗口,可对任一窗口一键建立拦截规则;常驻观察者\n 按间隔自动关闭命中窗口,规则累计拦截次数,支持总开关。\n- 启动项与已安装应用显示软件自带的中文名称(优先 ProductName/FileDescription 的\n 本地化名),启动项按软件分组并显示「n/n 开启」,长描述自动在标点处截断。\n- 软件名前显示程序真实图标:启动项分组标题与卸载应用列表均从 DisplayIcon、卸载器\n 或安装目录主程序提取图标(老式图标按 AND 掩码补全透明通道,.lnk 快捷方式解析\n 真实目标程序)。\n- 电脑概览新增「本机配置」:操作系统版本、主板、处理器型号/核数/线程数、内存\n 容量/品牌/频率、主硬盘品牌/型号/容量/接口、显卡品牌/芯片/显存,全部通过\n SMBIOS、存储 IOCTL 与注册表原生读取,无需管理员权限、不额外拉起命令行工具。\n\n改进\n- 电脑概览主卡片移除磁盘占用圆环,原位替换为本机配置面板;整页紧凑化,默认\n 1220×800 窗口内完整显示、无需滚动。\n- 存储空间面板列出所有盘符,逐个显示总容量与可用容量。\n- 修复 CPU 核数识别:逻辑核/物理核与每核占用采样正确(不再把核数算少)。\n- 内存按 1024 进制显示,并标注「硬件保留(含核显)」容量。\n- 修复 Windows 版本识别:升级装机注册表 ProductName 停留在 \"Windows 10\" 的机器,\n 现按构建号(≥22000 为 Windows 11)与 EditionID 营销名判定,正确显示如\n \"Windows 11 Pro 26H2\"。\n- 机器型号过滤 \"Default string\"、\"To be filled by O.E.M.\" 等占位值。\n\n修复\n- 权限管理页签在浅色主题下的激活态文字对比度。\n\n已知限制\n- 部分云桌面/虚拟机(SMBIOS 固件表不可用)无法读取内存品牌与频率,此时内存行\n 只显示容量;物理磁盘总容量在标准用户下可能不可读,此时以硬盘型号标注为准。", "notes": "Squid 0.1.6\n\n- 新增「安全」页:恶意软件扫描(快速 / 全盘 / 自定义,都可取消)、按「已确认 / 可疑 / 提示」分级的发现列表、隔离区与恢复。\n- 新增「启动项」页:LaunchAgent、LaunchDaemon、登录项、注册表 Run/RunOnce、启动文件夹、计划任务与服务;当前用户拥有的条目可以直接停用与恢复,且可逆。\n- 实时监控增加「进程」页签:全量进程表,含签名状态与所属启动项,可结束当前用户的进程,或对已确认恶意的文件「结束并隔离」。\n- 系统防护状态只读展示:macOS 读取 XProtect 版本与定义日期、启动/后台扫描与 Gatekeeper;Windows 读取当前杀毒产品、实时保护与定义版本。Squid 不替代 XProtect / Defender 的实时防护。\n- 侧栏新增「保护」分组,入口共 10 个。快捷键调整:`⌘7`/`⌘8` 现为安全与启动项,历史记录与设置顺延到 `⌘9`/`⌘0`。\n- 托盘与系统通知会显示保护状态与待处理发现数量;点击通知直接进入发现列表。\n- 可选的定时扫描(登录后 / 每天 / 每周)、「自动隔离已确认项」(默认关闭)与独立于清理白名单的安全排除项。\n- 规则包:内置规则离线可用;可下载更新,校验大小与 SHA-256,并在构建内无公钥时明确标注「仅校验哈希 · 未验签」,不把未验签说成已验证。\n- 不上传任何文件名、哈希、发现或隔离文件;不安装后台服务、内核扩展与常驻特权 helper。\n- 两个新页面沿用既有界面规范与配色,不新增第二套组件样式。\n- 修复:桌面端二进制此前从未被 strip(`src-tauri` 独立于根 workspace,没有继承 release 配置),现已补上,universal 二进制减少约 20 MiB。\n- macOS 与 Windows 同步发布 0.1.6。",
"artifacts": { "artifacts": {
"windows": { "macos": {
"file": "Squid-Setup-0.1.6-win-x64.exe", "file": "Squid-0.1.6-macOS-universal.dmg",
"sha256": "5c49e1ea2f37d35218889bf6ad3b917723595c29062c3f13a5cddc11dd57ae2a", "sha256": "859c1f4fcab14fbe1a343a9b5ee190bba6b324a627a7337653dd4b5c62db9761",
"size": 3510936 "size": 21831698
} },
} "windows": {
"file": "Squid-Setup-0.1.6-win-x64.exe",
"sha256": "73f4df78c7aae8f975aa67335bfca7148698a4988d6b7d2e20665ec9908ef128",
"size": 7816721
}
}
} }

View File

@ -8,8 +8,6 @@ Squid 0.1.7 - Windows x64
https://developer.microsoft.com/microsoft-edge/webview2/ https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为 - 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。 %LOCALAPPDATA%\Programs\Squid。
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
运行 Squid 才能修改,界面会给出明确提示。
安装 安装
---- ----
@ -27,13 +25,3 @@ Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会
---- ----
PowerShell: PowerShell:
Get-FileHash .\Squid-Setup-0.1.7-win-x64.exe -Algorithm SHA256 Get-FileHash .\Squid-Setup-0.1.7-win-x64.exe -Algorithm SHA256
提示
----
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
上右键退出),否则安装程序无法替换正在运行的程序文件。
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
临时目录,报"NSIS Error - Error writing temporary file"。遇到时请在
管家弹窗中选择"允许",或将安装文件加入信任区后重试;也可改用
便携包 Squid-0.1.7-portable-win-x64.zip 直接覆盖安装目录中的
squid-desktop.exe,效果相同。

View File

@ -1,31 +1,16 @@
Squid 0.1.7 更新说明 Squid 0.1.7
修复 - 概览页按新设计重做:智能维护、本机配置(系统、型号、处理器、内存、主硬盘、显卡)、处理器/内存/存储指标卡与日常维护入口;扫描结果仍在下方。
- 卸载应用:每个应用的大小此前都显示 0 B。现在读取安装器注册表的 - 应用卸载列表与卸载方案显示应用真实图标(macOS / Windows);图标按需加载并缓存,读取失败时回退首字母。
EstimatedSize(与 Windows「设置 > 应用」显示的同口径数值),没有该项 - 实时监控修复电池健康度:改用系统报告的 Maximum Capacity,Apple Silicon 不再把百分比再除以设计容量;本机显示 86%,循环次数 516。
时实测安装目录大小。 - 修复 CPU 统计:使用全局占用和全部逻辑核心,不再把第一个核心当总量,也不再少算一个核心。
- 电脑概览:本机配置面板中主板、处理器等长文本被截断。面板整体左移, - 修复内存统计:按 `vm_stat` 实际页大小(Apple Silicon 为 16 KiB)解析 compressor / wired;内存按 1024 进制显示,16 GB 不再显示为 17.2 GB。
长值自动换行,全部完整显示。 - 概览「本机配置」新增显卡信息(macOS `system_profiler`、Windows 注册表、Linux `lspci`)。
- 启动项页按 macOS / Windows 自己的分法重做:「登录项 / 后台程序」页签,按安装它的应用分组;系统自带条目默认隐藏。
改进 - 启动项读取从 8.65 秒降到 0.34 秒:不再为系统自带和已不存在的条目逐个询问签名,其余项并行处理。
- 电脑概览:处理器 / 内存 / 存储空间三个指标面板等宽,进度条更纤细并 - 修复启动项、进程表与信任状态共 4 处 IPC 字段名不一致:隐藏系统项恢复生效,启动时间、工作目录与 ad-hoc 签名状态不再显示为空或错误。
保留左右留白;存储空间为每个盘符显示占用百分比;整页在默认 1220×800 - 修复进程表「由启动项启动」标记与筛选:按可执行文件路径关联启动项,现在能正确显示与筛选。
窗口内仍无需滚动即可完整查看。 - 修复带点名称的特权 helper 被误报未签名;新增「无法读取签名」状态,不再把读不到说成没签名。
- 右键菜单管理按腾讯电脑管家的颗粒度重做: - 全部下拉菜单改为应用内自绘组件,不再弹出系统原生控件;列表统一为扁平分隔线。
- 分类按真实右键入口划分:文件 / 文件夹 / 桌面 / 驱动器 / 所有对象。 - 菜单第一项改名「概览」;除概览外移除重复的页面小标题,精简 22 处重复说明和 14 处冗长文案。
其中「桌面」(桌面空白处右键)为新增分类。 - macOS 与 Windows 同步发布 0.1.7。两个安装包均为未签名构建,首次打开需要用户自行授权(macOS 右键打开,Windows SmartScreen「仍要运行」)。
- 每一项显示可读的软件名:优先取模块自身的 FileDescription /
ProductName(中文本地化名优先),遇到「TODO: <文件说明>」这类占位
文本自动回退为安装目录名;Windows 内置项(新建、共享、发送到等)
不再混在列表里。
- 同一模块在同一分类内自动合并;分类标题显示「已启用/总数」。
- 参照电脑管家新增「创建者」(CompanyName)信息。
- 支持按名称、创建者或模块筛选。
- 凡是涉及第三方软件的地方统一显示该软件的默认图标:开机启动项列表
行、右键菜单项、弹窗拦截的当前窗口与拦截规则(启动项分组标题与
卸载应用列表沿用 0.1.6)。
已知限制
- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。
- 右键菜单分类与数量以本机注册表为准,与电脑管家的策划清单可能略有
出入。

View File

@ -1,2 +1,3 @@
17fac65b94f08bf76a90be8a5aab72233db7bb5a6368ea64b1c55df836c8910e *Squid-Setup-0.1.7-win-x64.exe f1841a084c76af824cbc5bc0feb2dd35a76743c03597c86bd64b0a478f6ad071 Squid-0.1.7-macOS-universal.dmg
4f4aafb1c1cb7a328f25f4ccbc3a0b46fba1197208cd04b5fe5bac09506b6e18 *Squid-0.1.7-portable-win-x64.zip 34bc8444f6241b50e7ba7edb4a4875989f950481a4c7d2da21125cca5b5694df Squid-Setup-0.1.7-win-x64.exe
cb826847c7b598b0121d80f64cd954ec2dc2d23e6d559ad87fa767c051af8805 README-Windows-x64.txt

Binary file not shown.

View File

@ -1,15 +1,18 @@
{ {
"schema": 1, "schema": 1,
"version": "0.1.7", "version": "0.1.7",
"date": "2026-11-08", "date": "2026-11-08",
"notes": "Squid 0.1.7 "notes": "Squid 0.1.7\n\n- 概览页按新设计重做:智能维护、本机配置(系统、型号、处理器、内存、主硬盘、显卡)、处理器/内存/存储指标卡与日常维护入口;扫描结果仍在下方。\n- 应用卸载列表与卸载方案显示应用真实图标(macOS / Windows);图标按需加载并缓存,读取失败时回退首字母。\n- 实时监控修复电池健康度:改用系统报告的 Maximum Capacity,Apple Silicon 不再把百分比再除以设计容量;本机显示 86%,循环次数 516。\n- 修复 CPU 统计:使用全局占用和全部逻辑核心,不再把第一个核心当总量,也不再少算一个核心。\n- 修复内存统计:按 `vm_stat` 实际页大小(Apple Silicon 为 16 KiB)解析 compressor / wired;内存按 1024 进制显示,16 GB 不再显示为 17.2 GB。\n- 概览「本机配置」新增显卡信息(macOS `system_profiler`、Windows 注册表、Linux `lspci`)。\n- 启动项页按 macOS / Windows 自己的分法重做:「登录项 / 后台程序」页签,按安装它的应用分组;系统自带条目默认隐藏。\n- 启动项读取从 8.65 秒降到 0.34 秒:不再为系统自带和已不存在的条目逐个询问签名,其余项并行处理。\n- 修复启动项、进程表与信任状态共 4 处 IPC 字段名不一致:隐藏系统项恢复生效,启动时间、工作目录与 ad-hoc 签名状态不再显示为空或错误。\n- 修复进程表「由启动项启动」标记与筛选:按可执行文件路径关联启动项,现在能正确显示与筛选。\n- 修复带点名称的特权 helper 被误报未签名;新增「无法读取签名」状态,不再把读不到说成没签名。\n- 全部下拉菜单改为应用内自绘组件,不再弹出系统原生控件;列表统一为扁平分隔线。\n- 菜单第一项改名「概览」;除概览外移除重复的页面小标题,精简 22 处重复说明和 14 处冗长文案。\n- macOS 与 Windows 同步发布 0.1.7。两个安装包均为未签名构建,首次打开需要用户自行授权(macOS 右键打开,Windows SmartScreen「仍要运行」)。",
"artifacts": {
Squid 0.1.7 更新说明\n\n修复\n- 卸载应用:每个应用的大小此前都显示 0 B。现在读取安装器注册表的\n EstimatedSize(与 Windows「设置 > 应用」显示的同口径数值),没有该项\n 时实测安装目录大小。\n- 电脑概览:本机配置面板中主板、处理器等长文本被截断。面板整体左移,\n 长值自动换行,全部完整显示。\n\n改进\n- 电脑概览:处理器 / 内存 / 存储空间三个指标面板等宽,进度条更纤细并\n 保留左右留白;存储空间为每个盘符显示占用百分比;整页在默认 1220×800\n 窗口内仍无需滚动即可完整查看。\n- 右键菜单管理按腾讯电脑管家的颗粒度重做:\n - 分类按真实右键入口划分:文件 / 文件夹 / 桌面 / 驱动器 / 所有对象。\n 其中「桌面」(桌面空白处右键)为新增分类。\n - 每一项显示可读的软件名:优先取模块自身的 FileDescription /\n ProductName(中文本地化名优先),遇到「TODO: <文件说明>」这类占位\n 文本自动回退为安装目录名;Windows 内置项(新建、共享、发送到等)\n 不再混在列表里。\n - 同一模块在同一分类内自动合并;分类标题显示「已启用/总数」。\n - 参照电脑管家新增「创建者」(CompanyName)信息。\n - 支持按名称、创建者或模块筛选。\n- 凡是涉及第三方软件的地方统一显示该软件的默认图标:开机启动项列表\n 行、右键菜单项、弹窗拦截的当前窗口与拦截规则(启动项分组标题与\n 卸载应用列表沿用 0.1.6)。\n\n已知限制\n- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。\n- 右键菜单分类与数量以本机注册表为准,与电脑管家的策划清单可能略有\n 出入。", "macos": {
"artifacts": { "file": "Squid-0.1.7-macOS-universal.dmg",
"windows": { "sha256": "f1841a084c76af824cbc5bc0feb2dd35a76743c03597c86bd64b0a478f6ad071",
"file": "Squid-Setup-0.1.7-win-x64.exe", "size": 21933611
"sha256": "17fac65b94f08bf76a90be8a5aab72233db7bb5a6368ea64b1c55df836c8910e", },
"size": 3512168 "windows": {
} "file": "Squid-Setup-0.1.7-win-x64.exe",
} "sha256": "34bc8444f6241b50e7ba7edb4a4875989f950481a4c7d2da21125cca5b5694df",
"size": 7875018
}
}
} }

View File

@ -1,45 +0,0 @@
Squid 0.1.8 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
运行 Squid 才能修改,界面会给出明确提示。
安装
----
1. 运行 Squid-Setup-0.1.8-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
更新
----
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
还会验证清单的 Ed25519 签名。
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.8-win-x64.exe -Algorithm SHA256
提示
----
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
上右键退出),否则安装程序无法替换正在运行的程序文件。
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
按方便程度排序:
1) 把 Squid-Setup-*.exe 复制到 C:\Users\<你>\AppData\Local\Temp
再双击运行(本机验证:管家只拦从非系统盘启动的安装程序);
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
3) 使用便携包 Squid-0.1.8-portable-win-x64.zip,解压后把 Squid 目录
内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。
- 桌面小工具在安装后默认开启,会出现在屏幕右上角;可在主程序
「桌面小工具」页或托盘菜单中关闭。

View File

@ -1,23 +0,0 @@
Squid 0.1.8 更新说明
新增
- 桌面小工具:仿飞牛资源监控的桌面看板,无边框、置顶、不抢焦点,可拖到屏幕
任意位置(默认停靠右上角)。四张面板卡片可独立开关——
- 运行状态:CPU / 内存 / GPU 占用圆环、设备名、本次运行时长;
- 网络:实时上下行速率与历史曲线;
- 存储读写:磁盘实时读写速率与历史曲线;
- 存储空间:每个盘符的已用 / 总容量进度条。
支持不透明度(60–100%)、更新频率(2/5/10 秒)、停靠角、折叠记忆等设置;
主界面新增「桌面小工具」页统一管理并实时预览,系统托盘也有一键开关。
小工具是独立窗口,主窗口关闭进托盘后它照常刷新。
- 安装程序改为静默覆盖升级:检测到旧版本时不再弹出「先卸载再安装」选择页,
直接原地覆盖安装目录(继承注册表中的旧安装位置);用户配置存放在
%APPDATA%\squid,覆盖安装不受影响,自动继承。
改进
- 权限管理 · 右键菜单:五个分类(文件 / 文件夹 / 桌面 / 驱动器 / 所有对象)
改为横向导航标签,一次只看一个分类,页面不再需要长距离滚动。
已知限制
- GPU 占用在多数 Windows 环境暂无轻量采样接口,圆环显示 0%(接口已预留)。
- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。

View File

@ -1,2 +0,0 @@
0ec67ed65b718a48fc60b91ebc68afacafc4f3ce371b293a5575cbd4335cf843 *Squid-Setup-0.1.8-win-x64.exe
94602403c566b7978319568448e4782981d0eb6981566b58240abe3c92f0875c *Squid-0.1.8-portable-win-x64.zip

View File

@ -1,13 +0,0 @@
{
"schema": 1,
"version": "0.1.8",
"date": "2026-11-18",
"notes": "Squid 0.1.8\n\n新增\n- 桌面小工具:仿飞牛资源监控的桌面看板,无边框、置顶、不抢焦点,可拖到屏幕\n 任意位置(默认停靠右上角)。四张面板卡片可独立开关——\n - 运行状态:CPU / 内存 / GPU 占用圆环、设备名、本次运行时长;\n - 网络:实时上下行速率与历史曲线;\n - 存储读写:磁盘实时读写速率与历史曲线;\n - 存储空间:每个盘符的已用 / 总容量进度条。\n 支持不透明度(60–100%)、更新频率(2/5/10 秒)、停靠角、折叠记忆等设置;\n 主界面新增「桌面小工具」页统一管理并实时预览,系统托盘也有一键开关。\n 小工具是独立窗口,主窗口关闭进托盘后它照常刷新。\n- 安装程序改为静默覆盖升级:检测到旧版本时不再弹出「先卸载再安装」选择页,\n 直接原地覆盖安装目录(继承注册表中的旧安装位置);用户配置存放在\n %APPDATA%\\squid,覆盖安装不受影响,自动继承。\n\n改进\n- 权限管理 · 右键菜单:五个分类(文件 / 文件夹 / 桌面 / 驱动器 / 所有对象)\n 改为横向导航标签,一次只看一个分类,页面不再需要长距离滚动。\n\n已知限制\n- GPU 占用在多数 Windows 环境暂无轻量采样接口,圆环显示 0%(接口已预留)。\n- 虚拟机 / VDI 环境 SMBIOS 不可用时,内存品牌与频率读不到。",
"artifacts": {
"windows": {
"file": "Squid-Setup-0.1.8-win-x64.exe",
"sha256": "0ec67ed65b718a48fc60b91ebc68afacafc4f3ce371b293a5575cbd4335cf843",
"size": 3555401
}
}
}

View File

@ -1,45 +0,0 @@
Squid 0.1.9 - Windows x64
系统要求
--------
- Windows 10 或 Windows 11(x64;ARM64 设备通过系统兼容层运行)。
- Microsoft Edge WebView2 Runtime。Windows 10/11 通常已内置;如果 Squid
启动后窗口空白,请从微软官方页面安装 WebView2 Evergreen Runtime:
https://developer.microsoft.com/microsoft-edge/webview2/
- 安装与运行都不需要管理员权限。安装位置为
%LOCALAPPDATA%\Programs\Squid。
- 权限管理页中,机单(HKLM)范围的启动项开关与系统服务需要以管理员身份
运行 Squid 才能修改,界面会给出明确提示。
安装
----
1. 运行 Squid-Setup-0.1.9-win-x64.exe。
2. 这是未签名构建。若 SmartScreen 显示警告,请选择“更多信息” > “仍要运行”。
3. 升级直接覆盖安装,不再询问是否先卸载旧版本;用户配置自动继承。
4. 卸载请在 Windows“设置 > 应用”中移除 Squid。
更新
----
Squid 使用与 nex_shift 一致的 releases 分支更新通道。更新包会先校验
文件大小与 SHA256,再在退出后运行同一个安装程序。若构建时写入发布公钥,
还会验证清单的 Ed25519 签名。
校验
----
PowerShell:
Get-FileHash .\Squid-Setup-0.1.9-win-x64.exe -Algorithm SHA256
提示
----
- 覆盖升级前请先完全退出 Squid(关闭窗口只会进入托盘,请在托盘图标
上右键退出),否则安装程序无法替换正在运行的程序文件。
- 本机若装有腾讯电脑管家,其"程序保护"可能拦截未签名安装程序写入
临时目录,报"NSIS Error - Error writing temporary file"。三种绕法,
按方便程度排序:
1) 双击本目录的「一键安装.bat」——它会把安装包复制到 C 盘临时目录
再启动(管家只拦从非系统盘启动的安装程序,此法本机验证有效);
2) 管家弹窗出现时选"允许",或将安装文件加入信任区后重试;
3) 使用便携包 Squid-0.1.9-portable-win-x64.zip,解压后把 Squid 目录
内的文件覆盖到安装目录(先退出托盘中的 Squid),效果相同。
- 桌面小工具在安装后默认开启,会出现在屏幕右上角;可在主程序
「桌面小工具」页或托盘菜单中关闭。

View File

@ -1,8 +0,0 @@
Squid 0.1.9 更新说明
修复
- 桌面小工具不再置顶:改为桌面层窗口,贴在壁纸与桌面图标之上、其他所有软件
窗口之下,打开 Office 等应用不会再被小工具遮挡;拖动小工具后也会自动落回
桌面层。
- 桌面小工具透明度收紧:最多 10% 半透明(滑块 90–100,默认 100 完全不透明),
卡片底色改为不透明白, busy 壁纸不再透出干扰读数;旧设置自动迁移。

View File

@ -1,2 +0,0 @@
d3781dd004f252d6ebb4065f4a1764c05d8c745a6e1376fd8eba2389bd97636e *Squid-Setup-0.1.9-win-x64.exe
ed6e5fb5c1d94b75ce255dde0682ed2dcf5e2cbafc2eba6b68c392f8662a6a40 *Squid-0.1.9-portable-win-x64.zip

View File

@ -1,13 +0,0 @@
{
"schema": 1,
"version": "0.1.9",
"date": "2026-11-18",
"notes": "Squid 0.1.9\n\n修复\n- 桌面小工具不再置顶:改为桌面层窗口,贴在壁纸与桌面图标之上、其他所有软件\n 窗口之下,打开 Office 等应用不会再被小工具遮挡;拖动小工具后也会自动落回\n 桌面层。\n- 桌面小工具透明度收紧:最多 10% 半透明(滑块 90–100,默认 100 完全不透明),\n 卡片底色改为不透明白, busy 壁纸不再透出干扰读数;旧设置自动迁移。",
"artifacts": {
"windows": {
"file": "Squid-Setup-0.1.9-win-x64.exe",
"sha256": "d3781dd004f252d6ebb4065f4a1764c05d8c745a6e1376fd8eba2389bd97636e",
"size": 3543355
}
}
}

View File

@ -1,5 +0,0 @@
@echo off
rem 360/QQPC Manager blocks unsigned installers started from non-system
rem drives when they unpack into TEMP. Copy the setup to %TEMP% on C: first.
copy /Y "%~dp0Squid-Setup-0.1.9-win-x64.exe" "%TEMP%\" >nul
start "" "%TEMP%\Squid-Setup-0.1.9-win-x64.exe"

View File

@ -95,7 +95,10 @@ asset_text = "".join(
for p in assets.iterdir() for p in assets.iterdir()
if p.suffix in {".js", ".css", ".html"} if p.suffix in {".js", ".css", ".html"}
) )
for marker in ("智能扫描", "扫描完成", "自动检查更新"): # Markers are the Chinese copy that has to survive into the bundle: the overview,
# uninstall, monitor and update panels each contribute one phrase, so a bundle built
# from an older or newer `dist` than the one on disk fails here rather than shipping.
for marker in ("本机配置", "智能扫描", "卸载,干净彻底", "掌握设备的每一次呼吸", "扫描完成", "自动检查更新"):
if marker not in asset_text: if marker not in asset_text:
missing.append(marker) missing.append(marker)
if missing: if missing:

1920
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@ version = "0.1.10"
description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor." description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor."
authors = ["squid contributors"] authors = ["squid contributors"]
edition = "2021" edition = "2021"
rust-version = "1.80" rust-version = "1.95"
license = "GPL-3.0-only" license = "GPL-3.0-only"
default-run = "squid-desktop" default-run = "squid-desktop"
@ -23,11 +23,14 @@ tauri-build = { version = "2", features = [] }
squid-core = { path = "../crates/squid-core" } squid-core = { path = "../crates/squid-core" }
squid-engine = { path = "../crates/squid-engine" } squid-engine = { path = "../crates/squid-engine" }
squid-platform = { path = "../crates/squid-platform" } squid-platform = { path = "../crates/squid-platform" }
squid-guard = { path = "../crates/squid-guard" }
squid-stats = { path = "../crates/squid-stats" } squid-stats = { path = "../crates/squid-stats" }
tauri = { version = "2.11", features = ["tray-icon", "image-png", "macos-private-api"] } tauri = { version = "2.11", features = ["tray-icon", "image-png", "macos-private-api"] }
tauri-plugin-dialog = "2" tauri-plugin-dialog = "2"
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
tauri-plugin-notification = "2"
tauri-plugin-single-instance = "2" tauri-plugin-single-instance = "2"
dirs = "6"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
chrono = { version = "0.4", features = ["clock"] } chrono = { version = "0.4", features = ["clock"] }
@ -43,3 +46,16 @@ debug = 1
[profile.dev.package."*"] [profile.dev.package."*"]
debug = false debug = false
# The workspace root declares these for `crates/*`, but `src-tauri` is excluded
# from that workspace, so this package had no release profile of its own and every
# desktop build shipped its whole symbol table. `strip = true` would only have
# dropped debug info, which this binary does not carry; the 23 MB that came out of
# it was the symbol table, so it is the symbol table that has to go.
# `panic` is deliberately left to unwind: a panic on a command thread currently
# costs one request, and aborting the whole app instead would be a behaviour change
# this release has no business making.
[profile.release]
lto = "thin"
codegen-units = 1
strip = "symbols"

View File

@ -14,5 +14,7 @@
<string>Squid can analyze removable volumes you select.</string> <string>Squid can analyze removable volumes you select.</string>
<key>NSNetworkVolumesUsageDescription</key> <key>NSNetworkVolumesUsageDescription</key>
<string>Squid can analyze network volumes you select.</string> <string>Squid can analyze network volumes you select.</string>
<key>NSAppleEventsUsageDescription</key>
<string>Squid reads the login items macOS lists in System Settings so the startup page can show the same ones.</string>
</dict> </dict>
</plist> </plist>

View File

@ -10,7 +10,9 @@
"core:window:allow-show", "core:window:allow-show",
"core:window:allow-set-size", "core:window:allow-set-size",
"core:window:allow-set-focus", "core:window:allow-set-focus",
"core:window:allow-is-visible",
"dialog:default", "dialog:default",
"opener:default" "opener:default",
"notification:default"
] ]
} }

View File

@ -1,35 +1,13 @@
<svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg"> <svg width="1024" height="1024" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs> <rect x="102" y="102" width="820" height="820" rx="182.6" fill="#FF6B35"/>
<linearGradient id="bg" x1="110" y1="80" x2="902" y2="944" gradientUnits="userSpaceOnUse"> <g fill="#FFF4EA">
<stop stop-color="#FFB25C"/> <path d="M512 280C610 280 690 344 690 430V512C690 596 610 648 512 648C414 648 334 596 334 512V430C334 344 414 280 512 280Z"/>
<stop offset="0.52" stop-color="#FF6B35"/> <path d="M382 610C340 660 326 720 340 772" stroke="#FFF4EA" stroke-width="54" stroke-linecap="round"/>
<stop offset="1" stop-color="#C66BFF"/> <path d="M464 640C444 700 448 748 468 782" stroke="#FFF4EA" stroke-width="46" stroke-linecap="round"/>
</linearGradient> <path d="M560 640C580 700 576 748 556 782" stroke="#FFF4EA" stroke-width="46" stroke-linecap="round"/>
<linearGradient id="body" x1="356" y1="200" x2="678" y2="704" gradientUnits="userSpaceOnUse"> <path d="M642 610C684 660 698 720 684 772" stroke="#FFF4EA" stroke-width="54" stroke-linecap="round"/>
<stop stop-color="white"/>
<stop offset="1" stop-color="#FFF6EE"/>
</linearGradient>
<filter id="shadow" x="248" y="248" width="528" height="540" filterUnits="userSpaceOnUse">
<feDropShadow dx="0" dy="22" stdDeviation="28" flood-color="#7A3018" flood-opacity="0.28"/>
</filter>
</defs>
<rect x="40" y="40" width="944" height="944" rx="228" fill="url(#bg)"/>
<path d="M141 327C236 125 462 50 668 107C872 163 977 359 947 570C915 792 725 941 494 936C266 932 78 771 64 555C59 474 85 394 141 327Z" fill="url(#body)" fill-opacity="0.15"/>
<g filter="url(#shadow)">
<path d="M512 206C608 206 682 286 682 386V499C682 599 608 679 512 679C416 679 342 599 342 499V386C342 286 416 206 512 206Z" fill="url(#body)"/>
<path d="M386 353C430 323 479 313 512 313C545 313 594 323 638 353" stroke="#D94F1F" stroke-width="28" stroke-linecap="round" opacity="0.9"/>
<circle cx="443" cy="445" r="28" fill="#7A3018"/>
<circle cx="581" cy="445" r="28" fill="#7A3018"/>
<circle cx="434" cy="436" r="8" fill="white"/>
<circle cx="572" cy="436" r="8" fill="white"/>
<path d="M456 532C479 553 545 553 568 532" stroke="#D94F1F" stroke-width="22" stroke-linecap="round"/>
<path d="M393 624C350 665 333 720 342 786" stroke="#FFF6EE" stroke-width="54" stroke-linecap="round"/>
<path d="M456 652C438 714 447 770 478 820" stroke="#FFF6EE" stroke-width="48" stroke-linecap="round"/>
<path d="M568 652C586 714 577 770 546 820" stroke="#FFF6EE" stroke-width="48" stroke-linecap="round"/>
<path d="M631 624C674 665 691 720 682 786" stroke="#FFF6EE" stroke-width="54" stroke-linecap="round"/>
<circle cx="342" cy="813" r="32" fill="#FFF6EE"/>
<circle cx="478" cy="841" r="28" fill="#FFF6EE"/>
<circle cx="546" cy="841" r="28" fill="#FFF6EE"/>
<circle cx="682" cy="813" r="32" fill="#FFF6EE"/>
</g> </g>
<circle cx="442" cy="446" r="30" fill="#FF6B35"/>
<circle cx="582" cy="446" r="30" fill="#FF6B35"/>
<path d="M462 520Q512 552 562 520" stroke="#FF6B35" stroke-width="22" stroke-linecap="round"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 975 B

Some files were not shown because too many files have changed in this diff Show More