diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c99626..0963604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 0.5.0 — 2026-11-14 + +- **Self-update.** Update Workbench now updates itself. Every check, and the new **Update Workbench → Check for Updates…** command, reads `appcast.xml` from the latest GitHub release (`SUFeedURL` in Info.plist). The app shows up in Updates like any other, with a banner and **Update and Relaunch**; Settings → Updates shows the installed version, how it was installed and the result of the last check. The old configurable self-update feed (off by default, Developer ID only) is gone. +- **Release signing.** The app has no Developer ID team, so each release ZIP is signed with an Ed25519 release key (`tools/release-key.swift`, private key in the developer's login Keychain, public key in `Resources/release-public-key.txt` and Info.plist as `SUPublicEDKey`). `make-release.sh` signs the ZIP, checks the key against the app and writes `appcast.xml`. The direct-install pipeline now accepts an app without a team only when the archive verifies against the installed app's own key and the new app ships the same key; Developer ID apps keep their team rules and never accept a team-less update. +- **Homebrew.** New cask `update-workbench` in the `kasakir-ai/tap` tap. When Homebrew installed the app, its update runs `brew update` then `brew upgrade --cask update-workbench`, and the signed feed tells it whether a newer version exists (scans don't refresh taps). The cask removes the download quarantine flag after installing. +- **Pastel redesign.** A new palette of soft tones (lavender, lilac, sky, mint, aqua, rose, peach, butter, coral, slate), each with a pastel surface and a deeper ink for text, in light and dark mode. Pastel hero and sheet headers with dark text, pastel source and status badges, initial tiles, stat tiles, sidebar icon tiles, card header tiles and in-row **Update** buttons. +- **Right-click menu** on list rows: update, open, show in Finder, skip this version, snooze, ignore. +- Fixed: approving a new developer team or accepting a disk image license right after an update did nothing, because the follow-up check was still running. Updates requested while the app is busy are now queued and start when it's idle, using the latest scan. +- Fixed: the History badge counted every failure ever logged and never cleared. It now counts apps whose most recent attempt failed. +- Fixed: Relaunch quit the app even when the new copy couldn't be opened. +- Update All installs Update Workbench itself last. +- The menu bar panel's window button reads **Show Window** (the old label was cut off). +- Tests: `Tests/SelfUpdateTests.swift` (Ed25519-anchored installs: signed, unsigned, wrong key, swapped key, no key, Developer ID app offered a team-less update; self-update helpers; History badge). +- Version 0.5.0 (build 8). + ## 0.4.1 — 2026-11-13 - Development builds no longer show up in Spotlight or Launchpad next to the installed app. `./build.sh` now builds `dist.noindex/UpdateWorkbench.app` (Spotlight skips folders ending in `.noindex`) and unregisters that copy from Launch Services. `./test.sh` creates its fixture apps and disk images in a temporary `.noindex` folder, and `./make-release.sh` stages the DMG contents in one. diff --git a/README.md b/README.md index fb54a0e..855194c 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,23 @@ Update Workbench is a native macOS app that finds and installs updates for your ## Install +**With Homebrew:** + +```sh +brew install --cask kasakir-ai/tap/update-workbench +``` + +Homebrew then keeps it up to date (`brew upgrade`), and Update Workbench updates itself through Homebrew too. + +**Or download it:** + 1. Download the latest `UpdateWorkbench-.dmg` (or the `.zip`) from the [Releases page](https://github.com/Kasakir-AI/UpdateWorkbench/releases). 2. Open the DMG and drag **Update Workbench** into **Applications**. 3. **First launch:** the app is ad-hoc signed and not notarized by Apple, so macOS blocks a normal double-click the first time. Right-click (or Control-click) the app in Applications and choose **Open**, then **Open** again. Or try to open it once, then go to **System Settings → Privacy & Security** and click **Open Anyway**. After that it opens normally. Requires macOS 14 or newer on Apple silicon. Check the download against `SHA256SUMS` with `shasum -a 256 -c SHA256SUMS`. -**Upgrading from an earlier version:** quit Update Workbench, drag the new version into Applications and choose **Replace**. Settings, rules and approvals are kept. You may need the right-click **Open** step once more. +**Updating:** from 0.5.0 on, Update Workbench updates itself. Choose **Update Workbench → Check for Updates…** (every check also looks), then **Update and Relaunch**. A copy installed with Homebrew is updated through Homebrew; a downloaded copy installs the new release only if it carries the developer's release signature. To move from 0.4.x to 0.5.0, quit Update Workbench, drag the new version into Applications and choose **Replace** (settings, rules and approvals are kept); you may need the right-click **Open** step once more. **App Store updates (optional):** install the free `mas` tool with **Homebrew → Install mas…** (or `brew install mas` in Terminal) and stay signed in to the App Store app. When mas needs your Mac password to install an App Store update, click **Finish in Terminal** and type the password there. Update Workbench never sees it. You can also click **Open App Store Updates** and update in the App Store app. @@ -21,13 +31,23 @@ Requires Xcode command-line tools. ```sh ./build.sh # builds dist.noindex/UpdateWorkbench.app (ad-hoc signed) ./test.sh # offline test suite (swift test); extra arguments go to swift test, e.g. --filter VersionOrderTests -./make-release.sh # DMG, ZIP and SHA256SUMS in release/ +./make-release.sh # DMG, ZIP, SHA256SUMS and the signed appcast.xml in release/ ``` +Releases are signed with an Ed25519 release key kept in the developer's login Keychain (`xcrun swift tools/release-key.swift generate | public-key | sign FILE`). Only its public half is in the repository (`Resources/release-public-key.txt`); `build.sh` writes it into Info.plist as `SUPublicEDKey`, together with the feed address `SUFeedURL`. A build made with a different key can't update copies made with this one. + The version and build number are set once, at the top of `build.sh`. GitHub Actions runs `./test.sh` and `./build.sh` on every push to `main` and on pull requests. Builds go to `dist.noindex/`. Spotlight skips folders whose names end in `.noindex`, so development builds, test fixtures and release staging never appear in Spotlight or Launchpad next to the copy in Applications. +## New in 0.5.0 + +- **Updates itself.** Update Workbench checks for its own new versions with every check and from **Update Workbench → Check for Updates…**. **Update and Relaunch** installs the new version and restarts the app. Each release is signed with the developer's release key, and a download without that signature is never installed. +- **Install with Homebrew.** `brew install --cask kasakir-ai/tap/update-workbench`. When Homebrew installed it, Update Workbench updates itself through Homebrew. +- **A softer look.** Pastel colors throughout, in light and dark mode: the update summary, source and status badges, app tiles, the sidebar, cards and sheets. +- **Right-click an app** in any list to update, skip, snooze, ignore, open or show it in Finder. +- **Fixes.** Approving a new developer signature or accepting a license agreement right after an update now retries the install (it used to do nothing while the follow-up check ran). The History badge counts only apps whose last update failed, so it clears after a successful retry. Relaunching no longer quits the app if the new copy can't be opened. + ## New in 0.4.1 - **Betas move on to the final release.** If you run a beta such as `1.0-beta.1`, the finished `1.0` is now offered. Before, it wasn't. @@ -80,6 +100,8 @@ Rendered with fictional apps and the built-in snapshot harness. They show no rea | ![Signer approval sheet](docs/screenshots/signer-approval-dark.png) | ![Rules settings](docs/screenshots/settings-rules-dark.png) | | **Menu bar** | **Settings → Trust** | | ![Menu bar panel](docs/screenshots/menubar-dark.png) | ![Trust settings](docs/screenshots/settings-trust-dark.png) | +| **Update Workbench updates itself** | **Settings → Updates** | +| ![Self-update banner](docs/screenshots/self-update-light.png) | ![Update Workbench update settings](docs/screenshots/settings-updates-light.png) | To render every screen yourself in dark and light (fake data, no scanning, nothing installed, real settings untouched): @@ -104,7 +126,7 @@ Running the app from `dist.noindex/` registers that copy with Launch Services ag - **Permissions view:** read-only status for Full Disk Access (heuristic), App Management (no public query; guidance only), Automation (not used), notifications, administrator account, write access to each application folder, launch at login and Keychain, with System Settings links. - **Proxy settings:** system, none or manual HTTP/HTTPS or SOCKS proxy for the app's own requests. Authentication passwords are stored only in the login Keychain (Security framework, service `local.updateworkbench.proxy`) and are answered on proxy challenges. Homebrew/mas receive the proxy host and port through `http_proxy`/`https_proxy`/`all_proxy`, never the password. - **Notifications:** optional (Settings → General) banners for newly available updates (each version announced once) and for completed or failed updates. -- **Self-update:** Settings → Updates accepts `github:owner/repository`, a GitHub repository URL, or an HTTPS Sparkle appcast. It is **disabled by default** because no release feed is published. Installation reuses the verified direct-install pipeline, so a release must match the bundle ID and Developer ID team; the ad-hoc development build cannot self-update. +- **Self-update:** every check, and **Check for Updates…** in the app menu, reads the `appcast.xml` of the latest GitHub release. The ZIP it points to must carry a valid Ed25519 signature from the release key built into the installed app (`SUPublicEDKey`), and the new app must ship the same key, have the same bundle ID and be newer. Then it is installed through the normal direct-install pipeline and the app relaunches. Copies installed with Homebrew are updated with `brew update` and `brew upgrade --cask update-workbench` instead. Settings → Updates shows how the app was installed and where updates come from. - User-selected Homebrew adoption by cask token; catalog refresh; Homebrew diagnostics and cleanup. - Rules (Settings → Rules): ignored apps, skipped versions, and pre-release holds (global, on by default, with per-app overrides); two/four-day snoozes. Pre-releases include versions such as `-beta.1`, `b2`, `rc1`, alpha, preview or nightly, Sparkle beta channels and GitHub pre-releases. - Background checks Off, Daily or Weekly while the app runs (it stays in the menu bar), a menu bar icon with the update count and quick list, a Dock badge, launch at login, source filters, signature/Gatekeeper details, sanitized release notes, reveal/open actions, JSON inventory export. @@ -117,7 +139,7 @@ Choose **Homebrew → Refresh Catalog** before checking for the newest Homebrew ## Direct Sparkle, GitHub and Electron installs -Supports complete DMG/ZIP app payloads from public HTTPS appcasts, selected GitHub releases and declared Electron feeds. Downloads use HTTPS-only redirects and size limits. If the feed publishes a SHA-512 (Electron), it must match. If the installed app declares a Sparkle Ed25519 public key, its archive signature must verify before extraction. The app also checks bundle ID, installed signing team, code signatures, Gatekeeper approval, version, and OS/CPU compatibility. Running apps must be closed first. The new app is staged in a private folder on the same volume (never beside the app), swapped in and verified; the previous version is deleted only after that succeeds and is put back if anything fails, so no copies are left behind. The scanner skips hidden and `*-backup-*` app bundles. A different signing team stops the install and asks you to review and approve that team for the app; Gatekeeper and code signing must still pass. DMGs are checked for encryption and license agreements, attached read-only with `-nobrowse -noautoopen`, must contain exactly one app with the expected bundle ID, are copied out with `ditto`, and are always detached. When a release offers both, the DMG is preferred over the ZIP. ZIPs may contain symbolic links, such as the `Versions/Current` framework links every Electron app ships, as long as each link is relative and stays inside its `.app` bundle. The ZIP directory is checked before anything is written: absolute or escaping link targets, entries below a link, path traversal, duplicates, encrypted entries and special files are rejected, and after extraction every link must resolve inside the bundle and hard links are refused. DMGs permit only bundle-internal links. Unsigned or unapproved different-team updates, encrypted disk images, protected destinations, PKG installers, deltas and unsupported payloads fail closed. Many GitHub-distributed Electron apps are unsigned or ad-hoc signed and will therefore fail closed by design. +Supports complete DMG/ZIP app payloads from public HTTPS appcasts, selected GitHub releases and declared Electron feeds. Downloads use HTTPS-only redirects and size limits. If the feed publishes a SHA-512 (Electron), it must match. If the installed app declares a Sparkle Ed25519 public key, its archive signature must verify before extraction. Apps without a Developer ID team (ad-hoc signed) can only be replaced this way: the archive must verify against the installed app's key and the new app must carry the same key; otherwise they are refused. The app also checks bundle ID, installed signing team, code signatures, Gatekeeper approval, version, and OS/CPU compatibility. Running apps must be closed first. The new app is staged in a private folder on the same volume (never beside the app), swapped in and verified; the previous version is deleted only after that succeeds and is put back if anything fails, so no copies are left behind. The scanner skips hidden and `*-backup-*` app bundles. A different signing team stops the install and asks you to review and approve that team for the app; Gatekeeper and code signing must still pass. DMGs are checked for encryption and license agreements, attached read-only with `-nobrowse -noautoopen`, must contain exactly one app with the expected bundle ID, are copied out with `ditto`, and are always detached. When a release offers both, the DMG is preferred over the ZIP. ZIPs may contain symbolic links, such as the `Versions/Current` framework links every Electron app ships, as long as each link is relative and stays inside its `.app` bundle. The ZIP directory is checked before anything is written: absolute or escaping link targets, entries below a link, path traversal, duplicates, encrypted entries and special files are rejected, and after extraction every link must resolve inside the bundle and hard links are refused. DMGs permit only bundle-internal links. Unsigned or unapproved different-team updates, encrypted disk images, protected destinations, PKG installers, deltas and unsupported payloads fail closed. Many GitHub-distributed Electron apps are unsigned or ad-hoc signed and will therefore fail closed by design. ## Validation status @@ -129,7 +151,9 @@ No real application upgrades, installs, adoptions, reinstalls, uninstalls, unpin A read-only smoke run on the development Mac found 80 apps (2 Electron feeds, 21 vendor-managed), checked both Electron feeds live (one real newer release with a native arm64 ZIP was identified, not installed), and produced Homebrew cask suggestions for 19 apps. The 0.2.0 bundle launched and was quit; GUI navigation of the new screens was not exercised by automation. GUI launch, navigation and a read-only scan of 267 apps and packages were verified for 0.1.0; see `docs/validation.md`. -Not end-to-end validated: actual vendor downloads and installs (Sparkle, GitHub, Electron), Homebrew installation/adoption/reinstall/uninstall/unpin, App Store installation, Trash moves of real apps, notification delivery, authenticated proxies, self-update installation, login registration and rollback under real failure conditions. Permission states other than write access and admin membership are heuristics. +Not end-to-end validated: actual vendor downloads and installs (Sparkle, GitHub, Electron), Homebrew installation/adoption/reinstall/uninstall/unpin, App Store installation, Trash moves of real apps, notification delivery, authenticated proxies, a self-update from the published feed (the first one will be 0.5.0 → 0.5.1), login registration and rollback under real failure conditions. Permission states other than write access and admin membership are heuristics. + +0.5.0 checks: the redesigned screens and the new self-update banner and Settings → Updates tab were rendered in dark and light and reviewed. A self-update was installed end to end with the real `codesign` checks into a temporary copy: a 0.5.0 build was replaced by a re-signed 0.5.1 build from a ZIP signed with the release key, and the same ZIP with altered bytes was refused. Unit tests cover signed, unsigned, wrong-key, swapped-key and key-less archives and a Developer ID app offered a team-less update. ## Known limitations @@ -137,7 +161,7 @@ Not end-to-end validated: actual vendor downloads and installs (Sparkle, GitHub, - Vendor-managed updaters are opened, not driven; there is no in-app version check for Adobe, Microsoft, Google or Mozilla apps. - Electron providers other than public `github`, `generic` and `s3` (for example private GitHub, Bitbucket, Keygen, custom), and differential (blockmap) downloads, are not supported. - Cask matching uses app artifact names; apps whose bundle name differs from every cask artifact are not matched, and there is no automatic adoption. -- No published self-update feed or Developer ID signing and notarization yet. +- No Developer ID signing or notarization yet. Downloaded copies need the right-click **Open** step once; the Homebrew cask clears the download quarantine flag after installing, so Homebrew copies open normally. - Background checks run only while Update Workbench is open (it keeps running in the menu bar); there is no separate background agent. - Release notes are text only: images, tables and embedded media are dropped. - `hdiutil attach` prints deprecation warnings on recent macOS versions; it still works and is used because it supports license agreements. diff --git a/Resources/release-public-key.txt b/Resources/release-public-key.txt new file mode 100644 index 0000000..f62fafb --- /dev/null +++ b/Resources/release-public-key.txt @@ -0,0 +1 @@ +tJwCpdFilOwt4OwNmqA1Sb66XwS5D3UFOBibIn8gNF0= diff --git a/Sources/UpdateWorkbench/App.swift b/Sources/UpdateWorkbench/App.swift index cd74373..48ada65 100644 --- a/Sources/UpdateWorkbench/App.swift +++ b/Sources/UpdateWorkbench/App.swift @@ -6,7 +6,16 @@ import UniformTypeIdentifiers @MainActor final class WorkbenchModel: ObservableObject { @Published var items: [UpdateItem] = [] - @Published var busy = false + /// Updates requested while something else runs (a signer approval or license acceptance right after an + /// update, when the follow-up check is still going) start as soon as the app is idle again. + @Published var busy = false { + didSet { + guard !busy, !queuedUpdates.isEmpty else { return } + let next = queuedUpdates; queuedUpdates = [] + Task { @MainActor in self.update(next) } + } + } + private var queuedUpdates: [UpdateItem] = [] @Published var log = "Ready. Check for updates to scan installed applications." @Published var selected: String? @Published var search = "" @@ -50,9 +59,14 @@ final class WorkbenchModel: ObservableObject { @Published var launchAtLogin = SMAppService.mainApp.status == .enabled @Published var notificationsEnabled = UserDefaults.standard.bool(forKey: "notificationsEnabled") @Published var permissions: [PermissionCheck] = [] - @Published var selfUpdateRelease: SparkleRelease? - @Published var selfUpdateMessage = "" - @Published var selfUpdateInstalled = false + /// Result of the last "Check for Updates…" of Update Workbench itself. + @Published var selfCheckMessage = "" + @Published var checkingSelf = false + /// Update Workbench replaced itself; it runs the old code until it is relaunched. + @Published var relaunchNeeded = false + /// Shows the result of "Check for Updates…" from the app menu as an alert. + @Published var showSelfCheckResult = false + var installedWithHomebrew: Bool { isPreview ? false : SelfUpdate.installedWithHomebrew() } @Published var failures: [String: String] = [:] @Published var showConsole = false @Published var confirmUpdateAll = false @@ -95,12 +109,15 @@ final class WorkbenchModel: ObservableObject { case .updates: updates.count case .suggestions: suggestions.count case .ignored: ignoredItems.count - case .history: history.filter { $0.result == .failed || $0.result == .restoreFailed }.isEmpty ? 0 : history.filter { $0.result == .failed || $0.result == .restoreFailed }.count + case .history: unresolvedFailures case .packages: items.filter { $0.provider == .homebrewFormula }.count case .applications: items.filter { $0.provider != .homebrewFormula }.count case .permissions: permissions.filter { $0.state == .denied }.count } } + /// Apps whose most recent update attempt failed. A later successful install clears the badge. + var unresolvedFailures: Int { HistoryEntry.unresolvedFailures(history) } + var selfItem: UpdateItem? { items.first(where: \.isSelf) } var ignoredItems: [UpdateItem] { items.filter { decision($0) != .show || isSnoozed($0) } } var appVersion: String { AppIdentity.version } var suggestions: [UpdateItem] { @@ -151,9 +168,18 @@ final class WorkbenchModel: ObservableObject { NSApp?.dockTile.badgeLabel = updates.isEmpty ? nil : "\(updates.count)" } func update(_ targets: [UpdateItem]) { - guard !busy, !isPreview else { return }; busy = true + guard !isPreview else { return } + guard !busy else { + queuedUpdates += targets.filter { target in !queuedUpdates.contains { $0.id == target.id } } + append("Queued \(targets.map(\.name).joined(separator: ", ")); it starts when the current task finishes.") + return + } + busy = true + // A check may have finished since the request: install what the latest scan found. + let current = targets.map { target in items.first { $0.id == target.id } ?? target } Task { - let actionable = targets.filter(\.canUpdateDirectly) + // Update Workbench replaces itself last, after everything else in the batch is done. + let actionable = current.filter(\.canUpdateDirectly).sorted { !$0.isSelf && $1.isSelf } var succeeded: [String] = [], failed: [String] = [] for (index, item) in actionable.enumerated() { operation = "Updating \(index + 1) of \(actionable.count): \(item.name)" @@ -166,6 +192,7 @@ final class WorkbenchModel: ObservableObject { append(outcome.message); succeeded.append(item.name); failures.removeValue(forKey: item.id) record(item, result: .installed, message: outcome.message, toVersion: outcome.installedVersion) markInstalled(item, version: outcome.installedVersion) + if item.isSelf { relaunchNeeded = true } } catch let change as SignerChange { append("\(item.name): \(change.localizedDescription)"); failed.append(item.name) failures[item.id] = "Signed by a new developer team. Review it to continue." @@ -185,6 +212,10 @@ final class WorkbenchModel: ObservableObject { } busy = false; operation = failed.isEmpty ? "Updates finished" : "\(failed.count) update(s) need attention. See Console." if !failed.isEmpty && signerQueue.isEmpty && licenseQueue.isEmpty { showConsole = true } + // "Update and Relaunch" of Update Workbench alone: start the new copy right away. + if relaunchNeeded, actionable.count == 1, actionable[0].isSelf, failed.isEmpty, queuedUpdates.isEmpty { + relaunch(); return + } presentNextPrompt() scan() } @@ -431,37 +462,46 @@ final class WorkbenchModel: ObservableObject { permissions = PermissionsBackend.checks(probes) } } - func checkSelfUpdate() { - selfUpdateRelease = nil; selfUpdateInstalled = false - let feed: SelfUpdateFeed - do { feed = try SelfUpdateFeed.parse(UserDefaults.standard.string(forKey: SelfUpdateFeed.defaultsKey) ?? "") } - catch { selfUpdateMessage = error.localizedDescription; return } - guard feed != .disabled else { selfUpdateMessage = "Self-update is disabled. No release feed is configured."; return } - selfUpdateMessage = "Checking \(feed.description)…" - Task { - do { - selfUpdateRelease = try await SelfUpdate.check(feed, installedVersion: appVersion) - selfUpdateMessage = selfUpdateRelease.map { "Update Workbench \($0.version) is available." } ?? "Update Workbench is up to date." - } catch { selfUpdateMessage = error.localizedDescription } + /// "Check for Updates…" for Update Workbench itself: reads only its signed release feed, so it is quick and + /// doesn't need a full scan. The result becomes the app's own entry in the list. + func checkSelf(announce: Bool = false) { + guard !isPreview, !checkingSelf else { return } + guard let feed = SelfUpdate.feedURL else { + selfCheckMessage = "This build has no release feed, so it can't check for its own updates." + showSelfCheckResult = announce; return } - } - func installSelfUpdate() { - guard let release = selfUpdateRelease, !busy else { return } - busy = true; selfUpdateMessage = "Installing \(release.version)…" + checkingSelf = true; selfCheckMessage = "Checking for a new version of Update Workbench…" + let base = selfItem ?? SelfUpdate.currentItem() + let allowBetas = rules.allowsPrereleases(for: base.id) Task { do { - var options = InstallOptions(); options.trustedSigners = nil - let message = try await SparkleBackend.install(release: release, target: Bundle.main.bundleURL, replacingRunningSelf: true, options: options).message - append(message); selfUpdateMessage = message; selfUpdateInstalled = true - } catch { selfUpdateMessage = error.localizedDescription; append("Self-update: \(error.localizedDescription)") } - busy = false + let release = try await SparkleBackend.check(feedURL: feed, installedVersion: base.installedVersion, allowPrerelease: allowBetas) + var item = base + item.latestVersion = release?.version ?? item.installedVersion + item.sparkleRelease = release + item.isOutdated = release != nil + if let index = items.firstIndex(where: { $0.id == item.id }) { items[index] = item } else if release != nil { items.append(item) } + if let release { + selfCheckMessage = "Update Workbench \(release.version) is available" + (item.provider == .homebrewCask ? " through Homebrew." : ".") + if decision(item) == .show { section = .updates; selected = item.id } + } else { + selfCheckMessage = "Update Workbench \(appVersion) is the newest version." + } + updateBadge() + } catch { selfCheckMessage = "Couldn't check for a new version: \(error.localizedDescription)" } + checkingSelf = false + if announce { showSelfCheckResult = true } } } + /// Opens the freshly installed copy, then quits this one. If it can't be opened, this copy keeps running. func relaunch() { let configuration = NSWorkspace.OpenConfiguration() configuration.createsNewApplicationInstance = true - NSWorkspace.shared.openApplication(at: Bundle.main.bundleURL, configuration: configuration) { _, _ in - Task { @MainActor in NSApp.terminate(nil) } + NSWorkspace.shared.openApplication(at: Bundle.main.bundleURL, configuration: configuration) { _, error in + Task { @MainActor in + if let error { self.append("Couldn't relaunch Update Workbench: \(error.localizedDescription). Quit and open it again.") } + else { NSApp.terminate(nil) } + } } } func exportInventory() { @@ -517,6 +557,9 @@ struct UpdateWorkbenchApp: App { struct WorkbenchCommands: Commands { @ObservedObject var model: WorkbenchModel var body: some Commands { + CommandGroup(after: .appInfo) { + Button("Check for Updates…") { model.checkSelf(announce: true) }.disabled(model.checkingSelf) + } CommandGroup(after: .newItem) { Button("Check for Updates") { model.scan() }.keyboardShortcut("r", modifiers: .command).disabled(model.busy) Button("Update All…") { model.section = .updates; model.confirmUpdateAll = true } diff --git a/Sources/UpdateWorkbench/Core.swift b/Sources/UpdateWorkbench/Core.swift index f3b0d33..fb2798e 100644 --- a/Sources/UpdateWorkbench/Core.swift +++ b/Sources/UpdateWorkbench/Core.swift @@ -66,6 +66,14 @@ struct UpdateItem: Identifiable, Codable, Sendable, Hashable { } } + /// This entry is the running copy of Update Workbench. It is updated in place and relaunched, so the + /// usual "quit the app first" rule doesn't apply. + var isSelf: Bool { + guard let path else { return false } + return URL(fileURLWithPath: path).resolvingSymlinksInPath().standardizedFileURL.path + == Bundle.main.bundleURL.resolvingSymlinksInPath().standardizedFileURL.path + } + /// Sanitized notes for the available version, from the feed or the GitHub release body. var releaseNotes: String? { isOutdated ? (sparkleRelease?.notes ?? githubRelease?.notes) : nil } /// HTTPS notes page (Sparkle `releaseNotesLink`) that can be fetched on demand. @@ -308,12 +316,43 @@ actor Engine { } } else { items[index].detail = "No newer stable GitHub release found." } } + await describeSelf(&items, rules: rules) return items.sorted { if $0.isOutdated != $1.isOutdated { return $0.isOutdated } return $0.name.localizedStandardCompare($1.name) == .orderedAscending } } + /// Update Workbench's own entry. Direct installs come from its signed feed (checked above like any Sparkle app). + /// A copy installed with Homebrew is updated through its cask, but the scan doesn't refresh taps, so the + /// signed feed tells whether a newer version exists. + private func describeSelf(_ items: inout [UpdateItem], rules: UpdateRules) async { + guard let index = items.firstIndex(where: \.isSelf) else { return } + switch items[index].provider { + case .sparkle: + if items[index].isOutdated { + items[index].detail = "A new version of Update Workbench is available. The download must carry the release signature of Update Workbench's own update key; it replaces this copy and Update Workbench relaunches." + } else if !items[index].detail.hasPrefix("Feed check failed") { + items[index].detail = "Update Workbench checks its own signed releases with every check." + } + case .homebrewCask: + if !items[index].isOutdated, let feed = items[index].feedURL { + do { + if let release = try await SparkleBackend.check(feedURL: feed, installedVersion: items[index].installedVersion, + allowPrerelease: rules.allowsPrereleases(for: items[index].id)) { + items[index].latestVersion = release.version + items[index].sparkleRelease = release + items[index].isOutdated = true + } + } catch { diagnostics.append("Update Workbench: \(error.localizedDescription)") } + } + items[index].detail = items[index].isOutdated + ? "Installed with Homebrew, so Homebrew installs the new version (brew update, then brew upgrade). Update Workbench relaunches afterwards." + : "Installed with Homebrew from the kasakir-ai/tap tap." + default: break + } + } + /// Runs one source's checks six at a time. Each result carries the item index and either the /// check's value (nil when nothing newer was found) or the error text. private static func checkInBatches( @@ -337,14 +376,15 @@ actor Engine { func update(_ item: UpdateItem, options: InstallOptions = InstallOptions()) async throws -> UpdateOutcome { guard item.canUpdateDirectly else { throw UpdateError.unavailable("No verified direct update is available for \(item.name).") } - if let bundleID = item.bundleID, + let isSelf = item.isSelf + if !isSelf, let bundleID = item.bundleID, !NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).isEmpty { throw UpdateError.unavailable("Quit \(item.name) before updating it, then try again.") } var options = options options.appName = options.appName ?? item.name func direct(_ release: SparkleRelease, _ path: String) async throws -> UpdateOutcome { - let outcome = try await SparkleBackend.install(release: release, target: URL(fileURLWithPath: path), options: options) + let outcome = try await SparkleBackend.install(release: release, target: URL(fileURLWithPath: path), replacingRunningSelf: isSelf, options: options) return UpdateOutcome(message: outcome.message, installedVersion: outcome.installedVersion) } switch item.provider { @@ -353,7 +393,11 @@ actor Engine { throw UpdateError.unavailable("Homebrew or the package identifier is unavailable.") } let args = try Self.homebrewArguments(for: item) - return UpdateOutcome(message: try await execute(brewPath, args)) + // Update Workbench's own cask lives in a tap; refresh it so Homebrew knows the new version. + if isSelf, let refresh = try? await CommandRunner.run(brewPath, ["update"], timeout: 600), refresh.status != 0 { + diagnostics.append("brew update: \(refresh.errorOutput.prefix(500))") + } + return UpdateOutcome(message: try await execute(brewPath, args), installedVersion: isSelf ? item.latestVersion : nil) case .appStore: guard let masPath else { throw UpdateError.unavailable("mas isn't installed. Choose Homebrew → Install mas…, or update the app in the App Store.") } guard let token = item.token, AppStoreCLI.validID(token) else { throw UpdateError.unavailable("The App Store ID for this app is unknown. Check for updates again.") } diff --git a/Sources/UpdateWorkbench/DetailView.swift b/Sources/UpdateWorkbench/DetailView.swift index f55f8fc..628d284 100644 --- a/Sources/UpdateWorkbench/DetailView.swift +++ b/Sources/UpdateWorkbench/DetailView.swift @@ -62,7 +62,7 @@ struct ItemDetail: View { } private var whatsNewCard: some View { - Card(title: "What's new in \(item.latestVersion ?? "the update")", symbol: "sparkles", tint: Theme.pink) { + Card(title: "What's new in \(item.latestVersion ?? "the update")", symbol: "sparkles", tone: Pastel.rose) { WhatsNewContent(item: item) .frame(maxHeight: 260, alignment: .top) .clipped() @@ -92,14 +92,14 @@ struct ItemDetail: View { HStack(spacing: 14) { versionBlock("Installed", item.installedVersion, color: .primary) Image(systemName: "arrow.right").font(.title3.weight(.semibold)) - .foregroundStyle(item.isOutdated ? AnyShapeStyle(Theme.accentGradient) : AnyShapeStyle(.tertiary)) + .foregroundStyle(item.isOutdated ? AnyShapeStyle(Theme.inkGradient) : AnyShapeStyle(.tertiary)) .accessibilityHidden(true) versionBlock("Available", item.latestVersion ?? "Unknown", color: item.isOutdated ? Theme.accent : .secondary) Spacer(minLength: 0) } if let failure = model.failures[item.id] { Label { Text("Last update failed: \(failure)").fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "exclamationmark.triangle.fill") } - .font(.callout).foregroundStyle(.red) + .font(.callout).foregroundStyle(Pastel.coral.ink) } HStack(spacing: 8) { primaryAction @@ -114,18 +114,18 @@ struct ItemDetail: View { } .controlSize(.large) if let until = model.snoozed[item.id], until > Date().timeIntervalSince1970 { - Label("Snoozed until \(Date(timeIntervalSince1970: until).formatted(date: .abbreviated, time: .shortened))", systemImage: "moon.zzz.fill").font(.caption).foregroundStyle(.purple) + Label("Snoozed until \(Date(timeIntervalSince1970: until).formatted(date: .abbreviated, time: .shortened))", systemImage: "moon.zzz.fill").font(.caption).foregroundStyle(Pastel.lilac.ink) } if status == .heldBack { HStack(spacing: 8) { - Label("\(item.latestVersion ?? "This version") is a pre-release. Your rules hold back betas.", systemImage: "flask.fill").font(.callout).foregroundStyle(.orange) + Label("\(item.latestVersion ?? "This version") is a pre-release. Your rules hold back betas.", systemImage: "flask.fill").font(.callout).foregroundStyle(Pastel.butter.ink) Spacer(minLength: 0) Button("Allow Betas for This App") { model.setPrereleaseRule(.allow, for: item.id) }.controlSize(.small) } } if let approval = model.approvals.first(where: { $0.bundleID == item.bundleID }) { Label("You approved team \(approval.teamID) (\(approval.signerName)) for this app on \(approval.approvedAt.formatted(date: .abbreviated, time: .omitted)).", systemImage: "person.badge.shield.checkmark.fill") - .font(.caption).foregroundStyle(.orange) + .font(.caption).foregroundStyle(Pastel.peach.ink) } if item.provider == .appStore { appStoreHelp } if item.isOutdated && !item.canUpdateDirectly { @@ -149,7 +149,7 @@ struct ItemDetail: View { } else if let failure = model.failures[item.id], AppStoreCLI.classify(failure) == .needsAdministrator { VStack(alignment: .leading, spacing: 6) { Label("mas needs your administrator password to install App Store updates, which it can only ask for in Terminal.", systemImage: "lock.shield") - .font(.caption).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true) + .font(.caption).foregroundStyle(Pastel.peach.ink).fixedSize(horizontal: false, vertical: true) HStack { Button { model.finishInTerminal(item) } label: { Label("Finish in Terminal", systemImage: "terminal") } .help("Opens Terminal and runs mas update for this app; enter your password there") @@ -164,7 +164,7 @@ struct ItemDetail: View { @ViewBuilder private var primaryAction: some View { if item.canUpdateDirectly && item.isOutdated { - Button { model.pendingUpdate = item } label: { Label("Update to \(item.latestVersion ?? "Latest")", systemImage: "arrow.down.circle.fill") } + Button { model.pendingUpdate = item } label: { Label(item.isSelf ? "Update and Relaunch" : "Update to \(item.latestVersion ?? "Latest")", systemImage: "arrow.down.circle.fill") } .buttonStyle(.borderedProminent).disabled(model.busy) .help("Download and install the new version after confirmation") } else if let vendor = item.vendorUpdater { @@ -174,7 +174,7 @@ struct ItemDetail: View { Button { NSWorkspace.shared.open(URL(string: "macappstore://showUpdatesPage")!) } label: { Label("Open App Store Updates", systemImage: "bag.fill") } .buttonStyle(.borderedProminent) } else if model.status(item) == .upToDate { - Label("Up to date", systemImage: "checkmark.seal.fill").font(.callout.weight(.semibold)).foregroundStyle(.green) + Label("Up to date", systemImage: "checkmark.seal.fill").font(.callout.weight(.semibold)).foregroundStyle(Pastel.mint.ink) } } @@ -209,10 +209,10 @@ struct ItemDetail: View { } private var aboutCard: some View { - Card(title: "Update source", symbol: item.provider.symbol, tint: item.provider.tint) { + Card(title: "Update source", symbol: item.provider.symbol, tone: item.provider.tone) { Text(item.provider.explanation).font(.callout) if !item.detail.isEmpty { Text(item.detail).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } - if item.isPinned == true { Label("Pinned in Homebrew; excluded from upgrades until unpinned.", systemImage: "pin.fill").font(.callout).foregroundStyle(.orange) } + if item.isPinned == true { Label("Pinned in Homebrew; excluded from upgrades until unpinned.", systemImage: "pin.fill").font(.callout).foregroundStyle(Pastel.butter.ink) } if let repository = item.githubRepository { InfoRow(label: "GitHub", value: repository) } if let electron = item.electronUpdate { InfoRow(label: "Electron feed", value: electron.summary) } let links = linkList @@ -232,7 +232,7 @@ struct ItemDetail: View { } private func vendorCard(_ vendor: VendorUpdater) -> some View { - Card(title: "Vendor updater", symbol: "building.2.fill", tint: UpdateProvider.vendor.tint) { + Card(title: "Vendor updater", symbol: "building.2.fill", tone: UpdateProvider.vendor.tone) { Text(vendor.name).font(.callout.weight(.semibold)) Text(vendor.instructions).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) Text("Use the Open button above. Update Workbench only opens the vendor's own updater; it does not drive private vendor update protocols.").font(.caption).foregroundStyle(.secondary) @@ -240,7 +240,7 @@ struct ItemDetail: View { } private var suggestionsCard: some View { - Card(title: "Suggestions", symbol: "lightbulb.fill", tint: SidebarSection.suggestions.tint) { + Card(title: "Suggestions", symbol: "lightbulb.fill", tone: Pastel.peach) { ForEach(item.repositorySuggestions ?? [], id: \.self) { suggestion in HStack(alignment: .top, spacing: 10) { Image(systemName: UpdateProvider.github.symbol).foregroundStyle(UpdateProvider.github.tint).frame(width: 18) @@ -252,7 +252,7 @@ struct ItemDetail: View { if item.githubRepository != suggestion.repository { Button("Use…") { pendingRepository = suggestion.repository; confirmRepository = true }.disabled(model.busy) .help("Check this repository's releases for updates (asks first)") - } else { Pill(text: "In use", symbol: "checkmark", tint: .green) } + } else { Pill(text: "In use", symbol: "checkmark", tone: Pastel.mint) } } } ForEach(item.caskSuggestions ?? [], id: \.self) { suggestion in @@ -262,7 +262,7 @@ struct ItemDetail: View { HStack(spacing: 6) { Text("Homebrew cask \(suggestion.token)\(suggestion.version.map { " \($0)" } ?? "")").font(.callout.weight(.semibold)).textSelection(.enabled) Pill(text: "\(suggestion.confidence.rawValue) confidence", symbol: suggestion.confidence == .high ? "checkmark.seal.fill" : "questionmark.diamond.fill", - tint: suggestion.confidence == .high ? .green : .orange) + tone: suggestion.confidence == .high ? Pastel.mint : Pastel.butter) } Text(suggestion.evidence).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } @@ -276,7 +276,7 @@ struct ItemDetail: View { } private var detailsCard: some View { - Card(title: "Details", symbol: "info.circle.fill", tint: Theme.indigo) { + Card(title: "Details", symbol: "info.circle.fill", tone: Pastel.sky) { if let id = item.bundleID { InfoRow(label: "Bundle ID", value: id, monospaced: true) } if let path = item.path { InfoRow(label: "Location", value: abbreviatedPath(path)) } if let token = item.token { InfoRow(label: "Homebrew", value: token, monospaced: true) } @@ -286,7 +286,7 @@ struct ItemDetail: View { } private func securityCard(_ path: String) -> some View { - Card(title: "App security", symbol: "checkmark.shield.fill", tint: Theme.mint) { + Card(title: "App security", symbol: "checkmark.shield.fill", tone: Pastel.mint) { Text("Checks the installed copy's code signature and Gatekeeper assessment. Read-only.").font(.caption).foregroundStyle(.secondary) Button { inspectingSecurity = true @@ -346,16 +346,16 @@ struct ItemDetail: View { } .padding(.top, 8) } label: { - Label { Text("Custom update source").font(.headline) } icon: { Image(systemName: "slider.horizontal.3").foregroundStyle(Theme.violet) } + HStack(spacing: 10) { IconTile(symbol: "slider.horizontal.3", tone: Pastel.lilac, size: 26); Text("Custom update source").font(.headline) } } } } @ViewBuilder private var manageCard: some View { let homebrew = (item.provider == .homebrewCask || item.provider == .homebrewFormula) && item.token != nil - let trashable = !homebrew && item.path.map { !$0.hasPrefix("/System/") } == true + let trashable = !homebrew && !item.isSelf && item.path.map { !$0.hasPrefix("/System/") } == true if homebrew || trashable { - Card(title: "Manage", symbol: "wrench.and.screwdriver.fill", tint: .red) { + Card(title: "Manage", symbol: "wrench.and.screwdriver.fill", tone: Pastel.coral) { HStack(spacing: 8) { if homebrew { Button { pendingAction = .reinstall; confirmAction = true } label: { Label("Repair…", systemImage: "arrow.triangle.2.circlepath") } @@ -363,11 +363,11 @@ struct ItemDetail: View { if item.provider == .homebrewFormula && item.isPinned == true { Button { pendingAction = .unpin; confirmAction = true } label: { Label("Unpin…", systemImage: "pin.slash") } } - Button(role: .destructive) { pendingAction = .uninstall; confirmAction = true } label: { Label("Uninstall…", systemImage: "trash").foregroundStyle(.red) } - .tint(.red).help("Remove with Homebrew; user data is kept (asks first)") + Button(role: .destructive) { pendingAction = .uninstall; confirmAction = true } label: { Label("Uninstall…", systemImage: "trash").foregroundStyle(Pastel.coral.ink) } + .tint(Pastel.coral.ink).help("Remove with Homebrew; user data is kept (asks first)") } else { - Button(role: .destructive) { confirmTrash = true } label: { Label("Move to Trash…", systemImage: "trash").foregroundStyle(.red) } - .tint(.red).help("Move the app bundle to the Trash; it can be restored (asks first)") + Button(role: .destructive) { confirmTrash = true } label: { Label("Move to Trash…", systemImage: "trash").foregroundStyle(Pastel.coral.ink) } + .tint(Pastel.coral.ink).help("Move the app bundle to the Trash; it can be restored (asks first)") } } .buttonStyle(.bordered) diff --git a/Sources/UpdateWorkbench/FeatureViews.swift b/Sources/UpdateWorkbench/FeatureViews.swift index 746f197..2fe91af 100644 --- a/Sources/UpdateWorkbench/FeatureViews.swift +++ b/Sources/UpdateWorkbench/FeatureViews.swift @@ -14,7 +14,7 @@ struct ReleaseNotesView: View { Text(ReleaseNotes.inline(value)).font(level <= 2 ? .headline : .subheadline.weight(.semibold)).padding(.top, 2) case .bullet(let value): HStack(alignment: .firstTextBaseline, spacing: 8) { - Circle().fill(Theme.accentGradient).frame(width: 6, height: 6).offset(y: -2).accessibilityHidden(true) + Circle().fill(Theme.inkGradient).frame(width: 6, height: 6).offset(y: -2).accessibilityHidden(true) Text(ReleaseNotes.inline(value)).fixedSize(horizontal: false, vertical: true) } case .paragraph(let value): @@ -61,25 +61,25 @@ struct UpdateConfirmSheet: View { HStack(spacing: 14) { AppIconView(item: item, size: 54) VStack(alignment: .leading, spacing: 4) { - Text("Update \(item.name)").font(.title2.weight(.bold)).foregroundStyle(.white) + Text(item.isSelf ? "Update and relaunch" : "Update \(item.name)").font(.title2.weight(.bold)).foregroundStyle(Theme.heroText) HStack(spacing: 8) { - Text(item.installedVersion).foregroundStyle(.white.opacity(0.8)) - Image(systemName: "arrow.right").foregroundStyle(.white.opacity(0.8)) - Text(item.latestVersion ?? "Latest").foregroundStyle(.white) + Text(item.installedVersion).foregroundStyle(Theme.heroSecondary) + Image(systemName: "arrow.right").foregroundStyle(Theme.heroSecondary) + Text(item.latestVersion ?? "Latest").foregroundStyle(Theme.heroText) } .font(.system(.body, design: .monospaced).weight(.semibold)) } Spacer() - Pill(text: item.provider.shortName, symbol: item.provider.symbol, tint: .white.opacity(0.25), prominent: true) + SourceBadge(provider: item.provider) } .padding(18) .background(Theme.accentGradient) ScrollView { VStack(alignment: .leading, spacing: 14) { - Card(title: "What's new in \(item.latestVersion ?? "this version")", symbol: "sparkles", tint: Theme.pink) { + Card(title: "What's new in \(item.latestVersion ?? "this version")", symbol: "sparkles", tone: Pastel.rose) { WhatsNewContent(item: item) } - Card(title: "Before it's installed", symbol: "checkmark.shield.fill", tint: Theme.mint) { + Card(title: "Before it's installed", symbol: "checkmark.shield.fill", tone: Pastel.mint) { ForEach(SafetyChecklist.lines(for: item), id: \.self) { line in Label { Text(line).fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.mint) } .font(.callout) @@ -91,10 +91,10 @@ struct UpdateConfirmSheet: View { .frame(maxHeight: 420) Divider() HStack { - Label("Quit \(item.name) first.", systemImage: "info.circle").font(.caption).foregroundStyle(.secondary) + Label(item.isSelf ? "Update Workbench relaunches when it's done." : "Quit \(item.name) first.", systemImage: "info.circle").font(.caption).foregroundStyle(.secondary) Spacer() Button("Cancel", role: .cancel) { model.pendingUpdate = nil; dismiss() }.keyboardShortcut(.cancelAction) - Button { model.pendingUpdate = nil; dismiss(); model.update([item]) } label: { Label("Update to \(item.latestVersion ?? "Latest")", systemImage: "arrow.down.circle.fill") } + Button { model.pendingUpdate = nil; dismiss(); model.update([item]) } label: { Label(item.isSelf ? "Update and Relaunch" : "Update to \(item.latestVersion ?? "Latest")", systemImage: "arrow.down.circle.fill") } .buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).disabled(model.busy) } .padding(14) @@ -131,25 +131,25 @@ struct SignerApprovalSheet: View { var body: some View { VStack(spacing: 0) { HStack(spacing: 14) { - Image(systemName: "person.badge.shield.checkmark.fill").font(.system(size: 34, weight: .semibold)).foregroundStyle(.white) - .frame(width: 54, height: 54).background(Circle().fill(.white.opacity(0.18))) + Image(systemName: "person.badge.shield.checkmark.fill").font(.system(size: 28, weight: .semibold)).foregroundStyle(Pastel.peach.ink) + .frame(width: 54, height: 54).background(Circle().fill(Theme.frosted)) VStack(alignment: .leading, spacing: 4) { - Text("New developer signature").font(.title2.weight(.bold)).foregroundStyle(.white) + Text("New developer signature").font(.title2.weight(.bold)).foregroundStyle(Theme.heroText) Text("\(change.appName) \(change.version) is signed by a different Developer ID team than the copy you have installed.") - .font(.callout).foregroundStyle(.white.opacity(0.9)).fixedSize(horizontal: false, vertical: true) + .font(.callout).foregroundStyle(Theme.heroSecondary).fixedSize(horizontal: false, vertical: true) } Spacer(minLength: 0) } .padding(18) - .background(LinearGradient(colors: [Color(red: 0.95, green: 0.45, blue: 0.20), Theme.pink, Theme.violet], startPoint: .topLeading, endPoint: .bottomTrailing)) + .background(Theme.warningGradient) ScrollView { VStack(alignment: .leading, spacing: 14) { HStack(alignment: .top, spacing: 12) { SignerCard(title: "Installed", identity: change.installed, highlight: false) - Image(systemName: "arrow.right").font(.title3.weight(.bold)).foregroundStyle(.orange).padding(.top, 40).accessibilityHidden(true) + Image(systemName: "arrow.right").font(.title3.weight(.bold)).foregroundStyle(Pastel.peach.ink).padding(.top, 40).accessibilityHidden(true) SignerCard(title: "Update \(change.version)", identity: change.candidate, highlight: true) } - Card(title: "Checks", symbol: "checklist", tint: Theme.mint) { + Card(title: "Checks", symbol: "checklist", tone: Pastel.mint) { CheckLine(ok: true, text: "Code signature is valid (codesign --deep --strict).") CheckLine(ok: true, text: "Gatekeeper accepted it: \(change.candidate.gatekeeper ?? "accepted").") CheckLine(ok: true, text: "Bundle ID matches: \(change.bundleID).") @@ -174,7 +174,7 @@ struct SignerApprovalSheet: View { Spacer(minLength: 8) Button("Don't Install", role: .cancel) { model.declineSigner(change); dismiss() }.keyboardShortcut(.cancelAction) Button { model.approveSigner(change); dismiss() } label: { Label("Approve and Install", systemImage: "checkmark.shield.fill") } - .buttonStyle(.borderedProminent).tint(.orange).disabled(!confirmed) + .buttonStyle(.borderedProminent).tint(Pastel.peach.ink).disabled(!confirmed) } .padding(14) } @@ -190,7 +190,7 @@ struct SignerCard: View { VStack(alignment: .leading, spacing: 8) { Text(title.uppercased()).font(.caption2.weight(.semibold)).foregroundStyle(.secondary) Text(identity.signerName).font(.headline).lineLimit(2).textSelection(.enabled) - Pill(text: "Team \(identity.teamID)", symbol: highlight ? "exclamationmark.triangle.fill" : "checkmark.seal.fill", tint: highlight ? .orange : .green) + Pill(text: "Team \(identity.teamID)", symbol: highlight ? "exclamationmark.triangle.fill" : "checkmark.seal.fill", tone: highlight ? Pastel.peach : Pastel.mint) VStack(alignment: .leading, spacing: 4) { detail("Certificate", identity.certificateKind) if identity.authorities.count > 1 { detail("Issued by", identity.authorities.dropFirst().joined(separator: " → ")) } @@ -201,8 +201,8 @@ struct SignerCard: View { } .padding(12) .frame(maxWidth: .infinity, alignment: .leading) - .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill((highlight ? Color.orange : Color.green).opacity(0.08))) - .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder((highlight ? Color.orange : Color.green).opacity(0.35), lineWidth: 1)) + .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill((highlight ? Pastel.peach : Pastel.mint).fill.opacity(0.6))) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder((highlight ? Pastel.peach : Pastel.mint).stroke, lineWidth: 1)) } private func detail(_ label: String, _ value: String, monospaced: Bool = false) -> some View { VStack(alignment: .leading, spacing: 1) { @@ -218,7 +218,7 @@ struct CheckLine: View { let text: String var body: some View { Label { Text(text).fixedSize(horizontal: false, vertical: true) } icon: { - Image(systemName: ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(ok ? Theme.mint : .orange) + Image(systemName: ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(ok ? Pastel.mint.ink : Pastel.peach.ink) } .font(.callout) } @@ -233,10 +233,10 @@ struct LicenseSheet: View { var body: some View { VStack(alignment: .leading, spacing: 0) { HStack(spacing: 12) { - Image(systemName: "doc.text.fill").font(.title).foregroundStyle(.white) + Image(systemName: "doc.text.fill").font(.title).foregroundStyle(Theme.heroText) VStack(alignment: .leading, spacing: 2) { - Text("License agreement").font(.title2.weight(.bold)).foregroundStyle(.white) - Text("\(prompt.appName) \(prompt.version) asks you to accept these terms before its disk image can be opened.").font(.callout).foregroundStyle(.white.opacity(0.9)) + Text("License agreement").font(.title2.weight(.bold)).foregroundStyle(Theme.heroText) + Text("\(prompt.appName) \(prompt.version) asks you to accept these terms before its disk image can be opened.").font(.callout).foregroundStyle(Theme.heroSecondary) } } .padding(18).frame(maxWidth: .infinity, alignment: .leading).background(Theme.idleGradient) @@ -269,14 +269,15 @@ extension HistoryEntry.Result { case .restoreFailed: "exclamationmark.triangle.fill" } } - var tint: Color { + var tone: Tone { switch self { - case .installed: .green - case .failed: .red - case .restored: Theme.indigo - case .restoreFailed: .orange + case .installed: Pastel.mint + case .failed: Pastel.coral + case .restored: Pastel.sky + case .restoreFailed: Pastel.peach } } + var tint: Color { tone.ink } } struct HistoryListColumn: View { @@ -287,10 +288,10 @@ struct HistoryListColumn: View { SectionHeader(section: .history) if !model.history.isEmpty { HStack(spacing: 8) { - StatTile(value: model.history.filter { $0.result == .installed }.count, label: "Installed", symbol: "checkmark.circle.fill", tint: .green) - StatTile(value: model.history.filter { $0.result == .failed || $0.result == .restoreFailed }.count, label: "Failed", symbol: "xmark.octagon.fill", tint: .red) - StatTile(value: Set(model.history.map(\.appName)).count, label: "Apps", symbol: "square.grid.2x2.fill", tint: Theme.indigo) - StatTile(value: model.history.filter { $0.date > Date().addingTimeInterval(-7 * 86400) }.count, label: "Last 7 days", symbol: "calendar", tint: Theme.violet) + StatTile(value: model.history.filter { $0.result == .installed }.count, label: "Installed", symbol: "checkmark.circle.fill", tone: Pastel.mint) + StatTile(value: model.history.filter { $0.result == .failed || $0.result == .restoreFailed }.count, label: "Failed", symbol: "xmark.octagon.fill", tone: Pastel.coral) + StatTile(value: Set(model.history.map(\.appName)).count, label: "Apps", symbol: "square.grid.2x2.fill", tone: Pastel.sky) + StatTile(value: model.history.filter { $0.date > Date().addingTimeInterval(-7 * 86400) }.count, label: "Last 7 days", symbol: "calendar", tone: Pastel.lavender) } } } @@ -323,7 +324,7 @@ struct HistoryRow: View { VStack(alignment: .leading, spacing: 3) { Text(entry.appName).font(.headline).lineLimit(1) HStack(spacing: 6) { - Pill(text: entry.result.rawValue, symbol: entry.result.symbol, tint: entry.result.tint) + Pill(text: entry.result.rawValue, symbol: entry.result.symbol, tone: entry.result.tone) } } Spacer(minLength: 6) @@ -344,9 +345,7 @@ struct HistoryDetail: View { ScrollView { VStack(alignment: .leading, spacing: Theme.spacing) { HStack(spacing: 14) { - Image(systemName: entry.result.symbol).font(.system(size: 30, weight: .semibold)).foregroundStyle(.white) - .frame(width: 60, height: 60) - .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(LinearGradient(colors: [entry.result.tint, entry.result.tint.opacity(0.6)], startPoint: .topLeading, endPoint: .bottomTrailing))) + IconTile(symbol: entry.result.symbol, tone: entry.result.tone, size: 60) VStack(alignment: .leading, spacing: 4) { Text(entry.appName).font(.title.weight(.bold)) Text("\(entry.result.rawValue) · \(entry.date.formatted(date: .complete, time: .shortened))").foregroundStyle(.secondary) @@ -355,13 +354,13 @@ struct HistoryDetail: View { Card { HStack(spacing: 14) { version("From", entry.fromVersion, .primary) - Image(systemName: "arrow.right").font(.title3.weight(.semibold)).foregroundStyle(Theme.accentGradient) + Image(systemName: "arrow.right").font(.title3.weight(.semibold)).foregroundStyle(Theme.inkGradient) version("To", entry.toVersion, Theme.accent) Spacer() } Text(entry.message).font(.callout).foregroundStyle(.secondary).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) } - Card(title: "Details", symbol: "info.circle.fill", tint: Theme.indigo) { + Card(title: "Details", symbol: "info.circle.fill", tone: Pastel.sky) { InfoRow(label: "Source", value: entry.source) if let bundle = entry.bundleID { InfoRow(label: "Bundle ID", value: bundle, monospaced: true) } if let path = entry.appPath { InfoRow(label: "Location", value: abbreviatedPath(path)) } @@ -401,15 +400,15 @@ struct MenuBarPanel: View { VStack(alignment: .leading, spacing: 10) { HStack(alignment: .top) { VStack(alignment: .leading, spacing: 3) { - Text(HeroSummary.title(updates: updates.count, scanned: model.scanned)).font(.headline).foregroundStyle(.white) - Text(statusLine).font(.caption).foregroundStyle(.white.opacity(0.85)).lineLimit(2) + Text(HeroSummary.title(updates: updates.count, scanned: model.scanned)).font(.headline).foregroundStyle(Theme.heroText) + Text(statusLine).font(.caption).foregroundStyle(Theme.heroSecondary).lineLimit(2) } Spacer() - if model.busy { ProgressView().controlSize(.small).tint(.white) } - else { Image(systemName: updates.isEmpty ? "checkmark.seal.fill" : "arrow.down.circle.fill").font(.title2).foregroundStyle(.white.opacity(0.9)) } + if model.busy { ProgressView().controlSize(.small) } + else { Image(systemName: updates.isEmpty ? "checkmark.seal.fill" : "arrow.down.circle.fill").font(.title2).foregroundStyle(Theme.heroText.opacity(0.85)) } } .padding(12) - .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(!model.scanned ? Theme.idleGradient : (updates.isEmpty ? Theme.successGradient : Theme.accentGradient))) + .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(!model.scanned ? Theme.idleGradient : (updates.isEmpty ? Theme.successGradient : Theme.accentGradient))) if !updates.isEmpty { VStack(spacing: 2) { ForEach(updates.prefix(6)) { item in @@ -437,7 +436,7 @@ struct MenuBarPanel: View { HStack(spacing: 8) { Button { model.scan() } label: { Label("Check Now", systemImage: "arrow.clockwise") } .buttonStyle(.borderedProminent).disabled(model.busy) - Button { openMain() } label: { Label("Open Update Workbench", systemImage: "macwindow") } + Button { openMain() } label: { Label("Show Window", systemImage: "macwindow") } Spacer(minLength: 0) } .controlSize(.regular) diff --git a/Sources/UpdateWorkbench/MainViews.swift b/Sources/UpdateWorkbench/MainViews.swift index 2744e82..9f1449c 100644 --- a/Sources/UpdateWorkbench/MainViews.swift +++ b/Sources/UpdateWorkbench/MainViews.swift @@ -70,6 +70,12 @@ struct ContentView: View { .confirmationDialog("Install mas with Homebrew?", isPresented: $model.confirmInstallMas) { Button("Install mas") { model.showConsole = true; model.installMas() } } message: { Text("Runs brew install mas. mas is the open-source Mac App Store command-line tool; Update Workbench uses it to check App Store apps (mas outdated) and, when you choose Update, to install them (mas update). You stay signed in to the App Store app as usual.") } + .alert("Update Workbench", isPresented: $model.showSelfCheckResult) { + if let item = model.selfItem, item.isOutdated, item.canUpdateDirectly { + Button("Update and Relaunch…") { model.pendingUpdate = item } + Button("Later", role: .cancel) {} + } else { Button("OK", role: .cancel) {} } + } message: { Text(model.selfCheckMessage) } .confirmationDialog("Update \(model.directUpdates.count) apps and packages?", isPresented: $model.confirmUpdateAll) { Button("Update All") { model.update(model.updates) } } message: { Text("Downloads and installations run directly. Close apps before updating them. Items requiring administrator access may fail and report the reason in Console. Apps that update through their own updater are not included.") } @@ -91,7 +97,7 @@ struct SidebarView: View { } @ViewBuilder private func row(_ section: SidebarSection) -> some View { let count = model.count(section) - Label { Text(section.rawValue) } icon: { Image(systemName: section.symbol).foregroundStyle(section.tint) } + Label { Text(section.rawValue) } icon: { IconTile(symbol: section.symbol, tone: section.tone, size: 22) } .badge([.updates, .suggestions, .ignored, .permissions, .history].contains(section) ? count : 0) .help(section.subtitle) .tag(section) @@ -123,7 +129,7 @@ struct StatusFooter: View { HStack(spacing: 6) { if model.busy { ProgressView().controlSize(.small) } else if !model.scanned { Image(systemName: "clock").foregroundStyle(.secondary) } - else { Image(systemName: model.failures.isEmpty ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(model.failures.isEmpty ? .green : .orange) } + else { Image(systemName: model.failures.isEmpty ? "checkmark.circle.fill" : "exclamationmark.triangle.fill").foregroundStyle(model.failures.isEmpty ? Pastel.mint.ink : Pastel.peach.ink) } Text(model.busy ? model.operation : (model.scanned ? "Last check \(model.lastCheck!.formatted(.relative(presentation: .named)))" : "Not checked yet")) .font(.caption.weight(.medium)).lineLimit(2) } @@ -131,7 +137,8 @@ struct StatusFooter: View { } .padding(10) .frame(maxWidth: .infinity, alignment: .leading) - .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(.quaternary.opacity(0.5))) + .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(model.failures.isEmpty ? Pastel.lavender.fill : Pastel.peach.fill)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(model.failures.isEmpty ? Pastel.lavender.stroke : Pastel.peach.stroke, lineWidth: 0.5)) .accessibilityElement(children: .combine) } } @@ -144,6 +151,7 @@ struct ItemListColumn: View { if model.section == .updates { UpdatesHero() } else { SectionHeader(section: model.section) } } .padding([.horizontal, .top], 14) + if model.section == .updates { SelfUpdateBanner().padding(.horizontal, 14).padding(.top, 10) } if !model.items.isEmpty { FilterBar().padding(.horizontal, 14).padding(.vertical, 10) Divider() @@ -171,13 +179,15 @@ struct UpdatesHero: View { HStack(alignment: .top) { VStack(alignment: .leading, spacing: 4) { Text(HeroSummary.title(updates: count, scanned: model.scanned)) - .font(.title2.weight(.bold)).foregroundStyle(.white) + .font(.title2.weight(.bold)).foregroundStyle(Theme.heroText) Text(model.busy ? model.operation : HeroSummary.subtitle(updates: count, direct: direct, scanned: model.scanned, total: model.items.count)) - .font(.callout).foregroundStyle(.white.opacity(0.85)).lineLimit(3) + .font(.callout).foregroundStyle(Theme.heroSecondary).lineLimit(3) } Spacer(minLength: 8) Image(systemName: !model.scanned ? "sparkle.magnifyingglass" : (count == 0 ? "checkmark.seal.fill" : "arrow.down.circle.fill")) - .font(.system(size: 34, weight: .semibold)).foregroundStyle(.white.opacity(0.9)) + .font(.system(size: 26, weight: .semibold)).foregroundStyle(Theme.heroText.opacity(0.85)) + .frame(width: 52, height: 52) + .background(Circle().fill(Theme.frosted)) .accessibilityHidden(true) } HStack(spacing: 8) { @@ -192,23 +202,20 @@ struct UpdatesHero: View { .buttonStyle(HeroButtonStyle()).disabled(model.busy) .help("Check for updates (⌘R)") } - if model.busy { ProgressView().controlSize(.small).tint(.white).padding(.leading, 4) } + if model.busy { ProgressView().controlSize(.small).padding(.leading, 4) } } } .padding(16) .frame(maxWidth: .infinity, alignment: .leading) - .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(!model.scanned ? Theme.idleGradient : (count == 0 ? Theme.successGradient : Theme.accentGradient))) - .overlay(alignment: .topTrailing) { - Circle().fill(.white.opacity(0.08)).frame(width: 120, height: 120).offset(x: 40, y: -50).allowsHitTesting(false) - } - .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) - .shadow(color: Theme.violet.opacity(0.25), radius: 10, y: 4) + .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(!model.scanned ? Theme.idleGradient : (count == 0 ? Theme.successGradient : Theme.accentGradient))) + .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Theme.heroText.opacity(0.08), lineWidth: 0.5)) if model.scanned { HStack(spacing: 8) { - StatTile(value: count, label: "Updates", symbol: "arrow.down.circle.fill", tint: Theme.indigo) - StatTile(value: direct, label: "Install here", symbol: "bolt.fill", tint: Theme.mint) - StatTile(value: model.items.count, label: "Installed", symbol: "square.grid.2x2.fill", tint: Theme.violet) - StatTile(value: model.suggestions.count, label: "Suggestions", symbol: "lightbulb.fill", tint: SidebarSection.suggestions.tint) + StatTile(value: count, label: "Updates", symbol: "arrow.down.circle.fill", tone: Pastel.lavender) + StatTile(value: direct, label: "Install here", symbol: "bolt.fill", tone: Pastel.mint) + StatTile(value: model.items.count, label: "Installed", symbol: "square.grid.2x2.fill", tone: Pastel.sky) + StatTile(value: model.suggestions.count, label: "Suggestions", symbol: "lightbulb.fill", tone: Pastel.peach) } } } @@ -221,10 +228,7 @@ struct SectionHeader: View { var body: some View { VStack(alignment: .leading, spacing: 10) { HStack(alignment: .center, spacing: 12) { - Image(systemName: section.symbol).font(.title2).foregroundStyle(.white) - .frame(width: 40, height: 40) - .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(LinearGradient(colors: [section.tint, section.tint.opacity(0.6)], startPoint: .topLeading, endPoint: .bottomTrailing))) - .accessibilityHidden(true) + IconTile(symbol: section.symbol, tone: section.tone, size: 42) VStack(alignment: .leading, spacing: 2) { Text(section.rawValue).font(.title3.weight(.semibold)) Text(section.subtitle).font(.callout).foregroundStyle(.secondary) @@ -282,7 +286,7 @@ struct ItemRow: View { SourceBadge(provider: item.provider) if model.section == .suggestions { let count = (item.repositorySuggestions ?? []).count + (item.caskSuggestions ?? []).count - Pill(text: count == 1 ? "1 suggestion" : "\(count) suggestions", symbol: "lightbulb.fill", tint: SidebarSection.suggestions.tint) + Pill(text: count == 1 ? "1 suggestion" : "\(count) suggestions", symbol: "lightbulb.fill", tone: Pastel.peach) } else if !(model.section == .updates && status == .ready) && status != .unknown { StatusBadge(status: status) } } } @@ -291,18 +295,78 @@ struct ItemRow: View { VersionColumn(item: item) if model.section == .updates && item.canUpdateDirectly { Button("Update") { model.pendingUpdate = item } - .buttonStyle(.borderedProminent).controlSize(.small) + .buttonStyle(PastelButtonStyle(tone: Pastel.lavender)) .disabled(model.busy) .help("Update \(item.name) to \(item.latestVersion ?? "the latest version")") } } .padding(.vertical, 5) .contentShape(Rectangle()) + .contextMenu { ItemActions(item: item) } .accessibilityElement(children: .combine) .accessibilityLabel("\(item.name), \(item.provider.rawValue), \(status.rawValue), installed \(item.installedVersion)\(item.isOutdated ? ", available \(item.latestVersion ?? "")" : "")") } } +/// Right-click actions for a list row: the same choices as the detail pane, one click away. +struct ItemActions: View { + let item: UpdateItem + @EnvironmentObject var model: WorkbenchModel + var body: some View { + if item.canUpdateDirectly { + Button(item.isSelf ? "Update and Relaunch…" : "Update to \(item.latestVersion ?? "Latest")…") { model.pendingUpdate = item }.disabled(model.busy) + Divider() + } + if let path = item.path { + Button("Open \(item.name)") { NSWorkspace.shared.open(URL(fileURLWithPath: path)) } + Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) } + Divider() + } + if item.isOutdated, item.latestVersion != nil { + Button(model.skipped[item.id] == item.latestVersion ? "Stop Skipping This Version" : "Skip This Version") { model.skip(item) } + } + if item.isOutdated { + Button("Snooze for 2 Days") { model.snooze(item, days: 2) } + if model.snoozed[item.id] != nil { Button("Clear Snooze") { model.snooze(item, days: 0) } } + } + Button(model.ignored.contains(item.id) ? "Stop Ignoring This App" : "Ignore This App") { model.ignore(item) } + } +} + +/// Update Workbench's own update: offered above the list, and a reminder to relaunch once it's installed. +struct SelfUpdateBanner: View { + @EnvironmentObject var model: WorkbenchModel + var body: some View { + if model.relaunchNeeded { + banner(symbol: "checkmark.seal.fill", tone: Pastel.mint, title: "Update Workbench was updated", + detail: "Relaunch to start using the new version.") { + Button("Relaunch") { model.relaunch() }.buttonStyle(.borderedProminent).controlSize(.small) + } + } else if let item = model.selfItem, item.isOutdated, model.decision(item) == .show { + banner(symbol: "sparkles", tone: Pastel.lilac, title: "Update Workbench \(item.latestVersion ?? "") is available", + detail: item.provider == .homebrewCask ? "Installs with Homebrew, then relaunches." : "A signed release from the developer. It installs, then relaunches.") { + Button("Update and Relaunch…") { model.pendingUpdate = item }.buttonStyle(.borderedProminent).controlSize(.small) + .disabled(model.busy || !item.canUpdateDirectly) + } + } + } + private func banner(symbol: String, tone: Tone, title: String, detail: String, @ViewBuilder actions: () -> Actions) -> some View { + HStack(spacing: 12) { + IconTile(symbol: symbol, tone: tone, size: 34) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.callout.weight(.semibold)) + Text(detail).font(.caption).foregroundStyle(.secondary).lineLimit(2) + } + Spacer(minLength: 8) + actions() + } + .padding(10) + .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(tone.fill.opacity(0.7))) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(tone.stroke, lineWidth: 0.5)) + .accessibilityElement(children: .contain) + } +} + struct VersionColumn: View { let item: UpdateItem var body: some View { @@ -356,7 +420,7 @@ struct EmptyStateView: View { switch model.section { case .updates: ContentUnavailableView { - Label("You're all set", systemImage: "checkmark.seal.fill").foregroundStyle(.green) + Label("You're all set", systemImage: "checkmark.seal.fill").foregroundStyle(Pastel.mint.ink) } description: { Text("Every app and package with a known update source is up to date.") } actions: { Button("Check Again") { model.scan() }.disabled(model.busy) } case .suggestions: @@ -381,7 +445,7 @@ struct ConsolePanel: View { VStack(spacing: 0) { Divider() HStack { - Label("Console", systemImage: "terminal.fill").font(.caption.weight(.semibold)).foregroundStyle(Theme.mint) + Label("Console", systemImage: "terminal.fill").font(.caption.weight(.semibold)).foregroundStyle(Pastel.mint.ink) Spacer() Button("Copy") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(model.log, forType: .string) } Button("Clear") { model.log = "Console cleared." } @@ -399,6 +463,6 @@ struct ConsolePanel: View { } } .frame(height: 190) - .background(.black.opacity(0.25)) + .background(Color.adaptive(light: .hex(0xF4F2FA), dark: .hex(0x000000, alpha: 0.25))) } } diff --git a/Sources/UpdateWorkbench/Maintenance.swift b/Sources/UpdateWorkbench/Maintenance.swift index 9377a7e..2e2d9d1 100644 --- a/Sources/UpdateWorkbench/Maintenance.swift +++ b/Sources/UpdateWorkbench/Maintenance.swift @@ -211,56 +211,31 @@ enum UpdateNotificationPolicy { } } -/// Where Update Workbench looks for its own releases. Disabled by default; there is no published feed. -enum SelfUpdateFeed: Equatable, Sendable { - case disabled - case github(String) - case appcast(URL) - - static let defaultsKey = "selfUpdateFeed" +/// Update Workbench's own releases. Every GitHub release carries `appcast.xml`, a Sparkle feed whose archive is +/// signed with the release key; build.sh writes the feed address (SUFeedURL) and the key's public half +/// (SUPublicEDKey) into Info.plist. The app has no Developer ID team, so that key is what proves an update is genuine. +enum SelfUpdate { + static let caskToken = "update-workbench" + static let caskrooms = ["/opt/homebrew/Caskroom", "/usr/local/Caskroom"] - static func parse(_ raw: String) throws -> SelfUpdateFeed { - let value = raw.trimmingCharacters(in: .whitespacesAndNewlines) - if value.isEmpty { return .disabled } - if value.lowercased().hasPrefix("github:") { - let repository = String(value.dropFirst("github:".count)) - guard GitHubBackend.validRepository(repository) else { throw UpdateError.unavailable("Use github:owner/repository.") } - return .github(repository) - } - guard let url = URL(string: value), HTTPFetcher.isSafeHTTPS(url) else { - throw UpdateError.unavailable("Enter github:owner/repository, a GitHub repository URL, or an HTTPS appcast URL.") - } - if url.host?.lowercased() == "github.com" { - let parts = url.path.split(separator: "/") - guard parts.count == 2, GitHubBackend.validRepository("\(parts[0])/\(parts[1])") else { - throw UpdateError.unavailable("Use the repository URL, for example https://github.com/owner/repository.") - } - return .github("\(parts[0])/\(parts[1])") - } - return .appcast(url) + static var feedURL: URL? { + (Bundle.main.object(forInfoDictionaryKey: "SUFeedURL") as? String).flatMap(URL.init(string:)).flatMap { HTTPFetcher.isSafeHTTPS($0) ? $0 : nil } } - var description: String { - switch self { - case .disabled: return "Disabled" - case .github(let repository): return "GitHub Releases: \(repository)" - case .appcast(let url): return "Appcast: \(url.absoluteString)" - } + /// Whether Homebrew installed this copy (the cask has a Caskroom folder). + static func installedWithHomebrew(exists: (String) -> Bool = { FileManager.default.fileExists(atPath: $0) }) -> Bool { + caskrooms.contains { exists("\($0)/\(caskToken)") } } -} -enum SelfUpdate { - /// Checks the configured feed; returns a release only when a single verifiable payload exists. - static func check(_ feed: SelfUpdateFeed, installedVersion: String) async throws -> SparkleRelease? { - switch feed { - case .disabled: throw UpdateError.unavailable("Self-update is disabled. Configure a release feed first.") - case .appcast(let url): return try await SparkleBackend.check(feedURL: url, installedVersion: installedVersion) - case .github(let repository): - guard let release = try await GitHubBackend.check(repository: repository, installedVersion: installedVersion) else { return nil } - guard let download = release.downloadURL else { - throw UpdateError.unavailable("Version \(release.version) is available, but no single native macOS ZIP/DMG was found: \(release.releasePageURL.absoluteString)") - } - return SparkleRelease(version: release.version, downloadURL: download, releaseNotesURL: release.releasePageURL) - } + /// The running app as a list entry, for "Check for Updates…" before any scan. The version is read from disk, + /// so an update installed but not yet relaunched counts as installed. + static func currentItem(bundle: URL = Bundle.main.bundleURL, homebrew: Bool = installedWithHomebrew()) -> UpdateItem { + let info = AppBundleInfo.read(bundle) + let version = info["CFBundleShortVersionString"] as? String ?? AppIdentity.version + return UpdateItem(id: bundle.resolvingSymlinksInPath().path, name: info["CFBundleDisplayName"] as? String ?? "Update Workbench", + bundleID: info["CFBundleIdentifier"] as? String, path: bundle.path, installedVersion: version, + provider: homebrew ? .homebrewCask : .sparkle, token: homebrew ? caskToken : nil, feedURL: feedURL, + detail: homebrew ? "Installed with Homebrew from the kasakir-ai/tap tap." : "Update Workbench checks its own signed releases.", + requiresSparkleSignature: info["SUPublicEDKey"] is String) } } diff --git a/Sources/UpdateWorkbench/SettingsViews.swift b/Sources/UpdateWorkbench/SettingsViews.swift index 72c02e8..49d340c 100644 --- a/Sources/UpdateWorkbench/SettingsViews.swift +++ b/Sources/UpdateWorkbench/SettingsViews.swift @@ -32,7 +32,7 @@ struct GeneralSettingsView: View { } header: { Text("Background checks") } footer: { VStack(alignment: .leading, spacing: 4) { if let next = model.schedule.nextCheck(after: model.lastScheduledCheck) { - Label("Next check \(next <= Date() ? "within a few minutes" : next.formatted(date: .abbreviated, time: .shortened))", systemImage: "clock").foregroundStyle(Theme.accent) + Label("Next check \(next <= Date() ? "within a few minutes" : next.formatted(date: .abbreviated, time: .shortened))", systemImage: "clock").foregroundStyle(Pastel.lavender.ink) } Text("Checks only look for updates and run while Update Workbench is open (it keeps running in the menu bar). Nothing is installed automatically: every update waits for your confirmation.") } @@ -114,13 +114,13 @@ struct RuleRow: View { VStack(alignment: .leading, spacing: 4) { Text(model.ruleName(id)).font(.callout.weight(.semibold)).lineLimit(1) HStack(spacing: 6) { - if model.ignored.contains(id) { Pill(text: "Ignored", symbol: "eye.slash.fill", tint: .gray) } - if let version = model.skipped[id] { Pill(text: "Skipping \(version)", symbol: "forward.end.fill", tint: Theme.indigo) } + if model.ignored.contains(id) { Pill(text: "Ignored", symbol: "eye.slash.fill", tone: Pastel.slate) } + if let version = model.skipped[id] { Pill(text: "Skipping \(version)", symbol: "forward.end.fill", tone: Pastel.sky) } if let rule = model.prereleaseRules[id], rule != .followGlobal { - Pill(text: rule == .allow ? "Betas allowed" : "Betas held", symbol: "flask.fill", tint: rule == .allow ? Theme.mint : .orange) + Pill(text: rule == .allow ? "Betas allowed" : "Betas held", symbol: "flask.fill", tone: rule == .allow ? Pastel.mint : Pastel.butter) } if let until = model.snoozed[id], until > Date().timeIntervalSince1970 { - Pill(text: "Snoozed to \(Date(timeIntervalSince1970: until).formatted(date: .abbreviated, time: .omitted))", symbol: "moon.zzz.fill", tint: .purple) + Pill(text: "Snoozed to \(Date(timeIntervalSince1970: until).formatted(date: .abbreviated, time: .omitted))", symbol: "moon.zzz.fill", tone: Pastel.lilac) } } } @@ -152,7 +152,7 @@ struct TrustSettingsView: View { } ForEach(model.approvals) { approval in HStack(alignment: .top, spacing: 10) { - Image(systemName: "person.badge.shield.checkmark.fill").font(.title3).foregroundStyle(.orange).frame(width: 26) + IconTile(symbol: "person.badge.shield.checkmark.fill", tone: Pastel.peach, size: 28) VStack(alignment: .leading, spacing: 3) { Text(approval.appName).font(.callout.weight(.semibold)) Text("\(approval.previousSignerName) (\(approval.previousTeamID)) → \(approval.signerName) (\(approval.teamID))").font(.caption).textSelection(.enabled) @@ -271,7 +271,7 @@ struct ProxySettingsView: View { } Section { HStack { - if !status.isEmpty { Label(status, systemImage: status.hasPrefix("Saved") ? "checkmark.circle.fill" : "exclamationmark.circle.fill").font(.callout).foregroundStyle(status.hasPrefix("Saved") ? .green : .orange) } + if !status.isEmpty { Label(status, systemImage: status.hasPrefix("Saved") ? "checkmark.circle.fill" : "exclamationmark.circle.fill").font(.callout).foregroundStyle(status.hasPrefix("Saved") ? Pastel.mint.ink : Pastel.peach.ink) } Spacer() Button("Remove Saved Password", role: .destructive) { removePassword() }.disabled(!passwordStored) Button("Save") { save() }.keyboardShortcut(.defaultAction) @@ -304,41 +304,51 @@ struct ProxySettingsView: View { struct SelfUpdateSettingsView: View { @EnvironmentObject var model: WorkbenchModel - @State private var feed = UserDefaults.standard.string(forKey: SelfUpdateFeed.defaultsKey) ?? "" - @State private var feedStatus = "" - @State private var confirmInstall = false var body: some View { + let homebrew = model.installedWithHomebrew Form { Section { LabeledContent("Installed version") { Text(model.appVersion).font(.system(.body, design: .monospaced)) } - TextField("Release feed", text: $feed, prompt: Text("github:owner/repo or appcast URL")) - HStack { - if !feedStatus.isEmpty { Text(feedStatus).font(.caption).foregroundStyle(.secondary) } - Spacer() - Button("Save Feed") { - do { - let parsed = try SelfUpdateFeed.parse(feed) - UserDefaults.standard.set(feed.trimmingCharacters(in: .whitespacesAndNewlines), forKey: SelfUpdateFeed.defaultsKey) - feedStatus = "Saved: \(parsed.description)" - } catch { feedStatus = error.localizedDescription } - } - Button("Check Now") { model.checkSelfUpdate() }.disabled(model.busy) + LabeledContent("Installed with") { + Label(homebrew ? "Homebrew" : "Direct download", systemImage: homebrew ? "mug.fill" : "arrow.down.app.fill") + .foregroundStyle(homebrew ? UpdateProvider.homebrewCask.tint : Theme.accent) + } + LabeledContent("New versions come from") { + Text(homebrew ? "brew upgrade --cask update-workbench" : "Signed GitHub releases").foregroundStyle(.secondary) + } + HStack(spacing: 8) { + if model.checkingSelf { ProgressView().controlSize(.small) } + Text(model.selfCheckMessage.isEmpty ? "Every check also looks for a new Update Workbench." : model.selfCheckMessage) + .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 8) + Button("Check Now") { model.checkSelf() }.disabled(model.checkingSelf) } - } header: { Text("Update Workbench updates") } footer: { - Text("Off by default: this build has no published releases. A new copy must have the same bundle ID, be signed by the same Developer ID team, pass Gatekeeper and be newer. Locally signed development builds can't update themselves.").foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).multilineTextAlignment(.leading) + } header: { Text("Update Workbench") } footer: { + Text(homebrew + ? "Homebrew installed this copy, so Homebrew installs its updates too. Update Workbench refreshes the kasakir-ai/tap tap first, then relaunches." + : "Each release is signed with Update Workbench's own release key. A download that isn't signed with it, or that has a different bundle ID or an older version, is never installed.") + .foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).multilineTextAlignment(.leading) } - if !model.selfUpdateMessage.isEmpty || model.selfUpdateRelease != nil || model.selfUpdateInstalled { - Section("Status") { - if !model.selfUpdateMessage.isEmpty { Text(model.selfUpdateMessage).font(.callout).textSelection(.enabled) } - if let release = model.selfUpdateRelease { Button("Install \(release.version)…") { confirmInstall = true }.buttonStyle(.borderedProminent).disabled(model.busy) } - if model.selfUpdateInstalled { Button("Relaunch Update Workbench") { model.relaunch() } } + if model.relaunchNeeded { + Section { + HStack { + Label("The new version is installed. Relaunch to start using it.", systemImage: "checkmark.seal.fill").foregroundStyle(Pastel.mint.ink) + Spacer() + Button("Relaunch Now") { model.relaunch() }.buttonStyle(.borderedProminent) + } + } + } else if let item = model.selfItem, item.isOutdated { + Section { + HStack { + Label("Update Workbench \(item.latestVersion ?? "") is available.", systemImage: "sparkles").foregroundStyle(Theme.accent) + Spacer() + Button("Update and Relaunch…") { model.pendingUpdate = item }.buttonStyle(.borderedProminent) + .disabled(model.busy || !item.canUpdateDirectly) + } } } } .formStyle(.grouped) - .confirmationDialog("Install Update Workbench \(model.selfUpdateRelease?.version ?? "")?", isPresented: $confirmInstall) { - Button("Install") { model.installSelfUpdate() } - } message: { Text("The new version replaces this copy after it passes the checks; the old copy is deleted. Relaunch afterwards to use the new version.") } } } @@ -378,7 +388,7 @@ struct PermissionRow: View { VStack(alignment: .leading, spacing: 4) { HStack(spacing: 8) { Text(check.title.replacingOccurrences(of: NSHomeDirectory() + "/", with: "~/")).font(.headline) - Pill(text: check.state.rawValue, symbol: check.state.symbol, tint: check.state.tint) + Pill(text: check.state.rawValue, symbol: check.state.symbol, tone: check.state.tone) } Text(check.detail).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) if let url = check.settingsURL { @@ -390,8 +400,8 @@ struct PermissionRow: View { Spacer(minLength: 0) } .padding(12) - .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(.background.secondary)) - .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(check.state == .denied ? Color.orange.opacity(0.5) : Color.secondary.opacity(0.15), lineWidth: check.state == .denied ? 1 : 0.5)) + .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(check.state == .denied ? AnyShapeStyle(Pastel.peach.fill.opacity(0.55)) : AnyShapeStyle(.background.secondary))) + .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(check.state == .denied ? Pastel.peach.stroke : Color.secondary.opacity(0.15), lineWidth: check.state == .denied ? 1 : 0.5)) .accessibilityElement(children: .contain) } } @@ -400,14 +410,14 @@ struct PermissionsHelpView: View { var body: some View { ScrollView { VStack(alignment: .leading, spacing: Theme.spacing) { - Label("Why these permissions matter", systemImage: "lock.shield.fill").font(.title2.weight(.bold)).foregroundStyle(Theme.mint) - Card(title: "App Management", symbol: "app.badge.checkmark", tint: Theme.indigo) { + Label("Why these permissions matter", systemImage: "lock.shield.fill").font(.title2.weight(.bold)).foregroundStyle(Pastel.mint.ink) + Card(title: "App Management", symbol: "app.badge.checkmark", tone: Pastel.lavender) { Text("macOS may block replacing apps until you allow Update Workbench under Privacy & Security → App Management. If an update fails with “Operation not permitted”, allow it there and try again.").font(.callout).fixedSize(horizontal: false, vertical: true) } - Card(title: "Full Disk Access", symbol: "externaldrive.fill", tint: Theme.violet) { + Card(title: "Full Disk Access", symbol: "externaldrive.fill", tone: Pastel.lilac) { Text("Not required for normal checks. It only helps when apps live in protected folders.").font(.callout).fixedSize(horizontal: false, vertical: true) } - Card(title: "Notifications", symbol: "bell.badge.fill", tint: Theme.pink) { + Card(title: "Notifications", symbol: "bell.badge.fill", tone: Pastel.rose) { Text("Optional. Turn them on in Settings → General to hear about new updates and results.").font(.callout).fixedSize(horizontal: false, vertical: true) } Text("Update Workbench never asks for your password and never changes these settings for you.").font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).multilineTextAlignment(.leading) diff --git a/Sources/UpdateWorkbench/SnapshotHarness.swift b/Sources/UpdateWorkbench/SnapshotHarness.swift index 2c5a6e4..71b0ef6 100644 --- a/Sources/UpdateWorkbench/SnapshotHarness.swift +++ b/Sources/UpdateWorkbench/SnapshotHarness.swift @@ -11,7 +11,7 @@ enum SnapshotHarness { "customRoots": ["/Volumes/Apps"], "interval": 14400.0, "ignored": [String](), "skipped": [String: String](), "snoozed": [String: Double](), "notificationsEnabled": true, AppearanceMode.defaultsKey: AppearanceMode.dark.rawValue, CheckSchedule.defaultsKey: CheckSchedule.daily.rawValue, - SelfUpdateFeed.defaultsKey: "", ProxySettings.defaultsKey: (try? JSONEncoder().encode(ProxySettings())) ?? Data(), + ProxySettings.defaultsKey: (try? JSONEncoder().encode(ProxySettings())) ?? Data(), ] UserDefaults.standard.setVolatileDomain(defaults, forName: UserDefaults.argumentDomain) let app = NSApplication.shared @@ -27,7 +27,7 @@ enum SnapshotHarness { let view = ContentView().environmentObject(model).tint(Theme.accent) if let path = render(view, size: CGSize(width: 1280, height: 800), dark: dark, name: "main-\(scenario.rawValue)-\(suffix)", folder: folder) { written.append(path) } } - let model = makeModel(.updates) + let model = makeModel(.selfUpdate) let tabs: [(String, AnyView)] = [ ("general", AnyView(GeneralSettingsView())), ("rules", AnyView(RulesSettingsView())), ("trust", AnyView(TrustSettingsView())), ("appearance", AnyView(AppearanceSettingsView())), ("network", AnyView(ProxySettingsView())), ("updates", AnyView(SelfUpdateSettingsView())), @@ -41,6 +41,7 @@ enum SnapshotHarness { let sheets: [(String, CGSize, AnyView)] = [ ("sheet-signer-approval", CGSize(width: 660, height: 790), AnyView(SignerApprovalSheet(change: FakeData.signerChange))), ("sheet-update-notes", CGSize(width: 580, height: 560), AnyView(UpdateConfirmSheet(item: aurora))), + ("sheet-self-update", CGSize(width: 580, height: 500), AnyView(UpdateConfirmSheet(item: FakeData.selfItem))), ("sheet-license", CGSize(width: 560, height: 480), AnyView(LicenseSheet(prompt: FakeData.license))), ("menubar-panel", CGSize(width: 340, height: 440), AnyView(MenuBarPanel())), ] @@ -68,6 +69,7 @@ enum SnapshotHarness { case console case permissions case history + case selfUpdate = "self-update" } static func makeModel(_ scenario: Scenario) -> WorkbenchModel { @@ -105,6 +107,7 @@ enum SnapshotHarness { model.log = "Ready. Check for updates to scan installed applications.\n[10:41:02] Checking installed apps and update sources…\n[10:41:09] Found 14 apps and packages; 7 available updates.\n[10:42:15] Updating PixelForge…\n[10:42:16] PixelForge: Quit PixelForge before updating it." case .permissions: model.section = .permissions case .history: model.section = .history; model.selectedHistory = model.history.first?.id + case .selfUpdate: model.section = .updates; model.items.append(FakeData.selfItem); model.selected = "aurora" default: break } return model @@ -192,6 +195,15 @@ enum FakeData { ] } + /// Update Workbench itself with a newer signed release, so the self-update banner and sheet render. + static var selfItem: UpdateItem { + var release = SparkleRelease(version: "0.5.1", downloadURL: URL(string: "https://github.com/Kasakir-AI/UpdateWorkbench/releases/download/v0.5.1/UpdateWorkbench-0.5.1.zip")!, releaseNotesURL: nil, signature: "c2lnbmF0dXJl") + release.notes = "- Softer colors in the update list\n- Fixes for the menu bar panel" + return UpdateItem(id: Bundle.main.bundleURL.resolvingSymlinksInPath().path, name: "Update Workbench", bundleID: "local.updateworkbench.app", path: Bundle.main.bundlePath, + installedVersion: AppIdentity.version, latestVersion: "0.5.1", provider: .sparkle, feedURL: URL(string: "https://github.com/Kasakir-AI/UpdateWorkbench/releases/latest/download/appcast.xml"), + isOutdated: true, detail: "A new version of Update Workbench is available.", sparkleRelease: release, requiresSparkleSignature: true) + } + static var approvals: [TrustedSignerApproval] { [TrustedSignerApproval(bundleID: "com.example.tidy", appName: "Tidy Terminal", teamID: "TIDYNEW001", signerName: "Tidy Software GmbH", previousTeamID: "TIDYOLD999", previousSignerName: "Example Developer", certificateSHA256: "5C1E 9A04 77B2 0D6F", diff --git a/Sources/UpdateWorkbench/SparkleBackend.swift b/Sources/UpdateWorkbench/SparkleBackend.swift index e39338d..7cbe336 100644 --- a/Sources/UpdateWorkbench/SparkleBackend.swift +++ b/Sources/UpdateWorkbench/SparkleBackend.swift @@ -140,8 +140,11 @@ enum SparkleBackend { try requireReplaceable(original) guard ["zip", "dmg"].contains(fileExtension) else { throw Failure(message: "Direct installation supports complete ZIP or DMG app bundles.") } if let sha512 = release.sha512 { try verifySHA512(payload, expected: sha512) } + // Set only when the archive passed the installed app's own Sparkle Ed25519 key. + var edKey: String? if let publicKey = AppBundleInfo.read(original)["SUPublicEDKey"] as? String { try verifyArchiveSignature(payload, signature: release.signature, publicKey: publicKey) + edKey = publicKey } let fm = FileManager.default let work = fm.temporaryDirectory.appendingPathComponent("UpdateWorkbench-work-\(UUID().uuidString).noindex", isDirectory: true) @@ -160,14 +163,18 @@ enum SparkleBackend { } defer { if fileExtension == "dmg" { DiskImage.detach(sourceRoot) } } return try await verifyAndReplace(sourceRoot: sourceRoot, original: original, release: release, appName: appName, - isZIP: fileExtension == "zip", isSelf: isSelf, options: options) + isZIP: fileExtension == "zip", isSelf: isSelf, verifiedEDKey: edKey, options: options) }.value } /// The checks shared by ZIP and DMG payloads, then staging and replacement. The previous copy exists only /// during the swap: it is deleted once the new app is in place and verified, or put back if anything fails. + /// + /// Developer ID apps must keep their signing team (or one the user approved). An app without a team + /// (ad-hoc signed, like Update Workbench itself) can only be replaced when `verifiedEDKey` is set: the archive + /// carried a valid signature from the installed app's own Ed25519 key, and the new app ships the same key. private static func verifyAndReplace(sourceRoot: URL, original: URL, release: SparkleRelease, appName: String, - isZIP: Bool, isSelf: Bool, options: InstallOptions) async throws -> InstallOutcome { + isZIP: Bool, isSelf: Bool, verifiedEDKey: String?, options: InstallOptions) async throws -> InstallOutcome { let fm = FileManager.default let verifier = options.verifier let oldInfo = AppBundleInfo.read(original) @@ -205,18 +212,35 @@ enum SparkleBackend { throw Failure(message: "The downloaded app is not newer than the installed app.") } try verifier.verify(original) - let installedSigner = try verifier.identity(original) - // The candidate must pass codesign and Gatekeeper before any signer question is asked. + // The candidate must pass codesign (and, with a team, Gatekeeper) before any signer question is asked. try verifier.verify(candidate) - var candidateSigner = try verifier.identity(candidate) - candidateSigner.gatekeeper = try verifier.assess(candidate) + let installedTeam: String?, candidateTeam: String? var approved = false - if candidateSigner.teamID != installedSigner.teamID { - guard let store = options.trustedSigners, store.isApproved(bundleID: identifier, teamID: candidateSigner.teamID) else { - throw SignerChange(appName: appName, bundleID: identifier, version: release.version, installed: installedSigner, candidate: candidateSigner) + var candidateSigner: SignerIdentity? + if let installedSigner = try? verifier.identity(original) { + var signer = try verifier.identity(candidate) + signer.gatekeeper = try verifier.assess(candidate) + if signer.teamID != installedSigner.teamID { + guard let store = options.trustedSigners, store.isApproved(bundleID: identifier, teamID: signer.teamID) else { + throw SignerChange(appName: appName, bundleID: identifier, version: release.version, installed: installedSigner, candidate: signer) + } + approved = true + } + installedTeam = installedSigner.teamID; candidateTeam = signer.teamID; candidateSigner = signer + } else { + guard let verifiedEDKey else { throw Failure(message: "Ad-hoc or unsigned apps cannot be replaced directly.") } + guard newInfo["SUPublicEDKey"] as? String == verifiedEDKey else { + throw Failure(message: "The update doesn't carry the same Ed25519 update key as the installed app.") + } + // A team-signed update of a team-less app still has to pass Gatekeeper. + if let signer = try? verifier.identity(candidate) { + var assessed = signer + assessed.gatekeeper = try verifier.assess(candidate) + candidateSigner = assessed } - approved = true + installedTeam = nil; candidateTeam = candidateSigner?.teamID } + func team(_ app: URL) -> String? { (try? verifier.identity(app))?.teamID } // Staging happens in a private replacement folder on the same volume, never beside the app. let workspace = try fm.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: original, create: true) var keepWorkspace = false @@ -228,9 +252,9 @@ enum SparkleBackend { let previous = holding.appendingPathComponent("previous-" + original.lastPathComponent) try SyncCommand.run("/usr/bin/ditto", [candidate.path, staged.path]) try verifier.verify(staged) - guard try verifier.identity(staged).teamID == candidateSigner.teamID else { throw Failure(message: "The staged app failed its signing identity check.") } + guard team(staged) == candidateTeam else { throw Failure(message: "The staged app failed its signing identity check.") } // Re-check the original identity immediately before replacing it. - guard AppBundleInfo.read(original)["CFBundleIdentifier"] as? String == identifier, try verifier.identity(original).teamID == installedSigner.teamID else { + guard AppBundleInfo.read(original)["CFBundleIdentifier"] as? String == identifier, team(original) == installedTeam else { throw Failure(message: "The installed app changed while downloading. Scan again.") } let isRunning = await MainActor.run { @@ -246,7 +270,7 @@ enum SparkleBackend { throw Failure(message: "The installed app didn't match the update after it was moved into place.") } try verifier.verify(original) - guard try verifier.identity(original).teamID == candidateSigner.teamID else { throw Failure(message: "The installed app failed its signing identity check.") } + guard team(original) == candidateTeam else { throw Failure(message: "The installed app failed its signing identity check.") } } catch { do { if fm.fileExists(atPath: original.path) { try fm.removeItem(at: original) } @@ -258,7 +282,10 @@ enum SparkleBackend { throw Failure(message: "The update was rolled back and the previous version is back in place: \(error.localizedDescription)") } try? fm.removeItem(at: previous) - let signerNote = approved ? " Signed by approved team \(candidateSigner.teamID) (\(candidateSigner.signerName))." : "" + let signerNote: String + if approved, let candidateSigner { signerNote = " Signed by approved team \(candidateSigner.teamID) (\(candidateSigner.signerName))." } + else if installedTeam == nil { signerNote = " Verified with the app's Ed25519 update key." } + else { signerNote = "" } return InstallOutcome(message: "Installed \(release.version).\(signerNote) The previous version was removed after the new one passed its checks.", installedVersion: newVersion, signerApproved: approved) } diff --git a/Sources/UpdateWorkbench/Theme.swift b/Sources/UpdateWorkbench/Theme.swift index f6dbd52..b4102c9 100644 --- a/Sources/UpdateWorkbench/Theme.swift +++ b/Sources/UpdateWorkbench/Theme.swift @@ -1,33 +1,93 @@ import SwiftUI import AppKit -/// Visual language: native macOS controls, dark by default, with a few deliberate color splashes. +/// One pastel color in three roles: a soft surface, a deeper ink for text and icons, and a hairline. +/// Light mode puts dark ink on pastel; dark mode puts the pastel itself on a faint tint of it. +struct Tone { + let fill: Color + let ink: Color + let stroke: Color + let solid: Color + + init(pastel: UInt32, ink: UInt32, darkInk: UInt32) { + fill = .adaptive(light: .hex(pastel), dark: .hex(darkInk, alpha: 0.16)) + self.ink = .adaptive(light: .hex(ink), dark: .hex(darkInk)) + stroke = .adaptive(light: .hex(ink, alpha: 0.16), dark: .hex(darkInk, alpha: 0.28)) + solid = .adaptive(light: .hex(pastel), dark: .hex(darkInk, alpha: 0.30)) + } +} + +/// The palette. Every color is soft; meaning is always carried by text and symbols too, never by color alone. +enum Pastel { + static let lavender = Tone(pastel: 0xE8E3FF, ink: 0x5F4FD6, darkInk: 0xB8ADFF) + static let lilac = Tone(pastel: 0xF0E2FB, ink: 0x8A47C4, darkInk: 0xD7B6F7) + static let sky = Tone(pastel: 0xDCEBFF, ink: 0x2E6AB8, darkInk: 0x9CC5FF) + static let mint = Tone(pastel: 0xD5F3E5, ink: 0x1F7D59, darkInk: 0x8BDDB9) + static let aqua = Tone(pastel: 0xD5F1F4, ink: 0x1C7580, darkInk: 0x8AD8E2) + static let rose = Tone(pastel: 0xFFE0EB, ink: 0xB83D72, darkInk: 0xFFA9C9) + static let peach = Tone(pastel: 0xFFE5D3, ink: 0xAD5726, darkInk: 0xFFBE96) + static let butter = Tone(pastel: 0xFFF1C4, ink: 0x8C680A, darkInk: 0xF3D57A) + static let coral = Tone(pastel: 0xFFDEDB, ink: 0xBE3A31, darkInk: 0xFFA39C) + static let slate = Tone(pastel: 0xE8EBF1, ink: 0x566073, darkInk: 0xB4BCCB) +} + +/// Visual language: native macOS controls on calm surfaces, with pastel color for state and source. enum Theme { - static let indigo = Color(red: 0.36, green: 0.42, blue: 1.00) - static let violet = Color(red: 0.62, green: 0.36, blue: 0.98) - static let pink = Color(red: 0.98, green: 0.38, blue: 0.62) - static let mint = Color(red: 0.20, green: 0.80, blue: 0.62) - static let accent = indigo - static let accentGradient = LinearGradient(colors: [indigo, violet, pink], startPoint: .topLeading, endPoint: .bottomTrailing) - static let successGradient = LinearGradient(colors: [Color(red: 0.13, green: 0.62, blue: 0.47), Color(red: 0.16, green: 0.55, blue: 0.80)], startPoint: .topLeading, endPoint: .bottomTrailing) - static let idleGradient = LinearGradient(colors: [Color(red: 0.25, green: 0.30, blue: 0.62), Color(red: 0.45, green: 0.28, blue: 0.70)], startPoint: .topLeading, endPoint: .bottomTrailing) - static let cardRadius: CGFloat = 14 + /// Control tint: a lavender deep enough for white text on prominent buttons. + static let accent = Color.adaptive(light: .hex(0x5F4FD6), dark: .hex(0x8476F0)) + static let indigo = Pastel.lavender.ink + static let violet = Pastel.lilac.ink + static let pink = Pastel.rose.ink + static let mint = Pastel.mint.ink + + /// Small accents (arrows, bullets) that must stay visible on plain backgrounds. + static let inkGradient = LinearGradient(colors: [Pastel.lavender.ink, Pastel.rose.ink], startPoint: .leading, endPoint: .trailing) + /// Hero and sheet headers: pastel in light mode, a deep muted version in dark mode. + static let accentGradient = gradient(light: [0xE6E0FF, 0xFFDDEA, 0xFFE6D6], dark: [0x3A3470, 0x4D2F4D, 0x4B3731]) + static let successGradient = gradient(light: [0xD4F3E6, 0xDCEBFF], dark: [0x1D4339, 0x213856]) + static let idleGradient = gradient(light: [0xDDE8FF, 0xEAE4FF], dark: [0x263257, 0x372F5E]) + static let warningGradient = gradient(light: [0xFFE5D3, 0xFFE0EB], dark: [0x4D3528, 0x4D2C3D]) + /// Text on those gradients. + static let heroText = Color.adaptive(light: .hex(0x2A2549), dark: .white) + /// Translucent surface for secondary buttons and chips on the hero gradients. + static let frosted = Color.adaptive(light: .hex(0xFFFFFF, alpha: 0.55), dark: .hex(0xFFFFFF, alpha: 0.14)) + static let heroSecondary = Color.adaptive(light: .hex(0x2A2549, alpha: 0.72), dark: .hex(0xFFFFFF, alpha: 0.80)) + + static let cardRadius: CGFloat = 16 static let spacing: CGFloat = 16 + + private static func gradient(light: [UInt32], dark: [UInt32]) -> LinearGradient { + LinearGradient(colors: zip(light, dark).map { Color.adaptive(light: .hex($0), dark: .hex($1)) }, startPoint: .topLeading, endPoint: .bottomTrailing) + } +} + +extension NSColor { + static func hex(_ value: UInt32, alpha: CGFloat = 1) -> NSColor { + NSColor(srgbRed: CGFloat((value >> 16) & 0xFF) / 255, green: CGFloat((value >> 8) & 0xFF) / 255, blue: CGFloat(value & 0xFF) / 255, alpha: alpha) + } +} + +extension Color { + /// Resolves per appearance, so one value serves the window, sheets and the menu bar panel. + static func adaptive(light: NSColor, dark: NSColor) -> Color { + Color(nsColor: NSColor(name: nil) { $0.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light }) + } } extension UpdateProvider { - var tint: Color { + var tone: Tone { switch self { - case .homebrewCask: Color(red: 0.98, green: 0.58, blue: 0.20) - case .homebrewFormula: Color(red: 0.90, green: 0.72, blue: 0.22) - case .appStore: Color(red: 0.25, green: 0.60, blue: 1.00) - case .sparkle: Color(red: 0.72, green: 0.45, blue: 1.00) - case .github: Color(red: 0.55, green: 0.62, blue: 0.72) - case .electron: Color(red: 0.25, green: 0.82, blue: 0.90) - case .vendor: Color(red: 0.98, green: 0.42, blue: 0.62) - case .manual: Color(red: 0.58, green: 0.58, blue: 0.62) + case .homebrewCask: Pastel.peach + case .homebrewFormula: Pastel.butter + case .appStore: Pastel.sky + case .sparkle: Pastel.lilac + case .github: Pastel.slate + case .electron: Pastel.aqua + case .vendor: Pastel.rose + case .manual: Pastel.slate } } + var tint: Color { tone.ink } var symbol: String { switch self { case .homebrewCask: "mug.fill" @@ -67,58 +127,59 @@ extension UpdateProvider { } extension ItemStatus { - var tint: Color { + var tone: Tone { switch self { - case .failed: .red - case .ready: Theme.accent - case .manualUpdate: .orange - case .selfUpdating: UpdateProvider.vendor.tint - case .snoozed: .purple - case .heldBack: .orange - case .skipped, .ignored, .unknown: .secondary - case .upToDate: .green + case .failed: Pastel.coral + case .ready: Pastel.lavender + case .manualUpdate: Pastel.peach + case .selfUpdating: Pastel.rose + case .snoozed: Pastel.lilac + case .heldBack: Pastel.butter + case .skipped, .ignored, .unknown: Pastel.slate + case .upToDate: Pastel.mint } } + var tint: Color { tone.ink } } extension PermissionState { - var tint: Color { - switch self { case .granted: .green; case .denied: .orange; case .unknown: .secondary; case .notNeeded: .secondary } + var tone: Tone { + switch self { case .granted: Pastel.mint; case .denied: Pastel.peach; case .unknown, .notNeeded: Pastel.slate } } + var tint: Color { tone.ink } var symbol: String { switch self { case .granted: "checkmark.circle.fill"; case .denied: "exclamationmark.circle.fill"; case .unknown: "questionmark.circle.fill"; case .notNeeded: "minus.circle.fill" } } } extension SidebarSection { - var tint: Color { + var tone: Tone { switch self { - case .updates: Theme.indigo - case .applications: Theme.violet - case .packages: UpdateProvider.homebrewFormula.tint - case .suggestions: Color(red: 1.0, green: 0.78, blue: 0.20) - case .ignored: .gray - case .history: Theme.pink - case .permissions: Theme.mint + case .updates: Pastel.lavender + case .applications: Pastel.sky + case .packages: Pastel.butter + case .suggestions: Pastel.peach + case .ignored: Pastel.slate + case .history: Pastel.rose + case .permissions: Pastel.mint } } + var tint: Color { tone.ink } } /// Small capsule with icon + text. Color is decorative; the text carries the meaning. struct Pill: View { let text: String let symbol: String - let tint: Color - var prominent = false - @Environment(\.colorScheme) private var colorScheme + let tone: Tone + init(text: String, symbol: String, tone: Tone) { self.text = text; self.symbol = symbol; self.tone = tone } var body: some View { - // Bright tints read well on dark backgrounds; in light mode the text uses the primary color for contrast. - Label { Text(text).lineLimit(1).foregroundStyle(prominent ? Color.white : (colorScheme == .dark ? tint : Color.primary.opacity(0.85))) } - icon: { Image(systemName: symbol).imageScale(.small).foregroundStyle(prominent ? Color.white : tint) } + Label { Text(text).lineLimit(1) } icon: { Image(systemName: symbol).imageScale(.small) } .font(.caption.weight(.semibold)) + .foregroundStyle(tone.ink) .padding(.horizontal, 8).padding(.vertical, 3) - .background(Capsule().fill(prominent ? AnyShapeStyle(tint) : AnyShapeStyle(tint.opacity(0.16)))) - .overlay(Capsule().strokeBorder(tint.opacity(prominent ? 0 : 0.35), lineWidth: 0.5)) + .background(Capsule().fill(tone.fill)) + .overlay(Capsule().strokeBorder(tone.stroke, lineWidth: 0.5)) .fixedSize() } } @@ -126,7 +187,7 @@ struct Pill: View { struct SourceBadge: View { let provider: UpdateProvider var body: some View { - Pill(text: provider.shortName, symbol: provider.symbol, tint: provider.tint) + Pill(text: provider.shortName, symbol: provider.symbol, tone: provider.tone) .help(provider.explanation) .accessibilityLabel("Source: \(provider.rawValue)") } @@ -135,11 +196,27 @@ struct SourceBadge: View { struct StatusBadge: View { let status: ItemStatus var body: some View { - Pill(text: status.rawValue, symbol: status.symbol, tint: status.tint) + Pill(text: status.rawValue, symbol: status.symbol, tone: status.tone) .accessibilityLabel("Status: \(status.rawValue)") } } +/// A symbol on a soft rounded tile, used for section, card and history headers. +struct IconTile: View { + let symbol: String + let tone: Tone + var size: CGFloat = 40 + var body: some View { + Image(systemName: symbol) + .font(.system(size: size * 0.45, weight: .semibold)) + .foregroundStyle(tone.ink) + .frame(width: size, height: size) + .background(RoundedRectangle(cornerRadius: size * 0.28, style: .continuous).fill(tone.fill)) + .overlay(RoundedRectangle(cornerRadius: size * 0.28, style: .continuous).strokeBorder(tone.stroke, lineWidth: 0.5)) + .accessibilityHidden(true) + } +} + /// App icon from disk when available, otherwise a colored tile with the app's initial. struct AppIconView: View { let item: UpdateItem @@ -150,12 +227,12 @@ struct AppIconView: View { Image(nsImage: AppIconCache.icon(forFile: path)).resizable().interpolation(.high) } else { ZStack { - RoundedRectangle(cornerRadius: size * 0.24, style: .continuous) - .fill(LinearGradient(colors: [item.provider.tint, item.provider.tint.opacity(0.55)], startPoint: .topLeading, endPoint: .bottomTrailing)) + RoundedRectangle(cornerRadius: size * 0.26, style: .continuous).fill(item.provider.tone.fill) + RoundedRectangle(cornerRadius: size * 0.26, style: .continuous).strokeBorder(item.provider.tone.stroke, lineWidth: 0.5) if item.provider == .homebrewFormula { - Image(systemName: "terminal.fill").font(.system(size: size * 0.42, weight: .semibold)).foregroundStyle(.white) + Image(systemName: "terminal.fill").font(.system(size: size * 0.40, weight: .semibold)).foregroundStyle(item.provider.tone.ink) } else { - Text(String(item.name.prefix(1)).uppercased()).font(.system(size: size * 0.48, weight: .bold, design: .rounded)).foregroundStyle(.white) + Text(String(item.name.prefix(1)).uppercased()).font(.system(size: size * 0.46, weight: .bold, design: .rounded)).foregroundStyle(item.provider.tone.ink) } } .padding(size * 0.06) @@ -170,19 +247,22 @@ struct AppIconView: View { struct Card: View { var title: String? = nil var symbol: String? = nil - var tint: Color = .secondary + var tone: Tone = Pastel.slate @ViewBuilder var content: Content var body: some View { VStack(alignment: .leading, spacing: 10) { if let title { - Label { Text(title).font(.headline) } icon: { Image(systemName: symbol ?? "circle").foregroundStyle(tint) } + HStack(spacing: 10) { + IconTile(symbol: symbol ?? "circle", tone: tone, size: 26) + Text(title).font(.headline) + } } content } - .padding(14) + .padding(16) .frame(maxWidth: .infinity, alignment: .leading) .background(RoundedRectangle(cornerRadius: Theme.cardRadius, style: .continuous).fill(.background.secondary)) - .overlay(RoundedRectangle(cornerRadius: Theme.cardRadius, style: .continuous).strokeBorder(.separator.opacity(0.6), lineWidth: 0.5)) + .overlay(RoundedRectangle(cornerRadius: Theme.cardRadius, style: .continuous).strokeBorder(.separator.opacity(0.45), lineWidth: 0.5)) } } @@ -191,23 +271,23 @@ struct StatTile: View { let value: Int let label: String let symbol: String - let tint: Color + let tone: Tone var body: some View { VStack(alignment: .leading, spacing: 4) { - Image(systemName: symbol).font(.callout.weight(.semibold)).foregroundStyle(tint) - Text("\(value)").font(.title2.weight(.bold)).monospacedDigit() - Text(label).font(.caption).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.8) + Image(systemName: symbol).font(.callout.weight(.semibold)).foregroundStyle(tone.ink) + Text("\(value)").font(.title2.weight(.bold)).monospacedDigit().foregroundStyle(tone.ink) + Text(label).font(.caption.weight(.medium)).foregroundStyle(.secondary).lineLimit(1).minimumScaleFactor(0.8) } .padding(10) .frame(maxWidth: .infinity, alignment: .leading) - .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(tint.opacity(0.10))) - .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(tint.opacity(0.25), lineWidth: 0.5)) + .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(tone.fill)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(tone.stroke, lineWidth: 0.5)) .accessibilityElement(children: .ignore) .accessibilityLabel("\(value) \(label)") } } -/// White button on a gradient hero card. +/// Capsule button on a pastel hero card: filled lavender for the main action, frosted for the rest. struct HeroButtonStyle: ButtonStyle { var filled = true @Environment(\.isEnabled) private var isEnabled @@ -215,14 +295,31 @@ struct HeroButtonStyle: ButtonStyle { configuration.label .font(.body.weight(.semibold)) .padding(.horizontal, 14).padding(.vertical, 7) - .foregroundStyle(filled ? Color(red: 0.22, green: 0.18, blue: 0.55) : .white) - .background(Capsule().fill(filled ? Color.white : Color.white.opacity(0.18))) - .overlay(Capsule().strokeBorder(Color.white.opacity(filled ? 0 : 0.45), lineWidth: 1)) + .foregroundStyle(filled ? Color.white : Theme.heroText) + .background(Capsule().fill(filled ? AnyShapeStyle(Theme.accent) : AnyShapeStyle(Theme.frosted))) + .overlay(Capsule().strokeBorder(filled ? Color.clear : Theme.heroText.opacity(0.18), lineWidth: 1)) + .shadow(color: filled ? Theme.accent.opacity(0.28) : .clear, radius: 6, y: 2) .opacity(isEnabled ? (configuration.isPressed ? 0.75 : 1) : 0.5) .contentShape(Capsule()) } } +/// Compact pastel capsule for in-row actions; looks the same whether or not the window is active. +struct PastelButtonStyle: ButtonStyle { + let tone: Tone + @Environment(\.isEnabled) private var isEnabled + func makeBody(configuration: Configuration) -> some View { + configuration.label + .font(.callout.weight(.semibold)) + .foregroundStyle(tone.ink) + .padding(.horizontal, 12).padding(.vertical, 4) + .background(Capsule().fill(tone.solid)) + .overlay(Capsule().strokeBorder(tone.stroke, lineWidth: 0.5)) + .opacity(isEnabled ? (configuration.isPressed ? 0.7 : 1) : 0.45) + .contentShape(Capsule()) + } +} + /// Labeled value row used in detail cards. struct InfoRow: View { let label: String diff --git a/Sources/UpdateWorkbench/UpdateHistory.swift b/Sources/UpdateWorkbench/UpdateHistory.swift index b08d9ad..11c1006 100644 --- a/Sources/UpdateWorkbench/UpdateHistory.swift +++ b/Sources/UpdateWorkbench/UpdateHistory.swift @@ -24,6 +24,13 @@ struct HistoryEntry: Codable, Identifiable, Equatable, Sendable { var message: String var succeeded: Bool { result == .installed || result == .restored } + + /// Number of apps whose newest attempt failed; a later success for the same app resolves it. + static func unresolvedFailures(_ entries: [HistoryEntry]) -> Int { + var newest: [String: HistoryEntry] = [:] + for entry in entries where (newest[entry.itemID]?.date ?? .distantPast) < entry.date { newest[entry.itemID] = entry } + return newest.values.filter { !$0.succeeded }.count + } } /// Update history persisted as JSON, newest first, capped at 500 entries. diff --git a/Tests/FeatureTests.swift b/Tests/FeatureTests.swift index f97ee11..3d9dfe5 100644 --- a/Tests/FeatureTests.swift +++ b/Tests/FeatureTests.swift @@ -5,7 +5,7 @@ import Security @testable import UpdateWorkbench /// Offline fixtures for Electron feeds, discovery, cask matching, management flows, permissions, -/// notifications, proxy/Keychain and self-update. No network, brew, or real app changes. +/// notifications and proxy/Keychain. No network, brew, or real app changes. enum FeatureTests { struct Failure: Error, CustomStringConvertible { let description: String } static func expect(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { @@ -26,10 +26,9 @@ enum FeatureTests { try testAppRemoval() try testPermissions() try testNotifications() - try testSelfUpdateFeed() try testProxy() try testKeychain() - print("PASS: Electron feeds, SHA-512, GitHub discovery, cask matching, vendor updaters, Homebrew actions, Trash removal, permissions, notifications, self-update feed, proxy, Keychain") + print("PASS: Electron feeds, SHA-512, GitHub discovery, cask matching, vendor updaters, Homebrew actions, Trash removal, permissions, notifications, proxy, Keychain") } static func testElectronConfig() throws { @@ -275,16 +274,6 @@ enum FeatureTests { try expect(UpdateNotificationPolicy.resultMessage(succeeded: ["A"], failed: ["B"])?.title == "Updates finished with errors", "Mixed text") } - static func testSelfUpdateFeed() throws { - try expect(try SelfUpdateFeed.parse(" ") == .disabled, "Empty feed disables self-update") - try expect(try SelfUpdateFeed.parse("github:kasakir-ai/update-workbench") == .github("kasakir-ai/update-workbench"), "github: shorthand") - try expect(try SelfUpdateFeed.parse("https://github.com/owner/repo") == .github("owner/repo"), "Repository URL") - try expect(try SelfUpdateFeed.parse("https://updates.example.com/appcast.xml") == .appcast(URL(string: "https://updates.example.com/appcast.xml")!), "Appcast URL") - for bad in ["http://updates.example.com/appcast.xml", "github:bad", "https://user:pw@example.com/a.xml", "https://github.com/owner/repo/releases", "nonsense"] { - try expect(rejects { _ = try SelfUpdateFeed.parse(bad) }, "Invalid self-update feed rejected: \(bad)") - } - } - final class ChallengeSender: NSObject, URLAuthenticationChallengeSender { func use(_ credential: URLCredential, for challenge: URLAuthenticationChallenge) {} func continueWithoutCredential(for challenge: URLAuthenticationChallenge) {} diff --git a/Tests/SelfUpdateTests.swift b/Tests/SelfUpdateTests.swift new file mode 100644 index 0000000..d815914 --- /dev/null +++ b/Tests/SelfUpdateTests.swift @@ -0,0 +1,110 @@ +import CryptoKit +import Foundation +@testable import UpdateWorkbench + +/// 0.5.0: apps without a Developer ID team (Update Workbench itself) update only through their own Ed25519 key, +/// plus the self-update helpers and the History badge. +enum SelfUpdateTests { + struct Failure: Error, CustomStringConvertible { let description: String } + static func expect(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { + if !(try condition()) { throw Failure(description: message) } + } + + static func run() async throws { + try await testKeyAnchoredInstalls() + try testHelpers() + try testHistoryBadge() + print("PASS: Ed25519-anchored installs of team-less apps (signed, unsigned, wrong key, swapped key, no key, team downgrade), self-update helpers, History badge") + } + + static func testKeyAnchoredInstalls() async throws { + let fm = FileManager.default + let work = TestTemp.root.appendingPathComponent("uw-self-\(UUID().uuidString)", isDirectory: true) + try fm.createDirectory(at: work, withIntermediateDirectories: true) + defer { try? fm.removeItem(at: work) } + let key = Curve25519.Signing.PrivateKey() + let publicKey = key.publicKey.rawRepresentation.base64EncodedString() + let otherKey = Curve25519.Signing.PrivateKey() + + /// A fixture app; no "team" means FixtureVerifier treats it as ad-hoc signed. + func app(_ folder: URL, version: String, edKey: String?, team: String? = nil) throws -> URL { + var extra: [String: Any] = [:] + if let edKey { extra["SUPublicEDKey"] = edKey } + let app = try DiskImageTests.app(in: folder, name: "Workbench", version: version, team: team ?? "", extra: extra) + if team == nil { + var info = AppBundleInfo.read(app); info.removeValue(forKey: "UWFixtureTeam") + try PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: 0).write(to: app.appendingPathComponent("Contents/Info.plist")) + } + return app + } + func zip(_ app: URL, _ name: String) throws -> URL { + let output = work.appendingPathComponent("\(name).zip") + try SyncCommand.run("/usr/bin/ditto", ["-c", "-k", "--keepParent", app.path, output.path]) + return output + } + func installed(_ name: String, edKey: String?, team: String? = nil) throws -> URL { + try app(work.appendingPathComponent(name).appendingPathComponent("Applications"), version: "1.0", edKey: edKey, team: team) + } + func install(_ payload: URL, into target: URL, signer: Curve25519.Signing.PrivateKey?) async throws -> InstallOutcome { + let signature = try signer.map { try $0.signature(for: Data(contentsOf: payload)).base64EncodedString() } + let release = SparkleRelease(version: "2.0", downloadURL: URL(string: "https://example.com/Workbench.zip")!, releaseNotesURL: nil, signature: signature) + return try await SparkleBackend.installPayload(payload, fileExtension: "zip", release: release, target: target, + options: InstallOptions(trustedSigners: nil, verifier: FixtureVerifier(), appName: "Workbench")) + } + func version(_ app: URL) -> String? { AppBundleInfo.read(app)["CFBundleShortVersionString"] as? String } + func failure(_ fragment: String, _ label: String, _ body: () async throws -> Void) async throws { + try await DiskImageTests.expectFailure(fragment, label, body) + } + + let good = try zip(try app(work.appendingPathComponent("src-good"), version: "2.0", edKey: publicKey), "good") + var target = try installed("t-good", edKey: publicKey) + let outcome = try await install(good, into: target, signer: key) + try expect(version(target) == "2.0" && outcome.message.contains("Ed25519 update key"), "A team-less app updates with its own signed archive: \(outcome.message)") + try expect(DiskImageTests.leftovers(beside: target).isEmpty, "No staging or previous copy is left behind") + + target = try installed("t-unsigned", edKey: publicKey) + try await failure("Ed25519", "Unsigned archive") { _ = try await install(good, into: target, signer: nil) } + try await failure("Ed25519", "Archive signed by another key") { _ = try await install(good, into: target, signer: otherKey) } + try expect(version(target) == "1.0", "Rejected updates leave the installed app untouched") + + let swapped = try zip(try app(work.appendingPathComponent("src-swapped"), version: "2.0", edKey: otherKey.publicKey.rawRepresentation.base64EncodedString()), "swapped") + target = try installed("t-swapped", edKey: publicKey) + try await failure("same Ed25519 update key", "Update that replaces the update key") { _ = try await install(swapped, into: target, signer: key) } + + let keyless = try zip(try app(work.appendingPathComponent("src-keyless"), version: "2.0", edKey: nil), "keyless") + target = try installed("t-keyless", edKey: nil) + try await failure("Ad-hoc or unsigned", "A team-less app without an update key") { _ = try await install(keyless, into: target, signer: nil) } + + // A Developer ID app never accepts a team-less update, even one signed with its update key. + target = try installed("t-team", edKey: publicKey, team: "TEAMA11111") + try await failure("Ad-hoc or unsigned", "Team-signed app offered a team-less update") { _ = try await install(good, into: target, signer: key) } + try expect(version(target) == "1.0", "The Developer ID app stays as installed") + } + + static func testHelpers() throws { + try expect(SelfUpdate.installedWithHomebrew(exists: { $0 == "/opt/homebrew/Caskroom/update-workbench" }), "Apple silicon Caskroom detected") + try expect(SelfUpdate.installedWithHomebrew(exists: { $0 == "/usr/local/Caskroom/update-workbench" }), "Intel Caskroom detected") + try expect(!SelfUpdate.installedWithHomebrew(exists: { _ in false }), "No Caskroom folder means a direct install") + let folder = TestTemp.root.appendingPathComponent("uw-selfitem-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: folder) } + let app = try DiskImageTests.app(in: folder, name: "Update Workbench", bundleID: "local.updateworkbench.app", version: "0.5.0", team: "", extra: ["CFBundleDisplayName": "Update Workbench", "SUPublicEDKey": "a2V5"]) + let direct = SelfUpdate.currentItem(bundle: app, homebrew: false) + try expect(direct.provider == .sparkle && direct.token == nil && direct.installedVersion == "0.5.0" && direct.requiresSparkleSignature == true, "Direct install updates from its signed feed") + try expect(direct.id == app.resolvingSymlinksInPath().path && direct.bundleID == "local.updateworkbench.app", "Same ID the scanner uses") + let brew = SelfUpdate.currentItem(bundle: app, homebrew: true) + try expect(brew.provider == .homebrewCask && brew.token == "update-workbench", "Homebrew install updates through its cask") + var outdated = brew; outdated.isOutdated = true; outdated.latestVersion = "0.5.1" + try expect(outdated.canUpdateDirectly && (try Engine.homebrewArguments(for: outdated)).last == "update-workbench", "The cask can be upgraded from inside the app") + try expect(!direct.isSelf, "A fixture copy is not the running app") + } + + static func testHistoryBadge() throws { + let now = Date() + func entry(_ id: String, _ result: HistoryEntry.Result, ago: TimeInterval) -> HistoryEntry { + HistoryEntry(date: now.addingTimeInterval(-ago), itemID: id, appName: id, fromVersion: "1", toVersion: "2", source: "Sparkle", result: result, message: "") + } + try expect(HistoryEntry.unresolvedFailures([]) == 0, "Empty history has no badge") + try expect(HistoryEntry.unresolvedFailures([entry("a", .failed, ago: 100), entry("a", .installed, ago: 10)]) == 0, "A later success clears a failure") + try expect(HistoryEntry.unresolvedFailures([entry("a", .installed, ago: 100), entry("a", .failed, ago: 10), entry("b", .failed, ago: 5), entry("b", .failed, ago: 50)]) == 2, "Counts apps whose latest attempt failed") + } +} diff --git a/Tests/Suites.swift b/Tests/Suites.swift index b390fcf..ef6584d 100644 --- a/Tests/Suites.swift +++ b/Tests/Suites.swift @@ -12,4 +12,5 @@ struct OfflineSuites { @Test func diskImages() async throws { try await DiskImageTests.run() } @Test func backend() async throws { try await BackendTests.run() } @Test func security() async throws { try await SecurityTests.run() } + @Test func selfUpdate() async throws { try await SelfUpdateTests.run() } } diff --git a/build.sh b/build.sh index 3f3ec85..0a9b3df 100755 --- a/build.sh +++ b/build.sh @@ -2,8 +2,8 @@ set -euo pipefail cd "$(dirname "$0")" # The one place the version is set. The app reads it back from Info.plist at runtime. -VERSION=0.4.1 -BUILD=7 +VERSION=0.5.0 +BUILD=8 # The app is built in dist.noindex/: Spotlight skips folders ending in .noindex, so development # builds never show up in Spotlight or Launchpad next to the installed app. APP=dist.noindex/UpdateWorkbench.app @@ -21,6 +21,9 @@ export SWIFTPM_MODULECACHE_OVERRIDE="$PWD/.build-cache" swift build --configuration release -debug-info-format none --scratch-path "$PWD/.build" --disable-sandbox BIN_DIR="$(swift build --configuration release --scratch-path "$PWD/.build" --disable-sandbox --show-bin-path)" cp "$BIN_DIR/UpdateWorkbench" "$APP/Contents/MacOS/UpdateWorkbench" +# Self-update: the signed release feed and the public half of the release key (tools/release-key.swift). +FEED_URL=https://github.com/Kasakir-AI/UpdateWorkbench/releases/latest/download/appcast.xml +PUBLIC_KEY="$(tr -d '[:space:]' < Resources/release-public-key.txt)" cat > "$APP/Contents/Info.plist" < @@ -36,6 +39,8 @@ cat > "$APP/Contents/Info.plist" <LSMinimumSystemVersion14.0 NSHighResolutionCapable LSApplicationCategoryTypepublic.app-category.utilities +SUFeedURL$FEED_URL +SUPublicEDKey$PUBLIC_KEY PLIST /usr/bin/codesign --force --sign - "$APP" diff --git a/docs/screenshots/first-run-dark.png b/docs/screenshots/first-run-dark.png index 3421d3d..6a42eb2 100644 Binary files a/docs/screenshots/first-run-dark.png and b/docs/screenshots/first-run-dark.png differ diff --git a/docs/screenshots/history-dark.png b/docs/screenshots/history-dark.png index b22cf9b..3c71014 100644 Binary files a/docs/screenshots/history-dark.png and b/docs/screenshots/history-dark.png differ diff --git a/docs/screenshots/menubar-dark.png b/docs/screenshots/menubar-dark.png index a8a408c..b9b69f6 100644 Binary files a/docs/screenshots/menubar-dark.png and b/docs/screenshots/menubar-dark.png differ diff --git a/docs/screenshots/permissions-dark.png b/docs/screenshots/permissions-dark.png index c444553..1858537 100644 Binary files a/docs/screenshots/permissions-dark.png and b/docs/screenshots/permissions-dark.png differ diff --git a/docs/screenshots/release-notes-dark.png b/docs/screenshots/release-notes-dark.png index b7c1c49..702e5fd 100644 Binary files a/docs/screenshots/release-notes-dark.png and b/docs/screenshots/release-notes-dark.png differ diff --git a/docs/screenshots/self-update-light.png b/docs/screenshots/self-update-light.png new file mode 100644 index 0000000..76322f6 Binary files /dev/null and b/docs/screenshots/self-update-light.png differ diff --git a/docs/screenshots/settings-appearance-dark.png b/docs/screenshots/settings-appearance-dark.png index 2da8dd5..d0297cc 100644 Binary files a/docs/screenshots/settings-appearance-dark.png and b/docs/screenshots/settings-appearance-dark.png differ diff --git a/docs/screenshots/settings-rules-dark.png b/docs/screenshots/settings-rules-dark.png index 5eebda2..9713ca1 100644 Binary files a/docs/screenshots/settings-rules-dark.png and b/docs/screenshots/settings-rules-dark.png differ diff --git a/docs/screenshots/settings-trust-dark.png b/docs/screenshots/settings-trust-dark.png index b34e030..2a3d767 100644 Binary files a/docs/screenshots/settings-trust-dark.png and b/docs/screenshots/settings-trust-dark.png differ diff --git a/docs/screenshots/settings-updates-light.png b/docs/screenshots/settings-updates-light.png new file mode 100644 index 0000000..0f60795 Binary files /dev/null and b/docs/screenshots/settings-updates-light.png differ diff --git a/docs/screenshots/signer-approval-dark.png b/docs/screenshots/signer-approval-dark.png index 57a2e62..ef1173a 100644 Binary files a/docs/screenshots/signer-approval-dark.png and b/docs/screenshots/signer-approval-dark.png differ diff --git a/docs/screenshots/suggestions-dark.png b/docs/screenshots/suggestions-dark.png index f81050d..50d72e8 100644 Binary files a/docs/screenshots/suggestions-dark.png and b/docs/screenshots/suggestions-dark.png differ diff --git a/docs/screenshots/updates-dark.png b/docs/screenshots/updates-dark.png index 25583c5..eb16a57 100644 Binary files a/docs/screenshots/updates-dark.png and b/docs/screenshots/updates-dark.png differ diff --git a/docs/screenshots/updates-light.png b/docs/screenshots/updates-light.png index a002fa3..32e9cba 100644 Binary files a/docs/screenshots/updates-light.png and b/docs/screenshots/updates-light.png differ diff --git a/make-release.sh b/make-release.sh index 04b1646..706f9b5 100755 --- a/make-release.sh +++ b/make-release.sh @@ -1,19 +1,46 @@ #!/bin/bash -# Packages dist.noindex/UpdateWorkbench.app as a drag-to-Applications DMG, a ZIP and SHA256SUMS in release/. +# Packages dist.noindex/UpdateWorkbench.app as a drag-to-Applications DMG, a ZIP, SHA256SUMS and appcast.xml in release/. +# The ZIP is signed with the release key (tools/release-key.swift); appcast.xml is the feed installed copies check. +# Optional: RELEASE_NOTES=path/to/notes.md puts plain release notes into the feed. set -euo pipefail cd "$(dirname "$0")" APP=dist.noindex/UpdateWorkbench.app VERSION="$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "$APP/Contents/Info.plist")" +BUILD="$(/usr/libexec/PlistBuddy -c 'Print CFBundleVersion' "$APP/Contents/Info.plist")" # The DMG staging copy lives in a temporary .noindex folder so Spotlight never lists it. OUT=release; STAGE_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/uw-dmg.XXXXXX")"; STAGE="$STAGE_ROOT/stage.noindex" trap 'rm -rf "$STAGE_ROOT"' EXIT mkdir -p "$STAGE" mkdir -p "$OUT" DMG="$OUT/UpdateWorkbench-$VERSION.dmg"; ZIP="$OUT/UpdateWorkbench-$VERSION.zip" -rm -f "$DMG" "$ZIP" "$OUT/SHA256SUMS" +rm -f "$DMG" "$ZIP" "$OUT/SHA256SUMS" "$OUT/appcast.xml" /usr/bin/ditto "$APP" "$STAGE/Update Workbench.app" ln -s /Applications "$STAGE/Applications" /usr/bin/hdiutil create -quiet -volname "Update Workbench" -srcfolder "$STAGE" -fs HFS+ -format UDZO -imagekey zlib-level=9 -ov "$DMG" >/dev/null /usr/bin/ditto -c -k --norsrc --noextattr --noqtn --keepParent "$STAGE/Update Workbench.app" "$ZIP" (cd "$OUT" && /usr/bin/shasum -a 256 "$(basename "$DMG")" "$(basename "$ZIP")" > SHA256SUMS) +# Sign the ZIP and check the signature against the key built into the app before publishing anything. +SIGNATURE="$(xcrun swift tools/release-key.swift sign "$ZIP")" +[ "$(xcrun swift tools/release-key.swift public-key)" = "$(/usr/libexec/PlistBuddy -c 'Print SUPublicEDKey' "$APP/Contents/Info.plist")" ] \ + || { echo "The app's SUPublicEDKey doesn't match the release key in the Keychain." >&2; exit 1; } +NOTES="" +[ -n "${RELEASE_NOTES:-}" ] && NOTES="$(sed 's/]]>/]]]]>/g' "$RELEASE_NOTES")" +cat > "$OUT/appcast.xml" < + + +Update Workbench + +Update Workbench $VERSION +$(LC_ALL=C date -u '+%a, %d %b %Y %H:%M:%S +0000') +$BUILD +$VERSION +14.0 + + + + + +XML cat "$OUT/SHA256SUMS" +echo "Signed $(basename "$ZIP") and wrote $OUT/appcast.xml" diff --git a/tools/release-key.swift b/tools/release-key.swift new file mode 100644 index 0000000..e3c4aa5 --- /dev/null +++ b/tools/release-key.swift @@ -0,0 +1,62 @@ +// Update Workbench release signing key (Ed25519, the format Sparkle uses). +// +// xcrun swift tools/release-key.swift generate create the key in the login Keychain, print the public key +// xcrun swift tools/release-key.swift public-key print the public key (base64) +// xcrun swift tools/release-key.swift sign FILE print the base64 signature of FILE +// +// The private key never leaves the login Keychain; only the public key is committed +// (Resources/release-public-key.txt) and written into Info.plist by build.sh. Losing the private key +// means installed copies can no longer update themselves in place: back it up with Keychain Access. +import CryptoKit +import Foundation +import Security + +let service = "Update Workbench release signing key" +let account = "ed25519" + +func fail(_ message: String) -> Never { + FileHandle.standardError.write(Data((message + "\n").utf8)) + exit(1) +} + +func storedKey() -> Curve25519.Signing.PrivateKey? { + let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, + kSecAttrAccount as String: account, kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne] + var result: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess, let data = result as? Data, let raw = Data(base64Encoded: data) else { + fail("Couldn't read the release key from the Keychain (status \(status)).") + } + do { return try Curve25519.Signing.PrivateKey(rawRepresentation: raw) } catch { fail("The stored release key is invalid.") } +} + +func requireKey() -> Curve25519.Signing.PrivateKey { + guard let key = storedKey() else { fail("No release key in the Keychain. Run: xcrun swift tools/release-key.swift generate") } + return key +} + +let arguments = Array(CommandLine.arguments.dropFirst()) +switch arguments.first { +case "generate": + guard storedKey() == nil else { fail("A release key already exists. Refusing to replace it.") } + let key = Curve25519.Signing.PrivateKey() + let item: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, + kSecAttrLabel as String: service, kSecValueData as String: Data(key.rawRepresentation.base64EncodedString().utf8), + kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked] + let status = SecItemAdd(item as CFDictionary, nil) + guard status == errSecSuccess else { fail("Couldn't save the release key to the Keychain (status \(status)).") } + print(key.publicKey.rawRepresentation.base64EncodedString()) +case "public-key": + print(requireKey().publicKey.rawRepresentation.base64EncodedString()) +case "sign": + guard arguments.count == 2 else { fail("Usage: release-key.swift sign FILE") } + let data: Data + do { data = try Data(contentsOf: URL(fileURLWithPath: arguments[1]), options: .mappedIfSafe) } catch { fail("Couldn't read \(arguments[1]).") } + let key = requireKey() + let signature = try! key.signature(for: data) + guard key.publicKey.isValidSignature(signature, for: data) else { fail("The signature didn't verify.") } + print(signature.base64EncodedString()) +default: + fail("Usage: release-key.swift generate | public-key | sign FILE") +}