Skip to content

Open-source Xbox-inspired desktop launcher for Xodus on Linux

TypeScript

feat(runtime): install managed families without changing game selections

domsvoboda84d80e2b53ea
diff --git a/src/main/index.ts b/src/main/index.ts
index 3f2e9b4..b636f36 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1665,6 +1665,8 @@ function registerDemoIpc(catalogMarket: () => string): void {
ipcMain.handle('runtime-families', () => []);
ipcMain.handle('runtime-check-update', () => snapshot().runtime);
ipcMain.handle('runtime-check-nexus', () => snapshot().runtime);
+ ipcMain.handle('runtime-family-check', () => {throw Error('Managed runtime installation is unavailable in the synthetic demo.');});
+ ipcMain.handle('runtime-family-install', () => {throw Error('Managed runtime installation is unavailable in the synthetic demo.');});
ipcMain.handle('runtime-install', () => {});
ipcMain.handle('runtime-install-nexus', () => {});
ipcMain.handle('runtime-rollback-preview', () => {});
@@ -1830,6 +1832,8 @@ function registerIpc(): void {
await refreshAccount(false);
});
});
+ ipcMain.handle('runtime-family-check', (_event,family:unknown,options:unknown) => runtime.checkManagedRuntime(family,options,emitSnapshot));
+ ipcMain.handle('runtime-family-install', (_event,family:unknown,expected:unknown,options:unknown) => {ensureIdle();return runtime.installManagedRuntime(family,expected,options,emitSnapshot);});
ipcMain.handle('runtime-check-update', async () => { const value = await runtime.check(); emitSnapshot(); return value; });
ipcMain.handle('runtime-check-nexus', async () => { const value = await runtime.checkNexus(); emitSnapshot(); return value; });
ipcMain.handle('runtime-install', async () => {
@@ -2587,7 +2591,7 @@ app.whenReady().then(async () => {
}
}
await store.patchGames(inspectedGames);
- runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => preparingLaunch || finalizingGame || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || backend?.current.updating === true);
+ runtime = new RuntimeManager(store.settings.runtimeRoot, emitLog, () => preparingLaunch || finalizingGame || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || backend?.current.updating === true, fetch, process.arch, () => ({launcher:app.getVersion(),backend:backend?.current.version??'0.0.0'}), emitSnapshot);
backend = new BackendManager(app.getPath('userData'), store.settings.externalXodusRoot, emitLog, () => keyringSupport.busy || downloadCancellations.size > 0 || operations.size > 0 || installQueue.size > 0 || preparingInstall || runtime?.busy === true);
await backend.refresh();
await runtime.refresh();
diff --git a/src/main/managed-runtime.test.ts b/src/main/managed-runtime.test.ts
new file mode 100644
index 0000000..eac686c
--- /dev/null
+++ b/src/main/managed-runtime.test.ts
@@ -0,0 +1,340 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { createHash } from 'node:crypto';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { RuntimeManager } from './runtime';
+import { ManagedRuntimeManager } from './managed-runtime';
+import { resolveRuntimeFamily, resolveRuntimeFamilyBuild } from './runtime-families';
+import * as pointer from './runtime-pointer-commit';
+const execute = promisify(execFile), hash = (value: Buffer | string) => createHash('sha256').update(value).digest('hex'), roots: string[] = [];
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await Promise.all(roots.splice(0).map(root => fs.rm(root, {
+ recursive: true, force: true
+ })));
+});
+const policy = {
+ allowCachyos: true, allowPrerelease: true
+};
+async function payload(root: string, letter: string, family = 'nexus-cachyos') {
+ const repository = 'domsvoboda/' + (family === 'nexus' ? 'nexus-runtime' : 'nexus-runtime-cachyos');
+ const commit = letter.repeat(40), name = (family === 'nexus' ? 'nexus-runtime' : 'nexus-runtime-cachyos') + '-11.0-experimental-g' + commit.slice(0, 8), directory = path.join(root, 'remote-' + letter, name), files: Record<string, string> = {}, graph = {
+ proton: commit, wine: 'c'.repeat(40), xgameruntime: 'd'.repeat(40), xml2Source: {
+ commit: 'e'.repeat(40)
+ }, modules: {
+ dxvk: 'f'.repeat(40)
+ }
+ };
+ const required = ['proton', 'files/bin/wine', 'files/bin/wineserver', 'files/bin/wine.nexus-original', ...['PlayFabGameSave.dll', 'gaming-services-version.exe', 'package-registration.exe'].map(n => 'files/share/xodus-nexus/compat/' + n), ...['x86_64', 'i386'].flatMap(cpu => ['xgameruntime.dll', 'winhttp.dll', 'libnghttp2.dll'].map(n => `files/lib/wine/${cpu}-windows/${n}`))];
+ for (const file of required) {
+ await fs.mkdir(path.dirname(path.join(directory, file)), {
+ recursive: true
+ });
+ const bytes = 'inert synthetic ' + letter + ' ' + file;
+ await fs.writeFile(path.join(directory, file), bytes, {
+ mode: 0o755
+ });
+ files[file] = hash(bytes);
+ }
+ await fs.mkdir(path.join(directory, 'files/share/default_pfx/dosdevices'), {
+ recursive: true
+ });
+ await fs.symlink('/', path.join(directory, 'files/share/default_pfx/dosdevices/z:'));
+ const metadata = JSON.stringify({
+ schema: 1, sourceLockSha256: '1'.repeat(64), sourceGraph: graph, requiresBackendVersion: '0.2.13', requiresLauncherVersion: '0.4.1'
+ });
+ await fs.writeFile(path.join(directory, 'XODUS_NEXUS_PATCH.json'), metadata);
+ files['XODUS_NEXUS_PATCH.json'] = hash(metadata);
+ const identity = {
+ schema: 1, family, sourceRepository: repository, sourceCommit: commit, arch: 'x64', prefixSchema: 1, sourceLockSha256: '1'.repeat(64), files, symlinks: {
+ 'files/share/default_pfx/dosdevices/z:': '/'
+ }
+ };
+ const buildId = hash(JSON.stringify(identity));
+ await fs.writeFile(path.join(directory, 'nexus-family.json'), JSON.stringify({
+ ...identity, buildId
+ }));
+ const archiveName = name + '-x86_64.tar.xz', archiveFile = path.join(root, archiveName);
+ await execute('tar', ['-cJf', archiveFile, '-C', path.dirname(directory), name]);
+ const archive = await fs.readFile(archiveFile), checksumName = name + '-x86_64.sha512sum', checksum = Buffer.from(createHash('sha512').update(archive).digest('hex') + ' ' + archiveName + '\n'), sourceName = name + '-source.tar.xz', sourceSum = name + '-source.sha512sum';
+ const assets = new Map<string, Buffer>([[archiveName, archive], [checksumName, checksum], [sourceName, Buffer.from('not downloaded source')], [sourceSum, Buffer.from('not downloaded source sum')]]);
+ const candidate = {
+ schema: 1, kind: 'runtime', repository, commit, ref: 'refs/heads/main', runId: '123', files: [...assets].map(([name, bytes]) => ({
+ name, sha256: hash(bytes), size: bytes.length
+ })), sourceGraph: graph, requiresBackendVersion: '0.2.13', requiresLauncherVersion: '0.4.1', validation: {
+ nativeGateCount: 12, treeSha256: '2'.repeat(64), resultsSha256: '3'.repeat(64), realGameTest: false, stableApproved: false
+ }
+ };
+ const bytes = Buffer.from(JSON.stringify(candidate));
+ assets.set('candidate.json', bytes);
+ const tag = (family === 'nexus' ? 'runtime' : 'runtime-cachyos') + '-11.0-20261103-g' + commit.slice(0, 8), release = {
+ tag_name: tag, target_commitish: commit, draft: false, prerelease: true, published_at: '2026-11-03T12:43:55Z', assets: [...assets].map(([name, bytes]) => ({
+ name, size: bytes.length, browser_download_url: `https://github.com/${repository}/releases/download/${tag}/${name}`
+ }))
+ };
+ return {
+ buildId, commit, archiveName, archiveFile, assets, release, bytes, candidate, directory
+ };
+}
+async function fixture(family = 'nexus-cachyos') {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'managed-install-'));
+ roots.push(root);
+ const runtimeRoot = path.join(root, 'runtime'), save = path.join(root, 'compatdata/game/pfx/save.dat');
+ await fs.mkdir(path.dirname(save), {
+ recursive: true
+ });
+ await fs.writeFile(save, 'preserve progress');
+ const beforeSave = await fs.stat(save);
+ await fs.mkdir(runtimeRoot, {
+ recursive: true
+ });
+ const legacy = path.join(runtimeRoot, 'current.json');
+ await fs.writeFile(legacy, 'legacy default untouched');
+ const saveLink = path.join(path.dirname(save), 'runtime-link');
+ await fs.symlink(legacy, saveLink);
+ let remote = await payload(root, 'a', family);
+ let held: Promise<void> | undefined;
+ let entered: (() => void) | undefined;
+ const fetcher = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes('/releases?'))
+ return new Response(JSON.stringify([remote.release]));
+ const name = url.split('/').pop()!;
+ if (name.endsWith('-source.tar.xz') || name.endsWith('-source.sha512sum'))
+ throw Error('Source archive must not be downloaded');
+ if (name === remote.archiveName && held) {
+ entered?.();
+ await held;
+ }
+ const bytes = remote.assets.get(name);
+ if (!bytes)
+ throw Error('Unexpected closed request ' + url);
+ return new Response(bytes);
+ }) as unknown as typeof fetch;
+ const manager = new RuntimeManager(runtimeRoot, () => {
+ }, () => false, fetcher, 'x64', () => ({
+ launcher: '0.4.2', backend: '0.2.14'
+ }));
+ const check = () => manager.checkManagedRuntime(family, policy), install = async () => {
+ const status = await check();
+ expect(status.error).toBeUndefined();
+ return manager.installManagedRuntime(family, status.available!.candidateSha256, policy);
+ };
+ const preserved = async () => {
+ expect(await fs.readFile(save, 'utf8')).toBe('preserve progress');
+ expect((await fs.stat(save)).ino).toBe(beforeSave.ino);
+ expect(await fs.readlink(saveLink)).toBe(legacy);
+ expect(await fs.readFile(legacy, 'utf8')).toBe('legacy default untouched');
+ expect(manager.current.winePath).toBeUndefined();
+ };
+ return {
+ root, runtimeRoot, manager, fetcher, check, install, preserved, get remote() {
+ return remote;
+ }, setRemote: (next: typeof remote) => {
+ remote = next;
+ }, hold: () => {
+ let resume!: () => void;
+ held = new Promise<void>(r => resume = r);
+ const waiting = new Promise<void>(r => entered = r);
+ return {
+ waiting, resume
+ };
+ }
+ };
+}
+it('installs A then B, retains verified A, keeps default and nonempty saves unchanged, invalidates same-identity readiness', async () => {
+ const f = await fixture();
+ expect((await f.install()).success).toBe(true);
+ const a = await resolveRuntimeFamily(f.runtimeRoot, 'nexus-cachyos', 'x64'), oldWine = await fs.stat(a.winePath);
+ await f.preserved();
+ f.setRemote(await payload(f.root, 'b'));
+ const status = await f.manager.checkManagedRuntime('nexus-cachyos', {
+ allowCachyos: false, allowPrerelease: true
+ });
+ expect(status.channel).toBe('prerelease');
+ expect(status.updateAvailable).toBe(true);
+ expect((await f.manager.installManagedRuntime('nexus-cachyos', status.available!.candidateSha256, {
+ allowCachyos: false, allowPrerelease: true
+ })).success).toBe(true);
+ expect((await resolveRuntimeFamily(f.runtimeRoot, 'nexus-cachyos', 'x64')).buildId).toBe(f.remote.buildId);
+ expect((await resolveRuntimeFamilyBuild(f.runtimeRoot, 'nexus-cachyos', a, 'x64')).buildId).toBe(a.buildId);
+ expect((await fs.stat(a.winePath)).ino).toBe(oldWine.ino);
+ const revision = f.manager.current.managedRevision!;
+ expect((await f.install()).success).toBe(true);
+ expect(f.manager.current.managedRevision).toBe(revision + 1);
+ expect((await f.check()).updateAvailable).toBe(false);
+ await f.preserved();
+});
+it('rejects stale targets, explicit prerelease opt-out and missing first CachyOS permission', async () => {
+ const f = await fixture();
+ const denied = await f.manager.checkManagedRuntime('nexus-cachyos', {
+ allowCachyos: false, allowPrerelease: true
+ });
+ expect(denied.available).toBeUndefined();
+ expect(denied.error).toContain('opt-in');
+ const target = await f.check();
+ expect((await f.manager.installManagedRuntime('nexus-cachyos', '0'.repeat(64), policy)).committed).toBe(false);
+ expect((await f.manager.installManagedRuntime('nexus-cachyos', target.available!.candidateSha256, {
+ allowCachyos: true, allowPrerelease: false
+ })).committed).toBe(false);
+ await f.preserved();
+});
+it('holds actual manager reservation through archive download and prevents root/settings races', async () => {
+ const f = await fixture(), status = await f.check(), gate = f.hold();
+ const job = f.manager.installManagedRuntime('nexus-cachyos', status.available!.candidateSha256, policy);
+ await gate.waiting;
+ expect(f.manager.busy).toBe(true);
+ expect(() => f.manager.setRoot(path.join(f.root, 'other'))).toThrow();
+ expect(() => f.manager.reserveSettingsChange()).toThrow();
+ await expect(f.manager.installNexus(() => {
+ })).rejects.toThrow();
+ gate.resume();
+ expect((await job).success).toBe(true);
+ expect(f.manager.busy).toBe(false);
+ await f.preserved();
+});
+it('fails safely for same-build payload corruption without replacing or deleting it', async () => {
+ const f = await fixture();
+ await f.install();
+ const a = await resolveRuntimeFamily(f.runtimeRoot, 'nexus-cachyos', 'x64');
+ await fs.writeFile(a.winePath, 'preserve corrupt evidence');
+ const result = await f.install();
+ expect(result.success).toBe(false);
+ expect(result.committed).toBe(false);
+ expect(result.error).toContain('preserved');
+ expect(await fs.readFile(a.winePath, 'utf8')).toBe('preserve corrupt evidence');
+ await f.preserved();
+});
+it('can recover to distinct verified B while preserving invalid old pointer as untrusted evidence', async () => {
+ const f = await fixture();
+ await f.install();
+ const current = path.join(f.runtimeRoot, 'variants/nexus-cachyos/current.json');
+ await fs.writeFile(current, 'invalid old pointer');
+ f.setRemote(await payload(f.root, 'b'));
+ expect((await f.install()).success).toBe(true);
+ const evidence = path.join(f.runtimeRoot, 'variants/nexus-cachyos/preserved', hash('invalid old pointer') + '.json');
+ expect(await fs.readFile(evidence, 'utf8')).toBe('invalid old pointer');
+ await f.preserved();
+});
+it('rejects validly downloaded but candidate-mismatched embedded graph before changing active selection', async () => {
+ const f = await fixture();
+ f.remote.candidate.sourceGraph.modules.dxvk = '0'.repeat(40);
+ const bytes = Buffer.from(JSON.stringify(f.remote.candidate));
+ f.remote.assets.set('candidate.json', bytes);
+ f.remote.release.assets.find(a => a.name === 'candidate.json')!.size = bytes.length;
+ const result = await f.install();
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('source graph');
+ await expect(fs.access(path.join(f.runtimeRoot, 'variants/nexus-cachyos/current.json'))).rejects.toThrow();
+ await f.preserved();
+});
+it('reports visible commit with unknown durability instead of pretending the old selection survived', async () => {
+ const f = await fixture(), real = pointer.commitRuntimePointer;
+ vi.spyOn(pointer, 'commitRuntimePointer').mockImplementation((root, record) => real(root, record, {
+ ...fs, open: async (file, flags, mode) => {
+ const handle = await fs.open(file, flags, mode);
+ return file === root ? {
+ writeFile: async () => {
+ }, sync: async () => {
+ throw Error('injected directory sync');
+ }, close: () => handle.close()
+ } : handle;
+ }
+ }));
+ const result = await f.install();
+ expect(result.success).toBe(false);
+ expect(result.committed).toBe(true);
+ expect(result.durability).toBe('unknown');
+ expect((await resolveRuntimeFamily(f.runtimeRoot, 'nexus-cachyos', 'x64')).buildId).toBe(f.remote.buildId);
+ expect(f.manager.busy).toBe(false);
+ await f.preserved();
+});
+it('clears checking after initial status callback failure and guarantees lease release despite completion/notify exceptions', async () => {
+ const f = await fixture();
+ let released = 0, broken = true;
+ const raw = new ManagedRuntimeManager({
+ root: () => f.runtimeRoot, reserve: () => ({
+ root: f.runtimeRoot, release: () => {
+ released++;
+ }
+ }), versions: () => ({
+ launcher: '0.4.2', backend: '0.2.14'
+ }), completed: () => {
+ broken = true;
+ throw Error('completion failure');
+ }, notify: () => {
+ if (broken)
+ throw Error('notify failure');
+ }, fetcher: f.fetcher, arch: 'x64'
+ });
+ expect((await raw.check('nexus-cachyos', policy)).checking).toBe(false);
+ broken = false;
+ const status = await raw.check('nexus-cachyos', policy);
+ broken = false;
+ const result = await raw.install('nexus-cachyos', status.available!.candidateSha256, policy);
+ expect(result.success).toBe(false);
+ expect(released).toBe(1);
+ expect(result.committed).toBe(true);
+ expect(result.error).toContain('completion failure');
+ expect(result.error).toContain('notify failure');
+});
+it('installs the standard managed family without changing legacy selection or requiring Cachy opt-in', async () => {
+ const f = await fixture('nexus');
+ const status = await f.manager.checkManagedRuntime('nexus', {
+ allowCachyos: false, allowPrerelease: true
+ });
+ expect(status.error).toBeUndefined();
+ const result = await f.manager.installManagedRuntime('nexus', status.available!.candidateSha256, {
+ allowCachyos: false, allowPrerelease: true
+ });
+ expect(result.success).toBe(true);
+ expect((await resolveRuntimeFamily(f.runtimeRoot, 'nexus', 'x64')).buildId).toBe(f.remote.buildId);
+ await f.preserved();
+});
+it('selects supported latest metadata before parsing irrelevant legacy or incompatible historic releases', async () => {
+ const f = await fixture(), original = vi.mocked(f.fetcher).getMockImplementation()!;
+ const legacy = {
+ ...f.remote.release, tag_name: 'runtime-cachyos-old', published_at: '2026-10-01T00:00:00Z', assets: []
+ }, old = {
+ ...f.remote.release, published_at: '2026-10-02T00:00:00Z', assets: [f.remote.release.assets.find(a => a.name === 'candidate.json')]
+ };
+ vi.mocked(f.fetcher).mockImplementation(async (input, init) => String(input).includes('/releases?') ? new Response(JSON.stringify([legacy, old, f.remote.release])) : original(input, init));
+ expect((await f.check()).available).toBeDefined();
+});
+it('does not fall back past a malformed newest supported candidate', async () => {
+ const f = await fixture();
+ const broken = {
+ ...f.remote.release, published_at: '2026-11-04T00:00:00Z', assets: f.remote.release.assets.filter(a => !a.name.endsWith('-source.sha512sum'))
+ };
+ vi.mocked(f.fetcher).mockResolvedValue(new Response(JSON.stringify([f.remote.release, broken])));
+ const status = await f.check();
+ expect(status.available).toBeUndefined();
+ expect(status.error).toBeTruthy();
+});
+it('does not reconcile stale A status after B has committed', async () => {
+ const f = await fixture();
+ await f.install();
+ const raw = (f.manager as any).managed as ManagedRuntimeManager, original = (raw as any).installed.bind(raw);
+ let resume!: () => void, entered!: () => void;
+ const gate = new Promise<void>(r => resume = r), waiting = new Promise<void>(r => entered = r);
+ let held = true;
+ vi.spyOn(raw as any, 'installed').mockImplementation(async (...args: any[]) => {
+ const value = await original(...args);
+ if (held && args[0] === 'nexus-cachyos') {
+ held = false;
+ entered();
+ await gate;
+ }
+ return value;
+ });
+ const old = raw.refresh();
+ await waiting;
+ f.setRemote(await payload(f.root, 'b'));
+ expect((await f.install()).success).toBe(true);
+ resume();
+ await old;
+ expect(raw.current.find(s => s.id === 'nexus-cachyos')?.installed?.buildId).toBe(f.remote.buildId);
+});
diff --git a/src/main/managed-runtime.ts b/src/main/managed-runtime.ts
new file mode 100644
index 0000000..a556dcb
--- /dev/null
+++ b/src/main/managed-runtime.ts
@@ -0,0 +1,502 @@
+import { promises as fs } from 'node:fs';
+import { createHash, randomUUID } from 'node:crypto';
+import path from 'node:path';
+import { isDeepStrictEqual } from 'node:util';
+import type { ManagedFamilyStatus, ManagedFamilyInstallResult, ManagedRuntimeOptions } from '../shared/types.js';
+import { runtimeFamilies, type RuntimeFamily } from '../shared/runtime-selection.js';
+import { parseManagedFamilyRelease, verifyManagedFamilyCandidate, type VerifiedManagedFamilyRelease } from './runtime-family-release.js';
+import { resolveRuntimeFamily, retainRuntimeFamilyBuild, verifyRuntimeFamilyPayload, type RuntimeFamilyReceipt } from './runtime-families.js';
+import { materializeRuntimeArchive } from './runtime-family-archive.js';
+import { runtimePayloadMatches } from './runtime-payload-identity.js';
+import { commitRuntimePointer } from './runtime-pointer-commit.js';
+const repositories = {
+ nexus: 'domsvoboda/nexus-runtime', 'nexus-cachyos': 'domsvoboda/nexus-runtime-cachyos'
+};
+const digest = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex');
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v) && typeof v === 'object' && !Array.isArray(v);
+function familyId(v: unknown): RuntimeFamily {
+ if (v !== 'nexus' && v !== 'nexus-cachyos')
+ throw Error('Unknown managed runtime family');
+ return v;
+}
+function options(v: unknown): ManagedRuntimeOptions {
+ if (!object(v) || typeof v.allowCachyos !== 'boolean' || typeof v.allowPrerelease !== 'boolean')
+ throw Error('Explicit runtime release options are required');
+ return {
+ allowCachyos: v.allowCachyos, allowPrerelease: v.allowPrerelease
+ };
+}
+export interface ManagedRuntimeLease {
+ root: string;
+ release(): void;
+}
+interface Target {
+ root: string;
+ release: VerifiedManagedFamilyRelease;
+ input: unknown;
+ bytes: Buffer;
+ policy: ManagedRuntimeOptions;
+}
+interface Context {
+ root: () => string;
+ reserve: () => ManagedRuntimeLease;
+ versions: () => {
+ launcher: string;
+ backend: string;
+ };
+ completed: () => void;
+ notify: () => void;
+ fetcher?: typeof fetch;
+ arch?: string;
+}
+/** Shared managed components only. Never writes global selection, games or prefixes. */
+export class ManagedRuntimeManager {
+ private states = new Map<RuntimeFamily, ManagedFamilyStatus>(runtimeFamilies.map(id => [id, {
+ id, checking: false, installing: false
+ }]));
+ private selectionEpoch = 0;
+ private targets = new Map<RuntimeFamily, Target>();
+ private epochs = new Map<RuntimeFamily, number>();
+ constructor(private context: Context) {
+ }
+ get revision(): number { return this.selectionEpoch; }
+ get current(): ManagedFamilyStatus[] {
+ return structuredClone([...this.states.values()]);
+ }
+ private async installed(id: RuntimeFamily, root: string) {
+ const directory = path.join(root, 'variants', id), pointerFile = path.join(directory, 'current.json');
+ const stamp = await fs.lstat(pointerFile);
+ if (!stamp.isFile() || stamp.size > 65536)
+ throw Error('Invalid managed pointer');
+ const pointerBytes = await fs.readFile(pointerFile);
+ const verified = await resolveRuntimeFamily(root, id, this.context.arch ?? process.arch), pointer = JSON.parse(pointerBytes.toString('utf8'));
+ if (pointer.buildId !== verified.buildId || pointer.sourceCommit !== verified.sourceCommit || pointer.manifestSha256 !== verified.manifestSha256)
+ throw Error('Managed selection changed while checking');
+ let provenance: Record<string, unknown> | undefined;
+ if (typeof pointer.candidateSha256 === 'string' && /^[a-f0-9]{64}$/.test(pointer.candidateSha256))
+ try {
+ const file = path.join(directory, 'provenance', verified.buildId + '.' + pointer.candidateSha256 + '.json');
+ const stat = await fs.lstat(file);
+ if (!stat.isFile() || stat.size > 65536)
+ throw Error('Invalid release provenance');
+ const record = JSON.parse(await fs.readFile(file, 'utf8'));
+ if (record.schema === 1 && record.family === id && record.buildId === verified.buildId && record.sourceCommit === verified.sourceCommit && record.manifestSha256 === verified.manifestSha256 && record.candidateSha256 === pointer.candidateSha256 && typeof record.tag === 'string' && typeof record.prerelease === 'boolean')
+ provenance = record;
+ }
+ catch { /* A legacy verified build is not silently assigned a release channel. */
+ }
+ if (!(await fs.readFile(pointerFile)).equals(pointerBytes))
+ throw Error('Managed selection changed while checking');
+ return {
+ verified, provenance
+ };
+ }
+ async refresh(): Promise<void> {
+ const root = this.context.root(), epoch = this.selectionEpoch;
+ await Promise.all(runtimeFamilies.map(async (id) => {
+ const state = this.states.get(id)!;
+ try {
+ const { verified, provenance } = await this.installed(id, root);
+ if (root !== this.context.root() || epoch !== this.selectionEpoch)
+ return;
+ state.installed = {
+ id: verified.id, label: verified.label, buildId: verified.buildId, sourceCommit: verified.sourceCommit, manifestSha256: verified.manifestSha256
+ };
+ state.version = provenance?.tag as string | undefined;
+ state.channel = provenance ? (provenance.prerelease ? 'prerelease' : 'stable') : undefined;
+ state.updateAvailable = state.available ? provenance?.candidateSha256 !== state.available.candidateSha256 : undefined;
+ }
+ catch {
+ if (root === this.context.root() && epoch === this.selectionEpoch) {
+ state.installed = undefined;
+ state.version = undefined;
+ state.channel = undefined;
+ state.updateAvailable = state.available ? true : undefined;
+ }
+ }
+ }));
+ }
+ private async policy(id: RuntimeFamily, root: string, value: unknown): Promise<ManagedRuntimeOptions> {
+ const request = options(value);
+ try {
+ const installed = await this.installed(id, root);
+ return {
+ allowCachyos: request.allowCachyos || id === 'nexus-cachyos', allowPrerelease: request.allowPrerelease
+ };
+ }
+ catch {
+ return request;
+ }
+ }
+ private async response(url: string): Promise<Response> {
+ let next = url;
+ for (let redirects = 0; redirects < 5; redirects++) {
+ const response = await (this.context.fetcher ?? fetch)(next, {
+ redirect: 'manual', signal: AbortSignal.timeout(600000), headers: {
+ Accept: 'application/vnd.github+json'
+ }
+ });
+ if (![301, 302, 303, 307, 308].includes(response.status)) {
+ if (!response.ok)
+ throw Error('Runtime release download failed: HTTP ' + response.status);
+ return response;
+ }
+ const location = response.headers.get('location');
+ if (!location)
+ throw Error('Missing runtime asset redirect');
+ const target = new URL(location, next);
+ if (target.protocol !== 'https:' || target.username || target.password || target.port || !['release-assets.githubusercontent.com', 'objects.githubusercontent.com'].includes(target.hostname))
+ throw Error('Untrusted runtime asset redirect');
+ next = target.href;
+ }
+ throw Error('Too many runtime asset redirects');
+ }
+ private async bytes(url: string, limit: number, exact?: number): Promise<Buffer> {
+ const response = await this.response(url);
+ if (!response.body)
+ throw Error('Empty runtime metadata response');
+ const chunks: Buffer[] = [];
+ let length = 0;
+ for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
+ length += chunk.length;
+ if (length > limit)
+ throw Error('Runtime metadata exceeds limit');
+ chunks.push(Buffer.from(chunk));
+ }
+ if (exact !== undefined && length !== exact)
+ throw Error('Runtime metadata size mismatch');
+ return Buffer.concat(chunks);
+ }
+ async check(selection: unknown, value: unknown): Promise<ManagedFamilyStatus> {
+ const id = familyId(selection), state = this.states.get(id)!, root = this.context.root(), epoch = (this.epochs.get(id) ?? 0) + 1;
+ this.epochs.set(id, epoch);
+ state.checking = true;
+ state.error = undefined;
+ try {
+ this.context.notify();
+ const policy = await this.policy(id, root, value), versions = this.context.versions(), arch = this.context.arch ?? process.arch;
+ const json = JSON.parse((await this.bytes('https://api.github.com/repos/' + repositories[id] + '/releases?per_page=30', 2 * 1024 * 1024)).toString('utf8'));
+ if (!Array.isArray(json) || json.length > 100)
+ throw Error('Invalid runtime release list');
+ // Legacy releases without candidate metadata are not managed-family targets.
+ // Select newest in the chosen channel first, then validate it exactly. Never
+ // fall back past a malformed newest trusted-format candidate.
+ const candidates = json.filter(item => object(item) && item.draft !== true && (item.prerelease !== true || policy.allowPrerelease) && typeof item.tag_name === 'string' && item.tag_name.startsWith(id === 'nexus' ? 'runtime-' : 'runtime-cachyos-') && Array.isArray(item.assets) && item.assets.some(asset => object(asset) && asset.name === 'candidate.json'));
+ for (const item of candidates)
+ if (typeof item.published_at !== 'string' || !Number.isFinite(Date.parse(item.published_at)))
+ throw Error('Invalid managed runtime publication date');
+ candidates.sort((a, b) => Date.parse(String(b.published_at)) - Date.parse(String(a.published_at)));
+ if (!candidates.length)
+ throw Error('No supported published managed-family release is available');
+ const selected = {
+ input: candidates[0], release: parseManagedFamilyRelease(id, candidates[0], {
+ ...policy, arch, launcherVersion: versions.launcher, backendVersion: versions.backend
+ })
+ };
+ const bytes = await this.bytes(selected.release.assets.candidate.url, 2 * 1024 * 1024, selected.release.assets.candidate.size), release = verifyManagedFamilyCandidate(bytes, selected.release);
+ if (root !== this.context.root() || this.epochs.get(id) !== epoch)
+ throw Error('Runtime release selection changed while checking');
+ this.targets.set(id, {
+ root, release, input: selected.input, bytes, policy
+ });
+ state.available = {
+ version: release.tag, candidateSha256: release.candidateSha256, sourceCommit: release.commit, archiveName: release.assets.binary.name, requiresBackendVersion: release.requiresBackendVersion, requiresLauncherVersion: release.requiresLauncherVersion
+ };
+ await this.refresh();
+ }
+ catch (error) {
+ if (this.epochs.get(id) === epoch) {
+ this.targets.delete(id);
+ state.available = undefined;
+ state.updateAvailable = undefined;
+ state.error = (error as Error).message;
+ }
+ }
+ finally {
+ if (this.epochs.get(id) === epoch) {
+ state.checking = false;
+ try {
+ this.context.notify();
+ }
+ catch (error) {
+ state.error = [state.error, 'Updating runtime status failed: ' + (error as Error).message].filter(Boolean).join(' ');
+ }
+ }
+ }
+ return structuredClone(state);
+ }
+ /** A frozen internal target is provided for later component coordinators. */
+ target(selection: unknown): Readonly<VerifiedManagedFamilyRelease> | undefined {
+ return this.targets.get(familyId(selection))?.release;
+ }
+ private async directory(root: string, ...parts: string[]): Promise<string> {
+ let next = root;
+ await fs.mkdir(root, {
+ recursive: true, mode: 0o700
+ });
+ if (!(await fs.lstat(root)).isDirectory())
+ throw Error('Managed runtime root must not be a symlink');
+ for (const part of parts) {
+ next = path.join(next, part);
+ try {
+ await fs.mkdir(next, {
+ mode: 0o700
+ });
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST')
+ throw error;
+ }
+ if (!(await fs.lstat(next)).isDirectory())
+ throw Error('Managed runtime directory must not be a symlink');
+ }
+ return next;
+ }
+ private async immutable(file: string, bytes: Buffer | string): Promise<void> {
+ const temporary = path.join(path.dirname(file), '.receipt-' + randomUUID());
+ let owned = false;
+ try {
+ const handle = await fs.open(temporary, 'wx', 0o600);
+ owned = true;
+ try {
+ await handle.writeFile(bytes);
+ await handle.sync();
+ }
+ finally {
+ await handle.close();
+ }
+ try {
+ await fs.link(temporary, file);
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST')
+ throw error;
+ if (!(await fs.lstat(file)).isFile() || !(await fs.readFile(file)).equals(Buffer.from(bytes)))
+ throw Error('Conflicting managed runtime receipt');
+ }
+ const directory = await fs.open(path.dirname(file), 'r');
+ try {
+ await directory.sync();
+ }
+ finally {
+ await directory.close();
+ }
+ }
+ finally {
+ if (owned)
+ await fs.unlink(temporary).catch(() => {
+ });
+ }
+ }
+ private async pointer(directory: string): Promise<Buffer | undefined> {
+ const file = path.join(directory, 'current.json');
+ try {
+ const before = await fs.lstat(file);
+ if (!before.isFile() || before.size > 65536)
+ throw Error('Invalid managed family pointer');
+ const bytes = await fs.readFile(file), after = await fs.lstat(file);
+ if (before.ino !== after.ino || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || before.size !== after.size)
+ throw Error('Managed family pointer changed');
+ return bytes;
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return undefined;
+ throw error;
+ }
+ }
+ private async archive(target: Target, file: string): Promise<void> {
+ const asset = target.release.assets.binary, record = target.release.files.find(item => item.name === asset.name)!;
+ const checksumAsset = target.release.assets.checksum, checksumRecord = target.release.files.find(item => item.name === checksumAsset.name)!, sum = await this.bytes(checksumAsset.url, 65536, checksumAsset.size);
+ if (digest(sum) !== checksumRecord.sha256)
+ throw Error('Runtime checksum metadata changed');
+ const line = sum.toString('utf8').match(/^([a-f0-9]{128})[ \t]+\*?([^\r\n]+)\r?\n?$/);
+ if (!line || line[2] !== asset.name)
+ throw Error('Runtime checksum does not name the selected archive');
+ const response = await this.response(asset.url);
+ if (!response.body)
+ throw Error('Empty runtime archive');
+ const handle = await fs.open(file, 'wx', 0o600), h256 = createHash('sha256'), h512 = createHash('sha512');
+ let bytes = 0;
+ try {
+ for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
+ bytes += chunk.length;
+ if (bytes > asset.size)
+ throw Error('Runtime archive exceeds selected size');
+ h256.update(chunk);
+ h512.update(chunk);
+ await handle.writeFile(chunk);
+ }
+ }
+ finally {
+ await handle.close();
+ }
+ if (bytes !== asset.size || h256.digest('hex') !== record.sha256 || h512.digest('hex') !== line[1])
+ throw Error('Runtime archive checksum mismatch');
+ }
+ async install(selection: unknown, expected: unknown, value: unknown): Promise<ManagedFamilyInstallResult> {
+ const id = familyId(selection), state = this.states.get(id)!, lease = this.context.reserve();
+ let staging: string | undefined, committed = false, buildId: string | undefined, durability: ManagedFamilyInstallResult['durability'] = 'not-committed';
+ this.selectionEpoch++;
+ this.epochs.set(id, (this.epochs.get(id) ?? 0) + 1);
+ state.checking = false;
+ state.installing = true;
+ state.error = undefined;
+ let outcome: ManagedFamilyInstallResult = {
+ family: id, success: false, committed: false, durability: 'not-committed'
+ };
+ const completionError = (message: string, error: unknown) => {
+ const text = message + ': ' + (error instanceof Error ? error.message : String(error));
+ state.error = [state.error, text].filter(Boolean).join(' ');
+ state.phase = committed ? 'Runtime installed; confirmation needs attention' : 'Active runtime selection was not changed';
+ outcome = {
+ ...outcome, success: false, committed, durability, error: state.error
+ };
+ };
+ try {
+ const selected = this.targets.get(id);
+ if (!selected || selected.root !== lease.root || typeof expected !== 'string' || selected.release.candidateSha256 !== expected)
+ throw Error('Check this runtime release again before installing');
+ const policy = await this.policy(id, lease.root, value), versions = this.context.versions();
+ const release = verifyManagedFamilyCandidate(selected.bytes, parseManagedFamilyRelease(id, selected.input, {
+ ...policy, arch: this.context.arch ?? process.arch, launcherVersion: versions.launcher, backendVersion: versions.backend
+ }));
+ const target = {
+ ...selected, release
+ };
+ const directory = await this.directory(lease.root, 'variants', id), releases = await this.directory(lease.root, 'variants', id, 'releases'), receipts = await this.directory(lease.root, 'variants', id, 'receipts'), provenance = await this.directory(lease.root, 'variants', id, 'provenance');
+ const before = await this.pointer(directory);
+ if (before) {
+ let valid = false;
+ try {
+ await resolveRuntimeFamily(lease.root, id, this.context.arch ?? process.arch);
+ valid = true;
+ }
+ catch { /* Preserve invalid old evidence, never bless it into a trusted receipt. */
+ }
+ if (valid)
+ await retainRuntimeFamilyBuild(lease.root, id, this.context.arch ?? process.arch);
+ else {
+ const evidence = await this.directory(lease.root, 'variants', id, 'preserved');
+ await this.immutable(path.join(evidence, digest(before) + '.json'), before);
+ }
+ }
+ staging = await this.directory(lease.root, 'variants', id, '.staging-' + randomUUID());
+ const archive = path.join(staging, release.assets.binary.name);
+ state.phase = 'Downloading and verifying runtime';
+ this.context.notify();
+ await this.archive(target, archive);
+ const extracted = path.join(staging, 'payload');
+ await fs.mkdir(extracted, {
+ mode: 0o700
+ });
+ state.phase = 'Checking runtime files';
+ this.context.notify();
+ const top = release.assets.binary.name.slice(0, -'.tar.xz'.length).replace(/-x86_64$/, '');
+ const payload = await materializeRuntimeArchive(archive, extracted, top);
+ const manifestFile = path.join(payload, 'nexus-family.json');
+ if (!(await fs.lstat(manifestFile)).isFile() || (await fs.stat(manifestFile)).size > 4 * 1024 * 1024)
+ throw Error('Missing bounded managed-family manifest');
+ const bytes = await fs.readFile(manifestFile), manifest = JSON.parse(bytes.toString('utf8'));
+ buildId = manifest.buildId;
+ const receipt: RuntimeFamilyReceipt = {
+ schema: 1, family: id, sourceRepository: repositories[id], buildId: manifest.buildId, manifestSha256: digest(bytes), sourceCommit: release.commit
+ };
+ const { buildId: ignored, ...identity } = manifest;
+ if (digest(JSON.stringify(identity)) !== buildId)
+ throw Error('Runtime build identity is not derived from its manifest');
+ await verifyRuntimeFamilyPayload(payload, receipt, this.context.arch ?? process.arch);
+ const metadata = JSON.parse(await fs.readFile(path.join(payload, 'XODUS_NEXUS_PATCH.json'), 'utf8'));
+ if (!isDeepStrictEqual(metadata.sourceGraph, release.sourceGraph) || metadata.requiresBackendVersion !== release.requiresBackendVersion || metadata.requiresLauncherVersion !== release.requiresLauncherVersion)
+ throw Error('Runtime payload differs from candidate source graph or requirements');
+ const destination = path.join(releases, receipt.buildId);
+ let exists = true;
+ try {
+ await fs.lstat(destination);
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
+ throw error;
+ exists = false;
+ }
+ if (exists) {
+ if (!await runtimePayloadMatches(payload, destination))
+ throw Error('The existing build differs from this verified release and was preserved. Choose a different release or restore it explicitly.');
+ }
+ else {
+ await fs.rename(payload, destination);
+ const parent = await fs.open(releases, 'r');
+ try {
+ await parent.sync();
+ }
+ finally {
+ await parent.close();
+ }
+ }
+ await verifyRuntimeFamilyPayload(destination, receipt, this.context.arch ?? process.arch);
+ const canonical = {
+ schema: 1, family: id, sourceRepository: repositories[id], buildId: receipt.buildId, manifestSha256: receipt.manifestSha256, sourceCommit: receipt.sourceCommit
+ };
+ await this.immutable(path.join(receipts, receipt.buildId + '.json'), JSON.stringify(canonical) + '\n');
+ const proof = {
+ ...canonical, tag: release.tag, prerelease: release.prerelease, candidateSha256: release.candidateSha256, files: release.files
+ };
+ await this.immutable(path.join(provenance, receipt.buildId + '.' + release.candidateSha256 + '.json'), JSON.stringify(proof) + '\n');
+ const actual = await this.pointer(directory);
+ if (before === undefined ? actual !== undefined : actual === undefined || !actual.equals(before))
+ throw Error('Managed runtime selection changed before publication');
+ const result = await commitRuntimePointer(directory, {
+ ...canonical, releaseTag: release.tag, prerelease: release.prerelease, candidateSha256: release.candidateSha256
+ });
+ committed = true;
+ this.selectionEpoch++;
+ durability = result.durability;
+ await this.refresh();
+ if (state.installed?.buildId !== receipt.buildId || state.installed.manifestSha256 !== receipt.manifestSha256)
+ throw Error('Runtime selection was published, but installed files could not be verified afterward');
+ if (result.errors.length)
+ throw new AggregateError(result.errors, 'Runtime installed, but confirming its saved selection failed: ' + result.errors.map(error => error.message).join(' '));
+ state.phase = 'Runtime installed';
+ outcome = {
+ family: id, success: true, committed: true, buildId, durability
+ };
+ }
+ catch (error) {
+ state.error = (error as Error).message;
+ state.phase = committed ? 'Runtime installed; confirmation needs attention' : 'Active runtime selection was not changed';
+ outcome = {
+ family: id, success: false, committed, buildId, durability, error: state.error
+ };
+ }
+ finally {
+ if (staging)
+ await fs.rm(staging, {
+ recursive: true, force: true
+ }).catch(error => completionError('Cleaning runtime staging failed', error));
+ state.installing = false;
+ try {
+ this.context.completed();
+ }
+ catch (error) {
+ completionError('Updating runtime readiness failed', error);
+ }
+ finally {
+ try {
+ lease.release();
+ }
+ catch (error) {
+ completionError('Releasing runtime reservation failed', error);
+ }
+ finally {
+ try {
+ this.context.notify();
+ }
+ catch (error) {
+ completionError('Updating runtime status failed', error);
+ }
+ }
+ }
+ }
+ return outcome;
+ }
+}
diff --git a/src/main/runtime.ts b/src/main/runtime.ts
index e6a7cc4..46866e2 100644
--- a/src/main/runtime.ts
+++ b/src/main/runtime.ts
@@ -1,3 +1,4 @@
+import {ManagedRuntimeManager} from './managed-runtime.js';
import {commitRuntimePointer,type PointerCommitResult} from './runtime-pointer-commit.js';
import {installedRuntimeFamilies} from './runtime-families.js';
import {runtimeWineFailure} from './runtime-prerequisites.js';
@@ -65,6 +66,7 @@ type AfterInstall = ((winePath: string) => Promise<void>) | {
interface Activation {winePath:string;pointer:PointerCommitResult;}
export class RuntimeManager {
+ private managed:ManagedRuntimeManager;
private mutation?: symbol;
private settingsReservation?: RuntimeSettingsReservation;
private status: RuntimeStatus;
@@ -75,7 +77,7 @@ export class RuntimeManager {
private readonly fetcher: typeof fetch;
private readonly hostArch: string;
- constructor(runtimeRoot: string, emitLog: (scope: string, line: string) => void, isOperationActive: () => boolean, fetcher: typeof fetch = fetch, hostArch: string = process.arch) {
+ constructor(runtimeRoot: string, emitLog: (scope: string, line: string) => void, isOperationActive: () => boolean, fetcher: typeof fetch = fetch, hostArch: string = process.arch, versions:()=>{launcher:string;backend:string}=()=>({launcher:'0.0.0',backend:'0.0.0'}), managedNotify:()=>void=()=>{}) {
this.emitLog = emitLog;
this.isOperationActive = isOperationActive;
this.fetcher = fetcher;
@@ -88,9 +90,14 @@ export class RuntimeManager {
artifactAvailable: false,
prerequisites: { gh: false, authenticated: false, tar: false, sha512sum: false },
};
+ this.managed=new ManagedRuntimeManager({root:()=>this.status.runtimeRoot,reserve:()=>this.reserveMutation(),versions,fetcher,arch:hostArch,notify:managedNotify,completed:()=>{this.status.managedRevision=(this.status.managedRevision??0)+1;}});
}
- get current(): RuntimeStatus { return structuredClone(this.status); }
+ get current(): RuntimeStatus { return structuredClone({...this.status,managedFamilies:this.managed.current}); }
+ checkManagedRuntime(family:unknown,options:unknown,onStatus:()=>void=()=>{}) {return this.managedCheck(family,options,onStatus);}
+ private async managedCheck(family:unknown,options:unknown,onStatus:()=>void) {try{onStatus();return await this.managed.check(family,options);}finally{onStatus();}}
+ async installManagedRuntime(family:unknown,expected:unknown,options:unknown,onStatus:()=>void=()=>{}) {const result=await this.managed.install(family,expected,options);try{await this.refreshFamilies();onStatus();}catch(error){return {...result,success:false,error:[result.error,'Updating runtime status failed: '+(error as Error).message].filter(Boolean).join(' ')};}return result;}
+ managedTarget(family:unknown){return this.managed.target(family);}
get busy(): boolean { return this.mutation !== undefined; }
setRoot(root: string): void {
if (this.busy) throw new Error('The runtime cannot be changed while a Xodus operation is active.');
@@ -144,10 +151,12 @@ export class RuntimeManager {
}
async refreshFamilies() {
- const root=this.status.runtimeRoot;
+ const root=this.status.runtimeRoot,revision=this.managed.revision;
const variants=await installedRuntimeFamilies(root,this.hostArch);
if(root!==this.status.runtimeRoot)throw Error('Runtime location changed. Check installed families again.');
+ if(revision!==this.managed.revision)return structuredClone(this.status.variants??[]);
this.status.variants=variants;
+ await this.managed.refresh();
return structuredClone(variants);
}