Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
feat(store): show installation only for verified Store licenses
domsvoboda08cfa7caf303
diff --git a/scripts/ui/store-access-smoke.cjs b/scripts/ui/store-access-smoke.cjsnew file mode 100644index 0000000..14d2c53--- /dev/null+++ b/scripts/ui/store-access-smoke.cjs@@ -0,0 +1,84 @@+// Run with Electron. Exercises Store actions using explicitly synthetic account access.+// XODUS_UI_SMOKE_OUTPUT must be a new private directory. Optional+// XODUS_UI_SMOKE_SOURCE selects a built checkout (defaults to this checkout).+// English-only synthetic account screenshots.+const {app,session,ipcMain} = require('electron');+const fs = require('node:fs/promises');+const path = require('node:path');+const {pathToFileURL} = require('node:url');+const source = path.resolve(process.env.XODUS_UI_SMOKE_SOURCE || path.join(__dirname,'../..'));+const output = process.env.XODUS_UI_SMOKE_OUTPUT;+if (!output || !path.isAbsolute(output)) throw Error('Set XODUS_UI_SMOKE_OUTPUT to a new absolute private directory');+if (process.argv.some(value=>value==='--launch-game'||value==='--nexus-profile')) throw Error('Demo fixture does not accept game or profile arguments');+process.env.XODUS_DEMO = '1';+app.disableHardwareAcceleration();+const language='en-US';+app.commandLine.appendSwitch('lang',language);+// Never inherit another capture action or a developer server from the caller.+for (const name of ['VITE_DEV_SERVER_URL','XODUS_DEMO_CAPTURE_DIR','XODUS_DEMO_TOUR','XODUS_NEXUS_SMOKE_SCREENSHOT','XODUS_NEXUS_SMOKE_STORE','XODUS_NEXUS_SMOKE_STORE_QUERY','XODUS_NEXUS_FONTCONFIG','XODUS_NEXUS_FONTCONFIG_ORIGINAL','XODUS_NEXUS_FONTCONFIG_ORIGINAL_SET']) delete process.env[name];+// Block both main-process Store requests and renderer artwork. This fixture+// needs no network and cannot accidentally fall through to live account APIs.+globalThis.fetch = async () => { throw Error('Network disabled by demo UI fixture'); };+let completed = false;+const timer = setTimeout(()=>{console.error('Demo Store eligibility smoke timed out');app.exit(1);},30000);+const evaluate = (window, fn, ...args) => window.webContents.executeJavaScript(`(${fn.toString()})(...${JSON.stringify(args)})`);+const ready = async (window, selector) => evaluate(window, async selector => {+ const deadline=Date.now()+6000;+ while(!document.querySelector(selector)) {+ if(Date.now()>deadline)throw Error('Missing demo element: '+selector);+ await new Promise(resolve=>setTimeout(resolve,30));+ }+},selector);+const settle = window => evaluate(window,async()=>{+ await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));+ await Promise.race([Promise.all(document.getAnimations().filter(animation=>Number.isFinite(animation.effect?.getTiming().iterations)).map(animation=>animation.finished.catch(()=>{}))),new Promise(resolve=>setTimeout(resolve,500))]);+});+async function capture(window) {+ const results=[];+ const initial=await evaluate(window,()=>window.launcher.getSnapshot());+ if(initial.auth.username!=='[email protected]')throw Error('Expected isolated sample account');+ const ids=['9AAAAAAAAAAA','9BBBBBBBBBBB','9CCCCCCCCCCC','9DDDDDDDDDDD'];+ const products=ids.map((productId,index)=>({productId,title:['Retail PC Adventure','Retail PC Racing','Retail PC Strategy','Retail PC Puzzle'][index],publisher:'Sample Studio',description:'Explore this retail PC game.',categories:['Action'],installability:'supported',supportNote:'Windows.Desktop MSIXVC',purchasePrice:'$29.99',includedWith:'Game Pass',storeUrl:`https://www.xbox.com/games/store/p/${productId}`}));+ let fixture,licensed=false;+ const replace=(name,handler)=>{ipcMain.removeHandler(name);ipcMain.handle(name,handler);};+ replace('catalog-featured',()=>({query:'',products,hasMore:false}));+ replace('store-access',()=>({account:fixture.auth.username,backend:fixture.backend.binaryPath,market:'US',configuredMarket:fixture.settings.market,checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60000).toISOString(),accessByProductId:licensed?Object.fromEntries(ids.map(id=>[id,'owned'])):{}}));+ replace('game-details',()=>({...products[0],description:'Explore this retail PC game. Store availability is shown independently of this account license.',screenshots:[],features:[],genres:['Action']}));+ replace('game-activity',()=>({status:'unavailable'}));replace('game-achievements',()=>({status:'unavailable'}));+ for(const [width,height] of [[1280,800],[800,600]])for(const state of ['unlicensed','licensed']){+ licensed=state==='licensed';window.setContentSize(width,height);+ window.webContents.send('launcher-page','home');await settle(window);+ fixture=structuredClone(initial);fixture.games=[];fixture.downloads=[];fixture.settings.market='US';fixture.settings.interfaceLanguage='en';fixture.settings.firstRunCompleted=true;+ fixture.auth={running:false,stored:true,username:'[email protected]',player:'[email protected]',gamertag:'PersonalPlayer',note:'Synthetic account fixture'};+ window.webContents.send('snapshot',fixture);window.webContents.send('launcher-page','store');+ await ready(window,'.catalog-card');await settle(window);+ const grid=await evaluate(window,()=>({language:document.documentElement.lang,width:document.documentElement.scrollWidth,actions:[...document.querySelectorAll('.catalog-card-install')].map(button=>button.textContent),manualForm:Boolean(document.querySelector('.manual-install'))}));+ if(grid.width>width||grid.language!=='en'||grid.manualForm||grid.actions.some(label=>label!==(licensed?'Install':'Store page')))throw Error('Store grid eligibility failed: '+JSON.stringify(grid));+ await fs.writeFile(path.join(output,`store-${state}-grid-${width}x${height}.png`),(await window.webContents.capturePage()).toPNG());+ await evaluate(window,()=>document.querySelector('.featured-tile').click());await ready(window,'.game-details-page');await settle(window);+ const detail=await evaluate(window,()=>({language:document.documentElement.lang,width:document.documentElement.scrollWidth,install:[...document.querySelectorAll('.gd-play-controls button')].some(button=>button.textContent==='Install'),storePage:[...document.querySelectorAll('.gd-play-controls button')].some(button=>button.textContent==='Store page'),location:Boolean(document.querySelector('.gd-install-options input'))}));+ if(detail.width>width||detail.language!=='en'||detail.install!==licensed||detail.location!==licensed||!detail.storePage)throw Error('Store detail eligibility failed: '+JSON.stringify(detail));+ await evaluate(window,()=>document.querySelector('.gd-play-controls').scrollIntoView({block:'center'}));await settle(window);+ await fs.writeFile(path.join(output,`store-${state}-detail-${width}x${height}.png`),(await window.webContents.capturePage()).toPNG());+ results.push({state,width,height,grid,detail});+ }+ await fs.writeFile(path.join(output,'store-access-results.json'),JSON.stringify({source,scope:'Actual compiled English demo, synthetic Store license evidence only. Network blocked in main and renderer. No real accounts, installations, games or saves.',results},null,2)+'\n');+ completed=true;clearTimeout(timer);app.exit(0);+}+(async()=>{+ // Refuse an existing directory, so no saved profile or prior result is reused.+ await fs.mkdir(output,{mode:0o700});+ const profile=path.join(output,'profile');await fs.mkdir(profile,{mode:0o700});+ app.setPath('userData',profile);+ app.on('browser-window-created',(_event,window)=>{+ window.show=()=>{};window.hide();window.webContents.setBackgroundThrottling(false);+ window.webContents.once('did-finish-load',()=>void capture(window).catch(error=>{console.error(error);app.exit(1);}));+ });+ await app.whenReady();+ session.defaultSession.webRequest.onBeforeRequest({urls:['http://*/*','https://*/*','ws://*/*','wss://*/*']},(_details,callback)=>callback({cancel:true}));+ // Use the built-in offscreen smoke surface, while this fixture owns exit.+ process.env.XODUS_NEXUS_SMOKE_SCREENSHOT=path.join(output,'built-in-smoke.png');+ app.quit=()=>{};+ await import(pathToFileURL(path.join(source,'dist-electron/main/index.js')).href);+})().catch(error=>{console.error(error);clearTimeout(timer);app.exit(1);});+app.on('will-quit',()=>{if(!completed)clearTimeout(timer);});diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 1a3c1ca..084edbd 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -1,3 +1,4 @@+import {useStoreAccess} from './store-access';import {GameRuntimeFields} from './GameRuntimeFields';import {gameRuntimeAvailable,sameRuntimeBuild,runtimeBuildApproval,type InstalledRuntimeFamily,type RuntimeBuildApproval,type GameRuntimeSelection} from '../shared/runtime-selection';import { CloudSaveWarning } from './CloudSaveWarning';@@ -270,8 +271,8 @@ function CatalogSupportBadge({ product }: { product: CatalogProduct }) {aria-label={product.installability === 'unknown' ? ui("ui.package_support_unknown_12fe897") : undefined}>{product.installability === 'supported' ? 'PC' : product.installability === 'unknown' ? '?' : ui("ui.unsupported_5432465")}</span>;}-export function StoreProductCard({ product, selected, disabled, label, select, install }: {- product: CatalogProduct; selected: boolean; disabled: boolean; label: string;+export function StoreProductCard({ product, selected, disabled, label, select, install, licensed = false }: {+ product: CatalogProduct; selected: boolean; disabled: boolean; label: string; licensed?: boolean;select: (product: CatalogProduct,openDetails?:boolean) => void; install: (product: CatalogProduct) => void;}) {return <article className={`catalog-card ${selected ? 'selected' : ''}`} data-gamepad-card>@@ -281,14 +282,15 @@ export function StoreProductCard({ product, selected, disabled, label, select, i<CatalogSupportBadge product={product} /><div><GameTitle title={product.title} /><small>{product.publisher ?? product.productId}</small><span>{product.purchasePrice ?? ui("ui.price_unavailable_6a9e657")}{product.includedWith ? ` · ${product.includedWith}` : ''}</span></div></button>- <button className="catalog-card-install" data-gamepad-skip data-gamepad-card-action disabled={disabled} onClick={() => install(product)}>+ {licensed ? <button className="catalog-card-install" data-gamepad-skip data-gamepad-card-action disabled={disabled} onClick={() => install(product)}>{label === 'Preparing…' ? <LoaderCircle className="spin" /> : label === 'Installed' ? <Check /> : <Download />}{label}- </button>+ </button> : <button className="catalog-card-install" data-gamepad-skip data-gamepad-card-action onClick={() => window.open(product.storeUrl ?? `https://www.xbox.com/games/store/p/${product.productId}`, '_blank')}>{ui("ui.store_page_9c667df")}</button>}</article>;}-function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toast: (value: Toast) => void; go: (page: Page) => void; initialQuery: string }) {+export function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toast: (value: Toast) => void; go: (page: Page) => void; initialQuery: string }) {const startPackageInstall = usePackageInstall();+ const access = useStoreAccess(data);const [catalog, setCatalog] = useState<CatalogSearchResult>();const [featured, setFeatured] = useState<CatalogSearchResult>();const [featuredLoading, setFeaturedLoading] = useState(true);@@ -303,11 +305,7 @@ function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toastwasOpen.current=detailOpen&&Boolean(selected);},[detailOpen,selected?.productId]);const [loadingMore, setLoadingMore] = useState(false);- const [manualProductId, setManualProductId] = useState('');- const [manualTitle, setManualTitle] = useState('');- const [destination, setDestination] = useState(data.settings.installRoot);const [busy, setBusy] = useState<string>();- useEffect(() => { if (!selected) setDestination(data.settings.installRoot); }, [data.settings.installRoot, selected]);useEffect(() => {if (initialQuery.trim().length < 2) return;let cancelled = false;@@ -332,7 +330,6 @@ function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toastfunction selectProduct(product: CatalogProduct,openDetails=true) {setSelected(product);- setDestination(installDestination(product));if(openDetails){savedScroll.current=pageRef.current?.closest('.page-scroll')?.scrollTop??0;setDetailOpen(true);}}@@ -347,29 +344,17 @@ function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toast}async function install(product: CatalogProduct, target = installDestination(product)) {+ if (!access.canInstall(product)) return;setBusy(product.productId);try {- if (!await startPackageInstall(catalogInstallRequest(product, target))) return;+ const request={...catalogInstallRequest(product,target),source:'store' as const};+ if (!await startPackageInstall(request, () => access.canInstall(product))) return;toast({ kind: 'success', message: ui("ui.xodus_is_checking_the_license_and_installing_be774b2", { game: product.title }) });go('downloads');} catch (error) { toast({ kind: 'error', message: errorMessage(error) }); }finally { setBusy(undefined); }}- async function manualInstall(event: FormEvent) {- event.preventDefault(); setBusy('manual');- try {- if (!await startPackageInstall({ productId: manualProductId, title: manualTitle, destination })) return;- toast({ kind: 'success', message: ui("ui.xodus_streaming_started_af5ad62") }); go('downloads');- } catch (error) { toast({ kind: 'error', message: errorMessage(error) }); }- finally { setBusy(undefined); }- }-- async function chooseDestination() {- const selected = await window.launcher.chooseDirectory(destination);- if (selected) setDestination(selected);- }-const installedIds = new Set(data.games.flatMap((game) => game.storeId?.toUpperCase() ?? []));const isInstalled = (product: CatalogProduct) => installedIds.has(product.productId) || Boolean(product.installProductId && installedIds.has(product.installProductId));const queuedIds = new Set(data.downloads.filter(task => ['running', 'queued', 'paused'].includes(task.status)).map(task => task.productId.toUpperCase()));@@ -377,19 +362,18 @@ function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toastconst productGrid = (products: CatalogProduct[]) => <div className="catalog-grid" data-gamepad-grid>{products.map((product) => {const installed = isInstalled(product);return <StoreProductCard key={product.productId} product={product} selected={selected?.productId === product.productId}+ licensed={access.canInstall(product)}disabled={product.installability !== 'supported' || Boolean(busy) || !data.backend.capabilities.streaming || installed || isQueued(product)}label={installed ? ui("ui.installed_f8b32f4") : isQueued(product) ? ui("ui.in_install_queue_7c818f2") : busy === product.productId ? ui("ui.preparing_5d1fa38") : ui("ui.install_569ca49")}select={selectProduct} install={install} />;})}</div>;- if(detailOpen&&selected)return <main ref={pageRef} className="page store-page library-detail-open"><CatalogGameDetails key={`${selected.productId}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} product={selected} data={data} back={()=>setDetailOpen(false)} backLabel={ui('game.back_to_store')} toast={toast}/></main>;+ if(detailOpen&&selected)return <main ref={pageRef} className="page store-page library-detail-open"><CatalogGameDetails key={`${selected.productId}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} product={selected} data={data} storeMode storeAccess={access} back={()=>setDetailOpen(false)} backLabel={ui('game.back_to_store')} toast={toast}/></main>;return <main ref={pageRef} className="page store-page"><header className="page-header"><div><h1>{ui("ui.store_ee7da93")}</h1></div><span className="catalog-source"><StatusDot />Microsoft Store</span></header>{!catalog ? <section className="featured-catalog"><SectionTitle title={ui("ui.featured_c533caf")} />{featuredLoading ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : featured?.products.length ? <><div className="featured-rail">{featured.products.slice(0, 3).map((product) => <button className="featured-tile" key={product.productId} data-gamepad-detail-target={product.productId} onClick={() => selectProduct(product)}>{product.heroUrl || product.posterUrl ? <img src={product.heroUrl ?? product.posterUrl} alt="" /> : <div className="featured-tile-placeholder"><Gamepad2 /></div>}<span className="featured-tile-copy"><GameTitle title={product.title} /><small>{product.publisher ?? 'Microsoft Store'} · {product.installability === 'supported' ? ui('store.verified_pc') : ui("ui.check_package_support_79592da")}</small></span></button>)}</div><SectionTitle title={ui("ui.trending_pc_games_2025848")} />{productGrid(featured.products.slice(3))}</> : <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{featuredError ?? ui("ui.search_still_works_with_live_microsoft_store_dat_b3eeb72")}</p></div>}</section> : null}{catalog ? <><SectionTitle title={ui("ui.results_for_343a212", { query: catalog.query })} />{productGrid(catalog.products)}{catalog.products.length === 0 ? <div className="empty-state compact"><div><Search /></div><h2>{ui("ui.no_games_found_6da4c04")}</h2><p>{ui("ui.try_a_different_title_or_a_microsoft_store_produ_326af8c")}</p></div> : null}{catalog.hasMore ? <div className="load-more" data-gamepad-library-footer><button className="secondary" aria-disabled={loadingMore} aria-busy={loadingMore} onClick={() => { if (!loadingMore) void loadMore(); }}>{loadingMore ? <LoaderCircle className="spin" /> : <Plus />}{ui("ui.load_more_results_e03f1e4")}</button></div> : null}</> : null}- <SectionTitle title={ui("ui.install_by_product_id_d863edd")} />- <form className="manual-install" onSubmit={manualInstall}><label>{ui("ui.product_id_c76c9e7")}<input value={manualProductId} onChange={(event) => setManualProductId(event.target.value)} placeholder={ui("ui.for_example_9n4pt8hgcdhq_b6119c7")} required /></label><label>{ui("ui.queue_name_5cb7293")}{' '}<em>{ui("ui.optional_59be713")}</em><input value={manualTitle} onChange={(event) => setManualTitle(event.target.value)} /></label><label>{ui("ui.install_location_af47896")}<div className="input-action"><input value={destination} onChange={(event) => setDestination(event.target.value)} required /><button type="button" onClick={chooseDestination}><FolderOpen /></button></div></label><button className="secondary" disabled={Boolean(busy) || !data.backend.capabilities.streaming}>{busy === 'manual' ? <LoaderCircle className="spin" /> : <Terminal />}{ui("ui.install_unlisted_id_1b85f63")}</button></form></main>;}diff --git a/src/renderer/CatalogGameDetails.tsx b/src/renderer/CatalogGameDetails.tsxindex d499cb1..256a95d 100644--- a/src/renderer/CatalogGameDetails.tsx+++ b/src/renderer/CatalogGameDetails.tsx@@ -1,8 +1,10 @@import {useEffect,useRef,useState} from 'react';-import {Check,Download,FolderOpen,LoaderCircle} from 'lucide-react';+import {Download,FolderOpen,LoaderCircle,Play} from 'lucide-react';import type {AppSnapshot,CatalogProduct} from '../shared/types';import {GameDetails} from './GameDetails';import {catalogInstallRequest,usePackageInstall} from './PackageInstall';+import {useStoreAccess} from './store-access';+import {gameRuntimeAvailable} from '../shared/runtime-selection';import {ui,uiText} from './i18n';export function catalogGameInstalled(product:CatalogProduct,data:AppSnapshot){@@ -12,15 +14,16 @@ export function catalogGameQueued(product:CatalogProduct,data:AppSnapshot){return data.downloads.some(task=>['running','queued','paused'].includes(task.status)&&[product.productId,product.installProductId].includes(task.productId.toUpperCase()));}-export function CatalogGameDetails({product,data,back,backLabel,toast}:{product:CatalogProduct;data:AppSnapshot;back:()=>void;backLabel?:string;toast:(value:{kind:'success'|'error';message:string})=>void}){+export function CatalogGameDetails({product,data,back,backLabel,toast,storeAccess,storeMode=false}:{product:CatalogProduct;storeMode?:boolean;storeAccess?:ReturnType<typeof useStoreAccess>;data:AppSnapshot;back:()=>void;backLabel?:string;toast:(value:{kind:'success'|'error';message:string})=>void}){const startInstall=usePackageInstall();+ const localAccess=useStoreAccess(data,storeMode&&!storeAccess),access=storeAccess??localAccess,licensed=!storeMode||access.canInstall(product);const [destination,setDestination]=useState(()=>{const folder=product.title.normalize('NFKD').replace(/[^\p{L}\p{N}]+/gu,'-').replace(/^-+|-+$/g,'').slice(0,80)||product.productId;return `${data.settings.installRoot.replace(/\/+$/,'')}/${folder}`;});const [busy,setBusy]=useState(false),pending=useRef(false);const installed=catalogGameInstalled(product,data),queued=catalogGameQueued(product,data);- const disabled=Boolean(installed)||queued||busy||product.installability!=='supported'||!data.backend.capabilities.streaming;+ const disabled=Boolean(installed)||!licensed||queued||busy||product.installability!=='supported'||!data.backend.capabilities.streaming;const scope=JSON.stringify([data.auth.username, data.auth.player,data.auth.stored,data.auth.running,data.backend.binaryPath,data.settings.market]);const identity=useRef(scope);identity.current=scope;useEffect(()=>{identity.current=scope;return()=>{identity.current='';};},[scope]);@@ -28,15 +31,23 @@ export function CatalogGameDetails({product,data,back,backLabel,toast}:{product:if(disabled||pending.current||!destination.trim())return;pending.current=true;setBusy(true);try{- if(await startInstall(catalogInstallRequest(product,destination))&&identity.current===scope)toast({kind:'success',message:ui('ui.added_to_install_queue_c755bb7',{game:product.title})});+ const request=storeMode?{...catalogInstallRequest(product,destination),source:'store' as const}:catalogInstallRequest(product,destination);+ if(await startInstall(request,()=>identity.current===scope&&(!storeMode||access.canInstall(product)))&&identity.current===scope)toast({kind:'success',message:ui('ui.added_to_install_queue_c755bb7',{game:product.title})});}catch(error){if(identity.current===scope)toast({kind:'error',message:error instanceof Error?error.message:String(error)});}finally{pending.current=false;setBusy(false);}}- const button=<button className="primary" data-gamepad-play disabled={disabled||!destination.trim()} onClick={()=>void install()}>{busy?<LoaderCircle className="spin"/>:installed?<Check/>:<Download/>}{installed?ui('ui.installed_f8b32f4'):queued?ui('ui.in_install_queue_7c818f2'):busy?ui('ui.preparing_5d1fa38'):ui('ui.install_569ca49')}</button>;+ const playDisabled=busy||installed?.installState!=='ready'||!data.backend.capabilities.run||!gameRuntimeAvailable(installed?.runtime,installed?.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[]);+ async function play(){+ if(!installed||playDisabled)return;setBusy(true);+ try{await window.launcher.launchGame(installed.id);}+ catch(error){if(identity.current===scope)toast({kind:'error',message:error instanceof Error?error.message:String(error)});}+ finally{if(identity.current===scope)setBusy(false);}+ }+ const button=installed?<button className="primary" data-gamepad-play disabled={playDisabled} onClick={()=>void play()}>{busy?<LoaderCircle className="spin"/>:<Play fill="currentColor"/>}{ui('ui.play_436e610')}</button>:licensed?<button className="primary" data-gamepad-play disabled={disabled||!destination.trim()} onClick={()=>void install()}>{busy?<LoaderCircle className="spin"/>:<Download/>}{queued?ui('ui.in_install_queue_7c818f2'):busy?ui('ui.preparing_5d1fa38'):ui('ui.install_569ca49')}</button>:null;return <GameDetails key={installed?.id??product.productId} game={installed??{id:'catalog:'+product.productId,title:product.title,publisher:product.publisher,heroUrl:product.heroUrl,coverUrl:product.posterUrl}}- detailId={product.productId} catalogProductId={installed?undefined:product.productId} data={data} back={back} backLabel={backLabel} play={<>{button}{product.storeUrl?<button className="secondary" onClick={()=>window.open(product.storeUrl,'_blank')}>{ui('ui.store_page_9c667df')}</button>:null}</>}+ detailId={product.productId} catalogProductId={installed?undefined:product.productId} data={data} back={back} backLabel={backLabel} play={<>{button}<button className="secondary" onClick={()=>window.open(product.storeUrl??`https://www.xbox.com/games/store/p/${product.productId}`,'_blank')}>{ui('ui.store_page_9c667df')}</button></>}notices={!installed?<section className="gd-install-options"><p className={product.installability==='supported'?'supported':'unsupported'}>{uiText(product.supportNote)}</p>{product.purchasePrice||product.includedWith?<div className="catalog-badges">{product.purchasePrice?<span>{product.purchasePrice}</span>:null}{product.includedWith?<span className="pass">{ui('store.available_with',{plan:product.includedWith})}</span>:null}</div>:null}- <label>{ui('ui.install_location_af47896')}<div className="input-action"><input value={destination} disabled={busy||queued} onChange={event=>setDestination(event.target.value)}/><button type="button" disabled={busy||queued} aria-label={ui('ui.choose_folder_3db7410')} onClick={async()=>{const value=await window.launcher.chooseDirectory(destination);if(value&&identity.current===scope)setDestination(value);}}><FolderOpen/></button></div></label>+ {licensed?<label>{ui('ui.install_location_af47896')}<div className="input-action"><input value={destination} disabled={busy||queued} onChange={event=>setDestination(event.target.value)}/><button type="button" disabled={busy||queued} aria-label={ui('ui.choose_folder_3db7410')} onClick={async()=>{const value=await window.launcher.chooseDirectory(destination);if(value&&identity.current===scope)setDestination(value);}}><FolderOpen/></button></div></label>:null}</section>:undefined}/>}diff --git a/src/renderer/PackageInstall.tsx b/src/renderer/PackageInstall.tsxindex 72e9a33..edca0e5 100644--- a/src/renderer/PackageInstall.tsx+++ b/src/renderer/PackageInstall.tsx@@ -8,18 +8,19 @@ export function catalogInstallRequest(product: Pick<CatalogProduct, 'productId'return { productId: product.productId, title: product.title, destination };}-type Install = (request: InstallRequest) => Promise<string | undefined>;+type Install = (request: InstallRequest, eligible?: () => boolean) => Promise<string | undefined>;const InstallContext = createContext<Install>(async () => { throw Error("Installation dialog is unavailable."); });export const usePackageInstall = () => useContext(InstallContext);export async function confirmedPackageInstall(request: InstallRequest,api: Pick<Window['launcher'], 'getInstallPlan' | 'startInstall'>,- confirm: (plan: InstallPlan) => Promise<string | undefined>, mounted: () => boolean): Promise<string | undefined> {+ confirm: (plan: InstallPlan) => Promise<string | undefined>, mounted: () => boolean, eligible: () => boolean = () => true): Promise<string | undefined> {+ if (!mounted() || !eligible()) return;const result = await api.getInstallPlan(request.productId, request.destination);- if (!mounted()) return;+ if (!mounted() || !eligible()) return;if (result.status === 'unavailable') throw Error("No supported Windows.Desktop MSIXVC package was found for this Store offer.");const selected = await confirm(result);- if (!selected || !mounted()) return;+ if (!selected || !mounted() || !eligible()) return;return api.startInstall({ ...request, selectedContentId: selected, selectionMarket: result.market });}@@ -55,13 +56,13 @@ export function PackageInstallProvider({ children }: { children: ReactNode }) {const mounted = useRef(true);useEffect(() => { mounted.current = true; return () => { mounted.current = false; pending.current?.(); }; }, []);function choose(id?: string) { pending.current?.(id); pending.current = undefined; setDialog(undefined); }- const install: Install = async request => {+ const install: Install = async (request, eligible) => {if (busy.current) throw Error("Finish the current package selection first.");busy.current = true;try {return await confirmedPackageInstall(request, window.launcher,result => new Promise<string | undefined>(resolve => { pending.current = resolve; setDialog({plan: result, destination: request.destination}); }),- () => mounted.current);+ () => mounted.current, eligible);} finally { busy.current = false; }};return <InstallContext.Provider value={install}>{children}{dialog ? <PackageDialog plan={dialog.plan} destination={dialog.destination} choose={choose} /> : null}</InstallContext.Provider>;diff --git a/src/renderer/account-library.test.tsx b/src/renderer/account-library.test.tsxindex aeb2bbe..506e8f2 100644--- a/src/renderer/account-library.test.tsx+++ b/src/renderer/account-library.test.tsx@@ -40,7 +40,7 @@ it.each(['supported', 'unsupported', 'unknown'] as const)('uses the Store %s badconst product: AccountLibraryPage['products'][number] = { productId: '9AAAAAAAAAAA', title: 'Owned & game', access: 'owned',description: '', categories: [], installability, supportNote: 'Package <reason>' };const html = renderToStaticMarkup(<LibraryProductCard product={product} present={false} downloading={false} canInstall install={() => {}} />);- const store = renderToStaticMarkup(<StoreProductCard product={product} selected={false} disabled={installability !== 'supported'} label="Install" select={() => {}} install={() => {}} />);+ const store = renderToStaticMarkup(<StoreProductCard licensed product={product} selected={false} disabled={installability !== 'supported'} label="Install" select={() => {}} install={() => {}} />);const badge = (text: string) => text.match(/<span class="catalog-support[^>]*>[\s\S]*?<\/span>/)?.[0];expect(badge(html)).toBe(badge(store));expect(html).toContain('<span>Owned</span>');diff --git a/src/renderer/catalog-game-details.test.tsx b/src/renderer/catalog-game-details.test.tsxindex 9b44594..5ed71cf 100644--- a/src/renderer/catalog-game-details.test.tsx+++ b/src/renderer/catalog-game-details.test.tsx@@ -4,19 +4,19 @@ import type {CatalogProduct} from '../shared/types';import {demoSnapshot} from '../shared/demo-data';import {CatalogGameDetails,catalogGameInstalled,catalogGameQueued} from './CatalogGameDetails';import {GameDetailsContent} from './GameDetails';-import {LibraryProductCard,StoreProductCard} from './App';+import {LibraryProductCard,StoreProductCard,StorePage} from './App';const product:CatalogProduct={productId:'9AAAAAAAAAAA',title:'Uninstalled game',description:'Description',publisher:'Studio',installability:'supported',supportNote:'Windows.Desktop MSIXVC',categories:[]};-it('renders the same full detail layout with Install, screenshots and achievements, without fabricated installation actions',()=>{+it('renders full public details with only a Store page action until a license is verified',()=>{const data=demoSnapshot();data.downloads=[];- const html=renderToStaticMarkup(<CatalogGameDetails product={product} data={data} back={()=>{}} toast={()=>{}}/>);- expect(html).toContain('game-details-page');expect(html).toContain('Not installed');expect(html).toContain('>Install</button>');expect(html).toContain('Screenshots');expect(html).toContain('Achievements');- expect(html).toContain('Install location');+ const html=renderToStaticMarkup(<CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/>);+ expect(html).toContain('game-details-page');expect(html).toContain('Not installed');expect(html).not.toContain('>Install</button>');expect(html).toContain('Store page');expect(html).toContain('Screenshots');expect(html).toContain('Achievements');+ expect(html).not.toContain('Install location');expect(html).not.toMatch(/>Play<|>Manage<|Installation details|Executable|>Imported</);expect(html).toContain(`data-gamepad-detail="${product.productId}"`);});it.each(['unsupported','unknown'] as const)('keeps %s products viewable without enabling installation',installability=>{- const html=renderToStaticMarkup(<CatalogGameDetails product={{...product,installability}} data={demoSnapshot()} back={()=>{}} toast={()=>{}}/>);- expect(html).toMatch(/<button[^>]*data-gamepad-play[^>]*disabled=""/);expect(html).toContain('Screenshots');expect(html).toContain('Achievements');+ const html=renderToStaticMarkup(<CatalogGameDetails storeMode product={{...product,installability}} data={demoSnapshot()} back={()=>{}} toast={()=>{}}/>);+ expect(html).not.toContain('data-gamepad-play');expect(html).toContain('Screenshots');expect(html).toContain('Achievements');});it('does not mistake an unrelated imported game without a Store ID for an installed catalog game',()=>{const data=demoSnapshot();data.games=[{...data.games[0],storeId:undefined}];data.downloads=[];@@ -34,7 +34,17 @@ it('keeps product-card detail clicks independent from installation and Store foclibrary.props.children[0].props.onClick();expect(calls).toEqual([['open',product.productId]]);library.props.children[1].props.onClick();expect(calls.at(-1)).toEqual(['install',product.productId]);calls.length=0;- const store=StoreProductCard({product,selected:false,disabled:false,label:'Install',select:(p,open)=>calls.push(['select',p.productId,open]),install:p=>calls.push(['install',p.productId])});+ const store=StoreProductCard({licensed:true,product,selected:false,disabled:false,label:'Install',select:(p,open)=>calls.push(['select',p.productId,open]),install:p=>calls.push(['install',p.productId])});store.props.children[0].props.onFocus();expect(calls).toEqual([['select',product.productId,false]]);store.props.children[0].props.onClick();expect(calls.at(-1)).toEqual(['select',product.productId,true]);});++it('applies strict public Store eligibility without changing the existing Library detail verification route',()=>{+ const data=demoSnapshot();data.games=[];data.downloads=[];+ const store=renderToStaticMarkup(<CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/>);+ const library=renderToStaticMarkup(<CatalogGameDetails product={product} data={data} back={()=>{}} toast={()=>{}}/>);+ expect(store).not.toContain('>Install</button>');expect(store).not.toContain('Install location');+ expect(library).toContain('>Install</button>');expect(library).toContain('Install location');+ const page=renderToStaticMarkup(<StorePage data={data} toast={()=>{}} go={()=>{}} initialQuery=""/>);+ expect(page).not.toContain('manual-install');expect(page).not.toContain('Install unlisted ID');+});diff --git a/src/renderer/gamepad-selection.test.tsx b/src/renderer/gamepad-selection.test.tsxindex 0fc69e8..fdebd26 100644--- a/src/renderer/gamepad-selection.test.tsx+++ b/src/renderer/gamepad-selection.test.tsx@@ -44,7 +44,7 @@ it('includes explicit library header actions without automatic activation', () =});it.each([false, true])('Store card focus only selects, activation opens details and installation stays guarded (disabled=%s)', disabled => {- const html = renderToStaticMarkup(<StoreProductCard product={queuedProduct} selected disabled={disabled} label={disabled ? 'In Install Queue' : 'Install'} select={() => {}} install={() => {}} />);+ const html = renderToStaticMarkup(<StoreProductCard licensed product={queuedProduct} selected disabled={disabled} label={disabled ? 'In Install Queue' : 'Install'} select={() => {}} install={() => {}} />);expect(html).toContain('class="catalog-card selected" data-gamepad-card');expect(html).toMatch(/<button[^>]*data-gamepad-auto-select="focus"[^>]*data-gamepad-detail-target/);expect(html).not.toContain('data-gamepad-card-activate');diff --git a/src/renderer/store-access.test.tsx b/src/renderer/store-access.test.tsxnew file mode 100644index 0000000..d79f2ac--- /dev/null+++ b/src/renderer/store-access.test.tsx@@ -0,0 +1,78 @@+// @vitest-environment jsdom+import {act} from 'react';+import {createRoot} from 'react-dom/client';+import {afterEach,expect,it,vi} from 'vitest';+import {CatalogGameDetails} from './CatalogGameDetails';+import {PackageInstallProvider,confirmedPackageInstall} from './PackageInstall';+import {demoSnapshot} from '../shared/demo-data';+import {freshStoreAccess,storeProductLicensed,useStoreAccess,type StoreAccessEvidence} from './store-access';+vi.mock('./GameDetails',()=>({GameDetails:({play,notices}:{play:React.ReactNode;notices:React.ReactNode})=><main>{play}{notices}</main>}));+const product={productId:'9AAAAAAAAAAA',installProductId:'9BBBBBBBBBBB',title:'Retail edition',description:'',categories:[],installability:'supported' as const,supportNote:'Supported',includedWith:'Game Pass Ultimate'};+const evidence=(data=demoSnapshot()):StoreAccessEvidence=>({account:data.auth.username!,backend:data.backend.binaryPath!,market:'US',configuredMarket:data.settings.market,checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60_000).toISOString(),accessByProductId:{[product.productId]:'owned'}});+afterEach(()=>{vi.restoreAllMocks();vi.unstubAllGlobals();});+it('accepts exact owned/Game Pass Store evidence and rejects marketing, other, stale, expired and wrong scope',()=>{+ const data=demoSnapshot(),value=evidence(data);expect(storeProductLicensed(value,data,product)).toBe(true);+ value.accessByProductId[product.productId]='gamepass';expect(storeProductLicensed(value,data,product)).toBe(true);+ value.accessByProductId[product.productId]='other';expect(storeProductLicensed(value,data,product)).toBe(false);+ delete value.accessByProductId[product.productId];value.accessByProductId[product.installProductId]='owned';expect(storeProductLicensed(value,data,product)).toBe(false);+ for(const patch of [{account:'another-store'},{backend:'/other'},{configuredMarket:'CZ'},{expiresAt:new Date(Date.now()-1).toISOString()},{checkedAt:'bad'}])expect(freshStoreAccess({...evidence(data),...patch},data)).toBe(false);+ data.auth.player='another-player';expect(storeProductLicensed(evidence(data),data,product)).toBe(true);+ data.auth.running=true;expect(storeProductLicensed(evidence(data),data,product)).toBe(false);data.auth.running=false;data.auth.stored=false;expect(storeProductLicensed(value,data,product)).toBe(false);+});+it('hides Install and location while access is pending/error, shows verified access and clears it on Store switch',async()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);+ const data=demoSnapshot();data.games=[];data.downloads=[];+ let resolve!:(value:StoreAccessEvidence)=>void;+ const read=vi.fn(()=>new Promise<StoreAccessEvidence>(done=>resolve=done));+ window.launcher={getStoreAccess:read} as unknown as Window['launcher'];+ const node=document.createElement('div'),root=createRoot(node);+ const render=()=>act(async()=>root.render(<CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/>));+ try{+ await render();expect(node.textContent).toContain('Store page');expect(node.querySelector('input')).toBeNull();expect(node.querySelector('[data-gamepad-play]')).toBeNull();+ await act(async()=>resolve(evidence(data)));expect(node.querySelector('[data-gamepad-play]')?.textContent).toBe('Install');expect(node.querySelector('input')).not.toBeNull();+ data.auth={...data.auth,username:'different-store'};read.mockRejectedValueOnce(Error('unavailable'));await render();expect(node.querySelector('[data-gamepad-play]')).toBeNull();expect(node.querySelector('input')).toBeNull();+ }finally{await act(async()=>root.unmount());}+});+it('checks eligibility again after package resolution and after a held package choice',async()=>{+ const request={productId:product.productId,title:product.title,destination:'/synthetic/game',source:'store' as const};+ let eligible=true,resolve!:(value:any)=>void,choose!:(value:string)=>void;+ const api={getInstallPlan:vi.fn(()=>new Promise<any>(done=>resolve=done)),startInstall:vi.fn(async()=> 'queued')};+ const confirm=vi.fn(()=>new Promise<string>(done=>choose=done));+ const first=confirmedPackageInstall(request,api,confirm,()=>true,()=>eligible);eligible=false;resolve({status:'ready',market:'US'});await first;expect(confirm).not.toHaveBeenCalled();+ eligible=true;const second=confirmedPackageInstall(request,api,confirm,()=>true,()=>eligible);resolve({status:'ready',market:'US'});await vi.waitFor(()=>expect(confirm).toHaveBeenCalled());eligible=false;choose('synthetic');await second;expect(api.startInstall).not.toHaveBeenCalled();+});+it('keeps installed Play available without Store-license evidence',async()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);const data=demoSnapshot();data.auth.stored=false;data.settings.winePath='/synthetic/wine';data.games=[{...data.games[0],storeId:product.productId,installState:'ready'}];data.downloads=[];+ window.launcher={launchGame:vi.fn(async()=>{})} as unknown as Window['launcher'];const node=document.createElement('div'),root=createRoot(node);+ try{await act(async()=>root.render(<PackageInstallProvider><CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/></PackageInstallProvider>));const play=node.querySelector<HTMLButtonElement>('[data-gamepad-play]')!;expect(play.textContent).toBe('Play');expect(play.disabled).toBe(false);await act(async()=>play.click());expect(window.launcher.launchGame).toHaveBeenCalledWith(data.games[0].id);expect(node.querySelector('input')).toBeNull();}finally{await act(async()=>root.unmount());}+});++it('expires an open installation form at the actual access boundary',async()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);vi.useFakeTimers();+ const data=demoSnapshot();data.games=[];data.downloads=[];+ const value={...evidence(data),expiresAt:new Date(Date.now()+100).toISOString()};+ const read=vi.fn().mockResolvedValueOnce(value).mockRejectedValue(Error('expired'));+ window.launcher={getStoreAccess:read} as unknown as Window['launcher'];const node=document.createElement('div'),root=createRoot(node);+ try{await act(async()=>root.render(<CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/>));expect(node.querySelector('input')).not.toBeNull();await act(async()=>vi.advanceTimersByTimeAsync(101));expect(node.querySelector('input')).toBeNull();expect(node.querySelector('[data-gamepad-play]')).toBeNull();}finally{await act(async()=>root.unmount());vi.useRealTimers();}+});+it('keeps license scope independent of the player and rejects old callbacks after Store A to B to A',async()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);const data=demoSnapshot();let access!:ReturnType<typeof useStoreAccess>;+ const read=vi.fn(async()=>evidence(data));window.launcher={getStoreAccess:read} as unknown as Window['launcher'];+ function Fixture(){access=useStoreAccess(data);return null;}+ const root=createRoot(document.createElement('div')),render=()=>act(async()=>root.render(<Fixture/>));+ try{await render();const old=access.canInstall;expect(old(product)).toBe(true);const store=data.auth.username;data.auth={...data.auth,player:'personal'};await render();expect(read).toHaveBeenCalledTimes(1);expect(access.canInstall(product)).toBe(true);+ data.auth={...data.auth,username:'store-B'};await render();data.auth={...data.auth,username:store};await render();expect(access.canInstall(product)).toBe(true);expect(old(product)).toBe(false);+ }finally{await act(async()=>root.unmount());}+});++it('invalidates a held package confirmation when its owning Store surface unmounts',async()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);const data=demoSnapshot();let access!:ReturnType<typeof useStoreAccess>;+ window.launcher={getStoreAccess:vi.fn(async()=>evidence(data))} as unknown as Window['launcher'];+ function Fixture(){access=useStoreAccess(data);return null;}+ const root=createRoot(document.createElement('div'));await act(async()=>root.render(<Fixture/>));+ const guard=access.canInstall;expect(guard(product)).toBe(true);+ let choose!:(id:string)=>void;const confirm=vi.fn(()=>new Promise<string>(resolve=>choose=resolve));+ const api={getInstallPlan:vi.fn(async()=>({status:'ready',market:'US'} as any)),startInstall:vi.fn(async()=> 'queued')};+ const pending=confirmedPackageInstall({productId:product.productId,title:product.title,destination:'/synthetic'},api,confirm,()=>true,()=>guard(product));+ await vi.waitFor(()=>expect(confirm).toHaveBeenCalled());await act(async()=>root.unmount());expect(guard(product)).toBe(false);choose('synthetic');await pending;expect(api.startInstall).not.toHaveBeenCalled();+});diff --git a/src/renderer/store-access.ts b/src/renderer/store-access.tsnew file mode 100644index 0000000..0e69949--- /dev/null+++ b/src/renderer/store-access.ts@@ -0,0 +1,45 @@+import {useEffect,useRef,useState} from 'react';+import type {AppSnapshot,CatalogProduct,LibraryAccess} from '../shared/types';++/** Account evidence is separate from public Store metadata and marketing labels. */+export interface StoreAccessEvidence {+ account:string;backend:string;market:string;configuredMarket:string;checkedAt:string;expiresAt:string;+ accessByProductId:Record<string,LibraryAccess>;+}+export function storeAccessScope(data:AppSnapshot):string {+ return JSON.stringify([data.auth.stored,data.auth.username,data.auth.running,data.backend.available,data.backend.binaryPath,data.settings.market]);+}+export function freshStoreAccess(evidence:StoreAccessEvidence|undefined,data:AppSnapshot,now=Date.now()):boolean {+ if(!evidence||data.auth.stored!==true||data.auth.running||!data.auth.username||!data.backend.available)return false;+ const checked=Date.parse(evidence.checkedAt),expires=Date.parse(evidence.expiresAt);+ return evidence.account===data.auth.username&&evidence.backend===data.backend.binaryPath&&evidence.configuredMarket===data.settings.market+ &&Number.isFinite(checked)&&Number.isFinite(expires)&&expires>checked&&checked<=now+60_000&&now<expires&&expires<=checked+5*60_000;+}+export function storeProductLicensed(evidence:StoreAccessEvidence|undefined,data:AppSnapshot,product:Pick<CatalogProduct,'productId'|'installability'>,now=Date.now()):boolean {+ if(product.installability!=='supported'||!freshStoreAccess(evidence,data,now))return false;+ const access=evidence!.accessByProductId?.[product.productId.toUpperCase()];+ return access==='owned'||access==='gamepass';+}+export function useStoreAccess(data:AppSnapshot, enabled=true) {+ const [evidence,setEvidence]=useState<StoreAccessEvidence>();+ const alive=useRef(true);+ const [revision,refresh]=useState(0);+ const scope=storeAccessScope(data),current=useRef({data,scope,evidence,epoch:0});+ const epoch=current.current.epoch+(current.current.scope===scope?0:1);current.current={data,scope,evidence,epoch};+ useEffect(()=>{+ let active=true,timer:ReturnType<typeof setTimeout>|undefined;+ setEvidence(undefined);+ if(enabled&&data.auth.stored===true&&!data.auth.running&&data.auth.username&&data.backend.available){+ const api=window.launcher as Window['launcher']&{getStoreAccess?:()=>Promise<StoreAccessEvidence>};+ void api.getStoreAccess?.().then(value=>{+ if(!active||current.current.scope!==scope||!freshStoreAccess(value,current.current.data))return;+ setEvidence(value);+ timer=setTimeout(()=>{if(active){setEvidence(undefined);refresh(value=>value+1);}},Math.max(1,Date.parse(value.expiresAt)-Date.now()));+ }).catch(()=>{/* Unknown account access has no installation action. */});+ }+ return()=>{active=false;if(timer)clearTimeout(timer);};+ },[scope,revision,enabled]);+ useEffect(()=>{alive.current=true;return()=>{alive.current=false;current.current.evidence=undefined;current.current.epoch++;};},[]);+ const canInstall=(product:Pick<CatalogProduct,'productId'|'installability'>)=>alive.current&¤t.current.epoch===epoch&¤t.current.scope===scope&&storeProductLicensed(current.current.evidence,current.current.data,product);+ return {canInstall};+}