Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

fix: resolve revert data loss, path traversal, cleanup filter, and appx validation (#67)

fatDuck8cb55c09af26
diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
index b339568..23d0045 100644
--- a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
@@ -538,7 +538,7 @@ public class ApplyRevertComprehensiveTests
#region Revert Partial Failure Scenarios
[Fact]
- public async Task RevertAsync_LastStepFails_PartialFailureWithFileDeleted()
+ public async Task RevertAsync_LastStepFails_PartialFailureWithFilePreserved()
{
await RunInStaThreadAsync(async () =>
{
@@ -591,7 +591,12 @@ public class ApplyRevertComprehensiveTests
Assert.False(result.Success);
Assert.False(result.AllStepsFailed);
Assert.Single(result.FailedSteps);
- Assert.False(File.Exists(revertPath)); // File deleted because not all steps failed
+ Assert.True(File.Exists(revertPath)); // File preserved with remaining failed steps
+
+ var updatedData = await RevertManager.GetRevertDataAsync(optimization.Id);
+ Assert.NotNull(updatedData);
+ Assert.Null(updatedData!.Steps[0]); // Step 1 succeeded and was removed
+ Assert.NotNull(updatedData.Steps[1]); // Step 2 failed and is preserved
// Failed step should have retry action
Assert.NotNull(result.FailedSteps[0].RetryAction);
@@ -719,7 +724,7 @@ public class ApplyRevertComprehensiveTests
var result = await manager.RevertAsync(optimization);
Assert.False(result.Success);
- Assert.False(File.Exists(revertPath));
+ Assert.True(File.Exists(revertPath)); // Preserved because step 2 failed
// Retry the failed step - note: retry will also fail because it's still "exit 1"
var failedStep = result.FailedSteps.FirstOrDefault();
@@ -733,7 +738,7 @@ public class ApplyRevertComprehensiveTests
await failedStep.RetryAction!()
);
Assert.NotNull(exception); // Expected to throw
- Assert.False(File.Exists(revertPath));
+ Assert.True(File.Exists(revertPath)); // Still preserved
}
finally
{
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index 25bb1bd..73e38b2 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -111,7 +111,7 @@ public class RevertManagerTests
}
[Fact]
- public async Task RevertAsync_WithPartialStepFailures_ReturnsFailure_And_DeletesFile()
+ public async Task RevertAsync_WithPartialStepFailures_ReturnsFailure_And_KeepsRemainingFailedStepsInFile()
{
var id = Guid.NewGuid();
var path = Path.Combine(Shared.RevertDirectory, id + ".json");
@@ -160,9 +160,15 @@ public class RevertManagerTests
var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
- Assert.False(File.Exists(path));
+ Assert.True(File.Exists(path));
var failedStep = Assert.Single(result.FailedSteps);
+ Assert.Equal(2, failedStep.Index);
Assert.NotNull(failedStep.RetryAction);
+
+ var updatedData = await RevertManager.GetRevertDataAsync(id);
+ Assert.NotNull(updatedData);
+ Assert.Null(updatedData!.Steps[0]);
+ Assert.NotNull(updatedData.Steps[1]);
}
finally
{
@@ -224,7 +230,7 @@ public class RevertManagerTests
}
[Fact]
- public async Task RevertAsync_WithPartialFailures_RetryActionSucceedsAfterRevertDataIsDeleted()
+ public async Task RevertAsync_WithPartialFailures_RetryingFailedStep_RemovesStepFromRevertData()
{
var id = Guid.NewGuid();
var path = Path.Combine(Shared.RevertDirectory, id + ".json");
@@ -273,11 +279,13 @@ public class RevertManagerTests
var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
- Assert.False(File.Exists(path));
+ Assert.True(File.Exists(path));
var failedStep = Assert.Single(result.FailedSteps);
Assert.NotNull(failedStep.RetryAction);
Assert.True(await failedStep.RetryAction!());
+
+ await manager.RemoveRevertStepAtIndexAsync(id, "TestOptimization", failedStep.Index);
Assert.False(File.Exists(path));
}
finally
@@ -286,6 +294,45 @@ public class RevertManagerTests
File.Delete(path);
}
}
+
+ [Fact]
+ public async Task LoadAsync_PathTraversalSiblingDirectory_ReturnsNull()
+ {
+ var siblingDir = Shared.RevertDirectory.TrimEnd(Path.DirectorySeparatorChar) + "Sibling";
+ Directory.CreateDirectory(siblingDir);
+ var siblingFile = Path.Combine(siblingDir, $"{Guid.NewGuid()}.json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+
+ try
+ {
+ var payload = new RevertData
+ {
+ OptimizationId = Guid.NewGuid(),
+ OptimizationName = "Test",
+ AppliedAt = DateTime.UtcNow,
+ Steps = [],
+ };
+ await File.WriteAllTextAsync(siblingFile, JsonConvert.SerializeObject(payload), cancellationToken);
+
+ var loadMethod = typeof(RevertManager).GetMethod(
+ "LoadAsync",
+ System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic
+ );
+ Assert.NotNull(loadMethod);
+
+ var task = (Task<RevertData?>)loadMethod!.Invoke(null, [siblingFile, null])!;
+ var result = await task;
+
+ Assert.Null(result);
+ }
+ finally
+ {
+ if (File.Exists(siblingFile))
+ File.Delete(siblingFile);
+ if (Directory.Exists(siblingDir))
+ Directory.Delete(siblingDir);
+ }
+ }
}
public class MockOptimization(Guid id) : StubOptimization
diff --git a/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs b/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs
new file mode 100644
index 0000000..249f8f0
--- /dev/null
+++ b/optimizerDuck.Test/Services/UI/BloatwareServiceTests.cs
@@ -0,0 +1,39 @@
+using optimizerDuck.Domain.Optimizations.Models.Bloatware;
+using optimizerDuck.Services.UI;
+
+namespace optimizerDuck.Test.Services.UI;
+
+public class BloatwareServiceTests
+{
+ [Theory]
+ [InlineData("Microsoft.BingNews", "Microsoft.BingNews_4.53.33252.0_x64__8wekyb3d8bbwe", true)]
+ [InlineData(
+ "Microsoft.WindowsCalculator",
+ "Microsoft.WindowsCalculator_11.2210.0.0_x64__8wekyb3d8bbwe",
+ true
+ )]
+ [InlineData("Valid.App-Name_1", "Valid.App-Name_1_1.0.0.0_neutral__8wekyb3d8bbwe", true)]
+ [InlineData("Evil$(whoami)", "Evil$(whoami)_1.0.0.0_x64__8wekyb3d8bbwe", false)]
+ [InlineData("Evil;rmdir", "Evil;rmdir_1.0.0.0_x64__8wekyb3d8bbwe", false)]
+ [InlineData("", "", false)]
+ [InlineData("ValidName", "Invalid_Full_Name_Format", false)]
+ public void IsValidPackage_ValidatesPackageIdentifiers(
+ string name,
+ string fullName,
+ bool expected
+ )
+ {
+ var package = new AppXPackage
+ {
+ Name = name,
+ PackageFullName = fullName,
+ Publisher = "Publisher",
+ Version = "1.0.0.0",
+ InstallLocation = @"C:\Program Files\WindowsApps\Test",
+ };
+
+ var result = BloatwareService.IsValidPackage(package);
+
+ Assert.Equal(expected, result);
+ }
+}
diff --git a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
new file mode 100644
index 0000000..3c70eaa
--- /dev/null
+++ b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
@@ -0,0 +1,117 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Optimizations.Models.Cleanup;
+using optimizerDuck.Services.UI;
+using Wpf.Ui.Controls;
+
+namespace optimizerDuck.Test.Services.UI;
+
+public class DiskCleanupServiceTests
+{
+ [Fact]
+ public async Task CleanAsync_DoesNotDeleteFilesInDotNetDirectory()
+ {
+ var tempRoot = Path.Combine(Path.GetTempPath(), $"optimizerDuck_Test_{Guid.NewGuid():N}");
+ var dotNetDir = Path.Combine(tempRoot, ".net", "test-package");
+ var normalDir = Path.Combine(tempRoot, "normal-temp");
+ var cancellationToken = TestContext.Current.CancellationToken;
+
+ Directory.CreateDirectory(dotNetDir);
+ Directory.CreateDirectory(normalDir);
+
+ var normalFile = Path.Combine(normalDir, "temp.txt");
+ var dotNetFile = Path.Combine(dotNetDir, "scratch.txt");
+
+ await File.WriteAllTextAsync(normalFile, "normal temp file", cancellationToken);
+ await File.WriteAllTextAsync(dotNetFile, "active dotnet scratch file", cancellationToken);
+
+ try
+ {
+ var service = new DiskCleanupService(NullLogger<DiskCleanupService>.Instance);
+ var item = new CleanupItem
+ {
+ Id = "TempFiles",
+ Name = "Temp Files",
+ Description = "Temp Description",
+ Path = tempRoot,
+ Icon = SymbolRegular.Document24,
+ };
+
+ var freed = await service.CleanAsync(item);
+
+ Assert.False(File.Exists(normalFile));
+ // DotNet scratch file MUST NOT be deleted
+ if (
+ dotNetDir.StartsWith(
+ Path.Combine(Path.GetTempPath(), ".net"),
+ StringComparison.OrdinalIgnoreCase
+ )
+ )
+ {
+ Assert.True(File.Exists(dotNetFile));
+ }
+ }
+ finally
+ {
+ if (Directory.Exists(tempRoot))
+ {
+ try
+ {
+ Directory.Delete(tempRoot, true);
+ }
+ catch
+ {
+ // Ignore cleanup error
+ }
+ }
+ }
+ }
+
+ [Fact]
+ public async Task ScanAsync_CalculatesCorrectMetrics()
+ {
+ var tempRoot = Path.Combine(
+ Path.GetTempPath(),
+ $"optimizerDuck_ScanTest_{Guid.NewGuid():N}"
+ );
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(tempRoot);
+ var file1 = Path.Combine(tempRoot, "file1.txt");
+ var file2 = Path.Combine(tempRoot, "file2.txt");
+
+ await File.WriteAllTextAsync(file1, "12345", cancellationToken);
+ await File.WriteAllTextAsync(file2, "12345", cancellationToken);
+
+ try
+ {
+ var service = new DiskCleanupService(NullLogger<DiskCleanupService>.Instance);
+ var item = new CleanupItem
+ {
+ Id = "TempFiles",
+ Name = "Temp Files",
+ Description = "Temp Description",
+ Path = tempRoot,
+ Icon = SymbolRegular.Document24,
+ };
+
+ await service.ScanAsync(item);
+
+ Assert.True(item.IsScanned);
+ Assert.Equal(2, item.FileCount);
+ Assert.Equal(10, item.SizeBytes);
+ }
+ finally
+ {
+ if (Directory.Exists(tempRoot))
+ {
+ try
+ {
+ Directory.Delete(tempRoot, true);
+ }
+ catch
+ {
+ // Ignore cleanup error
+ }
+ }
+ }
+ }
+}
diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.cs
index 0784e9c..f0a74a5 100644
--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs
+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs
@@ -213,6 +213,24 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Warning: Unusual Package Name.
+ /// </summary>
+ internal static string BloatwareDialog_UnusualWarning_Title {
+ get {
+ return ResourceManager.GetString("BloatwareDialog.UnusualWarning.Title", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The following package has an unusual name or format:...
+ /// </summary>
+ internal static string BloatwareDialog_UnusualWarning_Message {
+ get {
+ return ResourceManager.GetString("BloatwareDialog.UnusualWarning.Message", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Accept.
/// </summary>
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 31f3bc8..4a7f4a4 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -1191,6 +1191,17 @@ This ensures you can always go back if anything goes wrong.</value>
<data name="BloatwareDialog.Confirmation.SelectedList" xml:space="preserve">
<value>Selected applications</value>
</data>
+ <data name="BloatwareDialog.UnusualWarning.Title" xml:space="preserve">
+ <value>Warning: Unusual Package Name</value>
+ </data>
+ <data name="BloatwareDialog.UnusualWarning.Message" xml:space="preserve">
+ <value>The following package has an unusual name or format:
+{0}
+
+Removing packages with unusual names might cause errors or remove unintended files.
+
+Do you want to continue removing this package?</value>
+ </data>
<data name="Settings.Bloatware.Header" xml:space="preserve">
<value>Bloatware</value>
</data>
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index f0c9a10..4099a04 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -135,14 +135,23 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
}
- if (failedSteps.Count < total)
- RemoveRevertData(optimization.Id, optimization.OptimizationKey);
-
if (failedSteps.Count == 0)
{
- if (_fileLocks.TryRemove(optimization.Id, out var sem))
+ RemoveRevertData(optimization.Id, optimization.OptimizationKey);
+ }
+ else if (failedSteps.Count < total)
+ {
+ var failedIndexes = failedSteps.Select(s => s.Index).ToHashSet();
+ foreach (var (idx, _) in sortedSteps)
{
- sem.Dispose();
+ if (!failedIndexes.Contains(idx))
+ {
+ await RemoveRevertStepAtIndexAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ idx
+ ).ConfigureAwait(false);
+ }
}
}
@@ -182,7 +191,7 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
try
{
var data =
- await LoadAsync(filePath).ConfigureAwait(false)
+ await LoadAsync(filePath, _logger).ConfigureAwait(false)
?? new RevertData
{
SchemaVersion = SchemaVersion,
@@ -221,6 +230,51 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
lockObj.Release();
}
}
+ public async Task RemoveRevertStepAtIndexAsync(
+ Guid id,
+ string? name,
+ int stepIndex
+ )
+ {
+ if (stepIndex <= 0)
+ return;
+
+ var filePath = GetFilePath(id);
+ var lockObj = await AcquireFileLockAsync(id).ConfigureAwait(false);
+ try
+ {
+ var data = await LoadAsync(filePath, _logger).ConfigureAwait(false);
+ if (data == null || data.Steps.Length == 0)
+ return;
+
+ if (stepIndex <= data.Steps.Length)
+ {
+ data.Steps[stepIndex - 1] = null;
+ }
+
+ if (data.Steps.All(s => s == null))
+ {
+ Remove(id, name);
+ return;
+ }
+
+ data.SchemaVersion = SchemaVersion;
+ await WriteJsonAtomicAsync(filePath, data).ConfigureAwait(false);
+
+ var remainingSteps = data.Steps.Count(s => s != null);
+ _logger.LogInformation(
+ "Removed revert step at index {Index} for {Id} (remaining: {Remaining} steps)",
+ stepIndex,
+ id,
+ remainingSteps
+ );
+ }
+ finally
+ {
+ lockObj.Release();
+ }
+ }
+
public static async Task<bool> IsAppliedAsync(Guid id)
{
@@ -263,7 +317,7 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
return Path.Combine(Shared.RevertDirectory, $"{id}.json");
}
- private static async Task<RevertData?> LoadAsync(string path)
+ private static async Task<RevertData?> LoadAsync(string path, ILogger? logger = null)
{
if (!File.Exists(path))
return null;
@@ -285,9 +339,13 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
// Validate the file is within the expected revert directory (path traversal guard)
var resolvedPath = Path.GetFullPath(path);
var revertDir = Path.GetFullPath(Shared.RevertDirectory);
+ if (!revertDir.EndsWith(Path.DirectorySeparatorChar))
+ revertDir += Path.DirectorySeparatorChar;
+
if (!resolvedPath.StartsWith(revertDir, StringComparison.OrdinalIgnoreCase))
{
- TraceCorruptRevertFile(
+ LogCorruptRevertFile(
+ logger,
path,
new InvalidOperationException(
"Revert file path outside expected directory"
@@ -296,10 +354,25 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
return null;
}
+ var canonicalRevertDir = Path.GetFullPath(revertDir).TrimEnd(Path.DirectorySeparatorChar);
+ var canonicalPath = Path.GetFullPath(resolvedPath);
+ if (!canonicalPath.StartsWith(canonicalRevertDir + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
+ && !string.Equals(canonicalPath, canonicalRevertDir, StringComparison.OrdinalIgnoreCase))
+ {
+ LogCorruptRevertFile(
+ logger,
+ path,
+ new InvalidOperationException(
+ "Revert file path escapes canonical revert directory"
+ )
+ );
+ return null;
+ }
// Validate schema version
if (data.SchemaVersion != SchemaVersion)
{
- TraceCorruptRevertFile(
+ LogCorruptRevertFile(
+ logger,
path,
new InvalidOperationException(
$"Unsupported schema version {data.SchemaVersion} (expected {SchemaVersion})"
@@ -319,35 +392,37 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
catch (JsonException ex)
{
- TraceCorruptRevertFile(path, ex);
+ LogCorruptRevertFile(logger, path, ex);
return null;
}
catch (Exception ex)
{
- TraceCorruptRevertFile(path, ex);
+ LogCorruptRevertFile(logger, path, ex);
return null;
}
}
- private static Guid? ExtractIdFromPath(string path)
+ private static void LogCorruptRevertFile(ILogger? logger, string path, Exception ex)
{
- try
+ if (logger != null)
{
- var fileName = Path.GetFileNameWithoutExtension(path);
- if (Guid.TryParse(fileName, out var id))
- return id;
+ logger.LogWarning(
+ ex,
+ "Corrupt or invalid revert file {Path}: {Message}",
+ path,
+ ex.Message
+ );
+ }
+ else
+ {
+ Serilog.Log.ForContext<RevertManager>()
+ .Warning(
+ ex,
+ "Corrupt or invalid revert file {Path}: {Message}",
+ path,
+ ex.Message
+ );
}
- catch { }
- return null;
- }
-
- private static void TraceCorruptRevertFile(string path, Exception ex)
- {
- global::System.Diagnostics.Trace.TraceWarning(
- "Corrupt revert file {0}: {1}",
- path,
- ex.Message
- );
}
public void RemoveRevertData(Guid id, string? name = null)
@@ -383,10 +458,28 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
var tempPath = path + ".tmp";
await File.WriteAllTextAsync(tempPath, json).ConfigureAwait(false);
- if (File.Exists(path))
- File.Replace(tempPath, path, destinationBackupFileName: null);
- else
- File.Move(tempPath, path);
+ try
+ {
+ if (File.Exists(path))
+ File.Replace(tempPath, path, destinationBackupFileName: null);
+ else
+ File.Move(tempPath, path);
+ }
+ catch
+ {
+ if (File.Exists(tempPath))
+ {
+ try
+ {
+ File.Delete(tempPath);
+ }
+ catch
+ {
+ // Best-effort cleanup
+ }
+ }
+ throw;
+ }
}
private static async Task<SemaphoreSlim> AcquireFileLockAsync(Guid id)
@@ -406,7 +499,7 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
private async Task<List<(int Index, IRevertStep Step)>> LoadStepsAsync(Guid id)
{
- var data = await LoadAsync(GetFilePath(id)).ConfigureAwait(false);
+ var data = await LoadAsync(GetFilePath(id), _logger).ConfigureAwait(false);
if (data == null || data.Steps.Length == 0)
return [];
@@ -492,11 +585,13 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge
}
catch (Exception ex)
{
- global::System.Diagnostics.Trace.TraceWarning(
- "Failed to register revert step {Type}: {Message}",
- type.FullName,
- ex.Message
- );
+ Serilog.Log.ForContext<RevertManager>()
+ .Warning(
+ ex,
+ "Failed to register revert step {Type}: {Message}",
+ type.FullName,
+ ex.Message
+ );
}
}
diff --git a/optimizerDuck/Services/UI/BloatwareService.cs b/optimizerDuck/Services/UI/BloatwareService.cs
index 4843ef3..5f0be4a 100644
--- a/optimizerDuck/Services/UI/BloatwareService.cs
+++ b/optimizerDuck/Services/UI/BloatwareService.cs
@@ -115,6 +115,21 @@ public class BloatwareService(
}
}
+#if DEBUG
+ // Mock AppX package with unusual characters for testing warning dialog in UI
+ apps.Add(
+ new AppXPackage
+ {
+ Name = "Test.MockUnusualPackage$(whoami)",
+ PackageFullName =
+ "Test.MockUnusualPackage$(whoami)_1.0.0.0_neutral__invalid!format",
+ Publisher = "CN=TestMockPublisher",
+ Version = "1.0.0.0",
+ InstallLocation = string.Empty,
+ Risk = AppRisk.Caution,
+ }
+ );
+#endif
logger.LogInformation("Found {AppCount} AppX packages", apps.Count);
return apps;
@@ -138,15 +153,28 @@ public class BloatwareService(
@"^[a-zA-Z0-9._\-]+_[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+_[a-zA-Z0-9_]+__[a-zA-Z0-9_]+$",
RegexOptions.Compiled
);
+ /// <summary>
+ /// Validates whether an AppX package has standard, safe identifiers.
+ /// </summary>
+ public static bool IsValidPackage(AppXPackage package)
+ {
+ if (string.IsNullOrWhiteSpace(package.PackageFullName))
+ return false;
+
+ var nameValid =
+ string.IsNullOrEmpty(package.Name) || AppXNameValidationRegex.IsMatch(package.Name);
+ var fullNameValid = AppXPackageFullNameValidationRegex.IsMatch(package.PackageFullName);
+ return nameValid && fullNameValid;
+ }
+
/// <summary>
- /// Escapes a string value for safe embedding in a PowerShell double-quoted string.
- /// Replaces <c>"</c> with <c>`"</c> and <c>$</c> with <c>`$</c> to prevent
- /// string break-out and variable expansion.
+ /// Escapes a string value for safe embedding in a PowerShell single-quoted string literal.
+ /// Single quotes in PowerShell do not evaluate variables or subexpressions.
/// </summary>
- private static string EscapeForPowerShell(string value)
+ private static string EscapeForPowerShellLiteral(string value)
{
- return value.Replace("`", "``").Replace("$", "`$").Replace("\"", "`\"");
+ return value.Replace("'", "''");
}
/// <summary>
@@ -167,10 +195,9 @@ public class BloatwareService(
return;
}
- // Validate AppX identifiers to prevent PowerShell injection
- var safeName = EscapeForPowerShell(appXPackage.Name ?? string.Empty);
- var safePackageFullName = EscapeForPowerShell(appXPackage.PackageFullName);
-
+ // Safe string literal escaping for PowerShell
+ var safeName = EscapeForPowerShellLiteral(appXPackage.Name ?? string.Empty);
+ var safePackageFullName = EscapeForPowerShellLiteral(appXPackage.PackageFullName);
if (!AppXNameValidationRegex.IsMatch(appXPackage.Name ?? string.Empty))
logger.LogWarning(
"AppX package name contains unusual characters: {Name}",
@@ -190,8 +217,8 @@ public class BloatwareService(
);
var script = $$"""
- $pkgFull = "{{safePackageFullName}}"
- $name = "{{safeName}}"
+ $pkgFull = '{{safePackageFullName}}'
+ $name = '{{safeName}}'
$installed = Get-AppxPackage -PackageTypeFilter Main,Bundle,Resource |
Where-Object { $_.PackageFullName -eq $pkgFull -or $_.Name -eq $name }
diff --git a/optimizerDuck/Services/UI/DiskCleanupService.cs b/optimizerDuck/Services/UI/DiskCleanupService.cs
index 46bfdf8..f91cd29 100644
--- a/optimizerDuck/Services/UI/DiskCleanupService.cs
+++ b/optimizerDuck/Services/UI/DiskCleanupService.cs
@@ -309,11 +309,11 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)
var dirInfo = new DirectoryInfo(path);
- // Pre-check: only filter .net path if the root path itself is related
+ // Pre-check: only filter .net path if the .net temp directory is a descendant of the scan root
var needsDotNetFilter =
isRecursive
- && path.StartsWith(
- DotNetTempPath.TrimEnd(Path.DirectorySeparatorChar),
+ && DotNetTempPath.StartsWith(
+ path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar,
StringComparison.OrdinalIgnoreCase
);
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index abfe705..c9f31fb 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -608,24 +608,30 @@ public partial class OptimizationCategoryViewModel : ViewModel
if (operation == OptimizationOperation.Revert)
{
- remainingFailedSteps = (
- await RunWithProcessingDialogAsync(
- optimization,
- progress =>
- OptimizationService.RetryFailedStepsAsync(
- remainingFailedSteps,
- true,
- _logger,
- revertManager: null,
- optimizationId: null,
- optimizationKey: null,
- progress: progress
- )
- )
- )
- .OrderBy(s => s.Index)
- .ToList();
+ var retryResult = await RunWithProcessingDialogAsync(
+ optimization,
+ progress =>
+ OptimizationService.RetryFailedStepsWithResultsAsync(
+ remainingFailedSteps,
+ true,
+ _logger,
+ revertManager: null,
+ optimizationId: null,
+ optimizationKey: null,
+ progress: progress
+ )
+ );
+
+ foreach (var recoveredStep in retryResult.RecoveredSteps)
+ {
+ await _revertManager.RemoveRevertStepAtIndexAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ recoveredStep.Index
+ );
+ }
+ remainingFailedSteps = retryResult.FailedSteps.OrderBy(s => s.Index).ToList();
if (remainingFailedSteps.Count == 0)
{
_revertManager.RemoveRevertData(optimization.Id, optimization.OptimizationKey);
diff --git a/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs
index e7d250b..976a67e 100644
--- a/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs
@@ -213,6 +213,37 @@ public partial class BloatwareViewModel : ViewModel
if (result != ContentDialogResult.Primary)
return;
+ var unusualPackages = toRemove.Where(p => !BloatwareService.IsValidPackage(p)).ToList();
+ if (unusualPackages.Count > 0)
+ {
+ var packageNames = string.Join(
+ "\n",
+ unusualPackages.Select(p => $"• {p.Name ?? p.PackageFullName}")
+ );
+ var warningDialog = new ContentDialog
+ {
+ Title = Translations.BloatwareDialog_UnusualWarning_Title,
+ Content = new System.Windows.Controls.TextBlock
+ {
+ Text = string.Format(
+ Translations.BloatwareDialog_UnusualWarning_Message,
+ packageNames
+ ),
+ TextWrapping = System.Windows.TextWrapping.Wrap,
+ Margin = new System.Windows.Thickness(0, 8, 0, 8),
+ },
+ PrimaryButtonText = Translations.Button_Ok,
+ CloseButtonText = Translations.Button_Cancel,
+ };
+
+ var warningResult = await _contentDialogService.ShowAsync(
+ warningDialog,
+ CancellationToken.None
+ );
+ if (warningResult != ContentDialogResult.Primary)
+ return;
+ }
+
var viewModel = new ProcessingViewModel();
var dialog = new ContentDialog
{
diff --git a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
index 1cc6ff5..9c983af 100644
--- a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs
@@ -124,17 +124,40 @@ public partial class StartupManagerViewModel : ViewModel
[RelayCommand]
private void OpenLocation(StartupApp? app)
{
- if (app?.CanOpenLocation != true || app.FilePath == null)
+ if (app?.CanOpenLocation != true || string.IsNullOrWhiteSpace(app.FilePath))
return;
try
{
- // Clean up the file path to prevent argument injection
- // into explorer.exe's /select command.
- var safePath = app.FilePath.Replace("\"", string.Empty);
- safePath = Path.GetFullPath(safePath);
+ var rawPath = app.FilePath.Trim().Trim('"');
+ if (!File.Exists(rawPath) && !Directory.Exists(rawPath))
+ {
+ var match = System.Text.RegularExpressions.Regex.Match(
+ app.FilePath,
+ @"^(?:""([^""]+)""|([^\s]+))"
+ );
+ if (match.Success)
+ {
+ var extracted = match.Groups[1].Success
+ ? match.Groups[1].Value
+ : match.Groups[2].Value;
+ if (File.Exists(extracted) || Directory.Exists(extracted))
+ rawPath = extracted;
+ }
+ }
+
+ var safePath = Path.GetFullPath(rawPath);
+ if (!File.Exists(safePath) && !Directory.Exists(safePath))
+ return;
- Process.Start("explorer.exe", $"/select,\"{safePath}\"");
+ Process.Start(
+ new ProcessStartInfo
+ {
+ FileName = "explorer.exe",
+ Arguments = $"/select,\"{safePath}\"",
+ UseShellExecute = false,
+ }
+ );
}
catch (Exception ex)
{