Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
The helper takes a tool's link from /usr/local/bin once it leads nowhere
Țugui Dragoșdd333eaaafcb
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstringsindex c2962c4a..2976de1a 100644--- a/Localization/Peel/Localizable.xcstrings+++ b/Localization/Peel/Localizable.xcstrings@@ -43919,6 +43919,112 @@}}},+ "It still leads to something on this Mac." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Stále vede na něco v tomto Macu."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Der Link führt noch zu etwas auf diesem Mac."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aún lleva a algo que hay en este Mac."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Il mène encore à quelque chose sur ce Mac."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Punta ancora a qualcosa su questo Mac."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "このMacにあるものをまだ指しています。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "아직 이 Mac에 있는 항목으로 연결됩니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Het leidt nog steeds naar iets op deze Mac."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Nadal prowadzi do czegoś na tym Macu."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ainda aponta para algo neste Mac."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Încă duce la ceva de pe acest Mac."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ссылка все еще ведет к чему-то на этом Mac."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Länken leder fortfarande till något på den här datorn."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Hâlâ bu Mac’teki bir şeyi gösteriyor."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Посилання досі веде до чогось на цьому Mac."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "它仍指向这台Mac上的某个项目。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "它仍指向這部Mac上的某個項目。"+ }+ }+ }+ },"It was first seen signed by %@, and is signed by %@ now." : {"localizations" : {"cs" : {@@ -77784,6 +77890,112 @@}}},+ "Peel removes only links from that folder." : {+ "localizations" : {+ "cs" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Z této složky Peel odstraňuje jen odkazy."+ }+ },+ "de" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Aus diesem Ordner entfernt Peel nur Links."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "De esa carpeta, Peel solo elimina enlaces."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dans ce dossier, Peel ne supprime que des liens."+ }+ },+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Da quella cartella Peel rimuove solo link."+ }+ },+ "ja" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "そのフォルダからPeelがゴミ箱に入れるのはリンクだけです。"+ }+ },+ "ko" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel은 그 폴더에서 링크만 제거합니다."+ }+ },+ "nl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel verwijdert uit die map alleen links."+ }+ },+ "pl" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Z tego folderu Peel przenosi do Kosza tylko dowiązania."+ }+ },+ "pt" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Peel só remove links dessa pasta."+ }+ },+ "ro" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Din acel dosar, Peel elimină doar linkuri."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Из этой папки Peel удаляет только ссылки."+ }+ },+ "sv" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel tar bara bort länkar från den mappen."+ }+ },+ "tr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel o klasörden yalnızca bağlantıları kaldırır."+ }+ },+ "uk" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "З цієї папки Peel вилучає лише посилання."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel只会从该文件夹中移除链接。"+ }+ },+ "zh-Hant" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Peel只會從該檔案夾移除連結。"+ }+ }+ }+ },"Peel searches the Spotlight index for files. Folders, apps, and system files aren’t included. What an app keeps in a Library folder is listed last and never selected for you." : {"localizations" : {"cs" : {diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swiftindex 77396fac..ecf37bc1 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift@@ -155,16 +155,17 @@ public struct LeftoverScan: Sendable {/// Locations where the search inside other folders hit its limit, so some of the app's files may be missed.public var cutShortLocations: [SearchLocation] = []- /// Holds back, as `beyondTheHelper`, each item that needs an administrator and that the helper would refuse.- /// An item already held back by `holdsAnExclusion`, or by a reason that blocks the move, keeps its reason.- func holdingBack(beyond reach: HelperReach) -> LeftoverScan {+ /// Holds back, as `beyondTheHelper`, each item that needs an administrator and that the helper would refuse+ /// once `app` has moved. An item already held back by `holdsAnExclusion`, or by a reason that blocks the move,+ /// keeps its reason.+ func holdingBack(beyond reach: HelperReach, leaving app: URL) -> LeftoverScan {LeftoverScan(leftovers: leftovers.map { leftover inlet heldBack = leftover.match.heldBackguardleftover.requiresPrivileges,heldBack?.cannotBeMoved != true, heldBack != .holdsAnExclusion,- reach.isBeyond(leftover.url)+ reach.isBeyond(leftover.url, leaving: app)else { return leftover }return leftover.heldBack(.beyondTheHelper)},diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swiftindex f2cde570..93a5f202 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift@@ -13,14 +13,30 @@ struct HelperReach: Sendable {homeDirectory: PathPattern.comparablePath(of: environment.homeDirectory),systemLocations: PrivilegedPathPolicy.systemLocations.map { base + $0 },applicationLocations: [base + "/Applications"],- restoreLocations: PrivilegedPathPolicy.restoreLocations.map { base + $0 }+ restoreLocations: PrivilegedPathPolicy.restoreLocations.map { base + $0 },+ linkLocations: PrivilegedPathPolicy.linkLocations.map { base + $0 })}- /// True when the helper would refuse `url` for where it is: outside the folders it serves, or in- /// `/Applications` without being an app. `RemovalGuard` judges what the item itself is.- func isBeyond(_ url: URL) -> Bool {- guard let refusal = policy.refusal(of: url.path(percentEncoded: false)) else { return false }- return refusal == .outsideAllowedLocations || refusal == .notAnApplication+ /// True for an item in a folder command-line tools are linked into, which the helper takes only once the link+ /// leads nowhere.+ func takesOnlyALink(at url: URL) -> Bool {+ policy.takesOnlyALink(at: url.path(percentEncoded: false))+ }++ /// True when the helper would refuse `url` for where it is: outside the folders it serves, in `/Applications`+ /// without being an app, or in a folder command-line tools are linked into as anything but a link that leads+ /// nowhere, or into `leaving`, which moves first. `RemovalGuard` judges what the item itself is.+ func isBeyond(_ url: URL, leaving: URL? = nil) -> Bool {+ let path = url.path(percentEncoded: false)+ if let refusal = policy.refusal(of: path) {+ return refusal == .outsideAllowedLocations || refusal == .notAnApplication+ }+ guard policy.takesOnlyALink(at: path) else { return false }+ var info = stat()+ guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFLNK else { return true }+ guard let destination = PrivilegedPathPolicy.resolvedPath(path) else { return false }+ guard let leaving, let app = PrivilegedPathPolicy.resolvedPath(leaving.path(percentEncoded: false)) else { return true }+ return !PathComponents.isPath(destination, atOrInside: app)}}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swiftindex 1d4fd661..f88752ec 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift@@ -6,6 +6,9 @@ struct RemovalGuard: Sendable {/// Nothing inside these may be removed. `/Library/Updates` is where Software Update stages macOS updates./// Lower-cased, because the spellings they are compared against are.private static let protectedPrefixes = ["/system", "/usr", "/bin", "/sbin", "/library/updates"]+ /// The folders command-line tools are linked into. A link directly in one is the one thing under `/usr` that may+ /// go: what an app's tool leaves there, which Peel's helper takes only once it leads nowhere.+ private static let toolLinkFolders = PrivilegedPathPolicy.linkLocations.map { PathComponents.of($0.lowercased()) }private let protectedPaths: Set<String>private let protectedTrees: [[String]]@@ -41,11 +44,32 @@ struct RemovalGuard: Sendable {}func allowsRemoval(of url: URL) -> Bool {+ allows(url, isALink: nil)+ }++ /// Whether `trashed` may go back to `destination`, which is judged as a removal from there would be, for the+ /// kind of item `trashed` is: nothing is there yet to tell.+ func allowsPuttingBack(_ trashed: URL, at destination: URL) -> Bool {+ allows(destination, isALink: Self.isALink(trashed.path(percentEncoded: false)))+ }++ /// True for the lower-cased spelling of a link directly in a folder command-line tools are linked into.+ static func isAToolsLink(_ spelling: String, isALink: Bool) -> Bool {+ isALink && toolLinkFolders.contains(Array(PathComponents.of(spelling).dropLast()))+ }++ private static func isALink(_ path: String) -> Bool {+ var info = stat()+ return lstat(path, &info) == 0 && info.st_mode & S_IFMT == S_IFLNK+ }++ private func allows(_ url: URL, isALink known: Bool?) -> Bool {guard url.isFileURL, !exclusions.isUnreadable else { return false }let path = Self.normalized(url.path(percentEncoded: false))// A path can be written several ways (`/var` for `/private/var`, a different case), and a Put Back// destination does not exist yet. `located` names the part that exists the way the kernel does.guard let located = PathPattern.located(path) else { return false }+ let isALink = known ?? Self.isALink(located)// The kernel's own name for the item is judged too: `/.vol/<device>/<inode>` names a file by its numbers// alone and shows none of the folders it sits in.let names = Set([path, located, PathPattern.kernelName(of: path, followingLinks: false)].compactMap(\.self))@@ -59,7 +83,8 @@ struct RemovalGuard: Sendable {}for spelling in names.reduce(into: Set<String>(), { $0.formUnion(PathPattern.spellings(of: $1)) }) {- guard !protectedPaths.contains(spelling), !Self.protectedPrefixes.contains(where: { PathComponents.isPath(spelling, inside: $0) }) else {+ let isUnderAPrefix = Self.protectedPrefixes.contains { PathComponents.isPath(spelling, inside: $0) }+ guard !protectedPaths.contains(spelling), !isUnderAPrefix || Self.isAToolsLink(spelling, isALink: isALink) else {return false}diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swiftindex eac93fa5..41eb58bd 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift@@ -218,8 +218,17 @@ public struct TrashService: Sendable {return !paths.contains { PathComponents.isPath(path, inside: $0) }}let jobs = LaunchdCleanup.jobs(for: allowed, environment: environment)+ // A command-line tool's link leads into its app until the app has moved, and the helper takes such a link+ // only once it leads nowhere, so the links go after everything else.+ let reach = HelperReach(environment: environment)+ let links = Set(allowed.filter(reach.takesOnlyALink))ownMoves.began()- let helperResult = await moveThroughHelper(allowed)+ var helperResult = TrashResult()+ for batch in [allowed.filter { !links.contains($0) }, allowed.filter(links.contains)] where !batch.isEmpty {+ let moved = await moveThroughHelper(batch)+ helperResult.trashed += moved.trashed+ helperResult.failures += moved.failures+ }ownMoves.ended(landedAt: helperResult.trashed.map(\.trashedURL))result.trashed += helperResult.trashedresult.failures += helperResult.failures@@ -253,7 +262,7 @@ public struct TrashService: Sendable {public func restore(_ item: TrashedItem, canUseHelper: Bool = false) async -> RestoreFailure? {// The record comes from a file any process of the user can rewrite, so it is a request, not a fact.// Putting an item back must not write where removal is refused, or move a file that is not in a Trash.- guard removalGuard.allowsRemoval(of: item.originalURL), isInATrash(item.trashedURL) else { return .notAllowed }+ guard removalGuard.allowsPuttingBack(item.trashedURL, at: item.originalURL), isInATrash(item.trashedURL) else { return .notAllowed }let fileManager = FileManager.defaultguard item.trashedURL.isThere else { return .missingFromTrash }@@ -268,7 +277,7 @@ public struct TrashService: Sendable {if fileManager.isWritableFile(atPath: ancestor) {do {try fileManager.createDirectory(at: parent, withIntermediateDirectories: true)- try Self.putBack(item, isAllowed: removalGuard.allowsRemoval(of:))+ try Self.putBack(item) { removalGuard.allowsPuttingBack(item.trashedURL, at: $0) }return nil} catch is RefusedOnceHeld {return .notAlloweddiff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swiftindex e58ce586..184054b5 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift@@ -46,7 +46,7 @@ public struct Uninstallation: Sendable {}scan = scan.adding(await receiptLeftovers(for: app, receipts: receipts, exclusions: exclusions, environment: environment))let reach = HelperReach(environment: environment)- scan = scan.holdingBack(beyond: reach)+ scan = scan.holdingBack(beyond: reach, leaving: app.url)let appRequiresPrivileges = FileAccess.requiresPrivilegesToRemove(app.url)return Uninstallation(app: app,diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swiftindex 4e2afcde..8d13981f 100644--- a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift+++ b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift@@ -7,7 +7,7 @@ internal import PeelPrivileged/// wrote) is not one of these.public enum FixedSentence: CaseIterable, Sendable {case notAFullPath, dotInPath, controlCharacter, folderNotFound, outsideHelpersFolders, onlyAppsThere- case notThereAnymore, alreadyThere, protectedByMacOS, irreplaceable, codeFolder+ case notThereAnymore, alreadyThere, protectedByMacOS, irreplaceable, codeFolder, onlyLinksThere, leadsSomewherecase helperOutOfDate, accountNotAllowed, tooManyItems, noTrash, pathTooLong, cannotKeepRecord, notInTrashcase notMovedByHelper, invalidRequest, configurationMissingcase toolTimedOut, toolStopped@@ -32,6 +32,8 @@ public enum FixedSentence: CaseIterable, Sendable {case .protectedByMacOS: PrivilegedPathPolicy.Rejection.protectedByFlags.explanationcase .irreplaceable: PrivilegedPathPolicy.Rejection.irreplaceable.explanationcase .codeFolder: PrivilegedPathPolicy.Rejection.loadsCode.explanation+ case .onlyLinksThere: PrivilegedPathPolicy.Rejection.notALink.explanation+ case .leadsSomewhere: PrivilegedPathPolicy.Rejection.leadsSomewhere.explanationcase .helperOutOfDate: HelperRefusal.outOfDate.rawValuecase .accountNotAllowed: HelperRefusal.notAllowed.rawValuecase .tooManyItems: HelperRefusal.tooManyItems.rawValuediff --git a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swiftindex 03acd1ec..59aff66a 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift@@ -14,6 +14,8 @@ public struct PrivilegedPathPolicy: Sendable {case protectedByFlagscase irreplaceablecase loadsCode+ case notALink+ case leadsSomewhere/// What the helper sends back when it refuses. The app recognizes it and says it in the reader's language.public var explanation: String {@@ -29,6 +31,8 @@ public struct PrivilegedPathPolicy: Sendable {case .protectedByFlags: "macOS marks it as protected."case .irreplaceable: "It holds something nothing could bring back, so Peel never moves it."case .loadsCode: "Code is loaded from that folder, so only what Peel’s helper took from it can go back."+ case .notALink: "Peel removes only links from that folder."+ case .leadsSomewhere: "It still leads to something on this Mac."}}}@@ -73,11 +77,16 @@ public struct PrivilegedPathPolicy: Sendable {"/private/var/db/receipts",]+ /// The folders command-line tools are linked into. The helper takes only a link from them, and only one that+ /// leads nowhere: what an app's tool leaves there once the app is gone.+ public static let linkLocations = ["/usr/local/bin", "/usr/local/sbin"]+private static let protectedFlags = UInt32(SF_RESTRICTED) | UInt32(SF_IMMUTABLE) | UInt32(SF_NOUNLINK)private let locations: [String]private let restorable: [String]private let applicationLocations: [String]+ private let links: [String]private let homeDirectory: Stringprivate let trustedOwner: uid_t@@ -86,15 +95,23 @@ public struct PrivilegedPathPolicy: Sendable {systemLocations: [String] = Self.systemLocations,applicationLocations: [String] = ["/Applications"],restoreLocations: [String] = Self.restoreLocations,+ linkLocations: [String] = Self.linkLocations,trustedOwner: uid_t = 0) {self.homeDirectory = homeDirectoryself.trustedOwner = trustedOwner- locations = (systemLocations + [homeDirectory + "/Library"]).compactMap(Self.realPath)+ links = linkLocations.compactMap(Self.realPath)+ locations = (systemLocations + [homeDirectory + "/Library"]).compactMap(Self.realPath) + linksrestorable = (restoreLocations + [homeDirectory + "/Library"]).compactMap(Self.realPath)self.applicationLocations = applicationLocations.compactMap(Self.realPath)}+ /// True for a path directly in one of the folders the helper takes only a link from.+ public func takesOnlyALink(at path: String) -> Bool {+ guard let parent = Self.realPath((path as NSString).deletingLastPathComponent) else { return false }+ return links.contains(parent)+ }+private struct Resolved {let parent: Stringlet name: String@@ -129,6 +146,10 @@ public struct PrivilegedPathPolicy: Sendable {guard let location = locations.first(where: { PathComponents.isPath(resolved, inside: $0) }) else {return .failure(.outsideAllowedLocations)}+ // A tool's link sits directly in its folder, never deeper.+ if links.contains(location), resolvedParent != location {+ return .failure(.outsideAllowedLocations)+ }if applicationLocations.contains(location), !name.hasSuffix(".app") {return .failure(.notAnApplication)}@@ -155,6 +176,14 @@ public struct PrivilegedPathPolicy: Sendable {return .failure(.missing)}guard info.st_flags & Self.protectedFlags == 0 else { return .failure(.protectedByFlags) }+ if links.contains(item.parent) {+ guard info.st_mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }+ // Followed this time: nothing there, or a chain that loops, is a link that leads nowhere.+ var target = stat()+ let leads = item.name.withCString { fstatat(parent.descriptor, $0, &target, 0) } == 0+ let error = errno+ guard !leads, error == ENOENT || error == ENOTDIR || error == ELOOP else { return .failure(.leadsSomewhere) }+ }return .success(OpenItem(path: item.path, name: item.name, parent: parent, status: info))}}@@ -167,6 +196,9 @@ public struct PrivilegedPathPolicy: Sendable {case .failure(let rejection):return .failure(rejection)case .success(let item):+ if links.contains(item.parent) {+ guard let mode = trashed.mode, mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }+ }if !restorable.contains(where: { PathComponents.isPath(item.path, inside: $0) }) {guard trashed.owner == trustedOwner, let mode = trashed.mode, mode & 0o022 == 0 else { return .failure(.loadsCode) }}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swiftindex 15b80a12..3585ba7d 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift@@ -37,6 +37,32 @@ struct AttackRemovalGuardTests {#expect(guardian.allowsRemoval(of: home.appending(path: "Downloads/something.txt")))}+ /// Under `/usr` only a link directly in a folder command-line tools are linked into may go, and only a link may+ /// go back there. A file, a name with nothing under it yet, and anything deeper stay refused.+ @Test func underUsrOnlyAToolsLinkMayGoOrComeBack() throws {+ let directory = try TemporaryDirectory()+ let guardian = RemovalGuard(environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ ))+ let trash = try directory.directory("home/.Trash")+ let trashedLink = trash.appending(path: "tool")+ try link("/Applications/Gone.app/Contents/MacOS/tool", at: trashedLink.path(percentEncoded: false))+ let trashedFile = try directory.file("home/.Trash/file")+ let name = "peel-test-\(UUID().uuidString)"++ for folder in ["/usr/local/bin", "/usr/local/sbin"] {+ let destination = URL(filePath: "\(folder)/\(name)")+ #expect(guardian.allowsPuttingBack(trashedLink, at: destination), "a link can't go back to \(folder)")+ #expect(!guardian.allowsPuttingBack(trashedFile, at: destination), "ATTACK SUCCEEDED: a file can go to \(folder)")+ #expect(!guardian.allowsRemoval(of: destination), "a name with nothing there was allowed in \(folder)")+ }+ for path in ["/usr/bin/\(name)", "/usr/local/bin/deeper/\(name)", "/usr/local/\(name)"] {+ #expect(!guardian.allowsPuttingBack(trashedLink, at: URL(filePath: path)), "ATTACK SUCCEEDED: a link can go to \(path)")+ }+ #expect(!guardian.allowsRemoval(of: URL(filePath: "/usr/bin/true")))+ }+/// Attack 1: write the protected folder in a different case. APFS is case-insensitive by default, so the/// path still names the same file, and comparing strings must not miss it.@Test func caseSpellingOfAProtectedTree() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swiftindex 958ad600..1f99edd4 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift@@ -440,6 +440,22 @@ struct OrphanScannerTests {#expect(Set(try #require(groups["com.remembered.app"]).items.map(\.url.lastPathComponent)) == ["rem", "com.remembered.app"])}+ /// In root's `/usr/local/bin`, a link into an app that is gone leads nowhere, which is the one kind of item the+ /// helper takes from there, so it is offered like anything else the helper can move.+ @Test func aLinkIntoAnAppThatIsGoneIsWithinTheHelpersReach() async throws {+ let directory = try TemporaryDirectory()+ let bin = try directory.directory("root/usr/local/bin")+ let link = bin.appending(path: "docker")+ try FileManager.default.createSymbolicLink(atPath: link.path(percentEncoded: false), withDestinationPath: "../../../Applications/Gone.app/Contents/MacOS/docker")+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: bin.path(percentEncoded: false))+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bin.path(percentEncoded: false)) }++ let items = await scanner(in: directory).scan(installedApps: installed).groups.flatMap(\.items)+ let item = try #require(items.first { $0.url.lastPathComponent == "docker" })+ #expect(item.requiresPrivileges)+ #expect(item.leftAlone == nil, "left alone: \(String(describing: item.leftAlone))")+ }+/// A socket or a pipe holds nothing, and a live one belongs to something running. A name such as JetBrains/// Toolbox's `jb.station.<user>.sock` reads as reverse DNS, so the item's type is checked before its name.@Test func aSocketOrAPipeIsNobodysLeftover() async throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swiftindex be7601b2..109b4519 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PackageReceiptsTests.swift@@ -297,18 +297,23 @@ struct PackageReceiptsTests {}/// An item that needs an administrator is left alone when the helper would refuse it. The helper refuses- /// items outside the folders it serves, and anything in `/Applications` that is not an app.+ /// items outside the folders it serves, anything in `/Applications` that is not an app, and, in a folder+ /// command-line tools are linked into, anything but a link that leads nowhere.@Test func leavesAloneWhatTheHelperWouldRefuse() async throws {let directory = try TemporaryDirectory()let volume = PathPattern.canonical(directory.url).path(percentEncoded: false)let served = PathPattern.canonical(try directory.directory("root/Library/Application Support/Example"))let vendor = PathPattern.canonical(try directory.directory("root/Library/Example"))let tools = PathPattern.canonical(try directory.directory("root/Applications/Example Tools"))- for folder in [served, vendor, tools] {+ let bin = PathPattern.canonical(try directory.directory("root/usr/local/bin"))+ try directory.file("root/usr/local/bin/tool")+ try FileManager.default.createSymbolicLink(atPath: bin.appending(path: "linked").path(percentEncoded: false), withDestinationPath: "tool")+ try FileManager.default.createSymbolicLink(atPath: bin.appending(path: "gone").path(percentEncoded: false), withDestinationPath: "/Applications/Gone.app/Contents/MacOS/gone")+ for folder in [served, vendor, tools, bin] {try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: folder.path(percentEncoded: false))}defer {- for folder in [served, vendor, tools] {+ for folder in [served, vendor, tools, bin] {try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: folder.path(percentEncoded: false))}}@@ -320,7 +325,7 @@ struct PackageReceiptsTests {switch arguments.first {case "--pkgs-plist": PkgutilAnswer.packages("com.example.pkg")case "--pkg-info-plist": info- case "--files": "root/Library/Application Support/Example\nroot/Library/Example\nroot/Applications/Example Tools\n"+ case "--files": "root/Library/Application Support/Example\nroot/Library/Example\nroot/Applications/Example Tools\nroot/usr/local/bin/tool\nroot/usr/local/bin/linked\nroot/usr/local/bin/gone\n"default: ""}}@@ -335,5 +340,11 @@ struct PackageReceiptsTests {#expect(try item(served).isLeftAlone == false)#expect(try item(vendor).isLeftAlone == true)#expect(try item(tools).isLeftAlone == true)+ func tool(_ name: String) throws -> PackageReceipt.Item {+ try #require(receipt.items.first { $0.url.deletingLastPathComponent().lastPathComponent == "bin" && $0.url.lastPathComponent == name })+ }+ #expect(try tool("tool").isLeftAlone == true, "a file in a folder only links leave was offered")+ #expect(try tool("linked").isLeftAlone == true, "a link that leads somewhere was offered")+ #expect(try tool("gone").isLeftAlone == false)}}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swiftindex 7d97f4ec..fe072e78 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift@@ -10,12 +10,14 @@ struct PrivilegedPathPolicyTests {try directory.directory("root/Applications")try directory.directory("root/Library/Caches")try directory.directory("home/Library")+ try directory.directory("root/usr/local/bin")let root = directory.url.path(percentEncoded: false)return PrivilegedPathPolicy(homeDirectory: root + "home",systemLocations: [root + "root/Library/LaunchDaemons", root + "root/Applications", root + "root/Library/Caches"],applicationLocations: [root + "root/Applications"],restoreLocations: [root + "root/Applications", root + "root/Library/Caches"],+ linkLocations: [root + "root/usr/local/bin"],trustedOwner: trustedOwner)}@@ -45,6 +47,41 @@ struct PrivilegedPathPolicyTests {}}+ /// From the folders command-line tools are linked into, the helper takes a link and never a file, and only one+ /// that leads nowhere: Peel sends a tool's link once the app it leads into is gone, and a link that still leads+ /// somewhere stays. Only a link goes back there.+ @Test func takesOnlyALinkThatLeadsNowhereFromTheToolFolders() throws {+ let directory = try TemporaryDirectory()+ let policy = try policy(in: directory, trustedOwner: getuid())+ try directory.file("root/Applications/Tool.app/Contents/MacOS/tool")+ try directory.file("root/usr/local/bin/real")+ try directory.directory("root/usr/local/bin/folder")+ func link(_ name: String, to destination: String) throws {+ try FileManager.default.createSymbolicLink(atPath: path("root/usr/local/bin/\(name)", in: directory), withDestinationPath: destination)+ }+ try link("gone", to: path("root/Applications/Gone.app/Contents/MacOS/gone", in: directory))+ try link("relative", to: "../../../Applications/Gone.app/Contents/MacOS/gone")+ try link("loop", to: "loop")+ try link("tool", to: path("root/Applications/Tool.app/Contents/MacOS/tool", in: directory))+ try link("folder/deeper", to: "nowhere")++ for name in ["gone", "relative", "loop"] {+ #expect(policy.refusal(of: path("root/usr/local/bin/\(name)", in: directory)) == nil)+ #expect((try? policy.open(path("root/usr/local/bin/\(name)", in: directory)).get()) != nil, "\(name) was refused")+ }+ #expect(policy.open(path("root/usr/local/bin/tool", in: directory)).map(\.name) == .failure(.leadsSomewhere))+ #expect(policy.open(path("root/usr/local/bin/real", in: directory)).map(\.name) == .failure(.notALink))+ #expect(policy.open(path("root/usr/local/bin/folder", in: directory)).map(\.name) == .failure(.notALink))+ #expect(policy.refusal(of: path("root/usr/local/bin/folder/deeper", in: directory)) == .outsideAllowedLocations)++ let file = try trashed("gone", in: directory, by: policy)+ #expect(policy.openDestination(path("root/usr/local/bin/gone2", in: directory), for: file).map(\.name) == .failure(.notALink))+ try FileManager.default.createSymbolicLink(atPath: path("home/.Trash/link", in: directory), withDestinationPath: "nowhere")+ let trash = try #require(policy.openTrash(ownedBy: getuid()))+ let trashedLink = try #require(policy.openInTrash(path("home/.Trash/link", in: directory), trash: trash))+ #expect(policy.openDestination(path("root/usr/local/bin/gone2", in: directory), for: trashedLink).map(\.name) == .success("gone2"))+ }+/// A browser profile with a wallet extension's vault stays, and so does every folder around it, while the rest/// of the profile can still go.@Test func refusesAFolderHoldingABrowserWallet() throws {diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swiftindex db1a2ffa..ee6fa152 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift@@ -1,4 +1,5 @@import Foundation+import Synchronization@testable import PeelCoreimport Testing@@ -63,6 +64,31 @@ struct TrashServiceTests {)}+ /// A command-line tool's link leads into its app until the app has moved, and the helper takes such a link only+ /// once it leads nowhere, so the links go to the helper after everything else, in whatever order they came.+ @Test func sendsAToolsLinkToTheHelperAfterTheAppItLeadsInto() async throws {+ let directory = try TemporaryDirectory()+ let app = try directory.directory("root/Applications/Tool.app")+ try directory.directory("root/usr/local/bin")+ let link = directory.url.appending(path: "root/usr/local/bin/tool")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: app.appending(path: "Contents/MacOS/tool"))+ let batches = Mutex<[[String]]>([])+ let service = TrashService(+ environment: SearchEnvironment(+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)+ ),+ moveThroughHelper: { urls in+ batches.withLock { $0.append(urls.map(\.lastPathComponent)) }+ return TrashResult(trashed: urls.map { TrashedItem(originalURL: $0, trashedURL: $0, date: .now) })+ },+ moveToTrash: { _ in throw CocoaError(.fileWriteNoPermission) }+ )++ _ = await service.trash([link, app], usingHelperFor: [link, app])+ #expect(batches.withLock { $0 } == [["Tool.app"], ["tool"]])+ }+/// An item inside a folder that just moved went with it, whatever its name begins with: it is neither moved/// again nor a failure. A slash and a combining mark after it are one `Character`, so to a comparison of/// characters such an item was not inside its folder, and its move failed for a file already in the Trash.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swiftindex bdc2f7a6..ad23ba30 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift@@ -219,6 +219,27 @@ struct UninstallationTests {}}+ /// A command-line tool's link in root's `/usr/local/bin` that leads into the app goes with it, through the+ /// helper, which takes it once the app has moved and the link leads nowhere.+ @Test func aToolsLinkInRootsFolderGoesWithTheApp() async throws {+ let directory = try TemporaryDirectory()+ let app = InstalledApp(url: directory.url.appending(path: "root/Applications/Scribbler.app"), bundleIdentifier: "com.example.scribbler", name: "Scribbler")+ try directory.file("root/Applications/Scribbler.app/Contents/MacOS/scribble")+ let bin = try directory.directory("root/usr/local/bin")+ let link = bin.appending(path: "scribble")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: app.url.appending(path: "Contents/MacOS/scribble"))+ try FileManager.default.setAttributes([.posixPermissions: 0o555], ofItemAtPath: bin.path(percentEncoded: false))+ defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: bin.path(percentEncoded: false)) }+ let environment = SearchEnvironment(homeDirectory: directory.url.appending(path: "home"), rootDirectory: directory.url.appending(path: "root"))++ let plan = await Uninstallation.prepare(app, installedApps: [app], environment: environment)+ let leftover = try #require(plan.scan.leftovers.first { $0.url.lastPathComponent == "scribble" })+ #expect(leftover.requiresPrivileges)+ #expect(leftover.match.heldBack == nil, "held back: \(String(describing: leftover.match.heldBack))")+ #expect(plan.suggestedSelection(canUseHelper: true).contains(leftover.url))+ #expect(plan.privilegedURLs.contains(leftover.url))+ }+/// A folder the helper would refuse to move, such as root's `/Library/Developer` matched on the name of an/// app called Developer, is held back and cannot be selected, so it never reaches the helper to be refused.@Test func whatTheHelperMayNotMoveIsNeverOffered() async throws {diff --git a/Peel/Views/FixedSentenceText.swift b/Peel/Views/FixedSentenceText.swiftindex cd391115..969a689c 100644--- a/Peel/Views/FixedSentenceText.swift+++ b/Peel/Views/FixedSentenceText.swift@@ -16,6 +16,8 @@ extension FixedSentence {case .protectedByMacOS: "macOS marks it as protected."case .irreplaceable: "It holds something nothing could bring back, so Peel never moves it."case .codeFolder: "Code is loaded from that folder, so only what Peel’s helper took from it can go back."+ case .onlyLinksThere: "Peel removes only links from that folder."+ case .leadsSomewhere: "It still leads to something on this Mac."case .helperOutOfDate: "Peel’s helper is out of date. Reinstall it in Settings."case .accountNotAllowed: "This account isn’t allowed to use Peel’s helper."case .tooManyItems: "Too many items in one request."diff --git a/SAFETY.md b/SAFETY.mdindex 8eb16844..1fb4cafa 100644--- a/SAFETY.md+++ b/SAFETY.md@@ -227,6 +227,9 @@ is deliberately small: no shell, no arbitrary paths, and it fails closed.refused by the label each daemon declares, not by its file name, and if that list cannot be read itrefuses every daemon rather than allowing them all. It never acts on itself: Peel's helper is installedand uninstalled in Settings, and Background Items shows it without controls.+- From the folders command-line tools are linked into, `/usr/local/bin` and `/usr/local/sbin`, it takes only+ a link, never a file, and only one that leads nowhere. Peel sends an app's links there after the app itself,+ so they go once the app is gone, and a link that still leads to something stays.- It never reuses a path after checking it. It holds the parent directory open and works through thatdescriptor, so a folder swapped after the check leads nowhere.- "Put Back" is asked for by a record any process running as you can rewrite, so the helper believes none of