Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
Harden runtime family resolution and cache verified payloads
Dom Svobodac62f9aa0574e
diff --git a/scripts/RUNTIME_FAMILIES.md b/scripts/RUNTIME_FAMILIES.mdindex 271ee80..56afcb5 100644--- a/scripts/RUNTIME_FAMILIES.md+++ b/scripts/RUNTIME_FAMILIES.md@@ -20,7 +20,8 @@ This schema-1 manifest repeats the identity fields and binds `arch: "x64"`,file to its SHA-256. Optional `symlinks` maps links to exact relative targets.The combined inventory must cover every non-directory entry except the manifestitself. Links must resolve inside the release; executable entry points cannot-be symlinks. ARM64 variants require a separate reviewed payload contract.+be symlinks. The sole external-link exception is the exact template mapping+`files/share/default_pfx/dosdevices/z:` to `/`, recorded without traversal. ARM64 variants require a separate reviewed payload contract.`XODUS_NEXUS_PATCH.json` belongs to the hashed inventory. Its`sourceGraph.proton` must equal `sourceCommit`; its `sourceLockSha256` must@@ -42,7 +43,11 @@ Stop retains the generated runner and wineserver for that session. Laterselection or pointer changes cannot redirect it. Removal or cleanup must retainruntime releases referenced by active sessions or retained prefixes.-Verification currently streams and hashes the full payload on explicit runtime-refresh, capability preview and launch resolution. Snapshot reads and ordinary-UI renders do not scan the payload. Large installed variants may make those-explicit operations slower; no verification cache or performance claim is made.+Verification streams and hashes the full payload on first resolution or after+invalidation. A bounded in-memory cache compares complete inventory and file+identities (device, inode, mode, link count, size, modification and change times)+on subsequent explicit runtime refresh, capability preview or launch resolution.+Unchanged files are not rehashed. Before/after fingerprints must match; failed+or concurrently changed scans are never cached. Concurrent requests coalesce.+Snapshot reads and ordinary UI renders perform no verification I/O. Identity+checks still walk the tree; large uncached variants may take time to verify.diff --git a/src/main/index.ts b/src/main/index.tsindex 9b0e2a3..a997d9e 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -727,8 +727,10 @@ async function gameContent(id: string) {if (authState.running || authState.stored !== true) throw Error('Sign in before checking game content.');const identity = `${authState.username}:${backend.current.binaryPath}:${currentMarket()}`;accountLibrary.select(authState.username, backend.current.capabilities.library ? backend.current.binaryPath : undefined, currentMarket());+ const selectedRuntime=await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),gameId:game.id,+ selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)});const result = await contentManager().plan(game, () => accountLibrary.access(true), currentMarket());- const wine = selectedWinePath(store.settings.winePath, store.settings.runtimeRoot, runtime.current.winePath);+ const wine = selectedRuntime.winePath;result.plan.runtimeSupported = Boolean(wine && await storeContentRuntime(wine));if (authState.running || authState.stored !== true || identity !== `${authState.username}:${backend.current.binaryPath}:${currentMarket()}`) throw Error('Account changed. Check content again.');return result;diff --git a/src/main/runtime-families.test.ts b/src/main/runtime-families.test.tsindex 368fa7a..ab1f599 100644--- a/src/main/runtime-families.test.ts+++ b/src/main/runtime-families.test.ts@@ -1,4 +1,4 @@-import {afterEach,beforeEach,describe,expect,it} from 'vitest';+import {afterEach,beforeEach,describe,expect,it,vi} from 'vitest';import {promises as fs} from 'node:fs';import path from 'node:path';import os from 'node:os';@@ -6,7 +6,7 @@ import {execFile as execFileCallback} from 'node:child_process';import {promisify} from 'node:util';import {prepareProtonRunner} from './proton';import {createHash} from 'node:crypto';-import {resolveRuntimeFamily,installedRuntimeFamilies} from './runtime-families';+import {resolveRuntimeFamily,installedRuntimeFamilies,runtimeFamilyVerificationStats} from './runtime-families';import {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding';import {gameRuntimeSelection} from '../shared/runtime-selection';let root:string,release:string;@@ -131,3 +131,77 @@ it('verifies inventoried internal directory symlinks while rejecting external taawait fs.unlink(path.join(release,'files/shared-link'));await fs.symlink(root,path.join(release,'files/shared-link'));await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();});++async function reseal(change:(manifest:any)=>void) {+ const file=path.join(release,'nexus-family.json'),pointerFile=path.join(root,'variants',family,'current.json');+ const manifest=JSON.parse(await fs.readFile(file,'utf8'));change(manifest);const bytes=JSON.stringify(manifest);await fs.writeFile(file,bytes);+ const pointer=JSON.parse(await fs.readFile(pointerFile,'utf8'));pointer.manifestSha256=hash(bytes);await fs.writeFile(pointerFile,JSON.stringify(pointer));+}+it('accepts only the exact inventoried default-template Z mapping without dereferencing it',async()=>{+ await fixture();const link='files/share/default_pfx/dosdevices/z:';await fs.mkdir(path.dirname(path.join(release,link)));await fs.symlink('/',path.join(release,link));+ await reseal(manifest=>{manifest.symlinks={[link]:'/'};});+ expect((await resolveRuntimeFamily(root,family,'x64')).id).toBe(family);+ await fs.unlink(path.join(release,link));await fs.symlink('/tmp',path.join(release,link));+ await reseal(manifest=>{manifest.symlinks[link]='/tmp';});await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+});+it('rejects the same absolute target at another path and an escaped intermediate template directory',async()=>{+ await fixture();const link='files/share/default_pfx/z:';await fs.symlink('/',path.join(release,link));+ await reseal(manifest=>{manifest.symlinks={[link]:'/'};});await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+ await fs.unlink(path.join(release,link));const outside=path.join(root,'outside');await fs.mkdir(outside);await fs.symlink('/',path.join(outside,'z:'));+ await fs.symlink(outside,path.join(release,'files/share/default_pfx/dosdevices'));+ await reseal(manifest=>{manifest.symlinks={'files/share/default_pfx/dosdevices/z:':'/'};});await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+});+it('performs one full hash pass for concurrent and repeated unchanged requests, then invalidates changed files',async()=>{+ await fixture();const baseline=runtimeFamilyVerificationStats();+ await Promise.all(Array.from({length:8},()=>resolveRuntimeFamily(root,family,'x64')));+ for(let i=0;i<5;i++)await resolveRuntimeFamily(root,family,'x64');+ expect(runtimeFamilyVerificationStats().fullPasses-baseline.fullPasses).toBe(1);+ expect(runtimeFamilyVerificationStats().cacheHits-baseline.cacheHits).toBe(5);+ const file=path.join(release,'files/bin/wine');const original=await fs.readFile(file);await fs.writeFile(file,original);+ await resolveRuntimeFamily(root,family,'x64');expect(runtimeFamilyVerificationStats().fullPasses-baseline.fullPasses).toBe(2);+ await fs.writeFile(file,'modified');await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+ expect(runtimeFamilyVerificationStats().fullPasses-baseline.fullPasses).toBe(3);+});+it('invalidates receipt, inventory and symlink changes, and never caches a failing scan',async()=>{+ await fixture();await resolveRuntimeFamily(root,family,'x64');let baseline=runtimeFamilyVerificationStats().fullPasses;+ const pointer=path.join(root,'variants',family,'current.json');await fs.appendFile(pointer,' ');await resolveRuntimeFamily(root,family,'x64');+ expect(runtimeFamilyVerificationStats().fullPasses-baseline).toBe(1);+ await fs.writeFile(path.join(release,'extra'),'extra');await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+ expect(runtimeFamilyVerificationStats().fullPasses-baseline).toBe(3);+ await fs.unlink(path.join(release,'extra'));await fs.symlink('files',path.join(release,'extra-link'));await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+});+it('rejects a same-bytes write during full verification and does not cache the raced result',async()=>{+ await fixture();const baseline=runtimeFamilyVerificationStats().fullPasses;+ const original=fs.readFile.bind(fs);let changed=false;+ const spy=vi.spyOn(fs,'readFile').mockImplementation((async(file:any,...args:any[])=>{+ const result=await (original as any)(file,...args);+ if(String(file).endsWith('XODUS_NEXUS_PATCH.json')&&!changed){changed=true;const loader=path.join(release,'files/bin/wine');await fs.writeFile(loader,await original(loader));}+ return result;+ }) as typeof fs.readFile);+ try{await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();}finally{spy.mockRestore();}+ expect(changed).toBe(true);await resolveRuntimeFamily(root,family,'x64');+ expect(runtimeFamilyVerificationStats().fullPasses-baseline).toBe(2);+});++it('rejects a default-runtime alias into a managed family but preserves ordinary default symlinks',async()=>{+ await fixture();const alias=path.join(root,'wine-alias');await fs.symlink(path.join(release,'files/bin/wine'),alias);+ const options={runtimeRoot:root,dataRoot:root,gameId:'test',selection:'default',separatePrefix:false,arch:'x64'};+ await expect(resolveGameRuntime({...options,defaultWine:alias})).rejects.toThrow('separate prefix');+ await fs.unlink(alias);const legacy=path.join(root,'legacy-wine');await fs.writeFile(legacy,'synthetic');await fs.symlink(legacy,alias);+ expect((await resolveGameRuntime({...options,defaultWine:alias})).winePath).toBe(alias);+});+it('rejects a changed cached fingerprint and forces a fresh full pass on retry',async()=>{+ await fixture();await resolveRuntimeFamily(root,family,'x64');const baseline=runtimeFamilyVerificationStats().fullPasses;+ const original=fs.readFile.bind(fs);let pointers=0;+ const spy=vi.spyOn(fs,'readFile').mockImplementation((async(file:any,...args:any[])=>{+ const result=await (original as any)(file,...args);+ if(String(file).endsWith('current.json')&&++pointers===2){const loader=path.join(release,'files/bin/wine');await fs.writeFile(loader,await original(loader));}+ return result;+ }) as typeof fs.readFile);+ try{await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();}finally{spy.mockRestore();}+ await resolveRuntimeFamily(root,family,'x64');expect(runtimeFamilyVerificationStats().fullPasses-baseline).toBe(1);+});+it('rejects a release-root symlink even when its external payload has matching hashes',async()=>{+ await fixture();const moved=path.join(root,'outside-release');await fs.rename(release,moved);await fs.symlink(moved,release);+ await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+});diff --git a/src/main/runtime-families.ts b/src/main/runtime-families.tsindex c547fef..065e702 100644--- a/src/main/runtime-families.ts+++ b/src/main/runtime-families.ts@@ -15,7 +15,7 @@ export interface ResolvedRuntimeFamily extends InstalledRuntimeFamily {}/** Read a receipt written by a verified managed installer, never a user-supplied* executable. A missing or damaged selected family cannot fall back to default. */-export async function resolveRuntimeFamily(runtimeRoot:string,selection:unknown,arch:string=process.arch):Promise<Readonly<ResolvedRuntimeFamily>> {+async function verifyRuntimeFamily(runtimeRoot:string,selection:unknown,arch:string=process.arch):Promise<Readonly<ResolvedRuntimeFamily>> {const id=gameRuntimeSelection(selection);if(id==='default')throw Error('Default runtime resolution requires the existing global runtime.');if(!['x64','arm64'].includes(arch))throw Error('Unsupported runtime architecture.');@@ -50,11 +50,12 @@ export async function resolveRuntimeFamily(runtimeRoot:string,selection:unknown,if(!within(root,target)||(await fs.stat(target)).isFile()!==true||await fileDigest(target)!==expected)throw Error('Runtime payload checksum mismatch');}const symlinks=manifest.symlinks??{};+ const templateMapping=(name:string,target:unknown)=>name==='files/share/default_pfx/dosdevices/z:'&&target==='/';if(!symlinks||Array.isArray(symlinks)||typeof symlinks!=='object')throw Error('Invalid runtime symlink inventory');for(const [name,target] of Object.entries(symlinks)) {- if(typeof target!=='string'||!target||path.isAbsolute(target)||!name||name.includes('\\')||name.split('/').some(part=>!part||part==='.'||part==='..')||path.isAbsolute(name)||name in manifest.files)throw Error('Unsafe runtime symlink path');+ if(typeof target!=='string'||!target||path.isAbsolute(target)&&!templateMapping(name,target)||!name||name.includes('\\')||name.split('/').some(part=>!part||part==='.'||part==='..')||path.isAbsolute(name)||name in manifest.files)throw Error('Unsafe runtime symlink path');const file=path.join(root,name);- if(!(await fs.lstat(file)).isSymbolicLink()||await fs.readlink(file)!==target||!within(root,await fs.realpath(file)))throw Error('Runtime symlink leaves verified payload');+ if(!(await fs.lstat(file)).isSymbolicLink()||await fs.readlink(file)!==target||!within(root,await fs.realpath(path.dirname(file)))||!templateMapping(name,target)&&!within(root,await fs.realpath(file)))throw Error('Runtime symlink leaves verified payload');}const inventory:string[]=[];const walk=async(directory:string)=>{for(const item of await fs.readdir(directory,{withFileTypes:true})){@@ -74,6 +75,65 @@ export async function resolveRuntimeFamily(runtimeRoot:string,selection:unknown,return Object.freeze({id,label:runtimeFamilyLabels[id],buildId:pointer.buildId,sourceCommit:pointer.sourceCommit,winePath,root,arch:arch as 'x64'|'arm64',prefixSchema:1,manifestSha256:pointer.manifestSha256});}catch(error){throw Error(`${runtimeFamilyLabels[id]} is unavailable or failed verification. Reinstall this selected runtime; the default was not used.`,{cause:error});}}+// A cache hit still checks identities and the complete inventory, but never+// reads payload contents. Receipt/manifest/root changes, additions, removals,+// replacements and writes invalidate it. Never cache a concurrently changed scan.+const verified=new Map<string,{fingerprint:string;value:Readonly<ResolvedRuntimeFamily>}>();+const inFlight=new Map<string,Promise<Readonly<ResolvedRuntimeFamily>>>();+let fullPasses=0,cacheHits=0;+export const runtimeFamilyVerificationStats=()=>Object.freeze({fullPasses,cacheHits});+async function runtimeFingerprint(runtimeRoot:string,id:RuntimeFamily):Promise<string> {+ const hash=createHash('sha256');+ const add=(value:string)=>{hash.update(String(Buffer.byteLength(value)));hash.update(':');hash.update(value);};+ const root=await fs.realpath(runtimeRoot),directory=path.join(runtimeRoot,'variants',id);+ const canonical=await fs.realpath(directory);+ if(!within(root,canonical))throw Error('Family path leaves runtime root');+ add(root);add(canonical);+ const pointerFile=path.join(directory,'current.json');+ if(!(await fs.lstat(pointerFile)).isFile())throw Error('Receipt must be a regular file');+ const bytes=await fs.readFile(pointerFile);add(bytes.toString('utf8'));+ const pointer=JSON.parse(bytes.toString('utf8'));+ if(!hashId(pointer.buildId))throw Error('Invalid managed build identity');+ const release=path.join(directory,'releases',pointer.buildId);+ const identity=async(file:string)=>{+ const stat=await fs.lstat(file,{bigint:true});+ add(file);add([stat.dev,stat.ino,stat.mode,stat.nlink,stat.size,stat.mtimeNs,stat.ctimeNs].join(':'));+ if(stat.isSymbolicLink())add(await fs.readlink(file));+ return stat;+ };+ for(const file of [runtimeRoot,directory,path.join(directory,'releases'),pointerFile])await identity(file);+ const walk=async(file:string)=>{+ const stat=await identity(file);+ if(stat.isDirectory())for(const name of (await fs.readdir(file)).sort())await walk(path.join(file,name));+ };+ await walk(release);+ return hash.digest('hex');+}+const hashId=(value:unknown)=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);+export async function resolveRuntimeFamily(runtimeRoot:string,selection:unknown,arch:string=process.arch):Promise<Readonly<ResolvedRuntimeFamily>> {+ const id=gameRuntimeSelection(selection);+ if(id==='default')throw Error('Default runtime resolution requires the existing global runtime.');+ const key=JSON.stringify([path.resolve(runtimeRoot),id,arch]);+ const pending=inFlight.get(key);if(pending)return pending;+ const work=(async()=>{+ try {+ const before=await runtimeFingerprint(runtimeRoot,id);+ const previous=verified.get(key);+ if(previous?.fingerprint===before){+ if(await runtimeFingerprint(runtimeRoot,id)!==before)throw Error('Runtime changed during cached verification.');+ cacheHits++;return previous.value;+ }+ verified.delete(key);fullPasses++;+ const value=await verifyRuntimeFamily(runtimeRoot,id,arch);+ if(await runtimeFingerprint(runtimeRoot,id)!==before)throw Error('Runtime changed during verification. Retry after installation finishes.');+ verified.set(key,{fingerprint:before,value});+ while(verified.size>8)verified.delete(verified.keys().next().value!);+ return value;+ }catch(error){verified.delete(key);throw Error(`${runtimeFamilyLabels[id]} is unavailable or failed verification. Reinstall this selected runtime; the default was not used.`,{cause:error});}+ })();+ inFlight.set(key,work);+ try{return await work;}finally{if(inFlight.get(key)===work)inFlight.delete(key);}+}export async function installedRuntimeFamilies(runtimeRoot:string,arch:string=process.arch):Promise<InstalledRuntimeFamily[]> {const results=await Promise.all(runtimeFamilies.map(async id=>{try{const value=await resolveRuntimeFamily(runtimeRoot,id,arch);return {id:value.id,label:value.label,buildId:value.buildId,sourceCommit:value.sourceCommit};}catch{return undefined;}diff --git a/src/main/runtime-prefix-binding.ts b/src/main/runtime-prefix-binding.tsindex 8d0d406..72b3a9a 100644--- a/src/main/runtime-prefix-binding.ts+++ b/src/main/runtime-prefix-binding.ts@@ -14,8 +14,10 @@ export async function resolveGameRuntime(options:{runtimeRoot:string;dataRoot:stif(!/^[A-Za-z0-9_-]{1,128}$/.test(options.gameId))throw Error('Invalid game prefix identity.');if(selection==='default') {if(!options.defaultWine)throw Error('Select a default Wine / Proton runtime in Settings.');- const relative=path.relative(path.join(options.runtimeRoot,'variants'),options.defaultWine);- if(relative&&!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative))throw Error('Select managed runtime families per game with a separate prefix.');+ const canonical=async(file:string)=>fs.realpath(file).catch(error=>{if(error.code==='ENOENT')return path.resolve(file);throw error;});+ const managed=path.join(options.runtimeRoot,'variants');+ const inside=(root:string,file:string)=>{const relative=path.relative(root,file);return Boolean(relative)&&!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative);};+ if(inside(managed,options.defaultWine)||inside(await canonical(managed),await canonical(options.defaultWine)))throw Error('Select managed runtime families per game with a separate prefix.');return Object.freeze({selection,family:'default',winePath:options.defaultWine,dataRoot:options.dataRoot,compatibilityDataPath:path.join(options.dataRoot,'compatdata',options.gameId),legacyPrefixRoot:path.join(options.dataRoot,'prefixes',options.gameId)});}