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.

Tell before and after that a plug-in only Finder can bring back

Țugui Dragoș182a0b7cc844
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index e9ec679d..dd948d5e 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -18648,6 +18648,112 @@
}
}
},
+ "Apps that use it may stop working. History can’t put it back, since code is loaded from its folder and it isn’t root’s alone, but you can drag it back out in Finder." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aplikace, které ho používají, mohou přestat fungovat. Historie ho nemůže vrátit zpět, protože se z jeho složky načítá kód a sám nepatří výhradně uživateli root, ale ve Finderu ho můžete přetáhnout zpět ven."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Apps, die es verwenden, funktionieren möglicherweise nicht mehr. Im Verlauf lässt es sich nicht zurücklegen, da aus seinem Ordner Code geladen wird und es nicht ausschließlich root gehört, du kannst es aber im Finder wieder herausziehen."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Puede que las apps que lo usan dejen de funcionar. Historial no puede restaurarlo, ya que no pertenece solo a root y desde su carpeta se carga código, pero puedes sacarlo arrastrándolo en el Finder."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Les apps qui l’utilisent peuvent cesser de fonctionner. L’Historique ne peut pas le remettre en place, car du code est chargé depuis son dossier et cet élément n’appartient pas uniquement à root, mais vous pouvez le sortir de la corbeille dans le Finder, en le faisant glisser."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Le app che lo usano potrebbero smettere di funzionare. La Cronologia non può ripristinarlo, perché dalla sua cartella viene caricato del codice e l’elemento non appartiene esclusivamente a root, ma puoi trascinarlo fuori nel Finder."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "これを使用しているアプリが動作しなくなる場合があります。これがあるフォルダからはコードが読み込まれ、rootだけが所有するものでもないため、履歴から戻すことはできません。ただし、Finderでドラッグして取り出せます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 항목을 사용하는 앱이 작동을 멈출 수 있습니다. 이 항목이 들어 있는 폴더에서 코드가 로드되고 이 항목은 Root 사용자 전용이 아니므로 기록에서 되돌려 놓을 수 없지만, Finder에서 드래그하여 꺼낼 수 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Apps die het gebruiken, werken misschien niet meer. Geschiedenis kan het niet terugzetten, omdat er vanuit de map ervan code wordt geladen en het niet uitsluitend van root is, maar je kunt het in Finder er weer uit slepen."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aplikacje, które jej używają, mogą przestać działać. Historia nie może jej przywrócić, ponieważ z jej folderu wczytywany jest kod, a ona sama nie należy wyłącznie do użytkownika root, ale możesz przeciągnąć ją z Kosza w Finderze."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Os apps que o usam podem parar de funcionar. O Histórico não pode colocá-lo de volta, porque a pasta em que ele está é usada para carregar código e ele não pertence só ao usuário root, mas você pode arrastá-lo para fora no Finder."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aplicațiile care îl folosesc pot înceta să funcționeze. Nu îl puteți pune înapoi din Istoric, deoarece din dosarul său se încarcă cod și articolul nu aparține doar utilizatorului Root, însă, în Finder, îl puteți trage afară din Coș."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Приложения, которые его используют, могут перестать работать. История не сможет его восстановить, поскольку из его папки загружается код, а он принадлежит не только пользователю root, но в Finder его можно перетащить из Корзины обратно."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Appar som använder den kan sluta fungera. Historik kan inte lägga tillbaka den, eftersom kod läses in från dess mapp och den inte enbart tillhör rotanvändaren, men du kan dra ut den igen i Finder."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Onu kullanan uygulamalar çalışmayı durdurabilir. Geçmiş onu yerine koyamaz, çünkü klasöründen kod yüklenir ve tek sahibi root değildir; ancak onu Finder’da sürükleyerek dışarı çıkarabilirsiniz."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Програми, які ним користуються, можуть перестати працювати. Історія не зможе його повернути, бо з його папки завантажується код, а він належить не лише користувачу root, але у Finder його можна перетягнути зі Смітника назад."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用它的App可能会停止工作。“历史记录”无法将它放回原处,因为系统会从它所在的文件夹载入代码,而且它并非仅归root所有,不过你可以在“访达”中将它拖出来。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用它的App可能會停止運作。由於系統會從它所在的檔案夾載入程式碼,且它並非只屬於root,「歷史記錄」無法將它還原,但你可以在Finder中將它拖出來。"
+ }
+ }
+ }
+ },
"Apps you keep in the Dock are remembered, and come back when you turn this off." : {
"localizations" : {
"cs" : {
@@ -28633,112 +28739,6 @@
}
}
},
- "Code is loaded from that folder, so only what Peel’s helper took from it can go back." : {
- "localizations" : {
- "cs" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Z této složky se načítá kód, takže se do ní smí vrátit jen to, co z ní vzal pomocník Peelu."
- }
- },
- "de" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Aus diesem Ordner wird Code geladen, daher darf nur zurückgelegt werden, was das Hilfsprogramm von Peel daraus entnommen hat."
- }
- },
- "es" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Desde esa carpeta se carga código, así que solo puede volver lo que el asistente de Peel sacó de allí."
- }
- },
- "fr" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Du code est chargé depuis ce dossier : seul ce que l’utilitaire de Peel en a retiré peut donc y retourner."
- }
- },
- "it" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Da quella cartella viene caricato del codice, quindi può tornarci solo ciò che l’assistente di Peel ne ha tolto."
- }
- },
- "ja" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "そのフォルダからはコードが読み込まれるため、戻せるのはPeelのヘルパーがそこから移動したものだけです。"
- }
- },
- "ko" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "그 폴더에서 코드가 로드되므로, Peel 보조 프로그램이 그 폴더에서 가져온 항목만 되돌려 놓을 수 있습니다."
- }
- },
- "nl" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Vanuit die map wordt code geladen, dus alleen wat het hulpprogramma van Peel eruit heeft gehaald, kan terug."
- }
- },
- "pl" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Z tego folderu wczytywany jest kod, więc wrócić do niego może tylko to, co zabrał z niego pomocnik Peel."
- }
- },
- "pt" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Essa pasta é usada para carregar código, então só pode voltar para ela o que o auxiliar do Peel tirou de lá."
- }
- },
- "ro" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Din acel dosar se încarcă cod, așa că poate fi pus înapoi în el doar ce a luat de acolo instrumentul de ajutor Peel."
- }
- },
- "ru" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Из этой папки загружается код, поэтому вернуть туда можно только то, что оттуда забрал помощник Peel."
- }
- },
- "sv" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "Kod läses in från den mappen, så bara det som Peels hjälpprogram har tagit därifrån kan läggas tillbaka."
- }
- },
- "tr" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "O klasörden kod yüklenir, bu yüzden oraya yalnızca Peel’in yardımcısının oradan aldıkları geri dönebilir."
- }
- },
- "uk" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "З цієї папки завантажується код, тож повернути туди можна лише те, що з неї забрав помічник Peel."
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "系统会从该文件夹载入代码,因此只有Peel的帮助程序从那里移走的内容才能放回去。"
- }
- },
- "zh-Hant" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "系統會從該檔案夾載入程式碼,因此只有Peel的輔助程式從中取出的項目才能放回去。"
- }
- }
- }
- },
"Colima" : {
"comment" : "A product's name, never translated.",
"shouldTranslate" : false
@@ -62397,6 +62397,112 @@
}
}
},
+ "It could have changed while it was in the Trash, and code is loaded from that folder, so Peel’s helper puts back only what is root’s alone. You can drag it back out in Finder." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mohlo se to změnit, zatímco to bylo v koši, a z této složky se načítá kód, takže pomocník Peelu vrací zpět jen to, co patří výhradně uživateli root. Ve Finderu to můžete přetáhnout zpět ven."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Es könnte sich verändert haben, während es im Papierkorb lag, und aus diesem Ordner wird Code geladen, daher legt das Hilfsprogramm von Peel nur zurück, was ausschließlich root gehört. Du kannst es im Finder wieder herausziehen."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Podría haber cambiado mientras estaba en la papelera, y desde esa carpeta se carga código, así que el asistente de Peel solo restaura lo que pertenece únicamente a root. Puedes sacarlo arrastrándolo en el Finder."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Il a pu être modifié pendant qu’il était dans la corbeille, et du code est chargé depuis ce dossier : l’utilitaire de Peel ne remet donc en place que ce qui appartient uniquement à root. Vous pouvez l’en sortir dans le Finder, en le faisant glisser."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Potrebbe essere cambiato mentre era nel Cestino, e da quella cartella viene caricato del codice, quindi l’assistente di Peel ripristina soltanto ciò che appartiene esclusivamente a root. Puoi trascinarlo fuori nel Finder."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ゴミ箱にある間に変更された可能性があり、そのフォルダからはコードが読み込まれるため、Peelのヘルパーはrootだけが所有するものしか戻しません。Finderでドラッグして取り出せます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "휴지통에 있는 동안 변경되었을 수 있고 그 폴더에서 코드가 로드되므로, Peel 보조 프로그램은 Root 사용자 전용인 항목만 되돌려 놓습니다. Finder에서 드래그하여 꺼낼 수 있습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Het kan zijn gewijzigd terwijl het in de prullenmand stond, en vanuit die map wordt code geladen, dus het hulpprogramma van Peel zet alleen terug wat uitsluitend van root is. Je kunt het in Finder er weer uit slepen."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mogło się to zmienić, gdy było w Koszu, a z tego folderu wczytywany jest kod, więc pomocnik Peel przywraca tylko to, co należy wyłącznie do użytkownika root. Możesz przeciągnąć to z Kosza w Finderze."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ele pode ter sido alterado enquanto estava no Lixo, e essa pasta é usada para carregar código, então o auxiliar do Peel só coloca de volta o que pertence apenas ao usuário root. Você pode arrastá-lo para fora no Finder."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Este posibil să se fi modificat cât timp a stat în Coș, iar din acel dosar se încarcă cod, așa că instrumentul de ajutor Peel pune înapoi doar ce aparține exclusiv utilizatorului Root. În Finder, îl puteți trage afară din Coș."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Объект мог измениться, пока находился в Корзине, а из этой папки загружается код, поэтому помощник Peel восстанавливает только то, что принадлежит исключительно пользователю root. В Finder его можно перетащить из Корзины обратно."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Det kan ha ändrats medan det låg i papperskorgen, och kod läses in från den mappen, så Peels hjälpprogram lägger bara tillbaka det som tillhör rotanvändaren och ingen annan. Du kan dra ut det igen i Finder."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Çöp Sepeti’ndeyken değişmiş olabilir ve o klasörden kod yüklenir, bu yüzden Peel’in yardımcısı yalnızca tek sahibi root olan öğeleri yerine koyar. Onu Finder’da sürükleyerek dışarı çıkarabilirsiniz."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Поки елемент був у Смітнику, його могли змінити, а з тієї папки завантажується код, тож помічник Peel повертає туди лише те, що належить тільки користувачу root. У Finder його можна перетягнути зі Смітника назад."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "它在废纸篓中时可能已被更改,而且系统会从该文件夹载入代码,因此Peel的帮助程序只会放回仅归root所有的内容。你可以在“访达”中将它拖出来。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "它在「垃圾桶」中時可能已被更改,而且系統會從該檔案夾載入程式碼,因此Peel的輔助程式只會還原只屬於root的項目。你可以在Finder中將它拖出來。"
+ }
+ }
+ }
+ },
"It doesn’t pass Gatekeeper, the check macOS makes before it opens an app." : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift b/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift
index eb0ee52a..3967716c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift
@@ -39,6 +39,9 @@ public struct Plugin: Sendable, Hashable, Identifiable {
/// Why Peel would refuse to move it, such as a Mail bundle in the user's own Library, where all of Mail is
/// protected. Such a plug-in is listed and never offered.
public let refusal: GuardRefusal?
+ /// True when, moved through Peel's helper, it could not come back from History: code is loaded from its folder,
+ /// and it isn't root's alone (`PrivilegedPathPolicy.keepsOut`).
+ public var staysInTheTrash = false
public var id: URL { url }
}
@@ -132,10 +135,13 @@ public enum Plugins {
// A few at a time, as the other scans measure: the guard's answer and the size each take a while, and a Mac
// used for music can hold more than a thousand plug-ins.
let removalGuard = RemovalGuard(environment: environment, exclusions: exclusions)
+ let reach = HelperReach(environment: environment)
let plugins = await found.concurrentMap(width: LeftoverScanner.concurrentMeasurements) { item -> Plugin? in
guard !AppleCode.isApples(item.url) else { return nil }
let info = AppInspector.infoDictionary(in: item.url.appending(path: "Contents", directoryHint: .isDirectory))
- return Plugin(
+ let folder = ParentAccess(item.url.deletingLastPathComponent())
+ let requiresPrivileges = folder.requiresPrivileges(toRemove: item.url)
+ var plugin = Plugin(
url: item.url,
name: (info?["CFBundleName"] as? String) ?? item.url.deletingPathExtension().lastPathComponent,
bundleIdentifier: info?["CFBundleIdentifier"] as? String,
@@ -143,10 +149,11 @@ public enum Plugins {
category: item.category,
isInstalledForAllUsers: item.isForAllUsers,
size: await measure(item.url),
- requiresPrivileges: ParentAccess(item.url.deletingLastPathComponent())
- .requiresPrivileges(toRemove: item.url),
+ requiresPrivileges: requiresPrivileges,
refusal: removalGuard.refusal(of: item.url)
)
+ plugin.staysInTheTrash = requiresPrivileges && reach.keepsOut(item.url, at: item.url)
+ return plugin
}
let sorted = plugins.compactMap(\.self).sorted {
$0.name.localizedStandardCompare($1.name) == .orderedAscending
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
index 4718a036..89a6f407 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
@@ -25,6 +25,16 @@ struct HelperReach: Sendable {
policy.takesOnlyALink(at: url.path(percentEncoded: false))
}
+ /// True when the helper would keep `trashed` out of the place `original` names, a folder code is loaded from.
+ func keepsOut(_ trashed: URL, at original: URL) -> Bool {
+ var info = stat()
+ guard lstat(trashed.path(percentEncoded: false), &info) == 0,
+ let located = PathPattern.located(original.path(percentEncoded: false))
+ else { return false }
+ let parent = (located as NSString).deletingLastPathComponent
+ return policy.keepsOut(owner: info.st_uid, mode: info.st_mode, at: located, in: parent)
+ }
+
/// 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 or their completions are linked into as anything but
/// a link that leads nowhere, or into `leaving`, which moves first. `RemovalGuard` judges what the item itself is.
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index 49bfc3f9..75ee17fc 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -746,21 +746,27 @@ public struct TrashService: Sendable {
}
guard item.isInTheTrash else { return .missingFromTrash }
guard !item.originalURL.isThere else { return .alreadyThere }
+ if Self.needsTheHelper(toPutBack: item),
+ HelperReach(environment: environment).keepsOut(item.trashedURL, at: item.originalURL) {
+ return .failed(PrivilegedPathPolicy.Rejection.loadsCode.explanation)
+ }
return nil
}
+ /// Whether putting `item` back is the helper's to do: the nearest folder on its way that exists is one the person
+ /// can't write to. Missing folders are made again, so that is the folder that decides.
+ static func needsTheHelper(toPutBack item: TrashedItem) -> Bool {
+ var ancestor = item.originalURL.deletingLastPathComponent().path(percentEncoded: false)
+ while !FileManager.default.fileExists(atPath: ancestor), ancestor != "/" {
+ ancestor = (ancestor as NSString).deletingLastPathComponent
+ }
+ return !FileManager.default.isWritableFile(atPath: ancestor)
+ }
+
private func moveBack(_ item: TrashedItem, canUseHelper: Bool) async -> RestoreFailure? {
if let refusal = refusal(ofPuttingBack: item) { return refusal }
- let fileManager = FileManager.default
-
- let parent = item.originalURL.deletingLastPathComponent()
- // Missing folders are created again, so write access is checked on the nearest folder that exists.
- var ancestor = parent.path(percentEncoded: false)
- while !fileManager.fileExists(atPath: ancestor), ancestor != "/" {
- ancestor = (ancestor as NSString).deletingLastPathComponent
- }
- if fileManager.isWritableFile(atPath: ancestor) {
+ if !Self.needsTheHelper(toPutBack: item) {
do {
try Self.putBack(item) { removalGuard.refusal(ofPuttingBack: item.trashedURL, at: $0) }
return nil
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
index a133b40d..e2fc32b4 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
@@ -7,7 +7,7 @@ public enum HelperIdentity {
public static let launchdPlistName = "com.tuguidragos.Peel.Helper.plist"
/// Raise it whenever the helper changes, so Peel never works with a helper of another version. The helper
/// refuses requests that carry any other version.
- public static let protocolVersion = 18
+ public static let protocolVersion = 19
}
/// The complete set of privileged operations. The helper validates every argument itself.
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift
index 7d01c207..33d1bf36 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/PrivilegedPathPolicy.swift
@@ -34,7 +34,7 @@ public struct PrivilegedPathPolicy: Sendable {
case .alreadyExists: "Something is there already."
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 .loadsCode: "It could have changed while it was in the Trash, and code is loaded from that folder, so Peel’s helper puts back only what is root’s alone. You can drag it back out in Finder."
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."
@@ -270,9 +270,18 @@ public struct PrivilegedPathPolicy: Sendable {
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.
+ /// Whether a folder that code is loaded from keeps out an item `owner` owns with `mode`, going back to `path` in
+ /// `parent`: such a folder takes back only what root owns and 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. A
+ /// browser starts the program a manifest names, so a manifests folder is one that code is loaded from.
+ public func keepsOut(owner: uid_t?, mode: mode_t?, at path: String, in parent: String) -> Bool {
+ let takesAnything = restorable.contains { PathComponents.isPath(path, inside: $0) }
+ guard !takesAnything || manifests.contains(parent) else { return false }
+ return owner != trustedOwner || mode.map { $0 & 0o022 != 0 } ?? true
+ }
+
+ /// Like `open`, for a path where nothing exists yet. A folder that code is loaded from keeps out what `keepsOut`
+ /// says.
public func openDestination(_ path: String, for trashed: OpenItem) -> Result<OpenItem, Rejection> {
let aFolder = trashed.mode.map { $0 & S_IFMT == S_IFDIR } ?? false
return openFolder(of: path, beforeOpening: {}, puttingBackAFolder: aFolder).flatMap { name, parent in
@@ -280,12 +289,8 @@ public struct PrivilegedPathPolicy: Sendable {
if links.contains(item.parent) {
guard let mode = trashed.mode, mode & S_IFMT == S_IFLNK else { return .failure(.notALink) }
}
- // 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)
- }
+ if keepsOut(owner: trashed.owner, mode: trashed.mode, at: item.path, in: item.parent) {
+ return .failure(.loadsCode)
}
var info = stat()
guard item.name.withCString({ fstatat(parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) != 0 else {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift
index ef2ca2ab..936a685d 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift
@@ -47,6 +47,24 @@ struct PluginsTests {
#expect(scan.unreadable.map(\.lastPathComponent) == ["Vendor"])
}
+ @Test(.permissionsHold) func knowsAPlugInHistoryCouldNotPutBack() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.directory("root/Library/Audio/Plug-Ins/Components/Synth.component/Contents")
+ try directory.directory("home/Library/Audio/Plug-Ins/Components/Own.component/Contents")
+ let components = directory.url.appending(path: "root/Library/Audio/Plug-Ins/Components", directoryHint: .isDirectory)
+ try directory.setPermissions(0o555, of: components)
+ defer { try? directory.setPermissions(0o755, of: components) }
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+
+ let plugins = await Plugins.scan(environment: environment).plugins
+
+ #expect(plugins.first { $0.name == "Synth" }?.staysInTheTrash == true)
+ #expect(plugins.first { $0.name == "Own" }?.staysInTheTrash == false)
+ }
+
@Test func findsPluginBundlesInUserAndSystemLibraries() async throws {
let directory = try TemporaryDirectory()
let info = try PropertyListSerialization.data(
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
index a3b6c21e..f54939ef 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
@@ -576,6 +576,27 @@ struct TrashServiceTests {
#expect(await service.restore(planted) == .notAllowed)
}
+ @Test(.permissionsHold) func saysAtOnceWhatTheHelperKeepsOutOfAFolderCodeIsLoadedFrom() throws {
+ let directory = try TemporaryDirectory()
+ let components = try directory.directory("root/Library/Audio/Plug-Ins/Components")
+ let trashed = try directory.directory("home/.Trash/Synth.component")
+ let service = TrashService(
+ environment: SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home"),
+ rootDirectory: directory.url.appending(path: "root")
+ )
+ ) { $0 }
+ let item = TrashedItem(originalURL: components.appending(path: "Synth.component"), trashedURL: trashed, date: .now)
+
+ let byThePerson = service.refusal(ofPuttingBack: item)
+ try directory.setPermissions(0o555, of: components)
+ defer { try? directory.setPermissions(0o755, of: components) }
+ let throughTheHelper = service.refusal(ofPuttingBack: item)
+
+ #expect(byThePerson == nil)
+ #expect(throughTheHelper == .failed(PrivilegedPathPolicy.Rejection.loadsCode.explanation))
+ }
+
@Test func aMoveRefusedForAnItemLockedInFinderSaysItIsLocked() async throws {
let directory = try TemporaryDirectory()
let locked = try directory.file("home/Library/Preferences/org.example.locked.plist")
diff --git a/Peel/Views/FixedSentenceText.swift b/Peel/Views/FixedSentenceText.swift
index bde9b829..57c4d5e4 100644
--- a/Peel/Views/FixedSentenceText.swift
+++ b/Peel/Views/FixedSentenceText.swift
@@ -16,7 +16,7 @@ extension FixedSentence {
case .alreadyThere: "Something is there already."
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 .codeFolder: "It could have changed while it was in the Trash, and code is loaded from that folder, so Peel’s helper puts back only what is root’s alone. You can drag it back out in Finder."
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."
diff --git a/Peel/Views/Plugins/PluginDetailView.swift b/Peel/Views/Plugins/PluginDetailView.swift
index 0417c67e..24abfc29 100644
--- a/Peel/Views/Plugins/PluginDetailView.swift
+++ b/Peel/Views/Plugins/PluginDetailView.swift
@@ -120,7 +120,11 @@ struct PluginDetailView: View {
}
Button("Cancel", role: .cancel) {}
} message: {
- Text("Apps that use it may stop working.")
+ if plugin.staysInTheTrash {
+ Text("Apps that use it may stop working. History can’t put it back, since code is loaded from its folder and it isn’t root’s alone, but you can drag it back out in Finder.")
+ } else {
+ Text("Apps that use it may stop working.")
+ }
}
}
diff --git a/SAFETY.md b/SAFETY.md
index 376bf2c1..94b296e5 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -642,7 +642,8 @@ and it fails closed.
there. An item moves only once its record is on the drive itself, so a power cut can't keep the move and lose
the record. While the ledger can't be read, the helper moves nothing and puts nothing back; one it can't make
sense of is kept under another name, never written over, and a new one begins. A folder that code is loaded from
- takes back only what is still owned by root and writable by nobody else.
+ takes back only what is still owned by root and writable by nobody else. Peel says so before it moves a plug-in
+ that isn't, and Put Back says so too, since Finder can still drag it back out.
If you never install the helper, Peel still works; it just cannot touch what needs administrator rights.
Home lists the helper as required for that reason, and keeps a reminder there until it is installed. What needs an