Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
fix: bind launcher updates to reviewed plans and truthful outcomes
domsvoboda5bc458ef6113
diff --git a/src/main/launcher-update.test.ts b/src/main/launcher-update.test.tsindex 5fe1c29..25932fb 100644--- a/src/main/launcher-update.test.ts+++ b/src/main/launcher-update.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -6,7 +6,7 @@ import { createHash } from 'node:crypto';import { LauncherUpdater, launcherCandidate } from './launcher-update.js';import { APPIMAGE_ARCH_SUFFIX, ELF_MACHINE, currentArch, type NexusArch } from './arch.js';const roots: string[] = [];-afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });+afterEach(async () => { vi.restoreAllMocks(); for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });function image(marker: number, arch: NexusArch = currentArch()): Buffer {const bytes = Buffer.alloc(100, marker); Buffer.from('7f454c46', 'hex').copy(bytes);bytes[4] = 2; bytes[5] = 1; Buffer.from('414902', 'hex').copy(bytes, 8); bytes.writeUInt16LE(ELF_MACHINE[arch], 18); return bytes;@@ -34,6 +34,36 @@ async function fixture(bad = '', arch: NexusArch = currentArch(),repo='domsvobodawait updater.initialize(); await updater.check(); return { root, target, updater, fetcher };}describe('AppImage updater', () => {+ it('releases admission and lock when initial notification throws', async () => {+ const {root,target,fetcher}=await fixture();let fail=false;+ const updater=new LauncherUpdater('0.2.2',target,root,()=>{if(fail)throw Error('notify');},fetcher);await updater.initialize();await updater.check();fail=true;+ await expect(updater.install()).rejects.toMatchObject({committed:false});expect(updater.state.updating).toBe(false);expect(await fs.readFile(target)).toEqual(image(1));+ expect((await fs.readdir(root)).some(name=>name.endsWith('.nexus-update.lock'))).toBe(false);fail=false;await updater.install();+ });+ it('clears busy state after postcommit cleanup failure and reports actual replacement', async () => {+ const {root,target,updater}=await fixture();const original=fs.rm;let injected=false;+ vi.spyOn(fs,'rm').mockImplementation(async(p,options)=>{if(!injected&&String(p).includes('.nexus-update-')){injected=true;throw Error('cleanup failed');}return original(p,options);});+ await expect(updater.install()).rejects.toMatchObject({committed:true});expect(updater.state.updating).toBe(false);expect(await fs.readFile(target)).toEqual(image(2));expect(updater.state.restartRequired).toBe(true);+ expect((await fs.readdir(root)).some(name=>name.endsWith('.nexus-update.lock'))).toBe(false);+ });+ it('preserves backup and reports attention if rollback fails after replacement', async () => {+ const {root,target,updater}=await fixture();const write=fs.writeFile,rename=fs.rename;+ vi.spyOn(fs,'writeFile').mockImplementation(async(p,data,options)=>{if(String(p).includes('launcher-update.json.'))throw Error('journal failed');return write(p,data,options);});+ vi.spyOn(fs,'rename').mockImplementation(async(a,b)=>{if(String(a).includes('.nexus-backup-'))throw Error('restore failed');return rename(a,b);});+ await expect(updater.install()).rejects.toMatchObject({committed:true});expect(await fs.readFile(target)).toEqual(image(2));expect(updater.state.updating).toBe(false);+ const backups=(await fs.readdir(root)).filter(name=>name.includes('.nexus-backup-'));expect(backups).toHaveLength(1);expect(await fs.readFile(path.join(root,backups[0]))).toEqual(image(1));+ });+ it('does not remove a consumed journal temporary path after publication', async () => {+ const {updater}=await fixture();const rm=vi.spyOn(fs,'rm');await updater.install();expect(rm.mock.calls.some(([p])=>String(p).includes('launcher-update.json.'))).toBe(false);+ });+ it('rejects concurrent installation before awaited image validation', async () => {+ const {updater}=await fixture();let release!:()=>void;const hold=new Promise<void>(r=>release=r);+ const internal=updater as unknown as {writableImage():Promise<string>};const original=internal.writableImage.bind(updater);vi.spyOn(internal,'writableImage').mockImplementation(async()=>{await hold;return original();});+ const pending=updater.install();await expect(updater.install()).rejects.toThrow('pending');release();await pending;+ });+ it('rejects a changed installed image from an approved component plan', async () => {+ const {updater,target}=await fixture();const plan=await updater.prepareComponentUpdate();expect(plan.item.state).toBe('ready');await fs.writeFile(target,image(7));expect(await plan.isCurrent()).toBe(false);await expect(plan.apply({identity:Symbol()})).rejects.toThrow('changed');expect(await fs.readFile(target)).toEqual(image(7));+ });it('ignores backend/runtime tags and prereleases; uses newest complete stable launcher', () => {expect(launcherCandidate([{ ...release('9.0.0'), tag_name: 'backend-v9.0.0' }, { ...release('8.0.0'), prerelease: true }, release('0.2.3'), release('0.2.4')], '0.2.2')?.version).toBe('0.2.4');expect(launcherCandidate([release()], '0.2.3')).toBeUndefined();diff --git a/src/main/launcher-update.ts b/src/main/launcher-update.tsindex 2aaa11a..775cb2e 100644--- a/src/main/launcher-update.ts+++ b/src/main/launcher-update.ts@@ -1,6 +1,7 @@import { constants, promises as fs } from 'node:fs';import { createHash, randomUUID } from 'node:crypto';import path from 'node:path';+import type { PreparedComponentUpdate } from './component-updates.js';import type { LauncherUpdate } from '../shared/types.js';import { isNewerVersion } from '../shared/utils.js';import { APPIMAGE_ARCH_SUFFIX, currentArch, isLinuxElf64, type NexusArch } from './arch.js';@@ -42,6 +43,7 @@ export class LauncherUpdater {private journal?: Journal;private checking?: Promise<void>;private controller?: AbortController;+ private mutationReserved = false;cancel(): void { this.controller?.abort(); }constructor(private version: string, private image: string | undefined, private userData: string,private changed: () => void, private fetcher: typeof fetch = fetch, private arch: NexusArch = currentArch()) {@@ -86,10 +88,37 @@ export class LauncherUpdater {} catch (error) { this.state.error = (error as Error).message; }finally { this.state.checking = false; this.state.checkedAt = new Date().toISOString(); this.changed(); }}- async install(): Promise<void> {+ async prepareComponentUpdate(): Promise<PreparedComponentUpdate> {+ const item = { id: 'launcher', component: 'launcher' as const, label: 'Launcher', currentVersion: this.version,+ state: 'skipped' as 'ready' | 'skipped' | 'unchanged' | 'deferred', reason: 'An installed writable AppImage is required.' };+ if (this.state.restartRequired) return { item: { ...item, state: 'deferred', reason: 'Restart to use the installed launcher update.' }, isCurrent: async () => false, apply: async () => { throw Error('Restart required.'); } };+ let target: string;+ try { target = await this.writableImage(); } catch { return { item, isCurrent: async () => false, apply: async () => { throw Error(item.reason); } }; }+ const before = await fs.stat(target);+ await this.check();+ if (this.state.error) throw Error(this.state.error);+ const candidate = this.candidate ? structuredClone(this.candidate) : undefined;+ const same = async () => {+ try { const current = await fs.stat(target); return !this.state.restartRequired && await this.writableImage() === target && current.ino === before.ino && current.dev === before.dev && current.size === before.size && current.mtimeMs === before.mtimeMs && current.ctimeMs === before.ctimeMs; } catch { return false; }+ };+ return { item: { ...item, state: candidate ? 'ready' : 'unchanged', targetVersion: candidate?.version, reason: undefined },+ isCurrent: same,+ apply: async () => { if (!candidate) throw Error('No launcher update was selected.'); await this.install(candidate, same); return { committed: true, restartRequired: true }; },+ reconcile: async () => { if (!candidate || !this.state.restartRequired || this.journal?.version !== candidate.version || this.targetPath !== target) throw Error('Launcher update needs manual reconciliation.'); return { restartRequired: true }; },+ };+ }++ async install(selected?: LauncherCandidate, expectedCurrent?: () => Promise<boolean>): Promise<void> {+ if (this.mutationReserved) throw Error('A launcher update is already pending.');+ this.mutationReserved = true;+ try { await this.performInstall(selected, expectedCurrent); }+ finally { this.mutationReserved = false; }+ }+ private async performInstall(selected?: LauncherCandidate, expectedCurrent?: () => Promise<boolean>): Promise<void> {if (this.state.updating || this.state.restartRequired) throw new Error('A launcher update is already pending.');- if (!this.candidate) throw new Error('Check for a newer launcher release first.');- const candidate = this.candidate;+ const candidate = selected ?? this.candidate;+ if (!candidate) throw new Error('Check for a newer launcher release first.');+ if (expectedCurrent && !await expectedCurrent()) throw Error('The installed launcher changed. Check again.');const target = await this.writableImage();const lockPath = `${target}.nexus-update.lock`;let lock;@@ -104,15 +133,20 @@ export class LauncherUpdater {catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error; }await fs.rm(lockPath); lock = await fs.open(lockPath, 'wx', 0o600);}+ let activationCommitted = false;+ try {await lock.writeFile(String(process.pid)); await lock.close();const before = await fs.stat(target);const temporary = `${target}.nexus-update-${randomUUID()}`;const backup = `${target}.nexus-backup-${randomUUID()}`;const previousJournal = this.journal;- let replaced = false, backedUp = false;+ let replaced = false, backedUp = false, rollbackFailed = false;+ let failure: unknown;+ let failed = false;this.controller = new AbortController();- this.state.updating = true; this.state.error = undefined; this.state.progress = 0; this.state.phase = 'Downloading launcher update…'; this.changed();+ this.state.updating = true; this.state.error = undefined; this.state.progress = 0; this.state.phase = 'Downloading launcher update…';try {+ this.changed();const checksumResponse = await this.fetcher(candidate.checksum.browser_download_url, { signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(15_000)]) });if (!checksumResponse.ok || candidate.checksum.size > 4096) throw new Error('Could not download the launcher checksum.');const checksum = (await checksumResponse.text()).trim();@@ -136,27 +170,45 @@ export class LauncherUpdater {if (!isLinuxElf64(header, this.arch) || header.subarray(8, 11).toString('hex') !== '414902') throw new Error(`The update is not a ${APPIMAGE_ARCH_SUFFIX[this.arch]} AppImage.`);const now = await fs.stat(target);this.controller.signal.throwIfAborted();+ if (expectedCurrent && !await expectedCurrent()) throw Error('The installed launcher changed before activation. Check again.');if (now.ino !== before.ino || now.size !== before.size || now.mtimeMs !== before.mtimeMs || await this.writableImage() !== target) throw new Error('The installed launcher changed during download. Retry the update.');this.state.phase = 'Installing verified launcher…'; this.changed();await fs.copyFile(target, backup, constants.COPYFILE_EXCL); backedUp = true;- await fs.rename(temporary, target); replaced = true;+ await fs.rename(temporary, target); replaced = true; activationCommitted = true;const j: Journal = { target, backup, previousVersion: this.version, version: candidate.version };const journalFile = path.join(this.userData, 'launcher-update.json');await fs.mkdir(this.userData, { recursive: true });const journalTemp = `${journalFile}.${randomUUID()}`;- try { await fs.writeFile(journalTemp, JSON.stringify(j), { flag: 'wx', mode: 0o600 }); await fs.rename(journalTemp, journalFile); }- finally { await fs.rm(journalTemp, { force: true }); }+ let journalPublished = false;+ try { await fs.writeFile(journalTemp, JSON.stringify(j), { flag: 'wx', mode: 0o600 }); await fs.rename(journalTemp, journalFile); journalPublished = true; }+ finally { if (!journalPublished) await fs.rm(journalTemp, { force: true }); }this.journal = j; this.targetPath = target;this.state.restartRequired = true; this.state.canRollback = true; this.state.phase = 'Update installed. Restart to use it.';if (previousJournal?.backup) await fs.rm(previousJournal.backup, { force: true }).catch(() => {});} catch (error) {- if (replaced && backedUp) { await fs.rename(backup, target); backedUp = false; }- this.state.error = (error as Error).message; throw error;+ failed = true; failure = error;+ if (replaced && backedUp) {+ try { await fs.rename(backup, target); backedUp = false; activationCommitted = false; }+ catch (rollbackError) { rollbackFailed = true; failure = new AggregateError([error, rollbackError], 'The launcher was replaced but restoring its backup failed.'); }+ }+ this.state.error = failure instanceof Error ? failure.message : String(failure);+ throw Object.assign(new Error(this.state.error, { cause: failure }), { committed: activationCommitted });+ } finally {+ let finishingFailure: unknown, finishingFailed = false;+ try {+ await fs.rm(temporary, { force: true });+ if (backedUp && !this.state.restartRequired && !rollbackFailed) await fs.rm(backup, { force: true });+ } catch (error) { finishingFailed = true; finishingFailure = error; }+ this.state.updating = false; this.controller = undefined;+ try { this.changed(); } catch (error) { finishingFailure = finishingFailed ? new AggregateError([finishingFailure,error], 'Launcher cleanup and notification failed.') : error; finishingFailed = true; }+ if (finishingFailed) {+ const cause = failed ? new AggregateError([failure,finishingFailure], 'Launcher update needs attention.') : finishingFailure;+ throw Object.assign(new Error(cause instanceof Error ? cause.message : String(cause), { cause }), { committed: activationCommitted });+ }+ }} finally {- await fs.rm(temporary, { force: true });- if (backedUp && !this.state.restartRequired) await fs.rm(backup, { force: true });- this.state.updating = false; this.controller = undefined; this.changed();- await fs.rm(lockPath, { force: true });+ await lock.close().catch(() => undefined);+ try { await fs.rm(lockPath, { force: true }); } catch (error) { throw Object.assign(new Error('Launcher update lock cleanup failed.', { cause: error }), { committed: activationCommitted }); }}}async rollback(): Promise<void> {