diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 36b4deb..0dcd84f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,7 +15,7 @@ jobs: test: runs-on: macos-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Run tests run: make test @@ -24,7 +24,7 @@ jobs: runs-on: macos-latest needs: test steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Build (unsigned) run: make build-unsigned @@ -33,12 +33,12 @@ jobs: run: npm install --global create-dmg@8.1.0 && make dmg - name: Upload build artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: Palium.dmg path: Palium.dmg - name: Generate artifact attestation - uses: actions/attest@v4 + uses: actions/attest-build-provenance@v2 with: - subject-path: palium.dmg + subject-path: Palium.dmg diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ae6d849 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,185 @@ +name: Release + +on: + push: + tags: ["v*"] + +permissions: + contents: write + id-token: write + attestations: write + +env: + SPARKLE_VERSION: "2.9.4" + PAGES_BASE: https://mgruszkiewicz.github.io/palium + +jobs: + release: + runs-on: macos-latest + steps: + - uses: actions/checkout@v5 + with: + # Full history: the build number is the commit count, and it has to + # keep increasing or Sparkle will not treat the release as newer. + fetch-depth: 0 + + - name: Derive version + id: version + run: | + TAG="${GITHUB_REF_NAME}" + VERSION="${TAG#v}" + BUILD="$(git rev-list --count HEAD)" + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "build=$BUILD" >> "$GITHUB_OUTPUT" + echo "Releasing $VERSION (build $BUILD) from $TAG" + + - name: Run tests + run: make test + + - name: Build release artifacts + env: + VERSION: ${{ steps.version.outputs.version }} + BUILD: ${{ steps.version.outputs.build }} + run: | + npm install --global create-dmg@8.1.0 + make release-artifacts + mv Palium.zip "Palium-${VERSION}.zip" + mv Palium.dmg "Palium-${VERSION}.dmg" + + - name: Verify built version matches the tag + env: + VERSION: ${{ steps.version.outputs.version }} + BUILD: ${{ steps.version.outputs.build }} + run: | + PLIST=build/DerivedData/Build/Products/Release/palium.app/Contents/Info.plist + SHORT=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "$PLIST") + BUNDLE=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$PLIST") + FEED=$(/usr/libexec/PlistBuddy -c "Print SUFeedURL" "$PLIST") + KEY=$(/usr/libexec/PlistBuddy -c "Print SUPublicEDKey" "$PLIST") + echo "built: $SHORT ($BUNDLE) feed: $FEED" + [ "$SHORT" = "$VERSION" ] || { echo "::error::CFBundleShortVersionString $SHORT != $VERSION"; exit 1; } + [ "$BUNDLE" = "$BUILD" ] || { echo "::error::CFBundleVersion $BUNDLE != $BUILD"; exit 1; } + [ -n "$FEED" ] && [ -n "$KEY" ] || { echo "::error::SUFeedURL/SUPublicEDKey missing from the built app"; exit 1; } + + - name: Install Sparkle tools + run: | + curl -sSL -o sparkle.tar.xz \ + "https://github.com/sparkle-project/Sparkle/releases/download/${SPARKLE_VERSION}/Sparkle-${SPARKLE_VERSION}.tar.xz" + mkdir -p sparkle && tar -xJf sparkle.tar.xz -C sparkle + + - name: Sign update with EdDSA key + id: sign + env: + SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }} + VERSION: ${{ steps.version.outputs.version }} + run: | + if [ -z "$SPARKLE_PRIVATE_KEY" ]; then + echo "::error::SPARKLE_PRIVATE_KEY secret is not set"; exit 1 + fi + ARCHIVE="Palium-${VERSION}.zip" + # Piped via stdin so the key never touches the runner's disk. + SIGNATURE=$(printf '%s' "$SPARKLE_PRIVATE_KEY" \ + | ./sparkle/bin/sign_update "$ARCHIVE" --ed-key-file - -p) + printf '%s' "$SPARKLE_PRIVATE_KEY" \ + | ./sparkle/bin/sign_update "$ARCHIVE" --verify "$SIGNATURE" --ed-key-file - + echo "::add-mask::$SIGNATURE" + echo "signature=$SIGNATURE" >> "$GITHUB_OUTPUT" + echo "length=$(stat -f%z "$ARCHIVE")" >> "$GITHUB_OUTPUT" + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@v2 + with: + subject-path: | + Palium-${{ steps.version.outputs.version }}.zip + Palium-${{ steps.version.outputs.version }}.dmg + + # The appcast points at these assets, so they must exist before it is published. + - name: Create GitHub release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.version.outputs.tag }} + VERSION: ${{ steps.version.outputs.version }} + run: | + gh release create "$TAG" \ + --title "Palium $VERSION" \ + --generate-notes \ + "Palium-${VERSION}.dmg" \ + "Palium-${VERSION}.zip" + + - name: Publish appcast to GitHub Pages + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ steps.version.outputs.tag }} + VERSION: ${{ steps.version.outputs.version }} + BUILD: ${{ steps.version.outputs.build }} + SIGNATURE: ${{ steps.sign.outputs.signature }} + LENGTH: ${{ steps.sign.outputs.length }} + run: | + MIN_OS=$(xcodebuild -project palium.xcodeproj -scheme palium -configuration Release \ + -showBuildSettings 2>/dev/null \ + | awk -F' = ' '/ MACOSX_DEPLOYMENT_TARGET =/ {print $2; exit}') + + REPO_URL="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + if ! git clone --branch gh-pages --depth 1 "$REPO_URL" site 2>/dev/null; then + echo "gh-pages does not exist yet — creating it" + rm -rf site + git clone --depth 1 "$REPO_URL" site + git -C site checkout --orphan gh-pages + git -C site rm -rf . >/dev/null 2>&1 || true + fi + + # Sparkle renders these notes in the update prompt. + mkdir -p site/notes + gh release view "$TAG" --json body --jq .body > notes.md + [ -s notes.md ] || echo "See the release page for details." > notes.md + gh api -X POST /markdown \ + -f mode=gfm \ + -f context="$GITHUB_REPOSITORY" \ + -f text="$(cat notes.md)" > notes-body.html + { + echo '' + echo '' + echo "

Palium ${VERSION}

" + cat notes-body.html + echo '' + } > "site/notes/${VERSION}.html" + + python3 scripts/appcast.py site/appcast.xml \ + --version "$BUILD" \ + --short-version "$VERSION" \ + --url "https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/Palium-${VERSION}.zip" \ + --length "$LENGTH" \ + --signature "$SIGNATURE" \ + --minimum-system-version "$MIN_OS" \ + --release-notes-url "${PAGES_BASE}/notes/${VERSION}.html" \ + --full-release-notes-url "https://github.com/${GITHUB_REPOSITORY}/releases" \ + --channel-link "${PAGES_BASE}/appcast.xml" + + # Stops Pages from running the output through Jekyll. + touch site/.nojekyll + + cd site + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add -A + if git diff --cached --quiet; then + echo "appcast unchanged — nothing to publish" + else + git commit -m "release: Palium ${VERSION} (build ${BUILD})" + git push origin gh-pages + fi + + - name: Summary + env: + VERSION: ${{ steps.version.outputs.version }} + BUILD: ${{ steps.version.outputs.build }} + run: | + { + echo "### Palium $VERSION (build $BUILD) published" + echo "" + echo "- Appcast: ${PAGES_BASE}/appcast.xml" + echo "- Existing installs pick it up within 24h, or immediately via *Check for Updates…*" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index f3d48dd..ee4f23a 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,9 @@ *.mode2v3 *.perspectivev3 *.xcuserstate -project.xcworkspace/ +# project.xcworkspace/ is deliberately not ignored: it holds Package.resolved, +# which pins Sparkle to an exact revision for release builds. The xcuserdata/ +# rule below still covers the per-user noise inside it. xcuserdata/ # Generated files @@ -29,3 +31,6 @@ Carthage/ *.lock *.dmg + +# Sparkle update archive built by `make zip-app` +/Palium.zip diff --git a/Makefile b/Makefile index 4d3e9df..8619091 100644 --- a/Makefile +++ b/Makefile @@ -6,13 +6,35 @@ ARCHIVE := $(BUILD_DIR)/palium.xcarchive APP := $(ARCHIVE)/Products/Applications/palium.app ZIP := $(BUILD_DIR)/palium.zip -.PHONY: archive zip clean test build-unsigned +PRODUCTS := $(BUILD_DIR)/DerivedData/Build/Products/Release +RELEASE_APP := $(PRODUCTS)/palium.app + +# Version stamped into the built app. Sparkle compares CFBundleVersion (BUILD) +# to decide whether an update is newer, so it must increase monotonically; +# commit count does that for free. Override either from CI. +VERSION ?= $(patsubst v%,%,$(shell git describe --tags --abbrev=0 2>/dev/null)) +BUILD ?= $(shell git rev-list --count HEAD 2>/dev/null) + +VERSION_FLAGS := $(if $(VERSION),MARKETING_VERSION=$(VERSION)) \ + $(if $(BUILD),CURRENT_PROJECT_VERSION=$(BUILD)) + +# Shippable builds use exactly the Sparkle revision in Package.resolved. Without +# this, the upToNextMajorVersion requirement lets a release silently pick up a +# newer Sparkle than the one that was tested. Bump it via Xcode, not by drifting. +PIN_PACKAGES := -onlyUsePackageVersionsFromResolvedFile + +.PHONY: archive zip clean test test-all build-unsigned dmg zip-app release-artifacts version + +version: + @echo "MARKETING_VERSION=$(VERSION) CURRENT_PROJECT_VERSION=$(BUILD)" archive: xcodebuild -project $(PROJECT) \ -scheme $(SCHEME) \ -configuration $(CONFIG) \ -archivePath $(ARCHIVE) \ + $(PIN_PACKAGES) \ + $(VERSION_FLAGS) \ archive zip: archive @@ -25,6 +47,8 @@ build-unsigned: -configuration $(CONFIG) \ -derivedDataPath $(BUILD_DIR)/DerivedData \ CODE_SIGN_IDENTITY=- \ + $(PIN_PACKAGES) \ + $(VERSION_FLAGS) \ build test: @@ -43,8 +67,18 @@ test-all: test dmg: - create-dmg $(BUILD_DIR)/DerivedData/Build/Products/Release/palium.app --dmg-title=Palium --no-version-in-filename $(if $(CI),--no-code-sign) + create-dmg $(RELEASE_APP) --dmg-title=Palium --no-version-in-filename $(if $(CI),--no-code-sign) + @mv -f palium.dmg Palium.dmg 2>/dev/null || true + +# Sparkle's update enclosure. ditto (not zip) so symlinks inside +# Sparkle.framework and the code signature survive the round trip. +zip-app: + @rm -f Palium.zip + ditto -c -k --sequesterRsrc --keepParent $(RELEASE_APP) Palium.zip + @echo "Ready for Sparkle: Palium.zip" + +release-artifacts: build-unsigned zip-app dmg clean: - rm -rf $(BUILD_DIR) + rm -rf $(BUILD_DIR) Palium.zip Palium.dmg xcodebuild -project $(PROJECT) -scheme $(SCHEME) clean diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..c03f153 --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,138 @@ +# Releasing Palium + +Updates ship over-the-air via [Sparkle](https://sparkle-project.org). The app reads +an appcast from GitHub Pages; the actual binaries are GitHub Release assets. + +``` +git tag v1.1.0 → .github/workflows/release.yml + ├─ build + test + ├─ Palium-1.1.0.zip (Sparkle enclosure, EdDSA-signed) + ├─ Palium-1.1.0.dmg (first-time download) + ├─ GitHub Release ← assets live here + └─ gh-pages branch ← appcast.xml + notes/1.1.0.html + └─ https://mgruszkiewicz.github.io/palium/appcast.xml +``` + +## Cutting a release + +```sh +git tag v1.1.0 +git push origin v1.1.0 +``` + +That is the whole process. The tag drives the version: + +| Field | Value | Why | +|---|---|---| +| `CFBundleShortVersionString` | tag without `v` (`1.1.0`) | shown to users | +| `CFBundleVersion` | `git rev-list --count HEAD` | Sparkle's ordering key — must only ever increase | + +Because the build number is the commit count, **always tag a commit that is ahead of +the previous release's commit.** Tagging an older commit produces a lower build number +and Sparkle will not offer it as an update. + +The workflow asserts that the built app's `Info.plist` matches the tag before signing, +so a mismatch fails the run rather than shipping a bad appcast. + +## One-time setup + +### 1. Export the EdDSA private key into a GitHub secret + +The key generated by `generate_keys` lives in your login Keychain and has to be +exported for CI: + +```sh +curl -sSL -o sparkle.tar.xz \ + https://github.com/sparkle-project/Sparkle/releases/download/2.9.4/Sparkle-2.9.4.tar.xz +mkdir sparkle && tar -xJf sparkle.tar.xz -C sparkle +./sparkle/bin/generate_keys -x sparkle_private_key.txt +``` + +Add the file's contents as the repository secret **`SPARKLE_PRIVATE_KEY`** +(Settings → Secrets and variables → Actions → New repository secret), then delete +the local copy: + +```sh +rm sparkle_private_key.txt +``` + +Keep a backup somewhere safe (a password manager). **Losing this key means existing +installs can never be updated again** — they only trust `SUPublicEDKey`, and you +cannot change that key in an app that is already on someone's disk. Confirm the +public half still matches what is in `palium/Info.plist`: + +```sh +./sparkle/bin/generate_keys -p +``` + +### 2. Enable GitHub Pages + +Settings → Pages → Source: **Deploy from a branch**, branch `gh-pages`, folder `/`. + +The branch does not exist yet; the first release creates it. Run the release once, +then set the Pages source. + +### 3. Check Actions permissions + +Settings → Actions → General → Workflow permissions must be **Read and write**, so +the workflow can create releases and push to `gh-pages`. + +## How the app consumes it + +`palium/Info.plist` carries the whole client-side configuration: + +- `SUFeedURL` — where to look for the appcast +- `SUPublicEDKey` — the only thing that makes an update trusted +- `SUEnableAutomaticChecks` / `SUScheduledCheckInterval` — background check, daily + +`UpdaterService` owns the `SPUStandardUpdaterController`, exposed through +*Palium ▸ Check for Updates…* and the Settings ▸ Updates tab. + +## Verifying an appcast by hand + +```sh +make release-artifacts +./sparkle/bin/sign_update Palium.zip # signs using the Keychain key +python3 scripts/appcast.py /tmp/appcast.xml \ + --version 42 --short-version 1.1.0 \ + --url https://example.com/Palium-1.1.0.zip \ + --length "$(stat -f%z Palium.zip)" --signature "" +``` + +To test the update flow end to end, run a build with a *lower* version than the +published one and use *Check for Updates…*: + +```sh +VERSION=0.0.1 BUILD=1 make build-unsigned +open build/DerivedData/Build/Products/Release/palium.app +``` + +## Bumping Sparkle + +`Package.resolved` is committed and release builds pass +`-onlyUsePackageVersionsFromResolvedFile`, so they use exactly the revision +recorded there rather than whatever the `upToNextMajorVersion` requirement +currently allows. A release therefore ships the Sparkle you tested, not a newer +one that landed in between. + +To move to a new version: bump it in Xcode (File ▸ Packages ▸ Update to Latest +Package Versions), commit the changed `Package.resolved`, and bump +`SPARKLE_VERSION` in `.github/workflows/release.yml` so the `sign_update` binary +matches the framework. If those two drift apart the build fails loudly rather +than shipping a mismatch. + +## Code signing + +Palium currently ships ad-hoc signed and un-notarized. Sparkle is fine with this — +the EdDSA signature alone is sufficient to trust an update — but first-time users +must right-click ▸ Open to get past Gatekeeper. + +To move to Developer ID later, add to the release workflow before the DMG step: + +1. Import the `.p12` into a temporary keychain. +2. Build with `CODE_SIGN_IDENTITY="Developer ID Application: ..."` and + `--options runtime` instead of `CODE_SIGN_IDENTITY=-`. +3. `xcrun notarytool submit --wait` on the DMG, then `xcrun stapler staple`. + +Nothing about the appcast or the EdDSA key changes. Sparkle keeps accepting updates +across the transition because the EdDSA signature stays valid on its own. diff --git a/palium.xcodeproj/project.pbxproj b/palium.xcodeproj/project.pbxproj index aa8c73f..ca025a9 100644 --- a/palium.xcodeproj/project.pbxproj +++ b/palium.xcodeproj/project.pbxproj @@ -6,6 +6,10 @@ objectVersion = 77; objects = { +/* Begin PBXBuildFile section */ + 2BE05DF3301E19B400689E8C /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 2BE05DF4301E19B400689E8C /* Sparkle */; }; +/* End PBXBuildFile section */ + /* Begin PBXContainerItemProxy section */ 2B4967DD2F6317F4002536F0 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; @@ -29,9 +33,22 @@ 2B4967E62F6317F4002536F0 /* paliumUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = paliumUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + 2BE05DF4301E644200689E8C /* Exceptions for "palium" folder in "palium" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 2B4967CE2F6317F3002536F0 /* palium */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + /* Begin PBXFileSystemSynchronizedRootGroup section */ 2B4967D12F6317F3002536F0 /* palium */ = { isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 2BE05DF4301E644200689E8C /* Exceptions for "palium" folder in "palium" target */, + ); path = palium; sourceTree = ""; }; @@ -52,6 +69,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 2BE05DF3301E19B400689E8C /* Sparkle in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -112,6 +130,7 @@ ); name = palium; packageProductDependencies = ( + 2BE05DF4301E19B400689E8C /* Sparkle */, ); productName = palium; productReference = 2B4967CF2F6317F3002536F0 /* palium.app */; @@ -195,6 +214,9 @@ ); mainGroup = 2B4967C62F6317F3002536F0; minimizedProjectReferenceProxies = 1; + packageReferences = ( + 2BE05DF2301E19B400689E8C /* XCRemoteSwiftPackageReference "Sparkle" */, + ); preferredProjectObjectVersion = 77; productRefGroup = 2B4967D02F6317F3002536F0 /* Products */; projectDirPath = ""; @@ -404,6 +426,7 @@ ENABLE_PREVIEWS = YES; ENABLE_USER_SELECTED_FILES = readonly; GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = palium/Info.plist; INFOPLIST_KEY_NSHumanReadableCopyright = ""; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -437,6 +460,7 @@ ENABLE_PREVIEWS = YES; ENABLE_USER_SELECTED_FILES = readonly; GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = palium/Info.plist; INFOPLIST_KEY_NSHumanReadableCopyright = ""; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -575,6 +599,25 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 2BE05DF2301E19B400689E8C /* XCRemoteSwiftPackageReference "Sparkle" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/sparkle-project/Sparkle"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 2.9.4; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 2BE05DF4301E19B400689E8C /* Sparkle */ = { + isa = XCSwiftPackageProductDependency; + package = 2BE05DF2301E19B400689E8C /* XCRemoteSwiftPackageReference "Sparkle" */; + productName = Sparkle; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = 2B4967C72F6317F3002536F0 /* Project object */; } diff --git a/palium.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/palium.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/palium.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/palium.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/palium.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..feb7b4b --- /dev/null +++ b/palium.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,15 @@ +{ + "originHash" : "e721da7f9826abdffcb6185e886155efa2514bd6234475f1afa893e29eb258d6", + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "b6496a74a087257ef5e6da1c5b29a447a60f5bd7", + "version" : "2.9.4" + } + } + ], + "version" : 3 +} diff --git a/palium/Info.plist b/palium/Info.plist new file mode 100644 index 0000000..5646d9b --- /dev/null +++ b/palium/Info.plist @@ -0,0 +1,14 @@ + + + + + SUFeedURL + https://mgruszkiewicz.github.io/palium/appcast.xml + SUPublicEDKey + 5wUA02oaTkST1FdbxVDTph1z6U9ApHzFbFh5mAnUEk4= + SUEnableAutomaticChecks + + SUScheduledCheckInterval + 86400 + + diff --git a/palium/Services/UpdaterService.swift b/palium/Services/UpdaterService.swift new file mode 100644 index 0000000..5dde50e --- /dev/null +++ b/palium/Services/UpdaterService.swift @@ -0,0 +1,54 @@ +import Foundation +import Observation +import Sparkle + +/// Owns the Sparkle updater for the lifetime of the app. +/// +/// The feed URL and public EdDSA key live in Info.plist (`SUFeedURL`, +/// `SUPublicEDKey`); Sparkle picks them up on its own. The controller has to be +/// created once at launch and kept alive — it drives the scheduled background +/// check as well as the manual one. +@MainActor +@Observable +class UpdaterService { + static let shared = UpdaterService() + + /// False while a check is already in flight, so the menu item can grey out. + private(set) var canCheckForUpdates = false + + var automaticallyChecksForUpdates: Bool { + didSet { controller.updater.automaticallyChecksForUpdates = automaticallyChecksForUpdates } + } + + @ObservationIgnored private let controller: SPUStandardUpdaterController + @ObservationIgnored private var canCheckObserver: NSKeyValueObservation? + + private init() { + controller = SPUStandardUpdaterController( + startingUpdater: true, + updaterDelegate: nil, + userDriverDelegate: nil + ) + automaticallyChecksForUpdates = controller.updater.automaticallyChecksForUpdates + + // Sparkle posts this on the main thread. + canCheckObserver = controller.updater.observe( + \.canCheckForUpdates, + options: [.initial, .new] + ) { [weak self] updater, _ in + MainActor.assumeIsolated { + self?.canCheckForUpdates = updater.canCheckForUpdates + } + } + } + + /// User-initiated check — always reports a result, including "you're up to date". + func checkForUpdates() { + controller.updater.checkForUpdates() + } + + /// The last time a scheduled or manual check completed, for display in Settings. + var lastUpdateCheckDate: Date? { + controller.updater.lastUpdateCheckDate + } +} diff --git a/palium/Views/SettingsView.swift b/palium/Views/SettingsView.swift index 527f3ca..91bedaf 100644 --- a/palium/Views/SettingsView.swift +++ b/palium/Views/SettingsView.swift @@ -2,6 +2,7 @@ import SwiftUI struct SettingsView: View { @Bindable private var settings = LaunchSettings.shared + @Bindable private var updater = UpdaterService.shared var body: some View { TabView { @@ -20,6 +21,11 @@ struct SettingsView: View { Label("Performance", systemImage: "gauge.with.dots.needle.67percent") } + updatesTab + .tabItem { + Label("Updates", systemImage: "arrow.down.circle") + } + TroubleshootingTab() .tabItem { Label("Troubleshoot", systemImage: "wrench.and.screwdriver") @@ -28,6 +34,44 @@ struct SettingsView: View { .frame(width: 500, height: 380) } + // MARK: - Updates Tab + + private var updatesTab: some View { + Form { + Toggle("Check for updates automatically", isOn: $updater.automaticallyChecksForUpdates) + Text("Palium checks for a new version once a day and asks before installing anything.") + .font(.caption) + .foregroundStyle(.secondary) + + Divider() + + HStack { + VStack(alignment: .leading, spacing: 2) { + Text("Current version \(appVersion)") + .font(.caption) + if let last = updater.lastUpdateCheckDate { + Text("Last checked \(last.formatted(.relative(presentation: .named)))") + .font(.caption) + .foregroundStyle(.tertiary) + } + } + Spacer() + Button("Check Now") { + updater.checkForUpdates() + } + .disabled(!updater.canCheckForUpdates) + } + } + .formStyle(.grouped) + } + + private var appVersion: String { + let info = Bundle.main.infoDictionary + let short = info?["CFBundleShortVersionString"] as? String ?? "?" + let build = info?["CFBundleVersion"] as? String ?? "?" + return "\(short) (\(build))" + } + // MARK: - Wine Tab private var wineTab: some View { diff --git a/palium/paliumApp.swift b/palium/paliumApp.swift index 14afd65..9d7e79a 100644 --- a/palium/paliumApp.swift +++ b/palium/paliumApp.swift @@ -9,12 +9,23 @@ import SwiftUI @main struct PaliumApp: App { + /// Referenced here so the Sparkle updater starts at launch and stays alive. + @State private var updater = UpdaterService.shared + var body: some Scene { Window("Palium", id: "main") { ContentView() } .defaultSize(width: 500, height: 400) .windowResizability(.contentSize) + .commands { + CommandGroup(after: .appInfo) { + Button("Check for Updates…") { + updater.checkForUpdates() + } + .disabled(!updater.canCheckForUpdates) + } + } Settings { SettingsView() diff --git a/scripts/appcast.py b/scripts/appcast.py new file mode 100644 index 0000000..3db386e --- /dev/null +++ b/scripts/appcast.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Insert or replace a single release entry in a Sparkle appcast. + +Sparkle's own generate_appcast wants a directory holding every archive ever +shipped, which CI does not have. This keeps the published appcast.xml as the +source of truth and edits one into it per release. +""" + +import argparse +import sys +import xml.etree.ElementTree as ET +from datetime import datetime, timezone +from email.utils import format_datetime + +SPARKLE_NS = "http://www.andymatuschak.org/xml-namespaces/sparkle" +ET.register_namespace("sparkle", SPARKLE_NS) + + +def sparkle(tag): + return f"{{{SPARKLE_NS}}}{tag}" + + +def empty_appcast(title, link, description): + rss = ET.Element("rss", {"version": "2.0"}) + channel = ET.SubElement(rss, "channel") + ET.SubElement(channel, "title").text = title + ET.SubElement(channel, "link").text = link + ET.SubElement(channel, "description").text = description + ET.SubElement(channel, "language").text = "en" + return ET.ElementTree(rss) + + +def load(path, args): + try: + tree = ET.parse(path) + except (FileNotFoundError, ET.ParseError): + return empty_appcast(args.channel_title, args.channel_link, args.channel_description) + if tree.getroot().find("channel") is None: + sys.exit(f"{path}: no element, refusing to overwrite") + return tree + + +def build_item(args): + item = ET.Element("item") + ET.SubElement(item, "title").text = f"Version {args.short_version}" + ET.SubElement(item, sparkle("version")).text = args.version + ET.SubElement(item, sparkle("shortVersionString")).text = args.short_version + if args.minimum_system_version: + ET.SubElement(item, sparkle("minimumSystemVersion")).text = args.minimum_system_version + if args.release_notes_url: + ET.SubElement(item, sparkle("releaseNotesLink")).text = args.release_notes_url + if args.full_release_notes_url: + ET.SubElement(item, sparkle("fullReleaseNotesLink")).text = args.full_release_notes_url + if args.critical: + ET.SubElement(item, sparkle("criticalUpdate")) + pub_date = args.pub_date or format_datetime(datetime.now(timezone.utc)) + ET.SubElement(item, "pubDate").text = pub_date + ET.SubElement( + item, + "enclosure", + { + "url": args.url, + sparkle("edSignature"): args.signature, + "length": str(args.length), + "type": "application/octet-stream", + }, + ) + return item + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("appcast", help="path to appcast.xml (created if missing)") + p.add_argument("--version", required=True, help="CFBundleVersion — Sparkle's ordering key") + p.add_argument("--short-version", required=True, help="CFBundleShortVersionString, e.g. 1.2.0") + p.add_argument("--url", required=True, help="download URL of the .zip enclosure") + p.add_argument("--length", required=True, type=int, help="enclosure size in bytes") + p.add_argument("--signature", required=True, help="EdDSA signature from sign_update") + p.add_argument("--minimum-system-version", default="") + p.add_argument("--release-notes-url", default="") + p.add_argument("--full-release-notes-url", default="") + p.add_argument("--critical", action="store_true") + p.add_argument("--pub-date", default="", help="RFC 2822 date; defaults to now") + p.add_argument("--max-items", type=int, default=10, help="keep at most N most recent entries") + p.add_argument("--channel-title", default="Palium") + p.add_argument("--channel-link", default="https://mgruszkiewicz.github.io/palium/appcast.xml") + p.add_argument("--channel-description", default="Most recent Palium releases") + args = p.parse_args() + + tree = load(args.appcast, args) + channel = tree.getroot().find("channel") + + # Re-releasing the same build replaces the old entry rather than duplicating it. + for existing in channel.findall("item"): + node = existing.find(sparkle("version")) + if node is not None and node.text == args.version: + channel.remove(existing) + + items = channel.findall("item") + insert_at = list(channel).index(items[0]) if items else len(list(channel)) + channel.insert(insert_at, build_item(args)) + + for stale in channel.findall("item")[args.max_items:]: + channel.remove(stale) + + ET.indent(tree, space=" ") + tree.write(args.appcast, encoding="utf-8", xml_declaration=True) + print(f"{args.appcast}: wrote {args.short_version} (build {args.version})") + + +if __name__ == "__main__": + main()