Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
Require explicit per-game approval before switching runtime builds
Dom Svobodad176b962e93a
diff --git a/assets/locales/de.json b/assets/locales/de.jsonindex db078db..baec364 100644--- a/assets/locales/de.json+++ b/assets/locales/de.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "Der installierte Laufzeit-Build wurde geändert oder noch nicht genehmigt. Prüfe ihn und wähle ausdrücklich ein neues separates Präfix. Lokale Spielstände bleiben im alten Präfix.","runtime.game_runtime": "Spiel-Laufzeit","runtime.use_default": "Standard-Laufzeit verwenden","runtime.unavailable": "{{name}} (nicht verfügbar)",diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 58536ee..76da8d6 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "The installed runtime build changed or has not been approved. Review it and explicitly choose a new separate prefix. Existing local saves stay in the old prefix.","runtime.game_runtime": "Game runtime","runtime.use_default": "Use default runtime","runtime.unavailable": "{{name}} (unavailable)",diff --git a/assets/locales/es.json b/assets/locales/es.jsonindex 0c7837e..d51365e 100644--- a/assets/locales/es.json+++ b/assets/locales/es.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "La compilación del entorno cambió o no se ha aprobado. Revísala y elige explícitamente un nuevo prefijo independiente. Las partidas locales permanecen en el prefijo anterior.","runtime.game_runtime": "Entorno del juego","runtime.use_default": "Usar el entorno predeterminado","runtime.unavailable": "{{name}} (no disponible)",diff --git a/assets/locales/fr.json b/assets/locales/fr.jsonindex 82af1f5..5106085 100644--- a/assets/locales/fr.json+++ b/assets/locales/fr.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "La version installée a changé ou n’a pas été approuvée. Vérifiez-la et choisissez explicitement un nouveau préfixe séparé. Les sauvegardes locales restent dans l’ancien préfixe.","runtime.game_runtime": "Environnement du jeu","runtime.use_default": "Utiliser l’environnement par défaut","runtime.unavailable": "{{name}} (indisponible)",diff --git a/assets/locales/it.json b/assets/locales/it.jsonindex 3346786..47fccca 100644--- a/assets/locales/it.json+++ b/assets/locales/it.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "La versione installata è cambiata o non è stata approvata. Verificala e scegli esplicitamente un nuovo prefisso separato. I salvataggi locali restano nel vecchio prefisso.","runtime.game_runtime": "Ambiente del gioco","runtime.use_default": "Usa l’ambiente predefinito","runtime.unavailable": "{{name}} (non disponibile)",diff --git a/assets/locales/pl-PL.json b/assets/locales/pl-PL.jsonindex a9e3262..bc6107b 100644--- a/assets/locales/pl-PL.json+++ b/assets/locales/pl-PL.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "Zainstalowana kompilacja zmieniła się lub nie została zatwierdzona. Sprawdź ją i wyraźnie wybierz nowy osobny prefiks. Lokalne zapisy pozostają w starym prefiksie.","runtime.game_runtime": "Środowisko gry","runtime.use_default": "Użyj domyślnego środowiska","runtime.unavailable": "{{name}} (niedostępne)",diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.jsonindex b3eb1dc..55a9df8 100644--- a/assets/locales/pt-BR.json+++ b/assets/locales/pt-BR.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "A compilação instalada mudou ou não foi aprovada. Revise-a e escolha explicitamente um novo prefixo separado. Os salvamentos locais permanecem no prefixo antigo.","runtime.game_runtime": "Ambiente do jogo","runtime.use_default": "Usar o ambiente padrão","runtime.unavailable": "{{name}} (indisponível)",diff --git a/assets/locales/zh-CN.json b/assets/locales/zh-CN.jsonindex ed391d2..815a231 100644--- a/assets/locales/zh-CN.json+++ b/assets/locales/zh-CN.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "已安装的运行环境版本已更改或尚未获准。请检查后明确选择新的独立前缀。现有本地存档保留在旧前缀中。","runtime.game_runtime": "游戏运行环境","runtime.use_default": "使用默认运行环境","runtime.unavailable": "{{name}}(不可用)",diff --git a/assets/locales/zh-Hant.json b/assets/locales/zh-Hant.jsonindex 26e0beb..a7cfb4b 100644--- a/assets/locales/zh-Hant.json+++ b/assets/locales/zh-Hant.json@@ -1,4 +1,5 @@{+ "runtime.build_changed": "已安裝的執行環境版本已變更或尚未獲准。請檢查後明確選擇新的獨立前綴。現有本機存檔保留在舊前綴中。","runtime.game_runtime": "遊戲執行環境","runtime.use_default": "使用預設執行環境","runtime.unavailable": "{{name}}(無法使用)",diff --git a/scripts/RUNTIME_FAMILIES.md b/scripts/RUNTIME_FAMILIES.mdindex 56afcb5..77b3750 100644--- a/scripts/RUNTIME_FAMILIES.md+++ b/scripts/RUNTIME_FAMILIES.md@@ -32,8 +32,23 @@ 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+Selecting a managed family requires an explicit separate-prefix choice and a+server-captured per-game build approval (`buildId`, `manifestSha256`, and+`sourceCommit`). Approval requires a fresh transient action plus an expected+build precondition matching the once-resolved verified descriptor. Expected+renderer hashes are compared for staleness, never persisted as authority.+Ordinary title or locale Save preserves the existing approval without rebinding.+Opening Game settings refreshes only the local verified-family listing, without+changing the default Wine path or refreshing an account.++This model resolves the current family receipt only. If the installed family+pointer changes, the prior game's approval fails closed before any new prefix is+created. Old build files, prefixes and saves remain intact. Game settings offer+explicit same-family approval for the current build; fresh consent resets when+that displayed build changes. Automatic updates never authorize empty prefixes+for an already configured game.++Each approved build uses its own prefix. That prefix lives under `runtime-prefixes/<family>/<buildId>/<gameId>/`, separatelyfrom default `compatdata/<gameId>` and `prefixes/<gameId>`. Existing local savesstay in their old prefix. No copying, transfer or prefix initialization occurswhen saving the selection. Unknown or mismatched prefix bindings fail closed.diff --git a/src/main/index.ts b/src/main/index.tsindex a997d9e..f0ce0ad 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,5 +1,5 @@+import {approvedRuntimeSettings,type RuntimeSettingsRequest} from './runtime-settings.js';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';@@ -728,7 +728,7 @@ async function gameContent(id: string) {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)});+ selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)});const result = await contentManager().plan(game, () => accountLibrary.access(true), currentMarket());const wine = selectedRuntime.winePath;result.plan.runtimeSupported = Boolean(wine && await storeContentRuntime(wine));@@ -1054,7 +1054,7 @@ async function gameLaunchOptions(id: string): Promise<GameLaunchOptions> {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;+ selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,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);@@ -1116,7 +1116,7 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<const locale = supportedGameLocale(game.locale ?? '');const titleId = await gameTitleId(game).catch(() => undefined);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)});+ selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,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.');@@ -1409,7 +1409,7 @@ async function installGameVcRuntime(id: string): Promise<void> {const inspected = await inspectGameDirectory(game.path);if (inspected.installState !== 'ready') throw new Error(inspected.installMessage ?? 'The game installation is not ready.');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)});+ selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,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.');@@ -1562,6 +1562,7 @@ function registerDemoIpc(catalogMarket: () => string): void {ipcMain.handle('backend-update', () => {});ipcMain.handle('backend-rebuild', () => {});ipcMain.handle('runtime-refresh', () => snapshot().runtime);+ ipcMain.handle('runtime-families', () => []);ipcMain.handle('runtime-check-update', () => snapshot().runtime);ipcMain.handle('runtime-check-nexus', () => snapshot().runtime);ipcMain.handle('runtime-install', () => {});@@ -1926,20 +1927,15 @@ function registerIpc(): void {if (!game) throw new Error('Game not found.');return gameLocales(game);});- ipcMain.handle('update-game', async (_event, id: string, patch: Partial<Game>) => {+ ipcMain.handle('runtime-families', async () => {const families=await runtime.refreshFamilies();emitSnapshot();return families;});+ ipcMain.handle('update-game', async (_event, id: string, patch: Partial<Game>&RuntimeSettingsRequest) => {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;+ if ('runtime' in patch || 'runtimeSeparatePrefix' in patch || 'runtimeApproveBuild' 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);+ if(selection!==(current.runtime??'default')||patch.runtimeApproveBuild===true||selection!=='default'&&patch.runtimeSeparatePrefix!==undefined&&patch.runtimeSeparatePrefix!==current.runtimeSeparatePrefix)ensureIdle();+ Object.assign(allowed,await approvedRuntimeSettings(current,patch,store.settings.runtimeRoot));}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);diff --git a/src/main/runtime-families.test.ts b/src/main/runtime-families.test.tsindex ab1f599..9419502 100644--- a/src/main/runtime-families.test.ts+++ b/src/main/runtime-families.test.ts@@ -4,6 +4,8 @@ import path from 'node:path';import os from 'node:os';import {execFile as execFileCallback} from 'node:child_process';import {promisify} from 'node:util';+import {approvedRuntimeSettings} from './runtime-settings';+import type {Game} from '../shared/types';import {prepareProtonRunner} from './proton';import {createHash} from 'node:crypto';import {resolveRuntimeFamily,installedRuntimeFamilies,runtimeFamilyVerificationStats} from './runtime-families';@@ -11,6 +13,7 @@ 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');+async function approval(){const value=JSON.parse(await fs.readFile(path.join(root,'variants',family,'current.json'),'utf8'));return {buildId:value.buildId,manifestSha256:value.manifestSha256,sourceCommit:value.sourceCommit};}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>={};@@ -49,7 +52,7 @@ it('rejects executable symlink redirection even to matching bytes',async()=>{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'};+ await fixture();const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64',approvedBuild:await approval()};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'));@@ -61,7 +64,7 @@ it('captures immutable independent sessions and preserves the default prefix pat});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'};+ const options={runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,defaultWine:'/default/wine',arch:'x64',approvedBuild:await approval()};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']);@@ -71,7 +74,7 @@ it('requires explicit separate prefix consent without mutating the legacy prefixawait 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 fixture();const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,separatePrefix:true,approvedBuild:await approval(),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'});@@ -79,7 +82,7 @@ it('does not adopt an unbound experimental prefix or another family in the defauawait 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'});+ await fixture();const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,separatePrefix:true,approvedBuild:await approval(),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([]);});@@ -104,7 +107,7 @@ it('Stop uses its captured runtime and prefix after another launch is selected',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 options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64',approvedBuild:await approval()};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');@@ -205,3 +208,57 @@ it('rejects a release-root symlink even when its external payload has matching hawait 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();});++async function switchBuild(id:string) {+ const next=path.join(root,'variants',family,'releases',id);await fs.cp(release,next,{recursive:true});+ const file=path.join(next,'nexus-family.json');const manifest=JSON.parse(await fs.readFile(file,'utf8'));manifest.buildId=id;+ const bytes=JSON.stringify(manifest);await fs.writeFile(file,bytes);+ await fs.writeFile(path.join(root,'variants',family,'current.json'),JSON.stringify({schema:1,family,buildId:id,sourceRepository,sourceCommit,manifestSha256:hash(bytes)}));+ return {buildId:id,sourceCommit,manifestSha256:hash(bytes)};+}+const savedGame=():Game=>({id:'test',path:'/synthetic/game',title:'Synthetic',installState:'ready',addedAt:'2026-01-01'});+it('pins explicit build approval: A to B never creates a fresh prefix from old consent and preserves A local progress',async()=>{+ await fixture();let game=savedGame();const approvedA=await approval();+ Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:approvedA},root));+ const options=()=>({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,defaultWine:'/default/wine',arch:'x64'});+ const a=await resolveGameRuntime(options());await bindRuntimePrefix(a);const progress=path.join(a.compatibilityDataPath,'synthetic-progress');await fs.writeFile(progress,'A progress');+ const approvedB=await switchBuild('d'.repeat(64));const bRoot=path.join(root,'runtime-prefixes',family,approvedB.buildId,game.id);+ await expect(resolveGameRuntime(options())).rejects.toThrow('build changed');+ expect(await fs.readFile(progress,'utf8')).toBe('A progress');await expect(fs.stat(bRoot)).rejects.toMatchObject({code:'ENOENT'});+ const noResolve=vi.fn(()=>{throw Error('Ordinary settings Save must not approve a new build');});+ const ordinary=await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root,noResolve);+ expect(ordinary.runtimeBuild).toEqual(approvedA);expect(noResolve).not.toHaveBeenCalled();+ await expect(approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:approvedA},root)).rejects.toThrow('settings were open');+ const forged=await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeBuild:approvedB} as never,root);+ expect(forged.runtimeBuild).toEqual(approvedA);+ Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:approvedB},root));+ expect(game.runtimeBuild).toEqual(approvedB);await expect(fs.stat(bRoot)).rejects.toMatchObject({code:'ENOENT'}); // Saving the choice still does not create a prefix.+ const b=await resolveGameRuntime(options());await bindRuntimePrefix(b);+ expect(await fs.readdir(b.compatibilityDataPath)).toEqual(['.nexus-runtime-family.json']);expect(await fs.readFile(progress,'utf8')).toBe('A progress');+});+it('does not adopt a legacy family-wide consent or rebind on unrelated title/locale Save',async()=>{+ await fixture();const game={...savedGame(),runtime:family,runtimeSeparatePrefix:true} as Game;+ await expect(approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root)).rejects.toThrow('explicitly approve');+ await expect(resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:family,separatePrefix:true,defaultWine:'/default/wine',arch:'x64'})).rejects.toThrow('not been approved');+ const trusted=await approval();Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:trusted},root));+ await switchBuild('d'.repeat(64));+ const {StateStore}=await import('./store');const store=new StateStore(path.join(root,'profile'));await store.upsertGame(game);+ await store.patchGame(game.id,{...await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root),title:'New title',locale:'de-DE'});+ const loaded=new StateStore(path.join(root,'profile'));await loaded.load();expect(loaded.games[0]).toMatchObject({title:'New title',locale:'de-DE',runtimeBuild:trusted});+});+it('captures the approved descriptor once and cannot authorize C if pointer changes after resolving B',async()=>{+ await fixture();const game=savedGame();const expectedB=await approval();+ const resolve=vi.fn(async()=>{const b=await resolveRuntimeFamily(root,family,'x64');await switchBuild('d'.repeat(64));return b;});+ const patch=await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:expectedB},root,resolve);+ expect(resolve).toHaveBeenCalledOnce();expect(patch.runtimeBuild).toEqual(expectedB);+ await expect(resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:patch.runtime,separatePrefix:patch.runtimeSeparatePrefix,approvedBuild:patch.runtimeBuild,defaultWine:'/default/wine',arch:'x64'})).rejects.toThrow('build changed');+ await expect(fs.stat(path.join(root,'runtime-prefixes'))).rejects.toMatchObject({code:'ENOENT'});+});+it('requires a fresh transient approval and exact expected descriptor, and clears the binding only when default is chosen',async()=>{+ await fixture();const game=savedGame(),expected=await approval();+ await expect(approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root)).rejects.toThrow('Fresh explicit');+ await expect(approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:{...expected,manifestSha256:'f'.repeat(64)}},root)).rejects.toThrow('settings were open');+ const approved=await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:expected},root);+ expect(approved.runtimeBuild).toEqual(expected);+ expect(await approvedRuntimeSettings({...game,...approved},{runtime:'default'},root)).toEqual({runtime:'default',runtimeSeparatePrefix:false,runtimeBuild:undefined});+});diff --git a/src/main/runtime-families.ts b/src/main/runtime-families.tsindex 065e702..8ae9233 100644--- a/src/main/runtime-families.ts+++ b/src/main/runtime-families.ts@@ -136,7 +136,7 @@ export async function resolveRuntimeFamily(runtimeRoot:string,selection:unknown,}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;}+ try{const value=await resolveRuntimeFamily(runtimeRoot,id,arch);return {id:value.id,label:value.label,buildId:value.buildId,sourceCommit:value.sourceCommit,manifestSha256:value.manifestSha256};}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.tsindex 72b3a9a..b66c154 100644--- a/src/main/runtime-prefix-binding.ts+++ b/src/main/runtime-prefix-binding.ts@@ -1,6 +1,6 @@import {promises as fs} from 'node:fs';import path from 'node:path';-import {gameRuntimeSelection,type GameRuntimeSelection} from '../shared/runtime-selection.js';+import {gameRuntimeSelection,sameRuntimeBuild,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';@@ -9,7 +9,7 @@ export interface GameRuntimeContext {}/** 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>> {+export async function resolveGameRuntime(options:{runtimeRoot:string;dataRoot:string;gameId:string;selection:unknown;separatePrefix:unknown;approvedBuild?: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') {@@ -23,6 +23,7 @@ export async function resolveGameRuntime(options:{runtimeRoot:string;dataRoot:st}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);+ if(!sameRuntimeBuild(options.approvedBuild,managed))throw Error('The selected runtime build changed or has not been approved. Explicitly choose the installed build in Game settings. Existing prefix and local saves were preserved.');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')});diff --git a/src/main/runtime-settings.ts b/src/main/runtime-settings.tsnew file mode 100644index 0000000..9b4839d--- /dev/null+++ b/src/main/runtime-settings.ts@@ -0,0 +1,22 @@+import type {Game} from '../shared/types.js';+import {gameRuntimeSelection,runtimeBuildApproval,sameRuntimeBuild,type RuntimeBuildApproval} from '../shared/runtime-selection.js';+import {resolveRuntimeFamily} from './runtime-families.js';+export type RuntimeSettingsRequest=Partial<Pick<Game,'runtime'|'runtimeSeparatePrefix'>> & {runtimeApproveBuild?:boolean;runtimeExpectedBuild?:RuntimeBuildApproval};+/** Explicit compare-and-set. Expected hashes are only a stale-form precondition;+ * persist exclusively the once-resolved, verified server descriptor. */+export async function approvedRuntimeSettings(current:Game,request:RuntimeSettingsRequest,runtimeRoot:string,resolve=resolveRuntimeFamily):Promise<Partial<Game>> {+ const selection=gameRuntimeSelection('runtime' in request?request.runtime:current.runtime);+ const separate='runtimeSeparatePrefix' in request?request.runtimeSeparatePrefix:current.runtimeSeparatePrefix;+ if(separate!==undefined&&typeof separate!=='boolean')throw Error('Invalid runtime prefix choice.');+ if(request.runtimeApproveBuild!==undefined&&typeof request.runtimeApproveBuild!=='boolean')throw Error('Invalid explicit runtime build approval.');+ if(selection==='default')return {runtime:selection,runtimeSeparatePrefix:false,runtimeBuild:undefined};+ if(separate!==true)throw Error('Explicit separate prefix choice is required. Existing local saves remain in the old prefix.');+ if(selection===current.runtime&&request.runtimeApproveBuild!==true) {+ // Ordinary title/locale Save never refreshes a prior build's permission.+ return {runtime:selection,runtimeSeparatePrefix:true,runtimeBuild:runtimeBuildApproval(current.runtimeBuild)};+ }+ if(request.runtimeApproveBuild!==true)throw Error('Fresh explicit approval of the installed runtime build is required.');+ const verified=await resolve(runtimeRoot,selection);+ if(!sameRuntimeBuild(request.runtimeExpectedBuild,verified))throw Error('The installed runtime build changed while settings were open. Review it and approve a new separate prefix again.');+ return {runtime:selection,runtimeSeparatePrefix:true,runtimeBuild:runtimeBuildApproval(verified)};+}diff --git a/src/main/runtime.ts b/src/main/runtime.tsindex 0446f36..51ec8b1 100644--- a/src/main/runtime.ts+++ b/src/main/runtime.ts@@ -104,6 +104,14 @@ export class RuntimeManager {return false;}+ async refreshFamilies() {+ const root=this.status.runtimeRoot;+ const variants=await installedRuntimeFamilies(root,this.hostArch);+ if(root!==this.status.runtimeRoot)throw Error('Runtime location changed. Check installed families again.');+ this.status.variants=variants;+ return structuredClone(variants);+ }+async refresh(): Promise<RuntimeStatus> {const [gh, authenticated, tar, sha512sum] = await Promise.all([this.commandOk('gh', ['--version']),@@ -112,7 +120,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);+ await this.refreshFamilies();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 e2f67d5..6971a13 100644--- a/src/main/store.ts+++ b/src/main/store.ts@@ -1,4 +1,4 @@-import {gameRuntimeSelection} from '../shared/runtime-selection.js';+import {gameRuntimeSelection,runtimeBuildApproval} from '../shared/runtime-selection.js';import { createHash } from 'node:crypto';import { promises as fs } from 'node:fs';import os from 'node:os';@@ -111,6 +111,7 @@ export class StateStore {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.');+ if ('runtimeBuild' in patch && patch.runtimeBuild !== undefined) patch.runtimeBuild=runtimeBuildApproval(patch.runtimeBuild);Object.assign(game, patch);await this.save();return game;diff --git a/src/preload/index.cts b/src/preload/index.ctsindex 5337453..7934b56 100644--- a/src/preload/index.cts+++ b/src/preload/index.cts@@ -83,6 +83,7 @@ const api: LauncherApi = {updateBackend: () => ipcRenderer.invoke('backend-update'),rebuildBackend: () => ipcRenderer.invoke('backend-rebuild'),refreshRuntime: () => ipcRenderer.invoke('runtime-refresh'),+ getRuntimeFamilies: () => ipcRenderer.invoke('runtime-families'),checkRuntimeUpdate: () => ipcRenderer.invoke('runtime-check-update'),checkNexusRuntime: () => ipcRenderer.invoke('runtime-check-nexus'),installRuntime: () => ipcRenderer.invoke('runtime-install'),diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 6df3d5c..2a7a8ed 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -1,5 +1,5 @@import {GameRuntimeFields} from './GameRuntimeFields';-import {gameRuntimeAvailable,type GameRuntimeSelection} from '../shared/runtime-selection';+import {gameRuntimeAvailable,sameRuntimeBuild,runtimeBuildApproval,type InstalledRuntimeFamily,type RuntimeBuildApproval,type GameRuntimeSelection} from '../shared/runtime-selection';import { CloudSaveWarning } from './CloudSaveWarning';import { CheckField } from './CheckField';import { useDialogFocus } from './use-dialog-focus';@@ -211,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, 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]);+ }, [game?.id, game?.runtime, game?.runtimeSeparatePrefix, game?.runtimeBuild?.buildId, game?.runtimeBuild?.manifestSha256, 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;}@@ -655,6 +655,21 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,const [editLocale, setEditLocale] = useState('');const [editRuntime,setEditRuntime]=useState<GameRuntimeSelection>('default');const [editSeparatePrefix,setEditSeparatePrefix]=useState(false);+ const [editApproveRuntimeBuild,setEditApproveRuntimeBuild]=useState(false);+ const [editExpectedRuntimeBuild,setEditExpectedRuntimeBuild]=useState<Readonly<RuntimeBuildApproval>>();+ const [runtimeChoices,setRuntimeChoices]=useState<InstalledRuntimeFamily[]>(data.runtime.variants??[]);+ const runtimeChoicesKey=JSON.stringify(data.runtime.variants??[]);+ useEffect(()=>setRuntimeChoices(data.runtime.variants??[]),[runtimeChoicesKey]);+ const runtimeChoice=useRef<{gameId:string;key:string}>();+ const installedChoice=runtimeChoices.find(item=>item.id===editRuntime);+ const installedChoiceKey=JSON.stringify([editRuntime,installedChoice?.buildId,installedChoice?.manifestSha256,installedChoice?.sourceCommit]);+ useBrowserLayoutEffect(()=>{+ if(!dialogGame||dialogGame.kind!=='settings'){runtimeChoice.current=undefined;return;}+ if(runtimeChoice.current?.gameId===dialogGame.id&&runtimeChoice.current.key!==installedChoiceKey){+ setEditSeparatePrefix(false);setEditApproveRuntimeBuild(false);setEditExpectedRuntimeBuild(undefined);+ }+ runtimeChoice.current={gameId:dialogGame.id,key:installedChoiceKey};+ },[dialogGame?.id,dialogGame?.kind,installedChoiceKey]);const [editTools, setEditTools] = useState<GameLaunchTools>({ ...defaultLaunchTools });const [localeOptions, setLocaleOptions] = useState<string[]>([]);const localeRequest = useRef(0);@@ -732,10 +747,14 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,setMenu(undefined);setEditTitle(game.title);setEditLocale(game.locale ?? '');- setEditRuntime(game.runtime ?? 'default');setEditSeparatePrefix(game.runtimeSeparatePrefix===true);+ setEditRuntime(game.runtime ?? 'default');+ const installed=runtimeChoices.find(item=>item.id===game.runtime);+ setEditSeparatePrefix(game.runtimeSeparatePrefix===true&&sameRuntimeBuild(game.runtimeBuild,installed));+ setEditApproveRuntimeBuild(false);setEditExpectedRuntimeBuild(undefined);setEditTools({ ...defaultLaunchTools, ...game.launchTools });setLocaleOptions([]);const request = ++localeRequest.current;+ if(kind==='settings')void window.launcher.getRuntimeFamilies().then(families=>{if(request===localeRequest.current){setRuntimeChoices(families);if(!sameRuntimeBuild(game.runtimeBuild,families.find(item=>item.id===game.runtime))){setEditSeparatePrefix(false);setEditApproveRuntimeBuild(false);setEditExpectedRuntimeBuild(undefined);}}}).catch(error=>{if(request===localeRequest.current){setRuntimeChoices([]);toast({kind:'error',message:errorMessage(error)});}});if (kind === 'settings') void window.launcher.getGameLocales(game.id).then(locales => {if (request === localeRequest.current) setLocaleOptions(locales);}).catch((error) => { if (request === localeRequest.current) toast({ kind: 'error', message: errorMessage(error) }); });@@ -747,7 +766,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), runtime:editRuntime, runtimeSeparatePrefix:editSeparatePrefix });+ await window.launcher.updateGame(dialogGame.id, { title: editTitle.trim(), locale: editLocale, launchTools: normalizeLaunchTools(editTools), runtime:editRuntime, runtimeSeparatePrefix:editSeparatePrefix, runtimeApproveBuild:editApproveRuntimeBuild, runtimeExpectedBuild:editExpectedRuntimeBuild });toast({ kind: 'success', message: ui("ui.game_settings_saved_7f466a5") });setDialogGame(undefined);} catch (error) { toast({ kind: 'error', message: errorMessage(error) }); }@@ -857,7 +876,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}/>+ <GameRuntimeFields value={editRuntime} separate={editSeparatePrefix} approved={modalGame.runtimeBuild} installed={runtimeChoices} change={value=>{setEditRuntime(value);setEditSeparatePrefix(false);setEditApproveRuntimeBuild(false);setEditExpectedRuntimeBuild(undefined);}} changeSeparate={value=>{setEditSeparatePrefix(value);setEditApproveRuntimeBuild(value);const installed=runtimeChoices.find(item=>item.id===editRuntime);setEditExpectedRuntimeBuild(value&&installed?runtimeBuildApproval(installed):undefined);}}/><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.tsxindex 0fe4116..82d4459 100644--- a/src/renderer/GameRuntimeFields.tsx+++ b/src/renderer/GameRuntimeFields.tsx@@ -1,8 +1,10 @@import {CheckField} from './CheckField';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);+import {runtimeFamilyLabels,sameRuntimeBuild,type GameRuntimeSelection,type InstalledRuntimeFamily} from '../shared/runtime-selection';+export function GameRuntimeFields({value,separate,installed,approved,change,changeSeparate}:{value:GameRuntimeSelection;separate:boolean;installed:InstalledRuntimeFamily[];approved?:unknown;change:(value:GameRuntimeSelection)=>void;changeSeparate:(value:boolean)=>void}) {+ const current=installed.find(item=>item.id===value);+ const missing=value!=='default'&&!current;+ const changed=value!=='default'&&Boolean(current)&&!sameRuntimeBuild(approved,current);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>@@ -10,6 +12,7 @@ export function GameRuntimeFields({value,separate,installed,change,changeSeparat{missing?<option value={value} disabled>{ui('runtime.unavailable',{name:runtimeFamilyLabels[value as keyof typeof runtimeFamilyLabels]??String(value)})}</option>:null}</select></label>{value!=='default'?<>+ {changed?<p role="alert">{ui('runtime.build_changed')}</p>:null}<CheckField required checked={separate} onChange={event=>changeSeparate(event.target.checked)} label={ui('runtime.separate_prefix')} description={ui('runtime.prefix_warning')}/></>:null}</>;diff --git a/src/renderer/game-runtime-fields.test.tsx b/src/renderer/game-runtime-fields.test.tsxindex c309942..3bdfeb2 100644--- a/src/renderer/game-runtime-fields.test.tsx+++ b/src/renderer/game-runtime-fields.test.tsx@@ -8,7 +8,7 @@ it('offers only default when no verified variants are installed, never an unbuilexpect(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}/>);+ 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),manifestSha256:'c'.repeat(64)}]} change={change} changeSeparate={change}/>);expect(html).toContain('experimental');expect(html).toMatch(/type="checkbox" required/);expect(html).toContain('class="check-input"');const help=html.match(/aria-describedby="([^"]+)"/)?.[1];expect(help).toBeTruthy();expect(html).toContain('<small id="'+help+'">');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',()=>{@@ -17,7 +17,7 @@ it('shows a missing persisted selection as disabled rather than falling back',()});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)}];+ const installed=[{id:'nexus-cachyos' as const,label:'Experimental',buildId:'a'.repeat(64),sourceCommit:'b'.repeat(40),manifestSha256:'c'.repeat(64)}];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);diff --git a/src/renderer/game-runtime-settings.test.tsx b/src/renderer/game-runtime-settings.test.tsxnew file mode 100644index 0000000..5473f5a--- /dev/null+++ b/src/renderer/game-runtime-settings.test.tsx@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import {act} from 'react';+import {createRoot,type Root} from 'react-dom/client';+import {afterEach,beforeEach,expect,it,vi} from 'vitest';+import {LibraryPage} from './App';+import {demoAccountLibrary,demoLaunchOptions,demoSnapshot} from '../shared/demo-data';+import type {InstalledRuntimeFamily} from '../shared/runtime-selection';+let root:Root,data:ReturnType<typeof demoSnapshot>;+const family='nexus-cachyos';+const a={buildId:'a'.repeat(64),manifestSha256:'b'.repeat(64),sourceCommit:'c'.repeat(40)};+const b={buildId:'d'.repeat(64),manifestSha256:'e'.repeat(64),sourceCommit:'f'.repeat(40)};+const c={buildId:'1'.repeat(64),manifestSha256:'2'.repeat(64),sourceCommit:'3'.repeat(40)};+const installed=(build:typeof a):InstalledRuntimeFamily=>({id:family,label:'Nexus Runtime (CachyOS, experimental)',...build});+const render=async()=>{await act(async()=>root.render(<LibraryPage data={data} toast={()=>{}}/>));};+const click=async(element:Element)=>{await act(async()=>(element as HTMLElement).click());};+async function openSettings() {+ await click(document.querySelector('.library-card-menu-button')!);+ const settings=[...document.querySelectorAll('.game-context-menu button')].find(button=>button.textContent==='Game settings')!;+ await click(settings);+}+const consent=()=>document.querySelector<HTMLInputElement>('[role="dialog"] input[type="checkbox"][required]')!;+const save=()=>click(document.querySelector('[role="dialog"] button.primary')!);+beforeEach(async()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);+ data=demoSnapshot();data.games=[{...data.games[0],runtime:family,runtimeSeparatePrefix:true,runtimeBuild:a}];+ data.runtime.variants=[installed(b)];+ window.launcher={getRuntimeFamilies:vi.fn(async()=>data.runtime.variants??[]),getAccountLibrary:vi.fn(async()=>demoAccountLibrary('all',new Map())),getGameLaunchOptions:vi.fn(async()=>demoLaunchOptions),getGameLocales:vi.fn(async()=>[]),+ updateGame:vi.fn(async(_id,patch)=>({...data.games[0],...patch}))} as unknown as Window['launcher'];+ document.body.innerHTML='<div id="root"></div>';root=createRoot(document.getElementById('root')!);await render();+});+afterEach(async()=>{await act(async()=>root.unmount());vi.restoreAllMocks();vi.unstubAllGlobals();document.body.innerHTML='';});+it('permits same-family A-to-B recovery only after a fresh consent interaction',async()=>{+ await openSettings();expect(consent().checked).toBe(false);+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('runtime build changed');+ const select=[...document.querySelectorAll<HTMLSelectElement>('[role="dialog"] select')].find(select=>select.value===family)!;+ expect(select).toBeTruthy(); // Same family remains selected, no default detour.+ await click(consent());await save();+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family,runtimeSeparatePrefix:true,runtimeApproveBuild:true,runtimeExpectedBuild:b}));+});+it('ordinary Save of an already approved build sends no fresh build approval',async()=>{+ data.runtime.variants=[installed(a)];await render();await openSettings();expect(consent().checked).toBe(true);+ await save();expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtimeApproveBuild:false,runtimeExpectedBuild:undefined}));+});+it('clears pending B consent when a C snapshot arrives, requiring a fresh C interaction',async()=>{+ await openSettings();await click(consent());data.runtime.variants=[installed(c)];await render();+ expect(consent().checked).toBe(false);await save();expect(window.launcher.updateGame).not.toHaveBeenCalled();+ await click(consent());await save();+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtimeApproveBuild:true,runtimeExpectedBuild:c}));+});+it('clears prefilled A consent when the installed build changes while the form stays open',async()=>{+ data.runtime.variants=[installed(a)];await render();await openSettings();expect(consent().checked).toBe(true);+ data.runtime.variants=[installed(b)];await render();expect(consent().checked).toBe(false);+ await save();expect(window.launcher.updateGame).not.toHaveBeenCalled();+ await click(consent());await save();+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtimeApproveBuild:true,runtimeExpectedBuild:b}));+});+it('resets fresh approval after closing and reopening the same-family settings form',async()=>{+ await openSettings();await click(consent());await click(document.querySelector('[role="dialog"] [data-gamepad-cancel]')!);+ await openSettings();expect(consent().checked).toBe(false);+});++it('refreshes verified families locally when opening settings, recovering B from a stale A snapshot',async()=>{+ data.runtime.variants=[installed(a)];await render();vi.mocked(window.launcher.getRuntimeFamilies).mockResolvedValue([installed(b)]);+ await openSettings();expect(window.launcher.getRuntimeFamilies).toHaveBeenCalledOnce();expect(consent().checked).toBe(false);+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('runtime build changed');+ await click(consent());await save();+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family,runtimeApproveBuild:true,runtimeExpectedBuild:b}));+});diff --git a/src/shared/runtime-selection.ts b/src/shared/runtime-selection.tsindex 41483de..279553e 100644--- a/src/shared/runtime-selection.ts+++ b/src/shared/runtime-selection.ts@@ -10,8 +10,19 @@ export function gameRuntimeSelection(value: unknown): GameRuntimeSelection {export const runtimeFamilyLabels: Record<RuntimeFamily, string> = {nexus: 'Nexus Runtime', 'nexus-cachyos': 'Nexus Runtime (CachyOS, experimental)',};+export interface RuntimeBuildApproval {+ buildId:string; manifestSha256:string; sourceCommit:string;+}+export function runtimeBuildApproval(value:unknown):Readonly<RuntimeBuildApproval> {+ const item=value as RuntimeBuildApproval|undefined;+ if(!item||typeof item!=='object'||typeof item.buildId!=='string'||typeof item.manifestSha256!=='string'||typeof item.sourceCommit!=='string'||!/^[a-f0-9]{64}$/.test(item.buildId??'')||!/^[a-f0-9]{64}$/.test(item.manifestSha256??'')||!/^[a-f0-9]{40}$/.test(item.sourceCommit??''))throw Error('Choose and explicitly approve an installed runtime build.');+ return Object.freeze({buildId:item.buildId,manifestSha256:item.manifestSha256,sourceCommit:item.sourceCommit});+}+export function sameRuntimeBuild(a:unknown,b:unknown):boolean {+ try{const left=runtimeBuildApproval(a),right=runtimeBuildApproval(b);return left.buildId===right.buildId&&left.manifestSha256===right.manifestSha256&&left.sourceCommit===right.sourceCommit;}catch{return false;}+}export interface InstalledRuntimeFamily {- id: RuntimeFamily; label: string; buildId: string; sourceCommit: string;+ id: RuntimeFamily; label: string; buildId: string; sourceCommit: string; manifestSha256: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 {diff --git a/src/shared/types.ts b/src/shared/types.tsindex a007838..0aa3b5a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1,4 +1,4 @@-import type {GameRuntimeSelection,InstalledRuntimeFamily} from './runtime-selection.js';+import type {GameRuntimeSelection,InstalledRuntimeFamily,RuntimeBuildApproval} from './runtime-selection.js';export type Page = 'home' | 'store' | 'library' | 'downloads' | 'settings' | 'social';export interface BackendCapabilities {@@ -118,6 +118,7 @@ export interface Game {winePath?: string; // Legacy saved field; ignored for launch.runtime?: GameRuntimeSelection;runtimeSeparatePrefix?: boolean;+ runtimeBuild?: RuntimeBuildApproval;launchArgs?: string;launchTools?: GameLaunchTools;locale?: string;@@ -562,6 +563,7 @@ export interface LauncherApi {updateBackend(): Promise<void>;rebuildBackend(): Promise<void>;refreshRuntime(): Promise<RuntimeStatus>;+ getRuntimeFamilies(): Promise<InstalledRuntimeFamily[]>;checkRuntimeUpdate(): Promise<RuntimeStatus>;checkNexusRuntime(): Promise<RuntimeStatus>;installRuntime(): Promise<void>;@@ -603,7 +605,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' | 'runtime' | 'runtimeSeparatePrefix'>>): Promise<Game>;+ updateGame(id: string, patch: Partial<Pick<Game, 'title' | 'executable' | 'launchArgs' | 'locale' | 'launchTools' | 'runtime' | 'runtimeSeparatePrefix'>> & {runtimeApproveBuild?:boolean;runtimeExpectedBuild?:RuntimeBuildApproval}): Promise<Game>;getGameLocales(id: string): Promise<string[]>;removeGame(id: string, mode: 'library' | 'delete-files'): Promise<void>;getGameLaunchOptions(id: string): Promise<GameLaunchOptions>;