Skip to content

Free, open-source macOS cleaner. CleanMyMac alternative with zero telemetry. Native SwiftUI, scheduled auto-cleaning, Xcode/Homebrew/system cache cleanup. MIT licensed.

Harden orphan cleanup and add bulk selection

NeXoS_20634160c56845
diff --git a/PureMac.xcodeproj/project.pbxproj b/PureMac.xcodeproj/project.pbxproj
index 58209e1..f70a98d 100644
--- a/PureMac.xcodeproj/project.pbxproj
+++ b/PureMac.xcodeproj/project.pbxproj
@@ -23,6 +23,7 @@
9AA80E035DF7B33F6EE118DF /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = CED1B71D5F9510582E869CFD /* AppState.swift */; };
9BB5AAA574AFED6C27A3F8E2 /* AppPathFinder.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC0FEE7141871ED5F9E36121 /* AppPathFinder.swift */; };
A89DF967EC9E5E8123B2925A /* SmartScanView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11BA091943263913276F3CCF /* SmartScanView.swift */; };
+ A9C3A1F643C26930F442E729 /* OrphanSafetyPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AE790496C936424EF98320A /* OrphanSafetyPolicy.swift */; };
B52938BBD11842631314543D /* CategoryDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10B0AF194677EAC1D5568785 /* CategoryDetailView.swift */; };
BC6C800216343438413349A3 /* OnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D4FD34378988D430A582ED0 /* OnboardingView.swift */; };
CDCDFEBA39A3290101F86AC6 /* MainWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F510F232341EE18F11DC934 /* MainWindow.swift */; };
@@ -53,6 +54,7 @@
3D4FD34378988D430A582ED0 /* OnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingView.swift; sourceTree = "<group>"; };
424F7B28624C271620E13BBC /* EmptyStateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmptyStateView.swift; sourceTree = "<group>"; };
46660271CFF167AB0FE7371D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 4AE790496C936424EF98320A /* OrphanSafetyPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrphanSafetyPolicy.swift; sourceTree = "<group>"; };
5664D2BDAEAA9AE3A53DB364 /* PureMac.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = PureMac.entitlements; sourceTree = "<group>"; };
5785762276FB5E3209C6DE4D /* Logger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = "<group>"; };
60E6BC61614B27C065BB18C9 /* AppListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppListView.swift; sourceTree = "<group>"; };
@@ -187,6 +189,7 @@
children = (
01B2C5F66B6D812572BD4F05 /* CLI.swift */,
5785762276FB5E3209C6DE4D /* Logger.swift */,
+ 4AE790496C936424EF98320A /* OrphanSafetyPolicy.swift */,
);
path = Utilities;
sourceTree = "<group>";
@@ -323,6 +326,7 @@
826A750D2D7EC14C2AE306A3 /* Models.swift in Sources */,
BC6C800216343438413349A3 /* OnboardingView.swift in Sources */,
FDA30FE6349CA01C8D859F04 /* OrphanListView.swift in Sources */,
+ A9C3A1F643C26930F442E729 /* OrphanSafetyPolicy.swift in Sources */,
EDEF28CAD23E936FBED1783B /* PureMacApp.swift in Sources */,
D9445C2641A8637B65DA5ACE /* ScanEngine.swift in Sources */,
D50EB059E741011EB2523731 /* ScanError.swift in Sources */,
@@ -386,7 +390,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = PureMac/PureMac.entitlements;
- CODE_SIGN_IDENTITY = "Developer ID Application: Moamen Basel (H3WXHVTP97)";
+ CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
@@ -429,6 +433,8 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+ CODE_SIGNING_ALLOWED = NO;
+ CODE_SIGNING_REQUIRED = NO;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = PureMac/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
@@ -474,7 +480,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_ENTITLEMENTS = PureMac/PureMac.entitlements;
- CODE_SIGN_IDENTITY = "Developer ID Application: Moamen Basel (H3WXHVTP97)";
+ CODE_SIGN_IDENTITY = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
COPY_PHASE_STRIP = NO;
diff --git a/PureMac/Logic/Utilities/OrphanSafetyPolicy.swift b/PureMac/Logic/Utilities/OrphanSafetyPolicy.swift
new file mode 100644
index 0000000..34b5159
--- /dev/null
+++ b/PureMac/Logic/Utilities/OrphanSafetyPolicy.swift
@@ -0,0 +1,61 @@
+import Foundation
+
+enum OrphanSafetyPolicy {
+ private static let home = FileManager.default.homeDirectoryForCurrentUser.path
+
+ // Conservative allowlist: only volatile data directories.
+ static let allowedRoots: [String] = [
+ "\(home)/Library/Caches",
+ "\(home)/Library/Logs",
+ "\(home)/Library/Saved Application State",
+ "\(home)/Library/HTTPStorages",
+ "\(home)/Library/WebKit",
+ "\(home)/Library/Application Support/CrashReporter",
+ "/Library/Caches",
+ "/Library/Logs",
+ ]
+
+ private static let blockedFragments: [String] = [
+ "/Library/Preferences",
+ "/Library/PreferencePanes",
+ "/Library/Containers",
+ "/Library/Group Containers",
+ "/Library/Application Scripts",
+ "/Library/LaunchAgents",
+ "/Library/LaunchDaemons",
+ "/Library/PrivilegedHelperTools",
+ "/Library/Keychains",
+ "/Library/Mail",
+ "/Library/Safari",
+ "/Library/Messages",
+ "/Library/Calendars",
+ "/Library/Accounts",
+ "/Library/Mobile Documents",
+ "/Library/CloudStorage",
+ ]
+
+ static func isSafeCandidate(_ url: URL) -> Bool {
+ let path = normalizedPath(url)
+ let lowerPath = path.lowercased()
+
+ guard allowedRoots.contains(where: { lowerPath.hasPrefix($0.lowercased()) }) else {
+ return false
+ }
+
+ if blockedFragments.contains(where: { lowerPath.contains($0.lowercased()) }) {
+ return false
+ }
+
+ let name = url.lastPathComponent.lowercased()
+ if name.hasPrefix("com.apple.") || name == ".globalpreferences.plist" {
+ return false
+ }
+
+ return true
+ }
+
+ private static func normalizedPath(_ url: URL) -> String {
+ let standardized = url.standardizedFileURL
+ return standardized.resolvingSymlinksInPath().path
+ }
+}
diff --git a/PureMac/ViewModels/AppState.swift b/PureMac/ViewModels/AppState.swift
index 266615a..c2e1b91 100644
--- a/PureMac/ViewModels/AppState.swift
+++ b/PureMac/ViewModels/AppState.swift
@@ -156,7 +156,9 @@ final class AppState: ObservableObject {
if !belongsToApp {
let fullPath = URL(fileURLWithPath: path).appendingPathComponent(item)
- orphans.append(fullPath)
+ if OrphanSafetyPolicy.isSafeCandidate(fullPath) {
+ orphans.append(fullPath)
+ }
}
}
}
diff --git a/PureMac/Views/Orphans/OrphanListView.swift b/PureMac/Views/Orphans/OrphanListView.swift
index 0c50f84..cc47617 100644
--- a/PureMac/Views/Orphans/OrphanListView.swift
+++ b/PureMac/Views/Orphans/OrphanListView.swift
@@ -3,6 +3,8 @@ import SwiftUI
struct OrphanListView: View {
@EnvironmentObject var appState: AppState
@State private var selectedOrphans: Set<URL> = []
+ @State private var isRemoving = false
+ @State private var removalErrorMessage: String?
var body: some View {
Group {
@@ -54,23 +56,40 @@ struct OrphanListView: View {
.navigationTitle("Orphaned Files (\(appState.orphanedFiles.count))")
.toolbar {
ToolbarItemGroup {
+ if !appState.orphanedFiles.isEmpty {
+ Button(selectedOrphans.count == appState.orphanedFiles.count ? "Deselect All" : "Select All") {
+ if selectedOrphans.count == appState.orphanedFiles.count {
+ selectedOrphans.removeAll()
+ } else {
+ selectedOrphans = Set(appState.orphanedFiles)
+ }
+ }
+ }
+
Button("Scan for Orphans") {
appState.findOrphans()
}
if !selectedOrphans.isEmpty {
Button("Remove Selected (\(selectedOrphans.count))", role: .destructive) {
- for url in selectedOrphans {
- try? FileManager.default.removeItem(at: url)
+ Task {
+ await removeSelectedOrphans()
}
- appState.orphanedFiles.removeAll { selectedOrphans.contains($0) }
- selectedOrphans.removeAll()
}
.buttonStyle(.borderedProminent)
.tint(.red)
+ .disabled(isRemoving)
}
}
}
+ .alert("Some files could not be removed", isPresented: Binding(
+ get: { removalErrorMessage != nil },
+ set: { if !$0 { removalErrorMessage = nil } }
+ )) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(removalErrorMessage ?? "")
+ }
}
private func orphanBinding(for url: URL) -> Binding<Bool> {
@@ -91,4 +110,111 @@ struct OrphanListView: View {
let size = attrs[.size] as? Int64 else { return nil }
return size
}
+
+ private func removeSelectedOrphans() async {
+ isRemoving = true
+ defer { isRemoving = false }
+
+ let urlsToRemove = selectedOrphans
+ var failedPaths: [String] = []
+ var removedURLs: Set<URL> = []
+ var needsAdminURLs: [URL] = []
+
+ for url in urlsToRemove {
+ guard OrphanSafetyPolicy.isSafeCandidate(url) else {
+ failedPaths.append("\(url.path) (blocked by safety policy)")
+ continue
+ }
+
+ switch removeOrphan(url) {
+ case .removed:
+ removedURLs.insert(url)
+ case .needsAdmin:
+ needsAdminURLs.append(url)
+ case .failed:
+ failedPaths.append(url.path)
+ }
+ }
+
+ if !needsAdminURLs.isEmpty {
+ if removeWithAdminPrivileges(needsAdminURLs) {
+ for url in needsAdminURLs {
+ if !FileManager.default.fileExists(atPath: url.path) {
+ removedURLs.insert(url)
+ } else {
+ failedPaths.append(url.path)
+ }
+ }
+ } else {
+ failedPaths.append(contentsOf: needsAdminURLs.map(\.path))
+ }
+ }
+
+ appState.orphanedFiles.removeAll { removedURLs.contains($0) }
+ selectedOrphans.subtract(removedURLs)
+
+ if !failedPaths.isEmpty {
+ let preview = failedPaths.prefix(3).joined(separator: "\n")
+ let suffix = failedPaths.count > 3 ? "\n…" : ""
+ removalErrorMessage = "\(failedPaths.count) item(s) failed to delete.\n\n\(preview)\(suffix)"
+ }
+ }
+
+ private enum OrphanRemoveOutcome {
+ case removed
+ case needsAdmin
+ case failed
+ }
+
+ private func removeOrphan(_ url: URL) -> OrphanRemoveOutcome {
+ do {
+ try FileManager.default.removeItem(at: url)
+ return .removed
+ } catch {
+ let nsError = error as NSError
+ let permissionDeniedCodes = [
+ NSFileReadNoPermissionError,
+ NSFileWriteNoPermissionError,
+ NSFileWriteUnknownError,
+ 257,
+ 513,
+ ]
+
+ guard permissionDeniedCodes.contains(nsError.code) else {
+ return .failed
+ }
+
+ return .needsAdmin
+ }
+ }
+
+ private func removeWithAdminPrivileges(_ urls: [URL]) -> Bool {
+ guard !urls.isEmpty else { return true }
+ guard urls.allSatisfy({ OrphanSafetyPolicy.isSafeCandidate($0) }) else { return false }
+
+ // Quote path for a POSIX shell command.
+ let quotedPaths = urls.map { url in
+ "'\(url.path.replacingOccurrences(of: "'", with: "'\\\"'\\\"'"))'"
+ }
+ let shellCommand = "rm -rf -- \(quotedPaths.joined(separator: " "))"
+ let appleScriptCommand = shellCommand
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ let script = "do shell script \"\(appleScriptCommand)\" with administrator privileges"
+
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
+ process.arguments = ["-e", script]
+
+ do {
+ try process.run()
+ process.waitUntilExit()
+ if process.terminationStatus != 0 {
+ return false
+ }
+ return true
+ } catch {
+ return false
+ }
+ }
}
diff --git a/project.yml b/project.yml
index 067e449..b614524 100644
--- a/project.yml
+++ b/project.yml
@@ -13,7 +13,7 @@ settings:
MACOSX_DEPLOYMENT_TARGET: "13.0"
ARCHS: "arm64 x86_64"
ONLY_ACTIVE_ARCH: "NO"
- CODE_SIGN_IDENTITY: "Developer ID Application: Moamen Basel (H3WXHVTP97)"
+ CODE_SIGN_IDENTITY: "Apple Development"
CODE_SIGN_STYLE: "Automatic"
DEVELOPMENT_TEAM: "H3WXHVTP97"
CODE_SIGN_ENTITLEMENTS: "PureMac/PureMac.entitlements"
@@ -36,3 +36,7 @@ targets:
PRODUCT_NAME: PureMac
SWIFT_EMIT_LOC_STRINGS: "YES"
LD_RUNPATH_SEARCH_PATHS: "$(inherited) @executable_path/../Frameworks"
+ configs:
+ Debug:
+ CODE_SIGNING_ALLOWED: "NO"
+ CODE_SIGNING_REQUIRED: "NO"