Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apple/TablePro/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
ConnectionStorage.shared.keepLocalOnlySecretsOnDeviceIfNeeded()
FavoriteTablesStorage.shared.migrateSyncIdentityIfNeeded()
SoftwareUpdater.shared.start()
AppUpdatePluginStager.shared.follow(SoftwareUpdater.shared.$preparedUpdate.eraseToAnyPublisher())
ManagedPolicyCenter.shared.startMonitoring()
// Before the account starts, so a stored key's migration reaches it as a sign-in.
Telemetry.shared.start(
Expand Down
17 changes: 14 additions & 3 deletions apple/TablePro/Core/Plugins/PluginInstaller.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ protocol RegistryPluginInstalling: Sendable {
progress: @escaping @Sendable (Double) async -> Void
) async throws -> URL

// kits is the range the build must fall in: the running app's, or the release's own for the app update.
func stage(
_ registryPlugin: RegistryPlugin,
release: RegistryRelease,
pluginId: String,
bundleName: String,
kits: ClosedRange<Int>,
into userPluginsDir: URL,
progress: @escaping @Sendable (Double) async -> Void
) async throws -> URL
Expand Down Expand Up @@ -48,6 +50,7 @@ actor PluginInstaller: RegistryPluginInstalling {
let extracted = try await downloadExtractVerify(
registryPlugin,
release: release,
kits: PluginManager.compatibleKits,
into: userPluginsDir,
progress: progress
)
Expand All @@ -62,12 +65,14 @@ actor PluginInstaller: RegistryPluginInstalling {
release: RegistryRelease,
pluginId: String,
bundleName: String,
kits: ClosedRange<Int>,
into userPluginsDir: URL,
progress: @escaping @Sendable (Double) async -> Void
) async throws -> URL {
let extracted = try await downloadExtractVerify(
registryPlugin,
release: release,
kits: kits,
into: userPluginsDir,
progress: progress
)
Expand All @@ -91,6 +96,7 @@ actor PluginInstaller: RegistryPluginInstalling {
private func downloadExtractVerify(
_ registryPlugin: RegistryPlugin,
release: RegistryRelease,
kits: ClosedRange<Int>,
into userPluginsDir: URL,
progress: @escaping @Sendable (Double) async -> Void
) async throws -> ExtractedBundle {
Expand Down Expand Up @@ -130,7 +136,7 @@ actor PluginInstaller: RegistryPluginInstalling {
}

try PluginCodeSignatureVerifier.verify(bundle: stagedBundle)
try Self.validateBundle(stagedBundle, against: release, pluginId: registryPlugin.id)
try Self.validateBundle(stagedBundle, against: release, pluginId: registryPlugin.id, kits: kits)
Self.stripQuarantine(at: bundleURL)
try Task.checkCancellation()

Expand Down Expand Up @@ -221,8 +227,13 @@ actor PluginInstaller: RegistryPluginInstalling {
}

// The archive must be the build and the plugin its manifest entry names, as registry.py checks when it publishes.
nonisolated static func validateBundle(_ bundle: Bundle, against release: RegistryRelease, pluginId: String) throws {
try PluginManager.validateBundleVersions(bundle)
nonisolated static func validateBundle(
_ bundle: Bundle,
against release: RegistryRelease,
pluginId: String,
kits: ClosedRange<Int> = PluginManager.compatibleKits
) throws {
try PluginManager.validateBundleVersions(bundle, kits: kits)
let info = PluginManager.infoPlist(at: bundle.bundleURL)
let identifier = info["CFBundleIdentifier"] as? String ?? ""
guard identifier == pluginId else {
Expand Down
113 changes: 113 additions & 0 deletions apple/TablePro/Core/Plugins/PluginManager+AppUpdateStaging.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import Foundation
import os

// The new app applies staged builds before it loads any plugin; one not staged here is left to its update pass.
extension PluginManager {
func stagePluginsForAppUpdate(
_ appUpdate: PreparedAppUpdate,
registryClient: @autoclosure () -> RegistryClient = RegistryClient.shared,
systemVersion: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion
) async {
guard isUpdatingEnabled else { return }
await waitForInitialLoad()
let targets = appUpdateStagingTargets(appBuild: appUpdate.build)
guard !targets.isEmpty, !Task.isCancelled else { return }
guard let manifest = await registryClient().fetch(policy: .mustBeCurrent) else {
Self.logger.warning("No plugins staged for build \(appUpdate.build): the plugin manifest is unavailable")
return
}
let pending = Self.appUpdateStagings(
installed: targets,
manifest: manifest,
appUpdate: appUpdate,
systemVersion: systemVersion
)
for update in pending {
guard !Task.isCancelled else { return }
do {
try await stageForAppUpdate(update)
Self.logger.info("Staged build \(update.release.build) of '\(update.target.pluginId, privacy: .public)' for the app update")
} catch {
Self.logger.warning(
"'\(update.target.pluginId, privacy: .public)' not staged for the app update: \(error.publicLogShape, privacy: .public)"
)
}
}
}

func appUpdateStagingTargets(appBuild: Int) -> [RegistryUpdateTarget] {
plugins.compactMap { entry in
guard entry.source == .userInstalled,
installedBuild(of: entry) < appBuild,
Self.readRegistryMetadata(for: entry.url)?.pluginId == entry.id else { return nil }
return RegistryUpdateTarget(pluginId: entry.id, build: entry.build, rejectedURL: nil)
}
}

// Only the build the new app ships with: its kit is the new app's, and a lower build would stay a target of the
// new app's pass.
nonisolated static func appUpdateStagings(
installed: [RegistryUpdateTarget],
manifest: RegistryManifest,
appUpdate: PreparedAppUpdate,
systemVersion: OperatingSystemVersion
) -> [PendingRegistryUpdate] {
installed.compactMap { target in
guard target.build < appUpdate.build,
let plugin = manifest.plugins.first(where: { $0.id == target.pluginId }),
let release = plugin.releases.first(where: { release in
release.build == appUpdate.build
&& appUpdate.pluginChannel.accepts(release.channel)
&& release.runs(on: systemVersion)
}) else { return nil }
return PendingRegistryUpdate(target: target, plugin: plugin, release: release)
}
}

// Not on the install tracker, which notifies a failed update: here the new app's pass is the fallback.
private func stageForAppUpdate(_ update: PendingRegistryUpdate) async throws {
guard let existing = plugins.first(where: { $0.id == update.target.pluginId }),
existing.source == .userInstalled,
existing.build == update.target.build else {
throw PluginError.notFound
}
try reserveInstall(of: existing.id)
defer { installsInFlight.remove(existing.id) }
// A file opened while the manifest loaded may have staged a build of its own and dropped the sidecar.
guard Self.readRegistryMetadata(for: existing.url)?.pluginId == existing.id,
installedBuild(of: existing) < update.release.build else {
throw PluginError.installFailed(String(localized: "The downloaded plugin is not newer than the installed one."))
}
let kit = update.release.pluginKit
let stagedURL = try await registryInstaller.stage(
update.plugin,
release: update.release,
pluginId: existing.id,
bundleName: existing.url.lastPathComponent,
kits: kit...kit,
into: userPluginsDir,
progress: { _ in }
)
try recordStagedUpdate(at: stagedURL, replacing: existing)
}

// Otherwise Relaunch to Update would offer builds this app drops at launch.
func dropStagedUpdatesThisAppCannotLoad() {
var dropped = false
for pluginId in stagedPluginIds.sorted() where !Self.stagedUpdateLoads(pluginId: pluginId, in: userPluginsDir) {
removeStagedUpdate(pluginId: pluginId)
dropped = true
Self.logger.info("Dropped the staged build of '\(pluginId, privacy: .public)' made for an app update that will not install")
}
if dropped {
scheduleRegistryUpdatePass()
}
}

nonisolated static func stagedUpdateLoads(pluginId: String, in userPluginsDir: URL) -> Bool {
let directory = PluginInstaller.stagedUpdateDirectory(for: pluginId, in: userPluginsDir)
guard let bundleURL = try? PluginInstaller.findBundle(in: directory),
let bundle = Bundle(url: bundleURL) else { return false }
return (try? validateBundleVersions(bundle)) != nil
}
}
27 changes: 16 additions & 11 deletions apple/TablePro/Core/Plugins/PluginManager+Install.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,25 +84,30 @@ extension PluginManager {
release: release,
pluginId: existing.id,
bundleName: existing.url.lastPathComponent,
kits: Self.compatibleKits,
into: userPluginsDir,
progress: ticket.reportProgress
)
ticket.markInstalling()
// The next launch installs whatever build the staged bundle holds, whatever the manifest said.
guard Self.bundleBuild(at: stagedURL) > existing.build else {
removeStagedUpdate(pluginId: existing.id)
throw PluginError.installFailed(String(localized: "The downloaded plugin is not newer than the installed one."))
}
guard plugins.contains(where: { $0.id == existing.id }) else {
removeStagedUpdate(pluginId: existing.id)
throw PluginError.notFound
}
stagedPluginIds.insert(existing.id)
try recordStagedUpdate(at: stagedURL, replacing: existing)
}
}

// The next launch installs whatever build the staged bundle holds, whatever the manifest said.
func recordStagedUpdate(at stagedURL: URL, replacing existing: PluginEntry) throws {
guard Self.bundleBuild(at: stagedURL) > existing.build else {
removeStagedUpdate(pluginId: existing.id)
throw PluginError.installFailed(String(localized: "The downloaded plugin is not newer than the installed one."))
}
guard plugins.contains(where: { $0.id == existing.id }) else {
removeStagedUpdate(pluginId: existing.id)
throw PluginError.notFound
}
stagedPluginIds.insert(existing.id)
}

// One install per plugin at a time: a file and a registry download would overwrite each other's copy.
private func reserveInstall(of pluginId: String) throws {
func reserveInstall(of pluginId: String) throws {
guard !installsInFlight.contains(pluginId) else {
throw PluginError.installFailed(
String(localized: "Another install is already in progress for this plugin")
Expand Down
20 changes: 12 additions & 8 deletions apple/TablePro/Core/Plugins/PluginManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -510,37 +510,41 @@ final class PluginManager: ObservableObject {

nonisolated internal static let compatibleKits = minimumCompatiblePluginKitVersion...currentPluginKitVersion

// A plugin matches the build it ships with, so a beta app takes beta plugins whatever the update setting.
nonisolated internal static let registryChannel: UpdateChannel = Bundle.main.isPrerelease ? .beta : .stable
nonisolated internal static let registryChannel = UpdateChannel.plugins(ofAppVersion: Bundle.main.appVersion)

nonisolated internal static func isCompatibleKit(_ kit: Int) -> Bool {
compatibleKits.contains(kit)
}

// Bundle caches Info.plist per path, so a rejected plugin repaired in place still reports its old kit.
// A built-in plugin skips the architecture check: it ships inside the app, built for the app's own arch.
nonisolated internal static func validateBundleVersions(_ bundle: Bundle, source: PluginSource = .userInstalled) throws {
// kits is another app's range only for a build staged for the app update Sparkle downloaded.
nonisolated internal static func validateBundleVersions(
_ bundle: Bundle,
source: PluginSource = .userInstalled,
kits: ClosedRange<Int> = compatibleKits
) throws {
let info = infoPlist(at: bundle.bundleURL)
guard let version = info["TableProPluginKitVersion"] as? Int else {
throw PluginError.pluginOutdated(
pluginVersion: 0,
requiredVersion: currentPluginKitVersion
requiredVersion: kits.upperBound
)
}
if isCompatibleKit(version) {
if kits.contains(version) {
guard source != .builtIn else { return }
try validateArchitecture(at: bundle.bundleURL, info: info)
return
}
if version > currentPluginKitVersion {
if version > kits.upperBound {
throw PluginError.incompatibleVersion(
required: version,
current: currentPluginKitVersion
current: kits.upperBound
)
}
throw PluginError.pluginOutdated(
pluginVersion: version,
requiredVersion: currentPluginKitVersion
requiredVersion: kits.upperBound
)
}

Expand Down
34 changes: 34 additions & 0 deletions apple/TablePro/Core/Services/Infrastructure/SoftwareUpdater.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ final class SoftwareUpdater: ObservableObject {
private var installOnQuitNow: (() -> Void)?

@Published private(set) var phase: AppUpdatePhase = .idle
@Published private(set) var preparedUpdate: PreparedAppUpdate?
@Published private(set) var canCheckForUpdates = false
@Published private(set) var automaticallyChecksForUpdates = true
@Published private(set) var automaticallyDownloadsUpdates = true
Expand Down Expand Up @@ -104,6 +105,15 @@ final class SoftwareUpdater: ObservableObject {
phase = next
}

fileprivate func recordUpdatePrepared(_ item: SUAppcastItem) {
guard let update = PreparedAppUpdate(sparkleVersion: item.versionString, displayVersion: item.displayVersionString) else {
Self.logger.error("Update \(item.versionString, privacy: .public) has no numeric build")
return
}
guard update != preparedUpdate else { return }
preparedUpdate = update
}

fileprivate func recordReadyToInstallOnQuit(_ release: UpdateRelease, install: @escaping () -> Void) {
installOnQuitNow = install
apply(.readyToInstallOnQuit(release))
Expand All @@ -123,12 +133,21 @@ final class SoftwareUpdater: ObservableObject {
let nsError = error as NSError
guard nsError.code != Int(SUError.noUpdateError.rawValue) else { return }
installOnQuitNow = nil
preparedUpdate = nil
// A relaunch handed to Sparkle never quit, so its approval must not cover a later Quit.
AppRelauncher.shared.terminationWasCancelled()
apply(.updateAborted)
Self.logger.error("Update driver aborted: \(nsError.domain, privacy: .public) \(nsError.code, privacy: .public)")
}

// Skipping an update Sparkle already prepared cancels its install and reports no error, so no abort follows.
fileprivate func recordPreparedUpdateSkipped() {
installOnQuitNow = nil
preparedUpdate = nil
apply(.updateAborted)
Self.logger.info("The prepared update was skipped")
}

private func observeUpdater() {
let updater = controller.updater
func mirror<Value>(_ keyPath: KeyPath<SPUUpdater, Value>) -> NSKeyValueObservation {
Expand Down Expand Up @@ -183,6 +202,21 @@ extension SoftwareUpdaterDelegate: SPUUpdaterDelegate {
owner?.recordUpdateAborted(error: error)
}

func updater(
_ updater: SPUUpdater,
userDidMake choice: SPUUserUpdateChoice,
forUpdate updateItem: SUAppcastItem,
state: SPUUserUpdateState
) {
guard choice == .skip, state.stage == .installing else { return }
owner?.recordPreparedUpdateSkipped()
}

// Before willInstallUpdateOnQuit for an update downloaded on its own, and the only call for one chosen in Sparkle's window.
func updater(_ updater: SPUUpdater, didExtractUpdate item: SUAppcastItem) {
owner?.recordUpdatePrepared(item)
}

// The update Sparkle downloaded on its own; returning true keeps the handler for Relaunch to Update.
func updater(
_ updater: SPUUpdater,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ internal extension UpdateChannel {
}
}

// A plugin matches the build it ships with, so a prerelease app takes beta plugins whatever the update setting.
static func plugins(ofAppVersion version: String) -> UpdateChannel {
version.contains("-") ? .beta : .stable
}

func accepts(_ releaseChannel: String) -> Bool {
switch self {
case .stable: releaseChannel == Self.stable.rawValue
Expand Down
Loading
Loading