Skip to content

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

TypeScript

Filter Store offers and verify account access before installation

domsvoboda5d1ecfd79c89
diff --git a/src/main/account-library.test.ts b/src/main/account-library.test.ts
index ebe07d7..053d918 100644
--- a/src/main/account-library.test.ts
+++ b/src/main/account-library.test.ts
@@ -427,3 +427,31 @@ it('loads owned access for a launch while it prepares, waits only briefly and ne
failing.select('[email protected]', '/backend', 'US');
expect(await failing.startLaunchAccess()(1_000)).toEqual({});
});
+
+it('Store access is artwork-free, bounded by parent expiry and scoped to configured neutral market',async()=>{
+ const end=new Date(Date.now()+45_000).toISOString();
+ const catalog=vi.fn(async(ids:string[])=>ids.map(product));
+ // Reader response must match the actual resolved market, not the setting sentinel.
+ const scoped=new AccountLibrary(catalog,async()=>output([row(A,{satisfiedByProductId:'CFQ7TTC0KGQ8'}),row('CFQ7TTC0KGQ8',{endDate:end})],'[email protected]','CZ'));
+ scoped.select('[email protected]','/backend','CZ');
+ const result=await scoped.storeAccess('neutral');
+ expect(result).toMatchObject({account:'[email protected]',backend:'/backend',market:'CZ',configuredMarket:'neutral',expiresAt:end,accessByProductId:{[A]:'gamepass'}});
+ expect(catalog).not.toHaveBeenCalled();
+});
+it('Store access rejects account/backend/market changes and same-account reset during an in-flight read',async()=>{
+ for(const change of ['account','backend','market','reset']){
+ let release!:(value:string)=>void;
+ const catalog=vi.fn(async(ids:string[])=>ids.map(product));
+ const library=new AccountLibrary(catalog,()=>new Promise(resolve=>{release=resolve;}));
+ library.select('[email protected]','/backend','US');const pending=library.storeAccess();
+ if(change==='reset')library.reset();else library.select(change==='account'?'[email protected]':'[email protected]',change==='backend'?'/other':'/backend',change==='market'?'CZ':'US');
+ release(output());await expect(pending).rejects.toThrow('changed');expect(catalog).not.toHaveBeenCalled();
+ }
+});
+it('does not extend an entitlement that expires between access evaluation and response',async()=>{
+ const now=Date.now(),end=now+1000;
+ const library=new AccountLibrary(async ids=>ids.map(product),async()=>output([row(A,{endDate:new Date(end).toISOString()})]));
+ library.select('[email protected]','/backend','US');await library.access();
+ let calls=0;const clock=vi.spyOn(Date,'now').mockImplementation(()=>++calls<3?now:end+1);
+ try{await expect(library.storeAccess()).rejects.toThrow('expired');}finally{clock.mockRestore();}
+});
diff --git a/src/main/account-library.ts b/src/main/account-library.ts
index 7629359..b7fa572 100644
--- a/src/main/account-library.ts
+++ b/src/main/account-library.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import { spawnTracked } from './process.js';
import { backendDiagnostic } from './backend-diagnostics.js';
import { sessionFailureMessage } from './session-errors.js';
-import type { AccountLibraryPage, CatalogProduct } from '../shared/types.js';
+import type { AccountLibraryPage, CatalogProduct, StoreAccess } from '../shared/types.js';
interface Entitlement {
productId: string; status: string; isTrial: boolean; sharingSource: string;
@@ -189,6 +189,24 @@ export class AccountLibrary {
}
return { checkedAt: cached.checkedAt, accessByProductId };
}
+ async storeAccess(configuredMarket=this.identity?.market??'US'): Promise<StoreAccess> {
+ const identity=this.identity,generation=this.generation;
+ if(!identity)throw Error('Sign in before checking Store access.');
+ const cached=await this.load();
+ const now=Date.now();
+ const accessByProductId:StoreAccess['accessByProductId']={};
+ for(const product of cached.entries.keys()){const kind=entitlementKind(product,cached.entries,now);if(kind)accessByProductId[product]=kind;}
+ if(generation!==this.generation||identity!==this.identity||cached!==this.cached)throw Error('Account library changed. Refresh this page.');
+ // Conservative across all known graph rows, including subscription parents.
+ // This may refresh early, never beyond a known entitlement expiration.
+ let until=cached.until;
+ for(const row of cached.entries.values()){
+ const end=Date.parse(row.endDate);
+ if(row.status==='Active'&&!row.isTrial&&end>now)until=Math.min(until,end);
+ }
+ if(until<=Date.now())throw Error('Store access expired. Refresh this page.');
+ return {configuredMarket,account:identity.account,market:identity.market,checkedAt:cached.checkedAt,accessByProductId,backend:identity.binary,expiresAt:new Date(until).toISOString()};
+ }
async get(kind: Kind, cursor?: string, refresh = false, sort?: AccountLibraryPage['sort']): Promise<AccountLibraryPage> {
if (kind !== 'all' && kind !== 'owned' && kind !== 'gamepass' && kind !== 'other') throw Error('Invalid library filter.');
if (sort !== undefined && (sort !== 'recent-gamepass' || kind !== 'gamepass')) throw Error('Invalid library order.');
diff --git a/src/main/catalog-access.test.ts b/src/main/catalog-access.test.ts
new file mode 100644
index 0000000..c859c3a
--- /dev/null
+++ b/src/main/catalog-access.test.ts
@@ -0,0 +1,24 @@
+import {expect,it} from 'vitest';
+import {assertStoreOfferAccess} from './catalog-access.js';
+const now=Date.parse('2026-11-03T09:00:00Z'),id='9AAAAAAAAAAA';
+const context={account:'store',backend:'/backend',market:'US'};
+const access={...context,configuredMarket:'US',checkedAt:new Date(now).toISOString(),expiresAt:new Date(now+60_000).toISOString(),accessByProductId:{[id]:'owned' as const}};
+it('requires current Store/backend/market and exact owned or Game Pass offer evidence',()=>{
+ expect(()=>assertStoreOfferAccess(access,id,context,now)).not.toThrow();
+ expect(()=>assertStoreOfferAccess({...access,accessByProductId:{[id]:'gamepass'}},id,context,now)).not.toThrow();
+ for(const change of [{account:'player'},{backend:'/other'},{market:'CZ'}])expect(()=>assertStoreOfferAccess(access,id,{...context,...change},now)).toThrow();
+ for(const map of [{},{[id]:'other' as const}])expect(()=>assertStoreOfferAccess({...access,accessByProductId:map},id,context,now)).toThrow();
+ expect(()=>assertStoreOfferAccess(access,'9BBBBBBBBBBB',context,now)).toThrow();
+});
+it('rejects expired, malformed and overlong leases independently of branding',()=>{
+ for(const expiresAt of ['invalid',new Date(now).toISOString(),new Date(now+6*60_000).toISOString()])expect(()=>assertStoreOfferAccess({...access,expiresAt},id,context,now)).toThrow();
+});
+it('persists Store provenance across paused download restoration',async()=>{
+ const fs=await import('node:fs/promises'),path=await import('node:path'),{StateStore}=await import('./store.js');
+ const {tmpdir}=await import('node:os');
+ const root=await fs.mkdtemp(path.join(tmpdir(),'store-access-state-'));
+ try{
+ const store=new StateStore(root);await store.load();await store.addDownload({source:'store',id:'synthetic',title:'Synthetic',productId:id,destination:'/synthetic',status:'queued',progress:null,phase:'queued',log:[],startedAt:new Date().toISOString()});
+ const reopened=new StateStore(root);await reopened.load();expect(reopened.downloads[0]).toMatchObject({source:'store',status:'paused'});
+ }finally{await fs.rm(root,{recursive:true,force:true});}
+});
diff --git a/src/main/catalog-access.ts b/src/main/catalog-access.ts
new file mode 100644
index 0000000..4fe89dc
--- /dev/null
+++ b/src/main/catalog-access.ts
@@ -0,0 +1,11 @@
+import type {StoreAccess} from '../shared/types.js';
+
+/** A Store offer must have current account evidence, never public branding. */
+export function assertStoreOfferAccess(access:StoreAccess, productId:string, context:{account?:string;backend?:string;market:string}, now=Date.now()):void {
+ const expiry=Date.parse(access.expiresAt), checked=Date.parse(access.checkedAt);
+ if(access.account!==context.account||access.backend!==context.backend||access.market!==context.market
+ ||!Number.isFinite(expiry)||!Number.isFinite(checked)||checked>now+60_000||expiry<=now||expiry>checked+5*60_000
+ ||!['owned','gamepass'].includes(access.accessByProductId[productId]??'')){
+ throw Error('No current verified access to this Store offer. Open its Store page or refresh account access.');
+ }
+}
diff --git a/src/main/catalog-install-ipc.test.ts b/src/main/catalog-install-ipc.test.ts
new file mode 100644
index 0000000..9db0fdd
--- /dev/null
+++ b/src/main/catalog-install-ipc.test.ts
@@ -0,0 +1,57 @@
+import {readFileSync} from 'node:fs';
+import path from 'node:path';
+import {runInNewContext} from 'node:vm';
+import ts from 'typescript';
+import {expect,it,vi} from 'vitest';
+import {assertStoreOfferAccess} from './catalog-access.js';
+
+// Execute the actual main-process preparation, queue closure and resume IPC.
+// All side effects are synthetic; no Electron, account, backend or game starts.
+const source=readFileSync(new URL('./index.ts',import.meta.url),'utf8');
+const parsed=ts.createSourceFile('index.ts',source,ts.ScriptTarget.Latest,true);
+const names=new Set(['storeAccess','verifyStoreInstall','startInstall','prepareInstall']);
+const functions=parsed.statements.filter(node=>ts.isFunctionDeclaration(node)&&node.name&&names.has(node.name.text)).map(node=>node.getText(parsed)).join('\n');
+const start=source.indexOf(" ipcMain.handle('resume-download'",source.indexOf('function registerIpc():'));
+const resume=source.slice(start,source.indexOf(" ipcMain.handle('remove-download'",start));
+const code=ts.transpileModule(functions+'\n'+resume+'\nglobalThis.install=startInstall;', {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+const id='9AAAAAAAAAAA';
+function fixture(){
+ const handlers=new Map<string,Function>(),jobs:any[]=[],downloads:any[]=[];
+ let granted=true;
+ const plan=vi.fn(async()=>({choices:[{supported:true,contentId:'content',kind:'Game',productId:id}]}));
+ const run=vi.fn(async()=>{}),prepare=vi.fn(async()=>{});
+ const context:any={path,assertStoreOfferAccess,authState:{stored:true,running:false,username:'store'},backend:{current:{binaryPath:'/backend',capabilities:{library:true,packageSelection:true,streamingControls:true}},externalDownloadRunning:async()=>false},
+ store:{settings:{market:'US',runtimeRoot:'/synthetic/runtime'},games:[],downloads,addDownload:async(task:any)=>{downloads.push(task);},updateDownload:async()=>{},removeDownload:async()=>{}},
+ currentMarket:()=> 'US',accountLibrary:{select:vi.fn(),storeAccess:async()=>({account:'store',backend:'/backend',market:'US',configuredMarket:'US',checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60_000).toISOString(),accessByProductId:granted?{[id]:'owned'}:{}})},
+ stopGameUpdateCheck:async()=>{},ensureIdle:()=>{},prepareSystemWallet:async()=>{},preparingInstall:false,gameOperation:undefined,requireBackend:()=>'/backend',safeProductId:(value:string)=>value,
+ installPlans:{get:plan},installSelection:()=> 'content',contentParentForChoice:()=>undefined,prepareContentInstall:vi.fn(async()=> 'content-id'),assertInstallDestination:async(value:string)=>value,app:{getPath:()=>'/synthetic/user'},randomUUID:()=> 'queued-id',
+ downloadCleanup:{prepare,inheritResume:async()=>{}},enrichDownloadCovers:async()=>{},installQueue:{enqueue:(job:any)=>jobs.push(job)},emitSnapshot:()=>{},shutdownStarted:false,runDownload:run,
+ downloadCancellations:new Set(),downloadControls:new Map(),operations:new Map(),structuredClone,
+ ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)}};
+ runInNewContext(code,context);
+ return {context,handlers,jobs,downloads,plan,run,prepare,revoke:()=>{granted=false;},request:{source:'store',productId:id,title:'Synthetic',destination:'/synthetic/game'}};
+}
+it('denied Store offer never reaches package preparation or queue/backend',async()=>{
+ const f=fixture();f.revoke();await expect(f.context.install(f.request)).rejects.toThrow('No current verified access');
+ expect(f.plan).not.toHaveBeenCalled();expect(f.jobs).toHaveLength(0);expect(f.run).not.toHaveBeenCalled();expect(f.prepare).not.toHaveBeenCalled();
+});
+it('rechecks revoked access in the actual queued closure before backend or download cleanup',async()=>{
+ const f=fixture();await f.context.install(f.request);expect(f.jobs).toHaveLength(1);expect(f.downloads[0].source).toBe('store');
+ f.revoke();await expect(f.jobs[0].run()).rejects.toThrow('No current verified access');expect(f.run).not.toHaveBeenCalled();expect(f.prepare).not.toHaveBeenCalled();
+});
+it('retains the Store guard through actual saved-download resume IPC',async()=>{
+ const f=fixture();f.downloads.push({...f.request,id:'paused',status:'paused'});f.revoke();
+ await expect(f.handlers.get('resume-download')!({},'paused')).rejects.toThrow('No current verified access');
+ expect(f.downloads[0].status).toBe('paused');expect(f.plan).not.toHaveBeenCalled();expect(f.jobs).toHaveLength(0);expect(f.run).not.toHaveBeenCalled();
+});
+it('still queues and starts a currently verified Store offer',async()=>{
+ const f=fixture();await f.context.install(f.request);await f.jobs[0].run();expect(f.prepare).toHaveBeenCalledOnce();expect(f.run).toHaveBeenCalledOnce();
+});
+
+it('does not lose Store offer provenance through the installed-content redirect',async()=>{
+ const f=fixture();f.context.contentParentForChoice=()=> 'installed-parent';
+ await expect(f.context.install(f.request)).rejects.toThrow('Manage content');
+ expect(f.context.prepareContentInstall).not.toHaveBeenCalled();expect(f.jobs).toHaveLength(0);expect(f.run).not.toHaveBeenCalled();
+ // Existing Library/manual related-content routing remains available.
+ await expect(f.context.install({...f.request,source:undefined})).resolves.toBe('content-id');expect(f.context.prepareContentInstall).toHaveBeenCalledOnce();
+});
diff --git a/src/main/catalog.test.ts b/src/main/catalog.test.ts
index bc1d39e..f5f9ee9 100644
--- a/src/main/catalog.test.ts
+++ b/src/main/catalog.test.ts
@@ -209,3 +209,44 @@ describe('CatalogService', () => {
expect((await new CatalogService(logo).artwork(['9GAME123'], 'US')).size).toBe(0);
});
});
+
+describe('Store-only offer policy',()=>{
+ const sku=(price:number,props:Record<string,unknown>={},type='full')=>({Sku:{SkuType:type,Properties:props},Availabilities:[{OrderManagementData:{Price:{MSRP:price,ListPrice:price}}}]});
+ const parse=(skus:unknown[],extra={},policy:'store'|'library'='store')=>parseCatalogProducts({productsList:[{productId:'9AAAAAAAAAAA',title:'Free Spirit',isGame:true,...extra}]},{Products:[{ProductId:'9AAAAAAAAAAA',DisplaySkuAvailabilities:skus}]},policy);
+ it('excludes structured free, trial and demo but retains paid and missing/malformed prices',()=>{
+ expect(parse([sku(0)])).toEqual([]);
+ expect(parse([sku(0,{IsTrial:true})])).toEqual([]);
+ expect(parse([sku(0,{},'demo')])).toEqual([]);
+ expect(parse([sku(10,{IsDemo:true})])).toEqual([]);
+ expect(parse([null,{},sku(0,{IsTrial:true})])).toEqual([]);
+ expect(parse([sku(25,{IsTrial:false})],{plaintextPassName:'PC Game Pass'})).toHaveLength(1);
+ expect(parse([])).toHaveLength(1);
+ expect(parse([],{priceInfo:{displayPrice:'Free',price:null}})).toHaveLength(1);
+ expect(parse([],{priceInfo:{price:'0',isFree:'true'}})).toHaveLength(1);
+ expect(parse([],{priceInfo:{price:0}})).toEqual([]);
+ });
+ it('uses retail SKU metadata without mistaking an optional trial for the full edition',()=>{
+ expect(parse([sku(0,{IsTrial:true}),sku(40,{IsTrial:false})])).toHaveLength(1);
+ expect(parse([sku(40,{IsTrial:false}),sku(0,{IsTrial:true})])).toHaveLength(1);
+ expect(parse([sku(0,{IsTrial:true})],{},'library')).toHaveLength(1);
+ expect(parse([sku(0)],{},'library')).toHaveLength(1);
+ expect(parse([sku(0),{Sku:{Properties:{IsTrial:false}}}])).toHaveLength(1);
+ expect(parse([{Sku:{Properties:{IsTrial:false}},Availabilities:[{OrderManagementData:{Price:{MSRP:'malformed',ListPrice:0}}}]}])).toHaveLength(1);
+ });
+ it('never resolves package support or bundle children from explicit trial/preorder SKUs',()=>{
+ const pkg={Packages:[{PackageFormat:'MSIXVC',PlatformDependencies:[{PlatformName:'Windows.Desktop'}]}]};
+ expect(parse([sku(0,{...pkg,IsTrial:true}),sku(30,{IsTrial:false})])[0].installability).not.toBe('supported');
+ expect(parse([sku(30,{...pkg,IsPreOrder:true}),sku(30,{IsTrial:false})])[0].installability).not.toBe('supported');
+ });
+ it('handles malformed rows without treating absent prices as free',()=>{
+ expect(parseCatalogProducts({productsList:[null,{},false,{productId:'9AAAAAAAAAAA',title:'Valid'}]}, {Products:[null]},'store')).toHaveLength(1);
+ });
+ it('applies the same policy to actual search and featured service paths while preserving licensed games',async()=>{
+ const id='9AAAAAAAAAAA';
+ const fetcher=async(input:unknown)=>new Response(JSON.stringify(String(input).includes('displaycatalog')?{Products:[{ProductId:id,ProductType:'Game',LocalizedProperties:[{ProductTitle:'Owned free game'}],DisplaySkuAvailabilities:[sku(0)]}]}:{productsList:[{productId:id,title:'Free game',isGame:true}]}),{status:200});
+ const service=new CatalogService(fetcher as typeof fetch);
+ expect((await service.search('Free game','US')).products).toEqual([]);
+ expect((await service.featured('US')).products).toEqual([]);
+ expect(await service.licensedProducts([id],'US')).toHaveLength(1);
+ });
+});
diff --git a/src/main/catalog.ts b/src/main/catalog.ts
index ea619a8..3221d95 100644
--- a/src/main/catalog.ts
+++ b/src/main/catalog.ts
@@ -159,6 +159,7 @@ function directPackageSupport(product: Record<string, unknown> | undefined): Pac
for (const availability of skus) {
const sku = object(object(availability)?.Sku);
const properties = object(sku?.Properties);
+ if(properties?.IsTrial===true||properties?.IsDemo===true||properties?.IsPreOrder===true||['trial','demo'].includes(string(sku?.SkuType)?.toLowerCase()??''))continue;
const packages = Array.isArray(properties?.Packages) ? properties.Packages : [];
for (const entry of packages) {
const pkg = object(entry);
@@ -184,7 +185,9 @@ function bundleReferences(product: Record<string, unknown> | undefined): BundleR
const references = new Map<string, boolean>();
const skus = Array.isArray(product?.DisplaySkuAvailabilities) ? product.DisplaySkuAvailabilities : [];
for (const availability of skus) {
- const properties = object(object(object(availability)?.Sku)?.Properties);
+ const sku=object(object(availability)?.Sku);
+ const properties = object(sku?.Properties);
+ if(properties?.IsTrial===true||properties?.IsDemo===true||properties?.IsPreOrder===true||['trial','demo'].includes(string(sku?.SkuType)?.toLowerCase()??''))continue;
const bundled = Array.isArray(properties?.BundledSkus) ? properties.BundledSkus : [];
for (const entry of bundled) {
const record = object(entry);
@@ -244,7 +247,43 @@ function packageSupport(productId: string, details: Map<string, Record<string, u
};
}
-export function parseCatalogProducts(search: StoreSearchResponse, catalog: DisplayCatalogResponse): CatalogProduct[] {
+/** Public browsing excludes positively identified free/demo/trial offers.
+ * Missing prices remain unknown, and subscription branding is never a price. */
+export function excludedStoreOffer(search: Record<string, unknown>, detail?: Record<string, unknown>): boolean {
+ const props=object(detail?.Properties);
+ if (search.isDemo===true || search.isTrial===true || props?.IsDemo===true || props?.IsTrial===true) return true;
+ const rows=Array.isArray(detail?.DisplaySkuAvailabilities)?detail.DisplaySkuAvailabilities:[];
+ let retail=false, paid=false, free=false, unknownRetail=false, trial=false;
+ for(const entry of rows){
+ const availability=object(entry),sku=object(availability?.Sku),properties=object(sku?.Properties);
+ if(!sku)continue;
+ const kind=string(sku.SkuType)?.toLowerCase();
+ if(properties?.IsTrial===true||properties?.IsDemo===true||kind==='trial'||kind==='demo'){trial=true;continue;}
+ if(properties?.IsPreOrder===true) continue;
+ retail=true;
+ const offers=Array.isArray(availability?.Availabilities)?availability.Availabilities:[];
+ let skuFree=offers.length>0;
+ for(const offer of offers){
+ const price=object(object(object(offer)?.OrderManagementData)?.Price);
+ // MSRP distinguishes a paid title temporarily discounted to zero.
+ const values=[price?.MSRP,price?.ListPrice,price?.BasePrice].filter((v):v is number=>typeof v==='number'&&Number.isFinite(v)&&v>=0);
+ if(values.some(v=>v>0))paid=true;
+ const malformed=[price?.MSRP,price?.ListPrice,price?.BasePrice].some(v=>v!==undefined&&(typeof v!=='number'||!Number.isFinite(v)||v<0));
+ if(!values.length||malformed||values.some(v=>v>0))skuFree=false;
+ }
+ if(skuFree)free=true;else unknownRetail=true;
+ }
+ if(paid||unknownRetail)return false;
+ if(trial&&!retail)return true;
+ const price=object(search.priceInfo);
+ // Only structured booleans/numbers, never localized display strings/title.
+ const values=[price?.msrp,price?.listPrice,price?.price].filter((v):v is number=>typeof v==='number'&&Number.isFinite(v)&&v>=0);
+ if(values.some(v=>v>0))return false;
+ const malformed=[price?.msrp,price?.listPrice,price?.price].some(v=>v!==undefined&&(typeof v!=='number'||!Number.isFinite(v)||v<0));
+ return free || price?.isFree===true || (!malformed&&values.length>0&&values.every(v=>v===0));
+}
+
+export function parseCatalogProducts(search: StoreSearchResponse, catalog: DisplayCatalogResponse, policy: 'library' | 'store' = 'library'): CatalogProduct[] {
const detailMap = new Map<string, Record<string, unknown>>();
const details = Array.isArray(catalog.Products) ? catalog.Products : [];
for (const detail of details) {
@@ -254,9 +293,11 @@ export function parseCatalogProducts(search: StoreSearchResponse, catalog: Displ
}
const products = Array.isArray(search.productsList) ? search.productsList as StoreSearchProduct[] : [];
return products.flatMap((product) => {
+ if(!object(product))return [];
const productId = string(product.productId)?.toUpperCase();
const title = string(product.title);
if (!productId || !title || product.isGame === false) return [];
+ if(policy==='store' && excludedStoreOffer(product as Record<string,unknown>,detailMap.get(productId)))return [];
const support = packageSupport(productId, detailMap);
return [{
productId,
@@ -451,13 +492,13 @@ export class CatalogService {
private async result(search: StoreSearchResponse, query: string, market: string, includePaging: boolean): Promise<CatalogSearchResult> {
const ids = (Array.isArray(search.productsList) ? search.productsList as StoreSearchProduct[] : [])
- .flatMap((product) => string(product.productId)?.toUpperCase() ?? [])
+ .flatMap((product) => string(object(product)?.productId)?.toUpperCase() ?? [])
.filter((value, index, values) => values.indexOf(value) === index);
const catalog = await this.details(ids, market);
return {
query,
market,
- products: parseCatalogProducts(search, catalog),
+ products: parseCatalogProducts(search, catalog, 'store'),
cursor: includePaging ? string(search.cursor) : undefined,
hasMore: includePaging && search.hasMorePages === true && Boolean(string(search.cursor)),
fetchedAt: new Date().toISOString(),
diff --git a/src/main/index.ts b/src/main/index.ts
index 53a4ae8..c01c1a1 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -39,6 +39,7 @@ import { layoutOfWine } from './proton-layout.js';
import { accountCacheKey } from './offline-identity.js';
import { applyOfflinePermissions, assertOfflineAccessReady, bindOfflineAccess, licenseCacheDirectory, offlineAccessRevoked, revokeOfflineAccess, type OfflineRevocation } from './offline-access.js';
import { CatalogService } from './catalog.js';
+import {assertStoreOfferAccess} from './catalog-access.js';
import { cloudSaveRuntime, gameInviteRuntime, offlineIdentityRuntime, selectedWinePath, startXodusService, storeContentRuntime, storeDiscoveryRuntime, unbridgedCloudSaveRuntime, type XodusServiceSession } from './xodus-service.js';
import { GameLogReducer, gameLoggingEnvironment, gameWindowEnvironment } from './game-log.js';
import { downloadVerifiedVcRedist, installedVcRuntimeVersion, VC_REDIST_VERSION, versionAtLeast } from './vc-runtime.js';
@@ -760,6 +761,19 @@ function requestSavedAccount(action: 'use' | 'forget' | 'enable', name: unknown)
return job;
}
+async function storeAccess() {
+ if(authState.running||authState.stored!==true||!authState.username)throw Error('Sign in before checking Store access.');
+ const account=authState.username,binary=backend.current.binaryPath,market=currentMarket(),configuredMarket=store.settings.market;
+ accountLibrary.select(account,backend.current.capabilities.library?binary:undefined,market);
+ const result=await accountLibrary.storeAccess(configuredMarket);
+ if(authState.running||authState.stored!==true||account!==authState.username||binary!==backend.current.binaryPath||market!==currentMarket()||configuredMarket!==store.settings.market)throw Error('Store account changed. Refresh account access.');
+ return result;
+}
+async function verifyStoreInstall(productId:string) {
+ const access=await storeAccess();
+ assertStoreOfferAccess(access,productId,{account:authState.username,backend:backend.current.binaryPath,market:currentMarket()});
+}
+
async function startInstall(request: InstallRequest, updateGame?: Game, resumed?: DownloadTask): Promise<string> {
await stopGameUpdateCheck();
ensureIdle('install');
@@ -817,6 +831,8 @@ async function prepareInstall(request: InstallRequest, updateGame?: Game, conten
const binary = requireBackend('streaming');
if (updateGame && !backend.current.capabilities.streamingUpdateRecovery) throw Error('Update the Nexus backend in Settings before updating installed games safely.');
const productId = safeProductId(request.productId);
+ if(request.source!==undefined&&request.source!=='store')throw Error('Invalid installation source.');
+ if(request.source==='store')await verifyStoreInstall(productId);
const market = currentMarket();
let selectedContentId: string | undefined;
if (!content) {
@@ -829,6 +845,7 @@ async function prepareInstall(request: InstallRequest, updateGame?: Game, conten
const choice = plan.choices.find(choice => choice.supported && choice.contentId === selectedContentId)!;
if (updateGame && choice.kind === 'Durable') throw Error('An add-on cannot replace the base game. Use Manage content.');
const parent = contentParentForChoice(choice, store.games);
+ if(parent&&request.source==='store')throw Error('Use Manage content in the installed Library game to install add-ons.');
if (parent) return prepareContentInstall(parent, choice.productId, selectedContentId);
}
const activeTasks = store.downloads.filter(task => ['running', 'queued', 'paused'].includes(task.status));
@@ -851,9 +868,11 @@ async function prepareInstall(request: InstallRequest, updateGame?: Game, conten
(command.includes(actual.toLowerCase()) || executable.length > 0 && command.includes(executable)));
})) throw new Error('A game process is active. Close the game before updating files in place.');
}
+ if(request.source==='store')await verifyStoreInstall(productId);
const id = randomUUID();
const task: DownloadTask = {
id,
+ source: request.source,
kind: content ? 'content' : updateGame ? 'update' : 'install',
gameId: content?.game.id ?? updateGame?.id,
title: request.title.trim() || productId,
@@ -875,6 +894,7 @@ async function prepareInstall(request: InstallRequest, updateGame?: Game, conten
installQueue.enqueue({ id, run: async () => {
if (shutdownStarted) throw Error('The launcher is closing.');
if (identity !== `${authState.username}:${backend.current.binaryPath}:${currentMarket()}`) throw Error('Account, backend or Store market changed. Retry the installation.');
+ if(request.source==='store')await verifyStoreInstall(productId);
if (await backend.externalDownloadRunning()) throw Error('Another Xodus download is running outside this queue.');
await assertInstallDestination(destination, store.games.filter(game => game.id !== updateGame?.id && game.id !== content?.game.id).map(game => game.path));
if (gameOperation && ['preparing', 'running', 'stopping'].includes(gameOperation.status)) {
@@ -1667,6 +1687,7 @@ function registerDemoIpc(catalogMarket: () => string): void {
ipcMain.handle('set-offline-permissions', (_event, enabled: boolean) => ({ enabled: Boolean(enabled), requestSuccess: true, remainingToggles: 1, maxToggles: 3, periodDays: 365, checkedAt: new Date().toISOString() }));
ipcMain.handle('catalog-search', (_event, query: string, cursor?: string) => catalog.search(query, catalogMarket(), cursor));
ipcMain.handle('catalog-featured', () => catalog.featured(catalogMarket()));
+ ipcMain.handle('store-access', () => ({configuredMarket:snapshot().settings.market,account:snapshot().auth.username??'demo',backend:snapshot().backend.binaryPath??'',market:catalogMarket(),checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60_000).toISOString(),accessByProductId:{}}));
ipcMain.handle('account-library', (_event, kind: 'all' | 'owned' | 'gamepass') => demoAccountLibrary(kind, demoArtwork));
ipcMain.handle('stop-game-update-check', () => {});
ipcMain.handle('start-install', () => 'demo-download');
@@ -1928,6 +1949,7 @@ function registerIpc(): void {
ipcMain.handle('catalog-search', (_event, query: string, cursor?: string) => {
return catalog.search(query, catalogMarket(), cursor);
});
+ ipcMain.handle('store-access', () => storeAccess());
ipcMain.handle('account-library', (_event, kind: 'all' | 'owned' | 'gamepass' | 'other', cursor?: string, refresh = false, sort?: 'recent-gamepass') => {
if (authState.running || authState.stored !== true) throw Error('Finish signing in before loading account games.');
accountLibrary.select(authState.username, backend.current.capabilities.library ? backend.current.binaryPath : undefined, currentMarket());
@@ -1991,7 +2013,7 @@ function registerIpc(): void {
if (task.kind === 'content') {
if (!task.gameId) throw Error('Content download has no parent game.');
await installGameContent(task.gameId, task.productId);
- } else await startInstall({ productId: task.productId, title: task.title, destination: task.destination, selectedContentId: task.selectedContentId, selectionMarket: task.selectionMarket }, game, resumed);
+ } else await startInstall({ source:task.source, productId: task.productId, title: task.title, destination: task.destination, selectedContentId: task.selectedContentId, selectionMarket: task.selectionMarket }, game, resumed);
await store.removeDownload(id);
} catch (error) { task.status = 'paused'; throw error; }
finally { emitSnapshot(); }
diff --git a/src/preload/index.cts b/src/preload/index.cts
index 8355ad4..74d8825 100644
--- a/src/preload/index.cts
+++ b/src/preload/index.cts
@@ -118,6 +118,7 @@ const api: LauncherApi = {
setOfflinePermissions: (enabled: boolean) => ipcRenderer.invoke('set-offline-permissions', enabled),
searchCatalog: (query: string, cursor?: string) => ipcRenderer.invoke('catalog-search', query, cursor),
getFeaturedCatalog: () => ipcRenderer.invoke('catalog-featured'),
+ getStoreAccess: () => ipcRenderer.invoke('store-access'),
getAccountLibrary: (kind, cursor, refresh, sort) => ipcRenderer.invoke('account-library', kind, cursor, refresh, sort),
startInstall: (request: InstallRequest) => ipcRenderer.invoke('start-install', request),
getInstallPlan: (productId: string, destination?: string) => ipcRenderer.invoke('install-plan', productId, destination),
diff --git a/src/shared/types.ts b/src/shared/types.ts
index dc086c2..bd0d53c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -155,6 +155,7 @@ export interface GameLaunchOptions {
}
export interface DownloadTask {
+ source?: 'store';
id: string;
kind?: 'install' | 'update' | 'content';
gameId?: string;
@@ -298,6 +299,7 @@ export interface AppSnapshot {
}
export interface InstallRequest {
+ source?: 'store';
productId: string;
title: string;
destination: string;
@@ -416,6 +418,15 @@ export interface CatalogSearchResult {
}
export type LibraryAccess = 'owned' | 'gamepass' | 'other';
+export interface StoreAccess {
+ configuredMarket: string;
+ account: string;
+ backend: string;
+ market: string;
+ checkedAt: string;
+ expiresAt: string;
+ accessByProductId: Record<string, LibraryAccess>;
+}
export interface AccountLibraryPage {
kind: 'all' | LibraryAccess;
sort?: 'recent-gamepass';
@@ -605,6 +616,7 @@ export interface LauncherApi {
setOfflinePermissions(enabled: boolean): Promise<OfflinePermissions>;
searchCatalog(query: string, cursor?: string): Promise<CatalogSearchResult>;
getFeaturedCatalog(): Promise<CatalogSearchResult>;
+ getStoreAccess(): Promise<StoreAccess>;
getAccountLibrary(kind: AccountLibraryPage['kind'], cursor?: string, refresh?: boolean, sort?: AccountLibraryPage['sort']): Promise<AccountLibraryPage>;
startInstall(request: InstallRequest): Promise<string>;
getInstallPlan(productId: string, destination?: string): Promise<InstallPlan>;