diff --git a/App/Info.plist b/App/Info.plist
index c680818..d95cf63 100644
--- a/App/Info.plist
+++ b/App/Info.plist
@@ -34,5 +34,17 @@
NSApplicationNSSupportsAutomaticTermination
+ SUFeedURL
+ https://kernel-hunter.github.io/mudroom/appcast.xml
+ SUPublicEDKey
+ QKKfpvfADDZDhLbEDTOZ4QKgc5EgHgxP3hGulato8T8=
+ SURequireSignedFeed
+
+ SUVerifyUpdateBeforeExtraction
+
+ SUEnableSystemProfiling
+
+ SUAllowsAutomaticUpdates
+
diff --git a/Package.resolved b/Package.resolved
index 47f89f4..ebbe5be 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -1,6 +1,15 @@
{
- "originHash" : "011bb120634957a2571f91eb91640edd246aa903439badb7e4abfb8b1d487ad1",
+ "originHash" : "75d794dab488bc5e6415dd967a5b07b0e82e12c8f580611b6260ea5df4308e05",
"pins" : [
+ {
+ "identity" : "sparkle",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/sparkle-project/Sparkle",
+ "state" : {
+ "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100",
+ "version" : "2.10.0"
+ }
+ },
{
"identity" : "swift-argument-parser",
"kind" : "remoteSourceControl",
diff --git a/Package.swift b/Package.swift
index 8986a13..6eae81f 100644
--- a/Package.swift
+++ b/Package.swift
@@ -32,19 +32,31 @@ var targets: [Target] = [
.testTarget(name: "MudroomCoreTests", dependencies: ["MudroomCore"]),
]
+var dependencies: [Package.Dependency] = [
+ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
+ .package(url: "https://github.com/apple/swift-crypto", "3.0.0"..<"5.0.0"),
+]
+
#if os(macOS)
products.append(.executable(name: "MudroomApp", targets: ["MudroomApp"]))
-targets.append(.executableTarget(name: "MudroomApp", dependencies: ["MudroomCore"]))
+targets.append(.executableTarget(
+ name: "MudroomApp",
+ dependencies: ["MudroomCore", .product(name: "Sparkle", package: "Sparkle")],
+ linkerSettings: [
+ // scripts/build-app.sh puts Sparkle.framework in Contents/Frameworks.
+ .unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@executable_path/../Frameworks"]),
+ ]
+))
+// The app's updater. Pinned: an update to it is a change to how Mudroom
+// replaces itself, so it should be a deliberate one.
+dependencies.append(.package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.0"))
#endif
let package = Package(
name: "Mudroom",
platforms: [.macOS(.v26)],
products: products,
- dependencies: [
- .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
- .package(url: "https://github.com/apple/swift-crypto", "3.0.0"..<"5.0.0"),
- ],
+ dependencies: dependencies,
targets: targets,
swiftLanguageModes: [.v6]
)
diff --git a/README.md b/README.md
index 06eb466..96f5d83 100644
--- a/README.md
+++ b/README.md
@@ -130,8 +130,8 @@ Copy-Item "$env:TEMP\$name\*" $dir -Force
[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ";$dir", 'User')
```
-To upgrade, run the same lines with the new version, without the PATH
-line. `mudroom.exe` isn't code-signed; if Windows blocks it after you unzip
+To upgrade, run `mudroom update`, or the same lines with the new version
+without the PATH line. `mudroom.exe` isn't code-signed; if Windows blocks it after you unzip
with Explorer, run `Get-ChildItem $dir | Unblock-File`.
The Scoop and winget manifests are in [packaging/scoop](packaging/scoop)
@@ -162,6 +162,71 @@ mudroom network check --backend docker # see what the sandbox can reach
+### Updating
+
+**Mac app.** Mudroom.app updates itself with
+[Sparkle](https://sparkle-project.org): Mudroom > Check for Updates, or
+let it check once a day (it asks the second time you open it). Nothing is
+installed until you click Install, and Mudroom only installs an update that
+is signed with its own key. The `mudroom` command inside the app updates
+with it. Mudroom 0.5.0 and older don't have the updater yet, so update
+those once by hand: `brew upgrade --cask mudroom`, or run the install script
+again.
+
+**Command line.** `mudroom update` checks for a new release and updates
+the way Mudroom was installed:
+
+| Installed with | `mudroom update` |
+|---|---|
+| Homebrew | runs `brew upgrade --cask mudroom` |
+| The install script or the zip | opens Mudroom.app's updater |
+| A Windows release zip | downloads the new zip, checks its SHA-256 against the release, and swaps the files in |
+| Scoop, winget | prints `scoop update mudroom` or `winget upgrade --id KernelHunter.Mudroom --exact` to run (neither can replace `mudroom.exe` while it runs) |
+| Built from source | tells you to `git pull` and rebuild |
+
+It asks before changing anything; `--yes` skips the question and `--check`
+only checks. In a terminal, Mudroom also prints one line after a command
+when a newer release is out, at most once a day:
+
+```text
+Mudroom 0.6.0 is available (you have 0.5.0). Run `mudroom update` to get it.
+```
+
+
+What the update check sends, and how to turn it off
+
+
+
+The CLI makes one request, once a day (an hour later if GitHub couldn't be
+reached): `GET
+https://api.github.com/repos/Kernel-Hunter/mudroom/releases/latest`, over
+HTTPS, with no cookies or credentials. GitHub sees your IP address and a
+`User-Agent: mudroom/` header, which its API requires. Nothing
+else is sent: no ID, no system details, nothing about your projects or
+sessions. The answer is cached in Mudroom's data folder
+(`update-check.json`). The check runs on your machine only, never in the
+sandbox, and never during `run`, `start` or `agent`, in JSON output, under
+CI, or when standard output or standard error isn't a terminal. A slow or
+failed check never delays a command by more than a second and never
+changes its result.
+
+The Mac app reads its feed, `https://kernel-hunter.github.io/mudroom/appcast.xml`,
+once a day if you said yes to automatic checks. Sparkle sends the app's
+name and version in its User-Agent and no system profile. The feed and
+each update are signed with Mudroom's EdDSA key; an update or feed that
+doesn't match the key is refused.
+
+To turn the checks off:
+
+- the CLI: `mudroom update --auto-check off` (saved in Mudroom's
+ `settings.json`), or `MUDROOM_NO_UPDATE_CHECK=1` in your environment;
+- the app: Mudroom > Settings > Check for updates automatically. The
+ `mudroom` command inside the app follows this setting too.
+
+`mudroom update` itself always checks, since you asked it to.
+
+
+
## Quick start
In the app:
@@ -1493,6 +1558,19 @@ macOS, Linux and Windows.
## FAQ
+
+Does Mudroom connect to anything on its own?
+
+
+
+Only to check for updates: the CLI asks GitHub for the latest release at
+most once a day, and the Mac app reads its update feed once a day if you
+allow it. Neither sends anything about you or your projects. See [What the
+update check sends, and how to turn it off](#updating). Everything else
+Mudroom connects to is what you or the agent ask for.
+
+
+
Does the agent ever touch my real project folder?
@@ -1608,6 +1686,7 @@ swift test # diff, hunks, apply, undo, allowlist, proxy, snapsho
scripts/make-demo.sh # demo sessions in build/demo (no VM)
scripts/screenshots.sh # regenerates docs/screenshots from the demo
scripts/release.sh 0.4.0 # dist/Mudroom-0.4.0.zip and its SHA-256
+scripts/appcast.sh 0.4.0 # adds a published release to the app's update feed
scripts/windows-package.ps1 .build/release/mudroom.exe 0.4.0 x86_64 # on Windows: dist/mudroom-0.4.0-windows-x86_64.zip with its DLLs
mudroom network check # verifies isolation in a real sandbox (any backend)
```
@@ -1630,6 +1709,26 @@ The proxy tests run it against a loopback test server. The app target is
platforms). `MudroomCore` has no UI code; the app and the CLI both sit on
top of it.
+### Releasing
+
+1. Set the version in `Sources/mudroom/Version.swift`, commit, and push a
+ tag: `git tag v0.6.0 && git push origin v0.6.0`. The release workflow
+ builds `Mudroom-0.6.0.zip` and the Windows zips, with a `.sha256` for
+ each, and attaches them to the GitHub release.
+2. `scripts/appcast.sh 0.6.0`: downloads the Mac zip, checks it against
+ its `.sha256`, signs it with Sparkle's `sign_update` (the EdDSA key in the
+ login Keychain), adds it to `docs/appcast.xml` with the release notes and
+ signs the feed. Commit `docs/appcast.xml` and push it to main; GitHub
+ Pages serves it to the app.
+3. `scripts/update-cask.sh 0.6.0 --remote`, then copy the cask to the
+ Kernel-Hunter/homebrew-tap repo.
+4. `scripts/update-windows-manifests.sh 0.6.0`, then copy the Scoop manifest
+ to Kernel-Hunter/scoop-bucket and the winget folder to a winget-pkgs fork.
+5. In the README, set `$v = '0.6.0'` in the Windows zip install lines.
+
+The CLI's update notice reads GitHub's latest release, so it shows up as
+soon as the release is published; the app's comes with step 2.
+
## Contributing
Bug reports, corrections to the comparison tables and pull requests are
diff --git a/Sources/MudroomApp/MudroomApp.swift b/Sources/MudroomApp/MudroomApp.swift
index d527822..e2590b2 100644
--- a/Sources/MudroomApp/MudroomApp.swift
+++ b/Sources/MudroomApp/MudroomApp.swift
@@ -22,6 +22,7 @@ struct MudroomApp: App {
.commands {
CommandGroup(replacing: .appInfo) {
Button("About Mudroom") { AppDelegate.showAbout() }
+ CheckForUpdatesButton(updater: AppUpdater.shared)
Button("Setup…") { app.openSetup() }
}
CommandGroup(replacing: .newItem) {
@@ -65,6 +66,10 @@ struct MudroomApp: App {
}
.defaultSize(width: 720, height: 860)
.windowResizability(.contentMinSize)
+
+ Settings {
+ UpdateSettingsView(updater: AppUpdater.shared)
+ }
}
}
@@ -88,6 +93,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.regular)
NSApp.activate()
+ AppUpdater.shared.listenForCLI()
let defaults = UserDefaults.standard
switch defaults.string(forKey: "MudroomAppearance") {
diff --git a/Sources/MudroomApp/Updater.swift b/Sources/MudroomApp/Updater.swift
new file mode 100644
index 0000000..be12f93
--- /dev/null
+++ b/Sources/MudroomApp/Updater.swift
@@ -0,0 +1,100 @@
+import AppKit
+import Combine
+import Sparkle
+import SwiftUI
+
+/// Sparkle, set up from Info.plist: the feed (SUFeedURL), the key that
+/// signs every update and the feed itself (SUPublicEDKey), no system
+/// profile, and installs only when the user clicks Install. Sparkle asks
+/// on the second launch whether to check automatically.
+@MainActor
+final class AppUpdater: ObservableObject {
+ static let shared = AppUpdater()
+
+ private let controller: SPUStandardUpdaterController
+ /// False for builds without a feed (`swift run`) and for screenshots.
+ let isAvailable: Bool
+ @Published private(set) var canCheck = false
+ private var lastRequest = Date.distantPast
+
+ private init() {
+ controller = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: nil, userDriverDelegate: nil)
+ isAvailable = Bundle.main.object(forInfoDictionaryKey: "SUFeedURL") != nil && !AppDelegate.isSnapshot
+ guard isAvailable else { return }
+ controller.startUpdater()
+ controller.updater.publisher(for: \.canCheckForUpdates).assign(to: &$canCheck)
+ }
+
+ var automaticallyChecks: Bool {
+ get { isAvailable && controller.updater.automaticallyChecksForUpdates }
+ set {
+ objectWillChange.send()
+ controller.updater.automaticallyChecksForUpdates = newValue
+ }
+ }
+
+ func checkForUpdates() {
+ guard isAvailable else { return }
+ controller.checkForUpdates(nil)
+ }
+
+ /// `mudroom update` opens the app with --check-for-updates, and posts
+ /// this notification for a copy that is already running. Either way the
+ /// user still sees the update and clicks Install. Any local program can
+ /// post it, so it only opens the check, at most every 30 seconds, and
+ /// doesn't pull the app in front of what the user is typing into.
+ func listenForCLI() {
+ guard isAvailable else { return }
+ if CommandLine.arguments.contains("--check-for-updates") {
+ lastRequest = Date()
+ checkForUpdates()
+ }
+ let name = Notification.Name((Bundle.main.bundleIdentifier ?? "io.github.kernel-hunter.mudroom") + ".checkForUpdates")
+ DistributedNotificationCenter.default().addObserver(forName: name, object: nil, queue: .main) { _ in
+ MainActor.assumeIsolated {
+ let updater = AppUpdater.shared
+ guard Date().timeIntervalSince(updater.lastRequest) > 30 else { return }
+ updater.lastRequest = Date()
+ updater.checkForUpdates()
+ }
+ }
+ }
+}
+
+struct CheckForUpdatesButton: View {
+ @ObservedObject var updater: AppUpdater
+
+ var body: some View {
+ Button("Check for Updates…") { updater.checkForUpdates() }
+ .disabled(!updater.canCheck)
+ }
+}
+
+struct UpdateSettingsView: View {
+ @ObservedObject var updater: AppUpdater
+
+ var body: some View {
+ Form {
+ Section {
+ Toggle("Check for updates automatically", isOn: Binding(
+ get: { updater.automaticallyChecks },
+ set: { updater.automaticallyChecks = $0 }))
+ .disabled(!updater.isAvailable)
+ Text("Once a day Mudroom reads its update feed from kernel-hunter.github.io. Nothing about your Mac or your projects is sent. An update is installed only when you click Install, and only if it is signed with Mudroom's key. The mudroom command in Terminal follows this setting.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Section {
+ HStack {
+ Text("Version \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?")")
+ Spacer()
+ CheckForUpdatesButton(updater: updater)
+ }
+ }
+ }
+ .formStyle(.grouped)
+ .frame(width: 460)
+ .fixedSize()
+ }
+}
diff --git a/Sources/MudroomCore/InstallMethod.swift b/Sources/MudroomCore/InstallMethod.swift
new file mode 100644
index 0000000..0e3ca0e
--- /dev/null
+++ b/Sources/MudroomCore/InstallMethod.swift
@@ -0,0 +1,86 @@
+import Foundation
+
+/// How this copy of the `mudroom` CLI was installed, which decides what
+/// `mudroom update` does.
+public enum InstallMethod: Equatable, Sendable {
+ /// Inside Mudroom.app (Homebrew cask, install.sh or the zip). The app
+ /// updates itself, CLI included; `homebrew` is the cask's `brew`.
+ case appBundle(app: URL, homebrew: URL?)
+ /// `scoop install mudroom`.
+ case scoop
+ /// `winget install KernelHunter.Mudroom`.
+ case winget
+ /// A Windows release zip unpacked by hand: mudroom.exe with its DLLs.
+ case releaseZip(directory: URL)
+ /// Built from source, or something this doesn't recognize.
+ case source
+
+ public static let wingetID = "KernelHunter.Mudroom"
+
+ /// `executable` is this program's path with symlinks resolved.
+ /// `exists` is asked about paths only, so tests can use fake trees.
+ public static func detect(executable: URL, windows: Bool, exists: (URL) -> Bool,
+ contents: (URL) -> [String] = { _ in [] }) -> InstallMethod {
+ let parts = executable.pathComponents
+ let lower = parts.map { $0.lowercased() }
+ let dir = executable.deletingLastPathComponent()
+
+ if !windows, parts.count >= 4,
+ Array(lower.suffix(3)) == ["contents", "helpers", "mudroom"], parts[parts.count - 4].hasSuffix(".app") {
+ let app = URL(fileURLWithPath: dir.deletingLastPathComponent().deletingLastPathComponent().path, isDirectory: true)
+ return .appBundle(app: app, homebrew: homebrew(exists: exists))
+ }
+ guard windows else { return .source }
+
+ // \apps\mudroom\\mudroom.exe, with \shims.
+ if lower.count >= 4, lower[lower.count - 4] == "apps", lower[lower.count - 3] == "mudroom" {
+ let root = dir.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ if exists(root.appendingPathComponent("shims")) { return .scoop }
+ }
+ // ...\WinGet\Packages\KernelHunter.Mudroom_\\mudroom.exe
+ if let i = lower.firstIndex(of: "packages"), i > 0, lower[i - 1] == "winget", i + 1 < lower.count,
+ lower[i + 1].hasPrefix(wingetID.lowercased() + "_") {
+ return .winget
+ }
+ if isReleaseZipFolder(contents(dir)) { return .releaseZip(directory: URL(fileURLWithPath: dir.path, isDirectory: true)) }
+ return .source
+ }
+
+ /// A folder unpacked from a release zip: mudroom.exe, its license and
+ /// the Swift runtime, and no other program. `mudroom update` replaces
+ /// files there, so a shared tools folder (other .exe files, or
+ /// another Swift program's DLLs without our LICENSE.txt) doesn't count.
+ static func isReleaseZipFolder(_ names: [String]) -> Bool {
+ let lower = Set(names.map { $0.lowercased() })
+ guard lower.isSuperset(of: ["mudroom.exe", "license.txt", "swiftcore.dll", "foundation.dll"]) else { return false }
+ return !lower.contains { $0.hasSuffix(".exe") && $0 != "mudroom.exe" }
+ }
+
+ /// The `brew` that installed the mudroom cask, if one did.
+ static func homebrew(exists: (URL) -> Bool) -> URL? {
+ // The two standard prefixes only: `mudroom update --yes` runs this
+ // brew, so it isn't taken from the environment.
+ for p in ["/opt/homebrew", "/usr/local"] {
+ let prefix = URL(fileURLWithPath: p, isDirectory: true)
+ let brew = prefix.appendingPathComponent("bin/brew")
+ if exists(prefix.appendingPathComponent("Caskroom/mudroom")) && exists(brew) { return brew }
+ }
+ return nil
+ }
+
+ /// This program's path, symlinks resolved.
+ public static func currentExecutable() -> URL? {
+ Bundle.main.executableURL?.resolvingSymlinksInPath()
+ }
+
+ public static func current() -> InstallMethod {
+ guard let exe = currentExecutable() else { return .source }
+ #if os(Windows)
+ let windows = true
+ #else
+ let windows = false
+ #endif
+ return detect(executable: exe, windows: windows, exists: { FileManager.default.fileExists(atPath: $0.path) },
+ contents: { (try? FileManager.default.contentsOfDirectory(atPath: $0.path)) ?? [] })
+ }
+}
diff --git a/Sources/MudroomCore/ReleaseZipUpdate.swift b/Sources/MudroomCore/ReleaseZipUpdate.swift
new file mode 100644
index 0000000..1c1b809
--- /dev/null
+++ b/Sources/MudroomCore/ReleaseZipUpdate.swift
@@ -0,0 +1,259 @@
+#if canImport(Darwin)
+import Darwin
+#elseif canImport(Glibc)
+import Glibc
+#elseif canImport(Musl)
+import Musl
+#endif
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+#if canImport(CryptoKit)
+import CryptoKit
+#else
+import Crypto
+#endif
+import Foundation
+
+/// `mudroom update` for a Windows release zip unpacked by hand: download
+/// the new zip, check its SHA-256 against what the release publishes,
+/// unpack it next to the old files and swap them in, one rename each.
+public enum ReleaseZipUpdate {
+ /// Leftovers of a swap: Windows can rename a running mudroom.exe (and
+ /// the DLLs it loaded) but not delete it, so the old files stay until
+ /// the next update removes them.
+ public static let oldSuffix = ".mudroom-old"
+ /// Far more than a release zip (about 30 MB).
+ static let maxZipBytes = 300 << 20
+
+ public static func folderName(version: ReleaseVersion, arch: String) -> String {
+ "mudroom-\(version)-windows-\(arch)"
+ }
+
+ public static var currentArch: String {
+ #if arch(arm64)
+ return "arm64"
+ #else
+ return "x86_64"
+ #endif
+ }
+
+ static func downloadURL(version: ReleaseVersion, file: String) -> URL {
+ URL(string: "https://github.com/\(UpdateCheck.repository)/releases/download/v\(version)/\(file)")!
+ }
+
+ /// The hash in a `.sha256` file (""), if it names `file`.
+ public static func parseChecksum(_ text: String, file: String) -> String? {
+ let fields = text.split(whereSeparator: { $0 == " " || $0 == "\t" || $0 == "\n" || $0 == "\r" })
+ guard let hash = fields.first?.lowercased(), hash.count == 64, hash.allSatisfy(\.isHexDigit) else { return nil }
+ if fields.count > 1 {
+ var name = fields[1]
+ if name.hasPrefix("*") { name = name.dropFirst() }
+ guard name == file else { return nil }
+ }
+ return hash
+ }
+
+ /// The SHA-256 GitHub computed for a release asset (the `digest` field
+ /// of `releases/tags/`), if it lists one.
+ public static func parseAssetDigest(_ data: Data, file: String) -> String? {
+ struct Release: Decodable {
+ struct Asset: Decodable {
+ var name: String
+ var digest: String?
+ }
+ var assets: [Asset]
+ }
+ guard let r = try? JSONDecoder().decode(Release.self, from: data),
+ let digest = r.assets.first(where: { $0.name == file })?.digest, digest.hasPrefix("sha256:") else { return nil }
+ let hex = digest.dropFirst("sha256:".count).lowercased()
+ return hex.count == 64 && hex.allSatisfy(\.isHexDigit) ? hex : nil
+ }
+
+ /// Accepts the download only if at least one published hash exists and
+ /// every published hash matches it.
+ public static func checksumProblem(actual: String, published: [String]) -> String? {
+ if published.isEmpty { return "the release publishes no SHA-256 for this zip, so it can't be checked; not installing it" }
+ if let bad = published.first(where: { $0 != actual }) {
+ return "checksum mismatch (the release says \(bad), the download is \(actual)); not installing it"
+ }
+ return nil
+ }
+
+ public static func sha256(of url: URL) throws -> String {
+ let handle = try FileHandle(forReadingFrom: url)
+ defer { try? handle.close() }
+ var hasher = SHA256()
+ while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty { hasher.update(data: chunk) }
+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()
+ }
+
+ /// Moves each file of `staged` into `directory`, setting the file it
+ /// replaces aside as `.mudroom-old`. If any step fails, every file
+ /// already moved goes back and the error is thrown. Returns the names
+ /// replaced or added.
+ @discardableResult
+ public static func swapIn(_ staged: URL, to directory: URL) throws -> [String] {
+ let fm = FileManager.default
+ let names = try fm.contentsOfDirectory(atPath: staged.path).sorted()
+ // Folders in a release zip would be a different layout than the one
+ // this knows how to replace.
+ // Plain files only: a folder, link or junction (attributes are read
+ // without following links) would be a layout this doesn't know.
+ for name in names {
+ let type = try fm.attributesOfItem(atPath: staged.appendingPathComponent(name).path)[.type] as? FileAttributeType
+ guard type == .typeRegular else {
+ throw MudroomError.invalid("unexpected entry \(TextLines.visible(name)) in the release zip (not a plain file)")
+ }
+ }
+ var done: [(name: String, hadOld: Bool)] = []
+ /// False if some file couldn't be put back; then its old copy is
+ /// still `.mudroom-old` and must not be cleaned up.
+ func rollBack() -> Bool {
+ var ok = true
+ for step in done.reversed() {
+ let target = directory.appendingPathComponent(step.name)
+ if (try? moveFile(target, staged.appendingPathComponent(step.name))) == nil { ok = false }
+ if step.hadOld, (try? moveFile(directory.appendingPathComponent(step.name + oldSuffix), target)) == nil { ok = false }
+ }
+ return ok
+ }
+ for name in names {
+ let target = directory.appendingPathComponent(name)
+ let old = directory.appendingPathComponent(name + oldSuffix)
+ let hadOld = fm.fileExists(atPath: target.path)
+ do {
+ if hadOld {
+ if fm.fileExists(atPath: old.path) { try fm.removeItem(at: old) }
+ try moveFile(target, old)
+ }
+ do {
+ try moveFile(staged.appendingPathComponent(name), target)
+ } catch {
+ if hadOld, (try? moveFile(old, target)) == nil { throw RollbackFailed(directory: directory) }
+ throw error
+ }
+ } catch let e as RollbackFailed {
+ _ = rollBack()
+ throw e
+ } catch {
+ guard rollBack() else { throw RollbackFailed(directory: directory) }
+ throw MudroomError.invalid("couldn't replace \(name): \(MudroomError.message(error)). Nothing was changed.")
+ }
+ done.append((name, hadOld))
+ }
+ return names
+ }
+
+ /// A swap that failed and couldn't be fully undone. The old files are
+ /// still there as `.mudroom-old`; nothing deletes them.
+ public struct RollbackFailed: Error, CustomStringConvertible {
+ public let directory: URL
+ public var description: String {
+ "the update failed and not every file could be put back. The old files are in \(directory.path) "
+ + "with \(ReleaseZipUpdate.oldSuffix) added to their names: rename them back, or install the zip again by hand"
+ }
+ }
+
+ /// Deletes the `.mudroom-old` files a previous update left. Ones still
+ /// in use (the running mudroom.exe on Windows) stay for next time.
+ public static func removeLeftovers(in directory: URL) {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []
+ for name in names where name.hasSuffix(oldSuffix) {
+ try? FileManager.default.removeItem(at: directory.appendingPathComponent(name))
+ }
+ }
+
+ static func moveFile(_ from: URL, _ to: URL) throws {
+ #if os(Windows)
+ if let e = WinFS.move(from.path, to.path) { throw Win32.error("MoveFileExW", from.path, e) }
+ #else
+ if rename(from.path, to.path) != 0 {
+ throw MudroomError.posix("rename", from.path, errno)
+ }
+ #endif
+ }
+
+ /// Downloads, checks and installs `version` over the release zip in
+ /// `directory`. `say` gets progress lines.
+ public static func install(_ version: ReleaseVersion, into directory: URL, currentVersion: String,
+ arch: String = currentArch, say: (String) -> Void) throws {
+ let folder = folderName(version: version, arch: arch)
+ let zipName = folder + ".zip"
+ let agent = "mudroom/\(currentVersion)"
+ removeLeftovers(in: directory)
+
+ // Unpacked inside the install folder, so every swap is a rename on
+ // one volume.
+ let staging = directory.appendingPathComponent(".mudroom-update-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: false)
+ var keepStaging = false
+ defer { if !keepStaging { try? FileManager.default.removeItem(at: staging) } }
+
+ say("Downloading \(zipName)")
+ let zip: URL
+ switch HTTPFetch.file(downloadURL(version: version, file: zipName), userAgent: agent, timeout: 600, limit: maxZipBytes) {
+ case .success(let f): zip = f
+ case .failure(let e): throw MudroomError.invalid("download failed: \(e)")
+ }
+ defer { try? FileManager.default.removeItem(at: zip) }
+
+ var published: [String] = []
+ if case .success(let file) = HTTPFetch.file(downloadURL(version: version, file: zipName + ".sha256"),
+ userAgent: agent, timeout: 60, limit: 4096) {
+ defer { try? FileManager.default.removeItem(at: file) }
+ let text = (try? String(contentsOf: file, encoding: .utf8)) ?? ""
+ guard let hash = parseChecksum(text, file: zipName) else {
+ throw MudroomError.invalid("\(zipName).sha256 on the release doesn't hold a SHA-256 for \(zipName); not installing it")
+ }
+ published.append(hash)
+ }
+ var request = URLRequest(url: URL(string: "https://api.github.com/repos/\(UpdateCheck.repository)/releases/tags/v\(version)")!)
+ request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+ request.setValue(agent, forHTTPHeaderField: "User-Agent")
+ request.setValue("en", forHTTPHeaderField: "Accept-Language")
+ if case .success(let (200, data)) = HTTPFetch.data(request, timeout: 30, limit: 4 << 20),
+ let digest = parseAssetDigest(data, file: zipName) {
+ published.append(digest)
+ }
+ let actual = try sha256(of: zip)
+ if let why = checksumProblem(actual: actual, published: published) { throw MudroomError.invalid(why) }
+ say("SHA-256 ok (\(actual))")
+
+ try extract(zip, into: staging)
+ let unpacked = staging.appendingPathComponent(folder, isDirectory: true)
+ let exe = unpacked.appendingPathComponent("mudroom.exe")
+ guard FileManager.default.fileExists(atPath: exe.path) else {
+ throw MudroomError.invalid("the zip doesn't contain \(folder)\\mudroom.exe; not installing it")
+ }
+ let out = try ProcessRunner.capture(exe.path, ["--version"], timeout: 60)
+ let reported = out.stdout.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard out.status == 0, reported == version.description else {
+ throw MudroomError.invalid("the new mudroom.exe says it is '\(TextLines.visible(String(reported.prefix(80))))', not \(version); not installing it")
+ }
+
+ say("Replacing the files in \(directory.path)")
+ do {
+ try swapIn(unpacked, to: directory)
+ } catch let e as RollbackFailed {
+ keepStaging = true
+ throw e
+ }
+ removeLeftovers(in: directory)
+ }
+
+ /// Unpacks with Windows' own tar.exe (bsdtar), which refuses entries
+ /// with absolute paths or `..`.
+ static func extract(_ zip: URL, into dir: URL) throws {
+ #if os(Windows)
+ let root = ProcessInfo.processInfo.environment["SystemRoot"] ?? "C:\\Windows"
+ let tar = root + "\\System32\\tar.exe"
+ #else
+ let tar = "/usr/bin/tar"
+ #endif
+ let out = try ProcessRunner.capture(tar, ["-xf", zip.path, "-C", dir.path], timeout: 300)
+ guard out.status == 0 else {
+ throw MudroomError.commandFailed("tar -xf", out.status, TextLines.visible(String(out.stderr.prefix(2000))))
+ }
+ }
+}
diff --git a/Sources/MudroomCore/UpdateNotice.swift b/Sources/MudroomCore/UpdateNotice.swift
new file mode 100644
index 0000000..06431b9
--- /dev/null
+++ b/Sources/MudroomCore/UpdateNotice.swift
@@ -0,0 +1,189 @@
+import Foundation
+
+/// Mudroom-wide CLI settings: `/settings.json`.
+public struct MudroomSettings: Codable, Sendable, Equatable {
+ /// The daily check for a new release. Nil means on.
+ public var checkForUpdates: Bool?
+
+ public init(checkForUpdates: Bool? = nil) { self.checkForUpdates = checkForUpdates }
+
+ public static func url(_ store: SessionStore) -> URL { store.root.appendingPathComponent("settings.json") }
+
+ /// The saved settings; defaults when there is no file. A file that
+ /// can't be read turns the update check off rather than on.
+ public static func load(_ store: SessionStore) -> MudroomSettings {
+ guard FileManager.default.fileExists(atPath: url(store).path) else { return MudroomSettings() }
+ guard let data = try? Data(contentsOf: url(store)),
+ let s = try? JSONDecoder().decode(MudroomSettings.self, from: data) else { return MudroomSettings(checkForUpdates: false) }
+ return s
+ }
+
+ public func save(_ store: SessionStore) throws {
+ try FileManager.default.createDirectory(at: store.root, withIntermediateDirectories: true)
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ try encoder.encode(self).writeAtomically(to: Self.url(store))
+ }
+}
+
+/// When to check for a new release and when to say so. The check runs at
+/// most once a day; after a failed one it waits an hour before trying
+/// again; the notice for a version shows at most once a day.
+public struct UpdateNoticeState: Codable, Sendable, Equatable {
+ /// Last check that got an answer.
+ public var checked: Date?
+ /// Last check started, answered or not.
+ public var attempted: Date?
+ /// The latest release that answer named.
+ public var latest: String?
+ /// When the notice was last printed, and for which version.
+ public var shown: Date?
+ public var shownVersion: String?
+
+ public init(checked: Date? = nil, attempted: Date? = nil, latest: String? = nil,
+ shown: Date? = nil, shownVersion: String? = nil) {
+ self.checked = checked
+ self.attempted = attempted
+ self.latest = latest
+ self.shown = shown
+ self.shownVersion = shownVersion
+ }
+
+ public static let checkInterval: TimeInterval = 24 * 3600
+ public static let retryInterval: TimeInterval = 3600
+ /// A check the command finished before: try again this much later.
+ public static let cutOffRetry: TimeInterval = 300
+ public static let noticeInterval: TimeInterval = 24 * 3600
+
+ public static func url(_ store: SessionStore) -> URL { store.root.appendingPathComponent("update-check.json") }
+
+ public static func load(_ store: SessionStore) -> UpdateNoticeState {
+ guard let data = try? Data(contentsOf: url(store)),
+ let s = try? JSONDecoder().decode(UpdateNoticeState.self, from: data) else { return UpdateNoticeState() }
+ return s
+ }
+
+ public func save(_ store: SessionStore) throws {
+ try FileManager.default.createDirectory(at: store.root, withIntermediateDirectories: true)
+ try JSONEncoder().encode(self).writeAtomically(to: Self.url(store))
+ }
+
+ /// Whether `t` is less than `interval` ago. A time in the future (a
+ /// clock that was wrong) counts as long ago.
+ static func recent(_ t: Date?, _ interval: TimeInterval, now: Date) -> Bool {
+ guard let t else { return false }
+ let age = now.timeIntervalSince(t)
+ return age >= -300 && age < interval
+ }
+
+ public func needsCheck(now: Date) -> Bool {
+ !Self.recent(checked, Self.checkInterval, now: now) && !Self.recent(attempted, Self.retryInterval, now: now)
+ }
+
+ /// The version to tell the user about, if one is newer than `current`
+ /// and wasn't already shown in the last day.
+ public func versionToAnnounce(current: ReleaseVersion, now: Date) -> ReleaseVersion? {
+ guard let latest = latest.flatMap(ReleaseVersion.init), !latest.isPrerelease, latest > current else { return nil }
+ if shownVersion == latest.description, Self.recent(shown, Self.noticeInterval, now: now) { return nil }
+ return latest
+ }
+}
+
+public enum UpdateNotice {
+ public static let environmentVariable = "MUDROOM_NO_UPDATE_CHECK"
+
+ /// Why the automatic check is off, or nil when it's on. `appChecksOff`
+ /// is the Mac app's own "Check for updates automatically" setting, for
+ /// the copy of the CLI inside the app.
+ public static func disabledReason(environment: [String: String], settings: MudroomSettings,
+ appChecksOff: Bool = false) -> String? {
+ if let v = environment[environmentVariable], !v.isEmpty, v != "0" { return "\(environmentVariable) is set" }
+ if settings.checkForUpdates == false { return "turned off with `mudroom update --auto-check off`" }
+ if appChecksOff { return "turned off in Mudroom's settings" }
+ // CI logs aren't read by anyone who can act on it.
+ if let ci = environment["CI"], !ci.isEmpty, ci.lowercased() != "false", ci != "0" { return "running under CI" }
+ return nil
+ }
+
+ /// Commands that never print the notice: sessions own the terminal
+ /// (`run`, `start`, `agent login`), and `update` speaks for itself.
+ static let quietCommands: Set = ["run", "start", "agent", "update", "help"]
+
+ /// Whether a command line may end with the notice. Help, version and
+ /// JSON output never do.
+ public static func allowed(arguments: [String]) -> Bool {
+ guard let first = arguments.first(where: { !$0.hasPrefix("-") }) else { return false }
+ if quietCommands.contains(first) { return false }
+ let quietFlags: Set = ["--json", "--help", "-h", "--version", "--experimental-dump-help"]
+ return !arguments.contains { quietFlags.contains($0) || $0.hasPrefix("--generate-completion") }
+ }
+
+ public static func message(_ v: ReleaseVersion, current: ReleaseVersion) -> String {
+ "Mudroom \(v) is available (you have \(current)). Run `mudroom update` to get it."
+ }
+}
+
+/// The once-a-day check run alongside a command: `begin` starts it in the
+/// background when it's due, `finish` (after the command's own output)
+/// waits a moment for it and returns the line to print, if any.
+public final class UpdateNoticeRun: @unchecked Sendable {
+ let store: SessionStore
+ let current: ReleaseVersion
+ let fetch: @Sendable () -> Result
+ let now: @Sendable () -> Date
+ private let lock = NSLock()
+ private let done = DispatchSemaphore(value: 0)
+ private var started = false
+ private var result: Result?
+
+ public init(store: SessionStore, current: ReleaseVersion,
+ now: @escaping @Sendable () -> Date = { Date() },
+ fetch: @escaping @Sendable () -> Result) {
+ self.store = store
+ self.current = current
+ self.now = now
+ self.fetch = fetch
+ }
+
+ public func begin() {
+ var state = UpdateNoticeState.load(store)
+ guard state.needsCheck(now: now()) else { return }
+ state.attempted = now()
+ // Can't record the attempt (read-only store): don't check, or
+ // every command would.
+ guard (try? state.save(store)) != nil else { return }
+ started = true
+ Thread.detachNewThread { [self] in
+ let r = fetch()
+ lock.withLock { result = r }
+ done.signal()
+ }
+ }
+
+ /// Waits at most `wait` seconds for a check still running, saves what
+ /// it found, and returns the notice line, or nil.
+ public func finish(wait: TimeInterval) -> String? {
+ if started { _ = done.wait(timeout: .now() + wait) }
+ var state = UpdateNoticeState.load(store)
+ switch lock.withLock({ result }) {
+ case .success(let latest)?:
+ state.checked = now()
+ state.latest = latest.version.description
+ case .failure?:
+ break
+ case nil where started:
+ // Cut off by the command ending, not refused: try again soon.
+ state.attempted = now().addingTimeInterval(UpdateNoticeState.cutOffRetry - UpdateNoticeState.retryInterval)
+ case nil:
+ break
+ }
+ guard let v = state.versionToAnnounce(current: current, now: now()) else {
+ if started { try? state.save(store) }
+ return nil
+ }
+ state.shown = now()
+ state.shownVersion = v.description
+ try? state.save(store)
+ return UpdateNotice.message(v, current: current)
+ }
+}
diff --git a/Sources/MudroomCore/Updates.swift b/Sources/MudroomCore/Updates.swift
new file mode 100644
index 0000000..e55fa24
--- /dev/null
+++ b/Sources/MudroomCore/Updates.swift
@@ -0,0 +1,302 @@
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+import Foundation
+
+/// A release version, `major.minor.patch` with an optional pre-release part
+/// (`0.6.0-rc.1`), ordered the way semver orders them. Build metadata
+/// (`+...`) is accepted and ignored.
+public struct ReleaseVersion: Comparable, Hashable, Sendable, CustomStringConvertible {
+ public let major: Int
+ public let minor: Int
+ public let patch: Int
+ /// Dot-separated pre-release identifiers; empty for a normal release.
+ public let prerelease: [String]
+
+ /// Parses "1.2.3", "v1.2.3" or "1.2.3-beta.2". Anything else (extra
+ /// parts, leading zeros, odd characters, absurd lengths) is nil, so a
+ /// version read from the network is safe to print.
+ public init?(_ text: String) {
+ var s = Substring(text)
+ if s.hasPrefix("v") { s = s.dropFirst() }
+ guard !s.isEmpty, s.count <= 64,
+ s.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "." || $0 == "-" || $0 == "+") }) else { return nil }
+ if let plus = s.firstIndex(of: "+") {
+ let build = s[s.index(after: plus)...]
+ guard !build.isEmpty, !build.split(separator: ".", omittingEmptySubsequences: false).contains(where: \.isEmpty) else { return nil }
+ s = s[.. 1, id.first == "0" { return nil }
+ pre.append(String(id))
+ }
+ s = s[.. Bool {
+ if (a.major, a.minor, a.patch) != (b.major, b.minor, b.patch) {
+ return (a.major, a.minor, a.patch) < (b.major, b.minor, b.patch)
+ }
+ // A pre-release comes before its release.
+ if a.prerelease.isEmpty || b.prerelease.isEmpty { return !a.prerelease.isEmpty && b.prerelease.isEmpty }
+ for (x, y) in zip(a.prerelease, b.prerelease) where x != y {
+ switch (Int(x), Int(y)) {
+ case let (i?, j?): return i < j
+ case (_?, nil): return true // numbers sort before words
+ case (nil, _?): return false
+ case (nil, nil): return x < y
+ }
+ }
+ return a.prerelease.count < b.prerelease.count
+ }
+}
+
+/// What GitHub says the latest release is.
+public struct LatestRelease: Equatable, Sendable {
+ public let version: ReleaseVersion
+
+ public init(version: ReleaseVersion) { self.version = version }
+
+ /// The release page, built from the version rather than taken from the
+ /// response, so the only thing printed from the network is a checked
+ /// version number.
+ public var pageURL: String { UpdateCheck.releasePage(version) }
+}
+
+public enum UpdateCheck {
+ public static let repository = "Kernel-Hunter/mudroom"
+ /// The one request the update check makes: GitHub's latest release,
+ /// which leaves out drafts and pre-releases.
+ public static let latestReleaseURL = URL(string: "https://api.github.com/repos/\(repository)/releases/latest")!
+ /// Responses bigger than this are not a release record.
+ static let maxResponseBytes = 1 << 20
+
+ public static func releasePage(_ v: ReleaseVersion) -> String {
+ "https://github.com/\(repository)/releases/tag/v\(v)"
+ }
+
+ /// Reads a `releases/latest` response. Nil for anything that isn't a
+ /// published, final release with a version tag.
+ public static func parseLatest(_ data: Data) -> LatestRelease? {
+ struct Release: Decodable {
+ var tag_name: String
+ var draft: Bool?
+ var prerelease: Bool?
+ }
+ guard data.count <= maxResponseBytes,
+ let r = try? JSONDecoder().decode(Release.self, from: data),
+ r.draft != true, r.prerelease != true,
+ let v = ReleaseVersion(r.tag_name), !v.isPrerelease else { return nil }
+ return LatestRelease(version: v)
+ }
+
+ public enum CheckError: Error, CustomStringConvertible, Equatable {
+ case network(String)
+ case status(Int)
+ case unreadable
+
+ public var description: String {
+ switch self {
+ case .network(let why): return "couldn't reach GitHub: \(why)"
+ case .status(let code): return "GitHub answered with HTTP \(code)"
+ case .unreadable: return "GitHub's answer wasn't a release"
+ }
+ }
+ }
+
+ /// Asks GitHub for the latest release. No cookies, no cache, no
+ /// credentials; the only thing sent besides the URL is a User-Agent
+ /// with Mudroom's version, which GitHub's API requires.
+ public static func fetchLatest(from url: URL = latestReleaseURL, currentVersion: String,
+ timeout: TimeInterval) -> Result {
+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
+ request.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept")
+ request.setValue("mudroom/\(currentVersion)", forHTTPHeaderField: "User-Agent")
+ request.setValue("en", forHTTPHeaderField: "Accept-Language")
+ return HTTPFetch.data(request, timeout: timeout, limit: maxResponseBytes).flatMap { status, data in
+ guard status == 200 else { return .failure(.status(status)) }
+ guard let latest = parseLatest(data) else { return .failure(.unreadable) }
+ return .success(latest)
+ }
+ }
+}
+
+/// Plain HTTPS GETs for the update check and `mudroom update`: an
+/// ephemeral session (nothing stored, no cookies), HTTPS only, and
+/// redirects followed only to GitHub's own HTTPS hosts.
+enum HTTPFetch {
+ static func allowed(_ url: URL?) -> Bool {
+ guard let url, url.scheme?.lowercased() == "https", let host = url.host?.lowercased() else {
+ return testHost(url)
+ }
+ // Release downloads redirect to GitHub's asset hosts; nothing else
+ // under githubusercontent.com (raw files, gists) is followed.
+ return ["github.com", "api.github.com", "release-assets.githubusercontent.com",
+ "objects.githubusercontent.com"].contains(host)
+ }
+
+ /// Debug builds only: lets tests point the check at a local server.
+ /// Release builds never follow anything but GitHub over HTTPS.
+ static func testHost(_ url: URL?) -> Bool {
+ #if DEBUG
+ guard let url, url.scheme == "http", let host = url.host else { return false }
+ return host == "127.0.0.1" || host == "localhost"
+ #else
+ return false
+ #endif
+ }
+
+ final class Delegate: NSObject, URLSessionDataDelegate, URLSessionDownloadDelegate, @unchecked Sendable {
+ let limit: Int
+ let lock = NSLock()
+ var data = Data()
+ var downloaded: URL?
+ var tooBig = false
+ let done = DispatchSemaphore(value: 0)
+ var error: Error?
+ var status = 0
+
+ init(limit: Int) { self.limit = limit }
+
+ func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
+ newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
+ completionHandler(HTTPFetch.allowed(request.url) ? request : nil)
+ }
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
+ completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
+ lock.withLock { status = (response as? HTTPURLResponse)?.statusCode ?? 0 }
+ if response.expectedContentLength > Int64(limit) {
+ lock.withLock { tooBig = true }
+ completionHandler(.cancel)
+ } else {
+ completionHandler(.allow)
+ }
+ }
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) {
+ lock.withLock {
+ if data.count + chunk.count > limit {
+ tooBig = true
+ dataTask.cancel()
+ } else {
+ data.append(chunk)
+ }
+ }
+ }
+
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
+ totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
+ if totalBytesWritten > Int64(limit) || totalBytesExpectedToWrite > Int64(limit) {
+ lock.withLock { tooBig = true }
+ downloadTask.cancel()
+ }
+ }
+
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+ // The file is deleted when this returns; keep it.
+ let keep = FileManager.default.temporaryDirectory.appendingPathComponent("mudroom-download-\(UUID().uuidString)")
+ let moved = (try? FileManager.default.moveItem(at: location, to: keep)) != nil
+ lock.withLock {
+ status = (downloadTask.response as? HTTPURLResponse)?.statusCode ?? 0
+ downloaded = moved ? keep : nil
+ }
+ }
+
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+ lock.withLock {
+ if status == 0 { status = (task.response as? HTTPURLResponse)?.statusCode ?? 0 }
+ self.error = error
+ }
+ done.signal()
+ }
+ }
+
+ static func session(_ delegate: Delegate, timeout: TimeInterval) -> URLSession {
+ let config = URLSessionConfiguration.ephemeral
+ config.timeoutIntervalForRequest = timeout
+ config.timeoutIntervalForResource = timeout
+ config.httpCookieAcceptPolicy = .never
+ config.httpShouldSetCookies = false
+ config.urlCache = nil
+ config.urlCredentialStorage = nil
+ config.requestCachePolicy = .reloadIgnoringLocalCacheData
+ return URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
+ }
+
+ /// GETs a small document into memory. Blocks up to `timeout` seconds
+ /// (plus a moment); fails rather than read more than `limit` bytes.
+ static func data(_ request: URLRequest, timeout: TimeInterval, limit: Int) -> Result<(Int, Data), UpdateCheck.CheckError> {
+ guard allowed(request.url) else { return .failure(.network("refusing \(request.url?.absoluteString ?? "?")")) }
+ let delegate = Delegate(limit: limit)
+ let session = session(delegate, timeout: timeout)
+ defer { session.invalidateAndCancel() }
+ session.dataTask(with: request).resume()
+ if delegate.done.wait(timeout: .now() + timeout + 1) == .timedOut { return .failure(.network("timed out")) }
+ return delegate.lock.withLock {
+ if delegate.tooBig { return .failure(.network("the response was too large")) }
+ if let e = delegate.error { return .failure(.network(describe(e))) }
+ return .success((delegate.status, delegate.data))
+ }
+ }
+
+ /// Downloads to a temporary file the caller owns. Fails rather than
+ /// write more than `limit` bytes, or on any status but 200.
+ static func file(_ url: URL, userAgent: String, timeout: TimeInterval, limit: Int) -> Result {
+ guard allowed(url) else { return .failure(.network("refusing \(url.absoluteString)")) }
+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
+ request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
+ request.setValue("en", forHTTPHeaderField: "Accept-Language")
+ let delegate = Delegate(limit: limit)
+ let session = session(delegate, timeout: timeout)
+ defer { session.invalidateAndCancel() }
+ session.downloadTask(with: request).resume()
+ if delegate.done.wait(timeout: .now() + timeout + 1) == .timedOut { return .failure(.network("timed out")) }
+ return delegate.lock.withLock {
+ let file = delegate.downloaded
+ func drop() { if let file { try? FileManager.default.removeItem(at: file) } }
+ if delegate.tooBig { drop(); return .failure(.network("the download was too large")) }
+ if let e = delegate.error { drop(); return .failure(.network(describe(e))) }
+ guard delegate.status == 200 else { drop(); return .failure(.status(delegate.status)) }
+ guard let file else { return .failure(.network("the download didn't arrive")) }
+ return .success(file)
+ }
+ }
+
+ static func describe(_ error: Error) -> String {
+ let e = error as NSError
+ if e.domain == NSURLErrorDomain {
+ switch e.code {
+ case NSURLErrorTimedOut: return "timed out"
+ case NSURLErrorNotConnectedToInternet: return "not connected to the internet"
+ case NSURLErrorCannotFindHost, NSURLErrorDNSLookupFailed: return "couldn't look up the host"
+ case NSURLErrorCancelled: return "cancelled (a redirect to a host other than GitHub, or too much data)"
+ default: break
+ }
+ }
+ return e.localizedDescription
+ }
+}
diff --git a/Sources/mudroom/Mudroom.swift b/Sources/mudroom/Mudroom.swift
index 83c3b78..02d5269 100644
--- a/Sources/mudroom/Mudroom.swift
+++ b/Sources/mudroom/Mudroom.swift
@@ -23,15 +23,25 @@ struct Mudroom: ParsableCommand {
""",
version: mudroomVersion,
subcommands: [SetupCommand.self, Run.self, New.self, Start.self, Diff.self, Review.self, Hunks.self, Apply.self, Undo.self,
- Snapshots.self, NetworkCommand.self, Exclude.self, Agent.self, Keys.self, List.self, Stop.self, Discard.self, Image.self]
+ Snapshots.self, NetworkCommand.self, Exclude.self, Agent.self, Keys.self, List.self, Stop.self, Discard.self, Image.self,
+ Update.self]
)
- #if os(Windows)
+ /// ArgumentParser's main, plus the daily update check: started before
+ /// the command, its one line printed after the command's own output.
static func main() {
+ #if os(Windows)
WindowsConsole.setUp()
- main(nil)
+ #endif
+ let notice = UpdateNoticeHook.begin(arguments: Array(CommandLine.arguments.dropFirst()))
+ do {
+ var command = try parseAsRoot()
+ try command.run()
+ } catch {
+ exit(withError: error)
+ }
+ UpdateNoticeHook.finish(notice)
}
- #endif
}
func store() -> SessionStore { SessionStore.defaultStore() }
diff --git a/Sources/mudroom/Update.swift b/Sources/mudroom/Update.swift
new file mode 100644
index 0000000..ed51fc3
--- /dev/null
+++ b/Sources/mudroom/Update.swift
@@ -0,0 +1,186 @@
+import ArgumentParser
+#if canImport(Darwin)
+import Darwin
+#elseif canImport(Glibc)
+import Glibc
+#elseif canImport(Musl)
+import Musl
+#elseif canImport(WinSDK)
+import WinSDK
+#endif
+import Foundation
+import MudroomCore
+
+/// GitHub's latest-release endpoint. Debug builds can be pointed at a local
+/// server with MUDROOM_UPDATE_TEST_URL, for tests; release builds can't.
+func latestReleaseEndpoint() -> URL {
+ #if DEBUG
+ if let s = ProcessInfo.processInfo.environment["MUDROOM_UPDATE_TEST_URL"], let url = URL(string: s) { return url }
+ #endif
+ return UpdateCheck.latestReleaseURL
+}
+
+/// The Mac app's "Check for updates automatically" is off. The copy of the
+/// CLI inside the app follows it.
+func appUpdateChecksOff(_ method: InstallMethod) -> Bool {
+ #if os(macOS)
+ guard case .appBundle(let app, _) = method, let id = Bundle(url: app)?.bundleIdentifier else { return false }
+ return UserDefaults(suiteName: id)?.object(forKey: "SUEnableAutomaticChecks") as? Bool == false
+ #else
+ return false
+ #endif
+}
+
+/// The one-line notice after a command, when a release is out.
+enum UpdateNoticeHook {
+ static func begin(arguments: [String]) -> UpdateNoticeRun? {
+ // Only for a person at a terminal, and never in machine output.
+ guard UpdateNotice.allowed(arguments: arguments),
+ isatty(STDERR_FILENO) == 1, isatty(STDOUT_FILENO) == 1,
+ let current = ReleaseVersion(mudroomVersion) else { return nil }
+ let sessions = store()
+ let method = InstallMethod.current()
+ guard UpdateNotice.disabledReason(environment: ProcessInfo.processInfo.environment,
+ settings: MudroomSettings.load(sessions),
+ appChecksOff: appUpdateChecksOff(method)) == nil else { return nil }
+ let endpoint = latestReleaseEndpoint()
+ let run = UpdateNoticeRun(store: sessions, current: current) {
+ UpdateCheck.fetchLatest(from: endpoint, currentVersion: mudroomVersion, timeout: 3)
+ }
+ run.begin()
+ return run
+ }
+
+ /// Waits at most a second for a check still running (only a command
+ /// shorter than that waits at all).
+ static func finish(_ run: UpdateNoticeRun?) {
+ guard let run, let line = run.finish(wait: 1) else { return }
+ FileHandle.standardError.write(Data((line + "\n").utf8))
+ }
+}
+
+struct Update: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ abstract: "Check for a new release and install it the way Mudroom was installed.",
+ discussion: """
+ Homebrew: runs `brew upgrade --cask mudroom`. Mudroom.app from install.sh or the \
+ zip: opens the app's updater. A Windows release zip: downloads the new zip, checks \
+ it against the SHA-256 the release publishes and swaps the files in. Scoop and \
+ winget: prints the command to run, since they can't replace mudroom.exe while it \
+ runs. Asks before changing anything, unless --yes.
+
+ Mudroom also checks once a day, after a command run in a terminal, and prints one \
+ line when a release is out. Turn that off with `mudroom update --auto-check off` \
+ or MUDROOM_NO_UPDATE_CHECK=1.
+ """)
+
+ @Flag(help: "Only check, and say how this copy would be updated.")
+ var check = false
+
+ @Flag(name: .shortAndLong, help: "Update without asking.")
+ var yes = false
+
+ @Option(help: "Turn the daily update check on or off.")
+ var autoCheck: String?
+
+ func validate() throws {
+ if let autoCheck, !["on", "off"].contains(autoCheck) { throw ValidationError("--auto-check takes on or off") }
+ }
+
+ func run() throws {
+ let sessions = store()
+ if let autoCheck {
+ var settings = MudroomSettings.load(sessions)
+ settings.checkForUpdates = autoCheck == "on"
+ do { try settings.save(sessions) } catch { fail(error) }
+ print("The daily update check is \(autoCheck).")
+ let method = InstallMethod.current()
+ if autoCheck == "on", let why = UpdateNotice.disabledReason(environment: ProcessInfo.processInfo.environment,
+ settings: settings, appChecksOff: appUpdateChecksOff(method)) {
+ print("It still won't run here: \(why).")
+ }
+ return
+ }
+
+ guard let current = ReleaseVersion(mudroomVersion) else { fail(MudroomError.invalid("this build's version '\(mudroomVersion)' isn't a release version")) }
+ let latest: LatestRelease
+ switch UpdateCheck.fetchLatest(from: latestReleaseEndpoint(), currentVersion: mudroomVersion, timeout: 15) {
+ case .success(let l): latest = l
+ case .failure(let e): fail(MudroomError.invalid("couldn't check for updates: \(e)"))
+ }
+ var state = UpdateNoticeState.load(sessions)
+ state.checked = Date()
+ state.latest = latest.version.description
+ try? state.save(sessions)
+
+ guard latest.version > current else {
+ print("Mudroom \(current) is up to date.")
+ return
+ }
+ print("Mudroom \(latest.version) is available (you have \(current)).")
+ print("Release notes: \(latest.pageURL)")
+ try install(latest.version, method: InstallMethod.current())
+ }
+
+ func install(_ version: ReleaseVersion, method: InstallMethod) throws {
+ switch method {
+ case .appBundle(let app, let brew?):
+ print("Homebrew installed Mudroom. Update with: brew upgrade --cask mudroom")
+ guard !check else { return }
+ guard confirm("Run it now?", yes: yes) else { return notUpdating() }
+ fflush(nil)
+ let status: Int32
+ do { status = try ProcessRunner.runAttached(brew.path, ["upgrade", "--cask", "mudroom"]) } catch { fail(error) }
+ if status != 0 { throw ExitCode(status) }
+ print("Updated \(app.path).")
+
+ case .appBundle(let app, nil):
+ print("Mudroom.app updates itself, and this command with it: Mudroom > Check for Updates.")
+ guard !check else { return }
+ guard confirm("Open Mudroom and check now?", yes: yes) else { return notUpdating() }
+ openAppUpdater(app)
+ print("In Mudroom's update window, click Install Update. Mudroom restarts with \(version).")
+
+ case .scoop:
+ print("Scoop installed this copy. Update it with:\n scoop update mudroom")
+ print("(Scoop won't replace mudroom.exe while it runs, so mudroom doesn't run it for you.)")
+
+ case .winget:
+ print("winget installed this copy. Update it with:\n winget upgrade --id \(InstallMethod.wingetID) --exact")
+ print("(winget can't replace mudroom.exe while it runs, so mudroom doesn't run it for you.)")
+
+ case .releaseZip(let dir):
+ let zip = ReleaseZipUpdate.folderName(version: version, arch: ReleaseZipUpdate.currentArch) + ".zip"
+ print("This copy came from a release zip. The update downloads \(zip), checks its SHA-256 and replaces the files in \(dir.path).")
+ guard !check else { return }
+ guard confirm("Update now?", yes: yes) else { return notUpdating() }
+ do {
+ try ReleaseZipUpdate.install(version, into: dir, currentVersion: mudroomVersion) { say($0) }
+ } catch { fail(error) }
+ print("Mudroom \(version) is installed. `mudroom --version` shows it from the next command on.")
+
+ case .source:
+ print("This copy wasn't installed from a release (a build from source?). Update the checkout and rebuild:")
+ print(" git pull && swift build -c release")
+ }
+ }
+
+ func notUpdating() {
+ print(stdinIsTTY ? "Not updated." : "Not updated: pass --yes to update without a terminal to ask in.")
+ }
+
+ /// Opens this copy of Mudroom.app with its update check. A running app
+ /// gets the request as a notification instead of the argument.
+ func openAppUpdater(_ app: URL) {
+ #if os(macOS)
+ do {
+ let r = try ProcessRunner.capture("/usr/bin/open", ["-a", app.path, "--args", "--check-for-updates"], timeout: 30)
+ if r.status != 0 { fail(MudroomError.commandFailed("open -a \(app.path)", r.status, r.stderr)) }
+ } catch { fail(error) }
+ if let id = Bundle(url: app)?.bundleIdentifier {
+ DistributedNotificationCenter.default().postNotificationName(
+ Notification.Name(id + ".checkForUpdates"), object: nil, userInfo: nil, deliverImmediately: true)
+ }
+ #endif
+ }
+}
diff --git a/Tests/MudroomCoreTests/UpdateTests.swift b/Tests/MudroomCoreTests/UpdateTests.swift
new file mode 100644
index 0000000..1972f1e
--- /dev/null
+++ b/Tests/MudroomCoreTests/UpdateTests.swift
@@ -0,0 +1,421 @@
+#if canImport(Darwin)
+import Darwin
+#elseif canImport(Glibc)
+import Glibc
+#elseif canImport(Musl)
+import Musl
+#elseif canImport(WinSDK)
+import WinSDK
+#endif
+import Foundation
+import Testing
+@testable import MudroomCore
+
+@Suite("Release versions")
+struct ReleaseVersionTests {
+ func v(_ s: String) -> ReleaseVersion { ReleaseVersion(s)! }
+
+ @Test("semver order, pre-releases before their release")
+ func order() {
+ let sorted = ["0.5.0", "0.5.1", "0.6.0-alpha", "0.6.0-alpha.1", "0.6.0-alpha.beta", "0.6.0-beta",
+ "0.6.0-beta.2", "0.6.0-beta.11", "0.6.0-rc.1", "0.6.0", "0.10.0", "1.0.0"].map(v)
+ for (a, b) in zip(sorted, sorted.dropFirst()) {
+ #expect(a < b, "\(a) < \(b)")
+ #expect(!(b < a))
+ }
+ #expect(v("v1.2.3") == v("1.2.3"))
+ #expect(v("1.2.3+build.5") == v("1.2.3"))
+ #expect(v("0.9.9") < v("0.10.0"))
+ #expect(v("1.2.3-rc.1").description == "1.2.3-rc.1")
+ }
+
+ @Test("anything that isn't a plain version is rejected, so it is safe to print")
+ func rejects() {
+ for bad in ["", "1", "1.2", "1.2.3.4", "01.2.3", "1.02.3", "1.2.3-", "1.2.3-01", "1.2.3-a..b", "1.2.3+",
+ "v", "1.2.3 ", " 1.2.3", "1.2.3\u{1b}[31m", "1.2.3-é", "1.2.x", "-1.2.3",
+ "1.2.3-" + String(repeating: "a", count: 80), "9999999999.0.0"] {
+ #expect(ReleaseVersion(bad) == nil, "\(bad.debugDescription)")
+ }
+ }
+}
+
+@Suite("Update check")
+struct UpdateCheckTests {
+ @Test("reads GitHub's latest release; drafts, pre-releases and odd tags are ignored")
+ func parse() {
+ let ok = Data(#"{"tag_name":"v0.6.0","draft":false,"prerelease":false,"html_url":"https://evil.example"}"#.utf8)
+ #expect(UpdateCheck.parseLatest(ok)?.version == ReleaseVersion("0.6.0"))
+ #expect(UpdateCheck.parseLatest(ok)?.pageURL == "https://github.com/Kernel-Hunter/mudroom/releases/tag/v0.6.0")
+ #expect(UpdateCheck.parseLatest(Data(#"{"tag_name":"v0.6.0","prerelease":true}"#.utf8)) == nil)
+ #expect(UpdateCheck.parseLatest(Data(#"{"tag_name":"v0.6.0","draft":true}"#.utf8)) == nil)
+ #expect(UpdateCheck.parseLatest(Data(#"{"tag_name":"v0.6.0-rc.1"}"#.utf8)) == nil)
+ #expect(UpdateCheck.parseLatest(Data(#"{"tag_name":"latest\u001b]0;pwned\u0007"}"#.utf8)) == nil)
+ #expect(UpdateCheck.parseLatest(Data(#"{"message":"API rate limit exceeded"}"#.utf8)) == nil)
+ #expect(UpdateCheck.parseLatest(Data("not json".utf8)) == nil)
+ }
+
+ @Test("only GitHub over HTTPS (and loopback in debug test builds) is fetched or followed")
+ func hosts() {
+ #expect(HTTPFetch.allowed(URL(string: "https://api.github.com/repos/x/y/releases/latest")))
+ #expect(HTTPFetch.allowed(URL(string: "https://github.com/x/y/releases/download/v1/a.zip")))
+ #expect(HTTPFetch.allowed(URL(string: "https://release-assets.githubusercontent.com/a")))
+ #expect(!HTTPFetch.allowed(URL(string: "http://api.github.com/repos")))
+ #expect(!HTTPFetch.allowed(URL(string: "https://github.com.evil.example/a")))
+ #expect(!HTTPFetch.allowed(URL(string: "https://evilgithubusercontent.com/a")))
+ #expect(!HTTPFetch.allowed(URL(string: "https://raw.githubusercontent.com/someone/else/main/x.zip")))
+ #expect(!HTTPFetch.allowed(URL(string: "https://gist.githubusercontent.com/a")))
+ #expect(!HTTPFetch.allowed(URL(string: "file:///etc/passwd")))
+ #expect(!HTTPFetch.allowed(URL(string: "http://10.0.0.1/a")))
+ }
+
+ @Test("a check against a local server: answer, redirect elsewhere, too big, error status")
+ func fetch() throws {
+ let release = #"{"tag_name":"v9.8.7","draft":false,"prerelease":false}"#
+ let server = try CannedHTTPServer { path in
+ switch path {
+ case "/latest": return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: \(release.utf8.count)\r\nConnection: close\r\n\r\n\(release)"
+ case "/moved": return "HTTP/1.1 302 Found\r\nLocation: https://example.com/latest\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ case "/huge": return "HTTP/1.1 200 OK\r\nContent-Length: 5000000\r\nConnection: close\r\n\r\n" + String(repeating: "x", count: 1000)
+ default: return "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
+ }
+ }
+ defer { server.cancel() }
+ func get(_ path: String) -> Result {
+ UpdateCheck.fetchLatest(from: URL(string: "http://127.0.0.1:\(server.port)\(path)")!, currentVersion: "0.5.0", timeout: 5)
+ }
+ #expect(try get("/latest").get().version == ReleaseVersion("9.8.7"))
+ #expect(server.requests.first?.contains("User-Agent: mudroom/0.5.0") == true)
+ #expect(server.requests.first?.lowercased().contains("cookie") == false)
+ guard case .failure = get("/moved") else { Issue.record("followed a redirect off GitHub"); return }
+ guard case .failure = get("/huge") else { Issue.record("read an oversized answer"); return }
+ #expect(get("/limited") == .failure(.status(403)))
+ // Nothing listening: fails, quickly, without throwing.
+ let closed = UpdateCheck.fetchLatest(from: URL(string: "http://127.0.0.1:1/latest")!, currentVersion: "0.5.0", timeout: 2)
+ guard case .failure = closed else { Issue.record("a closed port answered"); return }
+ }
+}
+
+@Suite("Update notice")
+struct UpdateNoticeTests {
+ let t0 = Date(timeIntervalSince1970: 2_000_000_000)
+ let current = ReleaseVersion("0.5.0")!
+
+ @Test("checks once a day, retries an hour after a failure, distrusts future dates")
+ func schedule() {
+ #expect(UpdateNoticeState().needsCheck(now: t0))
+ let checked = UpdateNoticeState(checked: t0, attempted: t0)
+ #expect(!checked.needsCheck(now: t0.addingTimeInterval(23 * 3600)))
+ #expect(checked.needsCheck(now: t0.addingTimeInterval(24 * 3600)))
+ let failed = UpdateNoticeState(checked: t0.addingTimeInterval(-3 * 86400), attempted: t0)
+ #expect(!failed.needsCheck(now: t0.addingTimeInterval(59 * 60)))
+ #expect(failed.needsCheck(now: t0.addingTimeInterval(61 * 60)))
+ // A clock that ran ahead and came back doesn't stop checks forever.
+ #expect(UpdateNoticeState(checked: t0.addingTimeInterval(86400 * 30)).needsCheck(now: t0))
+ }
+
+ @Test("announces a newer release, once a day per version")
+ func announce() {
+ var s = UpdateNoticeState(latest: "0.6.0")
+ #expect(s.versionToAnnounce(current: current, now: t0) == ReleaseVersion("0.6.0"))
+ s.shown = t0
+ s.shownVersion = "0.6.0"
+ #expect(s.versionToAnnounce(current: current, now: t0.addingTimeInterval(3600)) == nil)
+ #expect(s.versionToAnnounce(current: current, now: t0.addingTimeInterval(86400)) != nil)
+ s.latest = "0.6.1"
+ #expect(s.versionToAnnounce(current: current, now: t0.addingTimeInterval(3600)) == ReleaseVersion("0.6.1"))
+ for same in ["0.5.0", "0.4.9", "0.6.0-rc.1", "garbage", "v0.6.0\u{1b}[2J"] {
+ #expect(UpdateNoticeState(latest: same).versionToAnnounce(current: current, now: t0) == nil, "\(same)")
+ }
+ #expect(UpdateNotice.message(ReleaseVersion("0.6.0")!, current: current)
+ == "Mudroom 0.6.0 is available (you have 0.5.0). Run `mudroom update` to get it.")
+ }
+
+ @Test("opt-outs: environment, settings, the app's setting, CI")
+ func optOut() {
+ let on = MudroomSettings()
+ #expect(UpdateNotice.disabledReason(environment: [:], settings: on) == nil)
+ #expect(UpdateNotice.disabledReason(environment: ["MUDROOM_NO_UPDATE_CHECK": "1"], settings: on) != nil)
+ #expect(UpdateNotice.disabledReason(environment: ["MUDROOM_NO_UPDATE_CHECK": "true"], settings: on) != nil)
+ #expect(UpdateNotice.disabledReason(environment: ["MUDROOM_NO_UPDATE_CHECK": "0"], settings: on) == nil)
+ #expect(UpdateNotice.disabledReason(environment: ["MUDROOM_NO_UPDATE_CHECK": ""], settings: on) == nil)
+ #expect(UpdateNotice.disabledReason(environment: [:], settings: MudroomSettings(checkForUpdates: false)) != nil)
+ #expect(UpdateNotice.disabledReason(environment: [:], settings: MudroomSettings(checkForUpdates: true)) == nil)
+ #expect(UpdateNotice.disabledReason(environment: [:], settings: on, appChecksOff: true) != nil)
+ #expect(UpdateNotice.disabledReason(environment: ["CI": "true"], settings: on) != nil)
+ #expect(UpdateNotice.disabledReason(environment: ["CI": "false"], settings: on) == nil)
+ }
+
+ @Test("never during sessions, update itself, help, version or JSON output")
+ func quietCommands() {
+ #expect(UpdateNotice.allowed(arguments: ["list"]))
+ #expect(UpdateNotice.allowed(arguments: ["diff", "last"]))
+ #expect(UpdateNotice.allowed(arguments: ["network", "log", "last"]))
+ for args in [[], ["run", "."], ["start", "last"], ["agent", "login", "claude"], ["update"], ["help"],
+ ["network", "log", "last", "--json"], ["--version"], ["list", "--help"], ["-h"],
+ ["--generate-completion-script", "zsh"]] {
+ #expect(!UpdateNotice.allowed(arguments: args), "\(args)")
+ }
+ }
+
+ @Test("settings and the check cache live in the store and survive a bad file")
+ func persistence() throws {
+ let tmp = try TempDir()
+ let store = SessionStore(root: tmp.path("home"))
+ #expect(MudroomSettings.load(store) == MudroomSettings())
+ try MudroomSettings(checkForUpdates: false).save(store)
+ #expect(MudroomSettings.load(store).checkForUpdates == false)
+ // A damaged settings file leaves the check off.
+ try write(#"{"checkForUpdates":"no"}"#, to: MudroomSettings.url(store))
+ #expect(MudroomSettings.load(store).checkForUpdates == false)
+ try write("{not json", to: UpdateNoticeState.url(store))
+ #expect(UpdateNoticeState.load(store) == UpdateNoticeState())
+ try UpdateNoticeState(checked: t0, latest: "0.6.0").save(store)
+ #expect(UpdateNoticeState.load(store).latest == "0.6.0")
+ }
+
+ @Test("a run: checks when due, prints once, then stays quiet; a failed check is quiet and backs off")
+ func run() throws {
+ let tmp = try TempDir()
+ let store = SessionStore(root: tmp.path("home"))
+ let calls = LockedBox(0)
+ let now = t0
+ func notice(_ answer: Result, at time: Date) -> String? {
+ let r = UpdateNoticeRun(store: store, current: current, now: { time }) {
+ calls.value += 1
+ return answer
+ }
+ r.begin()
+ return r.finish(wait: 5)
+ }
+ let newer = Result.success(LatestRelease(version: ReleaseVersion("0.6.0")!))
+ #expect(notice(newer, at: now)?.contains("0.6.0 is available") == true)
+ #expect(calls.value == 1)
+ // Same day: no second request and no second notice.
+ #expect(notice(newer, at: now.addingTimeInterval(600)) == nil)
+ #expect(calls.value == 1)
+ // A day later: one more check, and the notice again.
+ #expect(notice(newer, at: now.addingTimeInterval(86400 + 60)) != nil)
+ #expect(calls.value == 2)
+
+ let other = SessionStore(root: tmp.path("other"))
+ let failing = UpdateNoticeRun(store: other, current: current, now: { now }) {
+ calls.value += 1
+ return .failure(.network("offline"))
+ }
+ failing.begin()
+ #expect(failing.finish(wait: 5) == nil)
+ #expect(calls.value == 3)
+ let again = UpdateNoticeRun(store: other, current: current, now: { now.addingTimeInterval(600) }) {
+ calls.value += 1
+ return .failure(.network("offline"))
+ }
+ again.begin()
+ #expect(again.finish(wait: 5) == nil)
+ #expect(calls.value == 3)
+ }
+
+ @Test("a slow check doesn't hold the command up")
+ func slow() throws {
+ let tmp = try TempDir()
+ let store = SessionStore(root: tmp.path("home"))
+ let r = UpdateNoticeRun(store: store, current: current) {
+ Thread.sleep(forTimeInterval: 3)
+ return .success(LatestRelease(version: ReleaseVersion("0.6.0")!))
+ }
+ let start = Date()
+ r.begin()
+ #expect(r.finish(wait: 0.3) == nil)
+ #expect(Date().timeIntervalSince(start) < 1.5)
+ // Cut off rather than refused: tried again in minutes, not an hour.
+ let state = UpdateNoticeState.load(store)
+ #expect(!state.needsCheck(now: Date().addingTimeInterval(60)))
+ #expect(state.needsCheck(now: Date().addingTimeInterval(UpdateNoticeState.cutOffRetry + 5)))
+ }
+}
+
+@Suite("Install method")
+struct InstallMethodTests {
+ func detect(_ path: String, windows: Bool = false, existing: Set = [], files: [String] = []) -> InstallMethod {
+ let paths = Set(existing.map { URL(fileURLWithPath: $0).standardizedFileURL.path })
+ return InstallMethod.detect(executable: URL(fileURLWithPath: path), windows: windows,
+ exists: { paths.contains($0.standardizedFileURL.path) }, contents: { _ in files })
+ }
+
+ @Test("the CLI inside Mudroom.app, with and without the Homebrew cask")
+ func mac() {
+ let app = URL(fileURLWithPath: "/Applications/Mudroom.app", isDirectory: true)
+ #expect(detect("/Applications/Mudroom.app/Contents/Helpers/mudroom") == .appBundle(app: app, homebrew: nil))
+ #expect(detect("/Applications/Mudroom.app/Contents/Helpers/mudroom",
+ existing: ["/opt/homebrew/Caskroom/mudroom", "/opt/homebrew/bin/brew"])
+ == .appBundle(app: app, homebrew: URL(fileURLWithPath: "/opt/homebrew/bin/brew")))
+ // A Caskroom entry without brew next to it isn't Homebrew's.
+ #expect(detect("/Applications/Mudroom.app/Contents/Helpers/mudroom", existing: ["/opt/homebrew/Caskroom/mudroom"])
+ == .appBundle(app: app, homebrew: nil))
+ #expect(detect("/Users/me/Applications/Mudroom.app/Contents/Helpers/mudroom")
+ == .appBundle(app: URL(fileURLWithPath: "/Users/me/Applications/Mudroom.app", isDirectory: true), homebrew: nil))
+ #expect(detect("/Users/me/src/mudroom/.build/release/mudroom") == .source)
+ #expect(detect("/usr/local/bin/mudroom") == .source)
+ #expect(detect("/tmp/Contents/Helpers/mudroom") == .source)
+ }
+
+ @Test("Scoop, winget, a release zip, or a build on Windows")
+ func windows() {
+ #expect(detect("/C:/Users/me/scoop/apps/mudroom/current/mudroom.exe", windows: true,
+ existing: ["/C:/Users/me/scoop/shims"]) == .scoop)
+ #expect(detect("/C:/ProgramData/scoop/apps/mudroom/0.5.0/mudroom.exe", windows: true,
+ existing: ["/C:/ProgramData/scoop/shims"]) == .scoop)
+ #expect(detect("/C:/Users/me/AppData/Local/Microsoft/WinGet/Packages/KernelHunter.Mudroom_Microsoft.Winget.Source_8wekyb3d8bbwe/mudroom-0.5.0-windows-x86_64/mudroom.exe",
+ windows: true) == .winget)
+ let zipDir = "/C:/Users/me/AppData/Local/Programs/Mudroom"
+ let zip = ["mudroom.exe", "LICENSE.txt", "swiftCore.dll", "Foundation.dll", "vcruntime140.dll"]
+ #expect(detect(zipDir + "/mudroom.exe", windows: true, files: zip)
+ == .releaseZip(directory: URL(fileURLWithPath: zipDir, isDirectory: true)))
+ // A shared tools folder, or another Swift program's runtime: not ours to replace.
+ #expect(detect("/C:/tools/mudroom.exe", windows: true, files: zip + ["other.exe"]) == .source)
+ #expect(detect("/C:/tools/mudroom.exe", windows: true, files: ["mudroom.exe", "swiftCore.dll", "Foundation.dll"]) == .source)
+ #expect(detect("/C:/src/mudroom/.build/debug/mudroom.exe", windows: true) == .source)
+ // Someone else's apps/mudroom folder without Scoop's shims.
+ #expect(detect("/C:/x/apps/mudroom/current/mudroom.exe", windows: true) == .source)
+ }
+}
+
+@Suite("Release zip update")
+struct ReleaseZipUpdateTests {
+ let hash = String(repeating: "ab", count: 32)
+
+ @Test("checksum files and GitHub's asset digests")
+ func checksums() {
+ #expect(ReleaseZipUpdate.parseChecksum("\(hash) mudroom-0.6.0-windows-x86_64.zip\n", file: "mudroom-0.6.0-windows-x86_64.zip") == hash)
+ #expect(ReleaseZipUpdate.parseChecksum("\(hash.uppercased()) *a.zip", file: "a.zip") == hash)
+ #expect(ReleaseZipUpdate.parseChecksum(hash, file: "a.zip") == hash)
+ #expect(ReleaseZipUpdate.parseChecksum("\(hash) b.zip", file: "a.zip") == nil)
+ #expect(ReleaseZipUpdate.parseChecksum("Not Found", file: "a.zip") == nil)
+ #expect(ReleaseZipUpdate.parseChecksum(String(hash.dropLast()), file: "a.zip") == nil)
+
+ let api = Data(#"{"assets":[{"name":"a.zip","digest":"sha256:\#(hash)"},{"name":"b.zip","digest":null}]}"#.utf8)
+ #expect(ReleaseZipUpdate.parseAssetDigest(api, file: "a.zip") == hash)
+ #expect(ReleaseZipUpdate.parseAssetDigest(api, file: "b.zip") == nil)
+ #expect(ReleaseZipUpdate.parseAssetDigest(api, file: "c.zip") == nil)
+
+ #expect(ReleaseZipUpdate.checksumProblem(actual: hash, published: []) != nil)
+ #expect(ReleaseZipUpdate.checksumProblem(actual: hash, published: [hash]) == nil)
+ #expect(ReleaseZipUpdate.checksumProblem(actual: hash, published: [hash, hash]) == nil)
+ #expect(ReleaseZipUpdate.checksumProblem(actual: hash, published: [hash, String(repeating: "cd", count: 32)]) != nil)
+ }
+
+ @Test("SHA-256 of a file")
+ func sha() throws {
+ let tmp = try TempDir()
+ try write("abc", to: tmp.path("f"))
+ #expect(try ReleaseZipUpdate.sha256(of: tmp.path("f")) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
+ }
+
+ @Test("swaps new files in, sets old ones aside, and removes them later")
+ func swap() throws {
+ let tmp = try TempDir()
+ let dir = tmp.path("Mudroom")
+ let staged = tmp.path("Mudroom/.stage/mudroom-0.6.0-windows-x86_64")
+ try write("old exe", to: dir.appendingPathComponent("mudroom.exe"))
+ try write("old dll", to: dir.appendingPathComponent("swiftCore.dll"))
+ try write("mine", to: dir.appendingPathComponent("notes.txt"))
+ try write("new exe", to: staged.appendingPathComponent("mudroom.exe"))
+ try write("new dll", to: staged.appendingPathComponent("swiftCore.dll"))
+ try write("added", to: staged.appendingPathComponent("Foundation.dll"))
+ // Held open while it is replaced, like the running mudroom.exe.
+ let held = try FileHandle(forReadingFrom: dir.appendingPathComponent("mudroom.exe"))
+ defer { try? held.close() }
+
+ let names = try ReleaseZipUpdate.swapIn(staged, to: dir)
+ #expect(names == ["Foundation.dll", "mudroom.exe", "swiftCore.dll"])
+ #expect(try read(dir.appendingPathComponent("mudroom.exe")) == "new exe")
+ #expect(try read(dir.appendingPathComponent("swiftCore.dll")) == "new dll")
+ #expect(try read(dir.appendingPathComponent("Foundation.dll")) == "added")
+ #expect(try read(dir.appendingPathComponent("notes.txt")) == "mine")
+ #expect(try read(dir.appendingPathComponent("mudroom.exe.mudroom-old")) == "old exe")
+ try held.close()
+ ReleaseZipUpdate.removeLeftovers(in: dir)
+ #expect(!exists(dir.appendingPathComponent("mudroom.exe.mudroom-old")))
+ #expect(!exists(dir.appendingPathComponent("swiftCore.dll.mudroom-old")))
+ }
+
+ @Test("a folder in the zip is refused before anything moves")
+ func refusesFolders() throws {
+ let tmp = try TempDir()
+ let dir = tmp.path("Mudroom")
+ let staged = tmp.path("stage")
+ try write("old", to: dir.appendingPathComponent("mudroom.exe"))
+ try write("new", to: staged.appendingPathComponent("mudroom.exe"))
+ try write("x", to: staged.appendingPathComponent("sub/evil.dll"))
+ #expect(throws: MudroomError.self) { try ReleaseZipUpdate.swapIn(staged, to: dir) }
+ #expect(try read(dir.appendingPathComponent("mudroom.exe")) == "old")
+ }
+
+ @Test("a failure halfway puts every file back")
+ func rollsBack() throws {
+ guard !isWindows, !isRoot else { return }
+ let tmp = try TempDir()
+ let dir = tmp.path("Mudroom")
+ let staged = tmp.path("stage")
+ try write("old a", to: dir.appendingPathComponent("a.dll"))
+ try write("old b", to: dir.appendingPathComponent("b.dll"))
+ try write("new a", to: staged.appendingPathComponent("a.dll"))
+ try write("new b", to: staged.appendingPathComponent("b.dll"))
+ // A leftover for b that can't be deleted stops the swap at b.
+ let stuck = dir.appendingPathComponent("b.dll.mudroom-old/locked")
+ try write("x", to: stuck.appendingPathComponent("file"))
+ chmod(stuck.path, 0o555)
+ defer { chmod(stuck.path, 0o755) }
+
+ #expect(throws: MudroomError.self) { try ReleaseZipUpdate.swapIn(staged, to: dir) }
+ #expect(try read(dir.appendingPathComponent("a.dll")) == "old a")
+ #expect(try read(dir.appendingPathComponent("b.dll")) == "old b")
+ #expect(try read(staged.appendingPathComponent("a.dll")) == "new a")
+ #expect(!exists(dir.appendingPathComponent("a.dll.mudroom-old")))
+ }
+}
+
+/// A loopback HTTP server that answers each request with whatever `reply`
+/// returns for its path, and keeps the request heads.
+final class CannedHTTPServer: @unchecked Sendable {
+ let fd: Int32
+ let port: UInt16
+ private let reply: @Sendable (String) -> String
+ private let received = LockedBox<[String]>([])
+ private let stopped = LockedBox(false)
+ var requests: [String] { received.value }
+
+ init(_ reply: @escaping @Sendable (String) -> String) throws {
+ self.reply = reply
+ (fd, port) = try Sock.listen(host: "127.0.0.1", port: 0)
+ Thread { [self] in serve() }.start()
+ }
+
+ private func serve() {
+ while !stopped.value {
+ guard Sock.waitReadable(fd, timeout: 0.1) else { continue }
+ if stopped.value { return }
+ guard let (conn, _, _) = Sock.accept(fd) else { continue }
+ var buf = Data()
+ var chunk = [UInt8](repeating: 0, count: 65536)
+ while buf.range(of: Data("\r\n\r\n".utf8)) == nil {
+ guard let n = Sock.receive(conn, &chunk) else { continue }
+ if n <= 0 { break }
+ buf.append(contentsOf: chunk[0..What you get
Safe apply
If a file changed in your project since the session started, Mudroom flags the conflict and won't overwrite it.
Per-project network rules
Locked, open or offline. Settings live outside the project, so the agent can't change them. Turn on npm, PyPI and GitHub with one command.
App and CLI
A native SwiftUI app for starting and reviewing sessions, and a mudroom command that does the same from a terminal or a script.
-
Open source
MIT licensed, no account, no telemetry. The README explains how it works and what it doesn't stop.
+
Open source
MIT licensed, no account, no telemetry. The only request Mudroom makes on its own is a daily update check, and you can turn it off. The README explains how it works and what it doesn't stop.
diff --git a/packaging/homebrew-tap/Casks/mudroom.rb b/packaging/homebrew-tap/Casks/mudroom.rb
index 057dee7..808e1ff 100644
--- a/packaging/homebrew-tap/Casks/mudroom.rb
+++ b/packaging/homebrew-tap/Casks/mudroom.rb
@@ -12,6 +12,9 @@
strategy :github_latest
end
+ # Mudroom.app updates itself (Sparkle). `brew upgrade --cask mudroom`
+ # still works when asked for by name.
+ auto_updates true
depends_on arch: :arm64
depends_on formula: "container"
depends_on macos: :tahoe
@@ -30,6 +33,8 @@
zap trash: [
"~/Library/Application Support/Mudroom",
+ "~/Library/Caches/io.github.kernel-hunter.mudroom",
+ "~/Library/HTTPStorages/io.github.kernel-hunter.mudroom",
"~/Library/Preferences/io.github.kernel-hunter.mudroom.plist",
"~/Library/Saved Application State/io.github.kernel-hunter.mudroom.savedState",
]
diff --git a/scripts/appcast.sh b/scripts/appcast.sh
new file mode 100755
index 0000000..6bf8e61
--- /dev/null
+++ b/scripts/appcast.sh
@@ -0,0 +1,186 @@
+#!/bin/zsh
+# Adds a release to the Mac app's update feed, docs/appcast.xml, which GitHub
+# Pages serves at https://kernel-hunter.github.io/mudroom/appcast.xml.
+#
+# scripts/appcast.sh 0.6.0 []
+#
+# Pass the zip's SHA-256 from the release workflow's log (the "Upload to the
+# release" step prints it) to make sure the zip signed here is the one CI
+# built; without it the script trusts the .sha256 on the release.
+#
+# Run it after the release workflow has uploaded Mudroom-.zip. It
+# downloads the zip and its .sha256 and checks one against the other, reads
+# the version, build number and minimum macOS from the app inside, signs the
+# zip with Sparkle's sign_update (the EdDSA key in the login Keychain), puts
+# the item first in the feed (the last ten releases are kept) and signs the
+# feed. Then commit docs/appcast.xml and push it to main; installed copies
+# of Mudroom see the update on their next daily check.
+#
+# Environment:
+# SPARKLE_BIN folder with sign_update
+# (default ~/Library/Application Support/KernelHunter/sparkle-2.10.0/bin)
+# SPARKLE_KEY_FILE sign with the private key in this file instead of the
+# Keychain (sign_update --ed-key-file)
+# For testing only:
+# APPCAST_PUBLIC_KEY the public key the app must carry, instead of Mudroom's
+# APPCAST_ZIP use this zip (with .sha256 next to it) instead of downloading
+# APPCAST_URL put this download URL in the feed instead of the GitHub one
+# APPCAST_FILE write this feed instead of docs/appcast.xml
+set -euo pipefail
+
+cd "$(dirname "$0")/.."
+
+if [[ $# -lt 1 || $# -gt 2 ]]; then
+ echo "usage: scripts/appcast.sh [] (e.g. 0.6.0, no leading v)" >&2
+ exit 1
+fi
+VERSION=${1#v}
+PINNED=${2:-}
+if [[ -n "$PINNED" && ! "$PINNED" =~ '^[0-9a-f]{64}$' ]]; then
+ echo "appcast.sh: '$PINNED' isn't a SHA-256" >&2
+ exit 1
+fi
+# The test settings must never reach the real feed.
+if [[ -z "${APPCAST_FILE:-}" && -n "${APPCAST_ZIP:-}${APPCAST_URL:-}${APPCAST_PUBLIC_KEY:-}" ]]; then
+ echo "appcast.sh: APPCAST_ZIP, APPCAST_URL and APPCAST_PUBLIC_KEY are for tests; set APPCAST_FILE too" >&2
+ exit 1
+fi
+if [[ ! "$VERSION" =~ '^[0-9]+\.[0-9]+\.[0-9]+$' ]]; then
+ echo "appcast.sh: '$VERSION' isn't a release version" >&2
+ exit 1
+fi
+REPO=Kernel-Hunter/mudroom
+PUBLIC_KEY=${APPCAST_PUBLIC_KEY:-QKKfpvfADDZDhLbEDTOZ4QKgc5EgHgxP3hGulato8T8=}
+SPARKLE_BIN=${SPARKLE_BIN:-"$HOME/Library/Application Support/KernelHunter/sparkle-2.10.0/bin"}
+SIGN="$SPARKLE_BIN/sign_update"
+KEY_ARGS=()
+[[ -z "${SPARKLE_KEY_FILE:-}" ]] || KEY_ARGS=(--ed-key-file "$SPARKLE_KEY_FILE")
+FEED=${APPCAST_FILE:-docs/appcast.xml}
+NAME="Mudroom-$VERSION.zip"
+URL=${APPCAST_URL:-"https://github.com/$REPO/releases/download/v$VERSION/$NAME"}
+NOTES_URL="https://github.com/$REPO/releases/tag/v$VERSION"
+
+[[ -x "$SIGN" ]] || { echo "appcast.sh: no sign_update at $SIGN (set SPARKLE_BIN)" >&2; exit 1; }
+
+tmp=$(mktemp -d "${TMPDIR:-/tmp}/mudroom-appcast.XXXXXX")
+trap 'rm -rf "$tmp"' EXIT
+
+if [[ -n "${APPCAST_ZIP:-}" ]]; then
+ cp "$APPCAST_ZIP" "$tmp/$NAME"
+ cp "$APPCAST_ZIP.sha256" "$tmp/$NAME.sha256"
+else
+ echo "==> Downloading $URL"
+ curl -fL --proto '=https' --proto-redir '=https' --max-filesize 300000000 --progress-bar -o "$tmp/$NAME" "$URL"
+ curl -fsSL --proto '=https' --proto-redir '=https' --max-filesize 1000 -o "$tmp/$NAME.sha256" "$URL.sha256"
+fi
+expected=$(cut -d' ' -f1 "$tmp/$NAME.sha256")
+actual=$(shasum -a 256 "$tmp/$NAME" | cut -d' ' -f1)
+if [[ ! "$expected" =~ '^[0-9a-f]{64}$' || "$expected" != "$actual" ]]; then
+ echo "appcast.sh: checksum mismatch (the .sha256 says '$expected', the zip is $actual)" >&2
+ exit 1
+fi
+if [[ -n "$PINNED" && "$PINNED" != "$actual" ]]; then
+ echo "appcast.sh: the zip on the release is $actual, not the $PINNED you passed. Not signing it." >&2
+ exit 1
+fi
+echo " sha256 ok ($actual)${PINNED:+, matches the one you passed}"
+[[ -n "$PINNED" ]] || echo " Compare it with the release workflow's log before you push the feed."
+
+# What's inside has to be what the feed will say it is.
+ditto -x -k "$tmp/$NAME" "$tmp/unpacked"
+APP="$tmp/unpacked/Mudroom.app"
+plist() { /usr/libexec/PlistBuddy -c "Print :$1" "$APP/Contents/Info.plist"; }
+short=$(plist CFBundleShortVersionString)
+build=$(plist CFBundleVersion)
+min_os=$(plist LSMinimumSystemVersion)
+key=$(plist SUPublicEDKey)
+if [[ "$short" != "$VERSION" ]]; then
+ echo "appcast.sh: the zip holds Mudroom $short, not $VERSION" >&2
+ exit 1
+fi
+if [[ "$key" != "$PUBLIC_KEY" ]]; then
+ echo "appcast.sh: the app's SUPublicEDKey is '$key', not Mudroom's key" >&2
+ exit 1
+fi
+[[ "$build" =~ '^[0-9]+$' ]] || { echo "appcast.sh: odd build number '$build'" >&2; exit 1; }
+codesign --verify --deep --strict "$APP"
+# Sparkle wants major.minor.patch.
+parts=(${(s:.:)min_os})
+while (( ${#parts} < 3 )); do parts+=(0); done
+min_os=${(j:.:)parts}
+
+# sparkle:edSignature="..." length="..."
+signed=$("$SIGN" "${KEY_ARGS[@]}" "$tmp/$NAME")
+if [[ ! "$signed" =~ '^sparkle:edSignature="[A-Za-z0-9+/=]+" length="[0-9]+"$' ]]; then
+ echo "appcast.sh: unexpected sign_update output: $signed" >&2
+ exit 1
+fi
+signature=${${signed#*edSignature=\"}%%\"*}
+"$SIGN" "${KEY_ARGS[@]}" --verify "$tmp/$NAME" "$signature"
+
+# The release notes go in the feed itself, so they are covered by its
+# signature. GitHub writes them when the release is created.
+notes=""
+if [[ -z "${APPCAST_ZIP:-}" ]] && command -v gh >/dev/null 2>&1; then
+ notes=$(gh release view "v$VERSION" --repo "$REPO" --json body --jq .body 2>/dev/null || true)
+fi
+[[ -n "$notes" ]] || notes="See the [release notes]($NOTES_URL)."
+printf '%s' "$notes" > "$tmp/notes.md"
+
+mkdir -p "$(dirname "$FEED")"
+[[ -f "$FEED" ]] || : > "$FEED"
+python3 -I - "$FEED" "$tmp/notes.md" "$VERSION" "$build" "$min_os" "$URL" "$NOTES_URL" "$signed" <<'PY'
+import re, sys
+from email.utils import formatdate
+from xml.sax.saxutils import escape, quoteattr
+
+feed, notes_file, version, build, min_os, url, notes_url, signed = sys.argv[1:]
+notes = open(notes_file, encoding="utf-8").read().replace("]]>", "]] >")
+length = re.search(r'length="(\d+)"', signed).group(1)
+signature = re.search(r'edSignature="([^"]+)"', signed).group(1)
+
+item = f"""
+ Mudroom {escape(version)}
+ {formatdate(usegmt=True)}
+ {escape(build)}
+ {escape(version)}
+ {escape(min_os)}
+ arm64
+ {escape(notes_url)}
+
+
+ """
+
+old = open(feed, encoding="utf-8").read()
+items = re.findall(r" .*?", old, flags=re.S)
+items = [i for i in items if f"{version}" not in i]
+# Sparkle orders updates by build number; a smaller one would never be offered.
+older = [int(b) for i in items for b in re.findall(r"(\d+)", i)]
+if older and int(build) <= max(older):
+ sys.exit(f"appcast.sh: build {build} isn't newer than build {max(older)} already in the feed")
+items = [item] + items[:9]
+
+# Everything else, the old feed signature included, is written fresh.
+out = """
+
+
+ Mudroom
+ https://github.com/Kernel-Hunter/mudroom
+ Updates for Mudroom.app. Made by scripts/appcast.sh; edit nothing by hand, the signature covers the whole file.
+ en
+""" + "\n".join(items) + """
+
+
+"""
+open(feed, "w", encoding="utf-8").write(out)
+PY
+
+# Signs the feed in place (the signature goes in the file), then checks it.
+"$SIGN" "${KEY_ARGS[@]}" --disable-signing-warning "$FEED"
+"$SIGN" "${KEY_ARGS[@]}" --verify "$FEED"
+xmllint --noout "$FEED"
+
+echo
+echo "version $VERSION (build $build, macOS $min_os or later)"
+echo "feed $FEED"
+echo "next commit $FEED and push it to main"
diff --git a/scripts/build-app.sh b/scripts/build-app.sh
index d5a3106..8ffa30d 100755
--- a/scripts/build-app.sh
+++ b/scripts/build-app.sh
@@ -1,6 +1,7 @@
#!/bin/zsh
# Builds build/Mudroom.app: the SwiftUI app plus the `mudroom` CLI it runs in
-# Terminal, with Info.plist and icon, ad-hoc signed.
+# Terminal, with Info.plist, icon and Sparkle.framework (the updater),
+# ad-hoc signed.
#
# scripts/build-app.sh # release build
# CONFIG=debug scripts/build-app.sh
@@ -39,8 +40,19 @@ BIN=$(swift build -c "$CONFIG" --show-bin-path)
[[ -f App/AppIcon.icns ]] || swift scripts/make-icon.swift App/AppIcon.icns
rm -rf "$APP"
-mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Helpers" "$APP/Contents/Resources"
+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Helpers" "$APP/Contents/Resources" "$APP/Contents/Frameworks"
cp "$BIN/MudroomApp" "$APP/Contents/MacOS/Mudroom"
+# SwiftPM also leaves an rpath to its own build folder; the app loads
+# Sparkle from Contents/Frameworks only.
+otool -l "$APP/Contents/MacOS/Mudroom" |
+ awk '/cmd LC_RPATH/ { getline; getline; sub(/^ *path /, ""); sub(/ \(offset [0-9]+\)$/, ""); print }' |
+ while IFS= read -r rpath; do
+ [[ "$rpath" == @* ]] || install_name_tool -delete_rpath "$rpath" "$APP/Contents/MacOS/Mudroom"
+done
+# ditto keeps the framework's symlinks. The XPC services are only for
+# sandboxed apps, which Mudroom isn't.
+ditto "$BIN/Sparkle.framework" "$APP/Contents/Frameworks/Sparkle.framework"
+rm -rf "$APP/Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices" "$APP/Contents/Frameworks/Sparkle.framework/XPCServices"
# Not in MacOS/: "mudroom" and "Mudroom" are the same name on a
# case-insensitive volume.
cp "$BIN/mudroom" "$APP/Contents/Helpers/mudroom"
@@ -48,12 +60,17 @@ cp App/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"
sed -e "s/__VERSION__/$VERSION/" -e "s/__BUILD__/$BUILD/" App/Info.plist > "$APP/Contents/Info.plist"
printf 'APPL????' > "$APP/Contents/PkgInfo"
-# Ad-hoc signature, inside out (helper first, then the bundle). No hardened
-# runtime and no entitlements: the app and CLI only shell out to `container`,
-# which has its own virtualization entitlement.
+# Ad-hoc signature, inside out: Sparkle's helpers, then the framework, the
+# CLI, and the bundle last. No hardened runtime and no entitlements: the app
+# and CLI only shell out to `container`, which has its own virtualization
+# entitlement.
+SPARKLE="$APP/Contents/Frameworks/Sparkle.framework"
+codesign --force --sign - --timestamp=none "$SPARKLE/Versions/B/Autoupdate"
+codesign --force --sign - --timestamp=none "$SPARKLE/Versions/B/Updater.app"
+codesign --force --sign - --timestamp=none "$SPARKLE"
codesign --force --sign - --timestamp=none "$APP/Contents/Helpers/mudroom"
codesign --force --sign - --timestamp=none "$APP"
-codesign --verify --strict "$APP"
+codesign --verify --deep --strict "$APP"
# Keep dev builds out of Spotlight and the app launcher, so they don't show up
# next to an installed copy.
diff --git a/scripts/release.sh b/scripts/release.sh
index dd2836a..6081cb7 100755
--- a/scripts/release.sh
+++ b/scripts/release.sh
@@ -1,6 +1,8 @@
#!/bin/zsh
# Builds a release zip: dist/Mudroom-.zip, containing Mudroom.app
-# (app + bundled `mudroom` CLI), ad-hoc signed. Prints the SHA-256.
+# (app, bundled `mudroom` CLI and Sparkle), ad-hoc signed. Prints the SHA-256.
+# After the release is published, scripts/appcast.sh adds it to the update
+# feed.
#
# scripts/release.sh 0.4.0
#
@@ -29,7 +31,14 @@ if [[ "$plist_version" != "$VERSION" || "$cli_version" != "$VERSION" ]]; then
exit 1
fi
codesign --verify --deep --strict "$APP"
-for bin in "$APP/Contents/MacOS/Mudroom" "$CLI"; do
+# Sparkle checks updates against this key; a build without it could never
+# update again.
+key=$(/usr/libexec/PlistBuddy -c 'Print :SUPublicEDKey' "$APP/Contents/Info.plist")
+if [[ "$key" != "QKKfpvfADDZDhLbEDTOZ4QKgc5EgHgxP3hGulato8T8=" ]]; then
+ echo "release.sh: Info.plist has the wrong SUPublicEDKey: $key" >&2
+ exit 1
+fi
+for bin in "$APP/Contents/MacOS/Mudroom" "$CLI" "$APP/Contents/Frameworks/Sparkle.framework/Versions/B/Sparkle"; do
if ! lipo -archs "$bin" | grep -qw arm64; then
echo "release.sh: $bin is not arm64" >&2
exit 1