diff --git a/apps/desktop/README.md b/apps/desktop/README.md index c24bcaa8b..780aa7379 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -147,6 +147,12 @@ starts the candidate. A failed or interrupted trial restores the previous runtime and workspace. Backups are kept. Automatic update discovery is not connected yet. +Installing a newer app over an older one works the same way: on the next start, +a bundled core whose `coreVersion` is newer than the active one is installed and +trialled with the same backup and rollback. A bundled core that fails its trial +is not tried again, and an older bundled core never replaces a newer one that +was installed by hand. + ## Verification `npm test` covers edition names, language resolution, config validation, diff --git a/apps/desktop/src/bundles.mjs b/apps/desktop/src/bundles.mjs index f43809c63..7a8ed0736 100644 --- a/apps/desktop/src/bundles.mjs +++ b/apps/desktop/src/bundles.mjs @@ -24,6 +24,46 @@ export function verifyManifest(manifest, publicKey, architecture = process.arch, return manifest; } +function versionParts(value) { + const match = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(String(value ?? '')); + return match ? match.slice(1).map(part => Number(part ?? 0)) : null; +} + +// An installer that overwrites the app ships a newer seed, but the saved runtime +// would otherwise keep winning. Only a strictly newer core replaces it, so a core +// the user installed by hand is never downgraded to an older bundled one. +export function newerRuntime(candidate, current) { + if (!candidate) return false; + if (!current) return true; + if (candidate.runtimeId === current.runtimeId) return false; + const next = versionParts(candidate.coreVersion); + const installed = versionParts(current.coreVersion); + if (!next || !installed) return false; + for (let index = 0; index < next.length; index += 1) { + if (next[index] !== installed[index]) return next[index] > installed[index]; + } + return false; +} + +/** + * Decide what boot() starts from the saved runtime, the bundled seed and the last + * upgrade transaction. Without a saved runtime the seed is installed as before. + * An unusable seed never blocks the saved runtime, and a seed whose first start + * already failed is not tried again. + */ +export function startupRuntime({ saved, seed, transaction, publicKey }) { + if (!saved) return {}; + const current = verifyManifest(saved, publicKey); + let bundled = null; + let seedError; + if (seed) { + try { bundled = verifyManifest(seed, publicKey); } + catch (error) { seedError = error; } + } + const failed = Boolean(transaction?.failed) && transaction.candidate?.runtimeId === bundled?.runtimeId; + return { current, upgrade: newerRuntime(bundled, current) && !failed, seedError }; +} + export async function sha256(filename) { const hash = createHash('sha256'); for await (const chunk of createReadStream(filename)) hash.update(chunk); diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs index 0cff0cf32..af892a300 100644 --- a/apps/desktop/src/main.mjs +++ b/apps/desktop/src/main.mjs @@ -4,7 +4,7 @@ import { watch } from 'node:fs'; import { mkdir, readFile, writeFile, rename, cp, appendFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { installBundle, bundleConfig, verifyManifest } from './bundles.mjs'; +import { installBundle, bundleConfig, startupRuntime } from './bundles.mjs'; import { externalURL } from './config.mjs'; import { resolveLanguage, translate } from './i18n.mjs'; import { WINDOWS, agentMarker, edition, targetId } from './platform.mjs'; @@ -223,25 +223,69 @@ async function logStartupFailure(error) { } catch (logError) { console.error(logError); } } +async function startupManifest() { + const saved = await readJSON(activeFile); + if (!saved) return { manifestFile: seed }; + // A missing or unreadable seed must not stop the installed core from starting. + const bundled = await readJSON(seed).catch(error => { console.error(error); return null; }); + const { current, upgrade, seedError } = startupRuntime({ + saved, seed: bundled, transaction: await readJSON(transactionFile), publicKey, + }); + if (seedError) console.error(seedError); + const installed = path.join(userRoot, 'runtimes', current.runtimeId, 'installed.json'); + return upgrade ? { manifestFile: seed, previous: current, installed } : { manifestFile: installed }; +} + async function boot() { if (busy || quitting) return; busy = true; + let transaction; try { status({ phase: 'starting', step: 'starting' }); await stopWorker(); await recoverInterruptedUpgrade(); - const saved = await readJSON(activeFile); - const manifestFile = saved ? path.join(userRoot, 'runtimes', verifyManifest(saved, publicKey).runtimeId, 'installed.json') : seed; - active = await installBundle(manifestFile, userRoot, publicKey, step => status({ step })); + const { manifestFile, previous, installed } = await startupManifest(); + try { active = await installBundle(manifestFile, userRoot, publicKey, step => status({ step })); } + catch (error) { + if (!previous) throw error; + // The bundled core could not be unpacked; keep starting the installed one. + await logStartupFailure(error); + active = await installBundle(installed, userRoot, publicKey, step => status({ step })); + } if (quitting) return; + if (previous && active.manifest.runtimeId !== previous.runtimeId) { + // The app was installed over an older core: switch to the bundled one with the + // same backup and rollback as a manual update. + status({ phase: 'starting', step: 'updating' }); + let backup = path.join(userRoot, 'backups', `before-${active.manifest.runtimeId}-${Date.now()}`); + await mkdir(path.dirname(backup), { recursive: true }); + try { await cp(runtimeHome, backup, { recursive: true }); } + catch (error) { + // No workspace yet means nothing to restore on rollback. + if (error.code !== 'ENOENT') throw error; + backup = undefined; + } + transaction = { phase: 'testing', previous, candidate: active.manifest, backup }; + await writeJSON(transactionFile, transaction); + } const ready = await launchRuntime(active); if (quitting) return; await writeJSON(activeFile, active.manifest); + if (transaction) await writeJSON(transactionFile, { ...transaction, phase: 'complete' }); watchInterface(); await refreshInterface(); await openContent(ready.url); } catch (error) { await logStartupFailure(error); + if (transaction) { + // Restore the previous core and workspace; the next start uses them again. + await stopWorker(); + try { + await writeJSON(transactionFile, { ...transaction, failed: true }); + await recoverInterruptedUpgrade(); + } + catch (recoveryError) { await logStartupFailure(recoveryError); } + } status({ phase: 'error', step: null, message: error.message }); await stopWorker(); } finally { busy = false; } diff --git a/apps/desktop/test/runtime.test.mjs b/apps/desktop/test/runtime.test.mjs index 064b90a0e..e68aad9d7 100644 --- a/apps/desktop/test/runtime.test.mjs +++ b/apps/desktop/test/runtime.test.mjs @@ -7,7 +7,7 @@ import os from 'node:os'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; import { localURL, externalURL, validateConfig } from '../src/config.mjs'; -import { canonicalManifest, verifyManifest, installBundle, sha256 } from '../src/bundles.mjs'; +import { canonicalManifest, verifyManifest, installBundle, sha256, newerRuntime, startupRuntime } from '../src/bundles.mjs'; import { runtimeLayout, systemTar } from '../src/platform.mjs'; import { ProcessGroup, availablePort, probe, waitReady } from '../src/processes.mjs'; import { SourceRuntime, stageBundledWeb } from '../src/runtime.mjs'; @@ -38,6 +38,42 @@ test('update signatures bind version, checksum and architecture', () => { assert.throws(() => verifyManifest({ ...manifest, archive: '../core.tar.gz' }, publicKey, 'arm64')); }); +test('a newer bundled core replaces the saved one, never an equal or newer one', () => { + const runtime = (coreVersion, runtimeId = `${coreVersion}-abc-x64`) => ({ coreVersion, runtimeId }); + assert.equal(newerRuntime(runtime('1.7.2'), runtime('1.7.1')), true); + assert.equal(newerRuntime(runtime('1.10.0'), runtime('1.9.9')), true); + assert.equal(newerRuntime(runtime('2.0.0'), runtime('1.99.0')), true); + assert.equal(newerRuntime(runtime('1.7.2'), null), true); + assert.equal(newerRuntime(runtime('1.7.1'), runtime('1.7.2')), false); + assert.equal(newerRuntime(runtime('1.7.2', '1.7.2-def-x64'), runtime('1.7.2')), false); + assert.equal(newerRuntime(runtime('1.7.2'), runtime('1.7.2')), false); + assert.equal(newerRuntime(runtime('dev'), runtime('1.7.1')), false); + assert.equal(newerRuntime(null, runtime('1.7.1')), false); +}); + +test('boot keeps the saved core unless the app ships a newer signed one that has not failed', () => { + const { privateKey, publicKey } = generateKeyPairSync('ed25519'); + const signed = (coreVersion, runtimeId) => { + const manifest = { formatVersion: 1, protocolVersion: 1, platform: process.platform, arch: process.arch, runtimeId, coreVersion, archive: 'core.tar.gz', sha256: 'a'.repeat(64) }; + manifest.signature = sign(null, Buffer.from(canonicalManifest(manifest)), privateKey).toString('base64'); + return manifest; + }; + const saved = signed('1.7.1', '1.7.1-aaa-x64'); + const seed = signed('1.7.2', '1.7.2-bbb-x64'); + assert.deepEqual(startupRuntime({ saved: null, seed, publicKey }), {}); + assert.deepEqual(startupRuntime({ saved, seed, publicKey }), { current: saved, upgrade: true, seedError: undefined }); + assert.equal(startupRuntime({ saved: seed, seed: saved, publicKey }).upgrade, false); + assert.equal(startupRuntime({ saved, seed: null, publicKey }).upgrade, false); + const tampered = startupRuntime({ saved, seed: { ...seed, coreVersion: '9.0.0' }, publicKey }); + assert.equal(tampered.upgrade, false); + assert.match(tampered.seedError.message, /signature/); + const failed = { phase: 'recovered', failed: true, previous: saved, candidate: seed }; + assert.equal(startupRuntime({ saved, seed, transaction: failed, publicKey }).upgrade, false); + const interrupted = { phase: 'recovered', previous: saved, candidate: seed }; + assert.equal(startupRuntime({ saved, seed, transaction: interrupted, publicKey }).upgrade, true); + assert.throws(() => startupRuntime({ saved: { ...saved, runtimeId: '../outside' }, seed, publicKey })); +}); + test('occupied ports are left alone and an available port is chosen', async t => { const server = http.createServer((_req, res) => res.end('ready')); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));