diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23599ef..ff71ab1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,32 +1,55 @@ name: Release +# Two ways in: +# - Pushing a tag vX.Y.Z builds the release and creates a *draft* GitHub Release. +# - Running it by hand (workflow_dispatch) builds the same release and only uploads dist/ +# as an Actions artifact, for review: no tag, no release, no change to the update feed. +# Both run the same `build` job (scripts/release.sh). See docs/releasing.md. on: push: tags: ["v[0-9]+.[0-9]+.[0-9]+"] + workflow_dispatch: permissions: - contents: write + contents: read concurrency: group: release cancel-in-progress: false jobs: - release: - name: Release + build: + name: Build runs-on: macos-26 timeout-minutes: 60 + # Read-only token: this job holds the signing secrets, so it gets no write access. + permissions: + contents: read env: HAS_SIGNING: ${{ secrets.DEVELOPER_ID_CERT_P12_BASE64 != '' }} HAS_NOTARY: ${{ secrets.NOTARY_KEY_P8_BASE64 != '' }} + outputs: + artifact: ${{ steps.version.outputs.artifact }} + signed: ${{ steps.version.outputs.signed }} steps: - uses: actions/checkout@v7 - - name: Check tag matches app version + - name: Read app version + id: version run: | version=$(sed -n 's/^MARKETING_VERSION = //p' apps/macos/Config/Version.xcconfig) - if [[ "v$version" != "$GITHUB_REF_NAME" ]]; then - echo "::error::Tag $GITHUB_REF_NAME does not match MARKETING_VERSION $version" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "artifact=TokenBar-$version-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT" + echo "signed=$HAS_SIGNING" >> "$GITHUB_OUTPUT" + echo "::notice::Building TokenBar $version from $GITHUB_REF_NAME (${GITHUB_SHA::7}), triggered by $GITHUB_EVENT_NAME" + + - name: Check tag matches app version + if: github.event_name == 'push' + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + if [[ "v$VERSION" != "$GITHUB_REF_NAME" ]]; then + echo "::error::Tag $GITHUB_REF_NAME does not match MARKETING_VERSION $VERSION" exit 1 fi @@ -63,20 +86,55 @@ jobs: NOTARY_KEY_ID: ${{ secrets.NOTARY_KEY_ID }} NOTARY_ISSUER_ID: ${{ secrets.NOTARY_ISSUER_ID }} NOTARY_KEY_PATH: ${{ runner.temp }}/notary.p8 - run: scripts/release.sh + # EdDSA private key that signs the update archive for Sparkle. Required. + SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }} + run: | + if [[ -z "$SPARKLE_PRIVATE_KEY" ]]; then + echo "::error::The SPARKLE_PRIVATE_KEY secret is missing (docs/releasing.md › Sparkle)" + exit 1 + fi + scripts/release.sh + + # dist/: TokenBar-[-unsigned].zip (the signed update archive), .dmg, + # appcast.xml and SHA256SUMS.txt. The draft release below is made from this same artifact. + - name: Upload dist/ as an artifact + uses: actions/upload-artifact@v7 + with: + name: ${{ steps.version.outputs.artifact }} + path: dist/ + if-no-files-found: error + retention-days: 14 + + - name: Clean up signing material + if: always() + run: | + security delete-keychain "$RUNNER_TEMP/signing.keychain-db" 2>/dev/null || true + rm -f "$RUNNER_TEMP/notary.p8" + + draft-release: + name: Draft GitHub Release + # Tag pushes only. A manual run ends after the build job uploads its artifact. + if: github.event_name == 'push' + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + + - uses: actions/download-artifact@v8 + with: + name: ${{ needs.build.outputs.artifact }} + path: dist - name: Create draft GitHub Release env: GH_TOKEN: ${{ github.token }} + SIGNED: ${{ needs.build.outputs.signed }} run: | flags=(--draft --title "TokenBar ${GITHUB_REF_NAME#v}") notes="docs/release-notes/$GITHUB_REF_NAME.md" if [[ -f "$notes" ]]; then flags+=(--notes-file "$notes"); else flags+=(--generate-notes); fi - if [[ "$HAS_SIGNING" != "true" ]]; then flags+=(--prerelease); fi + if [[ "$SIGNED" != "true" ]]; then flags+=(--prerelease); fi gh release create "$GITHUB_REF_NAME" dist/* "${flags[@]}" - - - name: Clean up signing material - if: always() - run: | - security delete-keychain "$RUNNER_TEMP/signing.keychain-db" 2>/dev/null || true - rm -f "$RUNNER_TEMP/notary.p8" diff --git a/README.md b/README.md index 85b2541..e6aa251 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,12 @@ directly to the providers. There is no TokenBar server and no account. - **Honest when data is old.** If a refresh fails, you keep the last values with an "outdated" mark instead of an error screen. - **Opens at login**, if you want it to. +- **Updates itself when you ask** (from the first release after 0.1.0). Gear menu › + **Check for Updates…** installs a new version and relaunches TokenBar. It never checks + on its own. - **English and Portuguese (Brazil).** -- **Native and light.** SwiftUI and AppKit, no Electron, no web views, no third-party code. +- **Native and light.** SwiftUI and AppKit, no Electron. The only third-party code is + [Sparkle](https://sparkle-project.org), the standard Mac framework for in-app updates. ## Supported providers @@ -95,6 +99,37 @@ Because the build is unsigned, macOS may ask again for access to Claude Code's K item after you install an update. Signing and notarization are planned after 0.1.0 ([roadmap](docs/roadmap.md)). +### Updating + +> [!NOTE] +> In-app updates are not in a release yet. TokenBar 0.1.0 has no updater; the first +> release after 0.1.0 will be the first one that has it. + +**Where it is:** click the TokenBar icon in the menu bar, then the **gear** button at the +bottom right of the popover, and choose **Check for Updates…** (**Buscar atualizações…** +in Portuguese), just above **Quit TokenBar**. + +If a new version exists, TokenBar shows what changed. Click **Install Update** (**Instalar +Atualização**), then **Install and Relaunch** (**Instalar e Reabrir**). TokenBar quits, +installs the new version and opens again, with your preferences and enabled providers +kept. If you already have the latest version, it says so. TokenBar never checks on its +own; it only looks for updates when you choose this item. + +**Coming from TokenBar 0.1.0?** 0.1.0 has no **Check for Updates…** and cannot update +itself. Install the first version with the updater by hand, once: + +1. Quit TokenBar (gear menu › **Quit TokenBar**). +2. Download the new DMG from the [latest release](https://github.com/DerRafDev/tokenbar/releases/latest). +3. Open it and drag **TokenBar** to **Applications**, choosing **Replace**. +4. Open TokenBar. If that release is unsigned, approve it again with **Open Anyway** as in + the installation steps above. + +Your preferences and enabled providers are kept. From then on, every new version installs +from the gear menu. + +Updates are verified before they are installed: each one is signed with the project's +EdDSA key, and TokenBar refuses an update whose signature does not match. + ### Enabling a provider Every provider starts **disabled**. TokenBar reads nothing until you enable one, and it @@ -116,8 +151,11 @@ sign-in on its next refresh. TokenBar never renews tokens or writes them to disk **Your usage data stays on your Mac.** - TokenBar sends requests only to `api.anthropic.com` (Claude) and `chatgpt.com` (Codex), - and only for the providers you enabled. -- No analytics, telemetry, crash reporting, tracking, or update checks. + and only for the providers you enabled, plus GitHub when you check for updates. +- No analytics, telemetry, crash reporting, or tracking. +- Update checks happen only when you choose **Check for Updates…**. TokenBar then + downloads the release feed from GitHub (`github.com` and its download servers), and + the update itself if you install it. No information about you or your Mac is sent. - No database or history: usage is kept in memory and never written to disk. Network responses are not cached and cookies are not stored. - Sign-ins are read when a refresh needs them. TokenBar keeps the Claude Code token in @@ -142,7 +180,8 @@ From the repository root: scripts/test.sh # build and test TokenBarKit scripts/format.sh # format all Swift sources in place scripts/lint.sh # check formatting and lint rules (what CI runs) -scripts/release.sh # build the DMG and ZIP into dist/ (see docs/releasing.md) +scripts/release.sh # build the DMG, ZIP and appcast into dist/ (see docs/releasing.md) +scripts/test-update.sh build # local in-app update test (see docs/releasing.md) ``` Every build runs the real providers. To work on the UI without accounts, launch a Debug diff --git a/apps/macos/Config/Info.plist b/apps/macos/Config/Info.plist new file mode 100644 index 0000000..01163bb --- /dev/null +++ b/apps/macos/Config/Info.plist @@ -0,0 +1,19 @@ + + + + + + + SUFeedURL + $(SPARKLE_FEED_URL) + SUPublicEDKey + $(SPARKLE_PUBLIC_ED_KEY) + + SUEnableAutomaticChecks + + + SUVerifyUpdateBeforeExtraction + + + diff --git a/apps/macos/Config/TokenBar-AdHoc.entitlements b/apps/macos/Config/TokenBar-AdHoc.entitlements new file mode 100644 index 0000000..49a354c --- /dev/null +++ b/apps/macos/Config/TokenBar-AdHoc.entitlements @@ -0,0 +1,12 @@ + + + + + + com.apple.security.cs.disable-library-validation + + + diff --git a/apps/macos/Config/TokenBar-Debug.entitlements b/apps/macos/Config/TokenBar-Debug.entitlements index 96f7cde..eb25e94 100644 --- a/apps/macos/Config/TokenBar-Debug.entitlements +++ b/apps/macos/Config/TokenBar-Debug.entitlements @@ -6,5 +6,9 @@ The hardened runtime blocks Apple Events without this entitlement. --> com.apple.security.automation.apple-events + + com.apple.security.cs.disable-library-validation + diff --git a/apps/macos/Config/TokenBar.xcconfig b/apps/macos/Config/TokenBar.xcconfig index 293ea62..670d3fe 100644 --- a/apps/macos/Config/TokenBar.xcconfig +++ b/apps/macos/Config/TokenBar.xcconfig @@ -13,6 +13,22 @@ INFOPLIST_KEY_LSUIElement = YES INFOPLIST_KEY_CFBundleDisplayName = TokenBar INFOPLIST_KEY_LSApplicationCategoryType = public.app-category.utilities INFOPLIST_KEY_NSHumanReadableCopyright = © 2026 TokenBar contributors. MIT License. +// Extra keys (Sparkle) that have no INFOPLIST_KEY_ setting. Merged into the generated plist. +INFOPLIST_FILE = Config/Info.plist + +// Sparkle in-app updates (docs/releasing.md). The feed is the appcast.xml attached to the +// latest published GitHub Release, so drafts and pre-releases are never offered. +// `/$()/` keeps `//` from starting an xcconfig comment. +SPARKLE_FEED_URL = https:/$()/github.com/DerRafDev/tokenbar/releases/latest/download/appcast.xml +// Public half of the EdDSA key that signs update archives. Not a secret. The private key is +// never in the repository: it lives in the release maintainer's Keychain and in the +// SPARKLE_PRIVATE_KEY Actions secret. scripts/release.sh refuses to run while this is empty. +SPARKLE_PUBLIC_ED_KEY = +// Sparkle.framework is embedded in Contents/Frameworks. +LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/../Frameworks +// The only binary copied in a copy phase is Sparkle, which ships signed and cannot be +// stripped; leaving this on only produced a "not stripping binary" warning. +COPY_PHASE_STRIP = NO // App icon: TokenBar/AppIcon.icon (Icon Composer). Xcode also derives the .icns used before // macOS 26 from it. The original artwork is docs/assets/app-icon.png. diff --git a/apps/macos/TokenBar.xcodeproj/project.pbxproj b/apps/macos/TokenBar.xcodeproj/project.pbxproj index f51f45d..bd6c9a8 100644 --- a/apps/macos/TokenBar.xcodeproj/project.pbxproj +++ b/apps/macos/TokenBar.xcodeproj/project.pbxproj @@ -10,6 +10,7 @@ 7B0000000000000000000013 /* TokenBarCore in Frameworks */ = {isa = PBXBuildFile; productRef = 7B0000000000000000000011 /* TokenBarCore */; }; 7B0000000000000000000014 /* TokenBarUI in Frameworks */ = {isa = PBXBuildFile; productRef = 7B0000000000000000000012 /* TokenBarUI */; }; 7B0000000000000000000019 /* TokenBarProviders in Frameworks */ = {isa = PBXBuildFile; productRef = 7B0000000000000000000018 /* TokenBarProviders */; }; + 7B000000000000000000001C /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 7B000000000000000000001B /* Sparkle */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -34,6 +35,7 @@ 7B0000000000000000000013 /* TokenBarCore in Frameworks */, 7B0000000000000000000014 /* TokenBarUI in Frameworks */, 7B0000000000000000000019 /* TokenBarProviders in Frameworks */, + 7B000000000000000000001C /* Sparkle in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -89,6 +91,7 @@ 7B0000000000000000000011 /* TokenBarCore */, 7B0000000000000000000012 /* TokenBarUI */, 7B0000000000000000000018 /* TokenBarProviders */, + 7B000000000000000000001B /* Sparkle */, ); productName = TokenBar; productReference = 7B0000000000000000000004 /* TokenBar.app */; @@ -116,6 +119,7 @@ minimizedProjectReferenceProxies = 1; packageReferences = ( 7B0000000000000000000010 /* XCLocalSwiftPackageReference "TokenBarKit" */, + 7B000000000000000000001A /* XCRemoteSwiftPackageReference "Sparkle" */, ); preferredProjectObjectVersion = 77; productRefGroup = 7B0000000000000000000003 /* Products */; @@ -233,6 +237,17 @@ }; /* End XCLocalSwiftPackageReference section */ +/* Begin XCRemoteSwiftPackageReference section */ + 7B000000000000000000001A /* XCRemoteSwiftPackageReference "Sparkle" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/sparkle-project/Sparkle"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 2.10.1; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + /* Begin XCSwiftPackageProductDependency section */ 7B0000000000000000000011 /* TokenBarCore */ = { isa = XCSwiftPackageProductDependency; @@ -246,6 +261,11 @@ isa = XCSwiftPackageProductDependency; productName = TokenBarProviders; }; + 7B000000000000000000001B /* Sparkle */ = { + isa = XCSwiftPackageProductDependency; + package = 7B000000000000000000001A /* XCRemoteSwiftPackageReference "Sparkle" */; + productName = Sparkle; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = 7B0000000000000000000001 /* Project object */; diff --git a/apps/macos/TokenBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/apps/macos/TokenBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..337403a --- /dev/null +++ b/apps/macos/TokenBar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,15 @@ +{ + "originHash" : "4b25fd537a88926542d9d8182b4a8c49415ab1284054d56bf04e086c8b12a588", + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "ab7d71291238df6e0492143b120c9b696a35f603", + "version" : "2.10.1" + } + } + ], + "version" : 3 +} diff --git a/apps/macos/TokenBar/AppDelegate.swift b/apps/macos/TokenBar/AppDelegate.swift index 1f0fb28..966a2f3 100644 --- a/apps/macos/TokenBar/AppDelegate.swift +++ b/apps/macos/TokenBar/AppDelegate.swift @@ -10,6 +10,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let settings: AppSettings let store: UsageStore let launchAtLogin = LaunchAtLogin() + let updater = SoftwareUpdater() /// Sessions waiting for the user. `nil` unless agent monitoring runs (Debug prototype). let agents: AgentActivityStore? /// Brings a waiting session's window to the front. `nil` with ``agents``. diff --git a/apps/macos/TokenBar/SoftwareUpdater.swift b/apps/macos/TokenBar/SoftwareUpdater.swift new file mode 100644 index 0000000..a307934 --- /dev/null +++ b/apps/macos/TokenBar/SoftwareUpdater.swift @@ -0,0 +1,33 @@ +import AppKit +import Observation +import Sparkle +import TokenBarUI + +/// In-app updates with Sparkle's standard dialogs. Checks only when the user asks +/// (`SUEnableAutomaticChecks` is off in Config/Info.plist). The feed and the public EdDSA key +/// come from build settings; see docs/releasing.md. +@MainActor +@Observable +final class SoftwareUpdater: UpdateChecking { + private(set) var canCheckForUpdates = false + + @ObservationIgnored private let controller: SPUStandardUpdaterController + @ObservationIgnored private var observation: NSKeyValueObservation? + + init() { + controller = SPUStandardUpdaterController( + startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil) + canCheckForUpdates = controller.updater.canCheckForUpdates + // Sparkle changes this on the main thread. + observation = controller.updater.observe(\.canCheckForUpdates, options: [.new]) { [weak self] _, change in + guard let canCheck = change.newValue else { return } + MainActor.assumeIsolated { self?.canCheckForUpdates = canCheck } + } + } + + func checkForUpdates() { + // TokenBar has no Dock icon, so bring it forward or Sparkle's window opens behind others. + NSApp.activate() + controller.checkForUpdates(nil) + } +} diff --git a/apps/macos/TokenBar/TokenBarApp.swift b/apps/macos/TokenBar/TokenBarApp.swift index 7192f0e..0f20726 100644 --- a/apps/macos/TokenBar/TokenBarApp.swift +++ b/apps/macos/TokenBar/TokenBarApp.swift @@ -8,7 +8,12 @@ struct TokenBarApp: App { var body: some Scene { MenuBarExtra { - UsagePopover(store: appDelegate.store, agents: appDelegate.agents, navigator: appDelegate.navigator) + UsagePopover( + store: appDelegate.store, + agents: appDelegate.agents, + navigator: appDelegate.navigator, + updates: appDelegate.updater + ) } label: { MenuBarLabel(store: appDelegate.store, settings: appDelegate.settings, agents: appDelegate.agents) } diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings b/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings index 04f88d8..4f69eb2 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/Resources/pt-BR.lproj/Localizable.strings @@ -9,6 +9,7 @@ "Allow TokenBar in Login Items to open it at login." = "Permita o TokenBar em Itens de Início para abri-lo ao iniciar sessão."; "Already answered or cancelled? Remove it from the list." = "Já respondeu ou cancelou? Remova da lista."; "Cancel" = "Cancelar"; +"Check for Updates…" = "Buscar atualizações…"; "Checking…" = "Verificando…"; "Configure Providers…" = "Configurar provedores…"; "Could not change this setting. Try again in System Settings › General › Login Items." = "Não foi possível alterar este ajuste. Tente novamente em Ajustes do Sistema › Geral › Itens de Início."; diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/Support/UpdateChecking.swift b/apps/macos/TokenBarKit/Sources/TokenBarUI/Support/UpdateChecking.swift new file mode 100644 index 0000000..1fec315 --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/Support/UpdateChecking.swift @@ -0,0 +1,11 @@ +/// Checks for a newer TokenBar on request. The app implements it with Sparkle, which owns the +/// update dialogs (found, downloading, install and relaunch, up to date, errors). +/// +/// Lives here so the popover can offer *Check for Updates…* without depending on Sparkle. +@MainActor +public protocol UpdateChecking: AnyObject { + /// False while a check or an update is already in progress. + var canCheckForUpdates: Bool { get } + /// Starts a user-initiated check and shows its result. + func checkForUpdates() +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift b/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift index c7fd2cb..397e495 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift +++ b/apps/macos/TokenBarKit/Sources/TokenBarUI/UsagePopover.swift @@ -7,6 +7,8 @@ public struct UsagePopover: View { let store: UsageStore let agents: AgentActivityStore? let navigator: AgentSessionNavigator? + /// Offers *Check for Updates…* in the gear menu when set. + let updates: (any UpdateChecking)? let formatter: UsageFormatter @State private var isVisible = false @@ -22,11 +24,13 @@ public struct UsagePopover: View { store: UsageStore, agents: AgentActivityStore? = nil, navigator: AgentSessionNavigator? = nil, + updates: (any UpdateChecking)? = nil, formatter: UsageFormatter = UsageFormatter() ) { self.store = store self.agents = agents self.navigator = navigator + self.updates = updates self.formatter = formatter _tab = State(initialValue: PopoverTab.initial(pendingCount: agents?.pendingCount ?? 0)) } @@ -169,6 +173,12 @@ public struct UsagePopover: View { showSettings() } .keyboardShortcut(",") + if let updates { + Button(String(localized: "Check for Updates…", bundle: .module)) { + updates.checkForUpdates() + } + .disabled(!updates.canCheckForUpdates) + } Divider() Button(String(localized: "Quit TokenBar", bundle: .module)) { NSApp.terminate(nil) diff --git a/docs/architecture.md b/docs/architecture.md index 1720976..18242a7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,8 +9,8 @@ the few boundaries that exist and why each one does. tokenbar/ ├── apps/ │ ├── macos/ # The native macOS app -│ │ ├── TokenBar.xcodeproj # Thin app target: entry point, Info.plist, signing -│ │ ├── TokenBar/ # App sources (composition root only) +│ │ ├── TokenBar.xcodeproj # Thin app target: entry point, Info.plist, signing, Sparkle +│ │ ├── TokenBar/ # App sources: composition root and the Sparkle updater │ │ └── TokenBarKit/ # Swift package with all logic and all tests │ └── web/ # The official website (static Astro site, own npm project) ├── docs/ # Architecture, providers, releasing, roadmap @@ -217,8 +217,12 @@ Claude Code hook ──curl──▶ LocalHookServer (127.0.0.1) ──▶ Claud never synced to iCloud. Nothing sensitive goes in `UserDefaults`, files, or logs. - Logging uses `os.Logger` with privacy annotations. Tokens, cookies, account IDs, authenticated URLs, and response bodies are never logged. -- No TokenBar backend. The app talks only to provider endpoints. - *Usage data stays on your Mac.* +- No TokenBar backend. The app talks only to provider endpoints, and to GitHub when the + user chooses **Check for Updates…**. *Usage data stays on your Mac.* +- Updates (Sparkle) are checked only on request (`SUEnableAutomaticChecks` is off), without + system profiling. Each archive must carry an EdDSA signature that matches `SUPublicEDKey` + in the running app, checked before extraction (`SUVerifyUpdateBeforeExtraction`). The + private key never enters the repository. See [releasing.md](releasing.md#sparkle-in-app-updates). - The agent alerts prototype exists only in Debug builds and only when launched with `TOKENBAR_AGENT_HOOKS=1`. Its listener binds to 127.0.0.1, accepts small `POST`s, answers `200` with an empty body (so a hook never makes a decision for Claude Code), and stores and logs @@ -229,6 +233,9 @@ Claude Code hook ──curl──▶ LocalHookServer (127.0.0.1) ──▶ Claud ## Dependencies -None. Foundation, SwiftUI, AppKit, Security, ServiceManagement, and OSLog cover +One: [Sparkle 2](https://sparkle-project.org) (Swift Package Manager, app target only), for +in-app updates with the standard Mac dialogs. `TokenBarKit` does not depend on it; the +popover sees only the `UpdateChecking` protocol, which `SoftwareUpdater` in the app target +implements. Foundation, SwiftUI, AppKit, Security, ServiceManagement, and OSLog cover networking, JSON, Keychain, dates, and UI. The Debug-only agent listener uses Network. Lint and formatting use `swift format`, which ships with Xcode. diff --git a/docs/release-checklist.md b/docs/release-checklist.md index 4340a35..78171ce 100644 --- a/docs/release-checklist.md +++ b/docs/release-checklist.md @@ -67,8 +67,29 @@ defaults delete io.github.derrafdev.TokenBar # TokenBar's preferences only - [ ] Quit from the popover's gear menu and reopen: enabled providers, menu bar mode and refresh interval are kept, and Claude does not prompt again. +## Updates + +- [ ] `scripts/test-update.sh build` and its three scenarios pass (update installs, relaunches + and keeps preferences; "up to date"; bad signature refused). See + [releasing.md › Testing an update locally](releasing.md#testing-an-update-locally). +- [ ] Gear menu shows **Check for Updates…** (English) and **Buscar atualizações…** + (Portuguese). Before publishing, a check against the public feed says you are up to + date, because the latest release is older. (Until the first updater release is + published, it shows an error instead: 0.1.0 has no `appcast.xml`.) +- [ ] Dry run of the Release workflow on `main` passed and its artifact checks out + ([releasing.md › Dry run](releasing.md#dry-run-build-a-release-without-publishing)): + checksums, appcast version, build number, download URL + (`…/releases/download/v/TokenBar-[-unsigned].zip`), length, notes, + EdDSA signature, and `SUPublicEDKey` in the app. + ## Before publishing - [ ] README demo (`docs/assets/demo.gif`) matches the app as released. -- [ ] Draft release: notes are right, artifacts are `TokenBar-.dmg`, `.zip` and - `SHA256SUMS.txt`, and the version matches the tag. +- [ ] Draft release: notes are right, artifacts are `TokenBar-[-unsigned].dmg`, + `.zip`, `appcast.xml` and `SHA256SUMS.txt`, and the version matches the tag. +- [ ] Draft's `appcast.xml` checked as in + [releasing.md › Reviewing the draft](releasing.md#reviewing-the-draft): signature + verifies, `length` matches, and the `enclosure` URL names this tag and this zip. +- [ ] Publishing as *latest* offers this version to every installed TokenBar that checks for + updates. An unsigned draft starts as a pre-release: untick it and tick *Set as the + latest release*. diff --git a/docs/releasing.md b/docs/releasing.md index 8345145..a788c2c 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -19,27 +19,132 @@ $EDITOR docs/release-notes/v0.2.0.md # user-facing notes for the GitHub git commit -am "chore(release): prepare TokenBar 0.2.0" # open PR → CI green → merge git switch main && git pull -# run the manual checklist: docs/release-checklist.md -git tag v0.2.0 && git push origin v0.2.0 +scripts/test-update.sh build # 1. in-app update test (Testing an update locally) +gh workflow run release.yml --ref main # 2. dry run in Actions (Dry run) +# 3. download and check the dry run's zip and appcast.xml +# 4. run the manual checklist: docs/release-checklist.md +git tag v0.2.0 && git push origin v0.2.0 # 5. builds again and creates a draft +# 6. review the draft (Reviewing the draft), then publish it as the latest release ``` -The [Release workflow](../.github/workflows/release.yml) then runs: +The [Release workflow](../.github/workflows/release.yml) has two jobs: ```text -verify tag → tests → archive → sign → notarize app → staple → zip + dmg → sign + notarize dmg → SHA256SUMS → draft GitHub Release +build: [tag only: verify tag] → tests → archive → sign (app + Sparkle) → notarize app → staple → zip + dmg → sign + notarize dmg → EdDSA-sign zip → appcast.xml → SHA256SUMS → upload dist/ artifact +draft-release: [tag only] download that artifact → draft GitHub Release ``` -It creates a **draft**. Its notes come from `docs/release-notes/.md` (GitHub's -generated notes when that file is missing). Review the draft and its artifacts, then -publish it on GitHub. Nothing is published automatically. +A tag push runs both and ends with a **draft**. Its notes come from +`docs/release-notes/.md` (GitHub's generated notes when that file is missing). A +manual run (dry run) runs only `build`. Nothing is published automatically. + +**Publishing is what ships the update.** Installed copies read +`releases/latest/download/appcast.xml`, which is the `appcast.xml` attached to the latest +published, non-prerelease GitHub Release. A draft or a pre-release is invisible to them; +the moment you publish (as latest), every TokenBar that checks for updates is offered it. GitHub Releases are the changelog; there is no separate `CHANGELOG.md`. +## Dry run: build a release without publishing + +Running the Release workflow by hand (`workflow_dispatch`) runs the same `build` job as a tag +push, with the same secrets and the same `scripts/release.sh`, and stops after uploading +`dist/` as an Actions artifact. It creates no tag and no release, and does not change the +update feed (installed copies only read releases that are published). The job has a +read-only token; only the tag-only `draft-release` job can write to the repository. + +**Before you can run it:** + +- The workflow file with `workflow_dispatch` must be on the **default branch** (`main`). + GitHub offers *Run workflow* and accepts `gh workflow run` only for workflows that exist + there. Once it is merged, you can run it on any branch or tag; the run uses the workflow + file and the code of the ref you choose. Until then, not even this branch can trigger it. +- The ref must have `SPARKLE_PUBLIC_ED_KEY` set, and the `SPARKLE_PRIVATE_KEY` secret must + exist; otherwise the run fails, as a tag release would. + +**Run it**, either in the browser (*Actions › Release › Run workflow*, pick the branch, *Run +workflow*) or: + +```sh +gh workflow run release.yml --ref main # or a release branch +gh run watch "$(gh run list --workflow release.yml --limit 1 --json databaseId -q '.[0].databaseId')" +``` + +The run summary shows the version and commit it built (`Building TokenBar 0.2.0 from main +(abc1234)`), and the artifact `TokenBar--`, kept for 14 days. + +**Download and check it:** + +```sh +run=$(gh run list --workflow release.yml --limit 1 --json databaseId -q '.[0].databaseId') +gh run download "$run" -D review/ # unpacks to review/TokenBar--/ +cd review/TokenBar-*/ +ls # TokenBar-[-unsigned].zip, .dmg, appcast.xml, SHA256SUMS.txt +shasum -a 256 -c SHA256SUMS.txt # zip and dmg match their checksums +xmllint --noout appcast.xml # well-formed +grep -E 'sparkle:(version|shortVersionString|minimumSystemVersion)|enclosure' appcast.xml +``` + +In `appcast.xml`, check: + +- `sparkle:shortVersionString` is the version, and `sparkle:version` the build number, both + higher than the release currently published. +- The `enclosure` URL is + `https://github.com/DerRafDev/tokenbar/releases/download/v/`. + It only resolves once that release is published; a 404 now is expected. +- `length` equals `stat -f %z TokenBar-*.zip`. +- The release notes in `` are `docs/release-notes/v.md`. + +Then check the zip's signature, and that the app inside trusts your production key: + +```sh +bin=~/Documents/programming/tokenbar/build/SourcePackages/artifacts/sparkle/Sparkle/bin +sig=$(sed -n 's/.*sparkle:edSignature="\([^"]*\)".*/\1/p' appcast.xml) +$bin/sign_update --verify TokenBar-*.zip "$sig" # uses the key in your Keychain; silent on success +ditto -x -k TokenBar-*.zip app/ +plutil -extract SUPublicEDKey raw app/TokenBar.app/Contents/Info.plist # = $bin/generate_keys -p +plutil -extract SUFeedURL raw app/TokenBar.app/Contents/Info.plist # the public feed +codesign --verify --deep --strict --verbose=2 app/TokenBar.app +``` + +With Developer ID and notarization configured, also `spctl -a -vv app/TokenBar.app` +(`source=Notarized Developer ID`) and `xcrun stapler validate app/TokenBar.app`. + +A dry run proves the pipeline and the inputs, but the tag push builds again, so the draft's +files are new bytes (new signatures and timestamps). Review the draft too. + +## Reviewing the draft + +The tag push ends with a draft release whose assets are the `build` job's `dist/`. Drafts +are visible only to maintainers and invisible to installed copies. Before publishing: + +```sh +gh release view v0.2.0 # draft: true; notes; asset list +gh release download v0.2.0 -D draft/ # zip, dmg, appcast.xml, SHA256SUMS.txt +cd draft/ +``` + +Run the same checks as for a dry run (checksums, `appcast.xml` fields, `sign_update +--verify`, `SUPublicEDKey`, `codesign`). Also check: + +- The asset file names on the draft match the file name in the `enclosure` URL, character + for character, and the tag in that URL is the draft's tag. After publishing, that URL + is where installed copies download the update. +- `appcast.xml` is attached; without it, `releases/latest/download/appcast.xml` returns 404 + after publishing and every update check shows an error. +- The notes on the draft and in the appcast's `` say the same thing. + +Then publish from the draft's page (*Edit*). For an unsigned build, untick *Set as a +pre-release* and tick *Set as the latest release*. Publishing is the moment the update +reaches users; to stop a bad release afterwards, edit it back to a draft or a pre-release, +which removes it from the feed. + ## Secrets -Configure in *Settings → Secrets and variables → Actions*. All are optional: without -them the release is ad-hoc signed, its artifacts are suffixed `-unsigned`, and the draft -is marked prerelease. macOS Gatekeeper blocks unsigned apps on first launch. +Configure in *Settings → Secrets and variables → Actions*. The signing and notarization +secrets are optional: without them the release is ad-hoc signed, its artifacts are +suffixed `-unsigned`, and the draft is marked prerelease. macOS Gatekeeper blocks unsigned +apps on first launch. To ship an unsigned build as the main release (as 0.1.0 does), untick *Set as a pre-release* and tick *Set as the latest release* before publishing the draft. GitHub's @@ -54,8 +159,12 @@ pre-release* and tick *Set as the latest release* before publishing the draft. G | `NOTARY_KEY_P8_BASE64` | App Store Connect API key (`.p8`, role *Developer*), base64-encoded | | `NOTARY_KEY_ID` | Key ID of that API key | | `NOTARY_ISSUER_ID` | Issuer ID from App Store Connect → Users and Access → Integrations | +| `SPARKLE_PRIVATE_KEY` | **Required.** EdDSA private key that signs updates (see [Sparkle](#sparkle-in-app-updates)) | -Encode files with `base64 -i file.p12 | pbcopy`. Never commit them. +Encode files with `base64 -i file.p12 | pbcopy`. Never commit them. The Developer ID and +notary secrets are optional; `SPARKLE_PRIVATE_KEY` is not: without it the workflow stops +before building, because a release without a signed appcast could not be installed by the +updater. Getting them requires a paid Apple Developer Program membership: create a *Developer ID Application* certificate in Xcode (Settings → Accounts → Manage Certificates) or the @@ -74,4 +183,111 @@ scripts/release.sh # ad-hoc signed, output in dist/ Export the same variables as the table above (with `NOTARY_KEY_PATH` pointing at the `.p8` file) to sign and notarize locally. Requires Xcode 26 or later (the app icon is an -Icon Composer file). +Icon Composer file). Locally, the Sparkle key is read from your login Keychain, so +`SPARKLE_PRIVATE_KEY` is not needed there. + +## Sparkle (in-app updates) + +TokenBar updates itself with [Sparkle 2](https://sparkle-project.org), added through Swift +Package Manager to the app target. The user opens the gear menu, chooses **Check for +Updates…**, and Sparkle's standard dialogs do the rest (release notes, download, **Install +and Relaunch**). There are no background checks. + +| Piece | Where | +|---|---| +| Feed URL | `SPARKLE_FEED_URL` in `apps/macos/Config/TokenBar.xcconfig`: `https://github.com/DerRafDev/tokenbar/releases/latest/download/appcast.xml` | +| Public key | `SPARKLE_PUBLIC_ED_KEY` in the same file, written to `SUPublicEDKey` | +| Other Sparkle settings | `apps/macos/Config/Info.plist` (merged into the generated Info.plist) | +| Update archive | `TokenBar-[-unsigned].zip`, the same zip users can download | +| Appcast | `dist/appcast.xml`, written by `scripts/appcast.sh`, one item: the new version, its EdDSA signature, minimum macOS, and `docs/release-notes/v.md` as Markdown | +| Private key | Your login Keychain (local) and the `SPARKLE_PRIVATE_KEY` Actions secret. **Never** in the repository. | + +`scripts/release.sh` signs the zip, then checks the signature against the public key inside +the app it just built, and stops if they are not a pair. It also refuses to build while +`SPARKLE_PUBLIC_ED_KEY` is empty. + +### One-time setup: the signing key + +```sh +xcodebuild -resolvePackageDependencies -project apps/macos/TokenBar.xcodeproj \ + -clonedSourcePackagesDirPath build/SourcePackages +bin=build/SourcePackages/artifacts/sparkle/Sparkle/bin + +$bin/generate_keys # creates the key in your login Keychain, prints the public key +$bin/generate_keys -x sparkle-key.txt # exports the private key to a file, for the secret +``` + +1. Put the printed public key in `SPARKLE_PUBLIC_ED_KEY` (`TokenBar.xcconfig`) and commit it. + It is not a secret. +2. Paste the contents of `sparkle-key.txt` into the `SPARKLE_PRIVATE_KEY` Actions secret, + then delete the file (`rm -P sparkle-key.txt`). +3. Back up the Keychain item *Private key for signing Sparkle updates* (for example in your + password manager). **If the key is lost, installed copies can never be updated again**: + users would have to install the next version by hand. Sparkle can rotate keys only while + the Apple code signing identity stays the same, which ad-hoc builds do not have. + +### Signing, notarization and the first updater release + +What the project has today: the pipeline signs with Developer ID, uses the hardened runtime, +notarizes and staples the app and the DMG, but only when the secrets exist. No Developer ID +or notary secrets are configured in the repository yet, so 0.1.0 and any release built now +is ad-hoc signed (`-unsigned`). + +The updater works either way. Sparkle accepts an update when its EdDSA signature matches, +even if the Apple signing identity changes, so going from an ad-hoc build to a Developer ID +build later is a normal update. Ad-hoc builds carry one extra entitlement, +`com.apple.security.cs.disable-library-validation` (`Config/TokenBar-AdHoc.entitlements`), +because the hardened runtime otherwise refuses to load Sparkle.framework without a Team ID; +Developer ID builds do not need it and do not get it. Sparkle removes the quarantine flag +from what it installs, so an unsigned update does not go through *Open Anyway* again, but +macOS asks again for Claude's Keychain item after each unsigned update. + +What is missing to ship the first version with the updater: + +- [ ] `SPARKLE_PUBLIC_ED_KEY` committed and `SPARKLE_PRIVATE_KEY` secret set (above). Required. +- [ ] The Sparkle changes, including the `workflow_dispatch` trigger, merged into `main`, so + the dry run can be started. +- [ ] A dry run on `main` passed and its zip and `appcast.xml` check out (Dry run). +- [ ] Optional but recommended: the Developer ID and notary secrets. With them, the release + script re-signs Sparkle's helpers (`Autoupdate`, `Updater.app`, the XPC services) with + the Developer ID and the hardened runtime, as notarization requires. This path cannot be + tested without a certificate; check the first notarized release's log. +- [ ] Release notes for the version, telling 0.1.0 users to install it by hand (README › + Updating). +- [ ] An unsigned draft is marked pre-release; untick that and tick *Set as the latest release* + before publishing, or the feed keeps pointing at the previous release. + +### Testing an update locally + +`scripts/test-update.sh` runs the real release script twice with test settings: versions +0.90.0 and 0.91.0, bundle ID `io.github.derrafdev.TokenBar.updatetest` (your TokenBar +preferences are not touched), a throwaway EdDSA key, and a feed on +`http://127.0.0.1:8765`. Nothing is published and no real key is used. + +```sh +scripts/test-update.sh build # ~3 min; everything goes to build/update-test/ +scripts/test-update.sh serve # in a second terminal; keep it running +scripts/test-update.sh install # installs and opens 0.90.0 +defaults write io.github.derrafdev.TokenBar.updatetest menuBarDisplay detailed +``` + +Quit and reopen the test app (from `build/update-test/Installed/`) so it reads that +preference. A second TokenBar icon appears in the menu bar; it is the test copy. Then: + +1. **Update.** Gear menu › **Check for Updates…** → the dialog offers 0.91.0 with the test + notes → **Install Update** → **Install and Relaunch**. TokenBar reopens; + `plutil -extract CFBundleShortVersionString raw build/update-test/Installed/TokenBar.app/Contents/Info.plist` + says `0.91.0`, and `defaults read io.github.derrafdev.TokenBar.updatetest` still has + `menuBarDisplay = detailed`. +2. **No update.** `scripts/test-update.sh install`, `scripts/test-update.sh feed none`, + check again → "You're up to date!" ("O app está atualizado!" in Portuguese). +3. **Bad signature.** `scripts/test-update.sh install`, `scripts/test-update.sh feed bad-signature`, + check, **Install Update** → Sparkle downloads the zip, refuses it with an error, and + 0.90.0 stays installed. + +`scripts/test-update.sh feed update` restores the good feed. `scripts/test-update.sh clean` +quits the test app and deletes it with its preferences. + +These are test builds. The release candidate itself is checked with the dry run in Actions +([Dry run](#dry-run-build-a-release-without-publishing)). Without Actions, `scripts/release.sh` +builds the same files into `dist/` with the key in your Keychain, and the same checks apply. diff --git a/docs/roadmap.md b/docs/roadmap.md index 7e08ef6..1cd3212 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -15,6 +15,7 @@ merged pull requests. | Item | Status | |---|---| | **Windows app** | Being planned. No release date and no download yet. | +| **In-app updates** (Sparkle, gear menu › Check for Updates…) | Built and tested locally with release builds. Ships with the first release after 0.1.0, once the release signing key is configured. 0.1.0 users install that release by hand once ([README › Updating](../README.md#updating)). | ## After 0.1.0 @@ -26,7 +27,7 @@ Candidates, not commitments. Each needs evidence that it works reliably before i | **Codex Keychain sign-in** (`cli_auth_credentials_store = "keyring"`) | Needs a verified capture of the item's format. Until then those installations show "Not connected". | | **Codex 403 vs. workspace without Codex** | Needs a captured 403 response that tells the two apart. Both show "Sign-in expired" today. | | **Refresh when the network comes back** | Today data stays marked outdated until the next scheduled refresh after an outage. | -| **Automatic updates** | Would add the first network request not made for a provider. Needs a privacy-preserving design. | +| **Automatic update checks** | Manual checks ship with Sparkle (gear menu › Check for Updates…). Checking in the background would add a request the user did not ask for; needs a privacy-preserving design and an opt-in. | | **More providers** (Gemini, Cursor, Copilot, …) | Only with a reliable, documented-enough source. Start with a section in [providers.md](providers.md). | | **Menu bar customization** | Driven by dogfooding feedback. | | **Agent alerts: Claude Code questions** | Debug-only prototype ([agents.md](agents.md)). Validated with real sessions: structured questions (`AskUserQuestion`) in the menu bar and popover, `2 → 1 → usage` as they are answered, and **Go to Session** in Terminal.app. Before a release: listener authentication, installing and removing hooks from Settings with consent, and a safe edit of `~/.claude/settings.json`. | diff --git a/scripts/appcast.sh b/scripts/appcast.sh new file mode 100755 index 0000000..8a94d46 --- /dev/null +++ b/scripts/appcast.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# Signs an update archive with EdDSA and writes a Sparkle appcast with one item for it. +# Called by scripts/release.sh; runnable on its own. +# +# scripts/appcast.sh APP ZIP DOWNLOAD_URL OUTPUT [NOTES_MD] [RELEASE_PAGE_URL] +# +# APP The TokenBar.app inside ZIP (version, minimum macOS, public key are read here) +# ZIP The archive Sparkle downloads +# DOWNLOAD_URL Where ZIP will be served (the GitHub Release asset URL) +# OUTPUT appcast.xml to write +# NOTES_MD Optional Markdown release notes shown in the update dialog +# RELEASE_PAGE_URL Optional link for "Version History" / full release notes +# +# The private key is read from, in order: +# SPARKLE_PRIVATE_KEY the key itself (the Actions secret); passed to sign_update on stdin +# SPARKLE_PRIVATE_KEY_FILE a file holding the key +# the login Keychain where Sparkle's generate_keys stores it +# +# Fails unless the signature verifies against the app's SUPublicEDKey, so a release can never +# carry a signature that installed copies would reject. +set -euo pipefail + +if [[ $# -lt 4 ]]; then + sed -n '4,6p' "$0" >&2 + exit 64 +fi +app=$1 zip=$2 url=$3 out=$4 notes=${5:-} page=${6:-} +root="$(cd "$(dirname "$0")/.." && pwd)" +bin="${SPARKLE_BIN:-$root/build/SourcePackages/artifacts/sparkle/Sparkle/bin}" + +if [[ ! -x "$bin/sign_update" ]]; then + echo "error: $bin/sign_update not found; resolve packages first (scripts/release.sh does)" >&2 + exit 1 +fi + +plist="$app/Contents/Info.plist" +read_plist() { plutil -extract "$1" raw "$plist"; } +build=$(read_plist CFBundleVersion) +version=$(read_plist CFBundleShortVersionString) +minimum=$(read_plist LSMinimumSystemVersion) +public_key=$(read_plist SUPublicEDKey 2>/dev/null || true) +if [[ -z "$public_key" ]]; then + echo "error: $app has no SUPublicEDKey; set SPARKLE_PUBLIC_ED_KEY (docs/releasing.md)" >&2 + exit 1 +fi + +if [[ -n "${SPARKLE_PRIVATE_KEY:-}" ]]; then + signature=$(printf '%s' "$SPARKLE_PRIVATE_KEY" | "$bin/sign_update" --ed-key-file - -p "$zip") +elif [[ -n "${SPARKLE_PRIVATE_KEY_FILE:-}" ]]; then + signature=$("$bin/sign_update" --ed-key-file "$SPARKLE_PRIVATE_KEY_FILE" -p "$zip") +else + signature=$("$bin/sign_update" -p "$zip") +fi + +# Check with the public key the app ships, not the one derived from the private key. +verifier=$(mktemp -t tokenbar-verify).swift +trap 'rm -f "$verifier"' EXIT +cat > "$verifier" <<'SWIFT' +import CryptoKit +import Foundation +let args = CommandLine.arguments +guard let keyData = Data(base64Encoded: args[1]), let signature = Data(base64Encoded: args[2]), + let key = try? Curve25519.Signing.PublicKey(rawRepresentation: keyData), + let file = FileManager.default.contents(atPath: args[3]), + key.isValidSignature(signature, for: file) +else { exit(1) } +SWIFT +if ! xcrun swift "$verifier" "$public_key" "$signature" "$zip"; then + echo "error: the update signature does not match SUPublicEDKey in $app;" \ + "the private key and SPARKLE_PUBLIC_ED_KEY are not a pair" >&2 + exit 1 +fi + +length=$(stat -f %z "$zip") +pub_date=$(LC_ALL=C date -u "+%a, %d %b %Y %H:%M:%S +0000") + +{ + echo '' + echo '' + echo ' ' + echo ' TokenBar' + echo ' ' + echo " TokenBar $version" + echo " $pub_date" + echo " $build" + echo " $version" + echo " $minimum" + if [[ -n "$page" ]]; then + echo " $page" + fi + if [[ -n "$notes" ]]; then + if grep -q ']]>' "$notes"; then + echo "error: $notes contains ']]>', which cannot go in the appcast" >&2 + exit 1 + fi + echo ' ' + fi + echo " " + echo ' ' + echo ' ' + echo '' +} > "$out" + +xmllint --noout "$out" +echo "Appcast: TokenBar $version (build $build) → $out" diff --git a/scripts/release.sh b/scripts/release.sh index 734b6e0..e8a5336 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Builds a TokenBar release: archive → sign → notarize → package → checksum. +# Builds a TokenBar release: archive → sign → notarize → package → appcast → checksum. # Output goes to dist/. Used by .github/workflows/release.yml and runnable locally. # # Signing and notarization only run when their variables are set. Without them the app @@ -10,16 +10,27 @@ # NOTARY_KEY_PATH Path to an App Store Connect API key (.p8) # NOTARY_KEY_ID API key ID # NOTARY_ISSUER_ID API issuer ID +# +# The Sparkle appcast (dist/appcast.xml) is always produced and needs the EdDSA private key: +# SPARKLE_PRIVATE_KEY, SPARKLE_PRIVATE_KEY_FILE or the login Keychain (see scripts/appcast.sh). +# +# For local update tests only (scripts/test-update.sh): +# RELEASE_DIST Output directory instead of dist/ +# RELEASE_WORK Work directory instead of build/release +# RELEASE_BUILD_SETTINGS Extra xcodebuild settings, space-separated (e.g. a test feed URL) +# SPARKLE_DOWNLOAD_URL Where the zip will be served instead of the GitHub Release set -euo pipefail cd "$(dirname "$0")/.." -version=$(sed -n 's/^MARKETING_VERSION = //p' apps/macos/Config/Version.xcconfig) -work=build/release +work="${RELEASE_WORK:-build/release}" +dist="${RELEASE_DIST:-dist}" +packages=build/SourcePackages archive="$work/TokenBar.xcarchive" app="$archive/Products/Applications/TokenBar.app" +read -r -a extra_settings <<< "${RELEASE_BUILD_SETTINGS:-}" -rm -rf "$work" dist -mkdir -p "$work" dist +rm -rf "$work" "$dist" +mkdir -p "$work" "$dist" sign_args=() suffix="" @@ -32,24 +43,53 @@ if [[ -n "${DEVELOPER_ID_IDENTITY:-}" ]]; then else echo "warning: DEVELOPER_ID_IDENTITY not set; producing an ad-hoc signed build" >&2 suffix="-unsigned" + # Lets the ad-hoc app load the embedded Sparkle.framework; see the file for why. + sign_args=(CODE_SIGN_ENTITLEMENTS=Config/TokenBar-AdHoc.entitlements) +fi + +if [[ -n "${NOTARY_KEY_ID:-}" && -n "$suffix" ]]; then + echo "error: notarization requires a Developer ID signed build" >&2 + exit 1 fi -echo "==> Archiving TokenBar $version" +echo "==> Archiving TokenBar" xcodebuild archive -quiet \ -project apps/macos/TokenBar.xcodeproj \ -scheme TokenBar \ -configuration Release \ -destination 'generic/platform=macOS' \ -archivePath "$archive" \ - ${sign_args[@]+"${sign_args[@]}"} + -clonedSourcePackagesDirPath "$packages" \ + ${sign_args[@]+"${sign_args[@]}"} \ + ${extra_settings[@]+"${extra_settings[@]}"} -codesign --verify --deep --strict "$app" +version=$(plutil -extract CFBundleShortVersionString raw "$app/Contents/Info.plist") +build=$(plutil -extract CFBundleVersion raw "$app/Contents/Info.plist") +echo "==> Built TokenBar $version (build $build)" -if [[ -n "${NOTARY_KEY_ID:-}" && -n "$suffix" ]]; then - echo "error: notarization requires a Developer ID signed build" >&2 +if [[ -z "$(plutil -extract SUPublicEDKey raw "$app/Contents/Info.plist" 2>/dev/null || true)" ]]; then + echo "error: SPARKLE_PUBLIC_ED_KEY is empty in apps/macos/Config/TokenBar.xcconfig;" \ + "installed copies could not verify updates (docs/releasing.md › Sparkle)" >&2 exit 1 fi +# Sparkle ships ad-hoc signed helpers. Xcode re-signs only the framework itself, so the +# helpers, then the framework, then the app are signed again, innermost first, with the +# release identity and the hardened runtime (as Sparkle's documentation describes). +echo "==> Signing Sparkle" +identity="${DEVELOPER_ID_IDENTITY:--}" +codesign_args=(--force --sign "$identity" --options runtime) +if [[ -n "${DEVELOPER_ID_IDENTITY:-}" ]]; then codesign_args+=(--timestamp); fi +sparkle="$app/Contents/Frameworks/Sparkle.framework" +codesign "${codesign_args[@]}" "$sparkle/Versions/B/XPCServices/Installer.xpc" +codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$sparkle/Versions/B/XPCServices/Downloader.xpc" +codesign "${codesign_args[@]}" "$sparkle/Versions/B/Autoupdate" +codesign "${codesign_args[@]}" "$sparkle/Versions/B/Updater.app" +codesign "${codesign_args[@]}" "$sparkle" +codesign "${codesign_args[@]}" --preserve-metadata=entitlements,requirements,flags "$app" + +codesign --verify --deep --strict "$app" + # Submits a file for notarization and fails unless Apple accepts it. `notarytool --wait` can # exit 0 for a rejected submission, so the status is checked explicitly. notarize() { @@ -74,22 +114,30 @@ fi name="TokenBar-$version$suffix" echo "==> Packaging" -ditto -c -k --keepParent "$app" "dist/$name.zip" +# The zip is also the Sparkle update archive. --sequesterRsrc as Sparkle recommends for ditto. +ditto -c -k --sequesterRsrc --keepParent "$app" "$dist/$name.zip" staging="$work/dmg" mkdir -p "$staging" cp -R "$app" "$staging/" ln -s /Applications "$staging/Applications" -hdiutil create -quiet -volname TokenBar -srcfolder "$staging" -format UDZO "dist/$name.dmg" +hdiutil create -quiet -volname TokenBar -srcfolder "$staging" -format UDZO "$dist/$name.dmg" if [[ -n "${DEVELOPER_ID_IDENTITY:-}" ]]; then - codesign --sign "$DEVELOPER_ID_IDENTITY" --timestamp "dist/$name.dmg" + codesign --sign "$DEVELOPER_ID_IDENTITY" --timestamp "$dist/$name.dmg" fi if [[ -n "${NOTARY_KEY_ID:-}" ]]; then echo "==> Notarizing disk image" - notarize "dist/$name.dmg" - xcrun stapler staple "dist/$name.dmg" + notarize "$dist/$name.dmg" + xcrun stapler staple "$dist/$name.dmg" fi -(cd dist && shasum -a 256 ./*.zip ./*.dmg > SHA256SUMS.txt) +echo "==> Appcast" +release_page="https://github.com/DerRafDev/tokenbar/releases/tag/v$version" +download_url="${SPARKLE_DOWNLOAD_URL:-https://github.com/DerRafDev/tokenbar/releases/download/v$version/$name.zip}" +notes="docs/release-notes/v$version.md" +[[ -f "$notes" ]] || notes="" +scripts/appcast.sh "$app" "$dist/$name.zip" "$download_url" "$dist/appcast.xml" "$notes" "$release_page" + +(cd "$dist" && shasum -a 256 ./*.zip ./*.dmg > SHA256SUMS.txt) echo "==> Done" -cat dist/SHA256SUMS.txt +cat "$dist/SHA256SUMS.txt" diff --git a/scripts/test-update.sh b/scripts/test-update.sh new file mode 100755 index 0000000..6f0c3fe --- /dev/null +++ b/scripts/test-update.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# Local end-to-end test of in-app updates, with no GitHub Release and no real signing key. +# +# scripts/test-update.sh build # two test builds (old 0.90.0, new 0.91.0) + feeds +# scripts/test-update.sh install # installs the old build and opens it +# scripts/test-update.sh serve # serves the feed on http://127.0.0.1:8765 (foreground) +# scripts/test-update.sh feed SCENARIO # switches what the feed offers (while serving): +# # update 0.91.0, correctly signed +# # none 0.90.0 (the installed version) +# # bad-signature 0.91.0 signed with another key +# scripts/test-update.sh clean # quits the test app, deletes its files and prefs +# +# The test builds are real release builds (scripts/release.sh, ad-hoc signed) with a different +# bundle ID (io.github.derrafdev.TokenBar.updatetest, so your TokenBar preferences are never +# touched), a throwaway EdDSA key and this local feed. Everything lives in build/update-test/. +# See docs/releasing.md › Testing an update locally. +set -euo pipefail +cd "$(dirname "$0")/.." + +dir=build/update-test +bundle_id=io.github.derrafdev.TokenBar.updatetest +port=8765 +feed_url="http://127.0.0.1:$port" +installed="$dir/Installed/TokenBar.app" + +# A throwaway Ed25519 key pair in Sparkle's format (base64 seed / base64 public key). +make_key() { + local out=$1 + local gen + gen=$(mktemp -t tokenbar-key).swift + cat > "$gen" <<'SWIFT' +import CryptoKit +let key = Curve25519.Signing.PrivateKey() +print(key.rawRepresentation.base64EncodedString()) +print(key.publicKey.rawRepresentation.base64EncodedString()) +SWIFT + xcrun swift "$gen" > "$out" + rm -f "$gen" +} + +build_variant() { + local name=$1 version=$2 build=$3 public_key=$4 + RELEASE_DIST="$dir/$name" \ + RELEASE_WORK="$dir/$name-work" \ + RELEASE_BUILD_SETTINGS="MARKETING_VERSION=$version CURRENT_PROJECT_VERSION=$build PRODUCT_BUNDLE_IDENTIFIER=$bundle_id SPARKLE_PUBLIC_ED_KEY=$public_key SPARKLE_FEED_URL=$feed_url/appcast.xml" \ + SPARKLE_DOWNLOAD_URL="$feed_url/TokenBar-$version-unsigned.zip" \ + SPARKLE_PRIVATE_KEY_FILE="$dir/test.key" \ + DEVELOPER_ID_IDENTITY="" NOTARY_KEY_ID="" \ + scripts/release.sh +} + +cmd_build() { + rm -rf "$dir" + mkdir -p "$dir/feed" + make_key "$dir/keys.txt" + make_key "$dir/other-keys.txt" + sed -n 1p "$dir/keys.txt" > "$dir/test.key" + sed -n 1p "$dir/other-keys.txt" > "$dir/other.key" + local public_key + public_key=$(sed -n 2p "$dir/keys.txt") + + build_variant old 0.90.0 9000 "$public_key" + build_variant new 0.91.0 9001 "$public_key" + + local old_app="$dir/old-work/TokenBar.xcarchive/Products/Applications/TokenBar.app" + local new_app="$dir/new-work/TokenBar.xcarchive/Products/Applications/TokenBar.app" + cp "$dir/new/TokenBar-0.91.0-unsigned.zip" "$dir/old/TokenBar-0.90.0-unsigned.zip" "$dir/feed/" + + cat > "$dir/notes.md" <<'MD' +**Test update.** If you can read this, Markdown release notes work. + +- Installed from a local feed +- Signed with a throwaway key +MD + SPARKLE_PRIVATE_KEY_FILE="$dir/test.key" scripts/appcast.sh "$new_app" "$dir/feed/TokenBar-0.91.0-unsigned.zip" \ + "$feed_url/TokenBar-0.91.0-unsigned.zip" "$dir/feed/appcast-update.xml" "$dir/notes.md" + SPARKLE_PRIVATE_KEY_FILE="$dir/test.key" scripts/appcast.sh "$old_app" "$dir/feed/TokenBar-0.90.0-unsigned.zip" \ + "$feed_url/TokenBar-0.90.0-unsigned.zip" "$dir/feed/appcast-none.xml" + + # Same item, but the signature comes from a key the app does not trust. + local good bad + good=$(sed -n 's/.*sparkle:edSignature="\([^"]*\)".*/\1/p' "$dir/feed/appcast-update.xml") + bad=$(build/SourcePackages/artifacts/sparkle/Sparkle/bin/sign_update --ed-key-file "$dir/other.key" -p \ + "$dir/feed/TokenBar-0.91.0-unsigned.zip") + sed "s|$good|$bad|" "$dir/feed/appcast-update.xml" > "$dir/feed/appcast-bad-signature.xml" + + cp "$dir/feed/appcast-update.xml" "$dir/feed/appcast.xml" + echo "==> Test builds ready in $dir (feed offers: update)" +} + +cmd_install() { + pkill -f "$PWD/$installed/Contents/MacOS/TokenBar" 2>/dev/null || true + rm -rf "$dir/Installed" + mkdir -p "$dir/Installed" + ditto -x -k "$dir/old/TokenBar-0.90.0-unsigned.zip" "$dir/Installed" + open "$installed" + echo "==> Installed and opened $installed (0.90.0)" +} + +cmd_serve() { + echo "==> Serving $dir/feed on $feed_url (Ctrl-C to stop)" + exec python3 -m http.server "$port" --bind 127.0.0.1 --directory "$dir/feed" +} + +cmd_feed() { + local scenario=${1:-} + if [[ ! -f "$dir/feed/appcast-$scenario.xml" ]]; then + echo "usage: $0 feed update|none|bad-signature" >&2 + exit 64 + fi + cp "$dir/feed/appcast-$scenario.xml" "$dir/feed/appcast.xml" + echo "==> Feed now offers: $scenario" +} + +cmd_clean() { + pkill -f "$PWD/$installed/Contents/MacOS/TokenBar" 2>/dev/null || true + defaults delete "$bundle_id" 2>/dev/null || true + rm -rf "$dir" "$HOME/Library/Caches/$bundle_id" + echo "==> Removed the test app, its files and its preferences" +} + +case "${1:-}" in + build) cmd_build ;; + install) cmd_install ;; + serve) cmd_serve ;; + feed) cmd_feed "${2:-}" ;; + clean) cmd_clean ;; + *) + sed -n '4,11p' "$0" >&2 + exit 64 + ;; +esac