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.

Let the helper take a browser's manifest that starts nothing from /Library

Țugui Dragoș9d88752c1772
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index af047941..1267ba8e 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -101,7 +101,8 @@ Take the most common case, uninstalling an app. Every other page follows the sam
- `TrashService` asks `RemovalGuard` about each item first, holds the folder around the item open, asks again
about what the kernel calls that folder, and moves the item through it, so the thing judged is the thing
moved. Items only an administrator can move go through the helper, and the links an app's tools and their
- shell completions left in `/usr/local` go last, once the app they lead into has moved.
+ shell completions left in `/usr/local` go last, once the app they lead into has moved. A browser's manifest in
+ `/Library` goes through the helper too, which takes it only once the program it names is gone.
- An item stays where it is while a program holds it (`OpenFiles`): a file one of the user's programs holds
open, or the program any process runs from it. Inside an app, which is code and loses nothing when it moves,
a file open only for reading holds nothing, and neither does the program running from an app that
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index c07b3ee0..413b120a 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -44635,6 +44635,112 @@
}
}
},
+ "From that folder, Peel removes only what starts a program that is no longer there." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Z této složky Peel odstraňuje jen soubory, které spouštějí program, který už neexistuje."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aus diesem Ordner entfernt Peel nur Dateien, die ein Programm starten, das nicht mehr vorhanden ist."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "De esa carpeta, Peel solo elimina archivos que inician un programa que ya no está."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dans ce dossier, Peel ne supprime que ce qui lance un programme qui n’est plus là."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Da quella cartella Peel rimuove solo ciò che avvia un programma che non c’è più."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "そのフォルダからPeelがゴミ箱に入れるのは、もう存在しないプログラムを起動するものだけです。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "그 폴더에서 Peel은 시작하는 프로그램이 더 이상 없는 항목만 제거합니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel verwijdert uit die map alleen onderdelen die een programma starten dat er niet meer is."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Z tego folderu Peel przenosi do Kosza tylko to, co uruchamia program, którego już nie ma."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dessa pasta, o Peel só remove o que inicia um programa que não existe mais."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Din acel dosar, Peel elimină doar ce pornește un program care nu mai există."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Из этой папки Peel удаляет только то, что запускает программу, которой больше нет."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Från den mappen tar Peel bara bort det som startar ett program som inte längre finns."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel o klasörden yalnızca artık yerinde olmayan bir programı başlatanları kaldırır."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "З цієї папки Peel вилучає лише те, що запускає виконуваний файл, якого вже немає."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel只会从该文件夹中移除用于启动一个已不存在的程序的文件。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel只會從該檔案夾移除所啟動的程式已不存在的項目。"
+ }
+ }
+ }
+ },
"From ~/.ssh/config" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift
index 72094d29..a798a291 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/NativeMessagingManifest.swift
@@ -1,25 +1,20 @@
import Foundation
+internal import PeelPrivileged
-/// 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.
+extension NativeMessagingManifest {
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)
+ guard isManifest(named: url.lastPathComponent), let data = BoundedRead.data(at: url, maximum: maximumSize)
else { return nil }
- return program
+ return program(in: data)
}
/// Whether the manifest at `url` starts nothing: a link that leads nowhere, or a manifest naming a program that is
- /// not there, on a disk that is connected.
+ /// gone.
static func startsNothing(at url: URL) -> Bool {
let path = url.path(percentEncoded: false)
if (try? FileManager.default.destinationOfSymbolicLink(atPath: path)) != nil {
return !FileManager.default.fileExists(atPath: path)
}
- guard let program = program(at: url) else { return false }
- return !FileManager.default.fileExists(atPath: program) && !URL(filePath: program).isOnADiskNotConnected
+ return program(at: url).map(isGone) ?? false
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift
index 0c6a3249..fceed67b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift
@@ -236,7 +236,10 @@ public struct SearchEnvironment: Sendable {
}.map {
SearchLocation(kind: .shellCompletions, url: rootDirectory.appending(path: $0, directoryHint: .isDirectory))
}
- let hosts = [(userLibrary, Self.nativeMessagingHosts.user), (localLibrary, Self.nativeMessagingHosts.local)]
+ let hosts = [
+ (userLibrary, NativeMessagingFolder.inTheUsersLibrary),
+ (localLibrary, NativeMessagingFolder.inTheMacsLibrary),
+ ]
locations += hosts.flatMap { library, folders in
folders.map { folder in
SearchLocation(
@@ -260,50 +263,6 @@ public struct SearchEnvironment: Sendable {
return locations
}
- /// A folder browsers read native messaging manifests from, with the apps that read it besides its own browser.
- struct NativeMessagingFolder: Sendable, ExpressibleByStringLiteral {
- let path: String
- var alsoReadBy: [String] = []
-
- init(stringLiteral path: String) {
- self.path = path
- }
-
- init(_ path: String, alsoReadBy: [String]) {
- self.path = path
- self.alsoReadBy = alsoReadBy
- }
- }
-
- /// Each browser's own documentation: Chrome's and Chromium's "Native messaging", MDN's "Native manifests" for
- /// Firefox, and Microsoft's "Native messaging" for Edge and its Beta, Dev, and Canary channels. Chrome's other
- /// channels keep theirs in their own user data folder (Chromium's `docs/user_data_dir.md`), and Chrome for
- /// Testing has its own in `/Library` (`chrome/common/chrome_paths.cc`). Every build of Brave reads Chrome's two
- /// on the Mac, where other apps leave their manifests (brave-core `app/brave_main_delegate.cc` at
- /// 5e268a047e51ba615c536db3aabbb782eb34550c, and its `app/theme/*/BRANDING` for each build's identifier).
- static let nativeMessagingHosts: (user: [NativeMessagingFolder], local: [NativeMessagingFolder]) = (
- user: [
- NativeMessagingFolder("Application Support/Google/Chrome/NativeMessagingHosts", alsoReadBy: ["com.brave.Browser"]),
- "Application Support/Google/Chrome Beta/NativeMessagingHosts",
- "Application Support/Google/Chrome Dev/NativeMessagingHosts",
- "Application Support/Google/Chrome Canary/NativeMessagingHosts",
- "Application Support/Google/Chrome for Testing/NativeMessagingHosts",
- "Application Support/Chromium/NativeMessagingHosts",
- "Application Support/Mozilla/NativeMessagingHosts",
- "Application Support/Microsoft Edge/NativeMessagingHosts",
- "Application Support/Microsoft Edge Beta/NativeMessagingHosts",
- "Application Support/Microsoft Edge Dev/NativeMessagingHosts",
- "Application Support/Microsoft Edge Canary/NativeMessagingHosts",
- ],
- local: [
- NativeMessagingFolder("Google/Chrome/NativeMessagingHosts", alsoReadBy: ["com.brave.Browser"]),
- "Google/ChromeForTesting/NativeMessagingHosts",
- "Application Support/Chromium/NativeMessagingHosts",
- "Application Support/Mozilla/NativeMessagingHosts",
- "Microsoft/Edge/NativeMessagingHosts",
- ]
- )
-
private static func darwinUserDirectory(_ name: Int32) -> URL? {
let length = confstr(name, nil, 0)
guard length > 0 else { return nil }
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
index 0a584b3c..4718a036 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
@@ -14,7 +14,8 @@ struct HelperReach: Sendable {
systemLocations: PrivilegedPathPolicy.systemLocations.map { base + $0 },
applicationLocations: [base + "/Applications"],
restoreLocations: PrivilegedPathPolicy.restoreLocations.map { base + $0 },
- linkLocations: PrivilegedPathPolicy.linkLocations.map { base + $0 }
+ linkLocations: PrivilegedPathPolicy.linkLocations.map { base + $0 },
+ manifestLocations: PrivilegedPathPolicy.manifestLocations.map { base + $0 }
)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
index 6d892845..39ad9843 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
@@ -9,6 +9,7 @@ public enum FixedSentence: CaseIterable, Sendable {
case notAFullPath, dotInPath, controlCharacter, folderNotFound, tooManyOpenFolders, outsideHelpersFolders
case onlyAppsThere
case notThereAnymore, alreadyThere, protectedByMacOS, irreplaceable, codeFolder, onlyLinksThere, leadsSomewhere
+ case onlyGoneProgramsThere
case helperOutOfDate, accountNotAllowed, tooManyItems, noTrash, pathTooLong, cannotKeepRecord, cannotReadRecord
case notInTrash, notMovedByHelper, invalidRequest, configurationMissing
case toolTimedOut, toolStopped
@@ -36,6 +37,7 @@ public enum FixedSentence: CaseIterable, Sendable {
case .codeFolder: PrivilegedPathPolicy.Rejection.loadsCode.explanation
case .onlyLinksThere: PrivilegedPathPolicy.Rejection.notALink.explanation
case .leadsSomewhere: PrivilegedPathPolicy.Rejection.leadsSomewhere.explanation
+ case .onlyGoneProgramsThere: PrivilegedPathPolicy.Rejection.startsAProgram.explanation
case .helperOutOfDate: HelperRefusal.outOfDate.rawValue
case .accountNotAllowed: HelperRefusal.notAllowed.rawValue
case .tooManyItems: HelperRefusal.tooManyItems.rawValue
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
index 092d135e..4761261d 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/DirectoryHandle.swift
@@ -133,20 +133,28 @@ public final class OpenItem: Sendable {
}
extension OpenItem {
- /// Deletes this item for good when it is a regular file of `owner`, at most `maximum` bytes, whose bytes
- /// `isDisposable` accepts. The file is read without following a link, and its name is removed only while it
- /// still leads to the file that was read.
- public func deleteFile(ownedBy owner: uid_t, ofAtMost maximum: Int, if isDisposable: (Data) -> Bool) {
- guard let identity, let mode, mode & S_IFMT == S_IFREG else { return }
+ /// The bytes of this item while it is still the regular file that was judged, at most `maximum` of them, read
+ /// without following a link, with the status of the file they were read from.
+ func contents(ofAtMost maximum: Int) -> (data: Data, status: stat)? {
+ guard let identity, let mode, mode & S_IFMT == S_IFREG else { return nil }
let file = name.withCString { openat(parent.descriptor, $0, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) }
- guard file >= 0 else { return }
+ guard file >= 0 else { return nil }
var info = stat()
var bytes = [UInt8](repeating: 0, count: maximum + 1)
let count = fstat(file, &info) == 0 ? read(file, &bytes, bytes.count) : -1
close(file)
- guard
- ItemIdentity(info) == identity, info.st_uid == owner, count >= 0, count <= maximum,
- Int64(count) == info.st_size, isDisposable(Data(bytes[..<count]))
+ guard ItemIdentity(info) == identity, count >= 0, count <= maximum, Int64(count) == info.st_size else {
+ return nil
+ }
+ return (Data(bytes[..<count]), info)
+ }
+
+ /// Deletes this item for good when it is a regular file of `owner`, at most `maximum` bytes, whose bytes
+ /// `isDisposable` accepts. The file is read without following a link, and its name is removed only while it
+ /// still leads to the file that was read.
+ public func deleteFile(ownedBy owner: uid_t, ofAtMost maximum: Int, if isDisposable: (Data) -> Bool) {
+ guard let identity, let contents = contents(ofAtMost: maximum), contents.status.st_uid == owner,
+ isDisposable(contents.data)
else { return }
var now = stat()
guard
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/NativeMessaging.swift b/Packages/PeelCore/Sources/PeelPrivileged/NativeMessaging.swift
new file mode 100644
index 00000000..70671c1a
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelPrivileged/NativeMessaging.swift
@@ -0,0 +1,75 @@
+import Darwin
+public import Foundation
+
+/// A folder browsers read native messaging manifests from, with the apps that read it besides its own browser.
+public struct NativeMessagingFolder: Sendable, ExpressibleByStringLiteral {
+ public let path: String
+ public var alsoReadBy: [String] = []
+
+ public init(stringLiteral path: String) {
+ self.path = path
+ }
+
+ public init(_ path: String, alsoReadBy: [String]) {
+ self.path = path
+ self.alsoReadBy = alsoReadBy
+ }
+
+ /// Each browser's own documentation: Chrome's and Chromium's "Native messaging", MDN's "Native manifests" for
+ /// Firefox, and Microsoft's "Native messaging" for Edge and its Beta, Dev, and Canary channels. Chrome's other
+ /// channels keep theirs in their own user data folder (Chromium's `docs/user_data_dir.md`), and Chrome for
+ /// Testing has its own in `/Library` (`chrome/common/chrome_paths.cc`). Every build of Brave reads Chrome's two
+ /// on the Mac, where other apps leave their manifests (brave-core `app/brave_main_delegate.cc` at
+ /// 5e268a047e51ba615c536db3aabbb782eb34550c, and its `app/theme/*/BRANDING` for each build's identifier).
+ public static let inTheUsersLibrary: [NativeMessagingFolder] = [
+ NativeMessagingFolder("Application Support/Google/Chrome/NativeMessagingHosts", alsoReadBy: ["com.brave.Browser"]),
+ "Application Support/Google/Chrome Beta/NativeMessagingHosts",
+ "Application Support/Google/Chrome Dev/NativeMessagingHosts",
+ "Application Support/Google/Chrome Canary/NativeMessagingHosts",
+ "Application Support/Google/Chrome for Testing/NativeMessagingHosts",
+ "Application Support/Chromium/NativeMessagingHosts",
+ "Application Support/Mozilla/NativeMessagingHosts",
+ "Application Support/Microsoft Edge/NativeMessagingHosts",
+ "Application Support/Microsoft Edge Beta/NativeMessagingHosts",
+ "Application Support/Microsoft Edge Dev/NativeMessagingHosts",
+ "Application Support/Microsoft Edge Canary/NativeMessagingHosts",
+ ]
+
+ public static let inTheMacsLibrary: [NativeMessagingFolder] = [
+ NativeMessagingFolder("Google/Chrome/NativeMessagingHosts", alsoReadBy: ["com.brave.Browser"]),
+ "Google/ChromeForTesting/NativeMessagingHosts",
+ "Application Support/Chromium/NativeMessagingHosts",
+ "Application Support/Mozilla/NativeMessagingHosts",
+ "Microsoft/Edge/NativeMessagingHosts",
+ ]
+}
+
+/// A browser's native messaging manifest, a small JSON file naming the program the browser starts for an extension.
+public enum NativeMessagingManifest {
+ public static let maximumSize = 64 * 1_024
+
+ public static func isManifest(named name: String) -> Bool {
+ URL(filePath: name).pathExtension == "json"
+ }
+
+ /// The program `data` names, or nil when it can't be told: a NUL in the path would end it where the kernel reads
+ /// it.
+ public static func program(in data: Data) -> String? {
+ guard 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
+ }
+
+ /// Whether `program` is not there, on a disk that is connected: one on a disk that is away may come back.
+ public static func isGone(_ program: String) -> Bool {
+ var info = stat()
+ guard stat(program, &info) != 0 else { return false }
+ let error = errno
+ guard error == ENOENT || error == ENOTDIR else { return false }
+ let names = PathComponents.of(program)
+ guard names.count > 2, names[0] == "Volumes" else { return true }
+ var volume = stat()
+ return lstat("/Volumes/" + names[1], &volume) == 0
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift
index 1f0250f5..3bdb3a7b 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift
@@ -18,6 +18,7 @@ public struct PrivilegedPathPolicy: Sendable {
case loadsCode
case notALink
case leadsSomewhere
+ case startsAProgram
/// What the helper sends back when it refuses. The app recognizes it and says it in the reader's language.
public var explanation: String {
@@ -36,6 +37,7 @@ public struct PrivilegedPathPolicy: Sendable {
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."
+ case .startsAProgram: "From that folder, Peel removes only what starts a program that is no longer there."
}
}
@@ -73,12 +75,17 @@ public struct PrivilegedPathPolicy: Sendable {
"share/zsh/site-functions", "share/fish/vendor_completions.d", "etc/bash_completion.d", "share/pwsh/completions",
]
+ /// The folders of `/Library` browsers read native messaging manifests from. The helper takes from them only a
+ /// manifest that starts nothing, as it judges the item it opened.
+ public static let manifestLocations = NativeMessagingFolder.inTheMacsLibrary.map { "/Library/" + $0.path }
+
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 manifests: [String]
/// The device and inode of the `peel` tool inside the app the helper runs from.
private let ownTool: (device: dev_t, inode: ino_t)?
/// The folders of the home's Library that Peel searches, lowercased, as names from the root.
@@ -92,18 +99,20 @@ public struct PrivilegedPathPolicy: Sendable {
applicationLocations: [String] = ["/Applications"],
restoreLocations: [String] = Self.restoreLocations,
linkLocations: [String] = Self.linkLocations,
+ manifestLocations: [String] = Self.manifestLocations,
ownTool: String? = nil,
trustedOwner: uid_t = 0
) {
self.homeDirectory = homeDirectory
self.trustedOwner = trustedOwner
links = linkLocations.compactMap(Self.realPath)
+ manifests = manifestLocations.compactMap(Self.realPath)
self.ownTool = ownTool.flatMap { path in
var info = stat()
guard stat(path, &info) == 0 else { return nil }
return (info.st_dev, info.st_ino)
}
- locations = (systemLocations + [homeDirectory + "/Library"]).compactMap(Self.realPath) + links
+ locations = (systemLocations + [homeDirectory + "/Library"]).compactMap(Self.realPath) + links + manifests
restorable = (restoreLocations + [homeDirectory + "/Library"]).compactMap(Self.realPath)
self.applicationLocations = applicationLocations.compactMap(Self.realPath)
let library = Self.realPath(homeDirectory + "/Library") ?? homeDirectory + "/Library"
@@ -171,10 +180,14 @@ 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.
+ // A tool's link sits directly in its folder, never deeper, and so does a browser's manifest.
if links.contains(location), resolvedParent != location {
return .failure(.outsideAllowedLocations)
}
+ if manifests.contains(resolved)
+ || manifests.contains(where: { PathComponents.isPath(resolved, inside: $0) && resolvedParent != $0 }) {
+ return .failure(.outsideAllowedLocations)
+ }
if applicationLocations.contains(location), !name.hasSuffix(".app") {
return .failure(.notAnApplication)
}
@@ -212,11 +225,31 @@ public struct PrivilegedPathPolicy: Sendable {
return .failure(.leadsSomewhere)
}
}
- return .success(OpenItem(path: item.path, name: item.name, parent: parent, status: info))
+ let opened = OpenItem(path: item.path, name: item.name, parent: parent, status: info)
+ if manifests.contains(item.parent), !Self.startsNothing(opened, status: info) {
+ return .failure(.startsAProgram)
+ }
+ return .success(opened)
}
}
}
+ /// Whether `item`, in a folder browsers read native messaging manifests from, starts nothing: a link that leads
+ /// nowhere, or a manifest whose bytes, read from the file that was judged, name a program that is gone.
+ private static func startsNothing(_ item: OpenItem, status: stat) -> Bool {
+ if status.st_mode & S_IFMT == S_IFLNK {
+ var target = stat()
+ let leads = item.name.withCString { fstatat(item.parent.descriptor, $0, &target, 0) } == 0
+ let error = errno
+ return !leads && (error == ENOENT || error == ENOTDIR || error == ELOOP)
+ }
+ guard NativeMessagingManifest.isManifest(named: item.name),
+ let contents = item.contents(ofAtMost: NativeMessagingManifest.maximumSize),
+ let program = NativeMessagingManifest.program(in: contents.data)
+ else { return false }
+ return NativeMessagingManifest.isGone(program)
+ }
+
/// Like `open`, for a path where nothing exists yet. A folder that code is loaded from takes back only an
/// item owned by root that nobody else can write to, which is how anything the helper took from there
/// looks. Anything else could have been rewritten while it sat in the user's Trash.
@@ -226,7 +259,9 @@ public struct PrivilegedPathPolicy: Sendable {
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) }) {
+ // A browser starts the program a manifest names, so its folder is one that code is loaded from.
+ if !restorable.contains(where: { PathComponents.isPath(item.path, inside: $0) })
+ || manifests.contains(item.parent) {
guard trashed.owner == trustedOwner, let mode = trashed.mode, mode & 0o022 == 0 else {
return .failure(.loadsCode)
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
index eaaf2417..2d39da2b 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftoverScannerTests.swift
@@ -1803,6 +1803,25 @@ struct LeftoverScannerTests {
#expect(manifest?.match.isRecommended == true)
}
+ @Test(.permissionsHold) func movesTheAppsManifestFromTheMacsChromeFolderThroughTheHelper() async throws {
+ let directory = try TemporaryDirectory()
+ let hosts = "root/Library/Google/Chrome/NativeMessagingHosts"
+ try directory.file("\(hosts)/com.example.bridge.json", contents: Data("""
+ {"name": "com.example.bridge", "path": "/Applications/Tunewell.app/Contents/MacOS/bridge", "type": "stdio"}
+ """.utf8))
+ try directory.setPermissions(0o555, of: hosts)
+ defer { try? directory.setPermissions(0o755, of: hosts) }
+
+ let scanner = LeftoverScanner(environment: environment(in: directory))
+ let found = await scanner.scan(tunewell, installedApps: [tunewell])
+ let reach = HelperReach(environment: environment(in: directory))
+ let scan = found.holdingBack(beyond: reach, leaving: tunewell.url)
+
+ let manifest = try #require(scan.leftovers.first { $0.url.lastPathComponent == "com.example.bridge.json" })
+ #expect(manifest.requiresPrivileges)
+ #expect(manifest.match.heldBack != .beyondTheHelper)
+ }
+
/// Only the program a manifest runs says whose it is, wherever its NativeMessagingHosts folder sits: one named
/// after this app's identifier but running another program is not this app's, and one in a browser's folder that
/// is not listed is found by its program all the same.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift
index 5dce338f..562cc3a7 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PrivilegedPathPolicyTests.swift
@@ -23,6 +23,7 @@ struct PrivilegedPathPolicyTests {
try directory.directory("root/Library/Caches")
try directory.directory("home/Library")
try directory.directory("root/usr/local/bin")
+ try directory.directory("root/Library/Google/Chrome/NativeMessagingHosts")
let root = directory.url.path(percentEncoded: false)
return PrivilegedPathPolicy(
homeDirectory: root + "home",
@@ -30,6 +31,7 @@ struct PrivilegedPathPolicyTests {
applicationLocations: [root + "root/Applications"],
restoreLocations: [root + "root/Applications", root + "root/Library/Caches"],
linkLocations: [root + "root/usr/local/bin"],
+ manifestLocations: [root + "root/Library/Google/Chrome/NativeMessagingHosts"],
ownTool: ownTool,
trustedOwner: trustedOwner
)
@@ -100,6 +102,66 @@ struct PrivilegedPathPolicyTests {
#expect(policy.openDestination(path("root/usr/local/bin/gone2", in: directory), for: trashedLink).map(\.name) == .success("gone2"))
}
+ @Test func takesFromAManifestFolderOnlyWhatStartsNothing() throws {
+ let directory = try TemporaryDirectory()
+ let policy = try policy(in: directory)
+ let folder = "root/Library/Google/Chrome/NativeMessagingHosts"
+ try directory.file("root/Applications/Tool.app/Contents/MacOS/host")
+ func manifest(_ name: String, naming program: String) throws {
+ let json = #"{"name": "org.example.host", "path": "\#(program)", "type": "stdio"}"#
+ try directory.file("\(folder)/\(name)", contents: Data(json.utf8))
+ }
+ try manifest("gone.json", naming: path("root/Applications/Gone.app/Contents/MacOS/host", in: directory))
+ try manifest("there.json", naming: path("root/Applications/Tool.app/Contents/MacOS/host", in: directory))
+ try manifest("away.json", naming: "/Volumes/org.example.away/Host.app/Contents/MacOS/host")
+ try directory.file("\(folder)/broken.json", contents: Data("{".utf8))
+ try directory.directory("\(folder)/folder.json")
+ try manifest("folder.json/deeper.json", naming: "/nowhere")
+ let links = [("nowhere.json", "missing.json"), ("somewhere.json", "there.json")]
+ for (name, destination) in links {
+ try FileManager.default.createSymbolicLink(
+ atPath: path("\(folder)/\(name)", in: directory), withDestinationPath: destination
+ )
+ }
+
+ for name in ["gone.json", "nowhere.json"] {
+ #expect((try? policy.open(path("\(folder)/\(name)", in: directory)).get()) != nil, "\(name) was refused")
+ }
+ for name in ["there.json", "away.json", "broken.json", "folder.json", "somewhere.json"] {
+ let opened = policy.open(path("\(folder)/\(name)", in: directory))
+ #expect(opened.map(\.name) == .failure(.startsAProgram), "\(name)")
+ }
+ #expect(policy.refusal(of: path("\(folder)/folder.json/deeper.json", in: directory)) == .outsideAllowedLocations)
+ #expect(policy.refusal(of: path(folder, in: directory)) == .outsideAllowedLocations)
+ let item = try trashed("gone.json", in: directory, by: policy)
+ #expect(policy.openDestination(path("\(folder)/gone.json", in: directory), for: item).rejection == .loadsCode)
+ }
+
+ @Test func aManifestFolderInsideAServedFolderTakesOnlyWhatStartsNothing() throws {
+ let directory = try TemporaryDirectory()
+ let folder = "root/Library/Application Support/Mozilla/NativeMessagingHosts"
+ try directory.file("root/Applications/Tool.app/Contents/MacOS/host")
+ let json = #"{"name": "org.example.host", "path": "\#(path("root/Applications/Tool.app/Contents/MacOS/host", in: directory))"}"#
+ try directory.file("\(folder)/there.json", contents: Data(json.utf8))
+ try directory.file("root/Library/Application Support/Example/settings.plist")
+ let root = directory.url.path(percentEncoded: false)
+ let policy = PrivilegedPathPolicy(
+ homeDirectory: root + "home",
+ systemLocations: [root + "root/Library/Application Support"],
+ restoreLocations: [root + "root/Library/Application Support"],
+ linkLocations: [],
+ manifestLocations: [root + folder],
+ trustedOwner: getuid()
+ )
+
+ #expect(policy.open(path("\(folder)/there.json", in: directory)).map(\.name) == .failure(.startsAProgram))
+ #expect(policy.refusal(of: path(folder, in: directory)) == .outsideAllowedLocations)
+ let settings = path("root/Library/Application Support/Example/settings.plist", in: directory)
+ #expect((try? policy.open(settings).get()) != nil)
+ let item = try trashed("there.json", permissions: 0o664, in: directory, by: policy)
+ #expect(policy.openDestination(path("\(folder)/there.json", in: directory), for: item).rejection == .loadsCode)
+ }
+
/// Remove Peel hands the helper the link to Peel's own tool while the app is still in place, so that link goes
/// though it leads somewhere. A link to anything else still stays.
@Test func takesTheLinkToThePeelToolOfTheAppItRunsFrom() throws {
diff --git a/Peel/Views/FixedSentenceText.swift b/Peel/Views/FixedSentenceText.swift
index aa33e070..aecc7ac3 100644
--- a/Peel/Views/FixedSentenceText.swift
+++ b/Peel/Views/FixedSentenceText.swift
@@ -19,6 +19,7 @@ extension FixedSentence {
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 .onlyGoneProgramsThere: "From that folder, Peel removes only what starts a program that is no longer there."
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.md
index 82411362..d74c3b0b 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -527,7 +527,8 @@ and it fails closed.
of `/Library` (Application Support, Caches, Preferences, Logs, LaunchAgents, LaunchDaemons,
PrivilegedHelperTools, and StartupItems) and the 22 that hold plug-ins; the installer receipts in
`/private/var/db/receipts`; the links in `/usr/local/bin`, `/usr/local/sbin`, and the four folders of
- `/usr/local` that shell completions are linked into; and the Library of the administrator who asks.
+ `/usr/local` that shell completions are linked into; the folders of `/Library` browsers read native messaging
+ manifests from; and the Library of the administrator who asks.
- It takes at most 100 items in one request, and quits 30 seconds after its last request ends, or as soon as
it is idle once an update has replaced it, so it isn't left running.
- A path with a control character in it is refused. The rules read the whole name and the system stops at
@@ -542,6 +543,12 @@ and it fails closed.
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. The one exception is a link to the `peel`
command inside the Peel the helper runs from, which Remove Peel hands it before the helper goes.
+- From the folders of `/Library` browsers read native messaging manifests from (`Google/Chrome`,
+ `Google/ChromeForTesting`, and `Microsoft/Edge`, and Chromium's and Mozilla's in Application Support, each in its
+ `NativeMessagingHosts`), it takes only a manifest that starts nothing: a link that leads nowhere, or a file that
+ names a program that is no longer there, as the helper reads the file itself. Peel sends an app's manifest after
+ the app, so it goes once the app is gone, and one that still starts a program stays. A browser starts what a
+ manifest there names, so these folders take back only what is owned by root and writable by nobody else.
- It never reuses a path after checking it. It opens the parent directory, checks the item there as the system
names that directory, works only through that descriptor, and moves the item only while it is still the one it
checked, so a folder or an item swapped after the check leads nowhere.