Mole icon indicating copy to clipboard operation
Mole copied to clipboard

[BUG] [windows] User home directory is not protected — recursive delete silently destroys profile subdirectories

Open BingWuJ opened this issue 5 months ago • 3 comments

Describe the bug

The $script:ProtectedPaths list in lib/core/base.ps1 does not include the user home directory ($env:USERPROFILE). When Invoke-SafeCleanup receives a TargetPath pointing to the user home directory, it passes the protected-path check (which only protects Documents, Desktop, .ssh, etc.) and proceeds to recursively delete subdirectories of the user profile.

Both Invoke-RecycleBinDelete (Microsoft.VisualBasic.FileIO.FileSystem::DeleteDirectory) and Invoke-PermanentDelete (Remove-Item -Recurse -Force) are non-atomic: they recursively traverse and delete children one by one. If the operation fails partway through (e.g., file in use, Windows reserved name like nul), the already-deleted children are not rolled back, and the operation log only records a single failed entry with no per-item audit trail.

This caused 21 skill directories under ~/.agents/skills/ to be permanently deleted in a real incident, while the 22nd survived only because it contained a nul file that halted the recursion.

Root Cause

1. Missing protected path:

# lib/core/base.ps1 — current ProtectedPaths
$script:ProtectedPaths = @(
    "C:\Windows"
    "C:\Windows\System32"
    # ... system dirs ...
    "$env:USERPROFILE\Documents"
    "$env:USERPROFILE\Desktop"
    "$env:USERPROFILE\.ssh"
    "$env:USERPROFILE\.gitconfig"
    "$env:USERPROFILE\.config\secrets"
    # ← $env:USERPROFILE itself is NOT listed
)

Test-ProtectedPath uses prefix matching (StartsWith), so C:\Users\<user> is not caught. However, its children like Documents are caught, which means:

  • A direct Invoke-SafeCleanup call with TargetPath = $env:USERPROFILE passes the protection check
  • The recursive delete then traverses the entire profile, skipping Documents/Desktop (caught by prefix match), but deleting everything else including .agents/, .cache/, .config/, .factory/, etc.

2. Non-atomic recursive deletion without per-item logging:

When DeleteDirectory or Remove-Item -Recurse -Force fails partway, the catch block in Invoke-SafeCleanup logs only the top-level failure. Deleted children are gone but appear nowhere in operations.log.

Steps to reproduce

# Source the gateway modules
. .\lib\core\base.ps1
. .\lib\core\log.ps1
. .\lib\core\file_ops.ps1

# This call is NOT rejected by the protected-path check
# because $env:USERPROFILE is not in $script:ProtectedPaths
$request = @{
    RuleId       = "test-repro"
    TargetPath   = $env:USERPROFILE
    DeletionMode = "permanent"
    IsDirectory  = $true
    Recurse      = $true
    DryRun       = $true   # safe — preview only
}
Invoke-SafeCleanup -Request $request
# Returns Action=preview, Success=true
# (Would proceed to delete if DryRun were false)

With DryRun = $false or omitted, the call would start deleting subdirectories of the user profile until it hits a locked file or reserved name.

Real-world evidence

From ~/.cache/mole/logs/operations.log on 2026-06-14:

2026-06-14 21:09:46 [ERROR] rule=purge-project-artifacts action=failed mode=recoverable path="C:\Users\<user>" reason="另一个程序正在使用此文件,进程无法访问。"
2026-06-14 21:10:28 [ERROR] rule=uninstall-leftover-cleanup action=failed mode=recoverable path="C:\Users\<user>" reason="另一个程序正在使用此文件,进程无法访问。"
2026-06-14 21:14:50 [ERROR] rule=test action=failed mode=recoverable path="C:\Users\<user>" reason="另一个程序正在使用此文件,进程无法访问。"
2026-06-14 21:22:35 [ERROR] rule=mole-uninstall-install-dir action=failed mode=permanent path="C:\Users\<user>" reason="函数不正确。 : 'C:\Users\<user>\.agents\skills\windows-software-installer\nul'"

After these operations, 21 of 22 directories under ~/.agents/skills/ were deleted. Only the directory containing a nul file survived (it halted the Remove-Item recursion). The operations log recorded only the 4 failed entries above, with no per-item deletion records.

Expected behavior

  1. $env:USERPROFILE must be in $script:ProtectedPaths (or Test-ProtectedPath must reject any path that is a user home directory, not just its known children).

  2. Recursive deletion should be atomic or at minimum auditable: if a bulk delete fails partway, every successfully deleted child must be individually logged in operations.log so users can understand what was lost.

  3. Consider a preflight scan for recursive deletes: enumerate children first, validate each against protected/whitelist, log the full plan, then execute.

Environment

Mole v1.29.1 (windows branch, commit 627342b)
Built: 2026-01-07
PowerShell: 5.1.26100.8457
Windows: 10.0.26200

Branch: windows

Additional context

  • Severity: Critical — irreversible data loss in user profile directory
  • Related: #657 (font deletion), #626 (StrictMode variable issues) — same pattern of unsafe deletion paths
  • The Invoke-NestedWhitelistDelete function already demonstrates a safe pattern: iterate children explicitly and route each through Invoke-SafeCleanup. The same approach should be used for all recursive deletes, not just nested-whitelist cases

BingWuJ avatar Jun 14 '26 15:06 BingWuJ

Fixed on the windows branch in d5c74d4.

Please run mo update to pull the latest windows source. The cleanup guard now rejects the user profile root and protected install roots, and recursive directory cleanup preflights child paths before deleting anything.

Closing this as fixed. Thanks for the detailed report.

tw93 avatar Jun 15 '26 02:06 tw93

@BingWuJ Thanks for the report. Windows 1.30.0 protects the profile root and validates every descendant before recursive removal. Download it from https://github.com/tw93/Mole/releases/tag/v1.30.0-windows, or run mo update if you installed from source.

tw93 avatar Aug 16 '26 12:08 tw93

As for the desktop app: I'd pass on it. The command line is the right shape for how I work. What I'd actually value is keeping the cleanup scriptable — command line or a batch-style invocation I can wire into other tooling. An app with a confirmation dialog would just stand in the way of that. So: no app needed, lean CLI is all I want.

BingWuJ avatar Aug 16 '26 15:08 BingWuJ