Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
Add verified per-game runtime families with isolated prefixes
Dom Svobodaec72f7979877
diff --git a/assets/locales/de.json b/assets/locales/de.jsonindex 3f916c7..db078db 100644--- a/assets/locales/de.json+++ b/assets/locales/de.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Spiel-Laufzeit",+ "runtime.use_default": "Standard-Laufzeit verwenden",+ "runtime.unavailable": "{{name}} (nicht verfügbar)",+ "runtime.separate_prefix": "Separates Präfix für diesen Laufzeit-Build verwenden",+ "runtime.prefix_warning": "Für jeden Laufzeit-Build wird ein separates Präfix erstellt. Vorhandene lokale Spielstände bleiben im alten Präfix. Sie werden nicht automatisch kopiert oder übertragen.","auth.browser": "Im Browser fortfahren","auth.browser_error": "Die Anmeldung konnte nicht im Browser geöffnet werden. Google Chrome muss installiert sein. Versuche es erneut oder wähle eine andere Methode.","auth.cancel_passkey": "Passkey Abfrage abbrechen",diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 0db19bd..58536ee 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Game runtime",+ "runtime.use_default": "Use default runtime",+ "runtime.unavailable": "{{name}} (unavailable)",+ "runtime.separate_prefix": "Use a separate prefix for this runtime build",+ "runtime.prefix_warning": "This creates a separate prefix for each runtime build. Existing local saves stay in the old prefix. Saves are not copied or transferred automatically.","library.stop_update_check": "Stop checking updates","notifications.title": "Notifications","notifications.unread_one": "Notifications, {{count}} unread",diff --git a/assets/locales/es.json b/assets/locales/es.jsonindex c6f6011..0c7837e 100644--- a/assets/locales/es.json+++ b/assets/locales/es.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Entorno del juego",+ "runtime.use_default": "Usar el entorno predeterminado",+ "runtime.unavailable": "{{name}} (no disponible)",+ "runtime.separate_prefix": "Usar un prefijo independiente para esta compilación",+ "runtime.prefix_warning": "Se crea un prefijo independiente para cada compilación del entorno. Las partidas locales existentes permanecen en el prefijo anterior. No se copian ni transfieren automáticamente.","auth.browser": "Continuar en el navegador","auth.browser_error": "No se ha podido abrir el inicio de sesión en el navegador. Google Chrome debe estar instalado. Inténtalo de nuevo o elige otro método.","auth.cancel_passkey": "Cancelar solicitud de llave de acceso",diff --git a/assets/locales/fr.json b/assets/locales/fr.jsonindex 69576e2..82af1f5 100644--- a/assets/locales/fr.json+++ b/assets/locales/fr.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Environnement du jeu",+ "runtime.use_default": "Utiliser l’environnement par défaut",+ "runtime.unavailable": "{{name}} (indisponible)",+ "runtime.separate_prefix": "Utiliser un préfixe séparé pour cette version",+ "runtime.prefix_warning": "Un préfixe séparé est créé pour chaque version de l’environnement. Les sauvegardes locales restent dans l’ancien préfixe. Elles ne sont pas copiées ni transférées automatiquement.","auth.browser": "Continuer dans le navigateur","auth.browser_error": "Impossible d'ouvrir la connexion dans le navigateur. Google Chrome doit être installé. Réessayez ou choisissez une autre méthode.","auth.passkey_label": "Aide pour la clé d'accès de Xodus Nexus",diff --git a/assets/locales/it.json b/assets/locales/it.jsonindex 9fe61f1..3346786 100644--- a/assets/locales/it.json+++ b/assets/locales/it.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Ambiente del gioco",+ "runtime.use_default": "Usa l’ambiente predefinito",+ "runtime.unavailable": "{{name}} (non disponibile)",+ "runtime.separate_prefix": "Usa un prefisso separato per questa versione",+ "runtime.prefix_warning": "Viene creato un prefisso separato per ogni versione dell’ambiente. I salvataggi locali esistenti restano nel vecchio prefisso. Non vengono copiati o trasferiti automaticamente.","auth.browser": "Continua nel browser","auth.browser_error": "Impossibile aprire il browser per accedere. Google Chrome deve essere installato. Prova di nuovo o scegli un altro metodo.","auth.cancel_passkey": "Annulla la richiesta di passkey",diff --git a/assets/locales/pl-PL.json b/assets/locales/pl-PL.jsonindex 76aa858..a9e3262 100644--- a/assets/locales/pl-PL.json+++ b/assets/locales/pl-PL.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Środowisko gry",+ "runtime.use_default": "Użyj domyślnego środowiska",+ "runtime.unavailable": "{{name}} (niedostępne)",+ "runtime.separate_prefix": "Użyj osobnego prefiksu dla tej kompilacji",+ "runtime.prefix_warning": "Dla każdej kompilacji środowiska tworzony jest osobny prefiks. Istniejące lokalne zapisy pozostają w starym prefiksie. Nie są automatycznie kopiowane ani przenoszone.","common.view_all": "Pokaż wszystkie ({{count}})","downloads.active_summary": "Kolejka instalacji, instalacje w toku: {{count}}, {{state}}, {{game}}","downloads.current": "{{state}} ({{current}}/{{total}})",diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.jsonindex a0a0c05..b3eb1dc 100644--- a/assets/locales/pt-BR.json+++ b/assets/locales/pt-BR.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "Ambiente do jogo",+ "runtime.use_default": "Usar o ambiente padrão",+ "runtime.unavailable": "{{name}} (indisponível)",+ "runtime.separate_prefix": "Usar um prefixo separado para esta compilação",+ "runtime.prefix_warning": "Um prefixo separado é criado para cada compilação do ambiente. Os salvamentos locais existentes permanecem no prefixo antigo. Eles não são copiados ou transferidos automaticamente.","auth.browser": "Continuar no navegador","auth.browser_error": "Não foi possível abrir o login no navegador. O Google Chrome precisa estar instalado. Tente novamente ou escolha outro método.","auth.cancel_passkey": "Cancelar solicitação de chave de acesso",diff --git a/assets/locales/zh-CN.json b/assets/locales/zh-CN.jsonindex f80e2e8..ed391d2 100644--- a/assets/locales/zh-CN.json+++ b/assets/locales/zh-CN.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "游戏运行环境",+ "runtime.use_default": "使用默认运行环境",+ "runtime.unavailable": "{{name}}(不可用)",+ "runtime.separate_prefix": "为此运行环境版本使用独立前缀",+ "runtime.prefix_warning": "每个运行环境版本都会创建独立前缀。现有本地存档保留在旧前缀中,不会自动复制或转移。","auth.browser": "在浏览器中继续","auth.browser_error": "未能打开浏览器登录页面。必须安装Google Chrome。请重试或选择其他方式。","auth.cancel_passkey": "取消通行密钥请求",diff --git a/assets/locales/zh-Hant.json b/assets/locales/zh-Hant.jsonindex 97fa8a2..26e0beb 100644--- a/assets/locales/zh-Hant.json+++ b/assets/locales/zh-Hant.json@@ -1,4 +1,9 @@{+ "runtime.game_runtime": "遊戲執行環境",+ "runtime.use_default": "使用預設執行環境",+ "runtime.unavailable": "{{name}}(無法使用)",+ "runtime.separate_prefix": "為此執行環境版本使用獨立前綴",+ "runtime.prefix_warning": "每個執行環境版本都會建立獨立前綴。現有本機存檔保留在舊前綴中,不會自動複製或轉移。","auth.browser": "在瀏覽器中繼續","auth.browser_error": "無法開啟瀏覽器登入。必須已安裝 Google Chrome。請重試或選擇其他方式。","auth.cancel_passkey": "取消金鑰(Passkey)請求",diff --git a/scripts/RUNTIME_FAMILIES.md b/scripts/RUNTIME_FAMILIES.mdnew file mode 100644index 0000000..271ee80--- /dev/null+++ b/scripts/RUNTIME_FAMILIES.md@@ -0,0 +1,48 @@+# Managed runtime families++Per-game runtime selection accepts `default`, `nexus`, or `nexus-cachyos`.+The default keeps the global runtime and existing prefix locations. The game+settings selector lists other families only after installed payload verification.+An absent or invalid selected family fails without falling back to the default.+The selector does not download or install variants.++## Installed receipt++A family uses `variants/<family>/current.json` beneath the configured runtime+root. Its schema is `1`, with `family`, `sourceRepository`, `sourceCommit`+(40 hexadecimal characters), `buildId` (64 hexadecimal characters), and+`manifestSha256` (64 hexadecimal characters). Repositories are fixed to+`domsvoboda/nexus-runtime` and `domsvoboda/nexus-runtime-cachyos`, respectively.++The receipt identifies `variants/<family>/releases/<buildId>/nexus-family.json`.+This schema-1 manifest repeats the identity fields and binds `arch: "x64"`,+`prefixSchema: 1`, and `sourceLockSha256`. `files` maps every regular payload+file to its SHA-256. Optional `symlinks` maps links to exact relative targets.+The combined inventory must cover every non-directory entry except the manifest+itself. Links must resolve inside the release; executable entry points cannot+be symlinks. 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+match the family manifest. Required launch components include Proton, Wine,+its original loader, wineserver, the runtime compatibility helpers, both Windows+ABIs of XGameRuntime, WinHTTP and nghttp2, and the default prefix template.+A receipt is an installer contract, not a substitute for native candidate gates.++## Prefix and session rules++Selecting a managed family requires an explicit separate-prefix choice. Its+prefix lives under `runtime-prefixes/<family>/<buildId>/<gameId>/`, separately+from default `compatdata/<gameId>` and `prefixes/<gameId>`. Existing local saves+stay in their old prefix. No copying, transfer or prefix initialization occurs+when saving the selection. Unknown or mismatched prefix bindings fail closed.++Play and VC++ preparation capture one verified runtime and prefix before use.+Stop retains the generated runner and wineserver for that session. Later+selection or pointer changes cannot redirect it. Removal or cleanup must retain+runtime 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.diff --git a/src/main/index.ts b/src/main/index.tsindex 3e21eb9..9b0e2a3 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,3 +1,6 @@+import {gameRuntimeSelection} from '../shared/runtime-selection.js';+import {resolveRuntimeFamily} from './runtime-families.js';+import {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding.js';import {desktopTrayAvailable} from './launcher-tray-desktop.js';import {LauncherTray} from './launcher-tray.js';import {SteamKeyboard} from './steam-keyboard.js';@@ -1046,7 +1049,11 @@ async function importGame(input?: string): Promise<Game | null> {async function gameLaunchOptions(id: string): Promise<GameLaunchOptions> {const game = store.games.find((entry) => entry.id === id);if (!game) throw new Error('Game not found.');- const wine = selectedWinePath(store.settings.winePath, store.settings.runtimeRoot, runtime.current.winePath);+ let wine: string;+ try {+ wine=(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)})).winePath;+ } catch(error) { const reason=(error as Error).message;return {cloudSaves:false,cloudReason:reason,vcInstall:false,vcReason:reason}; }if (!wine) return { cloudSaves: false, cloudReason: 'Select Xodus Runtime in Settings.', vcInstall: false, vcReason: 'Select Xodus Runtime in Settings.' };const wineAvailable = await fs.access(wine, constants.X_OK).then(() => true, () => false);if (!wineAvailable) return { cloudSaves: false, cloudReason: 'The selected Wine binary is unavailable.', vcInstall: false, vcReason: 'The selected Wine binary is unavailable.' };@@ -1106,7 +1113,10 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<if (inspected.installState !== 'ready') throw new Error(inspected.installMessage ?? 'The installation is not ready for Xodus run.');const locale = supportedGameLocale(game.locale ?? '');const titleId = await gameTitleId(game).catch(() => undefined);- const wine = selectedWinePath(store.settings.winePath, store.settings.runtimeRoot, runtime.current.winePath);+ const runtimeContext = 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 wine = runtimeContext.winePath;+ await bindRuntimePrefix(runtimeContext);if (!wine) throw new Error('Select a Wine / Proton binary in Settings.');try { await fs.access(wine, constants.X_OK); }catch { throw new Error(`The selected Wine runtime is unavailable: ${wine}. Select or reinstall Xodus Runtime in Settings.`); }@@ -1204,8 +1214,8 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<if (game.launchTools?.dualSenseCompatibility) writeLaunchLog('DualSense compatibility mode enabled for this game (054c:0ce6).');if (game.launchTools?.dualShock4Compatibility) writeLaunchLog('DualShock 4 compatibility mode enabled for this game (v1, v2 and wireless adapter).');await prepareSystemWallet();- const legacyPrefixRoot = path.join(dataRoot, 'prefixes', game.id);- const compatibilityDataPath = path.join(dataRoot, 'compatdata', game.id);+ const legacyPrefixRoot = runtimeContext.legacyPrefixRoot;+ const compatibilityDataPath = runtimeContext.compatibilityDataPath;const steamRoot = path.join(app.getPath('home'), '.steam', 'root');launchWrapper = await prepareGameWrapper(wine, game.launchTools, path.join(dataRoot, 'launch-wrappers'), launchEnvironment, game.path);const protonRunner = await prepareProtonRunner(wine, compatibilityDataPath, steamRoot, launchWrapper.command, store.settings.shaderCacheLimitGiB);@@ -1396,7 +1406,10 @@ async function installGameVcRuntime(id: string): Promise<void> {if (!game) throw new Error('Game not found.');const inspected = await inspectGameDirectory(game.path);if (inspected.installState !== 'ready') throw new Error(inspected.installMessage ?? 'The game installation is not ready.');- const wine = selectedWinePath(store.settings.winePath, store.settings.runtimeRoot, runtime.current.winePath);+ const runtimeContext = 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 wine = runtimeContext.winePath;+ await bindRuntimePrefix(runtimeContext);if (!wine) throw new Error('Select Xodus Runtime in Settings first.');await fs.access(wine, constants.X_OK);@@ -1430,7 +1443,7 @@ async function installGameVcRuntime(id: string): Promise<void> {const controller = new AbortController();preparationControllers.set(operationId, controller);try {- const compatibilityDataPath = path.join(dataRoot, 'compatdata', game.id);+ const compatibilityDataPath = runtimeContext.compatibilityDataPath;const protonRunner = await prepareProtonRunner(wine, compatibilityDataPath, path.join(app.getPath('home'), '.steam', 'root'), undefined, store.settings.shaderCacheLimitGiB);if (!protonRunner) throw new Error('VC++ installation requires a full Proton runtime, not a standalone Wine binary.');const prefix = path.join(compatibilityDataPath, 'pfx');@@ -1913,6 +1926,19 @@ function registerIpc(): void {});ipcMain.handle('update-game', async (_event, id: string, patch: Partial<Game>) => {const allowed: Partial<Game> = {};+ if ('runtime' in patch || 'runtimeSeparatePrefix' in patch) {+ const current = store.games.find(game=>game.id===id);+ if (!current) throw Error('Game not found.');+ const selection=gameRuntimeSelection('runtime' in patch ? patch.runtime : current.runtime);+ const separate='runtimeSeparatePrefix' in patch ? patch.runtimeSeparatePrefix : current.runtimeSeparatePrefix;+ if(selection!==(current.runtime??'default')||selection!=='default'&&separate!==current.runtimeSeparatePrefix)ensureIdle();+ if (separate !== undefined && typeof separate !== 'boolean') throw Error('Invalid runtime prefix choice.');+ if (selection !== 'default') {+ if (separate !== true) throw Error('Explicit separate prefix choice is required. Existing local saves remain in the old prefix.');+ if (selection !== current.runtime) await resolveRuntimeFamily(store.settings.runtimeRoot,selection);+ }+ allowed.runtime=selection;allowed.runtimeSeparatePrefix=separate;+ }for (const key of ['title', 'executable', 'launchArgs'] as const) if (typeof patch[key] === 'string') allowed[key] = patch[key];if ('launchTools' in patch) allowed.launchTools = normalizeLaunchTools(patch.launchTools);if (typeof patch.locale === 'string') {diff --git a/src/main/runtime-families.test.ts b/src/main/runtime-families.test.tsnew file mode 100644index 0000000..368fa7a--- /dev/null+++ b/src/main/runtime-families.test.ts@@ -0,0 +1,133 @@+import {afterEach,beforeEach,describe,expect,it} from 'vitest';+import {promises as fs} from 'node:fs';+import path from 'node:path';+import os from 'node:os';+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 {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding';+import {gameRuntimeSelection} from '../shared/runtime-selection';+let root:string,release:string;+const hash=(value:string|Buffer)=>createHash('sha256').update(value).digest('hex');+const family='nexus-cachyos',buildId='b'.repeat(64),sourceCommit='a'.repeat(40),sourceRepository='domsvoboda/nexus-runtime-cachyos';+async function fixture() {+ const files:Record<string,string>={};+ const payload=['proton','files/bin/wine','files/bin/wineserver','files/bin/wine.nexus-original',+ ...['PlayFabGameSave.dll','gaming-services-version.exe','package-registration.exe'].map(name=>'files/share/xodus-nexus/compat/'+name),+ ...['x86_64','i386'].flatMap(cpu=>['xgameruntime.dll','winhttp.dll','libnghttp2.dll'].map(name=>`files/lib/wine/${cpu}-windows/${name}`))];+ for(const name of payload){const target=path.join(release,name);await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,'synthetic inert fixture',{mode:0o755});files[name]=hash('synthetic inert fixture');}+ await fs.mkdir(path.join(release,'files/share/default_pfx'),{recursive:true});+ const metadata=JSON.stringify({schema:1,sourceLockSha256:'c'.repeat(64),sourceGraph:{proton:sourceCommit}});+ await fs.writeFile(path.join(release,'XODUS_NEXUS_PATCH.json'),metadata);files['XODUS_NEXUS_PATCH.json']=hash(metadata);+ const manifest=JSON.stringify({schema:1,family,buildId,sourceRepository,sourceCommit,arch:'x64',prefixSchema:1,sourceLockSha256:'c'.repeat(64),files});+ await fs.writeFile(path.join(release,'nexus-family.json'),manifest);+ await fs.writeFile(path.join(root,'variants',family,'current.json'),JSON.stringify({schema:1,family,buildId,sourceRepository,sourceCommit,manifestSha256:hash(manifest)}));+}+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),'runtime-family-test-'));release=path.join(root,'variants',family,'releases',buildId);await fs.mkdir(release,{recursive:true});});+afterEach(async()=>{await fs.rm(root,{recursive:true,force:true});});+it('accepts only known IDs, defaults only an absent preference, rejects hostile persisted values',()=>{+ expect(gameRuntimeSelection(undefined)).toBe('default');+ for(const value of ['../nexus','/bin/wine','cachyos',null,{},''])expect(()=>gameRuntimeSelection(value)).toThrow();+});+it('only lists a complete verified managed installation',async()=>{+ expect(await installedRuntimeFamilies(root,'x64')).toEqual([]);await fixture();+ expect(await installedRuntimeFamilies(root,'x64')).toEqual([expect.objectContaining({id:family,buildId})]);+ await fs.writeFile(path.join(release,'files/bin/wine'),'changed');+ expect(await installedRuntimeFamilies(root,'x64')).toEqual([]);+ await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow('default was not used');+});+it('rejects an unlisted payload, changed metadata and incompatible architecture',async()=>{+ await fixture();await fs.writeFile(path.join(release,'unlisted'),'extra');+ await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+ await fs.unlink(path.join(release,'unlisted'));await expect(resolveRuntimeFamily(root,family,'arm64')).rejects.toThrow();+ await fs.appendFile(path.join(release,'XODUS_NEXUS_PATCH.json'),' ');await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+});+it('rejects executable symlink redirection even to matching bytes',async()=>{+ await fixture();const loader=path.join(release,'files/bin/wine');await fs.unlink(loader);await fs.symlink('wineserver',loader);+ await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();+});+it('captures immutable independent sessions and preserves the default prefix path',async()=>{+ await fixture();const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64'};+ const legacy=await resolveGameRuntime({...options,selection:undefined,separatePrefix:false});+ const variant=await resolveGameRuntime({...options,selection:family,separatePrefix:true});+ expect(legacy.compatibilityDataPath).toBe(path.join(root,'compatdata','test'));+ expect(variant.compatibilityDataPath).toContain(path.join('runtime-prefixes',family,buildId));+ expect(Object.isFrozen(variant)).toBe(true);expect(Object.isFrozen(variant.managed)).toBe(true);+ await fs.unlink(path.join(root,'variants',family,'current.json'));+ expect(variant.winePath).toBe(path.join(release,'files/bin/wine'));+ await expect(resolveGameRuntime({...options,selection:family,separatePrefix:true})).rejects.toThrow();+});+it('requires explicit separate prefix consent without mutating the legacy prefix or copying saves',async()=>{+ await fixture();await fs.mkdir(path.join(root,'compatdata','test'),{recursive:true});await fs.writeFile(path.join(root,'compatdata','test','save'),'original');+ const options={runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,defaultWine:'/default/wine',arch:'x64'};+ await expect(resolveGameRuntime({...options,separatePrefix:false})).rejects.toThrow('local saves');+ const context=await resolveGameRuntime({...options,separatePrefix:true});await bindRuntimePrefix(context);+ expect(await fs.readdir(context.compatibilityDataPath)).toEqual(['.nexus-runtime-family.json']);+ expect(await fs.readFile(path.join(root,'compatdata','test','save'),'utf8')).toBe('original');+ await bindRuntimePrefix(context);+ await fs.writeFile(path.join(context.compatibilityDataPath,'.nexus-runtime-family.json'),'{}');+ await expect(bindRuntimePrefix(context)).rejects.toThrow('mismatch');+});+it('does not adopt an unbound experimental prefix or another family in the default path',async()=>{+ await fixture();const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,separatePrefix:true,defaultWine:'/default/wine',arch:'x64'});+ await fs.mkdir(context.compatibilityDataPath,{recursive:true});await fs.writeFile(path.join(context.compatibilityDataPath,'save'),'keep');+ await expect(bindRuntimePrefix(context)).rejects.toThrow('no runtime binding');+ const legacy=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:'default',separatePrefix:false,defaultWine:'/default/wine'});+ await fs.mkdir(legacy.compatibilityDataPath,{recursive:true});await fs.writeFile(path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json'),JSON.stringify({family}));+ await expect(bindRuntimePrefix(legacy)).rejects.toThrow('another runtime');+});+it('rejects prefix symlinks and never writes into their target',async()=>{+ await fixture();const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,separatePrefix:true,defaultWine:'/default/wine',arch:'x64'});+ const other=path.join(root,'untouched');await fs.mkdir(other);await fs.mkdir(path.dirname(context.compatibilityDataPath),{recursive:true});await fs.symlink(other,context.compatibilityDataPath);+ await expect(bindRuntimePrefix(context)).rejects.toThrow('symlinks');expect(await fs.readdir(other)).toEqual([]);+});+it('persists valid game selections and rejects malformed updates without changing existing state',async()=>{+ const {StateStore}=await import('./store');const store=new StateStore(path.join(root,'profile'));+ await store.upsertGame({id:'test',path:'/synthetic/game',title:'Synthetic',installState:'ready',addedAt:'2026-01-01'});+ await store.patchGame('test',{runtime:family,runtimeSeparatePrefix:true});+ const reloaded=new StateStore(path.join(root,'profile'));await reloaded.load();+ expect(reloaded.games[0]).toMatchObject({runtime:family,runtimeSeparatePrefix:true});+ await expect(store.patchGame('test',{runtime:'/bin/wine' as never})).rejects.toThrow('Unknown');+ await expect(store.patchGame('test',{runtimeSeparatePrefix:'yes' as never})).rejects.toThrow('Invalid');+ expect(store.games[0].runtime).toBe(family);+});++it('Stop uses its captured runtime and prefix after another launch is selected',async()=>{+ await fixture();+ const server=path.join(release,'files/bin/wineserver');+ const stopLog=path.join(root,'captured-stop.log');+ await fs.writeFile(server,`#!/bin/sh\nprintf '%s\\n' "$WINEPREFIX" >> '${stopLog}'\n`,{mode:0o755});+ const pointerFile=path.join(root,'variants',family,'current.json');+ const manifestFile=path.join(release,'nexus-family.json');+ const manifest=JSON.parse(await fs.readFile(manifestFile,'utf8'));manifest.files['files/bin/wineserver']=hash(await fs.readFile(server));+ const bytes=JSON.stringify(manifest);await fs.writeFile(manifestFile,bytes);+ const pointer=JSON.parse(await fs.readFile(pointerFile,'utf8'));pointer.manifestSha256=hash(bytes);await fs.writeFile(pointerFile,JSON.stringify(pointer));+ const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64'};+ const captured=await resolveGameRuntime({...options,selection:family,separatePrefix:true});await bindRuntimePrefix(captured);+ const system32=path.join(captured.compatibilityDataPath,'pfx/drive_c/windows/system32');await fs.mkdir(system32,{recursive:true});+ for(const name of ['libvkd3d-utils-1.dll','dxgi.dll','d3d12.dll'])await fs.writeFile(path.join(system32,name),'synthetic');+ const runner=await prepareProtonRunner(captured.winePath,captured.compatibilityDataPath,path.join(root,'synthetic-steam'));+ expect(runner).toBeDefined();+ await resolveGameRuntime({...options,selection:'default',separatePrefix:false});+ await fs.unlink(pointerFile); // Current selection/pointer cannot change a running Stop command.+ await promisify(execFileCallback)(runner!.stopPrefix.command,runner!.stopPrefix.args);+ expect((await fs.readFile(stopLog,'utf8')).trim()).toBe(path.join(captured.compatibilityDataPath,'pfx'));+ expect(await fs.readdir(path.join(root,'compatdata')).catch(()=>[])).toEqual([]);+});++it.each([{sourceRepository:'xodus-gaming/Proton'},{sourceCommit:'bad'},{family:'nexus'},{buildId:'../escape'},{manifestSha256:'0'.repeat(64)}])('rejects a mismatched or hostile installed receipt: %j',async patch=>{+ await fixture();const file=path.join(root,'variants',family,'current.json');const pointer=JSON.parse(await fs.readFile(file,'utf8'));+ await fs.writeFile(file,JSON.stringify({...pointer,...patch}));await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow('verification');+});++it('verifies inventoried internal directory symlinks while rejecting external targets',async()=>{+ await fixture();await fs.symlink('share',path.join(release,'files/shared-link'));+ 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'));manifest.symlinks={'files/shared-link':'share'};+ 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));+ expect((await resolveRuntimeFamily(root,family,'x64')).id).toBe(family);+ await 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();+});diff --git a/src/main/runtime-families.ts b/src/main/runtime-families.tsnew file mode 100644index 0000000..c547fef--- /dev/null+++ b/src/main/runtime-families.ts@@ -0,0 +1,82 @@+import {constants,createReadStream,promises as fs} from 'node:fs';+import {createHash} from 'node:crypto';+import path from 'node:path';+import {gameRuntimeSelection,runtimeFamilies,runtimeFamilyLabels,type RuntimeFamily,type InstalledRuntimeFamily} from '../shared/runtime-selection.js';+const repositories:Record<RuntimeFamily,string>={nexus:'domsvoboda/nexus-runtime','nexus-cachyos':'domsvoboda/nexus-runtime-cachyos'};+const digest=(bytes:Buffer)=>createHash('sha256').update(bytes).digest('hex');+async function fileDigest(file:string) {+ const hash=createHash('sha256');for await(const bytes of createReadStream(file))hash.update(bytes);return hash.digest('hex');+}+const hash=(value:unknown)=>typeof value==='string'&&/^[a-f0-9]{64}$/.test(value);+const commit=(value:unknown)=>typeof value==='string'&&/^[a-f0-9]{40}$/.test(value);+const within=(root:string,file:string)=>{const relative=path.relative(root,file);return Boolean(relative)&&!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative);};+export interface ResolvedRuntimeFamily extends InstalledRuntimeFamily {+ readonly winePath:string;readonly root:string;readonly arch:'x64'|'arm64';readonly prefixSchema:1;readonly manifestSha256:string;+}+/** 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>> {+ 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.');+ try {+ const managedRoot=await fs.realpath(runtimeRoot);+ const directory=path.join(runtimeRoot,'variants',id);+ if(!within(managedRoot,await fs.realpath(directory)))throw Error('Family directory leaves managed root');+ const pointer=JSON.parse(await fs.readFile(path.join(directory,'current.json'),'utf8'));+ if(pointer.schema!==1||pointer.family!==id||pointer.sourceRepository!==repositories[id]||!commit(pointer.sourceCommit)||!hash(pointer.manifestSha256)||!hash(pointer.buildId))throw Error('Invalid managed runtime receipt');+ const requestedRoot=path.join(directory,'releases',pointer.buildId);+ if(!(await fs.lstat(requestedRoot)).isDirectory())throw Error('Runtime root must be a real directory');+ const root=await fs.realpath(requestedRoot);+ const releases=await fs.realpath(path.join(directory,'releases'));+ if(!within(managedRoot,releases)||!within(releases,root))throw Error('Runtime build leaves its managed directory');+ if(!(await fs.lstat(path.join(root,'nexus-family.json'))).isFile())throw Error('Runtime manifest must be a regular file');+ const bytes=await fs.readFile(path.join(root,'nexus-family.json'));+ if(digest(bytes)!==pointer.manifestSha256)throw Error('Runtime manifest checksum mismatch');+ const manifest=JSON.parse(bytes.toString('utf8'));+ if(manifest.schema!==1||manifest.family!==id||manifest.sourceRepository!==repositories[id]||manifest.sourceCommit!==pointer.sourceCommit||manifest.buildId!==pointer.buildId||manifest.arch!==arch||manifest.prefixSchema!==1||!manifest.files||Array.isArray(manifest.files)||typeof manifest.files!=='object')throw Error('Runtime manifest identity mismatch');+ const loader=arch==='arm64'?'files/bin-arm64/wine':'files/bin/wine';+ const server=arch==='arm64'?'files/bin-arm64/wineserver':'files/bin/wineserver';+ // Installer manifests must cover the Proton entry point and complete payload.+ const critical=['proton',loader,server,loader+'.nexus-original','XODUS_NEXUS_PATCH.json',+ ...['PlayFabGameSave.dll','gaming-services-version.exe','package-registration.exe'].map(name=>'files/share/xodus-nexus/compat/'+name),+ ...['x86_64','i386'].flatMap(cpu=>['xgameruntime.dll','winhttp.dll','libnghttp2.dll'].map(name=>`files/lib/wine/${cpu}-windows/${name}`))];+ if(arch==='arm64')throw Error('Experimental managed variants require a separately reviewed ARM64 payload contract');+ for(const required of critical)if(!hash(manifest.files[required]))throw Error('Runtime launch file missing');+ for(const [name,expected] of Object.entries(manifest.files)) {+ if(!hash(expected)||!name||name.includes('\\')||name.split('/').some(part=>!part||part==='.'||part==='..')||path.isAbsolute(name))throw Error('Unsafe runtime manifest path');+ if(!(await fs.lstat(path.join(root,name))).isFile())throw Error('Runtime file inventory must name regular files');+ const target=await fs.realpath(path.join(root,name));+ if(!within(root,target)||(await fs.stat(target)).isFile()!==true||await fileDigest(target)!==expected)throw Error('Runtime payload checksum mismatch');+ }+ const symlinks=manifest.symlinks??{};+ 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');+ 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');+ }+ const inventory:string[]=[];+ const walk=async(directory:string)=>{for(const item of await fs.readdir(directory,{withFileTypes:true})){+ const file=path.join(directory,item.name),name=path.relative(root,file).split(path.sep).join('/');+ if(item.isDirectory())await walk(file);else if(name!=='nexus-family.json')inventory.push(name);+ }};+ await walk(root);+ if(inventory.sort().join('\n')!==[...Object.keys(manifest.files),...Object.keys(symlinks)].sort().join('\n'))throw Error('Runtime payload inventory is incomplete');+ const metadata=JSON.parse(await fs.readFile(path.join(root,'XODUS_NEXUS_PATCH.json'),'utf8'));+ if(metadata.schema!==1||!hash(metadata.sourceLockSha256)||!metadata.sourceGraph||typeof metadata.sourceGraph!=='object'||metadata.sourceGraph.proton!==pointer.sourceCommit||metadata.sourceLockSha256!==manifest.sourceLockSha256)throw Error('Runtime source graph is not bound');+ if(!(await fs.stat(path.join(root,'files/share/default_pfx'))).isDirectory())throw Error('Runtime default prefix missing');+ const winePath=path.join(root,loader);+ for(const file of [winePath,path.join(root,'proton'),path.join(root,server)]) {+ if(!(await fs.lstat(file)).isFile())throw Error('Runtime launcher cannot be a symlink');+ await fs.access(file,constants.X_OK);+ }+ 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});}+}+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;}+ }));+ return results.filter((value):value is InstalledRuntimeFamily=>Boolean(value));+}diff --git a/src/main/runtime-prefix-binding.ts b/src/main/runtime-prefix-binding.tsnew file mode 100644index 0000000..8d0d406--- /dev/null+++ b/src/main/runtime-prefix-binding.ts@@ -0,0 +1,56 @@+import {promises as fs} from 'node:fs';+import path from 'node:path';+import {gameRuntimeSelection,type GameRuntimeSelection} from '../shared/runtime-selection.js';+import {resolveRuntimeFamily,type ResolvedRuntimeFamily} from './runtime-families.js';+export interface GameRuntimeContext {+ readonly selection:GameRuntimeSelection;readonly family:'default'|'nexus'|'nexus-cachyos';+ readonly winePath:string;readonly compatibilityDataPath:string;readonly legacyPrefixRoot:string;readonly dataRoot:string;+ readonly managed?:Readonly<ResolvedRuntimeFamily>;+}+/** Capture once before prerequisite staging or launch. Later setting/pointer+ * changes cannot redirect this session, its prefix or its captured Stop runner. */+export async function resolveGameRuntime(options:{runtimeRoot:string;dataRoot:string;gameId:string;selection:unknown;separatePrefix:unknown;defaultWine:string|undefined;arch?:string}):Promise<Readonly<GameRuntimeContext>> {+ const selection=gameRuntimeSelection(options.selection);+ if(!/^[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.');+ 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)});+ }+ if(options.separatePrefix!==true)throw Error('Choose a separate runtime prefix before using this family. Existing local saves remain in the old prefix.');+ const managed=await resolveRuntimeFamily(options.runtimeRoot,selection,options.arch);+ const root=path.join(options.dataRoot,'runtime-prefixes',selection,managed.buildId,options.gameId);+ return Object.freeze({selection,family:selection,winePath:managed.winePath,dataRoot:options.dataRoot,managed,+ compatibilityDataPath:path.join(root,'compatdata'),legacyPrefixRoot:path.join(root,'wine')});+}+/** No pfx/wineboot, copying, save migration or default pointer mutation. */+export async function bindRuntimePrefix(context:Readonly<GameRuntimeContext>):Promise<void> {+ const marker=path.join(context.compatibilityDataPath,'.nexus-runtime-family.json');+ if(context.managed) {+ const relative=path.relative(context.dataRoot,context.compatibilityDataPath);+ if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('Unsafe runtime prefix location.');+ let directory=context.dataRoot;+ for(const part of relative.split(path.sep)) {+ directory=path.join(directory,part);+ try{if(!(await fs.lstat(directory)).isDirectory())throw Error('Runtime prefix path cannot contain symlinks.');}+ catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')break;throw error;}+ }+ try{if(!(await fs.lstat(marker)).isFile())throw Error('Runtime prefix binding must be a regular file.');}+ catch(error){if((error as NodeJS.ErrnoException).code!=='ENOENT')throw error;}+ }+ const expected=context.managed?{schema:1,family:context.family,buildId:context.managed.buildId,sourceCommit:context.managed.sourceCommit,manifestSha256:context.managed.manifestSha256,prefixSchema:context.managed.prefixSchema,arch:context.managed.arch}:undefined;+ try {+ const current=JSON.parse(await fs.readFile(marker,'utf8'));+ if(!expected) {if(current.family!=='default')throw Error('The default prefix belongs to another runtime family.');return;}+ if(Object.keys(current).length!==Object.keys(expected).length||Object.entries(expected).some(([key,value])=>current[key]!==value))throw Error('Runtime prefix binding mismatch. Existing prefix was preserved.');+ return;+ }catch(error){if((error as NodeJS.ErrnoException).code!=='ENOENT')throw error;}+ if(!expected)return; // Preserve the existing, unbound legacy default prefix.+ // An unbound nonempty experimental prefix has unknown provenance, never adopt it.+ const entries=await fs.readdir(context.compatibilityDataPath).catch(error=>{if(error.code==='ENOENT')return [];throw error;});+ if(entries.length)throw Error('Experimental prefix has no runtime binding. Existing files were preserved.');+ await fs.mkdir(context.compatibilityDataPath,{recursive:true,mode:0o700});+ await fs.writeFile(marker,JSON.stringify(expected),{flag:'wx',mode:0o600});+}diff --git a/src/main/runtime.ts b/src/main/runtime.tsindex f9c716f..0446f36 100644--- a/src/main/runtime.ts+++ b/src/main/runtime.ts@@ -1,3 +1,4 @@+import {installedRuntimeFamilies} from './runtime-families.js';import {runtimeWineFailure} from './runtime-prerequisites.js';import { constants, createWriteStream, promises as fs } from 'node:fs';import path from 'node:path';@@ -111,6 +112,7 @@ export class RuntimeManager {this.commandOk('sha512sum', ['--version']),]);this.status.prerequisites = { gh, authenticated, tar, sha512sum };+ this.status.variants = await installedRuntimeFamilies(this.status.runtimeRoot, this.hostArch);const pointer = await this.readPointer();if (pointer && await this.validateWine(pointer.winePath)) {Object.assign(this.status, {diff --git a/src/main/store.ts b/src/main/store.tsindex 2a03155..e2f67d5 100644--- a/src/main/store.ts+++ b/src/main/store.ts@@ -1,3 +1,4 @@+import {gameRuntimeSelection} from '../shared/runtime-selection.js';import { createHash } from 'node:crypto';import { promises as fs } from 'node:fs';import os from 'node:os';@@ -108,6 +109,8 @@ export class StateStore {async patchGame(id: string, patch: Partial<Game>): Promise<Game> {const game = this.state.games.find((entry) => entry.id === id);if (!game) throw new Error('Game not found.');+ if ('runtime' in patch) patch.runtime = gameRuntimeSelection(patch.runtime);+ if ('runtimeSeparatePrefix' in patch && typeof patch.runtimeSeparatePrefix !== 'boolean') throw Error('Invalid runtime prefix choice.');Object.assign(game, patch);await this.save();return game;diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 9b66240..6df3d5c 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -1,3 +1,5 @@+import {GameRuntimeFields} from './GameRuntimeFields';+import {gameRuntimeAvailable,type GameRuntimeSelection} from '../shared/runtime-selection';import { CloudSaveWarning } from './CloudSaveWarning';import { CheckField } from './CheckField';import { useDialogFocus } from './use-dialog-focus';@@ -209,7 +211,7 @@ function useGameLaunchOptions(game: Game | undefined, data: AppSnapshot): GameLa.then((value) => { if (!cancelled) setOptions(value); }).catch((error) => { if (!cancelled) setOptions({ cloudSaves: false, cloudReason: errorMessage(error), vcInstall: false, vcReason: errorMessage(error) }); });return () => { cancelled = true; };- }, [game?.id, data.settings.winePath, data.settings.runtimeRoot, data.runtime.winePath, data.backend.binaryPath, data.backend.commit, data.backend.available]);+ }, [game?.id, game?.runtime, game?.runtimeSeparatePrefix, data.runtime.variants?.map(item=>item.id+':'+item.buildId).join(','), data.settings.winePath, data.settings.runtimeRoot, data.runtime.winePath, data.backend.binaryPath, data.backend.commit, data.backend.available]);return options;}@@ -217,7 +219,7 @@ export function HomePage({ data, go, action, openGame, returnFocusKey }: {data: AppSnapshot; go: (page: Page) => void; action: (fn: () => Promise<unknown>, success?: string) => void; openGame?: (id: string, returnKey: string) => void; returnFocusKey?: string;}) {const featured = data.games[0];- const canPlay = Boolean(featured?.installState === 'ready' && data.backend.capabilities.run && (data.settings.winePath || data.runtime.winePath));+ const canPlay = Boolean(featured?.installState === 'ready' && data.backend.capabilities.run && gameRuntimeAvailable(featured?.runtime,featured?.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[]));const launchOptions = useGameLaunchOptions(featured, data);const spotlightArt = featured?.heroUrl ?? featured?.coverUrl;const home = useRef<HTMLElement>(null);@@ -651,6 +653,8 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,const [dialogGame, setDialogGame] = useState<{ id: string; kind: 'settings' | 'remove' }>();const [editTitle, setEditTitle] = useState('');const [editLocale, setEditLocale] = useState('');+ const [editRuntime,setEditRuntime]=useState<GameRuntimeSelection>('default');+ const [editSeparatePrefix,setEditSeparatePrefix]=useState(false);const [editTools, setEditTools] = useState<GameLaunchTools>({ ...defaultLaunchTools });const [localeOptions, setLocaleOptions] = useState<string[]>([]);const localeRequest = useRef(0);@@ -728,6 +732,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,setMenu(undefined);setEditTitle(game.title);setEditLocale(game.locale ?? '');+ setEditRuntime(game.runtime ?? 'default');setEditSeparatePrefix(game.runtimeSeparatePrefix===true);setEditTools({ ...defaultLaunchTools, ...game.launchTools });setLocaleOptions([]);const request = ++localeRequest.current;@@ -742,7 +747,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,if (!dialogGame) return;setDialogBusy(true);try {- await window.launcher.updateGame(dialogGame.id, { title: editTitle.trim(), locale: editLocale, launchTools: normalizeLaunchTools(editTools) });+ await window.launcher.updateGame(dialogGame.id, { title: editTitle.trim(), locale: editLocale, launchTools: normalizeLaunchTools(editTools), runtime:editRuntime, runtimeSeparatePrefix:editSeparatePrefix });toast({ kind: 'success', message: ui("ui.game_settings_saved_7f466a5") });setDialogGame(undefined);} catch (error) { toast({ kind: 'error', message: errorMessage(error) }); }@@ -829,7 +834,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,contentDisabled: !game.storeId || data.auth.stored !== true || !data.backend.capabilities.library,});const selectedPanel = catalogProduct&&detailVisible?<CatalogGameDetails key={catalogProduct.productId+catalogScope} product={catalogProduct} data={data} back={closeDetails} toast={toast}/>:!catalogSelection&&selected&&detailVisible ? <GameDetails key={`${selected.id}:${data.auth.username}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} game={selected} data={data} back={closeDetails} backLabel={returnHomeKey.current ? ui('game.back_to_home') : undefined} play={<>- <button className="primary" data-gamepad-play disabled={gameBusy || selected.installState !== 'ready' || !data.backend.capabilities.run || !(data.settings.winePath || data.runtime.winePath)} onClick={() => play()}>{gameBusy ? <LoaderCircle className="spin" /> : <Play fill="currentColor" />}{gameBusy ? ui("ui.working_5474eef") : ui("ui.play_436e610")}</button>+ <button className="primary" data-gamepad-play disabled={gameBusy || selected.installState !== 'ready' || !data.backend.capabilities.run || !gameRuntimeAvailable(selected.runtime,selected.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[])} onClick={() => play()}>{gameBusy ? <LoaderCircle className="spin" /> : <Play fill="currentColor" />}{gameBusy ? ui("ui.working_5474eef") : ui("ui.play_436e610")}</button>{gameBusy && !(selectedOperation?.kind === 'prerequisite' && selectedOperation.status === 'running') ? <button className="secondary danger" onClick={stopGame}><X />{ui("ui.stop_cae7d57")}</button> : null}</>} manage={<GameMenuActions {...managementProps(selected)} />} technical={<dl><div><dt>{ui("ui.store_id_4a3eac6")}</dt><dd>{selected.storeId ?? ui("ui.not_found_e3ebaa1")}</dd></div><div><dt>{ui("ui.executable_72cd8a6")}</dt><dd>{selected.executable ?? ui("ui.not_found_e3ebaa1")}</dd></div><div><dt>{ui("ui.location_15b6197")}</dt><dd>{selected.path}</dd></div></dl>} notices={<>{selected.installMessage ? <div className="alert amber"><CircleAlert /><span>{uiText(selected.installMessage)}</span></div> : null}@@ -852,6 +857,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,<h2>{ui("ui.game_settings_fece860")}</h2><label>{ui("ui.display_name_2b7f6a8")}<input data-gamepad-initial required value={editTitle} onChange={(event) => setEditTitle(event.target.value)} /></label><GameLanguage value={editLocale} locales={localeOptions} onChange={setEditLocale} />+ <GameRuntimeFields value={editRuntime} separate={editSeparatePrefix} installed={data.runtime.variants??[]} change={value=>{setEditRuntime(value);setEditSeparatePrefix(false);}} changeSeparate={setEditSeparatePrefix}/><GameLaunchToolFields value={editTools} change={setEditTools} /><div className="dialog-actions"><button type="button" className="secondary" disabled={dialogBusy} data-gamepad-cancel onClick={() => setDialogGame(undefined)}>{ui("ui.cancel_19766ed")}</button><button className="primary" disabled={dialogBusy || !editTitle.trim()}><Check />{ui("ui.save_1509f56")}</button></div></form>}diff --git a/src/renderer/GameRuntimeFields.tsx b/src/renderer/GameRuntimeFields.tsxnew file mode 100644index 0000000..e9d35bb--- /dev/null+++ b/src/renderer/GameRuntimeFields.tsx@@ -0,0 +1,16 @@+import {ui} from './i18n';+import {runtimeFamilyLabels,type GameRuntimeSelection,type InstalledRuntimeFamily} from '../shared/runtime-selection';+export function GameRuntimeFields({value,separate,installed,change,changeSeparate}:{value:GameRuntimeSelection;separate:boolean;installed:InstalledRuntimeFamily[];change:(value:GameRuntimeSelection)=>void;changeSeparate:(value:boolean)=>void}) {+ const missing=value!=='default'&&!installed.some(item=>item.id===value);+ return <>+ <label>{ui('runtime.game_runtime')}<select value={value} onChange={event=>change(event.target.value as GameRuntimeSelection)}>+ <option value="default">{ui('runtime.use_default')}</option>+ {installed.map(item=><option key={item.id} value={item.id}>{item.label}</option>)}+ {missing?<option value={value} disabled>{ui('runtime.unavailable',{name:runtimeFamilyLabels[value as keyof typeof runtimeFamilyLabels]??String(value)})}</option>:null}+ </select></label>+ {value!=='default'?<>+ <label className="check-field"><input type="checkbox" required checked={separate} onChange={event=>changeSeparate(event.target.checked)}/><span>{ui('runtime.separate_prefix')}</span></label>+ <small>{ui('runtime.prefix_warning')}</small>+ </>:null}+ </>;+}diff --git a/src/renderer/game-runtime-fields.test.tsx b/src/renderer/game-runtime-fields.test.tsxnew file mode 100644index 0000000..9c15a07--- /dev/null+++ b/src/renderer/game-runtime-fields.test.tsx@@ -0,0 +1,25 @@+import {gameRuntimeAvailable} from '../shared/runtime-selection';+import {expect,it} from 'vitest';+import {renderToStaticMarkup} from 'react-dom/server';+import {GameRuntimeFields} from './GameRuntimeFields';+const change=()=>{};+it('offers only default when no verified variants are installed, never an unbuilt CachyOS option',()=>{+ const html=renderToStaticMarkup(<GameRuntimeFields value="default" separate={false} installed={[]} change={change} changeSeparate={change}/>);+ expect(html.match(/<option/g)).toHaveLength(1);expect(html).not.toContain('CachyOS');expect(html).toContain('Use default runtime');+});+it('lists verified families with explicit separate-prefix acknowledgment and save warning',()=>{+ const html=renderToStaticMarkup(<GameRuntimeFields value="nexus-cachyos" separate={false} installed={[{id:'nexus-cachyos',label:'Nexus Runtime (CachyOS, experimental)',buildId:'a'.repeat(64),sourceCommit:'b'.repeat(40)}]} change={change} changeSeparate={change}/>);+ expect(html).toContain('experimental');expect(html).toMatch(/type="checkbox" required/);expect(html).toContain('Existing local saves stay in the old prefix');expect(html).not.toContain('checked=""');+});+it('shows a missing persisted selection as disabled rather than falling back',()=>{+ const html=renderToStaticMarkup(<GameRuntimeFields value="nexus-cachyos" separate installed={[]} change={change} changeSeparate={change}/>);+ expect(html).toMatch(/value="nexus-cachyos" disabled="" selected=""/);expect(html).toContain('(unavailable)');+});++it('allows a verified selected family without a default and never borrows default availability for a missing family',()=>{+ const installed=[{id:'nexus-cachyos' as const,label:'Experimental',buildId:'a'.repeat(64),sourceCommit:'b'.repeat(40)}];+ expect(gameRuntimeAvailable('nexus-cachyos',true,false,installed)).toBe(true);+ expect(gameRuntimeAvailable('nexus-cachyos',true,true,[])).toBe(false);+ expect(gameRuntimeAvailable('nexus-cachyos',false,true,installed)).toBe(false);+ expect(gameRuntimeAvailable(undefined,false,true,[])).toBe(true);+});diff --git a/src/shared/runtime-selection.ts b/src/shared/runtime-selection.tsnew file mode 100644index 0000000..41483de--- /dev/null+++ b/src/shared/runtime-selection.ts@@ -0,0 +1,20 @@+/** Fixed, managed families only. Legacy Game.winePath is never consulted. */+export const runtimeFamilies = ['nexus', 'nexus-cachyos'] as const;+export type RuntimeFamily = typeof runtimeFamilies[number];+export type GameRuntimeSelection = 'default' | RuntimeFamily;+export function gameRuntimeSelection(value: unknown): GameRuntimeSelection {+ if (value === undefined || value === 'default') return 'default';+ if (runtimeFamilies.includes(value as RuntimeFamily)) return value as RuntimeFamily;+ throw Error('Unknown managed runtime selection. Choose the default or an installed Nexus runtime.');+}+export const runtimeFamilyLabels: Record<RuntimeFamily, string> = {+ nexus: 'Nexus Runtime', 'nexus-cachyos': 'Nexus Runtime (CachyOS, experimental)',+};+export interface InstalledRuntimeFamily {+ id: RuntimeFamily; label: string; buildId: string; sourceCommit: string;+}+/** A chosen managed family never borrows the global runtime's availability. */+export function gameRuntimeAvailable(selection:unknown,separatePrefix:unknown,defaultAvailable:boolean,installed:readonly InstalledRuntimeFamily[]):boolean {+ if(selection===undefined||selection==='default')return defaultAvailable;+ return separatePrefix===true&&runtimeFamilies.includes(selection as RuntimeFamily)&&installed.some(item=>item.id===selection);+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex b9f3de4..a007838 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,3 +1,4 @@+import type {GameRuntimeSelection,InstalledRuntimeFamily} from './runtime-selection.js';export type Page = 'home' | 'store' | 'library' | 'downloads' | 'settings' | 'social';export interface BackendCapabilities {@@ -71,6 +72,7 @@ export interface BackendStatus {}export interface RuntimeStatus {+ variants?: InstalledRuntimeFamily[];installed: boolean;checking: boolean;updating: boolean;@@ -113,7 +115,9 @@ export interface Game {installedVersion?: string;packageName?: string;executable?: string;- winePath?: string; // Legacy saved field; ignored for launch. The runtime is global.+ winePath?: string; // Legacy saved field; ignored for launch.+ runtime?: GameRuntimeSelection;+ runtimeSeparatePrefix?: boolean;launchArgs?: string;launchTools?: GameLaunchTools;locale?: string;@@ -599,7 +603,7 @@ export interface LauncherApi {removeDownload(id: string): Promise<void>;clearFinishedDownloads(): Promise<void>;importGame(path?: string): Promise<Game | null>;- updateGame(id: string, patch: Partial<Pick<Game, 'title' | 'executable' | 'launchArgs' | 'locale' | 'launchTools'>>): Promise<Game>;+ updateGame(id: string, patch: Partial<Pick<Game, 'title' | 'executable' | 'launchArgs' | 'locale' | 'launchTools' | 'runtime' | 'runtimeSeparatePrefix'>>): Promise<Game>;getGameLocales(id: string): Promise<string[]>;removeGame(id: string, mode: 'library' | 'delete-files'): Promise<void>;getGameLaunchOptions(id: string): Promise<GameLaunchOptions>;