Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Judge a browser's manifest in Orphaned Files by the program it starts

Țugui Dragoș63ccaf94bda2
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
index 31afbae4..3c6f8515 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
@@ -472,10 +472,7 @@ public struct LeftoverScanner: Sendable {
/// A browser's native messaging manifest is the app's when the program it names, an absolute path, is inside it.
private static func runsSomethingInside(_ bundle: String, manifest url: URL) -> LeftoverMatch? {
- guard url.pathExtension == "json", let data = BoundedRead.data(at: url, maximum: 64 * 1_024),
- let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let program = manifest["path"] as? String, program.hasPrefix("/")
- else { return nil }
+ guard let program = NativeMessagingManifest.program(at: url) else { return nil }
let path = PathPattern.comparablePath(of: URL(filePath: program))
guard PathComponents.isPath(path, atOrInside: bundle) else { return nil }
return LeftoverMatch(reason: .nativeMessagingHost, confidence: .certain, sharedWith: [])
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift
new file mode 100644
index 00000000..d7035df5
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift
@@ -0,0 +1,14 @@
+import Foundation
+
+/// A browser's native messaging manifest, which names the program the browser starts for an extension.
+enum NativeMessagingManifest {
+ /// The program the manifest at `url` names, or nil when it can't be told: a manifest is a small JSON file, and a
+ /// NUL in the path would end it where the kernel reads it.
+ static func program(at url: URL) -> String? {
+ guard url.pathExtension == "json", let data = BoundedRead.data(at: url, maximum: 64 * 1_024),
+ let manifest = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let program = manifest["path"] as? String, program.hasPrefix("/"), !program.utf8.contains(0)
+ else { return nil }
+ return program
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
index 7c6833c6..2b032596 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
@@ -86,8 +86,7 @@ public struct OrphanScanner: Sendable {
let results = await withTaskGroup(of: LocationResult.self) { group in
let 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. Safari's web app
+ // A browser's manifest is an app's only through the program it names (`servesAProgram`). 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) {
@@ -125,10 +124,12 @@ public struct OrphanScanner: Sendable {
? Set((await systemExtensions() ?? []).filter { $0.election == .beingRemoved }.compactMap(\.url)
.map(PathPattern.comparablePath(of:)))
: []
+ let folders = manifestFolders
let kept = found.filter {
!exclusions.excludes($0.item.url) && !exclusions.holds($0.item.url)
&& !exclusions.excludes(bundleIdentifier: $0.identifier)
&& !(owners[$0.identifier.lowercased()].map { here.contains($0.lowercased()) } ?? false)
+ && !Self.servesAProgram($0.item.url, in: folders)
}
.map { entry in
var item = entry.item
@@ -153,6 +154,19 @@ public struct OrphanScanner: Sendable {
)
}
+ private var manifestFolders: Set<String> {
+ let manifests = environment.locations.filter { $0.kind == .nativeMessagingHosts }
+ return Set(manifests.map { PathPattern.comparablePath(of: $0.url) })
+ }
+
+ /// Whether `url` is a manifest in a folder browsers read native messaging manifests from that still serves its
+ /// program: one that is there, or that can't be told. Whatever it is named for, it is no orphan then.
+ static func servesAProgram(_ url: URL, in folders: Set<String>) -> Bool {
+ guard folders.contains(PathPattern.comparablePath(of: url.deletingLastPathComponent())) else { return false }
+ guard let program = NativeMessagingManifest.program(at: url) else { return true }
+ return FileManager.default.fileExists(atPath: program)
+ }
+
/// The apps installed now, with those `remembered` holds that are only out of sight, and the remembered apps
/// that are gone. `remembered` also holds the apps installed now, and only an app that is gone can have left
/// files behind.
@@ -180,8 +194,9 @@ public struct OrphanScanner: Sendable {
isRegisteredApp: isRegisteredApp
)
let jobs = BackgroundItemOwnership(installedApps: installedApps + systemApps).knowingJobs(in: launchdFolders)
+ let folders = manifestFolders
var kept: [OrphanItem] = []
- for item in items {
+ for item in items where !Self.servesAProgram(item.url, in: folders) {
let isStillOrphaned = if let app = item.namedAfter {
await Self.goneApp(
named: item.url,
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
index 28f14be2..a44b7b94 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
@@ -95,6 +95,31 @@ struct OrphanScannerTests {
#expect(item(going)?.leftAlone == .systemExtensionGoingAtRestart)
}
+ @Test func aBrowsersManifestIsAnOrphanOnlyOnceItsProgramIsGone() async throws {
+ let directory = try TemporaryDirectory()
+ let folder = "home/Library/Application Support/Mozilla/NativeMessagingHosts"
+ let live = try directory.file("programs/host")
+ let gone = directory.url.appending(path: "programs/assist")
+ func manifest(_ name: String, program: URL) throws {
+ let text = #"{"name": "\#(name)", "path": "\#(program.path(percentEncoded: false))", "type": "stdio"}"#
+ try directory.file("\(folder)/\(name).json", contents: Data(text.utf8))
+ }
+ try manifest("org.example.remote", program: live)
+ try manifest("org.example.remote.assist", program: gone)
+ try directory.file("\(folder)/org.example.remote.broken.json", contents: Data("not a manifest".utf8))
+ let remote = RememberedApp(
+ bundleIdentifier: "org.example.remote", name: "Remote", teamIdentifier: nil, lastSeen: .now,
+ lastPath: "/Applications/Remote.app"
+ )
+ let scanner = scanner(in: directory)
+
+ let items = await scanner.scan(installedApps: installed, remembered: [remote]).groups.flatMap(\.items)
+
+ #expect(items.map(\.url.lastPathComponent) == ["org.example.remote.assist.json"])
+ try directory.file("programs/assist")
+ #expect(await scanner.stillOrphaned(items, installedApps: installed, remembered: [remote]).isEmpty)
+ }
+
/// The recent documents list macOS 26 writes (`.sfl4`) belongs to the installed app it is named for.
@Test func anInstalledAppsRecentDocumentListIsNoOrphan() async throws {
let directory = try TemporaryDirectory()