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
Remove a Safari web app with its container and its settings
Țugui Dragoș999a3e99dad7
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swiftindex 93f251ca..cbd24b22 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift@@ -99,7 +99,8 @@ public enum AppInspector {contents: contents,isFromAppStore: isFromAppStore,isSystemProtected: isSystemProtected- )+ ),+ isASafariWebApp: SafariWebApp.isOne(identifier: bundleIdentifier, info: info))}diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/InstalledApp.swift b/Packages/PeelCore/Sources/PeelCore/Apps/InstalledApp.swiftindex 20c07ab5..9555d69a 100644--- a/Packages/PeelCore/Sources/PeelCore/Apps/InstalledApp.swift+++ b/Packages/PeelCore/Sources/PeelCore/Apps/InstalledApp.swift@@ -33,6 +33,8 @@ public struct InstalledApp: Sendable, Hashable, Identifiable {public let isPeelItself: Bool/// Whether this is the very bundle the running code was started from: the copy of Peel that is running.public let isTheRunningCopy: Bool+ /// Whether this is a web app Safari made (`SafariWebApp`), whose identifier names it and nothing of Apple's.+ public let isASafariWebApp: Bool/// Whether `other`, a reading of the same path, is the same build. Not `==`: the date an app was last opened/// changes every time it is opened, which is no reason to forget its size or check it for updates again.@@ -59,7 +61,8 @@ public struct InstalledApp: Sendable, Hashable, Identifiable {lastUsedDate: Date? = nil,isUseRecorded: Bool = true,dateAdded: Date? = nil,- updateFeed: UpdateFeed? = nil+ updateFeed: UpdateFeed? = nil,+ isASafariWebApp: Bool = false) {self.url = urlself.bundleIdentifier = bundleIdentifier@@ -78,6 +81,7 @@ public struct InstalledApp: Sendable, Hashable, Identifiable {self.lastUsedDate = lastUsedDateself.isUseRecorded = isUseRecordedself.dateAdded = dateAdded+ self.isASafariWebApp = isASafariWebAppself.updateFeed = updateFeedlet path = PathPattern.comparablePath(of: url)isPeelItself = Self.isPeel(bundleIdentifier, at: path)@@ -117,7 +121,8 @@ public struct InstalledApp: Sendable, Hashable, Identifiable {lastUsedDate: date,isUseRecorded: isRecorded,dateAdded: dateAdded,- updateFeed: updateFeed+ updateFeed: updateFeed,+ isASafariWebApp: isASafariWebApp)}diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/SafariWebApp.swift b/Packages/PeelCore/Sources/PeelCore/Apps/SafariWebApp.swiftnew file mode 100644index 00000000..db3ce1b0--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Apps/SafariWebApp.swift@@ -0,0 +1,31 @@+import Foundation++/// A web app Safari makes with File > Add to Dock (Apple, "Use Safari web apps on Mac"). Safari writes it as a+/// template of its own `com.apple.Safari.WebApp`, under an identifier that is the template's followed by the UUID it+/// gives the web app, so that identifier names this one web app and nothing else of Apple's.+enum SafariWebApp {+ static let template = "com.apple.Safari.WebApp"++ /// True when `info`, an app's Info.plist, is one Safari wrote for a web app named `identifier`.+ static func isOne(identifier: String, info: [String: Any]) -> Bool {+ guard+ info["LSTemplateApplication"] as? Bool == true,+ let parameters = info["LSTemplateApplicationParameters"] as? [String: Any],+ parameters["CFBundleIdentifier"] as? String == template,+ let uuid = parameters["TemplateAppUUID"] as? String+ else { return false }+ return identifier == template + "." + uuid && isIdentifier(identifier)+ }++ /// True for an identifier of the shape Safari gives a web app: its template, a dot, and a UUID.+ static func isIdentifier(_ identifier: String) -> Bool {+ guard identifier.count == template.count + 37 else { return false }+ let uuid = identifier.suffix(36)+ return identifier.lowercased().hasPrefix(template.lowercased() + ".") && UUID(uuidString: String(uuid)) != nil+ }++ /// The folder inside Safari's web app container where each web app gets a container named by its identifier.+ static func containers(inLibrary library: URL) -> URL {+ library.appending(path: "Containers/\(template)/Data/Library/Containers", directoryHint: .isDirectory)+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swiftindex 033e8e3f..ec1ce227 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift@@ -259,6 +259,7 @@ extension LeftoverMatcher {let names: [String]let normalizedNames: Set<String>let isApplesOwn: Bool+ let isASafariWebApp: Boolinit(_ app: InstalledApp) {url = app.url@@ -281,6 +282,7 @@ extension LeftoverMatcher {names = app.matchingNames.filter(Naming.isSignificant).map { $0.lowercased() }normalizedNames = Set(names.map(Naming.normalized))isApplesOwn = app.isSystemProtected || teamPrefix == Self.appleTeam+ isASafariWebApp = app.isASafariWebApp}func isSibling(of other: Profile) -> Bool {@@ -305,8 +307,10 @@ extension LeftoverMatcher {func evidence(for candidate: Candidate) -> Evidence? {let key = candidate.key// Everything an app says about itself (its identifier, what it embeds, the groups it claims)- // comes from a bundle anyone can write. Only an app Apple signed may answer for Apple's files.- guard !candidate.isApple || isApplesOwn else { return nil }+ // comes from a bundle anyone can write. Only an app Apple signed may answer for Apple's files, and a+ // Safari web app for the files named exactly by its own identifier, which Safari made for it alone.+ let isItsOwnWebAppName = isASafariWebApp && key == identifier+ guard !candidate.isApple || isApplesOwn || isItsOwnWebAppName else { return nil }if key == identifier {guard Identifier.isValid(key) else { return unproven(.bundleIdentifier, candidate) }diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swiftindex 8a04256d..df6a7cac 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift@@ -83,7 +83,9 @@ public struct LeftoverScanner: Sendable {@concurrentfunc scan(_ app: InstalledApp, matcher: LeftoverMatcher) async -> LeftoverScan {let results = await withTaskGroup(of: (location: SearchLocation, result: LocationResult).self) { group in- for location in environment.locations {+ // Safari's web app container is read only for one of its web apps: anything inside another app's+ // container makes macOS ask for its data unless Peel has Full Disk Access.+ for location in environment.locations where location.kind != .safariWebApps || app.isASafariWebApp {let home = environment.homeDirectory.path(percentEncoded: false)let bundle = PathPattern.comparablePath(of: app.url)_ = group.addTaskUnlessCancelled { [exclusions, measure, refuses, nestedFolderLimit] indiff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swiftindex 03b3c74d..87a28221 100644--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift@@ -44,6 +44,9 @@ public struct SearchLocation: Sendable, Hashable {/// The folders where a browser looks for the manifests of the programs its extensions may run. A manifest/// is named for its host, not for the app, so only one whose program is inside the app counts as the app's.case nativeMessagingHosts+ /// The folder inside Safari's own `com.apple.Safari.WebApp` container where it keeps a container for each of+ /// its web apps, named by that web app's identifier. Looked into only when a Safari web app is removed.+ case safariWebApps/// Somewhere no scan looks, which only a Homebrew cask can name: `~/Documents/Foo`, `/usr/local/etc/foo`.case elsewhere}@@ -209,6 +212,7 @@ public struct SearchEnvironment: Sendable {locations += hosts.flatMap { library, folders infolders.map { library.appending(path: $0, directoryHint: .isDirectory) }}.map { SearchLocation(kind: .nativeMessagingHosts, url: $0) }+ locations.append(SearchLocation(kind: .safariWebApps, url: SafariWebApp.containers(inLibrary: userLibrary)))locations.append(SearchLocation(kind: .sharedFolder,url: rootDirectory.appending(path: "Users/Shared", directoryHint: .isDirectory)diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swiftindex 78818950..0df28702 100644--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift@@ -83,8 +83,10 @@ public struct OrphanScanner: Sendable {let results = await withTaskGroup(of: LocationResult.self) { group inlet home = environment.homeDirectory.path(percentEncoded: false)// A browser's manifest is an app's only through the program it names, which an uninstall reads. Here one- // is still found by the identifier it is named for, inside Application Support.- for location in environment.locations where location.kind != .nativeMessagingHosts {+ // is still found by the identifier it is named for, inside Application Support. Safari's web app+ // container is another app's container, which macOS asks about, and is read only for one of its web apps.+ let skipped: Set<SearchLocation.Kind> = [.nativeMessagingHosts, .safariWebApps]+ for location in environment.locations where !skipped.contains(location.kind) {_ = group.addTaskUnlessCancelled { [exclusions, nestedFolderLimit, walk] inawait Self.scan(location, ownership: ownership, jobs: jobs, goneBundles: goneBundles, goneApps: goneApps,@@ -172,6 +174,7 @@ public struct OrphanScanner: Sendable {identifier.removeFirst("group.".count)}let lowercased = identifier.lowercased()+ if SafariWebApp.isIdentifier(identifier) { return identifier }guard !systemPrefixes.contains(where: lowercased.hasPrefix), !lowercased.contains("com.apple.") else { return nil }if Identifier.isReverseDNS(identifier) {diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swiftindex 28a11aa3..f443798c 100644--- a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift+++ b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift@@ -89,7 +89,7 @@ public struct AppReset: Sendable {case .preferences, .preferencesByHost, .savedApplicationState, .caches, .logs, .recentDocuments,.temporaryItems:.settings- case .cookies, .httpStorages, .webKit:+ case .cookies, .httpStorages, .webKit, .safariWebApps:.webDatacase .applicationSupport, .containers, .groupContainers, .applicationScripts:.appDatadiff --git a/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swiftindex a8e94bbf..786e5efd 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AppInspectorTests.swift@@ -332,6 +332,35 @@ struct AppInspectorTests {#expect(app.isFromAppStore)}+ /// Safari writes each web app as a template of its own `com.apple.Safari.WebApp`, named by the UUID it gives it.+ @Test func knowsASafariWebAppByTheTemplateSafariWrote() throws {+ let directory = try TemporaryDirectory()+ let uuid = "0E4F6A2C-1B3D-4E5F-8A9B-0C1D2E3F4A5B"+ func webApp(_ name: String, identifier: String, template: String = "com.apple.Safari.WebApp") throws -> URL {+ let info: [String: Any] = [+ "CFBundleIdentifier": identifier, "CFBundleName": name, "LSTemplateApplication": true,+ "LSTemplateApplicationParameters": [+ "CFBundleIdentifier": template, "TemplateAppUUID": uuid, "teamIdentifier": "0000000000",+ ],+ ]+ let contents = try directory.directory("\(name).app/Contents")+ try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0)+ .write(to: contents.appending(path: "Info.plist"))+ return directory.url.appending(path: "\(name).app")+ }++ let wiki = try #require(AppInspector.inspect(try webApp("Wiki", identifier: "com.apple.Safari.WebApp.\(uuid)")))+ #expect(wiki.isASafariWebApp)+ let otherUUID = try #require(+ AppInspector.inspect(try webApp("Other", identifier: "com.apple.Safari.WebApp.1A2B3C4D-0000-4000-8000-000000000000"))+ )+ #expect(!otherUUID.isASafariWebApp)+ let otherTemplate = try #require(+ AppInspector.inspect(try webApp("Mail", identifier: "com.apple.mail.\(uuid)", template: "com.apple.mail"))+ )+ #expect(!otherTemplate.isASafariWebApp)+ }+@Test func aWrappedBundleLinkThatLeadsOutOfTheWrapperIsNoApp() throws {let directory = try TemporaryDirectory()let elsewhere = try directory.directory("Elsewhere/example.app")diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swiftindex d3580a48..df445993 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackRemovalGuardTests.swift@@ -127,6 +127,21 @@ struct AttackRemovalGuardTests {/// Attack 1b: the guard lower-cases the path it is given, so `protectedPrefixes` must be lower-case too, or/// those entries would match nothing.+ /// The folder where Safari keeps every web app's container is never moved whole, while one web app's container+ /// inside it can go with that web app.+ @Test func safarisWebAppContainersStayWhileOneWebAppsCanGo() 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 webApps = "home/Library/Containers/com.apple.Safari.WebApp/Data/Library/Containers"+ let one = try directory.directory("\(webApps)/com.apple.Safari.WebApp.0E4F6A2C-1B3D-4E5F-8A9B-0C1D2E3F4A5B")++ #expect(!guardian.allowsRemoval(of: directory.url.appending(path: webApps, directoryHint: .isDirectory)))+ #expect(guardian.allowsRemoval(of: one))+ }+@Test func protectedPrefixesSurviveTheLowerCasing() throws {let directory = try TemporaryDirectory()let home = directory.url.appending(path: "home", directoryHint: .isDirectory)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swiftindex 1b6b61c6..92e9650a 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverMatcherTests.swift@@ -32,6 +32,27 @@ struct LeftoverMatcherTests {.match(fileName: fileName, kind: kind)}+ /// A Safari web app's identifier is Safari's template followed by the web app's own UUID, so the files named+ /// exactly that are the web app's, though the name begins with `com.apple.`. Nothing else of Apple's is.+ @Test func aSafariWebAppClaimsOnlyWhatSafariNamedForIt() throws {+ let identifier = "com.apple.Safari.WebApp.0E4F6A2C-1B3D-4E5F-8A9B-0C1D2E3F4A5B"+ let wiki = InstalledApp(+ url: URL(filePath: "/Users/x/Applications/Wiki.app"),+ bundleIdentifier: identifier,+ name: "Wiki",+ isASafariWebApp: true+ )++ #expect(match("\(identifier).plist", in: .preferences, for: wiki)?.confidence == .certain)+ #expect(match(identifier, in: .safariWebApps, for: wiki)?.confidence == .certain)+ #expect(match("com.apple.Safari.WebApp", in: .containers, for: wiki) == nil)+ #expect(match("com.apple.Safari.WebApp.1A2B3C4D-0000-4000-8000-000000000000.plist", in: .preferences, for: wiki) == nil)+ #expect(match("com.apple.Safari.plist", in: .preferences, for: wiki) == nil)++ let pretender = InstalledApp(url: wiki.url, bundleIdentifier: identifier, name: "Wiki")+ #expect(match("\(identifier).plist", in: .preferences, for: pretender) == nil)+ }+/// The list of installed apps covers only `/Applications` and `~/Applications`. Chrome Canary kept on another/// disk is still installed, so Launch Services is asked about a longer identifier before it is taken for one/// of Chrome's own.diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swiftindex 624c0f7d..f2e2284e 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift@@ -92,6 +92,30 @@ struct LeftoverScannerTests {#expect(scan.leftovers.contains { $0.url.lastPathComponent == "org.example.hexachord.helper.plist" })}+ /// A Safari web app keeps its data in a container inside Safari's own web app container, and its settings beside+ /// every app's. Both are found when it is removed, and Safari's container itself never is.+ @Test func findsWhatASafariWebAppKeptInsideSafarisContainer() async throws {+ let directory = try TemporaryDirectory()+ let identifier = "com.apple.Safari.WebApp.0E4F6A2C-1B3D-4E5F-8A9B-0C1D2E3F4A5B"+ let webApps = "home/Library/Containers/com.apple.Safari.WebApp/Data/Library/Containers"+ try directory.file("\(webApps)/\(identifier)/Library/WebApp/PerSiteZoomPreferences.plist", bytes: 4096)+ try directory.file("\(webApps)/com.apple.Safari.WebApp.1A2B3C4D-0000-4000-8000-000000000000/Library/x.plist")+ try directory.file("home/Library/Preferences/\(identifier).plist", bytes: 4096)+ let wiki = InstalledApp(+ url: URL(filePath: "/Users/x/Applications/Wiki.app"),+ bundleIdentifier: identifier,+ name: "Wiki",+ isASafariWebApp: true+ )++ let scan = await LeftoverScanner(environment: environment(in: directory)).scan(wiki, installedApps: [wiki])++ #expect(Set(scan.leftovers.map { "\($0.kind.rawValue)/\($0.url.lastPathComponent)" }) == [+ "safariWebApps/\(identifier)", "preferences/\(identifier).plist",+ ])+ #expect(scan.leftovers.allSatisfy { $0.match.isRecommended })+ }+@Test func aCopyMacOSKnowsElsewhereSharesTheAppsFiles() async throws {let directory = try TemporaryDirectory()try directory.file("home/Library/Preferences/com.apple.CharacterPaletteIM.plist", bytes: 4096)diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swiftindex 46a6fef8..05af8cd3 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift@@ -314,6 +314,30 @@ struct OrphanScannerTests {#expect(await scanner.stillOrphaned(group.items, installedApps: installed + [back]).isEmpty)}+ /// The settings a Safari web app leaves are named by its own identifier, which begins with `com.apple.`. Once+ /// the web app is gone they are orphans, while an installed web app keeps its own and Safari keeps Safari's.+ @Test func findsTheSettingsASafariWebAppThatLeftKept() async throws {+ let directory = try TemporaryDirectory()+ let gone = "com.apple.Safari.WebApp.0E4F6A2C-1B3D-4E5F-8A9B-0C1D2E3F4A5B"+ let kept = "com.apple.Safari.WebApp.1A2B3C4D-0000-4000-8000-000000000000"+ try directory.file("home/Library/Preferences/\(gone).plist", bytes: 4096)+ try directory.file("home/Library/Preferences/\(kept).plist")+ try directory.file("home/Library/Preferences/com.apple.Safari.plist")+ let wiki = RememberedApp(+ bundleIdentifier: gone, name: "Wiki", teamIdentifier: nil,+ lastSeen: .now.addingTimeInterval(-24 * 60 * 60), lastPath: "/Users/x/Applications/Wiki.app"+ )+ let news = InstalledApp(+ url: URL(filePath: "/Users/x/Applications/News Site.app"), bundleIdentifier: kept, name: "News Site",+ isASafariWebApp: true+ )++ let groups = await scanner(in: directory).scan(installedApps: installed + [news], remembered: [wiki]).groups++ #expect(groups.map(\.identifier) == [gone])+ #expect(groups.first?.items.map(\.url.lastPathComponent) == ["\(gone).plist"])+ }+@Test func reportsOnlyUnclaimedAppItems() async throws {let directory = try TemporaryDirectory()try directory.file("home/Library/Preferences/com.gone.app.plist")diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swiftindex 669bf321..7e0bb4fc 100644--- a/Peel/Views/Presentation.swift+++ b/Peel/Views/Presentation.swift@@ -54,7 +54,7 @@ extension SearchLocation.Kind {case .applicationSupport: "Application Support"case .applicationScripts: "Application Scripts"case .caches: LocalizedStringResource("Caches (Library folder)", defaultValue: "Caches")- case .containers: "Container"+ case .containers, .safariWebApps: "Container"case .groupContainers: "Group Container"case .preferences, .preferencesByHost: "Preferences"case .savedApplicationState: "Saved Windows"@@ -90,7 +90,7 @@ extension SearchLocation.Kind {case .commandLineTools: "terminal"case .nativeMessagingHosts: "puzzlepiece.extension"case .elsewhere: "mappin.and.ellipse"- case .containers, .groupContainers: "shippingbox"+ case .containers, .groupContainers, .safariWebApps: "shippingbox"case .preferences, .preferencesByHost: "gearshape"case .savedApplicationState: "macwindow"case .recentDocuments: "clock.arrow.circlepath"