Skip to content

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

TypeScript

[source-only] fix(store): scope public details to the public browse market

Nexus Maintainer1f63a7325e2c
diff --git a/src/main/game-catalog-detail-ipc.test.ts b/src/main/game-catalog-detail-ipc.test.ts
index f2f9811..122fe3a 100644
--- a/src/main/game-catalog-detail-ipc.test.ts
+++ b/src/main/game-catalog-detail-ipc.test.ts
@@ -4,6 +4,7 @@ import ts from 'typescript';
import {expect,it,vi} from 'vitest';
import {demoSnapshot} from '../shared/demo-data';
import {gameDetailsTarget} from './game-details-target';
+import {catalogDetailMarket} from './public-store-market';
const source=readFileSync(new URL('./index.ts',import.meta.url),'utf8');
const start=source.indexOf(" ipcMain.handle('game-details'",source.indexOf('function registerIpc():'));
const code=ts.transpileModule(source.slice(start,source.indexOf(" ipcMain.handle('launch-game'",start)),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
@@ -13,7 +14,7 @@ function fixture(){
let market='US';const catalog={gameDetails:vi.fn(async()=>({productId:'9AAAAAAAAAAA',xboxTitleId:'123'} as {productId:string;xboxTitleId?:string}))};
const gameActivities={select:vi.fn(),get:vi.fn(async()=>({status:'available',minutesPlayed:42}))},gameAchievements={select:vi.fn(),get:vi.fn(async()=>({status:'available',items:[]}))};
const installedTitleId=vi.fn(async()=> '456');
- runInNewContext(code,{ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},store:{games},catalog,currentMarket:()=>market,authState,backend,gameActivities,gameAchievements,gameDetailsTarget,installedTitleId});
+ runInNewContext(code,{ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},store:{games},catalog,currentMarket:()=>market,catalogDetailMarket,authState,backend,gameActivities,gameAchievements,gameDetailsTarget,installedTitleId});
return {games,authState,backend,catalog,gameActivities,gameAchievements,installedTitleId,setMarket:(value:string)=>market=value,call:(name:string,...args:unknown[])=>handlers.get(name)!(undefined,...args)};
}
it('reads catalog details/activity/achievements without installation, file access or guessed title IDs',async()=>{
@@ -44,10 +45,33 @@ it.each(['game-activity','game-achievements'])('%s rejects late catalog lookup a
expect(f.gameActivities.get).not.toHaveBeenCalled();expect(f.gameAchievements.get).not.toHaveBeenCalled();
}
});
-it('rejects catalog metadata after a market change',async()=>{
- const f=fixture();let resolve!:(value:{productId:string})=>void;
- f.catalog.gameDetails.mockReturnValueOnce(new Promise(done=>resolve=done));const pending=f.call('game-details',{productId:'9AAAAAAAAAAA'});f.setMarket('CZ');resolve({productId:'9AAAAAAAAAAA'});
- await expect(pending).rejects.toThrow('market changed');
+it('keeps explicit public Store metadata on the public market and Library details on the account market',async()=>{
+ const f=fixture();
+ // Only an explicit public Store scope selects public browse metadata, and a
+ // later account-market change neither alters nor invalidates it.
+ let resolvePublic!:(value:{productId:string})=>void;
+ f.catalog.gameDetails.mockReturnValueOnce(new Promise(done=>resolvePublic=done));
+ const pendingPublic=f.call('game-details',{productId:'9AAAAAAAAAAA',scope:'public-store'});
+ f.setMarket('CZ');resolvePublic({productId:'9AAAAAAAAAAA'});
+ await expect(pendingPublic).resolves.toMatchObject({productId:'9AAAAAAAAAAA'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9AAAAAAAAAAA','US');
+ // An unscoped product, which is what an uninstalled owned/Game Pass Library
+ // card passes, keeps the account market and still rejects late metadata.
+ f.setMarket('CZ');
+ let resolveLibrary!:(value:{productId:string})=>void;
+ f.catalog.gameDetails.mockReturnValueOnce(new Promise(done=>resolveLibrary=done));
+ const pendingLibrary=f.call('game-details',{productId:'9AAAAAAAAAAA'});
+ f.setMarket('US');resolveLibrary({productId:'9AAAAAAAAAAA'});
+ await expect(pendingLibrary).rejects.toThrow('market changed');
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9AAAAAAAAAAA','CZ');
+ // An installed Library identity keeps the account market as well.
+ f.setMarket('CZ');
+ let resolveOwned!:(value:{productId:string})=>void;
+ f.catalog.gameDetails.mockReturnValueOnce(new Promise(done=>resolveOwned=done));
+ const pendingOwned=f.call('game-details',f.games[0].id);
+ f.setMarket('DE');resolveOwned({productId:f.games[0].storeId!});
+ await expect(pendingOwned).rejects.toThrow('market changed');
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith(f.games[0].storeId,'CZ');
});
it.each(['game-activity','game-achievements'])('%s uses the player identity and rejects a late player switch',async route=>{
diff --git a/src/main/game-details-target.test.ts b/src/main/game-details-target.test.ts
index 4474abe..ebacc3c 100644
--- a/src/main/game-details-target.test.ts
+++ b/src/main/game-details-target.test.ts
@@ -5,9 +5,12 @@ const games=demoSnapshot().games;
it('keeps installed identities separate from a read-only catalog target',()=>{
expect(gameDetailsTarget(games[0].id,games)).toEqual({game:games[0],productId:games[0].storeId});
expect(gameDetailsTarget({productId:'9AAAAAAAAAAA'},games)).toEqual({productId:'9AAAAAAAAAAA'});
+ expect(gameDetailsTarget({productId:'9AAAAAAAAAAA',scope:'public-store'},games)).toEqual({productId:'9AAAAAAAAAAA',scope:'public-store'});
expect(()=>gameDetailsTarget('9AAAAAAAAAAA',games)).toThrow('Game not found');
});
-it.each([null,[],{},123,{productId:'bad'},{productId:'9aaaaaaaaaaa'},{productId:'9AAAAAAAAAAA',path:'/tmp/game'},{productId:'9AAAAAAAAAAA',titleId:'123'},{productId:['9AAAAAAAAAAA']}])('rejects malformed catalog targets without accepting a path or caller title ID: %j',value=>{
+it.each([null,[],{},123,{productId:'bad'},{productId:'9aaaaaaaaaaa'},{productId:'9AAAAAAAAAAA',path:'/tmp/game'},{productId:'9AAAAAAAAAAA',titleId:'123'},{productId:['9AAAAAAAAAAA']},
+ {productId:'9AAAAAAAAAAA',scope:'account'},{productId:'9AAAAAAAAAAA',scope:'PUBLIC-STORE'},{productId:'9AAAAAAAAAAA',scope:'publicStore'},{productId:'9AAAAAAAAAAA',scope:null},{productId:'9AAAAAAAAAAA',scope:true},{productId:'9AAAAAAAAAAA',scope:42},
+ {productId:'9AAAAAAAAAAA',scope:'public-store',path:'/tmp/game'},{productId:'9AAAAAAAAAAA',scope:'public-store',titleId:'123'},{scope:'public-store',productId:'bad'},{scope:'public-store'}])('rejects malformed catalog targets without accepting a path, caller title ID or unknown scope: %j',value=>{
expect(()=>gameDetailsTarget(value,games)).toThrow();
});
it('uses only one exact, validated Display Catalog XboxTitleId mapping',()=>{
diff --git a/src/main/game-details-target.ts b/src/main/game-details-target.ts
index 643fadd..98b04f3 100644
--- a/src/main/game-details-target.ts
+++ b/src/main/game-details-target.ts
@@ -1,15 +1,24 @@
-import type {Game} from '../shared/types.js';
+import type {Game,GameDetailsScope} from '../shared/types.js';
-/** Catalog details are read-only and never insert an installation or accept a path. */
-export function gameDetailsTarget(value:unknown,games:Game[]):{game?:Game;productId?:string} {
+/** A resolved read-only detail request. `scope` is presentation only and never
+ * an ownership, license or installation decision. */
+export interface GameDetailsRequest {game?:Game;productId?:string;scope?:GameDetailsScope}
+
+/** Catalog details are read-only and never insert an installation or accept a path.
+ * A saved game ID stays on the account market. An explicit product identity also
+ * stays on the account market unless it carries the allowlisted public scope. */
+export function gameDetailsTarget(value:unknown,games:Game[]):GameDetailsRequest {
if(typeof value==='string'){
const game=games.find(game=>game.id===value);
if(!game)throw Error('Game not found.');
return {game,productId:game.storeId&&/^[A-Z0-9]{12}$/.test(game.storeId)?game.storeId:undefined};
}
- if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).length!==1
- ||!('productId' in value)||typeof value.productId!=='string'||!/^[A-Z0-9]{12}$/.test(value.productId))throw Error('Invalid game details request.');
- return {productId:value.productId};
+ if(!value||typeof value!=='object'||Array.isArray(value))throw Error('Invalid game details request.');
+ const record=value as Record<string,unknown>,keys=Object.keys(record);
+ if(keys.some(key=>key!=='productId'&&key!=='scope'))throw Error('Invalid game details request.');
+ if(typeof record.productId!=='string'||!/^[A-Z0-9]{12}$/.test(record.productId))throw Error('Invalid game details request.');
+ if('scope' in record&&record.scope!=='public-store')throw Error('Invalid game details scope.');
+ return record.scope==='public-store'?{productId:record.productId,scope:'public-store'}:{productId:record.productId};
}
/** Display Catalog AlternateIds is authoritative; ambiguity is not a title match. */
diff --git a/src/main/index.ts b/src/main/index.ts
index 566e6ad..bd2b54e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -45,6 +45,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 {catalogDetailMarket, publicStoreMarket} from './public-store-market.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';
@@ -1761,8 +1762,8 @@ function registerDemoIpc(catalogMarket: () => string): void {
ipcMain.handle('forget-account', () => {});
ipcMain.handle('offline-permissions', () => ({ enabled: false, requestSuccess: true, remainingToggles: 2, maxToggles: 3, periodDays: 365, checkedAt: new Date().toISOString() }));
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('catalog-search', (_event, query: string, cursor?: string) => catalog.search(query, publicStoreMarket(), cursor));
+ ipcMain.handle('catalog-featured', () => catalog.featured(publicStoreMarket()));
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', () => {});
@@ -1787,7 +1788,7 @@ function registerDemoIpc(catalogMarket: () => string): void {
ipcMain.handle('game-details', async (_event, id: unknown) => {
const game = demoGames.find(game => game.id === id);
const target=typeof id==='object'?gameDetailsTarget(id,[]):game?gameDetailsTarget(id,demoGames):undefined;
- return target?.productId ? catalog.gameDetails(target.productId, catalogMarket()) : undefined;
+ return target?.productId ? catalog.gameDetails(target.productId, catalogDetailMarket(target.scope, catalogMarket())) : undefined;
});
ipcMain.handle('game-activity', () => ({ status: 'unavailable' }));
ipcMain.handle('game-achievements', () => ({ status: 'unavailable' }));
@@ -2040,7 +2041,7 @@ function registerIpc(): void {
} finally { offlinePermissionChanging = false; }
});
ipcMain.handle('catalog-search', (_event, query: string, cursor?: string) => {
- return catalog.search(query, catalogMarket(), cursor);
+ return catalog.search(query, publicStoreMarket(), cursor);
});
ipcMain.handle('store-access', () => storeAccess());
ipcMain.handle('account-library', (_event, kind: 'all' | 'owned' | 'gamepass' | 'other', cursor?: string, refresh = false, sort?: 'recent-gamepass') => {
@@ -2058,7 +2059,7 @@ function registerIpc(): void {
});
});
ipcMain.handle('save-diagnostic-report', (_event, content: unknown) => saveReviewedReport(content));
- ipcMain.handle('catalog-featured', () => catalog.featured(catalogMarket()));
+ ipcMain.handle('catalog-featured', () => catalog.featured(publicStoreMarket()));
ipcMain.handle('start-install', (_event, request: InstallRequest) => startInstall(request));
ipcMain.handle('install-plan', async (_event, raw: string, destination?: string) => {
const binary = requireBackend('streaming');
@@ -2174,9 +2175,12 @@ function registerIpc(): void {
ipcMain.handle('game-details', async (_event, id: unknown) => {
const target=gameDetailsTarget(id,store.games);
if (!target.productId) return undefined;
- const market = currentMarket();
+ // Only an explicit public Store presentation scope selects public browsing
+ // metadata. A saved game ID and an unscoped Library product keep the real
+ // account market.
+ const market=catalogDetailMarket(target.scope,currentMarket());
const details = await catalog.gameDetails(target.productId, market);
- if (market !== currentMarket()) throw Error('Store market changed. Try again.');
+ if (market !== catalogDetailMarket(target.scope,currentMarket())) throw Error('Store market changed. Try again.');
return details;
});
ipcMain.handle('game-activity', async (_event, id: unknown, refresh = false) => {
diff --git a/src/main/public-store-ipc.test.ts b/src/main/public-store-ipc.test.ts
new file mode 100644
index 0000000..30a56af
--- /dev/null
+++ b/src/main/public-store-ipc.test.ts
@@ -0,0 +1,125 @@
+import {readFileSync} from 'node:fs';
+import {runInNewContext} from 'node:vm';
+import ts from 'typescript';
+import {expect,it,vi} from 'vitest';
+import {gameDetailsTarget} from './game-details-target';
+import {catalogDetailMarket,publicStoreMarket} from './public-store-market';
+
+// Execute the actual public catalog IPC handlers. Everything is synthetic: no
+// Electron window, account, backend, license, network or game is started.
+const source=readFileSync(new URL('./index.ts',import.meta.url),'utf8');
+const parsed=ts.createSourceFile('index.ts',source,ts.ScriptTarget.Latest,true);
+
+function declarations(names:string[]):string{
+ return parsed.statements
+ .flatMap(node=>ts.isFunctionDeclaration(node)&&node.name&&names.includes(node.name.text)?[node.getText(parsed)]:[])
+ .join('\n');
+}
+function handlerStatements(names:string[],owner:string):string{
+ const fn=parsed.statements.find((node):node is ts.FunctionDeclaration=>ts.isFunctionDeclaration(node)&&node.name?.text===owner);
+ if(!fn?.body)throw Error(`Missing ${owner}.`);
+ const found:ts.Node[]=[];
+ for(const statement of fn.body.statements){
+ if(!ts.isExpressionStatement(statement)||!ts.isCallExpression(statement.expression))continue;
+ const call=statement.expression,callee=call.expression,channel=call.arguments[0];
+ if(!ts.isPropertyAccessExpression(callee)||callee.name.text!=='handle'||!ts.isIdentifier(callee.expression)||callee.expression.text!=='ipcMain')continue;
+ if(ts.isStringLiteral(channel)&&names.includes(channel.text))found.push(statement);
+ }
+ const missing=names.filter(name=>!found.some(node=>node.getText(parsed).includes(`'${name}'`)));
+ if(missing.length)throw Error(`Missing IPC handlers: ${missing.join(', ')}.`);
+ return found.map(node=>node.getText(parsed)).join('\n');
+}
+const mainNames=['catalog-search','catalog-featured','game-details','store-access','account-library','install-plan','game-activity','game-achievements'];
+const mainCode=ts.transpileModule([declarations(['storeAccess']),handlerStatements(mainNames,'registerIpc')].join('\n'),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+const demoCode=ts.transpileModule(handlerStatements(['catalog-search','catalog-featured','game-details','store-access'],'registerDemoIpc'),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+
+function fixture(mode:'main'|'demo'){
+ const handlers=new Map<string,Function>(),products={query:'q',market:'US',products:[],hasMore:false,fetchedAt:'',source:'Microsoft Store'};
+ // CZ desktop with settings.market 'neutral': the effective account region.
+ let market='CZ';
+ const catalog={search:vi.fn(async()=>products),featured:vi.fn(async()=>products),gameDetails:vi.fn(async(productId:string)=>({productId,xboxTitleId:'123'}))};
+ const games=[{id:'owned-game',storeId:'9GGGGGGGGGGG',title:'Owned Game',path:'/synthetic/game'}];
+ const store={games,settings:{market:'neutral'}};
+ const accountLibrary={select:vi.fn(),get:vi.fn(async()=>({kind:'owned',products:[],accessByProductId:{}})),storeAccess:vi.fn(async(configuredMarket:string)=>({configuredMarket,account:'fixture',market,checkedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+60_000).toISOString(),accessByProductId:{},backend:'/fixture/cli'}))};
+ const installPlans={get:vi.fn(async()=>({choices:[]}))};
+ const gameActivities={select:vi.fn(),get:vi.fn(async()=>({status:'available'}))},gameAchievements={select:vi.fn(),get:vi.fn(async()=>({status:'available'}))};
+ const installedTitleId=vi.fn(async()=> '456');
+ const context:any={ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},catalog,currentMarket:()=>market,publicStoreMarket,catalogDetailMarket,gameDetailsTarget,store,accountLibrary,installPlans,
+ authState:{running:false,stored:true,username:'fixture',player:undefined},backend:{current:{binaryPath:'/fixture/cli',capabilities:{library:true,packageSelection:true,gameActivity:true,achievements:true}}},
+ requireBackend:()=>'/fixture/cli',safeProductId:(value:string)=>value,availableInstallBytes:async()=>1024,
+ gameActivities,gameAchievements,installedTitleId,
+ snapshot:()=>({settings:{market:'neutral'},auth:{username:'fixture'},backend:{binaryPath:'/fixture/cli'}}),
+ catalogMarket:()=>market,demoGames:games,demoArtwork:new Map(),demoAccountLibrary:vi.fn(),demoLocales:{},demoLaunchOptions:{}};
+ runInNewContext(mode==='main'?mainCode:demoCode,context);
+ return {catalog,accountLibrary,installPlans,gameActivities,gameAchievements,setMarket:(value:string)=>market=value,call:(name:string,...args:unknown[])=>handlers.get(name)!(undefined,...args)};
+}
+
+it('browses the neutral US Store on a CZ desktop while Store access keeps the effective region',async()=>{
+ const f=fixture('main');
+ await f.call('catalog-search','gears','cursor');
+ expect(f.catalog.search).toHaveBeenCalledWith('gears','US','cursor');
+ await f.call('catalog-featured');
+ expect(f.catalog.featured).toHaveBeenCalledWith('US');
+ const access=await f.call('store-access');
+ expect(access).toMatchObject({configuredMarket:'neutral',market:'CZ'});
+ expect(f.accountLibrary.storeAccess).toHaveBeenCalledWith('neutral');
+ expect(f.accountLibrary.select).toHaveBeenCalledWith('fixture','/fixture/cli','CZ');
+});
+
+it('uses the public market only for an explicit public Store scope and keeps every other target on the account market',async()=>{
+ const f=fixture('main');
+ // Public Store card detail: explicit read-only presentation scope.
+ await f.call('game-details',{productId:'9PUBLICGAME1',scope:'public-store'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9PUBLICGAME1','US');
+ // Uninstalled owned/Game Pass Library card: unscoped identity stays account.
+ await f.call('game-details',{productId:'9ACCOUNTGAME'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9ACCOUNTGAME','CZ');
+ // Installed Library identity stays account.
+ await f.call('game-details','owned-game');
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9GGGGGGGGGGG','CZ');
+ // Malformed or unknown scopes are rejected before any catalog request.
+ f.catalog.gameDetails.mockClear();
+ for(const value of [{productId:'9PUBLICGAME1',scope:'account'},{productId:'9PUBLICGAME1',scope:'US'},{productId:'9PUBLICGAME1',scope:'public-store',path:'/tmp/x'},{productId:'9PUBLICGAME1',scope:true}])await expect(f.call('game-details',value)).rejects.toThrow();
+ expect(f.catalog.gameDetails).not.toHaveBeenCalled();
+ // Activity, achievements, install and entitlement never follow a metadata scope.
+ await f.call('game-activity',{productId:'9PUBLICGAME1',scope:'public-store'});
+ await f.call('game-achievements',{productId:'9PUBLICGAME1',scope:'public-store'});
+ expect(f.catalog.gameDetails.mock.calls.slice(-2).map(call=>call[1])).toEqual(['CZ','CZ']);
+ expect(f.gameActivities.get).toHaveBeenCalledWith('123',false);
+ expect(f.gameAchievements.get).toHaveBeenCalledWith('123',false);
+ await f.call('account-library','owned');
+ expect(f.accountLibrary.select).toHaveBeenLastCalledWith('fixture','/fixture/cli','CZ');
+ await f.call('install-plan','9INSTALLGAME');
+ expect(f.installPlans.get).toHaveBeenCalledWith('/fixture/cli','9INSTALLGAME','CZ',false);
+});
+
+it('keeps public metadata stable while account operations follow a market change',async()=>{
+ const f=fixture('main');
+ f.setMarket('DE');
+ await f.call('game-details',{productId:'9PUBLICGAME1',scope:'public-store'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9PUBLICGAME1','US');
+ await f.call('game-details',{productId:'9ACCOUNTGAME'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9ACCOUNTGAME','DE');
+ await f.call('game-activity',{productId:'9PUBLICGAME1',scope:'public-store'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9PUBLICGAME1','DE');
+ await f.call('install-plan','9INSTALLGAME');
+ expect(f.installPlans.get).toHaveBeenCalledWith('/fixture/cli','9INSTALLGAME','DE',false);
+ const access=await f.call('store-access');
+ expect(access).toMatchObject({configuredMarket:'neutral',market:'DE'});
+});
+
+it('demo applies the same scoped policy instead of an all-US catalog',async()=>{
+ const f=fixture('demo');
+ await f.call('catalog-search','gears','cursor');
+ expect(f.catalog.search).toHaveBeenCalledWith('gears','US','cursor');
+ await f.call('catalog-featured');
+ expect(f.catalog.featured).toHaveBeenCalledWith('US');
+ await f.call('game-details',{productId:'9PUBLICGAME1',scope:'public-store'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9PUBLICGAME1','US');
+ await f.call('game-details',{productId:'9ACCOUNTGAME'});
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9ACCOUNTGAME','CZ');
+ await f.call('game-details','owned-game');
+ expect(f.catalog.gameDetails).toHaveBeenLastCalledWith('9GGGGGGGGGGG','CZ');
+ const access=await f.call('store-access');
+ expect(access).toMatchObject({configuredMarket:'neutral',market:'CZ'});
+});
diff --git a/src/main/public-store-market.test.ts b/src/main/public-store-market.test.ts
new file mode 100644
index 0000000..4b4dd86
--- /dev/null
+++ b/src/main/public-store-market.test.ts
@@ -0,0 +1,67 @@
+import {expect,it} from 'vitest';
+import {CatalogService} from './catalog';
+import {catalogDetailMarket,PUBLIC_STORE_MARKET,publicStoreMarket} from './public-store-market';
+
+it('selects one stable public browse market that never depends on the OS locale',()=>{
+ expect(PUBLIC_STORE_MARKET).toBe('US');
+ expect(publicStoreMarket()).toBe('US');
+ expect(publicStoreMarket()).toMatch(/^[A-Z]{2}$/);
+ // Read-only public Store metadata always uses the public browse market.
+ expect(catalogDetailMarket('public-store','CZ')).toBe('US');
+ expect(catalogDetailMarket('public-store','DE')).toBe('US');
+ expect(catalogDetailMarket('public-store','US')).toBe('US');
+ // An unscoped identity, including an uninstalled Library product, keeps the
+ // actual configured/effective account region.
+ expect(catalogDetailMarket(undefined,'CZ')).toBe('CZ');
+ expect(catalogDetailMarket(undefined,'DE')).toBe('DE');
+ expect(catalogDetailMarket(undefined,'US')).toBe('US');
+});
+
+const paid = {Sku:{SkuType:'full',Properties:{}},Availabilities:[{OrderManagementData:{Price:{MSRP:29.99,ListPrice:29.99}}}]};
+const free = {Sku:{SkuType:'full',Properties:{}},Availabilities:[{OrderManagementData:{Price:{MSRP:0,ListPrice:0}}}]};
+const trial = {Sku:{SkuType:'trial',Properties:{IsTrial:true}},Availabilities:[{OrderManagementData:{Price:{MSRP:0,ListPrice:0}}}]};
+const row = (productId:string,title:string,price:number)=>({productId,title,isGame:true,priceInfo:{msrp:price,price,displayPrice:price>0?`$${price}`:'Free'}});
+const detail = (productId:string,skus:unknown[])=>({ProductId:productId,ProductType:'Game',DisplaySkuAvailabilities:skus});
+
+function fixture(){
+ const requests:string[]=[];
+ const fetcher=(async(input:URL|RequestInfo)=>{
+ const url=new URL(String(input)); requests.push(url.pathname+url.search);
+ const payload=url.pathname.includes('/api/products/search')
+ ? {productsList:[row('9PAIDGAME001','Paid Game',29.99),row('9FREEGAME001','Free Game',0),row('9TRIALGAME01','Trial Only',0)],hasMorePages:false}
+ : url.pathname.includes('GetComputedProductsList')
+ ? {title:'Top paid games',hasMorePages:false,productsList:[row('9PAIDGAME001','Paid Game',29.99)]}
+ : {Products:[detail('9PAIDGAME001',[paid]),detail('9FREEGAME001',[free]),detail('9TRIALGAME01',[trial])]};
+ return new Response(JSON.stringify(payload),{status:200,headers:{'Content-Type':'application/json'}});
+ }) as typeof fetch;
+ return {service:new CatalogService(fetcher),requests};
+}
+
+it('requests the neutral English US Store catalog and reuses one cache entry',async()=>{
+ const f=fixture();
+ const [first,second,third]=await Promise.all([
+ f.service.search('gears',publicStoreMarket()),f.service.search('gears',publicStoreMarket()),f.service.search('gears',publicStoreMarket()),
+ ]);
+ expect(first.market).toBe('US');
+ expect(second).toEqual(first);expect(third).toEqual(first);
+ const search=f.requests.filter(url=>url.includes('/api/products/search'));
+ expect(search).toHaveLength(1);
+ const params=new URL(`https://store${search[0]}`).searchParams;
+ expect(params.get('gl')).toBe('US');
+ expect(params.get('hl')).toBe('en-us');
+ const details=f.requests.filter(url=>url.includes('/v7.0/products'));
+ expect(details).toHaveLength(1);
+ const detailParams=new URL(`https://store${details[0]}`).searchParams;
+ expect(detailParams.get('market')).toBe('US');
+ expect(detailParams.get('languages')).toBe('en-us,neutral');
+});
+
+it('keeps the paid-only public policy inside the neutral US browse path',async()=>{
+ const f=fixture();
+ const result=await f.service.search('games',publicStoreMarket());
+ expect(result.products.map(product=>product.title)).toEqual(['Paid Game']);
+ expect(result.products.some(product=>['Free Game','Trial Only'].includes(product.title))).toBe(false);
+ const featured=await f.service.featured(publicStoreMarket());
+ expect(featured.market).toBe('US');
+ expect(featured.products.map(product=>product.title)).toEqual(['Paid Game']);
+});
diff --git a/src/main/public-store-market.ts b/src/main/public-store-market.ts
new file mode 100644
index 0000000..3b6e87d
--- /dev/null
+++ b/src/main/public-store-market.ts
@@ -0,0 +1,30 @@
+import type {GameDetailsScope} from '../shared/types.js';
+
+/** Public Store browsing uses one stable technical market.
+ *
+ * The Microsoft Store search and recommendation endpoints have no global
+ * offer: they require a concrete market code. Public browsing therefore uses
+ * the US market with the Store's English metadata for every installation, so
+ * an international page does not silently inherit a country from the OS locale
+ * or from a `neutral` market setting. It is also one stable cache key and one
+ * English description for the same product everywhere.
+ *
+ * This is a browsing policy only. It does not promise a local or global price,
+ * it never selects the region for an account, and it never proves ownership:
+ * account, Library, entitlement, install, license and cloud operations keep
+ * using the configured/effective account market.
+ */
+export const PUBLIC_STORE_MARKET = 'US';
+
+/** Market for public Store search, featured collections and public details.
+ * Deliberately independent of the OS locale and of a `neutral` setting. */
+export function publicStoreMarket(): string {
+ return PUBLIC_STORE_MARKET;
+}
+
+/** Read-only descriptive metadata for an explicit public Store presentation
+ * scope uses the public browse market. Every other target, including an
+ * unscoped Library product and a saved game ID, keeps the account market. */
+export function catalogDetailMarket(scope: GameDetailsScope | undefined, accountMarket: string): string {
+ return scope === 'public-store' ? publicStoreMarket() : accountMarket;
+}
diff --git a/src/renderer/CatalogGameDetails.tsx b/src/renderer/CatalogGameDetails.tsx
index 5ba8468..cfdd160 100644
--- a/src/renderer/CatalogGameDetails.tsx
+++ b/src/renderer/CatalogGameDetails.tsx
@@ -46,7 +46,7 @@ export function CatalogGameDetails({product,data,back,backLabel,toast,storeAcces
}
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}<button className="secondary" onClick={()=>window.open(product.storeUrl??`https://www.xbox.com/games/store/p/${product.productId}`,'_blank')}>{ui('ui.store_page_9c667df')}</button></>}
+ detailId={product.productId} catalogProductId={installed?undefined:product.productId} publicMetadataProductId={storeMode?product.productId:undefined} 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">{licensed?<p className={product.installability==='supported'?'supported':'unsupported'}>{uiText(product.supportNote)}</p>:null}
{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}
{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}
diff --git a/src/renderer/GameDetails.tsx b/src/renderer/GameDetails.tsx
index 35df29e..d11f4ee 100644
--- a/src/renderer/GameDetails.tsx
+++ b/src/renderer/GameDetails.tsx
@@ -1,7 +1,7 @@
import { ui } from './i18n';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { ArrowLeft, Check, ChevronLeft, ChevronRight, Clock3, Download, Gamepad2, Images, LoaderCircle, MoreHorizontal, RefreshCw, X } from 'lucide-react';
-import type { AppSnapshot, Game, GameActivity, GameStoreDetails } from '../shared/types';
+import type { AppSnapshot, Game, GameActivity, GameDetailsTarget, GameStoreDetails } from '../shared/types';
import './game-details.css';
import { Achievements } from './Achievements';
@@ -59,6 +59,9 @@ export function Gallery({ title, images, initial, close }: { title: string; imag
interface PageProps {
game: Pick<Game,'id'|'title'|'publisher'|'coverUrl'|'heroUrl'> & {installState?:Game['installState']};
catalogProductId?: string;
+ /** Read-only public Store metadata identity. It never changes activity,
+ * achievements, Play or any account/install decision. */
+ publicMetadataProductId?: string;
detailId?: string;
back: () => void;
backLabel?: string;
@@ -154,6 +157,9 @@ export function GameDetailsContent({ game, detailId,back, backLabel, play, manag
export function GameDetails(props: PageProps & { data: AppSnapshot }) {
const { game, data } = props;
const target=useMemo(()=>props.catalogProductId?{productId:props.catalogProductId}:game.id,[game.id,props.catalogProductId]);
+ // Descriptive metadata may come from public Store browsing; the identity target
+ // above still drives Play, activity and achievements on the account market.
+ const metadataTarget=useMemo<GameDetailsTarget>(()=>props.publicMetadataProductId?{productId:props.publicMetadataProductId,scope:'public-store'}:target,[props.publicMetadataProductId,target]);
const [details, setDetails] = useState<GameStoreDetails>();
const [metadataLoading, setMetadataLoading] = useState(true);
const [metadataError, setMetadataError] = useState(false);
@@ -162,9 +168,9 @@ export function GameDetails(props: PageProps & { data: AppSnapshot }) {
const request = useRef(0);
useEffect(() => {
let live = true; setDetails(undefined); setMetadataLoading(true); setMetadataError(false);
- window.launcher.getGameDetails(target).then(value => { if (live) setDetails(value); }).catch(() => { if (live) setMetadataError(true); }).finally(() => { if (live) setMetadataLoading(false); });
+ window.launcher.getGameDetails(metadataTarget).then(value => { if (live) setDetails(value); }).catch(() => { if (live) setMetadataError(true); }).finally(() => { if (live) setMetadataLoading(false); });
return () => { live = false; };
- }, [target, data.settings.market]);
+ }, [metadataTarget, data.settings.market]);
const loadActivity = useCallback((refresh = false) => {
const id = ++request.current; setActivityLoading(true);
void window.launcher.getGameActivity(target, refresh).then(value => { if (request.current === id) setActivity(value); }).catch(() => { if (request.current === id) setActivity({ status: 'error' }); }).finally(() => { if (request.current === id) setActivityLoading(false); });
diff --git a/src/renderer/game-details-market-scope.test.tsx b/src/renderer/game-details-market-scope.test.tsx
new file mode 100644
index 0000000..d5a58ab
--- /dev/null
+++ b/src/renderer/game-details-market-scope.test.tsx
@@ -0,0 +1,84 @@
+// @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 {GameDetails} from './GameDetails';
+import {demoSnapshot} from '../shared/demo-data';
+import type {CatalogProduct,GameDetailsTarget} from '../shared/types';
+
+const product:CatalogProduct={productId:'9AAAAAAAAAAA',title:'Neutral Store Game',description:'',categories:[],installability:'supported',supportNote:'Supported'};
+
+function installLauncher(){
+ const details:GameDetailsTarget[]=[],activities:GameDetailsTarget[]=[],achievements:GameDetailsTarget[]=[];
+ window.launcher={
+ getGameDetails:vi.fn(async(target:GameDetailsTarget)=>{details.push(structuredClone(target));}),
+ getGameActivity:vi.fn(async(target:GameDetailsTarget)=>{activities.push(structuredClone(target));return {status:'unavailable'};}),
+ getGameAchievements:vi.fn(async(target:GameDetailsTarget)=>{achievements.push(structuredClone(target));return {status:'unavailable',items:[]};}),
+ getStoreAccess:vi.fn(async()=>undefined),
+ gameRuntimeReadiness:vi.fn(async()=>true),
+ launchGame:vi.fn(async()=>{}),
+ } as unknown as Window['launcher'];
+ return {details,activities,achievements};
+}
+async function mount(element:React.ReactElement){
+ const node=document.createElement('div'),root=createRoot(node);
+ await act(async()=>{root.render(element);});
+ await act(async()=>{await Promise.resolve();});
+ return {node,unmount:async()=>{await act(async()=>root.unmount());}};
+}
+function snapshot(market='CZ'){
+ const data=demoSnapshot();data.games=[];data.downloads=[];data.settings.market=market;
+ return data;
+}
+afterEach(()=>{vi.unstubAllGlobals();});
+
+it('keeps an uninstalled owned/Game Pass Library product detail on the account market',async()=>{
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
+ const data=snapshot(),calls=installLauncher();
+ const view=await mount(<CatalogGameDetails product={product} data={data} back={()=>{}} toast={()=>{}}/>);
+ try{
+ expect(calls.details.at(-1)).toEqual({productId:product.productId});
+ expect(calls.activities.at(-1)).toEqual({productId:product.productId});
+ expect(calls.achievements.at(-1)).toEqual({productId:product.productId});
+ }finally{await view.unmount();}
+});
+
+it('opts only an explicit public Store detail into public metadata while activity stays on the account identity',async()=>{
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
+ const data=snapshot(),calls=installLauncher();
+ const view=await mount(<CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/>);
+ try{
+ expect(calls.details.at(-1)).toEqual({productId:product.productId,scope:'public-store'});
+ expect(calls.activities.at(-1)).toEqual({productId:product.productId});
+ expect(calls.achievements.at(-1)).toEqual({productId:product.productId});
+ }finally{await view.unmount();}
+});
+
+it('reflects public metadata for an installed product opened from the Store without changing Play or activity binding',async()=>{
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
+ const data=snapshot();
+ data.games=[{...demoSnapshot().games[0],storeId:product.productId,installState:'ready'}];
+ const calls=installLauncher();
+ const view=await mount(<CatalogGameDetails storeMode product={product} data={data} back={()=>{}} toast={()=>{}}/>);
+ try{
+ expect(calls.details.at(-1)).toEqual({productId:product.productId,scope:'public-store'});
+ expect(calls.activities.at(-1)).toBe(data.games[0].id);
+ expect(calls.achievements.at(-1)).toBe(data.games[0].id);
+ const play=view.node.querySelector<HTMLButtonElement>('[data-gamepad-play]')!;
+ expect(play.textContent).toContain('Play');
+ await act(async()=>play.click());
+ expect(window.launcher.launchGame).toHaveBeenCalledWith(data.games[0].id);
+ }finally{await view.unmount();}
+});
+
+it('keeps an installed Library game opened from the Library on the account market',async()=>{
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
+ const data=demoSnapshot();data.downloads=[];data.settings.market='CZ';const game=data.games[0],calls=installLauncher();
+ const view=await mount(<GameDetails game={game} data={data} back={()=>{}} play={<button>Play</button>} />);
+ try{
+ expect(calls.details.at(-1)).toBe(game.id);
+ expect(calls.activities.at(-1)).toBe(game.id);
+ expect(calls.achievements.at(-1)).toBe(game.id);
+ }finally{await view.unmount();}
+});
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 16c035f..fa35c6a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -401,8 +401,15 @@ export interface CatalogProduct {
supportNote: string;
}
-/** A saved installation ID, or an explicit read-only Store catalog identity. */
-export type GameDetailsTarget = string | {productId:string};
+/** Public Store browsing is the only non-account catalog presentation scope.
+ * It selects read-only metadata from the neutral public Store market only; it
+ * never proves ownership or grants install access, and account activity,
+ * achievements and licensing keep their configured market. */
+export type GameDetailsScope = 'public-store';
+/** A saved installation ID, or an explicit read-only Store catalog identity.
+ * An unscoped identity keeps the configured/effective account market; only an
+ * explicit `public-store` scope selects public browsing metadata. */
+export type GameDetailsTarget = string | {productId:string; scope?:GameDetailsScope};
/** Public catalog data only, never an ownership/installation decision. */
export interface GameStoreDetails {