Skip to content

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

TypeScript

fix(profile): recover verified game artwork within account and time bounds

Nexus Maintainer23d58f75636e
diff --git a/index.html b/index.html
index e89c82c..126d968 100644
--- a/index.html
+++ b/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#080a0c" />
- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data: https://store-images.s-microsoft.com https://store-images.microsoft.com https://images-eds-ssl.xboxlive.com https://images-eds.xboxlive.com https://gamerpic.xboxlive.com https://avatar-ssl.xboxlive.com https://xboxavatargamerpic.azureedge.net; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http://127.0.0.1:5173 ws://127.0.0.1:5173" />
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data: https://store-images.s-microsoft.com https://store-images.microsoft.com https://images-eds-ssl.xboxlive.com https://images-eds.xboxlive.com https://images-assets-ssl.xboxlive.com https://gamerpic.xboxlive.com https://avatar-ssl.xboxlive.com https://xboxavatargamerpic.azureedge.net; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http://127.0.0.1:5173 ws://127.0.0.1:5173" />
<title>Nexus Launcher</title>
</head>
<body>
diff --git a/src/main/catalog-title-artwork.test.ts b/src/main/catalog-title-artwork.test.ts
new file mode 100644
index 0000000..cf05c81
--- /dev/null
+++ b/src/main/catalog-title-artwork.test.ts
@@ -0,0 +1,130 @@
+import { afterEach,describe,expect,it,vi } from 'vitest';
+import { CatalogService } from './catalog.js';
+
+const image=(host:string,purpose='BoxArt')=>({ImagePurpose:purpose,Uri:`//${host}/image/${purpose.toLowerCase()}`});
+const product=(titleId:string,images:unknown[],patch:Record<string,unknown>={})=>({
+ ProductId:'9AAAAAAAAAAA',ProductType:'Game',
+ AlternateIds:[{IdType:'XboxTitleId',Value:titleId}],
+ LocalizedProperties:[{Images:images}],...patch,
+});
+const response=(products:unknown[])=>new Response(JSON.stringify({Products:products}),{status:200,headers:{'Content-Type':'application/json'}});
+const lookupTitleId=(input:URL|RequestInfo)=>new URL(String(input)).searchParams.get('value')??'';
+afterEach(()=>vi.useRealTimers());
+
+describe('profile artwork from verified Store title IDs', () => {
+ it('resolves a missing cover through the documented alternate-ID lookup', async () => {
+ const fetcher=vi.fn(async (input:URL|RequestInfo)=>{
+ const url=new URL(String(input));
+ expect(url.origin+url.pathname).toBe('https://displaycatalog.mp.microsoft.com/v7.0/products/lookup');
+ expect(url.searchParams.get('alternateId')).toBe('XboxTitleID');
+ expect(url.searchParams.get('fieldsTemplate')).toBe('Details');
+ return response([product(lookupTitleId(input),[
+ image('store-images.s-microsoft.com','Logo'),
+ image('store-images.s-microsoft.com','FeaturePromotionalSquareArt'),
+ image('store-images.s-microsoft.com','BoxArt'),
+ ])]);
+ }) as unknown as typeof fetch;
+ const artwork=await new CatalogService(fetcher).artworkForXboxTitleIds(['1842701288'],'cz');
+ expect(artwork.get('1842701288')).toBe('https://store-images.s-microsoft.com/image/boxart');
+ const url=new URL(String(fetcher.mock.calls[0][0]));
+ expect(url.searchParams.get('market')).toBe('CZ');
+ });
+
+ it('requires the returned AlternateIds to contain exactly the requested title ID and a safe Game cover', async () => {
+ const fetcher=(async (input:URL|RequestInfo)=>response([
+ product('999',[image('store-images.s-microsoft.com')]),
+ product(lookupTitleId(input),[image('tracker.example.test')]),
+ product(lookupTitleId(input),[image('store-images.s-microsoft.com')],{ProductType:'Application'}),
+ product(lookupTitleId(input),[image('store-images.s-microsoft.com','Logo')]),
+ ])) as unknown as typeof fetch;
+ const artwork=await new CatalogService(fetcher).artworkForXboxTitleIds(['123'],'US');
+ expect(artwork.size).toBe(0);
+ });
+
+ it('accepts the Store image hosts already allowed by the launcher policy', async () => {
+ for(const host of ['store-images.s-microsoft.com','store-images.microsoft.com']){
+ const fetcher=(async ()=>response([product('123',[image(host)])])) as unknown as typeof fetch;
+ expect((await new CatalogService(fetcher).artworkForXboxTitleIds(['123'],'US')).get('123')).toBe(`https://${host}/image/boxart`);
+ }
+ });
+
+ it('coalesces concurrent and repeated snapshots and caches negative results', async () => {
+ const fetcher=vi.fn(async (input:URL|RequestInfo)=>{
+ const value=lookupTitleId(input);
+ if(value==='404')return response([]);
+ return response([product(value,[image('store-images.s-microsoft.com')])]);
+ }) as unknown as typeof fetch;
+ const catalog=new CatalogService(fetcher);
+ const [first,second]=await Promise.all([catalog.artworkForXboxTitleIds(['123'],'US'),catalog.artworkForXboxTitleIds(['123'],'US')]);
+ expect(first.get('123')).toBe('https://store-images.s-microsoft.com/image/boxart');
+ expect(second.get('123')).toBe(first.get('123'));
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ await catalog.artworkForXboxTitleIds(['123'],'US');
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect((await catalog.artworkForXboxTitleIds(['404'],'US')).size).toBe(0);
+ await catalog.artworkForXboxTitleIds(['404'],'US');
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it('is optional and bounded: invalid IDs make no request, offline lookup cannot reject the profile, and one call stays within its budget', async () => {
+ const offline=vi.fn(async ()=>{throw Error('offline');}) as unknown as typeof fetch;
+ const empty=await new CatalogService(offline).artworkForXboxTitleIds(['','0','4294967296','abc','12/../'],'US');
+ expect(empty.size).toBe(0);
+ expect(offline).not.toHaveBeenCalled();
+ expect((await new CatalogService(offline).artworkForXboxTitleIds(['123'],'US')).size).toBe(0);
+ expect(offline).toHaveBeenCalledOnce();
+
+ const ids=Array.from({length:30},(_,index)=>String(index+1));
+ const fetcher=vi.fn(async (input:URL|RequestInfo)=>response([product(lookupTitleId(input),[image('store-images.s-microsoft.com')])])) as unknown as typeof fetch;
+ const artwork=await new CatalogService(fetcher).artworkForXboxTitleIds(ids,'US');
+ expect(fetcher).toHaveBeenCalledTimes(24);
+ expect(artwork.size).toBe(24);
+ expect([...artwork.keys()]).toEqual(ids.slice(0,24));
+ });
+
+ it('keeps every coalesced joiner inside its own deadline without cancelling shared work', async () => {
+ vi.useFakeTimers();vi.setSystemTime(0);
+ const calls:{id:string;start:number}[]=[];
+ const fetcher=vi.fn((input:URL|RequestInfo)=>{
+ const id=lookupTitleId(input);
+ calls.push({id,start:Date.now()});
+ return new Promise<Response>(resolve=>setTimeout(()=>resolve(response([product(id,[image('store-images.s-microsoft.com')])])),Number(id)<=4?5900:5000));
+ }) as unknown as typeof fetch;
+ const catalog=new CatalogService(fetcher);
+ let firstEnded=-1;
+ const first=catalog.artworkForXboxTitleIds(['1','2','3','4','5','6','7','8'],'US').then(value=>{firstEnded=Date.now();return value;});
+ await vi.advanceTimersByTimeAsync(5800);
+ const second=catalog.artworkForXboxTitleIds(['5','6','7','8'],'US');
+ await vi.advanceTimersByTimeAsync(5000);
+ const [a,b]=await Promise.all([first,second]);
+ expect(calls).toHaveLength(8);
+ expect(firstEnded).toBeLessThanOrEqual(8000);
+ expect([...a.keys()].sort()).toEqual(['1','2','3','4']);
+ expect([...b.keys()].sort()).toEqual(['5','6','7','8']);
+ await catalog.artworkForXboxTitleIds(['1','2','3','4','5','6','7','8'],'US');
+ expect(fetcher).toHaveBeenCalledTimes(8);
+ });
+
+ it('handles a late shared failure after the caller expired and keeps shared cleanup usable', async () => {
+ vi.useFakeTimers();vi.setSystemTime(0);
+ const unhandled=vi.fn();
+ process.on('unhandledRejection',unhandled);
+ try{
+ const fetcher=vi.fn((input:URL|RequestInfo)=>{
+ const id=lookupTitleId(input);
+ if(fetcher.mock.calls.length===1)return new Promise<Response>((_resolve,reject)=>setTimeout(()=>reject(Error('late failure')),9000));
+ return Promise.resolve(response([product(id,[image('store-images.s-microsoft.com')])]));
+ }) as unknown as typeof fetch;
+ const catalog=new CatalogService(fetcher);
+ const first=catalog.artworkForXboxTitleIds(['5'],'US');
+ await vi.advanceTimersByTimeAsync(8000);
+ expect(await first).toEqual(new Map());
+ await vi.advanceTimersByTimeAsync(2000);
+ await Promise.resolve();await Promise.resolve();
+ expect(unhandled).not.toHaveBeenCalled();
+ const second=await catalog.artworkForXboxTitleIds(['5'],'US');
+ expect(second.get('5')).toBe('https://store-images.s-microsoft.com/image/boxart');
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ }finally{process.off('unhandledRejection',unhandled);}
+ });
+});
diff --git a/src/main/catalog.ts b/src/main/catalog.ts
index bdecdbc..faa4dc2 100644
--- a/src/main/catalog.ts
+++ b/src/main/catalog.ts
@@ -60,6 +60,36 @@ const STORE_HOSTS = new Set(['www.xbox.com', 'xbox.com', 'apps.microsoft.com']);
const CACHE_TTL_MS = 10 * 60 * 1000;
const SEARCH_CACHE_LIMIT = 100;
const SEARCH_REQUEST_LIMIT = 32;
+// Social title history identifies games by Xbox title ID, not by Store product
+// ID. The documented Display Catalog alternate-ID lookup is the only stable
+// mapping we use; it is anonymous public metadata and never carries account
+// tokens, headers or per-player state into the cached image URL.
+const TITLE_ARTWORK_TTL_MS = 10 * 60 * 1000;
+const TITLE_ARTWORK_NEGATIVE_TTL_MS = 2 * 60 * 1000;
+const TITLE_ARTWORK_CACHE_LIMIT = 500;
+const TITLE_ARTWORK_LOOKUPS_PER_CALL = 24;
+const TITLE_ARTWORK_CONCURRENCY = 4;
+const TITLE_ARTWORK_REQUESTS_LIMIT = 8;
+// A slow catalog must not hold the whole game history open. Workers stop
+// starting lookups after this deadline and keep the existing placeholders.
+const TITLE_ARTWORK_DEADLINE_MS = 8_000;
+const TITLE_ARTWORK_REQUEST_TIMEOUT_MS = 6_000;
+const TITLE_ARTWORK_EXPIRED = Symbol('title-artwork-expired');
+
+/** Race one awaited lookup against the current caller's budget. The shared
+ * request keeps running for other callers and for the cache; only this caller
+ * stops waiting. The listener is removed as soon as either side settles. */
+function raceCallerDeadline<T>(promise: Promise<T>, signal: AbortSignal): Promise<T | typeof TITLE_ARTWORK_EXPIRED> {
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) { resolve(TITLE_ARTWORK_EXPIRED); return; }
+ const expired = () => resolve(TITLE_ARTWORK_EXPIRED);
+ signal.addEventListener('abort', expired, {once: true});
+ promise.then(
+ value => { signal.removeEventListener('abort', expired); resolve(value); },
+ error => { signal.removeEventListener('abort', expired); reject(error); },
+ );
+ });
+}
// The Store's games recommendation feeds return about ten products per page.
// Trending games are dominated by free-to-play titles that the public browsing
// policy has to hide, so the top paid collection supplies real breadth. Both
@@ -364,6 +394,8 @@ export class CatalogService {
private readonly gameRequests = new Map<string,Promise<GameStoreDetails|undefined>>();
private readonly cache = new Map<string, { expires: number; value: CatalogSearchResult }>();
private readonly requests = new Map<string, Promise<CatalogSearchResult>>();
+ private readonly titleArtworkCache = new Map<string,{until:number;value?:string}>();
+ private readonly titleArtworkRequests = new Map<string,Promise<string|undefined>>();
constructor(private readonly fetcher: Fetcher = fetch) {}
@@ -690,4 +722,87 @@ export class CatalogService {
}
return artwork;
}
+
+ /**
+ * Map missing social-profile artwork from an Xbox title ID to the public
+ * Store cover. A returned product is used only when its AlternateIds contain
+ * exactly the requested title ID, so a similar name can never substitute a
+ * guessed cover. Lookups are deduplicated, coalesced, cached and bounded;
+ * callers keep their existing placeholder when a title has no Store product.
+ */
+ async artworkForXboxTitleIds(titleIds: string[], rawMarket: string): Promise<Map<string,string>> {
+ const market = normalizeMarket(rawMarket);
+ const unique = titleIds
+ .map(value => value.trim())
+ .filter(value => /^\d{1,10}$/.test(value) && Number(value) > 0 && Number(value) <= 0xffffffff)
+ .filter((value, index, values) => values.indexOf(value) === index)
+ .slice(0, TITLE_ARTWORK_LOOKUPS_PER_CALL);
+ const artwork = new Map<string,string>();
+ if (!unique.length) return artwork;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), TITLE_ARTWORK_DEADLINE_MS);
+ timer.unref?.();
+ const budget = controller.signal;
+ const queue = [...unique];
+ try {
+ const worker = async () => {
+ while (queue.length && !budget.aborted) {
+ const titleId = queue.shift()!;
+ const key = `${market}\u0000${titleId}`;
+ const cached = this.titleArtworkCache.get(key);
+ if (cached && cached.until > Date.now()) {
+ if (cached.value) artwork.set(titleId, cached.value);
+ continue;
+ }
+ if (cached) this.titleArtworkCache.delete(key);
+ let request = this.titleArtworkRequests.get(key);
+ if (!request) {
+ if (budget.aborted || this.titleArtworkRequests.size >= TITLE_ARTWORK_REQUESTS_LIMIT) continue;
+ request = this.fetchTitleArtwork(titleId, market)
+ .then(value => {
+ while (this.titleArtworkCache.size >= TITLE_ARTWORK_CACHE_LIMIT) this.titleArtworkCache.delete(this.titleArtworkCache.keys().next().value!);
+ this.titleArtworkCache.set(key, {until: Date.now() + (value ? TITLE_ARTWORK_TTL_MS : TITLE_ARTWORK_NEGATIVE_TTL_MS), value});
+ return value;
+ })
+ .finally(() => { this.titleArtworkRequests.delete(key); });
+ this.titleArtworkRequests.set(key, request);
+ }
+ // Artwork is optional: a failed lookup never fails the profile, and
+ // an expired caller stops waiting without cancelling shared work.
+ try {
+ const value = await raceCallerDeadline(request, budget);
+ if (value !== TITLE_ARTWORK_EXPIRED && value) artwork.set(titleId, value);
+ } catch {}
+ }
+ };
+ await Promise.all(Array.from({length: Math.min(TITLE_ARTWORK_CONCURRENCY, unique.length)}, worker));
+ return artwork;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ private async fetchTitleArtwork(titleId: string, market: string): Promise<string | undefined> {
+ const url = new URL('https://displaycatalog.mp.microsoft.com/v7.0/products/lookup');
+ url.searchParams.set('alternateId', 'XboxTitleID');
+ url.searchParams.set('value', titleId);
+ url.searchParams.set('market', market);
+ url.searchParams.set('languages', 'en-us,neutral');
+ url.searchParams.set('fieldsTemplate', 'Details');
+ const response = await this.fetcher(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(TITLE_ARTWORK_REQUEST_TIMEOUT_MS) });
+ if (!response.ok) return undefined;
+ const catalog = await response.json() as DisplayCatalogResponse;
+ const products = Array.isArray(catalog?.Products) ? catalog.Products : [];
+ if (products.length > 25) return undefined;
+ for (const entry of products) {
+ const product = object(entry);
+ if (!product || product.ProductType !== 'Game') continue;
+ if (catalogXboxTitleId(product.AlternateIds) !== titleId) continue;
+ const localized = Array.isArray(product.LocalizedProperties) ? object(product.LocalizedProperties[0]) : undefined;
+ const images = Array.isArray(localized?.Images) ? localized.Images as DisplayCatalogImage[] : [];
+ const cover = displayImage(images.filter(image => object(image)), POSTER_PURPOSES);
+ if (cover) return cover;
+ }
+ return undefined;
+ }
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 7feb209..35171c5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -8,7 +8,7 @@ import {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding.js'
import {desktopTrayAvailable} from './launcher-tray-desktop.js';
import {LauncherTray} from './launcher-tray.js';
import {SteamKeyboard} from './steam-keyboard.js';
-import type {XboxProfileRequest} from '../shared/types.js';
+import type {XboxProfileGames,XboxProfileRequest} from '../shared/types.js';
import {XboxSocial as NativeXboxSocial} from './xbox-native-social.js';
import {resetSocialTransport} from './xbox-social-transport.js';
import { app, BrowserWindow, clipboard, dialog, globalShortcut, ipcMain, nativeImage, net, Notification, powerSaveBlocker, screen, shell, Tray, Menu } from 'electron';
@@ -46,6 +46,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 {readXboxProfileGames} from './xbox-profile-games.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';
@@ -1700,6 +1701,14 @@ function currentMarket(): string {
return configured.toLowerCase() === 'neutral' ? app.getLocaleCountryCode() || 'US' : configured;
}
+// Title history artwork is optional: the native service omits an image when
+// the Xbox URL it received is not accepted. Fill only missing covers from the
+// verified public Store title-ID mapping; never replace service artwork and
+// never fail the player's history when Store metadata is unavailable.
+async function xboxProfileGames(xuid:string):Promise<XboxProfileGames>{
+ return readXboxProfileGames(xboxNativeSocial,xuid,titleIds=>catalog.artworkForXboxTitleIds(titleIds,currentMarket()));
+}
+
// Fetch real covers and wide art even when an installation has a small logo.
async function enrichDownloadCovers(tasks: readonly DownloadTask[], market: string): Promise<void> {
const missing = tasks.filter(task => !task.coverUrl && ['queued', 'running', 'paused'].includes(task.status));
@@ -1901,7 +1910,7 @@ function registerIpc(): void {
chatReads.viewed(account,binary,peer,ids);
});
ipcMain.handle('xbox-player-details',(event,xuid:string)=>{socialSender(event);return xboxNativeSocial.details(xuid);});
- ipcMain.handle('xbox-player-games',(event,xuid:string)=>{socialSender(event);return xboxNativeSocial.games(xuid);});
+ ipcMain.handle('xbox-player-games',(event,xuid:string)=>{socialSender(event);return xboxProfileGames(xuid);});
ipcMain.handle('xbox-social-people',(event,list:Parameters<NativeXboxSocial['people']>[0],query?:string)=>{socialSender(event);return xboxNativeSocial.people(list,query);});
ipcMain.handle('xbox-social-relationship',(event,xuid:string)=>{socialSender(event);return xboxNativeSocial.relationship(xuid);});
ipcMain.handle('xbox-social-relationship-change',(event,account:string,xuid:string,action:Parameters<NativeXboxSocial['changeRelationship']>[2])=>{socialSender(event);return xboxNativeSocial.changeRelationship(account,xuid,action);});
@@ -2745,7 +2754,7 @@ app.whenReady().then(async () => {
const text=(index:number)=>{const value=args[index];if(typeof value!=='string')throw Error('Invalid Guide request.');return value;};
switch(method){
case 'getXboxPlayerDetails':return xboxNativeSocial.details(text(0));
- case 'getXboxPlayerGames':return xboxNativeSocial.games(text(0));
+ case 'getXboxPlayerGames':return xboxProfileGames(text(0));
case 'getXboxPeople':return xboxNativeSocial.people(text(0) as Parameters<NativeXboxSocial['people']>[0],args[1]===undefined||args[1]===null?undefined:text(1));
case 'getXboxRelationship':return xboxNativeSocial.relationship(text(0));
case 'changeXboxRelationship':if(text(0)!=='current')throw Error('Xbox account changed.');return xboxNativeSocial.changeRelationship(nativeSocialConnection()!.account,text(1),text(2) as Parameters<NativeXboxSocial['changeRelationship']>[2]);
diff --git a/src/main/xbox-guide-server.ts b/src/main/xbox-guide-server.ts
index 372be59..ee17572 100644
--- a/src/main/xbox-guide-server.ts
+++ b/src/main/xbox-guide-server.ts
@@ -71,7 +71,7 @@ export class XboxGuideServer {
const filename=path.join(this.options.directory,route);
const type=media[path.extname(filename)];if(!type)return fail(response,404,'Not found.');
const bytes=await fs.readFile(filename).catch(()=>undefined);if(!bytes)return fail(response,404,'Not found.');
- response.writeHead(200,{'Content-Type':type,'Content-Security-Policy':"default-src 'self'; base-uri 'none'; frame-ancestors 'none'; frame-src 'none'; form-action 'none'; img-src 'self' data: https://store-images.s-microsoft.com https://images-assets-ssl.xboxlive.com https://images-eds-ssl.xboxlive.com https://gamerpic.xboxlive.com https://avatar-ssl.xboxlive.com https://xboxavatargamerpic.azureedge.net; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; media-src 'none'; object-src 'none'"});response.end(bytes);
+ response.writeHead(200,{'Content-Type':type,'Content-Security-Policy':"default-src 'self'; base-uri 'none'; frame-ancestors 'none'; frame-src 'none'; form-action 'none'; img-src 'self' data: https://store-images.s-microsoft.com https://store-images.microsoft.com https://images-assets-ssl.xboxlive.com https://images-eds-ssl.xboxlive.com https://images-eds.xboxlive.com https://gamerpic.xboxlive.com https://avatar-ssl.xboxlive.com https://xboxavatargamerpic.azureedge.net; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; media-src 'none'; object-src 'none'"});response.end(bytes);
})().catch(()=>{if(!response.headersSent)fail(response,500,'Nexus Overlay unavailable.');else response.end();});});
this.server=server;server.requestTimeout=15_000;server.headersTimeout=10_000;server.maxConnections=16;server.on('clientError',(_error,socket)=>socket.destroy());
await new Promise<void>((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',()=>{server.removeListener('error',reject);resolve();});});
diff --git a/src/main/xbox-native-social.ts b/src/main/xbox-native-social.ts
index 6068d9a..b86b2bc 100644
--- a/src/main/xbox-native-social.ts
+++ b/src/main/xbox-native-social.ts
@@ -4,6 +4,10 @@ import type { XboxConversation, XboxFriend, XboxMessage,XboxMessageReceipt,XboxP
type Connection = { binary: string; account: string };
type Reader = (binary: string, args: string[], input: string | undefined, signal: AbortSignal) => Promise<string>;
+/** One exact social identity binding. `revision` advances whenever the
+ * launcher clears social state, so a reconnect of the same account or a Store
+ * and player role change can never inherit an older pending read. */
+export interface XboxSocialContext { account: string; binary: string; revision: number }
const id = (value: unknown): value is string => typeof value === 'string' && /^[1-9][0-9]{0,19}$/.test(value) && BigInt(value) <= 18446744073709551615n;
const string = (value: unknown, max: number): value is string => typeof value === 'string' && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
const object = (value: unknown): value is Record<string, unknown> => Boolean(value && typeof value === 'object' && !Array.isArray(value));
@@ -57,14 +61,20 @@ function cleanDetails(value:unknown):XboxPlayerDetails{
}
return result;
}
+function gameImage(value:unknown):string|undefined{
+ if(typeof value!=='string'||value.length>8192)return;
+ try{
+ const url=new URL(value);
+ if(url.protocol!=='https:'||url.username||url.password||url.port)return;
+ return ['store-images.s-microsoft.com','store-images.microsoft.com','images-eds-ssl.xboxlive.com','images-eds.xboxlive.com','images-assets-ssl.xboxlive.com'].includes(url.hostname)?url.href:undefined;
+ }catch{return;}
+}
function cleanGame(value:unknown):XboxProfileGame{
if(!object(value)||!id(value.titleId)||BigInt(value.titleId)>4294967295n||!string(value.name,512)||!value.name)throw Error('Xbox returned an invalid game.');
const game:XboxProfileGame={titleId:value.titleId,name:value.name};
- if(value.imageUrl!==undefined){
- if(typeof value.imageUrl!=='string'||value.imageUrl.length>8192)throw Error('Xbox returned an invalid game image.');
- const url=new URL(value.imageUrl);
- if(url.protocol!=='https:'||url.username||url.password||url.port||!['store-images.s-microsoft.com','images-eds-ssl.xboxlive.com','images-assets-ssl.xboxlive.com'].includes(url.hostname))throw Error('Xbox returned an invalid game image.');game.imageUrl=url.href;
- }
+ // Artwork is optional. An unexpected image must not hide a valid title,
+ // timestamp or achievement history; the renderer shows a placeholder.
+ const image=gameImage(value.imageUrl);if(image)game.imageUrl=image;
if(value.lastPlayed!==undefined){if(!string(value.lastPlayed,64)||!Number.isFinite(Date.parse(value.lastPlayed)))throw Error('Xbox returned an invalid game timestamp.');game.lastPlayed=value.lastPlayed;}
for(const key of ['currentGamerscore','totalGamerscore','achievementsUnlocked','achievementsTotal'] as const){
const field=value[key];if(field!==undefined){if(typeof field!=='number'||!Number.isSafeInteger(field)||field<0||field>1_000_000_000)throw Error('Xbox returned invalid achievement counts.');game[key]=field;}
@@ -140,12 +150,22 @@ export async function readXboxSocial(binary: string, args: string[], input: stri
/** Backend-only authentication; no remote web page, token IPC, or message history on disk. */
export class XboxSocial {
+ private revision = 0;
private readonly controllers = new Set<AbortController>();
private readonly reads = new Map<string, { connection: Connection; expires: number; promise: Promise<unknown[]> }>();
private readonly peopleReads = new Map<string,{connection:Connection;expires:number;promise:Promise<unknown>}>();
private readonly peopleMutations = new Set<string>();
constructor(private readonly connection: () => Connection | undefined, private readonly reader: Reader = readXboxSocial) {}
+ context(): XboxSocialContext | undefined {
+ const connection=this.connection();
+ return connection?{account:connection.account,binary:connection.binary,revision:this.revision}:undefined;
+ }
+ matches(context: XboxSocialContext | undefined): boolean {
+ const current=this.context();
+ return Boolean(context&&current&&current.account===context.account&&current.binary===context.binary&&current.revision===context.revision);
+ }
clear(): void {
+ this.revision++;
for (const controller of this.controllers) controller.abort();
this.controllers.clear();this.reads.clear();this.peopleReads.clear();
}
@@ -189,8 +209,9 @@ export class XboxSocial {
if(xuid!=='me'&&!id(xuid))return Promise.reject(Error('Select an Xbox player.'));
return this.peopleRequest('profile',{xuid}) as Promise<XboxPlayerDetails>;
}
- games(xuid:string):Promise<XboxProfileGames>{
+ games(xuid:string,context?:XboxSocialContext):Promise<XboxProfileGames>{
if(xuid!=='me'&&!id(xuid))return Promise.reject(Error('Select an Xbox player.'));
+ if(context&&!this.matches(context))return Promise.reject(Error('Xbox account changed. Open Social again.'));
return this.peopleRequest('games',{xuid}) as Promise<XboxProfileGames>;
}
async changeRelationship(account:string,xuid:string,action:XboxRelationshipAction):Promise<void>{
diff --git a/src/main/xbox-people.test.ts b/src/main/xbox-people.test.ts
index 782b231..7e730ea 100644
--- a/src/main/xbox-people.test.ts
+++ b/src/main/xbox-people.test.ts
@@ -59,11 +59,25 @@ describe('Xbox people service boundary',()=>{
await expect(api.changeRelationship('account','2','send-request')).rejects.toThrow('current player action');expect(reader).toHaveBeenCalledTimes(1);
finish(reply('send-request',{xuid:'2',success:true}));await first;
});
- it('keeps title history public and bounded without accepting arbitrary images or counters',async()=>{
+ it('keeps title history public and bounded while dropping unsafe artwork without hiding the title',async()=>{
const game={titleId:'123',name:'E-Day',imageUrl:'https://store-images.s-microsoft.com/game.png',lastPlayed:'2026-10-23T12:00:00Z',currentGamerscore:0,achievementsUnlocked:0};
const api=new XboxSocial(connect,async()=>reply('games',{items:[{...game,authorization:'private'}],continuation:null,truncated:false}));
expect(await api.games('2')).toEqual({items:[game],continuation:null,truncated:false});
- for(const invalid of [{...game,imageUrl:'https://[email protected]/game.png'},{...game,titleId:'4294967296'},{...game,achievementsUnlocked:-1}]){
+ for(const imageUrl of ['https://store-images.microsoft.com/game.png','https://images-eds.xboxlive.com/game.png','https://images-assets-ssl.xboxlive.com/game.png']){
+ expect((await new XboxSocial(connect,async()=>reply('games',{items:[{...game,imageUrl}]})).games('2')).items[0].imageUrl).toBe(imageUrl);
+ }
+ const {imageUrl:_ignored,...withoutArt}=game;
+ for(const invalid of [
+ {...game,imageUrl:'https://[email protected]/game.png'},
+ {...game,imageUrl:'https://example.test/game.png'},
+ {...game,imageUrl:'http://store-images.s-microsoft.com/game.png'},
+ {...game,imageUrl:'not a url'},
+ {...game,imageUrl:'https://store-images.s-microsoft.com/'+'a'.repeat(8192)},
+ {...game,imageUrl:42},
+ ]){
+ expect((await new XboxSocial(connect,async()=>reply('games',{items:[invalid]})).games('2')).items[0]).toEqual(withoutArt);
+ }
+ for(const invalid of [{...game,titleId:'4294967296'},{...game,achievementsUnlocked:-1}]){
await expect(new XboxSocial(connect,async()=>reply('games',{items:[invalid]})).games('2')).rejects.toThrow();
}
});
diff --git a/src/main/xbox-profile-artwork.test.ts b/src/main/xbox-profile-artwork.test.ts
new file mode 100644
index 0000000..285d749
--- /dev/null
+++ b/src/main/xbox-profile-artwork.test.ts
@@ -0,0 +1,46 @@
+import {expect,it,vi} from 'vitest';
+import type {XboxProfileGames} from '../shared/types.js';
+import {withXboxProfileArtwork} from './xbox-profile-artwork.js';
+
+// Production contract fixture: title history with artwork omitted by the native
+// service, exactly as the profile renderer receives it after parsing.
+const fixture=(override:Partial<XboxProfileGames>={}):XboxProfileGames=>({
+ items:[
+ {titleId:'123',name:'Synthetic Game',lastPlayed:'2026-10-23T12:00:00Z',currentGamerscore:10,achievementsUnlocked:1},
+ {titleId:'456',name:'Already Illustrated',imageUrl:'https://store-images.s-microsoft.com/image/service-art'},
+ {titleId:'123',name:'Synthetic Game Duplicate'},
+ {titleId:'789',name:'No Store Product'},
+ ],
+ continuation:null,truncated:true,...override,
+});
+
+it('resolves each missing title ID once and keeps existing service artwork',async()=>{
+ const resolve=vi.fn(async(titleIds:string[])=>new Map([[ '123','https://store-images.s-microsoft.com/image/catalog-art' ]]));
+ const value=await withXboxProfileArtwork(fixture(),resolve);
+ expect(resolve).toHaveBeenCalledOnce();
+ expect(resolve).toHaveBeenCalledWith(['123','789']);
+ expect(value.items.map(game=>game.imageUrl)).toEqual([
+ 'https://store-images.s-microsoft.com/image/catalog-art',
+ 'https://store-images.s-microsoft.com/image/service-art',
+ 'https://store-images.s-microsoft.com/image/catalog-art',
+ undefined,
+ ]);
+ expect(value.continuation).toBeNull();
+ expect(value.truncated).toBe(true);
+ expect(value.items[0]).toMatchObject({titleId:'123',name:'Synthetic Game',lastPlayed:'2026-10-23T12:00:00Z',currentGamerscore:10,achievementsUnlocked:1});
+});
+
+it('does not resolve or replace anything when every game already has artwork',async()=>{
+ const resolve=vi.fn(async()=>new Map());
+ const games:XboxProfileGames={items:[{titleId:'1',name:'Illustrated',imageUrl:'https://store-images.s-microsoft.com/image/one'}]};
+ expect(await withXboxProfileArtwork(games,resolve)).toBe(games);
+ expect(resolve).not.toHaveBeenCalled();
+});
+
+it('leaves the history intact when the Store lookup fails or returns an unrequested title',async()=>{
+ const games=fixture();
+ expect(await withXboxProfileArtwork(games,async()=>{throw Error('offline');})).toBe(games);
+ const unrelated=await withXboxProfileArtwork(games,async()=>new Map([['999','https://store-images.s-microsoft.com/image/other']]));
+ expect(unrelated).toBe(games);
+ expect(games.items.filter(game=>game.imageUrl)).toHaveLength(1);
+});
diff --git a/src/main/xbox-profile-artwork.ts b/src/main/xbox-profile-artwork.ts
new file mode 100644
index 0000000..f70d528
--- /dev/null
+++ b/src/main/xbox-profile-artwork.ts
@@ -0,0 +1,21 @@
+import type {XboxProfileGames} from '../shared/types.js';
+
+/**
+ * Fill only missing Xbox title-history artwork from a verified resolver.
+ * Service artwork always wins, duplicate title IDs are resolved once per
+ * snapshot, and an unavailable catalog leaves the existing placeholder instead
+ * of failing the player's game history.
+ */
+export async function withXboxProfileArtwork(
+ games:XboxProfileGames,
+ resolve:(titleIds:string[])=>Promise<Map<string,string>>,
+):Promise<XboxProfileGames>{
+ const missing=[...new Set(games.items.filter(game=>!game.imageUrl).map(game=>game.titleId))];
+ if(!missing.length)return games;
+ try{
+ const artwork=await resolve(missing);
+ if(!artwork.size)return games;
+ const items=games.items.map(game=>game.imageUrl||!artwork.has(game.titleId)?game:{...game,imageUrl:artwork.get(game.titleId)!});
+ return items.some((game,index)=>game!==games.items[index])?{...games,items}:games;
+ }catch{return games;}
+}
diff --git a/src/main/xbox-profile-games.test.ts b/src/main/xbox-profile-games.test.ts
new file mode 100644
index 0000000..d8bae51
--- /dev/null
+++ b/src/main/xbox-profile-games.test.ts
@@ -0,0 +1,93 @@
+import { expect,it,vi } from 'vitest';
+import { XboxSocial } from './xbox-native-social.js';
+import { readXboxProfileGames } from './xbox-profile-games.js';
+
+const response=(items:unknown[])=>JSON.stringify({schema:1,account:'account',kind:'people',operation:'games',result:{items,continuation:null,truncated:false}});
+const game={titleId:'123',name:'Synthetic Game'};
+const artwork='https://store-images.s-microsoft.com/image/catalog-art';
+
+function deferred<T>(){
+ let resolve!:(value:T)=>void,reject!:(reason:unknown)=>void;
+ const promise=new Promise<T>((resolveValue,rejectValue)=>{resolve=resolveValue;reject=rejectValue;});
+ return {promise,resolve,reject};
+}
+
+it('returns title history artwork on the captured identity',async()=>{
+ const reader=vi.fn(async()=>response([game]));
+ const api=new XboxSocial(()=>({binary:'xodus-cli',account:'account'}),reader);
+ const result=await readXboxProfileGames(api,'2',async()=>new Map([['123',artwork]]));
+ expect(result.items).toEqual([{titleId:'123',name:'Synthetic Game',imageUrl:artwork}]);
+ expect(reader).toHaveBeenCalledOnce();
+});
+
+it('rejects stale history when the account changes while optional artwork is pending',async()=>{
+ let account='account';
+ const reader=vi.fn(async()=>response([game]));
+ const api=new XboxSocial(()=>({binary:'xodus-cli',account}),reader);
+ const art=deferred<Map<string,string>>();
+ let reachedResolve!:()=>void;const reached=new Promise<void>(resolve=>{reachedResolve=resolve;});
+ const pending=readXboxProfileGames(api,'2',()=>{reachedResolve();return art.promise;});
+ await reached;
+ account='other';
+ api.clear();
+ art.resolve(new Map([['123',artwork]]));
+ await expect(pending).rejects.toThrow('Xbox account changed');
+});
+
+it('rejects stale history when the connected account changes without a clear',async()=>{
+ let account='account';
+ const api=new XboxSocial(()=>({binary:'xodus-cli',account}),async()=>response([game]));
+ const art=deferred<Map<string,string>>();
+ let reachedResolve!:()=>void;const reached=new Promise<void>(resolve=>{reachedResolve=resolve;});
+ const pending=readXboxProfileGames(api,'2',()=>{reachedResolve();return art.promise;});
+ await reached;
+ account='other';
+ art.resolve(new Map([['123',artwork]]));
+ await expect(pending).rejects.toThrow('Xbox account changed');
+});
+
+it('rejects the previous history when the same identity reconnects while artwork is pending',async()=>{
+ const reader=vi.fn(async()=>response([game]));
+ const api=new XboxSocial(()=>({binary:'xodus-cli',account:'account'}),reader);
+ const art=deferred<Map<string,string>>();
+ let reachedResolve!:()=>void;const reached=new Promise<void>(resolve=>{reachedResolve=resolve;});
+ const pending=readXboxProfileGames(api,'2',()=>{reachedResolve();return art.promise;});
+ await reached;
+ api.clear();
+ art.resolve(new Map([['123',artwork]]));
+ await expect(pending).rejects.toThrow('Xbox account changed');
+});
+
+it('does not hide an account change when the optional artwork lookup fails',async()=>{
+ let account='account';
+ const api=new XboxSocial(()=>({binary:'xodus-cli',account}),async()=>response([game]));
+ const art=deferred<Map<string,string>>();
+ let reachedResolve!:()=>void;const reached=new Promise<void>(resolve=>{reachedResolve=resolve;});
+ const pending=readXboxProfileGames(api,'2',()=>{reachedResolve();return art.promise;});
+ await reached;
+ account='other';
+ api.clear();
+ art.reject(Error('offline'));
+ await expect(pending).rejects.toThrow('Xbox account changed');
+});
+
+it('cancels before the native read when the captured context is already invalid',async()=>{
+ const games=vi.fn(async()=>({items:[]}));
+ const source={context:()=>({account:'account',binary:'xodus-cli',revision:0}),matches:()=>false,games};
+ await expect(readXboxProfileGames(source,'2',async()=>new Map())).rejects.toThrow('Xbox account changed');
+ expect(games).not.toHaveBeenCalled();
+});
+
+it('rejects a service call whose explicit context was already cleared',async()=>{
+ const reader=vi.fn(async()=>response([game]));
+ const api=new XboxSocial(()=>({binary:'xodus-cli',account:'account'}),reader);
+ const context=api.context()!;
+ await expect(api.games('2',{...context,revision:context.revision+1})).rejects.toThrow('Xbox account changed');
+ expect(reader).not.toHaveBeenCalled();
+});
+
+it('requires an active store or player identity before reading history',async()=>{
+ const games=vi.fn(async()=>({items:[]}));
+ await expect(readXboxProfileGames({context:()=>undefined,matches:()=>true,games},'2',async()=>new Map())).rejects.toThrow('Sign in');
+ expect(games).not.toHaveBeenCalled();
+});
diff --git a/src/main/xbox-profile-games.ts b/src/main/xbox-profile-games.ts
new file mode 100644
index 0000000..23a715e
--- /dev/null
+++ b/src/main/xbox-profile-games.ts
@@ -0,0 +1,33 @@
+import type {XboxProfileGames} from '../shared/types.js';
+import type {XboxSocialContext} from './xbox-native-social.js';
+import {withXboxProfileArtwork} from './xbox-profile-artwork.js';
+
+export interface XboxProfileGamesSource {
+ context(): XboxSocialContext | undefined;
+ matches(context: XboxSocialContext): boolean;
+ games(xuid: string, context?: XboxSocialContext): Promise<XboxProfileGames>;
+}
+
+const changed = () => Error('Xbox account changed. Open Social again.');
+
+/**
+ * Read one player's title history on an exact social identity binding.
+ * The context is checked before the native read, after it and after optional
+ * artwork enrichment. A clear or account/role change during the artwork wait
+ * rejects instead of returning the previous account's history. Artwork failure
+ * stays optional, but it can never skip the final identity check.
+ */
+export async function readXboxProfileGames(
+ source: XboxProfileGamesSource,
+ xuid: string,
+ resolveArtwork: (titleIds: string[]) => Promise<Map<string, string>>,
+): Promise<XboxProfileGames> {
+ const context = source.context();
+ if (!context) throw Error('Sign in and use a Nexus backend with Xbox social support.');
+ if (!source.matches(context)) throw changed();
+ const games = await source.games(xuid, context);
+ if (!source.matches(context)) throw changed();
+ const enriched = await withXboxProfileArtwork(games, resolveArtwork);
+ if (!source.matches(context)) throw changed();
+ return enriched;
+}
diff --git a/src/renderer/XboxProfileGames.tsx b/src/renderer/XboxProfileGames.tsx
index c8f8e92..4fcae14 100644
--- a/src/renderer/XboxProfileGames.tsx
+++ b/src/renderer/XboxProfileGames.tsx
@@ -12,6 +12,14 @@ export function xboxGameProgress(game:XboxProfileGame):{achievements?:string;gam
return result;
}
+export function XboxProfileGameArt({game}:{game:XboxProfileGame}){
+ const [failed,setFailed]=useState(false);
+ useEffect(()=>{setFailed(false);},[game.imageUrl]);
+ return game.imageUrl&&!failed
+ ?<img src={game.imageUrl} alt="" loading="lazy" decoding="async" referrerPolicy="no-referrer" onError={()=>setFailed(true)}/>
+ :<div className="social-profile-game-placeholder" role="img" aria-label={ui('ui.artwork_unavailable_f4d58d3')}><Gamepad2 aria-hidden="true"/></div>;
+}
+
export function XboxProfileGames({api,xuid}:{api:XboxSocialApi;xuid:string}){
const [games,setGames]=useState<ProfileGames>(),[problem,setProblem]=useState<string>(),[revision,setRevision]=useState(0);
useEffect(()=>{
@@ -23,7 +31,7 @@ export function XboxProfileGames({api,xuid}:{api:XboxSocialApi;xuid:string}){
<h3>{ui("social.games_d9dae7")}</h3>
{games?<>
{games.items.length?<div className="social-profile-game-list">{games.items.map(game=>{const progress=xboxGameProgress(game);return <article key={game.titleId} className="social-profile-game">
- {game.imageUrl?<img src={game.imageUrl} alt="" loading="lazy" referrerPolicy="no-referrer"/>:<div className="social-profile-game-placeholder"><Gamepad2/></div>}
+ <XboxProfileGameArt game={game}/>
<div><h4>{game.name}</h4>{game.lastPlayed?<p>{ui("ui.last_played_63abe4e")} {new Date(game.lastPlayed).toLocaleDateString()}</p>:null}
{progress.achievements?<p>{progress.achievements}</p>:null}
{progress.gamerscore?<p><b className="social-score-icon" aria-hidden="true">G</b> {progress.gamerscore}</p>:null}
diff --git a/src/renderer/xbox-profile-games-artwork.test.tsx b/src/renderer/xbox-profile-games-artwork.test.tsx
new file mode 100644
index 0000000..d4444fb
--- /dev/null
+++ b/src/renderer/xbox-profile-games-artwork.test.tsx
@@ -0,0 +1,47 @@
+// @vitest-environment jsdom
+import {act} from 'react';
+import {createRoot,type Root} from 'react-dom/client';
+import {afterEach,beforeEach,expect,it,vi} from 'vitest';
+import type {XboxProfileGame,XboxProfileGames as ProfileGames,XboxSocialApi} from '../shared/types';
+import {XboxProfileGames} from './XboxProfileGames';
+
+let root:Root,node:HTMLDivElement;
+const game=(patch:Partial<XboxProfileGame>={}):XboxProfileGame=>({titleId:'123',name:'Synthetic Game',...patch});
+const api=(value:ProfileGames|Error)=>({getXboxPlayerGames:vi.fn(async()=>{if(value instanceof Error)throw value;return value;})} as unknown as XboxSocialApi);
+const mount=async(element:React.ReactElement)=>{
+ await act(async()=>{root.render(element);});
+ await act(async()=>{await Promise.resolve();});
+};
+beforeEach(()=>{
+ Object.assign(globalThis,{IS_REACT_ACT_ENVIRONMENT:true});
+ node=document.createElement('div');document.body.append(node);root=createRoot(node);
+});
+afterEach(async()=>{
+ await act(async()=>root.unmount());
+ node.remove();vi.restoreAllMocks();document.body.innerHTML='';
+});
+
+it('shows an accessible placeholder when the service supplies no artwork',async()=>{
+ await mount(<XboxProfileGames api={api({items:[game()],continuation:null,truncated:false})} xuid="2"/>);
+ expect(node.querySelector('img')).toBeNull();
+ const placeholder=node.querySelector('[role="img"]')!;
+ expect(placeholder.getAttribute('aria-label')).toBe('Artwork unavailable');
+ expect(node.textContent).toContain('Synthetic Game');
+});
+
+it('renders artwork without a referrer and falls back to the placeholder after a load error',async()=>{
+ await mount(<XboxProfileGames api={api({items:[game({imageUrl:'https://store-images.s-microsoft.com/image/boxart'})],continuation:null,truncated:false})} xuid="2"/>);
+ const image=node.querySelector('img')!;
+ expect(image.getAttribute('src')).toBe('https://store-images.s-microsoft.com/image/boxart');
+ expect(image.getAttribute('referrerpolicy')).toBe('no-referrer');
+ expect(image.getAttribute('alt')).toBe('');
+ await act(async()=>{image.dispatchEvent(new Event('error',{bubbles:true}));});
+ expect(node.querySelector('img')).toBeNull();
+ expect(node.querySelector('[role="img"]')?.getAttribute('aria-label')).toBe('Artwork unavailable');
+});
+
+it('keeps the history failure isolated from the profile shell',async()=>{
+ await mount(<XboxProfileGames api={api(Error('private'))} xuid="2"/>);
+ expect(node.textContent).toContain('It may be private');
+ expect(node.querySelector('button')?.textContent).toContain('Try again');
+});