The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
Automatic updates, the way Arc does them
Victor12fa95ef954c
diff --git a/.github/release-notes-unsigned.md b/.github/release-notes-unsigned.mdindex 9119c72..eaff76f 100644--- a/.github/release-notes-unsigned.md+++ b/.github/release-notes-unsigned.md@@ -6,7 +6,7 @@curl -fsSL https://raw.githubusercontent.com/VictorKildahl/cra/main/scripts/install.sh | bash```-It puts Cra in your Applications folder and opens it, with no security prompts. Run the same line again any time to update.+It puts Cra in your Applications folder and opens it, with no security prompts. From then on Cra keeps itself up to date.**Or download `Cra.dmg` below**diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 7e137e6..f0c41e9 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -11,6 +11,8 @@ name: Release# APPLE_ID Apple ID used for notarization# APPLE_TEAM_ID 10-character team id# APPLE_APP_PASSWORD app-specific password for that Apple ID+# SPARKLE_PRIVATE_KEY EdDSA key that signs updates (generate_keys --account cra -x),+# required: installed copies only accept updates it signedon:push:@@ -74,6 +76,7 @@ jobs:APPLE_ID: ${{ secrets.APPLE_ID }}APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}APPLE_APP_PASSWORD: ${{ secrets.APPLE_APP_PASSWORD }}+ SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}run: scripts/release.sh- name: Upload artifactsdiff --git a/Package.swift b/Package.swiftindex 9aa45b2..6ebb8f6 100644--- a/Package.swift+++ b/Package.swift@@ -19,6 +19,10 @@ let cefLinkerFlags: [String] = ["-L\(cefRoot)/build/libcef_dll_wrapper",]+// Sparkle, the updater framework Arc ships, lives in vendor/sparkle (scripts/fetch-sparkle.sh);+// scripts/build.sh copies Sparkle.framework into Cra.app/Contents/Frameworks.+let sparkleRoot = "\(Context.packageDirectory)/vendor/sparkle"+let package = Package(name: "Cra",platforms: [.macOS(.v14)],@@ -58,7 +62,9 @@ let package = Package(name: "Cra",dependencies: ["CraCEF"],path: "Sources/Cra",- swiftSettings: [.unsafeFlags(["-Onone"], .when(configuration: .debug))]+ swiftSettings: [.unsafeFlags(["-F", sparkleRoot]), .unsafeFlags(["-Onone"], .when(configuration: .debug))],+ linkerSettings: [.unsafeFlags(["-F", sparkleRoot, "-framework", "Sparkle",+ "-Xlinker", "-rpath", "-Xlinker", "@executable_path/../Frameworks"])]),],swiftLanguageVersions: [.v5],diff --git a/README.md b/README.mdindex 722f5d2..db37e0c 100644--- a/README.md+++ b/README.md@@ -19,8 +19,8 @@ Needs macOS 14 or later on Apple silicon.curl -fsSL https://raw.githubusercontent.com/VictorKildahl/cra/main/scripts/install.sh | bash-It puts Cra in your Applications folder and opens it, with no security prompts. Run-the same line again any time to update.+It puts Cra in your Applications folder and opens it, with no security prompts. From+then on Cra keeps itself up to date (Cra ▸ Check for Updates…).**Or download [Cra.dmg](https://github.com/VictorKildahl/cra/releases/latest/download/Cra.dmg)**diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex 98a149f..bda8522 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -41,6 +41,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {installURLEventHandler()CraCEFRuntime.setChromeHosting(store.settings.chromeEngine)startContentBlocking()+ SoftwareUpdater.shared.start(app: self)buildMenus()NotificationCenter.default.addObserver(forName: .craKeyBindingsChanged, object: nil, queue: .main) { [weak self] _ inTask { @MainActor in self?.buildMenus() }@@ -55,7 +56,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {autoArchiveTimer = Timer.scheduledTimer(withTimeInterval: 1800, repeats: true) { [weak self] _ inTask { @MainActor in self?.store.runAutoArchive() }}- NSApp.activate(ignoringOtherApps: true)+ // A restart into an update while the user was away leaves the front app alone.+ if !SoftwareUpdater.shared.launchedByAutoUpdate { NSApp.activate(ignoringOtherApps: true) }DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.installURLEventHandler() }// Extension welcome pages and chrome.tabs.create land in Cra, not in a Chrome window.// --load-extension extensions count as freshly installed on every launch, so their@@ -183,6 +185,24 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {func applicationWillShutdown() { store.saveAll() }+ /// Sparkle quits Cra to install an update and starts it again: no quit confirmation.+ func prepareForUpdateRelaunch() {+ isRelaunching = true+ store.saveAll()+ }++ /// Why an automatic update restart should wait (Arc: downloads in progress,+ /// window_dialog_sheet_visible, active tabs). Little Windows go to the Library on quit,+ /// so an open one waits too.+ func autoUpdateBlocker() -> String? {+ if main.overlay.toasts.contains(where: { $0.state == CraDownloadState.inProgress.rawValue }) { return "a download is in progress" }+ if NSApp.modalWindow != nil || NSApp.windows.contains(where: { $0.isVisible && $0.attachedSheet != nil }) { return "a dialog is open" }+ if !littleWindows.isEmpty { return "a Little Window is open" }+ if PictureInPictureChrome.shared.isPlaying { return "Picture in Picture is playing" }+ if main.isImportVisible { return "the import is open" }+ return nil+ }+private func confirmQuit() -> Bool {let alert = NSAlert()alert.messageText = "Quit Cra?"@@ -629,6 +649,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {appMenu.addItem(setDefault)appMenu.addItem(.separator())appMenu.addItem(item("importData"))+ let update = NSMenuItem(title: "Check for Updates…", action: #selector(SoftwareUpdater.checkForUpdates(_:)), keyEquivalent: "")+ update.target = SoftwareUpdater.shared+ appMenu.addItem(update)appMenu.addItem(.separator())appMenu.addItem(std("Hide Cra", #selector(NSApplication.hide(_:)), "h"))appMenu.addItem(std("Hide Others", #selector(NSApplication.hideOtherApplications(_:)), "h", [.command, .option]))diff --git a/Sources/Cra/Services/SoftwareUpdater.swift b/Sources/Cra/Services/SoftwareUpdater.swiftnew file mode 100644index 0000000..79d27d2--- /dev/null+++ b/Sources/Cra/Services/SoftwareUpdater.swift@@ -0,0 +1,389 @@+import AppKit+import IOKit.pwr_mgt+import Observation+import Sparkle++/// Arc's SoftwareUpdaterClient, rebuilt from the same parts (docs/arc-reverse-engineering.md,+/// "Software updates"): Sparkle 2 with an EdDSA-signed appcast, checked every 8 hours,+/// downloaded in the background and installed when Cra quits. A custom user driver+/// replaces Sparkle's windows with the updater window (Check for Updates…) and the+/// sidebar banners, and a downloaded update installs itself once the user is away, the+/// way Arc's auto-update restarts Arc.+@MainActor+@Observable+final class SoftwareUpdater: NSObject {+ static let shared = SoftwareUpdater()++ struct Release: Equatable {+ var version: String+ var build: String+ var notesHTML: String?++ init(_ item: SUAppcastItem) {+ version = item.displayVersionString+ build = item.versionString+ notesHTML = item.itemDescription+ }+ }++ /// What the updater window shows (Arc's UpdaterWindowView).+ enum Phase: Equatable {+ case idle+ case checking+ case upToDate+ case found(Release, downloaded: Bool)+ case downloading(received: UInt64, expected: UInt64)+ case extracting+ case readyToInstall+ case installing+ case failed(String)+ }++ private(set) var phase: Phase = .idle+ /// Downloaded and waiting for a restart: "An update is ready!" in the sidebar.+ private(set) var readyRelease: Release?+ /// Found by a background check while automatic updates are off.+ private(set) var foundRelease: Release?+ /// The first launch after an update: "Cra Updated!" with See What's New.+ private(set) var updatedTo: String?+ /// The close button on a banner hides it until the next launch (Arc counts these in+ /// autoUpdateBannerDismissalCount).+ var bannerDismissed = false+ /// Arc's "Automatically update my Arc" (Dia: "Automatically update Dia"): download in+ /// the background and restart while the user is away. Off, a found update only shows a+ /// banner. Stored by Sparkle as SUAutomaticallyUpdate.+ var automaticallyUpdates = true {+ didSet { updater?.automaticallyDownloadsUpdates = automaticallyUpdates }+ }+ private(set) var isAvailable = false+ /// This launch came from an automatic restart, so it should not take focus.+ private(set) var launchedByAutoUpdate = false++ static let releaseNotesURL = "https://crabrowser.app/release-notes"+ static let downloadURL = "https://github.com/VictorKildahl/cra/releases/latest"++ @ObservationIgnored private var updater: SPUUpdater?+ @ObservationIgnored private weak var app: AppDelegate?+ @ObservationIgnored private var window: UpdaterWindowController?+ @ObservationIgnored private var installNow: (() -> Void)?+ @ObservationIgnored private var choiceReply: ((SPUUserUpdateChoice) -> Void)?+ @ObservationIgnored private var cancellation: (() -> Void)?+ @ObservationIgnored private var acknowledgement: (() -> Void)?+ @ObservationIgnored private var autoRestartTimer: Timer?+ @ObservationIgnored private var inactiveSince: Date?++ private enum Keys {+ static let pendingBuild = "updateSummaryPendingBuild"+ static let autoRelaunch = "automaticUpdateWillRelaunchApp"+ }++ /// Arc's feed override: a feed URL for testing (e.g. a local appcast).+ private var feedOverride: String? { ProcessInfo.processInfo.environment["CRA_UPDATE_FEED"] }+ /// Shortens every wait of the automatic restart to this many seconds, for testing.+ private var quickRestart: TimeInterval? { ProcessInfo.processInfo.environment["CRA_UPDATE_IDLE_SECONDS"].flatMap(TimeInterval.init) }++ func start(app: AppDelegate) {+ self.app = app+ let d = UserDefaults.standard+ launchedByAutoUpdate = d.bool(forKey: Keys.autoRelaunch)+ d.removeObject(forKey: Keys.autoRelaunch)+ if let build = d.string(forKey: Keys.pendingBuild) {+ d.removeObject(forKey: Keys.pendingBuild)+ if build == Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String {+ updatedTo = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String+ }+ }+ // Dev builds carry no feed (scripts/build.sh drops SUFeedURL outside releases), so they+ // never replace themselves with a release.+ guard !ProcessInfo.processInfo.arguments.contains("--disable-software-updater"),+ feedOverride != nil || Bundle.main.object(forInfoDictionaryKey: "SUFeedURL") != nil else { return }+ let u = SPUUpdater(hostBundle: .main, applicationBundle: .main, userDriver: self, delegate: self)+ do {+ try u.start()+ } catch {+ NSLog("Cra: software updater did not start: %@", error.localizedDescription)+ return+ }+ updater = u+ isAvailable = true+ automaticallyUpdates = u.automaticallyDownloadsUpdates+ let nc = NotificationCenter.default+ nc.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.inactiveSince = Date() }+ }+ nc.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.inactiveSince = nil }+ }+ if !NSApp.isActive { inactiveSince = Date() }+ }++ // MARK: Actions++ @objc func checkForUpdates(_ sender: Any?) {+ // A downloaded update is one click from installing; Sparkle would only resume it.+ if readyRelease != nil {+ phase = .readyToInstall+ showWindow()+ return+ }+ if case .found = phase, choiceReply != nil {+ showWindow()+ return+ }+ updater?.checkForUpdates()+ }++ /// Restart into the downloaded update (the banner, Install and Relaunch).+ func installAndRelaunch() {+ if let reply = choiceReply {+ choiceReply = nil+ switch phase {+ case .readyToInstall, .found(_, downloaded: true): app?.prepareForUpdateRelaunch()+ default: break // .install on an update that isn't downloaded starts the download+ }+ reply(.install)+ } else if let install = installNow {+ // Sparkle accepts the block again if the quit gets cancelled (a page's beforeunload).+ phase = .installing+ app?.prepareForUpdateRelaunch()+ install()+ }+ }++ /// The banner for an update found while automatic updates are off.+ func showFoundUpdate() {+ guard let r = foundRelease else { return }+ phase = .found(r, downloaded: false)+ showWindow()+ }++ /// Later, Cancel, Close and the window's close button.+ func dismissWindowAction(closeWindow: Bool = true) {+ if let reply = choiceReply {+ choiceReply = nil+ foundRelease = nil+ reply(.dismiss)+ }+ cancellation?()+ cancellation = nil+ acknowledgement?()+ acknowledgement = nil+ if readyRelease == nil { phase = .idle }+ if closeWindow { window?.close() }+ }++ /// The banner's close button. A found update is answered "later" so Sparkle goes back+ /// to its schedule; the others hide until the next launch.+ func dismissBanner() {+ if readyRelease != nil {+ bannerDismissed = true+ } else if foundRelease != nil {+ dismissWindowAction()+ } else {+ updatedTo = nil+ }+ }++ func openReleaseNotes() {+ updatedTo = nil+ guard let app else { return }+ app.store.createTab(url: Self.releaseNotesURL, select: true)+ app.main.showWindow(nil)+ }++ func openDownloadPage() {+ dismissWindowAction()+ if let u = URL(string: Self.downloadURL) { NSWorkspace.shared.open(u) }+ }++ private func showWindow() {+ if window == nil { window = UpdaterWindowController(updater: self) }+ window?.showWindow(nil)+ window?.window?.makeKeyAndOrderFront(nil)+ NSApp.activate(ignoringOtherApps: true)+ }++ func windowDidClose() {+ switch phase {+ case .checking, .upToDate, .found, .failed, .downloading: dismissWindowAction(closeWindow: false)+ default: break+ }+ }++ // MARK: Automatic restart++ /// Arc restarts into a downloaded update by itself (auto_update_queued, time_since_last_active,+ /// ignore_user_idle, active_tabs_blocked_update, window_dialog_sheet_visible). Its timing comes+ /// from remote flags (auto-update-inactivity-delay-in-seconds, auto-update-required-idle-+ /// duration-in-seconds); Cra waits until the user is away: Cra in the background for 10+ /// minutes and no input for 2, or no input at all for 30.+ private func scheduleAutoRestart() {+ autoRestartTimer?.invalidate()+ autoRestartTimer = Timer.scheduledTimer(withTimeInterval: max(1, min(60, quickRestart ?? 60)), repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.considerAutoRestart() }+ }+ }++ private func considerAutoRestart() {+ guard automaticallyUpdates, installNow != nil, let app else { return }+ let idle = CGEventSource.secondsSinceLastEventType(.combinedSessionState, eventType: CGEventType(rawValue: ~0)!)+ let background = inactiveSince.map { Date().timeIntervalSince($0) } ?? 0+ let q = quickRestart+ guard (background >= q ?? 600 && idle >= q ?? 120) || idle >= q ?? 1800 else { return }+ if let reason = app.autoUpdateBlocker() ?? (Self.holdsPowerAssertion ? "a page is playing media" : nil) {+ NSLog("Cra: automatic update waits: %@", reason)+ return+ }+ NSLog("Cra: restarting to install the downloaded update")+ UserDefaults.standard.set(true, forKey: Keys.autoRelaunch)+ installAndRelaunch()+ }++ /// Chromium holds a power assertion while a page plays audio or video and while a+ /// download runs (PowerSaveBlocker), which stands in for Arc's per-tab media check.+ private static var holdsPowerAssertion: Bool {+ var byProcess: Unmanaged<CFDictionary>?+ guard IOPMCopyAssertionsByProcess(&byProcess) == kIOReturnSuccess,+ let all = byProcess?.takeRetainedValue() as? [NSNumber: [[String: Any]]] else { return false }+ return !(all[NSNumber(value: ProcessInfo.processInfo.processIdentifier)] ?? []).isEmpty+ }+}++// MARK: - SPUUpdaterDelegate++extension SoftwareUpdater: SPUUpdaterDelegate {+ func feedURLString(for updater: SPUUpdater) -> String? { feedOverride }++ /// The update is downloaded and extracted. Keeping the block lets the banner and the+ /// automatic restart install it now; otherwise it installs when Cra quits.+ func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem,+ immediateInstallationBlock: @escaping () -> Void) -> Bool {+ installNow = immediateInstallationBlock+ readyRelease = Release(item)+ foundRelease = nil+ bannerDismissed = false+ UserDefaults.standard.set(item.versionString, forKey: Keys.pendingBuild)+ scheduleAutoRestart()+ return true+ }++ func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) {+ UserDefaults.standard.set(item.versionString, forKey: Keys.pendingBuild)+ }++ func updater(_ updater: SPUUpdater, didAbortWithError error: Error) {+ NSLog("Cra: software update stopped: %@", error.localizedDescription)+ }+}++// MARK: - SPUUserDriver++extension SoftwareUpdater: SPUUserDriver {+ /// Never asked: SUEnableAutomaticChecks is in Info.plist (Arc logs the same).+ func show(_ request: SPUUpdatePermissionRequest, reply: @escaping (SUUpdatePermissionResponse) -> Void) {+ reply(SUUpdatePermissionResponse(automaticUpdateChecks: true, sendSystemProfile: false))+ }++ func showUserInitiatedUpdateCheck(cancellation: @escaping () -> Void) {+ self.cancellation = cancellation+ phase = .checking+ showWindow()+ }++ func showUpdateFound(with appcastItem: SUAppcastItem, state: SPUUserUpdateState,+ reply: @escaping (SPUUserUpdateChoice) -> Void) {+ cancellation = nil+ choiceReply = reply+ let release = Release(appcastItem)+ phase = .found(release, downloaded: state.stage != .notDownloaded)+ if state.userInitiated {+ showWindow()+ } else {+ foundRelease = release+ bannerDismissed = false+ }+ }++ func showUpdateReleaseNotes(with downloadData: SPUDownloadData) {+ let html = String(data: downloadData.data, encoding: .utf8)+ if case .found(var r, let downloaded) = phase, let html {+ r.notesHTML = html+ phase = .found(r, downloaded: downloaded)+ }+ }++ func showUpdateReleaseNotesFailedToDownloadWithError(_ error: Error) {}++ func showUpdateNotFoundWithError(_ error: Error, acknowledgement: @escaping () -> Void) {+ cancellation = nil+ self.acknowledgement = acknowledgement+ phase = .upToDate+ showWindow()+ }++ func showUpdaterError(_ error: Error, acknowledgement: @escaping () -> Void) {+ NSLog("Cra: software update error: %@", error.localizedDescription)+ cancellation = nil+ // Background checks fail quietly (offline, GitHub down); only a window the user+ // is looking at reports it.+ guard window?.window?.isVisible == true else { acknowledgement(); return }+ self.acknowledgement = acknowledgement+ phase = .failed(error.localizedDescription)+ }++ func showDownloadInitiated(cancellation: @escaping () -> Void) {+ self.cancellation = cancellation+ phase = .downloading(received: 0, expected: 0)+ }++ func showDownloadDidReceiveExpectedContentLength(_ expectedContentLength: UInt64) {+ phase = .downloading(received: 0, expected: expectedContentLength)+ }++ func showDownloadDidReceiveData(ofLength length: UInt64) {+ if case .downloading(let received, let expected) = phase {+ phase = .downloading(received: received + length, expected: max(expected, received + length))+ }+ }++ func showDownloadDidStartExtractingUpdate() {+ cancellation = nil+ phase = .extracting+ }++ func showExtractionReceivedProgress(_ progress: Double) {}++ func showReady(toInstallAndRelaunch reply: @escaping (SPUUserUpdateChoice) -> Void) {+ choiceReply = reply+ phase = .readyToInstall+ }++ func showInstallingUpdate(withApplicationTerminated applicationTerminated: Bool,+ retryTerminatingApplication: @escaping () -> Void) {+ phase = .installing+ app?.prepareForUpdateRelaunch()+ }++ func showUpdateInstalledAndRelaunched(_ relaunched: Bool, acknowledgement: @escaping () -> Void) {+ acknowledgement()+ }++ func showUpdateInFocus() {+ if phase != .idle { showWindow() }+ }++ func dismissUpdateInstallation() {+ choiceReply = nil+ cancellation = nil+ acknowledgement = nil+ guard readyRelease == nil else { return }+ phase = .idle+ window?.close()+ }+}++extension SoftwareUpdater: NSMenuItemValidation {+ func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {+ isAvailable && (readyRelease != nil || updater?.canCheckForUpdates == true || choiceReply != nil)+ }+}diff --git a/Sources/Cra/UI/Settings/AdvancedPane.swift b/Sources/Cra/UI/Settings/AdvancedPane.swiftindex bcfbe08..c767655 100644--- a/Sources/Cra/UI/Settings/AdvancedPane.swift+++ b/Sources/Cra/UI/Settings/AdvancedPane.swift@@ -3,16 +3,19 @@ import SwiftUI/// Dia's Advanced pane is a form: "General:" (Automatically update), "Sounds:", "Address Bar:"/// (a routing popup) and "When quitting Dia:" (Warn before quitting + a restore popup). Cra-/// has no updater or chat sounds; its page engine, search engine, import and version rows-/// live here instead.+/// has no chat sounds; its page engine, search engine, import and version rows live here+/// instead.struct AdvancedPane: View {let actions: SettingsActions@Environment(SidebarStore.self) private var storevar body: some View {@Bindable var store = store+ @Bindable var updater = SoftwareUpdater.sharedSettingsFormPane {SettingsFormRow(label: "General:") {+ SettingsCheckbox(title: "Automatically update Cra", isOn: $updater.automaticallyUpdates)+ .disabled(!updater.isAvailable)SettingsCheckbox(title: "Chrome engine for pages (extensions, Chrome DevTools)", isOn: $store.settings.chromeEngine)Text("Restart Cra to apply an engine change.").font(.system(size: 11)).foregroundStyle(.secondary)}diff --git a/Sources/Cra/UI/Sidebar/SidebarRootView.swift b/Sources/Cra/UI/Sidebar/SidebarRootView.swiftindex 03dbea7..56894ac 100644--- a/Sources/Cra/UI/Sidebar/SidebarRootView.swift+++ b/Sources/Cra/UI/Sidebar/SidebarRootView.swift@@ -33,6 +33,8 @@ struct SidebarRootView: View {}.frame(maxHeight: .infinity, alignment: .top).clipped()+ UpdateBanner(palette: palette)+ .padding(.horizontal, 8)// Arc's list viewport ends 50pt above the window bottom; the dock sits centred in that band.SpaceDock(palette: palette).padding(.horizontal, 10)diff --git a/Sources/Cra/UI/Updates/UpdateBanner.swift b/Sources/Cra/UI/Updates/UpdateBanner.swiftnew file mode 100644index 0000000..9ccbf5d--- /dev/null+++ b/Sources/Cra/UI/Updates/UpdateBanner.swift@@ -0,0 +1,74 @@+import SwiftUI++/// Arc's software-update sidebar banners (SidebarBanner `updateAvailable` and `updateSummary`),+/// above the space dock. Copy from Arc 1.170's strings: "An update is ready!" / "Click to+/// restart", "New Arc Version Available", and after the restart "Updated!" with "See What's+/// New". The banner never appeared on this Mac during the analysis, so its look follows+/// Cra's sidebar cards rather than a capture.+struct UpdateBanner: View {+ let palette: SpacePalette+ @State private var hover = false+ @State private var hoverClose = false++ private struct Content {+ var symbol: String+ var title: String+ var subtitle: String+ var action: @MainActor () -> Void+ }++ @MainActor private var content: Content? {+ let u = SoftwareUpdater.shared+ if u.readyRelease != nil, !u.bannerDismissed {+ return Content(symbol: "arrow.down.circle.fill", title: "An update is ready!", subtitle: "Click to restart") { u.installAndRelaunch() }+ }+ if let r = u.foundRelease, !u.bannerDismissed {+ return Content(symbol: "arrow.down.circle", title: "New Cra Version Available", subtitle: "Cra \(r.version)") { u.showFoundUpdate() }+ }+ if u.updatedTo != nil {+ return Content(symbol: "heart.circle.fill", title: "Cra Updated!", subtitle: "See What's New") { u.openReleaseNotes() }+ }+ return nil+ }++ var body: some View {+ Group {+ if let c = content {+ HStack(spacing: 10) {+ Image(systemName: c.symbol)+ .font(.system(size: 20))+ .foregroundStyle(palette.textPrimary)+ VStack(alignment: .leading, spacing: 1) {+ Text(c.title).font(.system(size: 13, weight: .semibold))+ Text(c.subtitle).font(.system(size: 12)).foregroundStyle(palette.textSecondary)+ }+ .lineLimit(1)+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 12)+ .frame(height: 52)+ .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(hover ? palette.selectedFill : palette.hoverFill))+ .overlay(alignment: .topTrailing) {+ if hover {+ Image(systemName: "xmark")+ .font(.system(size: 9, weight: .bold))+ .foregroundStyle(palette.textSecondary)+ .frame(width: 18, height: 18)+ .background(Circle().fill(hoverClose ? palette.hoverFill : .clear))+ .contentShape(Circle())+ .onHover { hoverClose = $0 }+ .onTapGesture { SoftwareUpdater.shared.dismissBanner() }+ .padding(6)+ .help("Dismiss")+ }+ }+ .contentShape(RoundedRectangle(cornerRadius: 10, style: .continuous))+ .onHover { hover = $0 }+ .onTapGesture { c.action() }+ .padding(.top, 8)+ .transition(.move(edge: .bottom).combined(with: .opacity))+ }+ }+ .animation(.easeInOut(duration: 0.25), value: content?.title)+ }+}diff --git a/Sources/Cra/UI/Updates/UpdaterWindow.swift b/Sources/Cra/UI/Updates/UpdaterWindow.swiftnew file mode 100644index 0000000..ea98d38--- /dev/null+++ b/Sources/Cra/UI/Updates/UpdaterWindow.swift@@ -0,0 +1,235 @@+import AppKit+import SwiftUI++/// Arc's UpdaterWindowController: a small window without a title that opens for Check for+/// Updates… Measured on Arc 1.170 in its up-to-date state (window capture and AX tree, 26 Oct):+/// 270 × 342, window background, the app icon 64 pt in an 84 pt frame at y 53, the name in+/// 24 pt bold (frame y 147, 30 tall), the version 11 pt (y 175) and the status line 13 pt+/// (y 209) in white 50%, and one 170 × 48 button at y 256, 38 above the bottom, radius 6+/// (continuous, fitted to the corner's anti-aliasing), filled with UpdaterButtonBackgroundColor+/// (white, black in dark mode), with a 13 pt bold label. The other states never showed on this+/// Mac and follow the same layout.+final class UpdaterWindowController: NSWindowController, NSWindowDelegate {+ private weak var updater: SoftwareUpdater?++ init(updater: SoftwareUpdater) {+ self.updater = updater+ let host = NSHostingController(rootView: UpdaterWindowView(updater: updater))+ host.sizingOptions = [.preferredContentSize]+ // Content runs under the transparent title bar, as in Arc.+ host.safeAreaRegions = []+ let w = NSWindow(contentViewController: host)+ w.styleMask = [.titled, .closable, .miniaturizable, .fullSizeContentView]+ w.titlebarAppearsTransparent = true+ w.titleVisibility = .hidden+ w.title = "Software Update"+ w.isReleasedWhenClosed = false+ w.standardWindowButton(.zoomButton)?.isEnabled = false+ super.init(window: w)+ w.delegate = self+ w.center()+ }++ required init?(coder: NSCoder) { fatalError() }++ func windowWillClose(_ notification: Notification) {+ MainActor.assumeIsolated { updater?.windowDidClose() }+ }+}++struct UpdaterWindowView: View {+ let updater: SoftwareUpdater++ private var current: String {+ let info = Bundle.main.infoDictionary+ return "\(info?["CFBundleShortVersionString"] as? String ?? "") (\(info?["CFBundleVersion"] as? String ?? ""))"+ }++ var body: some View {+ VStack(spacing: 0) {+ Image(nsImage: NSApp.applicationIconImage)+ .resizable()+ .frame(width: 64, height: 64)+ .padding(10)+ .padding(.top, 53)+ Text(title)+ .font(.system(size: 24, weight: .bold))+ .frame(height: 30)+ .padding(.top, 10)+ Text(subtitle)+ .font(.system(size: 11))+ .foregroundStyle(Color(nsColor: .updaterSecondary))+ .frame(height: 16)+ .padding(.top, -2)+ content+ }+ .frame(width: 270)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.bottom, 38)+ }++ private var title: String {+ if case .found(let r, _) = updater.phase { return "Cra \(r.version)" }+ return "Cra"+ }++ private var subtitle: String {+ if case .found = updater.phase { return "You have \(current)" }+ return current+ }++ @ViewBuilder private var content: some View {+ switch updater.phase {+ case .idle, .checking:+ status("Checking for updates…")+ UpdaterButton(title: "Cancel") { updater.dismissWindowAction() }+ case .upToDate:+ status("Your browser is up to date")+ UpdaterButton(title: "Close") { updater.dismissWindowAction() }+ case .found(let r, let downloaded):+ if let html = r.notesHTML, !html.isEmpty {+ ReleaseNotesView(html: html)+ .padding(.top, 18)+ } else {+ status("A new version is available")+ }+ UpdaterButton(title: downloaded ? "Install and Relaunch" : "Download") { updater.installAndRelaunch() }+ LaterButton(title: "Later") { updater.dismissWindowAction() }+ case .downloading(let received, let expected):+ progress(expected > 0 ? Double(received) / Double(expected) : nil,+ expected > 0 ? "\(Self.bytes(received)) of \(Self.bytes(expected))" : "Downloading…")+ UpdaterButton(title: "Cancel") { updater.dismissWindowAction() }+ case .extracting:+ progress(nil, "Preparing update…")+ UpdaterButton(title: "Install and Relaunch") {}.disabled(true)+ case .readyToInstall:+ status("Ready to Install")+ UpdaterButton(title: "Install and Relaunch") { updater.installAndRelaunch() }+ case .installing:+ progress(nil, "Installing update…")+ UpdaterButton(title: "Install and Relaunch") {}.disabled(true)+ case .failed(let message):+ status(message)+ UpdaterButton(title: "Download Manually") { updater.openDownloadPage() }+ LaterButton(title: "Close") { updater.dismissWindowAction() }+ }+ }++ private func status(_ text: String) -> some View {+ Text(text)+ .font(.system(size: 13))+ .foregroundStyle(Color(nsColor: .updaterSecondary))+ .multilineTextAlignment(.center)+ .frame(width: 208)+ .frame(minHeight: 18)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.top, 18)+ .padding(.bottom, 10)+ }++ private func progress(_ value: Double?, _ label: String) -> some View {+ VStack(spacing: 6) {+ if let value { ProgressView(value: value) } else { ProgressView().progressViewStyle(.linear) }+ Text(label).font(.system(size: 11)).foregroundStyle(Color(nsColor: .updaterSecondary)).monospacedDigit()+ }+ .controlSize(.small)+ .frame(width: 170)+ .padding(.top, 18)+ .padding(.bottom, 10)+ }++ private static func bytes(_ n: UInt64) -> String {+ ByteCountFormatter.string(fromByteCount: Int64(n), countStyle: .file)+ }+}++/// The wide button.+private struct UpdaterButton: View {+ let title: String+ let action: () -> Void++ var body: some View {+ Button(title, action: action)+ .buttonStyle(UpdaterButtonStyle())+ .accessibilityLabel(title)+ .keyboardShortcut(.defaultAction)+ .padding(.top, 19)+ }+}++/// Arc's UpdaterButtonBackgroundColor with a faint shadow; the label is white ≈80% in dark mode.+private struct UpdaterButtonStyle: ButtonStyle {+ @Environment(\.isEnabled) private var enabled++ func makeBody(configuration: Configuration) -> some View {+ let shape = RoundedRectangle(cornerRadius: 6, style: .continuous)+ configuration.label+ .font(.system(size: 13, weight: .bold))+ .foregroundStyle(.primary.opacity(enabled ? 0.94 : 0.4))+ .frame(width: 170, height: 48)+ .background(shape.fill(Color(nsColor: .updaterButton)).shadow(color: .black.opacity(0.1), radius: 5))+ .contentShape(shape)+ .opacity(configuration.isPressed ? 0.75 : 1)+ }+}++/// Arc: "remind me to download and install the update later".+private struct LaterButton: View {+ let title: String+ let action: () -> Void++ var body: some View {+ Button(title, action: action)+ .buttonStyle(.plain)+ .font(.system(size: 13))+ .foregroundStyle(Color(nsColor: .updaterSecondary))+ .keyboardShortcut(.cancelAction)+ .padding(.top, 12)+ .padding(.bottom, -12)+ }+}++/// Arc's ReleaseNotesView: the appcast item's HTML with Arc's style (-apple-system 12px,+/// list rows 20px, links #458AFF).+private struct ReleaseNotesView: View {+ let html: String++ var body: some View {+ ScrollView {+ Text(Self.render(html))+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(10)+ }+ .frame(width: 230, height: 150)+ .background(RoundedRectangle(cornerRadius: 8, style: .continuous).fill(Color.primary.opacity(0.05)))+ }++ private static func render(_ html: String) -> AttributedString {+ let dark = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua+ let styled = """+ <style>+ body { font-family: -apple-system, BlinkMacSystemFont; font-size: 12px; color: \(dark ? "#fff" : "rgb(20, 20, 20)"); }+ li { line-height: 20px; }+ a, a:visited { color: #458AFF; }+ </style>+ """ + html+ guard let data = styled.data(using: .utf8),+ let s = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html,+ .characterEncoding: String.Encoding.utf8.rawValue],+ documentAttributes: nil),+ let a = try? AttributedString(s, including: \.appKit) else { return AttributedString(html) }+ return a+ }+}++private extension NSColor {+ /// The version and status lines: white 50% in dark mode (Arc measures 0.50, a touch under+ /// secondaryLabelColor's 0.55).+ static let updaterSecondary = NSColor(name: nil) { appearance in+ NSColor(white: appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? 1 : 0, alpha: 0.5)+ }+ static let updaterButton = NSColor(name: "UpdaterButtonBackgroundColor") { appearance in+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? .black : .white+ }+}diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex 5bb5666..40c03e3 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -1159,6 +1159,8 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMreturn true}+ var isImportVisible: Bool { importWindow?.window?.isVisible == true }+/// Close whatever transient UI is up (used by cra://dismiss for scripting).func dismissTransientUI() {if let sheet = window?.attachedSheet { window?.endSheet(sheet) }diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex 4b81114..0b1317d 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -1099,3 +1099,52 @@ Dark mode only; light mode was not observed.`applicationShouldTerminate`, skipped on engine relaunch), `autoArchiveEnabled`.- [U] Light-mode colours, the popup option lists, the Shortcuts details pane, hover states(the source list has none), and the "Advanced Settings" ad-block dialog were not opened.++## Software updates (Arc 1.170, 26 Oct 2026, static + one live check)+- [O] Arc bundles Sparkle 2.9.4 (Frameworks/Sparkle.framework, CFBundleShortVersionString 2.9.4). Info.plist:+ `SUFeedURL` https://releases.arc.net/updates.xml, `SUPublicEDKey` (EdDSA-signed archives), `SUEnableAutomaticChecks`,+ `SUAutomaticallyUpdate` (download in the background), `SUScheduledCheckInterval` 28800 (8 h). No `SURequireSignedFeed`.+- [O] Module `SoftwareUpdaterClient`: SoftwareUpdateManager (SPUUpdater + SPUUpdaterDelegate), `CustomUserDriver`+ (an SPUUserDriver in place of Sparkle's windows), UpdaterWindowController/UpdaterWindowView, UpdaterStatusView,+ ReleaseNotesView, SparkleVersionComparison, `--disable-software-updater`, `--fake-updater`, feed channels+ (release, release-candidate, canary, prototype, PR, a test feed at http://localhost:8889) via setUpdaterFeedOverride.+ Driver log lines name every SPUUserDriver callback; the permission request "should never be called, because we+ set SUEnableAutomaticChecks in Info.plist".+- [O] Window copy: "Checking for updates..." (Cancel), "Your browser is up to date" (Close), "A new version is+ available" (fallback title) with release notes and "Would you like to download …", a later button, Download /+ Install, "1kB of 100MB" progress, extracting label, "Ready to Install" + "Install and Relaunch", "Installing+ update...", errors with "Download manually". ReleaseNotesView CSS: -apple-system 12px, rgb(20,20,20) / white in+ dark, li line-height 20px, links #458AFF, margin 12px 8px 16px 0.+- [O] Check for Updates…, observed live (AX menu press, window-id capture): the Arc menu reads About Arc / Settings… /+ Share Arc / Set as Default Browser / Import from Another Browser… / Check for Updates… The up-to-date window is+ 270 × 342 with no title (traffic lights only), window background, the app icon 64 pt (84 pt AX frame at y 53, art+ x 109–160 y 69–120), "Arc" 24 pt bold label colour (frame y 147, 30 tall), "1.170.0 (89123)" 11 pt (y 175, 16+ tall), "Your browser is up to date" 13 pt (y 209, 208 wide), both white 50% in dark mode; "Close" button fill+ 170 × 48 at (50, 256), continuous radius ≈6 (fitted to the corner's anti-aliasing), a faint shadow, label 13 pt bold+ at white ≈80%. `UpdaterButtonBackgroundColor` asset: white, black in dark appearance. The other states were not+ reachable (Arc was current).+- [O] Sidebar banners (SidebarBanner module, AppData+SidebarBanner): `updateAvailable` "An update is ready!" / "Click+ to restart" (action "Restart and Update"), "New Arc Version Available", and after the restart `updateSummary`+ ("Updated!", "Update Complete!", "See What's New" opening the release notes; V2 with heart.circle.fill and the+ update-heart-animation Lottie). Defaults: `autoUpdateBannerDismissalCount` (41 on this Mac),+ `currentUpdateAvailableSince`, `currentUpdateDownloadedSince`, `lastInstalledAppVersion`,+ `firstLaunchAfterUpdatedFromVersion`, `lastUpdateWasAutoUpdate`, `automaticUpdateWillRelaunchApp`.+ `forceShowUpdateBanner` is read at launch only (a new window did not show it); the banner was not captured.+- [O] Automatic restart: analytics keys auto_update_queued, ignore_user_idle, is_auto_update_enabled,+ is_ready_to_install_update, time_since_last_active, active_tabs_blocked_update, window_dialog_sheet_visible,+ incognito_windows_with_web_contents_exist, sleep_satisfied_for_auto_update, forced_auto_update_occurred; remote+ flags auto-updates-enabled, new-auto-update-heuristic-enabled, auto-update-inactivity-delay-in-seconds,+ auto-update-required-idle-duration-in-seconds; logs "Auto update was cancelled because in progress download was+ detected" and "… one of the web contents reported unsaved work". Little Arc windows are restored only after an+ auto-update restart. Settings: "Automatically update my Arc" (`automaticallyUpdateArc`) with "Learn more about+ auto-updating". [U] the flag values (remote).+- Cra: `Services/SoftwareUpdater.swift` (Sparkle 2.10 from vendor/sparkle, same Info.plist keys, feed+ github.com/VictorKildahl/cra/releases/latest/download/appcast.xml written by scripts/appcast.sh), the updater window+ (`UI/Updates/UpdaterWindow.swift`, pixel-matched to the capture above), sidebar banners (`UI/Updates/UpdateBanner.swift`,+ Arc's copy, Cra's card style since Arc's was not captured), Cra menu ▸ Check for Updates… after the import item,+ Settings ▸ Advanced ▸ "Automatically update Cra". The automatic restart waits for 10 min in the background with+ 2 min without input, or 30 min without input, and holds off for downloads, sheets, Little Windows, Picture in+ Picture, the import and any power assertion Cra holds (Chromium's media wake locks); the relaunch doesn't take focus.+ Verified with local appcasts (renamed CraUpd test bundle, LSEnvironment for the relaunch): background download →+ banner → idle restart, auto-download off → "New Cra Version Available" → Download → Install and Relaunch, and the+ "Cra Updated!" banner after each, all ad-hoc signed.diff --git a/docs/release.md b/docs/release.mdindex c758b38..461dedf 100644--- a/docs/release.md+++ b/docs/release.md@@ -76,24 +76,63 @@ notarizes and staples the app, runs `package.sh` (zip, DMG with an Applicationschecksums), then notarizes and staples the DMG and checks it with `spctl`.Without `CRA_SIGN_IDENTITY` it produces an ad-hoc build and skips notarization.+## The DMG window++Opening `Cra.dmg` shows a drag-to-install window modelled on Dia's installer (decoded from+its `.DS_Store`): 800×400 pt, no toolbar or sidebar, 212 pt icons with Cra at (190, 180)+and Applications at (610, 180), and a background with the install line and a chevron+between them. `scripts/package.sh` builds it with [dmgbuild](https://github.com/dmgbuild/dmgbuild),+which writes the Finder layout directly, so it needs no Finder scripting and runs on CI.+It installs a pinned dmgbuild into `build/dmgbuild-venv` on first use.++- `resources/dmg/settings.py`: window, icon size and positions, volume icon.+- `resources/dmg/background.png`: 1600×800 px at 144 dpi. Regenerate it with+ `swift scripts/make-dmg-background.swift` after changing the brand colours or the layout.+## What the signing coversOrder matters because each signature seals what is inside it:1. every `.dylib` in `Chromium Embedded Framework.framework/Libraries`2. the framework itself-3. the five helper apps, each with `resources/CraHelper.entitlements`-4. `Cra.app` with `resources/Cra.entitlements`+3. Sparkle's `Autoupdate` and `Updater.app`, then `Sparkle.framework` (its XPC services are+ removed: they are only for sandboxed apps)+4. the five helper apps, each with `resources/CraHelper.entitlements`+5. `Cra.app` with `resources/Cra.entitlements`The entitlements are the hardened-runtime exceptions Chromium needs (JIT, unsignedexecutable memory, library validation off, dyld environment variables), plus camera,microphone and location so sites can ask for them.+## Updates++Cra updates itself the way Arc does, with [Sparkle 2](https://sparkle-project.org)+(`scripts/fetch-sparkle.sh` puts a pinned, checksummed release in `vendor/sparkle`). Every+8 hours it reads `releases/latest/download/appcast.xml`, downloads a newer `Cra.zip` in+the background, installs it when Cra quits, or restarts into it by itself once the user+is away. Cra menu ▸ Check for Updates… and Settings ▸ Advanced ▸ "Automatically update Cra"+are the controls. Details and Arc's original are in `docs/arc-reverse-engineering.md`+("Software updates").++- **Signing key.** Updates are accepted only when `Cra.zip` carries an EdDSA signature+ matching `SUPublicEDKey` in `resources/Info.plist`. The private key is in the login+ keychain of the Mac that made it (`vendor/sparkle/bin/generate_keys --account cra`,+ made 26 Oct 2026) and in the `SPARKLE_PRIVATE_KEY` secret. Back it up+ (`generate_keys --account cra -x <file>`): without it, installed copies can never be+ updated again.+- **Appcast.** `scripts/release.sh` ends with `scripts/appcast.sh`, which signs the final+ `Cra.zip` and writes `build/dist/appcast.xml`; the workflow uploads it with the other+ assets. `CRA_RELEASE_NOTES=<file.html>` adds release notes to the update window.+- **Version numbers.** Sparkle compares `CFBundleVersion`, the build number `build.sh`+ takes from the clock, so every release is newer than the last.+- **Dev builds** have no feed (`build.sh` drops `SUFeedURL` unless `CRA_RELEASE=1`), so they+ never replace themselves with a release. To test, run a copy with+ `CRA_UPDATE_FEED=http://127.0.0.1:8889/appcast.xml` (and `CRA_UPDATE_IDLE_SECONDS=0` for+ the automatic restart) against a local appcast made with `CRA_UPDATE_URL=… scripts/appcast.sh`.+- Copies from before the updater (0.1.0, 0.1.1) update once by hand: rerun the install line.+## Later-- **Updates in the app.** Add Sparkle 2 with an appcast generated by the release- workflow (`generate_appcast` over `build/dist`), so users get new versions without- visiting the site.- **Homebrew.** A cask (`brew install --cask cra`) pointing at the DMG and`SHA256SUMS.txt`.- **Intel.** The CEF fetch pins `macosarm64`; a universal build needs both CEFdiff --git a/resources/Info.plist b/resources/Info.plistindex 2add35e..ad2effb 100644--- a/resources/Info.plist+++ b/resources/Info.plist@@ -32,6 +32,18 @@<true/><key>NSSupportsAutomaticGraphicsSwitching</key><true/>+ <!-- Software updates: Sparkle with Arc's settings (8-hour checks, background downloads).+ scripts/build.sh drops SUFeedURL outside release builds. -->+ <key>SUFeedURL</key>+ <string>https://github.com/VictorKildahl/cra/releases/latest/download/appcast.xml</string>+ <key>SUPublicEDKey</key>+ <string>/ZvLn/gEyw0MSGRKJif47YTqQPI1WhxGYbF/nOBHu7E=</string>+ <key>SUEnableAutomaticChecks</key>+ <true/>+ <key>SUAutomaticallyUpdate</key>+ <true/>+ <key>SUScheduledCheckInterval</key>+ <integer>28800</integer><key>NSCameraUsageDescription</key><string>Web sites you visit can ask to use the camera.</string><key>NSMicrophoneUsageDescription</key>diff --git a/scripts/appcast.sh b/scripts/appcast.shnew file mode 100755index 0000000..b93635d--- /dev/null+++ b/scripts/appcast.sh@@ -0,0 +1,52 @@+#!/bin/bash+# Writes build/dist/appcast.xml, the Sparkle feed installed copies of Cra check every+# 8 hours (SUFeedURL: releases/latest/download/appcast.xml). The update archive is+# signed with the EdDSA key: SPARKLE_PRIVATE_KEY (CI secret), or the "cra" key in the+# login keychain (made once with vendor/sparkle/bin/generate_keys --account cra).+# scripts/appcast.sh [Cra.zip] [Cra.app] [release-notes.html]+# CRA_UPDATE_URL overrides the download URL (tests point it at a local server).+set -euo pipefail+cd "$(dirname "$0")/.."+ZIP="${1:-build/dist/Cra.zip}"+APP="${2:-build/Cra.app}"+NOTES="${3:-}"+OUT="$(dirname "$ZIP")/appcast.xml"++plist() { /usr/libexec/PlistBuddy -c "Print :$1" "$APP/Contents/Info.plist"; }+VERSION="$(plist CFBundleShortVersionString)"+BUILD="$(plist CFBundleVersion)"+MIN_OS="$(plist LSMinimumSystemVersion)"+URL="${CRA_UPDATE_URL:-https://github.com/VictorKildahl/cra/releases/download/v$VERSION/Cra.zip}"++SIGN=vendor/sparkle/bin/sign_update+if [ -n "${SPARKLE_PRIVATE_KEY:-}" ]; then+ ENCLOSURE="$(printf '%s' "$SPARKLE_PRIVATE_KEY" | "$SIGN" --ed-key-file - "$ZIP")"+else+ ENCLOSURE="$("$SIGN" --account cra "$ZIP")"+fi++DESCRIPTION=""+if [ -n "$NOTES" ] && [ -f "$NOTES" ]; then+ DESCRIPTION="+ <description><![CDATA[$(cat "$NOTES")]]></description>"+fi++cat > "$OUT" <<XML+<?xml version="1.0" encoding="utf-8"?>+<rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">+ <channel>+ <title>Cra</title>+ <link>https://crabrowser.app/release-notes</link>+ <item>+ <title>Cra $VERSION</title>+ <pubDate>$(LC_ALL=C date -u "+%a, %d %b %Y %H:%M:%S +0000")</pubDate>+ <sparkle:version>$BUILD</sparkle:version>+ <sparkle:shortVersionString>$VERSION</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>$MIN_OS</sparkle:minimumSystemVersion>+ <sparkle:fullReleaseNotesLink>https://crabrowser.app/release-notes</sparkle:fullReleaseNotesLink>$DESCRIPTION+ <enclosure url="$URL" type="application/octet-stream" $ENCLOSURE/>+ </item>+ </channel>+</rss>+XML+echo "Wrote $OUT (Cra $VERSION, build $BUILD)"diff --git a/scripts/build.sh b/scripts/build.shindex 23febb3..b763758 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -12,6 +12,7 @@ VERSION="${CRA_VERSION:-0.1.0}"BUILD_NUMBER="${CRA_BUILD:-$(date +%Y%m%d%H%M)}"scripts/fetch-cef.sh+scripts/fetch-sparkle.shswift build -c "$CONFIG"BIN="$(swift build -c "$CONFIG" --show-bin-path)"@@ -25,6 +26,9 @@ mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" "$APP/Contents/Frameworcp "$BIN/Cra" "$APP/Contents/MacOS/Cra"sed -e "s/__VERSION__/$VERSION/" -e "s/__BUILD__/$BUILD_NUMBER/" resources/Info.plist > "$APP/Contents/Info.plist"+# Only release builds (scripts/release.sh) check the update feed; a dev build would+# otherwise replace itself with the latest release.+[ "${CRA_RELEASE:-}" = 1 ] || /usr/libexec/PlistBuddy -c "Delete :SUFeedURL" "$APP/Contents/Info.plist"echo -n "APPL????" > "$APP/Contents/PkgInfo"[ -f resources/AppIcon.icns ] && cp resources/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns"[ -d resources/web ] && cp -R resources/web "$APP/Contents/Resources/web"@@ -33,6 +37,9 @@ echo -n "APPL????" > "$APP/Contents/PkgInfo"FRAMEWORK_SRC="$ROOT/vendor/cef/Release/Chromium Embedded Framework.framework"cp -R "$FRAMEWORK_SRC" "$APP/Contents/Frameworks/"+# Sparkle's XPC services are only for sandboxed apps; Cra uses Autoupdate and Updater.app.+ditto "$ROOT/vendor/sparkle/Sparkle.framework" "$APP/Contents/Frameworks/Sparkle.framework"+rm -rf "$APP/Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices" "$APP/Contents/Frameworks/Sparkle.framework/XPCServices"# CEF needs one helper app per process type (see cef_variables.cmake,# CEF_HELPER_APP_SUFFIXES). Format: "<name suffix>|<plist suffix>".@@ -66,6 +73,10 @@ sign() { # sign <path> [entitlements]FW="$APP/Contents/Frameworks/Chromium Embedded Framework.framework"find "$FW/Libraries" -name '*.dylib' -print0 2>/dev/null | while IFS= read -r -d '' lib; do sign "$lib"; donesign "$FW"+SPARKLE="$APP/Contents/Frameworks/Sparkle.framework"+sign "$SPARKLE/Versions/B/Autoupdate"+sign "$SPARKLE/Versions/B/Updater.app"+sign "$SPARKLE"for h in "$APP"/Contents/Frameworks/*.app; do sign "$h" "$ROOT/resources/CraHelper.entitlements"; donesign "$APP" "$ROOT/resources/Cra.entitlements"if [ "$IDENTITY" != "-" ]; thendiff --git a/scripts/fetch-sparkle.sh b/scripts/fetch-sparkle.shnew file mode 100755index 0000000..6e941d6--- /dev/null+++ b/scripts/fetch-sparkle.sh@@ -0,0 +1,25 @@+#!/bin/bash+# Downloads the pinned Sparkle release (the updater framework Arc ships) into+# vendor/sparkle: Sparkle.framework for the app, bin/ (generate_keys,+# sign_update) for releases. Safe to re-run; skips what is already there.+set -euo pipefail+cd "$(dirname "$0")/.."++SPARKLE_VERSION="2.10.0"+SPARKLE_SHA256="c2bf58aa8387266ac179357b1415d6f2635f044da8be41042af32425dae6da0c"++if [ "$(cat vendor/sparkle/VERSION 2>/dev/null)" != "$SPARKLE_VERSION" ]; then+ echo "Downloading Sparkle ${SPARKLE_VERSION}..."+ TMP="$(mktemp -d)"+ trap 'rm -rf "$TMP"' EXIT+ curl -fL --progress-bar -o "$TMP/Sparkle.tar.xz" \+ "https://github.com/sparkle-project/Sparkle/releases/download/${SPARKLE_VERSION}/Sparkle-${SPARKLE_VERSION}.tar.xz"+ echo "${SPARKLE_SHA256} $TMP/Sparkle.tar.xz" | shasum -a 256 -c - >/dev/null+ mkdir "$TMP/x"+ tar -xJf "$TMP/Sparkle.tar.xz" -C "$TMP/x"+ rm -rf vendor/sparkle+ mkdir -p vendor/sparkle+ mv "$TMP/x/Sparkle.framework" "$TMP/x/bin" "$TMP/x/LICENSE" vendor/sparkle/+ echo "$SPARKLE_VERSION" > vendor/sparkle/VERSION+fi+echo "Sparkle ready: vendor/sparkle"diff --git a/scripts/release.sh b/scripts/release.shindex 900893f..356c87f 100755--- a/scripts/release.sh+++ b/scripts/release.sh@@ -1,11 +1,15 @@#!/bin/bash-# Full distributable build: build, sign, notarize, package, notarize the DMG.+# Full distributable build: build, sign, notarize, package, notarize the DMG, and+# write the Sparkle appcast for the update archive.# CRA_VERSION=0.1.0 CRA_SIGN_IDENTITY="Developer ID Application: …" scripts/release.sh# Without CRA_SIGN_IDENTITY it still produces an ad-hoc build and packages, so-# the pipeline can be exercised before certificates exist.+# the pipeline can be exercised before certificates exist. The appcast needs the+# update signing key (SPARKLE_PRIVATE_KEY, or the "cra" key in the login keychain).set -euo pipefailcd "$(dirname "$0")/.."export CRA_VERSION="${CRA_VERSION:-0.1.0}"+# Release builds carry the update feed (scripts/build.sh drops it otherwise).+export CRA_RELEASE=1IDENTITY="${CRA_SIGN_IDENTITY:--}"scripts/build.sh release@@ -26,8 +30,12 @@ if [ "$IDENTITY" != "-" ]; then# Re-zip the stapled app so the zip download carries the ticket too.ditto -c -k --keepParent "$APP" "build/dist/Cra.zip"(cd build/dist && shasum -a 256 Cra.zip Cra.dmg > SHA256SUMS.txt)- spctl --assess --type execute --verbose=2 "$APP" && echo "Gatekeeper accepts $APP"+ # On its own line so set -e fails the release when Gatekeeper rejects the app.+ spctl --assess --type execute --verbose=2 "$APP"+ echo "Gatekeeper accepts $APP"elseecho "Ad-hoc build: not notarized. Set CRA_SIGN_IDENTITY and notary credentials for a distributable build." >&2fi+# Installed copies update from the zip; the appcast must sign the final one.+scripts/appcast.sh build/dist/Cra.zip "$APP" "${CRA_RELEASE_NOTES:-}"echo "Release artifacts in build/dist"diff --git a/scripts/test-update.sh b/scripts/test-update.shnew file mode 100755index 0000000..a5772d5--- /dev/null+++ b/scripts/test-update.sh@@ -0,0 +1,99 @@+#!/bin/bash+# Try the updater end to end without touching the installed Cra: builds an "old" and+# a "new" Cra, serves the new one from a local appcast on 127.0.0.1:8889 and opens the+# old one as "CraTest" (own bundle id, own data dir, so it runs next to your Cra).+# scripts/test-update.sh automatic updates on: downloads, shows the banner+# scripts/test-update.sh manual automatic updates off: "New Cra Version Available"+# scripts/test-update.sh idle also restarts into the update by itself after 20 s+# without mouse or keyboard input+# scripts/test-update.sh again reopen the old version without rebuilding+# scripts/test-update.sh stop quit CraTest and stop the feed server+# Signing the update uses the "cra" key in the login keychain (see docs/release.md).+set -euo pipefail+cd "$(dirname "$0")/.."+ROOT="$PWD"+DIR="$ROOT/build/update-test"+DOMAIN=dk.kildahl.cra.updatetest+PORT=8889+MODE="${1:-auto}"++stop() {+ pkill -f "$DIR/run/CraTest.app/Contents/MacOS/CraTest" 2>/dev/null || true+ [ -f "$DIR/server.pid" ] && kill "$(cat "$DIR/server.pid")" 2>/dev/null || true+ rm -f "$DIR/server.pid"+}++# A renamed copy: executable and helpers become CraTest*, so it is its own app.+make_copy() { # make_copy <Cra.app> <out dir> [idle seconds]+ local src="$1" out="$2" idle="${3:-}" app pb=/usr/libexec/PlistBuddy+ rm -rf "$out/CraTest.app" && mkdir -p "$out"+ ditto "$src" "$out/CraTest.app"+ app="$out/CraTest.app"+ mv "$app/Contents/MacOS/Cra" "$app/Contents/MacOS/CraTest"+ $pb -c "Set :CFBundleExecutable CraTest" -c "Set :CFBundleIdentifier $DOMAIN" -c "Set :CFBundleName CraTest" \+ -c "Add :LSEnvironment dict" -c "Add :LSEnvironment:CRA_DATA_DIR string $DIR/data" \+ -c "Add :LSEnvironment:CRA_UPDATE_FEED string http://127.0.0.1:$PORT/appcast.xml" "$app/Contents/Info.plist"+ [ -n "$idle" ] && $pb -c "Add :LSEnvironment:CRA_UPDATE_IDLE_SECONDS string $idle" "$app/Contents/Info.plist"+ for h in "$app"/Contents/Frameworks/Cra\ Helper*.app; do+ local name new+ name="$(basename "$h" .app)"+ new="CraTest${name#Cra}"+ mv "$h/Contents/MacOS/$name" "$h/Contents/MacOS/$new"+ $pb -c "Set :CFBundleExecutable $new" -c "Set :CFBundleName $new" "$h/Contents/Info.plist"+ mv "$h" "$app/Contents/Frameworks/$new.app"+ codesign --force --sign - --entitlements resources/CraHelper.entitlements "$app/Contents/Frameworks/$new.app" 2>/dev/null+ done+ codesign --force --sign - --entitlements resources/Cra.entitlements "$app" 2>/dev/null+}++case "$MODE" in+ stop) stop; echo "Stopped."; exit 0 ;;+ auto|manual|idle|again) ;;+ *) echo "Usage: scripts/test-update.sh [auto|manual|idle|again|stop]" >&2; exit 1 ;;+esac++stop+sleep 1+IDLE=""+[ "$MODE" = idle ] && IDLE=20++if [ "$MODE" != again ] || [ ! -d "$DIR/old.app" ]; then+ echo "Building Cra 0.9.0 (old) and 0.9.1 (new)…"+ mkdir -p "$DIR"+ CRA_VERSION=0.9.0 CRA_BUILD=1000 CRA_INSTALL_DIR="$DIR/install" scripts/build.sh debug > "$DIR/build.log" 2>&1+ rm -rf "$DIR/old.app" && ditto build/Cra.app "$DIR/old.app"+ CRA_VERSION=0.9.1 CRA_BUILD=1001 CRA_INSTALL_DIR="$DIR/install" scripts/build.sh debug >> "$DIR/build.log" 2>&1+ make_copy build/Cra.app "$DIR/new"+ rm -rf "$DIR/feed" && mkdir -p "$DIR/feed"+ ditto -c -k --keepParent "$DIR/new/CraTest.app" "$DIR/feed/Cra.zip"+ printf '<h3>Cra 0.9.1</h3><ul><li>A test update served from your Mac.</li><li>Nothing here is real.</li></ul>' > "$DIR/notes.html"+ CRA_UPDATE_URL="http://127.0.0.1:$PORT/Cra.zip" scripts/appcast.sh "$DIR/feed/Cra.zip" "$DIR/new/CraTest.app" "$DIR/notes.html"+fi++# Fresh state each run: the old version, onboarding done, no record of past checks.+make_copy "$DIR/old.app" "$DIR/run" "$IDLE"+rm -rf "$DIR/data" && mkdir -p "$DIR/data"+echo '{"hasSeenImportPrompt": true, "toolbarDefaultMigrated": true}' > "$DIR/data/settings.json"+defaults delete "$DOMAIN" >/dev/null 2>&1 || true+defaults write "$DOMAIN" SULastCheckTime -date "2000-01-01 00:00:00 +0000"+defaults write "$DOMAIN" SUAutomaticallyUpdate -bool "$([ "$MODE" = manual ] && echo NO || echo YES)"++python3 -I -m http.server "$PORT" --bind 127.0.0.1 --directory "$DIR/feed" > "$DIR/server.log" 2>&1 &+echo $! > "$DIR/server.pid"+sleep 1+open "$DIR/run/CraTest.app"++cat <<EOF++CraTest 0.9.0 is open (a separate test copy; your own Cra is untouched).+Within a few seconds it finds 0.9.1 on the local feed.+EOF+case "$MODE" in+ manual) echo " - The sidebar shows \"New Cra Version Available\". Click it, or Cra ▸ Check for Updates…, then Download." ;;+ idle) echo " - The sidebar shows \"An update is ready!\". Leave the mouse and keyboard alone for 20 s: CraTest restarts into 0.9.1 by itself." ;;+ *) echo " - The sidebar shows \"An update is ready!\". Click it to restart into 0.9.1, or quit CraTest to install on quit." ;;+esac+cat <<EOF+ - After the update the sidebar says "Cra Updated!"; Cra ▸ Check for Updates… then says you're up to date.+Run again with "again" to start over from 0.9.0, and "stop" when you're done.+EOF