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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions docs/reference/swaplabs-fork-builds.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,111 @@ certificate's designated requirement and only manifests signed by the key it was
compiled with. Treat the output directory as the only copy and back it up
privately.

## macOS self-updates (SwapLabs → SwapLabs)

`LOCAL:` upstream's macOS updater hands the downloaded zip to Squirrel.Mac, which
only installs a bundle that satisfies the running app's Developer ID designated
requirement. A fork build cannot meet that, so a SwapLabs build on macOS updates
itself through Orca's own installer in `src/main/updater/mac-self-update/`. It is
shaped like electron-updater (same events, same `checkForUpdates` /
`downloadUpdate` / `quitAndInstall` surface), so the updater state machine, the
Updates buttons, the update card, nudges, the quit-and-install sequence and the
exit watchdog run unchanged. Everything else (Linux, upstream builds, cross-source
jumps) still goes through electron-updater or a manual download.

### When it is active

All of these must hold, or the Mac assets stay download-only ("Open download
page"):

- macOS, packaged build;
- the running version belongs to a non-primary source (`…-swaplabs.<stamp>`);
- the build was compiled with `ORCA_SWAPLABS_UPDATE_PUBLIC_KEY` (the raw 32-byte
Ed25519 public key, base64; validated by `electron.vite.config.ts` like the
source registry);
- the running bundle's designated requirement is identity-bound (`certificate
leaf = …`), read once with `codesign -d -r-`. An ad-hoc signature is
`cdhash`-bound, so no later build could ever match it; the installer then
refuses up front and the buttons say manual.

`requiresManualInstall` says manual for a fork build's own next macOS build unless
the installer is active; cross-source jumps stay manual on macOS and Windows.

While the installer is active, "Check for local build" is refused before its file
dialog opens: the loopback feed serves `latest-mac.yml`, which the installer cannot
verify, and a local build is never signed with the SwapLabs release identity, so it
could not be installed anyway. The message says to install a local build by hand.

### Release assets the app consumes

Per macOS slice (`arm64`, `x64`), uploaded in this order, manifest last:

1. `orca-macos-<arch>.zip` — the `.app`, `ditto -c -k --keepParent`.
2. `swaplabs-update-mac-<arch>.json` — canonical JSON, no trailing newline:
`schema` (1), `source` (`swaplabs`), `version`, `arch`, `file`, `size`,
`sha512` (base64), `bundleId` (`com.stablyai.orca`), `commit`,
`designatedRequirementSha256` (hex sha256 of the text after `designated => `
in `codesign -d -r- <app>`, trimmed), `releasedAt` (ISO-8601). The name is
`<source id>-update-mac-<arch>.json`, so another source would publish its own.
3. `swaplabs-update-mac-<arch>.json.sig` — base64 Ed25519 signature over the
exact bytes of (2).

`latest-mac.yml` stays absent so electron-updater never tries Squirrel. The
atom-feed readiness probe, the pinned-tag verification and the Updates-section
listing all read the JSON manifest in place of `latest-mac.yml` on a build where
the installer is supported, and treat the `.sig` as a required asset.

### What a check, a download and a restart do

- **Check**: the existing atom-feed preflight pins the newest fork tag, then the
engine fetches the manifest and its signature through Electron's `net` (64 KiB /
1 KiB caps, enforced while the body streams so an oversized response is cut off
rather than buffered) and refuses
unless, in this order, the signature verifies, the manifest parses, `source`,
`arch` and `bundleId` match, the version belongs to the source and is newer
(routine) or exactly the pinned target, and `designatedRequirementSha256`
equals the running bundle's. Nothing is read from the manifest before the
signature check.
- **Download**: the zip streams into `<userData>/mac-self-update/downloads/`
through a stream pipeline, under the size and sha512 the signed manifest fixed
(a transfer past the size is abandoned; a full or unwritable disk is a retryable
error, not a crash), then `ditto -x -k` unpacks it into `.<App>-update-staging/`
beside the bundle, on the same volume so the swap is a rename. The staged
bundle must pass `codesign --verify --deep --strict`, carry the expected
`CFBundleIdentifier` and `CFBundleShortVersionString`, and have the same
designated requirement as the running app. Only then is
`com.apple.quarantine` stripped and `update-downloaded` emitted, which is also
the installer-ready signal Squirrel would have given. Any failure removes the
staging directory and the zip, and the error status carries the tag's release
page as `manualInstallUrl`. An unwritable app location is refused before the
download starts. Nothing from the download is executed at any point; the only
programs run are `codesign`, `PlistBuddy`, `ditto` and `xattr` under `/usr`.
- **Restart to update**: the existing quit-and-install sequence runs (session
save, terminal daemon handling, exit watchdog, supervised serve handoff), then
the engine records `install-state.json` and starts a detached `/bin/sh -c`
helper. The script is a fixed string in `mac-self-update-helper.ts`; every path
and number is an argv entry. It waits for the app pid to exit, moves the bundle
to `.<App>-update-rollback/`, moves the staged bundle into place, relaunches
with `/usr/bin/open`, and waits up to 90 s for the health marker the new app
writes once its first window is shown (or after 20 s headless). Without it, the
helper restores the rollback and relaunches the previous build. Every earlier
failure that leaves the previous bundle in place (staged bundle missing, no
rollback folder, either rename refused) relaunches it as well, so a failed
update never leaves Orca closed. Under a supervised `orca serve`, the helper
only swaps and the supervisor relaunches.
- **Next launch**: `reportMacSelfUpdateLaunchOutcome` writes the health marker,
records `updater_mac_self_update_completed` or `…_failed` with the helper's
one-word outcome, shows a rollback as an error in the update card, discards a
bundle that never installed, and prunes the rollback a few minutes after a
healthy launch.

### Not verified on a real Mac

- TCC grants surviving the swap with the self-signed identity.
- Gatekeeper on relaunch after the quarantine strip, for a non-notarized bundle.
- Renaming the bundle under a still-running terminal daemon.
- `open` relaunching promptly after the previous instance's exit.

## How to force a build

From the Actions tab pick **SwapLabs Fork Build**, **Run workflow**, tick
Expand Down
12 changes: 11 additions & 1 deletion electron.vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createBootstrapFatalExitBanner } from './config/build-plugins/bootstrap
import { createPdfjsViewerAssetsPlugin } from './config/build-plugins/pdfjs-viewer-assets'
import { createPlainNodeEntryGuardPlugin } from './config/build-plugins/plain-node-entry-guard'
import { parseReleaseSources } from './src/shared/release-sources'
import { parseMacSelfUpdatePublicKey } from './src/shared/mac-self-update-public-key'
import packageJson from './package.json' with { type: 'json' }

const BUNDLED_MAIN_DEPENDENCIES = new Set([
Expand Down Expand Up @@ -70,6 +71,14 @@ const ORCA_RELEASE_SOURCES_LITERAL =
typeof orcaReleaseSources === 'string' && orcaReleaseSources.trim().length > 0
? JSON.stringify(JSON.stringify(parseReleaseSources(orcaReleaseSources)))
: 'null'
// LOCAL: the Ed25519 key SwapLabs macOS builds verify their update manifests with. A define for
// the same reason as the registry: a shell export must not be able to re-key the installer.
// Validated by the runtime's own parser so a bad pipeline variable fails the build here.
const orcaSwapLabsUpdatePublicKey = process.env.ORCA_SWAPLABS_UPDATE_PUBLIC_KEY
const ORCA_SWAPLABS_UPDATE_PUBLIC_KEY_LITERAL =
typeof orcaSwapLabsUpdatePublicKey === 'string' && orcaSwapLabsUpdatePublicKey.trim().length > 0
? JSON.stringify(parseMacSelfUpdatePublicKey(orcaSwapLabsUpdatePublicKey))
: 'null'

function createStartupDiagnosticsBanner(chunkName: string): string {
return `
Expand Down Expand Up @@ -292,7 +301,8 @@ export const electronViteConfig: UserConfig = {
ORCA_BUILD_IDENTITY: ORCA_BUILD_IDENTITY_LITERAL,
ORCA_POSTHOG_WRITE_KEY: ORCA_POSTHOG_WRITE_KEY_LITERAL,
ORCA_DIAGNOSTICS_TOKEN_URL: ORCA_DIAGNOSTICS_TOKEN_URL_LITERAL,
ORCA_RELEASE_SOURCES: ORCA_RELEASE_SOURCES_LITERAL
ORCA_RELEASE_SOURCES: ORCA_RELEASE_SOURCES_LITERAL,
ORCA_SWAPLABS_UPDATE_PUBLIC_KEY: ORCA_SWAPLABS_UPDATE_PUBLIC_KEY_LITERAL
},
// Why: @xterm/headless declares "exports": null in package.json, which
// prevents Vite's default resolver from finding the CJS entry. Point
Expand Down
8 changes: 8 additions & 0 deletions src/main/startup/main-process-ready-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ import { initializeMainProcessPlugins } from './main-process-plugins'
import { collectWorktreeTrashSweepRoots, sweepStaleWorktreeTrash } from '../worktree-trash'
import { runAfterFirstWindowShown } from './first-window-deferral'
import { logStartupMilestone } from './startup-diagnostics'
import { reportMacSelfUpdateLaunchOutcome } from '../updater/mac-self-update/mac-self-update-launch-outcome'

// Headless serve never opens a window, so the sweep still has to run off a timer there.
const WORKTREE_TRASH_SWEEP_FALLBACK_MS = 15_000
// LOCAL: the self-update helper rolls back after 90 s without this marker; a window is the health signal, a timer covers headless serve.
const MAC_SELF_UPDATE_HEALTH_FALLBACK_MS = 20_000

export async function initializeReadyRuntimeServices(): Promise<void> {
const store = state.store
Expand Down Expand Up @@ -88,6 +91,11 @@ export async function initializeReadyRuntimeServices(): Promise<void> {
console.warn('[worktrees] Failed to sweep leftover worktree directories:', error)
})
}, WORKTREE_TRASH_SWEEP_FALLBACK_MS)
// LOCAL: a shown window is the health signal the self-update helper waits for; it also reports
// how the previous launch's install went and prunes what that install left behind.
runAfterFirstWindowShown(() => {
reportMacSelfUpdateLaunchOutcome()
}, MAC_SELF_UPDATE_HEALTH_FALLBACK_MS)
nativeTheme.themeSource = store.getSettings().theme ?? 'system'
// Why (#16441): the real-home grant runs a codex app-server session. It stays
// ordered before managed-hook reconciliation — an incapable host must re-arm
Expand Down
16 changes: 9 additions & 7 deletions src/main/updater-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from './updater-mac-install'
import { compareVersions } from './updater-fallback'
import { fetchChangelog } from './updater-changelog'
import type { ElectronAutoUpdater } from './electron-updater-loader'
import type { UpdateEngine } from './updater/update-engine'
import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics'
import {
getRetainedLinuxPackageManualInstallStatus,
Expand All @@ -16,12 +16,13 @@ import {
} from './linux-package-downloaded-status'
import { isExternallyManagedLinuxInstall } from './linux-update-package-type'
import * as linuxPackageRecovery from './linux-package-update-recovery'

const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000
const AUTO_UPDATE_RETRY_INTERVAL_MS = 60 * 60 * 1000
import {
AUTO_UPDATE_CHECK_INTERVAL_MS,
AUTO_UPDATE_RETRY_INTERVAL_MS
} from './updater/updater-state'

type UpdaterHandlerContext = {
autoUpdater: ElectronAutoUpdater
autoUpdater: UpdateEngine
clearBackgroundCheckLaunchPending: () => void
clearAvailableUpdateContext: () => void
consumeMissingManifestPrereleaseFallbackResult: () => { userInitiated: boolean } | null
Expand Down Expand Up @@ -53,7 +54,7 @@ type UpdaterHandlerContext = {
source?: 'event' | 'promise' | 'fallback-promise',
sourceError?: unknown
) => Promise<void>
sendErrorStatus: (message: string, userInitiated?: boolean) => void
sendErrorStatus: (message: string, userInitiated?: boolean, error?: unknown) => void
sendStatus: (status: UpdateStatus) => void
scheduleAutomaticUpdateCheck: (delayMs: number) => void
shouldSuppressMissingManifestPrereleaseFallbackEvent: (message: string, error: unknown) => boolean
Expand Down Expand Up @@ -101,6 +102,7 @@ export function registerAutoUpdaterHandlers({
setUserInitiatedCheck
}: UpdaterHandlerContext): void {
registerMacUpdaterEvents({
updateEngine: autoUpdater,
getCurrentStatus,
hasInstallableDownloadedVersion,
getPendingInstallVersion,
Expand Down Expand Up @@ -329,7 +331,7 @@ export function registerAutoUpdaterHandlers({
void sendCheckFailureStatus(message, wasUserInitiated || undefined, 'event', err)
return
}
sendErrorStatus(message, wasUserInitiated || undefined)
sendErrorStatus(message, wasUserInitiated || undefined, err)
if (isLocalBuildCheck() || isPinnedBuildCheck()) {
restoreReleaseUpdateSource()
}
Expand Down
8 changes: 7 additions & 1 deletion src/main/updater-mac-install.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { app, autoUpdater as nativeUpdater } from 'electron'
import type { UpdateStatus } from '../shared/update-status-types'
import { recordUpdaterLifecycle } from './updater-lifecycle-diagnostics'
import type { UpdateEngine } from './updater/update-engine'

const MAC_INSTALL_READY_TIMEOUT_MS = 15000

export function registerMacUpdaterEvents({
updateEngine,
getCurrentStatus,
hasInstallableDownloadedVersion,
getPendingInstallVersion,
Expand All @@ -13,6 +15,8 @@ export function registerMacUpdaterEvents({
shouldDeferMacQuitForInstall,
sendStatus
}: {
/** LOCAL: a staged-bundle engine's own `update-downloaded` is the ready signal; Squirrel.Mac's native one otherwise. */
updateEngine: Pick<UpdateEngine, 'on' | 'installerReadinessSource'>
getCurrentStatus: () => UpdateStatus
hasInstallableDownloadedVersion: () => boolean
getPendingInstallVersion: () => string
Expand All @@ -22,7 +26,9 @@ export function registerMacUpdaterEvents({
sendStatus: (status: UpdateStatus) => void
}): void {
if (process.platform === 'darwin') {
nativeUpdater.on('update-downloaded', () => {
const readySource =
updateEngine.installerReadinessSource === 'staged-bundle' ? updateEngine : nativeUpdater
readySource.on('update-downloaded', () => {
const hasInstallableVersion = hasInstallableDownloadedVersion()
handleMacInstallerReady(hasInstallableVersion, performQuitAndInstall, () => {
sendStatus({
Expand Down
16 changes: 13 additions & 3 deletions src/main/updater-prerelease-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
type ReleaseManifestProbe
} from './updater-release-asset-readiness'
import { getReleaseAtomFeedUrl, getReleaseTagHrefPattern } from './updater-release-urls'
import { getMacSelfUpdateSourceFor } from './updater/mac-self-update/mac-self-update-activation'

export { getReleaseDownloadUrl } from './updater-release-urls'

Expand Down Expand Up @@ -95,7 +96,12 @@ export async function verifyReleaseTagManifest(
source: ReleaseSource
): Promise<ReleaseTagManifestVerdict> {
return judgeManifestProbe(
await probeReleaseManifest(target.tag, target.repo),
await probeReleaseManifest(
target.tag,
target.repo,
undefined,
getMacSelfUpdateSourceFor(source)
),
target.version,
source
)
Expand Down Expand Up @@ -183,10 +189,11 @@ async function resolveVersionsFromManifests(
const unresolved = entries
.filter((entry) => entry.version === null)
.slice(0, MAX_MANIFEST_PROBE_CANDIDATES)
const macSelfUpdateSource = getMacSelfUpdateSourceFor(source)
const results = await Promise.all(
unresolved.map(async ({ tag }) => ({
tag,
probe: await probeReleaseManifest(tag, source.repo, assetProbes)
probe: await probeReleaseManifest(tag, source.repo, assetProbes, macSelfUpdateSource)
}))
)
const resolved: ReleaseFeedTag[] = []
Expand Down Expand Up @@ -288,12 +295,15 @@ export async function fetchNewerReleaseTagsWithReadiness(
newestNewerIndex,
newestNewerIndex + MAX_MANIFEST_PROBE_CANDIDATES
)
const macSelfUpdateSource = getMacSelfUpdateSourceFor(source)
const manifestResults = (
await Promise.all(
probeCandidates.map(async ({ tag, version }) => ({
tag,
version,
probe: probes.get(tag) ?? (await probeReleaseManifest(tag, source.repo, assetProbes))
probe:
probes.get(tag) ??
(await probeReleaseManifest(tag, source.repo, assetProbes, macSelfUpdateSource))
}))
)
).flatMap(({ tag, version, probe }) => {
Expand Down
53 changes: 53 additions & 0 deletions src/main/updater-release-asset-readiness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,59 @@ describe('probeReleaseManifest', () => {
).resolves.toBe('https://github.com/stablyai/orca/releases/download/v1.0.0/latest-mac.yml')
})

// LOCAL: on a build with Orca's own macOS installer, a fork tag's readiness is its signed
// per-slice manifest: the zip it names and the detached signature must both be there.
it('reads a fork macOS slice through its self-update manifest and requires the signature', async () => {
const swaplabs = {
id: 'swaplabs',
label: 'SwapLabs',
repo: 'SwapLabsInc/orca',
prereleaseIdentifier: 'swaplabs'
}
const arch = Object.getOwnPropertyDescriptor(process, 'arch')
Object.defineProperty(process, 'arch', { value: 'arm64', configurable: true })
const probed: string[] = []
const manifest = JSON.stringify({
schema: 1,
version: '1.4.197-swaplabs.202609251200',
file: 'orca-macos-arm64.zip'
})
let signatureStatus = 200
netFetchMock.mockImplementation((url: string, init?: { method?: string }) => {
if (init?.method === 'HEAD') {
probed.push(url)
const status = url.endsWith('.sig') ? signatureStatus : 200
return Promise.resolve({ ok: status === 200, status, text: () => Promise.resolve('') })
}
probed.push(url)
return Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve(manifest) })
})
try {
const { probeReleaseManifest } = await import('./updater-release-asset-readiness')
const tag = 'swaplabs-v1.4.197+202609251200'
await expect(probeReleaseManifest(tag, swaplabs.repo, undefined, swaplabs)).resolves.toEqual({
readiness: 'ready',
version: '1.4.197-swaplabs.202609251200'
})
const base = `https://github.com/SwapLabsInc/orca/releases/download/${encodeURIComponent(tag)}`
expect(probed).toEqual([
`${base}/swaplabs-update-mac-arm64.json`,
`${base}/orca-macos-arm64.zip`,
`${base}/swaplabs-update-mac-arm64.json.sig`
])

signatureStatus = 404
await expect(probeReleaseManifest(tag, swaplabs.repo, undefined, swaplabs)).resolves.toEqual({
readiness: 'not-ready',
version: '1.4.197-swaplabs.202609251200'
})
} finally {
if (arch) {
Object.defineProperty(process, 'arch', arch)
}
}
})

// Why: a dev-channel tag lives only in its own repo, so the probe must read the repo the pin
// reads rather than the source's main one.
it('reads the manifest from the given repo', async () => {
Expand Down
Loading
Loading