Skip to content

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

TypeScript

feat(accounts): separate Store licensing and Xbox player sessions

Claude03ce7a3284d9
diff --git a/assets/locales/en.json b/assets/locales/en.json
index c947325..64aa7bc 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -1,4 +1,7 @@
{
+ "auth.sign_out_active_help": "Signs out active Store and player accounts and removes device registration. Saved Store accounts remain available until forgotten.",
+ "auth.active_signed_out": "Active accounts signed out. Saved Store accounts are retained.",
+ "auth.sign_out_all": "Sign out all accounts",
"runtime.build_changed": "The installed runtime build changed or has not been approved. Review it and explicitly choose a new separate prefix. Existing local saves stay in the old prefix.",
"runtime.game_runtime": "Game runtime",
"runtime.use_default": "Use default runtime",
@@ -629,6 +632,20 @@
"ui.pinned_backend_source_was_built_and_activated_70c1519": "Pinned backend source was built and activated.",
"ui.play_436e610": "Play",
"ui.play_state_6f423d1": "Play state",
+ "ui.no_separate_player_account_44980b5": "No separate player account",
+ "ui.saved_store_accounts_a1c4e72": "Saved Store accounts",
+ "ui.account_in_use_5b09d3f": "In use",
+ "ui.use_this_account_e71c0a8": "Use this account",
+ "ui.forget_account_3d8f6b1": "Forget",
+ "ui.saved_store_accounts_help_94be2d0": "Store and Game Pass accounts you signed in with stay saved. Each game starts with the account it was installed with.",
+ "ui.account_switched_6a2e91c": "Store account switched",
+ "ui.account_forgotten_c05d7e3": "Saved account forgotten",
+ "ui.player_account_help_1d6f365": "The account above owns the games and the subscription. Add a second account here to play, earn achievements and sync cloud saves under it.",
+ "ui.player_account_signed_in_ac36aa2": "Player account signed in",
+ "ui.player_account_signed_out_6752e8f": "Player account signed out",
+ "ui.sign_in_player_account_c15aa58": "Sign in player account",
+ "ui.sign_out_player_account_013bd34": "Sign out player account",
+ "ui.xbox_player_account_021c236": "Xbox player account",
"ui.please_report_nexus_issues_only_in_the_c9de146": "Please report Nexus issues only in the",
"ui.preparing_5d1fa38": "Preparing…",
"ui.preparing_sign_in_cdca952": "Preparing sign-in…",
diff --git a/assets/locales/es.json b/assets/locales/es.json
index 49285c8..03b1e10 100644
--- a/assets/locales/es.json
+++ b/assets/locales/es.json
@@ -558,8 +558,11 @@
"ui.accept_89713b9": "Aceptar",
"ui.access_ec5ba0a": "Acceso",
"ui.account_backend_runtime_and_storage_11bda06": "Cuenta, backend, runtime y almacenamiento.",
+ "ui.account_forgotten_c05d7e3": "Cuenta guardada olvidada",
+ "ui.account_in_use_5b09d3f": "En uso",
"ui.account_status_is_still_being_checked_3a41b4e": "Aún se está comprobando el estado de la cuenta",
"ui.account_status_unavailable_3b97a47": "Estado de la cuenta no disponible",
+ "ui.account_switched_6a2e91c": "Cuenta de la Tienda cambiada",
"ui.achievement_progress_437de55": "Progreso de logros",
"ui.achievements_74cf2bc": "Logros",
"ui.action_unavailable_6342da9": "{{game}}, {{status}}. Acción no disponible",
@@ -678,6 +681,7 @@
"ui.finish_the_current_package_selection_first_4baf7cf": "Termina primero la selección de paquete actual.",
"ui.finished_queue_entries_cleared_game_files_were_k_230b4d1": "Se han borrado las entradas terminadas de la cola. Se han conservado los archivos de los juegos.",
"ui.for_example_9n4pt8hgcdhq_b6119c7": "Por ejemplo: 9N4PT8HGCDHQ",
+ "ui.forget_account_3d8f6b1": "Olvidar",
"ui.friends_bd104d1": "Amigos",
"ui.friends_list_e79cc91": "Lista de amigos",
"ui.from_xbox_availability_and_progress_may_vary_by_e4913f8": "De Xbox. La disponibilidad y el progreso pueden variar según el juego. Esta vista nunca desbloquea ni actualiza logros.",
@@ -821,6 +825,7 @@
"ui.no_related_add_ons_were_found_for_this_game_37fb940": "No se han encontrado complementos relacionados con este juego.",
"ui.no_runtime_selected_b8e7445": "Ningún runtime seleccionado",
"ui.no_screenshots_available_284d07a": "No hay capturas de pantalla disponibles.",
+ "ui.no_separate_player_account_44980b5": "Sin cuenta de jugador independiente",
"ui.no_supported_windows_desktop_msixvc_package_was_1f39e19": "No se ha encontrado ningún paquete MSIXVC Windows.Desktop compatible para esta oferta de la tienda.",
"ui.no_xbox_achievements_are_available_for_this_game_9615682": "Este juego no tiene logros de Xbox disponibles.",
"ui.not_an_official_xodus_project_d61df4f": "no es un proyecto oficial de Xodus",
@@ -862,6 +867,9 @@
"ui.pinned_backend_source_was_built_and_activated_70c1519": "Se ha compilado y activado la versión fijada del código fuente del backend.",
"ui.play_436e610": "Jugar",
"ui.play_state_6f423d1": "Estado de juego",
+ "ui.player_account_help_1d6f365": "La cuenta de arriba posee los juegos y la suscripción. Añade aquí una segunda cuenta para jugar, conseguir logros y sincronizar las partidas en la nube con ella.",
+ "ui.player_account_signed_in_ac36aa2": "Cuenta de jugador con sesión iniciada",
+ "ui.player_account_signed_out_6752e8f": "Sesión de la cuenta de jugador cerrada",
"ui.please_report_nexus_issues_only_in_the_c9de146": "Informa de los problemas de Nexus solo en el",
"ui.preparing_5d1fa38": "Preparando…",
"ui.preparing_sign_in_cdca952": "Preparando el inicio de sesión…",
@@ -926,6 +934,8 @@
"ui.save_download_limit_8abf702": "Guardar límite de descarga",
"ui.save_report_8ec314b": "Guardar informe",
"ui.saved_sign_in_credentials_and_local_device_regis_c9738bd": "Se han eliminado las credenciales de inicio de sesión guardadas y el registro local del dispositivo.",
+ "ui.saved_store_accounts_a1c4e72": "Cuentas de tienda guardadas",
+ "ui.saved_store_accounts_help_94be2d0": "Las cuentas de la Tienda y de Game Pass con las que iniciaste sesión quedan guardadas. Cada juego se inicia con la cuenta con la que se instaló.",
"ui.screenshot_a41bf12": "Captura {{index}} de {{game}}",
"ui.screenshots_067348c": "Capturas de pantalla",
"ui.screenshots_25e204e": "Capturas de pantalla de {{game}}",
@@ -957,12 +967,14 @@
"ui.showing_the_latest_100_messages_older_messages_a_7fb43bf": "Se muestran los últimos 100 mensajes. Los mensajes anteriores no se cargan.",
"ui.sign_in_again_51fbe1d": "Volver a iniciar sesión",
"ui.sign_in_bfd402b": "Iniciar sesión",
+ "ui.sign_in_player_account_c15aa58": "Iniciar sesión con la cuenta de jugador",
"ui.sign_in_to_load_your_account_games_installed_gam_580df7e": "Inicia sesión para cargar los juegos de tu cuenta. Los juegos instalados siguen disponibles.",
"ui.sign_in_to_view_xbox_activity_8f133b5": "Inicia sesión para ver la actividad de Xbox.",
"ui.sign_in_to_view_your_xbox_achievements_970a464": "Inicia sesión para ver tus logros de Xbox.",
"ui.sign_in_to_your_microsoft_account_in_settings_fi_187cd60": "Inicia sesión primero con tu cuenta Microsoft en Configuración.",
"ui.sign_in_with_xodus_252572f": "Iniciar sesión con Xodus",
"ui.sign_out_48f0d3d": "Cerrar sesión",
+ "ui.sign_out_player_account_013bd34": "Cerrar sesión de la cuenta de jugador",
"ui.signed_in_as_d7e6f22": "Sesión iniciada como {{name}}",
"ui.signed_out_db8436b": "SESIÓN CERRADA",
"ui.signing_in_can_also_be_done_later_from_settings_7753fd0": "También puedes iniciar sesión más tarde desde Configuración.",
@@ -1037,6 +1049,7 @@
"ui.updates_and_dlc_keep_their_files_to_protect_the_22f35d6": "Las actualizaciones y los DLC conservan sus archivos para proteger el juego instalado.",
"ui.updating_dfe40ef": "Actualizando…",
"ui.use_start_service_or_unlock_wallet_for_this_sess_de70f4d": "Usa Iniciar servicio o Desbloquear cartera para esta sesión. Crear cartera abre el diálogo de configuración de tu proveedor cuando no hay ninguna colección. Si la configuración no está disponible aquí, complétala en el modo Escritorio.",
+ "ui.use_this_account_e71c0a8": "Usar esta cuenta",
"ui.validated_3dac322": "VALIDADO",
"ui.verbose_game_logs_58e750b": "Registros detallados del juego",
"ui.verify_and_install_27d773b": "Verificar e instalar",
@@ -1063,6 +1076,7 @@
"ui.xbox_activity_may_be_delayed_or_unavailable_for_c15dd35": "La actividad de Xbox puede llegar con retraso o no estar disponible en algunos juegos. El tiempo de sesión local no se suma al total de Xbox.",
"ui.xbox_friends_and_chat_84d8cb6": "Amigos y chat de Xbox",
"ui.xbox_has_no_activity_available_for_this_game_1316723": "Xbox no tiene actividad disponible para este juego.",
+ "ui.xbox_player_account_021c236": "Cuenta de jugador de Xbox",
"ui.xbox_profile_picture_f6ca315": "Imagen de perfil de Xbox",
"ui.xbox_time_played_1e875b7": "Tiempo jugado en Xbox",
"ui.xodus_backend_a99abd3": "Backend de Xodus",
diff --git a/src/main/account-profile.test.ts b/src/main/account-profile.test.ts
index 71db9f5..02111ac 100644
--- a/src/main/account-profile.test.ts
+++ b/src/main/account-profile.test.ts
@@ -114,3 +114,23 @@ it('retains a fresh subscription only for the matching account and removes it on
await profile.select(undefined); expect(profile.value?.subscription).toBeUndefined();
} finally { await fs.rm(root, { recursive: true, force: true }); }
});
+
+it('keeps Store membership and player profile in separate identity caches', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-separate-profiles-'));
+ try {
+ const subscription = { status: 'active', productIds: ['CFQ7TTC0KGQ8'], checkedAt: new Date().toISOString() };
+ const store = new AccountProfile(root, () => {}, value => value, async () => JSON.stringify({ schema: 1, account: '[email protected]', gamertag: 'StoreOwner', subscription }), true);
+ const player = new AccountProfile(root, () => {}, value => value, async () => JSON.stringify({ schema: 1, account: '[email protected]', gamertag: 'PersonalPlayer' }));
+ await store.select('[email protected]', '/fake/backend'); await store.settled();
+ await player.select('[email protected]', '/fake/backend'); await player.settled();
+ expect(store.value?.subscription).toEqual(subscription);
+ expect(player.value?.gamertag).toBe('PersonalPlayer');
+ expect(player.value?.subscription).toBeUndefined();
+ await player.select(undefined);
+ expect(store.value?.subscription).toEqual(subscription);
+ const cachedStore = new AccountProfile(root, () => {}, value => value, undefined, true);
+ await cachedStore.select('[email protected]');
+ expect(cachedStore.value?.gamertag).toBe('StoreOwner');
+ expect(cachedStore.value?.subscription).toEqual(subscription);
+ } finally { await fs.rm(root, { recursive: true, force: true }); }
+});
diff --git a/src/main/account-profile.ts b/src/main/account-profile.ts
index d1669dd..63208fd 100644
--- a/src/main/account-profile.ts
+++ b/src/main/account-profile.ts
@@ -10,9 +10,9 @@ type Reader = (binary: string, signal: AbortSignal) => Promise<string>;
const name = (value: unknown): value is string => typeof value === 'string' && Boolean(value.trim()) && value.length <= 128 && !/[\x00-\x1f\x7f]/.test(value);
const image = (value: unknown): value is string => typeof value === 'string' && value.length < 3_000_000 && /^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(value);
-async function readProfile(binary: string, signal: AbortSignal): Promise<string> {
+async function readProfileWith(args: string[], binary: string, signal: AbortSignal): Promise<string> {
signal.throwIfAborted();
- const tracked = spawnTracked(binary, ['profile', '--json'], { maxOutput: 4_000_000, stdoutOnly: true });
+ const tracked = spawnTracked(binary, args, { maxOutput: 4_000_000, stdoutOnly: true });
const stop = () => { tracked.child.kill('SIGKILL'); };
signal.addEventListener('abort', stop, { once: true });
if (signal.aborted) stop();
@@ -25,6 +25,9 @@ async function readProfile(binary: string, signal: AbortSignal): Promise<string>
} finally { clearTimeout(timer); signal.removeEventListener('abort', stop); }
}
+const readProfile: Reader = (binary, signal) => readProfileWith(['profile', '--json'], binary, signal);
+const readLicenseProfile: Reader = (binary, signal) => readProfileWith(['profile', '--json', '--license'], binary, signal);
+
/** Only the currently stored account can publish/cache a profile result. */
export class AccountProfile {
value?: XboxProfile;
@@ -36,9 +39,11 @@ export class AccountProfile {
private job?: Promise<void>;
private disk: Promise<void> = Promise.resolve();
private readonly file: string;
+ private readonly reader: Reader;
constructor(userData: string, private changed: () => void,
- private normalize: (dataUrl: string) => string | undefined, private reader: Reader = readProfile) {
- this.file = path.join(userData, 'xbox-profile.json');
+ private normalize: (dataUrl: string) => string | undefined, reader?: Reader, license = false) {
+ this.reader = reader ?? (license ? readLicenseProfile : readProfile);
+ this.file = path.join(userData, license ? 'xbox-profile-license.json' : 'xbox-profile.json');
}
cancel(): void { this.generation++; this.controller?.abort(); this.controller = undefined; }
async settled(): Promise<void> { await this.job; await this.disk; }
diff --git a/src/main/auth-actions.test.ts b/src/main/auth-actions.test.ts
index e8c18f1..7979f1f 100644
--- a/src/main/auth-actions.test.ts
+++ b/src/main/auth-actions.test.ts
@@ -20,7 +20,7 @@ function fixture(code = 0) {
backend: { current: { capabilities: { externalAuth: true } } },
prepareSystemWallet: vi.fn(async () => {}), fallbackAuthViewFactory: vi.fn(() => ({})),
authViewFactory: vi.fn(), browserAuthViewFactory: vi.fn(), mainWindow: undefined,
- shutdownStarted: false, accountProfile: { select: vi.fn(async () => {}) },
+ shutdownStarted: false, licenseProfile: undefined, nativeText: (text: string) => text, process: { env: {} }, accountProfile: { select: vi.fn(async () => {}) },
startAuthTransport: vi.fn(() => tracked), spawnTracked: vi.fn(() => tracked),
emitLog: vi.fn(), operations: new Map(), refreshAccount: vi.fn(async () => {}), authJob: undefined,
revokeOffline: vi.fn(async () => {}),
@@ -53,7 +53,7 @@ describe('explicit account actions', () => {
await expect(runInContext("requestAuth('logout')", context)).rejects.toThrow(`exited with code ${code}`);
expect(context.spawnTracked).toHaveBeenCalledOnce();
expect(context.spawnTracked).toHaveBeenCalledWith('/synthetic/backend', ['logout', '--device'], expect.any(Object));
- expect(context.refreshAccount).not.toHaveBeenCalled();
+ expect(context.refreshAccount).toHaveBeenCalledWith(false, true);
// A failed device reset still drops offline licenses: the user asked to sign out.
expect(context.revokeOffline).toHaveBeenCalledOnce(); expect(context.revokeOffline).toHaveBeenCalledWith('sign-out');
expect(context.authState).toMatchObject({ running: false, lastResult: 'failed' });
@@ -99,3 +99,19 @@ describe('explicit account actions', () => {
expect(context.spawnTracked).toHaveBeenCalledOnce();
});
});
+
+it('signs out only the player without resetting Store device or offline licensing', async () => {
+ const context=fixture();context.backend.current.capabilities.playerAccount=true;
+ await runInContext("requestAuth('logout',true)",context);
+ expect(context.spawnTracked).toHaveBeenCalledWith('/synthetic/backend',['logout','--player'],expect.any(Object));
+ expect(context.revokeOffline).not.toHaveBeenCalled();
+ expect(context.refreshAccount).toHaveBeenCalledWith(false,true);
+});
+it('reconciles stored identities after a cancelled player transport', async () => {
+ const context=fixture();context.backend.current.capabilities.playerAccount=true;
+ context.startAuthTransport.mockImplementation(()=>({child:{},result:Promise.reject(Error('cancelled'))}));
+ await expect(runInContext("requestAuth('login',true)",context)).rejects.toThrow('cancelled');
+ expect(context.refreshAccount).toHaveBeenCalledWith(false,true);
+ expect(context.authState.running).toBe(false);expect(context.authJob).toBeUndefined();
+ expect(context.revokeOffline).not.toHaveBeenCalled();
+});
diff --git a/src/main/auth-transport.test.ts b/src/main/auth-transport.test.ts
index b2fc41e..409ac19 100644
--- a/src/main/auth-transport.test.ts
+++ b/src/main/auth-transport.test.ts
@@ -44,7 +44,7 @@ describe('private auth transport', () => {
else expect((await tracked.result).code).toBe(0);
} finally { await fs.rm(root, { recursive: true, force: true }); }
});
- it.each(['success', 'invalid', 'no-handshake', 'cancel', 'load-failure', 'credential-failure', 'unknown-credential'])('handles %s without exposing protocol output', async mode => {
+ it.each([false, true].flatMap(player => ['success', 'invalid', 'no-handshake', 'cancel', 'load-failure', 'credential-failure', 'unknown-credential'].map(mode => ({player, mode}))))('handles $mode, player=$player without exposing protocol output', async ({mode, player}) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'nexus-auth-fixture-'));
let disposed = false, opens = 0, closes = 0;
try {
@@ -54,7 +54,8 @@ describe('private auth transport', () => {
async open(frame) { opens++; if (mode === 'cancel') cancel(frame.session); else if (mode === 'load-failure') throw Error('synthetic-secret'); else send(frame.session, '{"synthetic":"not-a-real-token"}'); },
close() { closes++; }, async context() {}, async dispose() { disposed = true; },
});
- const tracked = startAuthTransport(binary, factory, { ...process.env, FIXTURE_MODE: mode }, 3000);
+ const tracked = startAuthTransport(binary, factory, { ...process.env, FIXTURE_MODE: mode }, 3000, player);
+ expect(tracked.child.spawnargs).toEqual([binary, '--external-webview-stdio', 'login', ...(player ? ['--player'] : [])]);
if (mode === 'credential-failure') { await expect(tracked.result).rejects.toThrow('keyring did not return the credentials just saved'); expect(opens).toBe(0); }
else if (mode === 'invalid' || mode === 'no-handshake' || mode === 'load-failure' || mode === 'unknown-credential') await expect(tracked.result).rejects.toThrow(/sign-in/i);
else { const result = await tracked.result; expect(result.code).toBe(mode === 'cancel' ? 1 : 0); expect(result.output).toBe(''); }
diff --git a/src/main/auth-transport.ts b/src/main/auth-transport.ts
index 6fe5e7a..06788c9 100644
--- a/src/main/auth-transport.ts
+++ b/src/main/auth-transport.ts
@@ -12,12 +12,12 @@ export interface AuthView {
}
export type AuthViewFactory = (send: (session: number, payload: string) => void, cancel: (session: number) => void, fail: () => void) => AuthView;
-export function startAuthTransport(binary: string, createView: AuthViewFactory, environment: NodeJS.ProcessEnv = process.env, timeoutMs = 600_000): {
+export function startAuthTransport(binary: string, createView: AuthViewFactory, environment: NodeJS.ProcessEnv = process.env, timeoutMs = 600_000, player = false): {
child: ChildProcessWithoutNullStreams; result: Promise<{ code: number; output: string }>;
} {
// This explicit flag is absent in the native backend. Never fall back to an
// incompatible handshake. The backend uses only these private stdio pipes.
- const child = spawn(binary, ['--external-webview-stdio', 'login'], {
+ const child = spawn(binary, ['--external-webview-stdio', 'login', ...(player ? ['--player'] : [])], {
env: { ...externalLauncherEnvironment(environment), XODUS_LOG: 'off', RUST_LOG: 'off' }, stdio: ['pipe', 'pipe', 'pipe'], shell: false,
});
observeBackendChild(child, 'login');
diff --git a/src/main/backend.ts b/src/main/backend.ts
index 6c0da36..a580404 100644
--- a/src/main/backend.ts
+++ b/src/main/backend.ts
@@ -88,6 +88,14 @@ export class BackendManager {
&& designation?.code === 0 && /(?:^|\s)--license-cache(?:\s|$)/m.test(designation.output);
capabilities.offlineLaunch = Boolean(capabilities.licenseCache && /(?:^|\s)--offline(?:\s|$)/m.test(launch.output));
}
+ if (capabilities.login) {
+ const login = await run(binaryPath, ['login', '--help'], { maxOutput: 100_000 });
+ capabilities.playerAccount = login.code === 0 && /(?:^|\s)--player(?:\s|$)/m.test(login.output);
+ const profileHelp = await run(binaryPath, ['profile', '--help']);
+ capabilities.licenseProfile = profileHelp.code === 0 && /(?:^|\s)--license(?:\s|$)/m.test(profileHelp.output);
+ const saved = await run(binaryPath, ['saved-accounts', '--help']);
+ capabilities.savedAccounts = saved.code === 0;
+ }
return capabilities.login && capabilities.streaming ? capabilities : null;
} catch (error) { if (error instanceof BackendPrerequisiteError) throw error; return null; }
}
diff --git a/src/main/game-catalog-detail-ipc.test.ts b/src/main/game-catalog-detail-ipc.test.ts
index da455be..88d55d0 100644
--- a/src/main/game-catalog-detail-ipc.test.ts
+++ b/src/main/game-catalog-detail-ipc.test.ts
@@ -9,7 +9,7 @@ const start=source.indexOf(" ipcMain.handle('game-details'",source.indexOf('fun
const code=ts.transpileModule(source.slice(start,source.indexOf(" ipcMain.handle('launch-game'",start)),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
function fixture(){
const handlers=new Map<string,Function>(),games=demoSnapshot().games;
- const authState={stored:true,running:false,username:'fixture-account'},backend={current:{binaryPath:'/fixture/cli',capabilities:{gameActivity:true,achievements:true}}};
+ const authState={stored:true,running:false,username:'fixture-account',player:undefined as string|undefined},backend={current:{binaryPath:'/fixture/cli',capabilities:{gameActivity:true,achievements:true}}};
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');
@@ -49,3 +49,15 @@ it('rejects catalog metadata after a market change',async()=>{
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.each(['game-activity','game-achievements'])('%s uses the player identity and rejects a late player switch',async route=>{
+ const f=fixture();f.authState.player='personal-player';
+ await f.call(route,{productId:'9AAAAAAAAAAA'});
+ const selected=route==='game-activity'?f.gameActivities:f.gameAchievements;
+ expect(selected.select).toHaveBeenCalledWith('personal-player','/fixture/cli');
+ let resolve!:(value:{productId:string;xboxTitleId:string})=>void;
+ f.catalog.gameDetails.mockReturnValueOnce(new Promise(done=>resolve=done));
+ const pending=f.call(route,{productId:'9AAAAAAAAAAA'});
+ f.authState.player='other-player';resolve({productId:'9AAAAAAAAAAA',xboxTitleId:'123'});
+ expect(await pending).toEqual({status:'error'});
+});
diff --git a/src/main/index.ts b/src/main/index.ts
index f0ce0ad..2baff76 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -68,6 +68,7 @@ import { acceptSteamHandoff, captureSteamLaunchEnvironment, offerSteamHandoff, s
type SteamHandoff, type SteamLaunchEnvironment, type SteamLaunchLease } from './steam-launch-context.js';
import { loadShortcutIcon } from './shortcut-icon.js';
import { AccountProfile } from './account-profile.js';
+import { forgetSavedAccount, listSavedAccounts, useSavedAccount, validAccountName } from './saved-accounts.js';
import { AccountRefresh, readAccount } from './account-refresh.js';
import { AccountLibrary } from './account-library.js';
import { RecentPcGamePass } from './gamepass-recent.js';
@@ -150,7 +151,8 @@ let overlayShortcut:XboxOverlayShortcut|undefined;
const nativeSocialSnapshots:(()=>void)[]=[];
function nativeSocialConnection(){
const status=backend?.current;
- return !demoMode&&!authState.running&&authState.stored===true&&authState.username&&status?.available&&status.binaryPath&&status.capabilities.nativeSocial?{account:authState.username,binary:status.binaryPath}:undefined;
+ // Xbox Live sees the player account when one is stored, otherwise the license account.
+ return !demoMode&&!authState.running&&authState.stored===true&&authState.username&&status?.available&&status.binaryPath&&status.capabilities.nativeSocial?{account:authState.player??authState.username,binary:status.binaryPath}:undefined;
}
function resetNativeSocial(){for(const reset of nativeSocialResets)reset();xboxNativeSocial?.clear();resetSocialTransport();}
let nativeSocialBackend:string|undefined;
@@ -228,7 +230,7 @@ const xboxSocial = new XboxSocialSessions(() => {
const status = backend?.current;
return !shutdownStarted && !authState.running && authState.stored === true && authState.username
&& status?.available && status.binaryPath && status.capabilities.commands.includes('social')
- ? { account: authState.username, binary: status.binaryPath } : undefined;
+ ? { account: authState.player ?? authState.username, binary: status.binaryPath } : undefined;
});
const keyringSupport = new KeyringSupport(process.env, undefined, process.platform, undefined, {
diagnostic: value => backendDiagnostic({ operation: 'keyring', event: 'diagnostic', keyring: value, elapsedMs: value.elapsedMs }),
@@ -257,6 +259,8 @@ let gameUpdateJob: Promise<void> | undefined;
let snapshotTimer: ReturnType<typeof setTimeout> | undefined;
let shortcuts: GameShortcuts;
let accountProfile: AccountProfile;
+let licenseProfile: AccountProfile | undefined;
+let savedAccounts: string[] = [];
let preparingLaunch = false;
let preparingInstall = false;
let preparingContent = false;
@@ -362,7 +366,7 @@ function snapshot(): AppSnapshot {
downloads: structuredClone(store.downloads.map(task => downloadCancellations.has(task.id)
? { ...task, cancelling: true, canPause: false, phase: 'Cancelling download and checking files…' } : task)),
settings: structuredClone(store.settings),
- auth: structuredClone({ ...authState, gamertag: accountProfile?.value?.gamertag, avatarDataUrl: accountProfile?.value?.avatarDataUrl, subscription: accountProfile?.value?.subscription }),
+ auth: structuredClone({ ...authState, gamertag: accountProfile?.value?.gamertag, avatarDataUrl: accountProfile?.value?.avatarDataUrl, saved: savedAccounts, licenseAvatarDataUrl: authState.player ? licenseProfile?.value?.avatarDataUrl : undefined, subscription: (authState.player ? licenseProfile : accountProfile)?.value?.subscription }),
launcherUpdate: structuredClone(launcherUpdater.state),
gameUpdates: structuredClone(gameUpdates),
overlayShortcut:overlayShortcut?.current,
@@ -476,7 +480,7 @@ function requireBackend(command: keyof typeof backend.current.capabilities): str
function ensureIdle(mode?: 'install' | 'launch' | 'remove'): void {
if (offlinePermissionChanging) throw Error('Wait for the offline-permission change to finish.');
if (keyringSupport.busy) throw Error('Wait for the wallet operation to finish.');
- if (authState.running) throw Error('A sign-in operation is already in progress.');
+ if (authState.running || authJob) throw Error('A sign-in operation is already in progress.');
if (shutdownStarted) throw Error('The launcher is closing.');
if (downloadCancellations.size) throw Error('A download is being cancelled. Wait for its cleanup to finish.');
if (preparingInstall || preparingContent) throw new Error('An installation is being prepared.');
@@ -505,7 +509,7 @@ async function refreshAccount(emit = true, afterAuth = false): Promise<AuthStatu
const status = backend.current;
const key = accountRefreshKey();
await accountRefresh.run(key, async signal => {
- let next: Pick<AuthStatus, 'stored' | 'username' | 'note'>;
+ let next: Pick<AuthStatus, 'stored' | 'username' | 'player' | 'note'>;
if (!status.available || !status.binaryPath) {
next = { stored: null, username: undefined, note: 'Account status is unavailable because the Xodus backend is offline.' };
} else if (!status.capabilities.account) {
@@ -523,17 +527,19 @@ async function refreshAccount(emit = true, afterAuth = false): Promise<AuthStatu
} else {
try {
const line = result.output.split('\n').map((entry) => entry.trim()).reverse().find((entry) => entry.startsWith('{'));
- const account = JSON.parse(line ?? '') as { stored?: unknown; username?: unknown };
- if (account.stored === true && typeof account.username === 'string' && account.username.trim()) {
+ const account = JSON.parse(line ?? '') as { stored?: unknown; username?: unknown; player?: { username?: unknown } | null };
+ const player = status.capabilities.playerAccount && validAccountName(account.player?.username) ? account.player!.username!.trim() : '';
+ if (account.stored === true && validAccountName(account.username)) {
next = {
stored: true,
username: account.username.trim(),
+ player: player || undefined,
note: runtime?.current.name?.includes('-xgamesave-pr28-')
? 'Credentials are stored by Xodus. The experimental PR #28 runtime can try in-game Xbox sign-in and two-way cloud save sync; this account status alone does not verify either.'
: 'Credentials are stored by Xodus in the system keychain. This does not mean in-game Xbox platform sign-in is implemented.',
};
} else if (account.stored === false) {
- next = { stored: false, username: undefined, note: 'No Microsoft account is stored by Xodus.' };
+ next = { stored: false, username: undefined, player: player || undefined, note: 'No Microsoft Store account is stored by Xodus.' };
} else {
throw new Error('unexpected account response');
}
@@ -544,17 +550,24 @@ async function refreshAccount(emit = true, afterAuth = false): Promise<AuthStatu
}
return next;
}, async next => {
- if (authState.username !== next.username || next.stored !== true) xboxSocial.close();
- if(next.username!==authState.username||next.stored!==true)resetNativeSocial();
- authState = { ...authState, ...next };
+ if (authState.username !== next.username || authState.player !== next.player || next.stored !== true) xboxSocial.close();
+ if(next.username!==authState.username||next.player!==authState.player||next.stored!==true)resetNativeSocial();
+ // An error result carries no player, so a stale one must never survive it.
+ authState = { ...authState, player: undefined, ...next };
+ const selectedAuth = authState;
accountLibrary.select(authState.stored === true ? authState.username : undefined,
status.capabilities.library ? status.binaryPath : undefined, currentMarket());
- gameActivities.select(authState.stored === true ? authState.username : undefined,
+ gameActivities.select(authState.stored === true ? authState.player ?? authState.username : undefined,
status.capabilities.gameActivity ? status.binaryPath : undefined);
- gameAchievements.select(authState.stored === true ? authState.username : undefined,
+ gameAchievements.select(authState.stored === true ? authState.player ?? authState.username : undefined,
status.capabilities.achievements ? status.binaryPath : undefined);
- await accountProfile?.select(authState.stored === true ? authState.username : undefined,
+ await accountProfile?.select(authState.player ?? (authState.stored === true ? authState.username : undefined),
status.capabilities.profile ? status.binaryPath : undefined, emit);
+ const saved = status.capabilities.savedAccounts && status.binaryPath ? (await listSavedAccounts(status.binaryPath).catch(() => null))?.accounts ?? [] : [];
+ if (authState !== selectedAuth) return;
+ savedAccounts = saved;
+ await licenseProfile?.select(authState.stored === true && authState.player ? authState.username : undefined,
+ status.capabilities.licenseProfile ? status.binaryPath : undefined, emit);
}, () => key === accountRefreshKey() && (!authState.running || afterAuth));
if (emit) emitSnapshot();
return structuredClone(authState);
@@ -653,11 +666,12 @@ function verifyOfflineDesignation(): void {
.finally(() => { designationCheck = undefined; });
}
-async function runAuth(command: 'login' | 'logout'): Promise<void> {
+async function runAuth(command: 'login' | 'logout', player = false): Promise<void> {
ensureIdle();
for(const prepare of nativeSocialBeforeAuth)await prepare();
resetNativeSocial();
const binary = requireBackend(command);
+ if (player && !backend.current.capabilities.playerAccount) throw Error('Update the Nexus backend in Settings before using a separate player account.');
const id = `auth-${randomUUID()}`;
accountRefresh.invalidate();
accountLibrary.reset();
@@ -674,38 +688,70 @@ async function runAuth(command: 'login' | 'logout'): Promise<void> {
const view = fallbackAuthViewFactory(request => authViewFactory(mainWindow ?? undefined, undefined, request, nativeText), () => browserAuthViewFactory());
if (shutdownStarted) throw Error('The launcher is closing.');
await accountProfile.select(undefined);
+ await licenseProfile?.select(undefined);
if (shutdownStarted) throw Error('The launcher is closing.');
- const tracked = command === 'login' ? startAuthTransport(binary, view)
+ const tracked = command === 'login' ? (player ? startAuthTransport(binary, view, process.env, undefined, true) : startAuthTransport(binary, view))
// Explicit sign-out removes the local device registration too. Ordinary
// sign-in must keep it, including when renewing an existing account.
- : spawnTracked(binary, ['logout', '--device'], { onLine: (line) => emitLog('auth', line) });
+ // Signing out only the player account never touches the license account or the device.
+ : spawnTracked(binary, player ? ['logout', '--player'] : ['logout', '--device'], { onLine: (line) => emitLog('auth', line) });
operations.set(id, tracked.child);
const result = await tracked.result;
accountRefresh.invalidate();
// Another account signing in is caught before its first launch (bindOfflineAccess).
- if (command === 'logout') await revokeOffline('sign-out');
- if (result.code === 0) await refreshAccount(false, true);
+ if (command === 'logout' && !player) await revokeOffline('sign-out');
authState = {
...authState,
- running: false,
+ running: true,
lastAction: command,
lastResult: result.code === 0 ? 'success' : 'failed',
};
if (result.code !== 0) throw new Error(`xodus-cli ${command} exited with code ${result.code}.`);
} finally {
operations.delete(id);
- authState.running = false;
- emitSnapshot();
+ try { if (!shutdownStarted) await refreshAccount(false, true); }
+ finally { authState.running = false; emitSnapshot(); }
}
}
-function requestAuth(command: 'login' | 'logout'): Promise<void> {
+function requestAuth(command: 'login' | 'logout', player = false): Promise<void> {
if (authJob) return Promise.reject(Error('A sign-in operation is already in progress.'));
- const job = runAuth(command); authJob = job;
+ const job = player ? runAuth(command, true) : runAuth(command); authJob = job;
const clear = () => { if (authJob === job) authJob = undefined; };
void job.then(clear, clear); return job;
}
+/** Reserve the auth job before any asynchronous preparation or credential mutation. */
+function requestSavedAccount(action: 'use' | 'forget', name: unknown): Promise<void> {
+ ensureIdle();
+ const binary = backend.current.binaryPath;
+ if (typeof name !== 'string' || !binary || !backend.current.capabilities.savedAccounts) return Promise.reject(Error('Saved accounts are not available.'));
+ const job = Promise.resolve().then(async () => {
+ authState = { ...authState, running: true };
+ accountRefresh.invalidate();
+ accountLibrary.reset();
+ gameActivities.select(); gameAchievements.select(); xboxSocial.close();
+ emitSnapshot();
+ try {
+ for (const prepare of nativeSocialBeforeAuth) await prepare();
+ resetNativeSocial();
+ await accountProfile.select(undefined);
+ await licenseProfile?.select(undefined);
+ if (shutdownStarted) throw Error('The launcher is closing.');
+ if (action === 'use') await useSavedAccount(binary, name);
+ else await forgetSavedAccount(binary, name);
+ } finally {
+ accountRefresh.invalidate();
+ try { if (!shutdownStarted) await refreshAccount(false, true); }
+ finally { authState.running = false; emitSnapshot(); }
+ }
+ });
+ authJob = job;
+ const clear = () => { if (authJob === job) authJob = undefined; };
+ void job.then(clear, clear);
+ return job;
+}
+
async function startInstall(request: InstallRequest, updateGame?: Game, resumed?: DownloadTask): Promise<string> {
await stopGameUpdateCheck();
ensureIdle('install');
@@ -940,7 +986,7 @@ async function runDownload(task: DownloadTask, binary: string, market: string, u
delete gameUpdates[updateGame.id];
}
}
- else await store.upsertGame({ ...inspected, offerProductId: /^[A-Z0-9]{12}$/.test(task.productId) ? task.productId : undefined });
+ else await store.upsertGame({ ...inspected, licenseAccount: authState.username, offerProductId: /^[A-Z0-9]{12}$/.test(task.productId) ? task.productId : undefined });
} catch (error) {
if (updateGame) await refreshIncompleteUpdate(updateGame).catch(() => {});
if (updateGame && task.status === 'complete') {
@@ -1099,6 +1145,18 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<
if (task.gameId === id || installPathsOverlap(target, await canonicalInstallPath(task.destination))) throw Error('Finish or cancel this game\'s installation before playing it.');
}
if (await refreshIncompleteUpdate(game)) { emitSnapshot(); throw Error(INCOMPLETE_UPDATE_MESSAGE); }
+ if (game.licenseAccount && game.licenseAccount !== authState.username
+ && savedAccounts.includes(game.licenseAccount) && backend.current.binaryPath && backend.current.capabilities.savedAccounts) {
+ // Changing Store credentials must not race a download using another account.
+ assertActivityCompatible(operations.keys(), store.downloads, gameOperation, installQueue.size);
+ // The game was installed with another saved Store account: use that one, no sign-in needed.
+ for (const prepare of nativeSocialBeforeAuth) await prepare();
+ resetNativeSocial(); xboxSocial.close();
+ await useSavedAccount(backend.current.binaryPath, game.licenseAccount);
+ accountRefresh.invalidate();
+ await refreshAccount(false, true);
+ if (authState.stored !== true || authState.username !== game.licenseAccount) throw Error('The saved Store account could not be activated. Sign in to it again.');
+ }
const inspected = await inspectGameDirectory(game.path);
await store.patchGame(id, {
installState: inspected.installState,
@@ -1291,8 +1349,8 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<
const inviteRuntime=await gameInviteRuntime(wine);
gameInviteUnavailableReason=!inviteRuntime?'The selected runtime does not support game invitations. Update the runtime and restart the game.':!titleId?'The game has no Xbox title information for invitations.':undefined;
if(titleId&&/^[a-f0-9]{1,8}$/i.test(titleId)&&inviteRuntime){
- const account=authState.username,epoch=xboxSocial.epoch;
- const current=()=>!shutdownStarted&&authState.stored===true&&authState.username===account&&xboxSocial.epoch===epoch;
+ const account=authState.player??authState.username,epoch=xboxSocial.epoch;
+ const current=()=>!shutdownStarted&&authState.stored===true&&(authState.player??authState.username)===account&&xboxSocial.epoch===epoch;
inviteBridge=new GameInviteBridge(operationId,game.title,String(parseInt(titleId,16)),current,emitSnapshot,()=>{void showFriends().catch(()=>{});},Date.now,sender=>{
if(!Notification.isSupported())return;
try{const notice=new Notification({title:nativeText('Game invitation'),body:nativeText(`${sender} invited you to ${game.title}. Open Friends to accept.`),urgency:'normal'});notice.on('click',()=>{void showFriends().catch(()=>{});});notice.on('failed',()=>{});notice.show();}catch{/* The dock remains available without desktop notifications. */}
@@ -1303,7 +1361,7 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<
}catch{await inviteBridge.stop().catch(()=>{});inviteBridge=undefined;gameInviteUnavailableReason='The game invitation connection could not be started. Restart the game to try again.';addGameLog('Optional game invitations are unavailable for this launch.');}
}
// Names the account for the runtime's offline identity cache (an opaque key, never the username).
- if (authState.stored === true && authState.username) environment.XODUS_ACCOUNT_HASH = accountCacheKey(authState.username);
+ if (authState.stored === true && authState.username) environment.XODUS_ACCOUNT_HASH = accountCacheKey(authState.player ?? authState.username);
if (protonRunner) addGameLog(`Proton prefix: ${protonRunner.compatibilityDataPath}/pfx`);
else await fs.mkdir(legacyPrefixRoot, { recursive: true });
steamSignal?.throwIfAborted();
@@ -1585,6 +1643,8 @@ function registerDemoIpc(catalogMarket: () => string): void {
ipcMain.handle('save-diagnostic-report', (_event, content: unknown) => saveReviewedReport(content));
ipcMain.handle('login', () => {});
ipcMain.handle('logout', () => {});
+ ipcMain.handle('use-account', () => {});
+ 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));
@@ -1810,8 +1870,10 @@ function registerIpc(): void {
if (!gameOperation?.logPath || gameOperation.id !== id) throw new Error('This diagnostic log is no longer available.');
await copyDiagnosticFile(gameOperation.logPath, path.join(path.dirname(store.settings.runtimeRoot), 'logs'), text => clipboard.writeText(text));
});
- ipcMain.handle('login', () => requestAuth('login'));
- ipcMain.handle('logout', () => requestAuth('logout'));
+ ipcMain.handle('use-account', (_event, name: unknown) => requestSavedAccount('use', name));
+ ipcMain.handle('forget-account', (_event, name: unknown) => requestSavedAccount('forget', name));
+ ipcMain.handle('login', (_event, player?: unknown) => player === true ? requestAuth('login', true) : requestAuth('login'));
+ ipcMain.handle('logout', (_event, player?: unknown) => player === true ? requestAuth('logout', true) : requestAuth('logout'));
ipcMain.handle('offline-permissions', async () => {
if (offlinePermissionChanging) throw Error('Wait for the offline-permission change to finish.');
if (authState.running || authState.stored !== true || !authState.username) throw Error('Sign in before changing offline permissions.');
@@ -1986,15 +2048,15 @@ function registerIpc(): void {
const target=gameDetailsTarget(id,store.games),market=currentMarket();
if (authState.running || authState.stored !== true || !authState.username) return { status: 'signed-out' };
if (!backend.current.capabilities.gameActivity || !backend.current.binaryPath) return { status: 'unsupported' };
- const account = authState.username, binary = backend.current.binaryPath;
+ const account = authState.player ?? authState.username, binary = backend.current.binaryPath;
gameActivities.select(account, binary);
let title:string|undefined;
try{title=target.game?await installedTitleId(target.game.path):await catalog.gameDetails(target.productId!,market).then(details=>details?.xboxTitleId);}
catch{return {status:'error'};}
if (!title) return { status: 'unavailable' };
- if (authState.running || authState.stored !== true || account !== authState.username || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
const activity = await gameActivities.get(title, refresh);
- if (authState.running || authState.stored !== true || account !== authState.username || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
return activity;
});
ipcMain.handle('game-achievements', async (_event, id: unknown, refresh = false) => {
@@ -2002,15 +2064,15 @@ function registerIpc(): void {
const target=gameDetailsTarget(id,store.games),market=currentMarket();
if (authState.running || authState.stored !== true || !authState.username) return { status: 'signed-out' };
if (!backend.current.capabilities.achievements || !backend.current.binaryPath) return { status: 'unsupported' };
- const account = authState.username, binary = backend.current.binaryPath;
+ const account = authState.player ?? authState.username, binary = backend.current.binaryPath;
gameAchievements.select(account, binary);
let title:string|undefined;
try{title=target.game?await installedTitleId(target.game.path):await catalog.gameDetails(target.productId!,market).then(details=>details?.xboxTitleId);}
catch{return {status:'error'};}
if (!title) return { status: 'unavailable' };
- if (authState.running || authState.stored !== true || account !== authState.username || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
const value = await gameAchievements.get(title, refresh);
- if (authState.running || authState.stored !== true || account !== authState.username || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
+ if (authState.running || authState.stored !== true || account !== (authState.player ?? authState.username) || binary !== backend.current.binaryPath || !target.game&&market!==currentMarket()) return { status: 'error' };
return value;
});
ipcMain.handle('launch-game', (_event, id: string) => launchGame(id));
@@ -2400,7 +2462,7 @@ app.whenReady().then(async () => {
nativeSocialShutdown.push(async()=>{clearInterval(partyInvitesTimer);await voiceHost.shutdown();});
downloadCleanup = new DownloadCleanup(app.getPath('userData'));
- accountProfile = new AccountProfile(app.getPath('userData'), scheduleSnapshot, dataUrl => {
+ const normalizeAvatar = (dataUrl: string): string | undefined => {
try {
const picture = nativeImage.createFromDataURL(dataUrl);
if (picture.isEmpty()) return;
@@ -2409,7 +2471,9 @@ app.whenReady().then(async () => {
const scale = Math.min(1, 256 / Math.max(width, height));
return picture.resize({ width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)), quality: 'best' }).toDataURL();
} catch { return undefined; }
- });
+ };
+ accountProfile = new AccountProfile(app.getPath('userData'), scheduleSnapshot, normalizeAvatar);
+ licenseProfile = new AccountProfile(app.getPath('userData'), scheduleSnapshot, normalizeAvatar, undefined, true);
launcherUpdater = new LauncherUpdater(app.getVersion(), app.isPackaged ? process.env.APPIMAGE : undefined, app.getPath('userData'), scheduleSnapshot);
await launcherUpdater.initialize();
const dataHome = process.env.XDG_DATA_HOME && path.isAbsolute(process.env.XDG_DATA_HOME)
@@ -2571,6 +2635,7 @@ app.on('before-quit', (event) => {
installQueue.stop();
accountLibrary.reset();
accountProfile?.cancel();
+ licenseProfile?.cancel();
accountRefresh.invalidate();
if (shutdownStarted || (!xboxNativeSocial && nativeSocialShutdown.length===0 && !xboxSocial.busy && !walletUnlocker.busy && !backendDiagnostics?.pendingWrites && !authJob && !preparingInstall && downloadCancellations.size === 0 && installQueue.size === 0 && operations.size === 0 && serviceSessions.size === 0 && gameInviteBridges.size === 0 && !checkingGameUpdates && !launcherUpdater?.state.updating)) return;
event.preventDefault();
diff --git a/src/main/install-integration.test.ts b/src/main/install-integration.test.ts
index 6b0cb7f..7cc8a38 100644
--- a/src/main/install-integration.test.ts
+++ b/src/main/install-integration.test.ts
@@ -8,6 +8,7 @@ import { StateStore } from './store.js';
import { GameContent } from './game-content.js';
import { ContentCatalog } from './content-catalog.js';
import { DownloadCleanup } from './download-cleanup.js';
+import { accountCacheKey } from './offline-identity.js';
import { offerSteamHandoff } from './steam-launch-context.js';
// Run the real IPC/admission/download lifecycle with synthetic child processes.
@@ -43,7 +44,7 @@ const h = vi.hoisted(() => ({
launchEnvironments: [] as NodeJS.ProcessEnv[],
launchArguments: [] as string[][],
backendRefreshes: 0, runtimeRefreshes: 0,
- accountRequests: 0,
+ accountRequests: 0, accountPlayer: undefined as string | undefined,
trayCreated: vi.fn(), trayDestroyed: vi.fn(),
prefixLocales: [] as (string | undefined)[],
planOverrides: new Map<string, any>(),
@@ -119,7 +120,7 @@ vi.mock('./connectivity.js',()=>({ConnectivityMonitor:class {
vi.mock('./proton.js', () => ({ prepareProtonRunner: async () => undefined, syncPrefixUserLocale: async (_wine: string, _prefix: string, locale: string | undefined) => { h.prefixLocales.push(locale); }, syncUnrealCultureGameIni: async () => {} }));
vi.mock('./game-wrapper.js', () => ({ prepareGameWrapper: async () => { await h.wrapperGate; return { command: h.wine, cleanup: async () => {} }; } }));
vi.mock('./process.js', () => ({
- run: async (_command: string, args: string[]) => ({ code: 0, output: args[0] === 'account' ? JSON.stringify({ stored: true, username: '[email protected]' }) : '' }),
+ run: async (_command: string, args: string[]) => ({ code: 0, output: args[0] === 'account' ? JSON.stringify({ stored: true, username: '[email protected]', player: h.accountPlayer ? { username: h.accountPlayer } : null }) : '' }),
spawnTracked: (_command: string, args: string[], options: any) => {
if (args[0] === 'library') { h.libraryReads++;return {
child: { kill: vi.fn(), stderr: { on() {}, removeListener() {} } },
@@ -129,7 +130,7 @@ vi.mock('./process.js', () => ({
child: { kill: vi.fn(() => true), stdin: { end: vi.fn() } },
result: h.holdAccountReads
? new Promise<{ code: number; output: string }>(resolve => { h.accountReads.push(resolve); })
- : Promise.resolve({ code: 0, output: JSON.stringify({ stored: true, username: '[email protected]' }) }),
+ : Promise.resolve({ code: 0, output: JSON.stringify({ stored: true, username: '[email protected]', player: h.accountPlayer ? { username: h.accountPlayer } : null }) }),
}; }
let resolve!: (result: { code: number; output: string }) => void, sequence = 0;
const result = new Promise<{ code: number; output: string }>(done => { resolve = done; });
@@ -286,7 +287,7 @@ it('real account-refresh IPC shares status reads and cannot publish a late old b
h.backend = { ...backend, binaryPath: path.join(h.root, 'new-synthetic-cli') };
const current = ipc('account-refresh');
await vi.waitFor(() => expect(h.accountReads).toHaveLength(2));
- h.accountReads[1]({ code: 0, output: JSON.stringify({ stored: true, username: '[email protected]' }) });
+ h.accountReads[1]({ code: 0, output: JSON.stringify({ stored: true, username: '[email protected]', player: h.accountPlayer ? { username: h.accountPlayer } : null }) });
await current;
h.accountReads[0]({ code: 0, output: JSON.stringify({ stored: false }) });
await Promise.all([old, repeated]);
@@ -579,6 +580,23 @@ it('saves and launches locale overrides without catalog or exhaustive manifest l
}
});
+it('launches with the player identity cache while keeping Store licensing bound to the Store account', async () => {
+ const prior=h.backend.capabilities.playerAccount;h.backend.capabilities.playerAccount=true;
+ try {
+ for(const player of ['[email protected]','[email protected]']) {
+ h.accountPlayer=player;await ipc('account-refresh');
+ expect(snapshot().auth.player).toBe(player);
+ await ipc('launch-game','sample');
+ expect(h.launchEnvironments.at(-1)!.XODUS_ACCOUNT_HASH).toBe(accountCacheKey(player));
+ expect(h.launchEnvironments.at(-1)!.XODUS_ACCOUNT_HASH).not.toBe(accountCacheKey('[email protected]'));
+ expect((await fs.readFile(path.join(path.dirname(snapshot().settings.runtimeRoot),'offline-owner'),'utf8')).trim()).toBe(accountCacheKey('[email protected]'));
+ h.game!.finish(0);await vi.waitFor(()=>expect(snapshot().gameOperation.status).toBe('complete'));
+ }
+ } finally {
+ h.accountPlayer=undefined;h.backend.capabilities.playerAccount=prior;await ipc('account-refresh');
+ }
+});
+
it('launches offline only with both compatible components and discards inherited identity modes', async () => {
const keys=['XODUS_FORCE_OFFLINE','XODUS_OFFLINE_IDENTITY','XODUS_ACCOUNT_HASH'] as const;
const old=keys.map(key=>process.env[key]);
diff --git a/src/main/multi-account.test.ts b/src/main/multi-account.test.ts
new file mode 100644
index 0000000..e9afc97
--- /dev/null
+++ b/src/main/multi-account.test.ts
@@ -0,0 +1,85 @@
+import { readFileSync } from 'node:fs';
+import { runInNewContext } from 'node:vm';
+import ts from 'typescript';
+import { expect, it, vi } from 'vitest';
+import { assertActivityCompatible } from './install-queue';
+import { parseSavedAccounts, useSavedAccount, forgetSavedAccount } from './saved-accounts';
+
+const source = readFileSync(new URL('./index.ts', import.meta.url), 'utf8');
+function savedFixture() {
+ const calls: string[] = [];
+ let finish!: () => void;
+ const mutation = new Promise<void>(resolve => { finish = resolve; });
+ const context: Record<string, any> = {
+ authState: { stored: true, username: 'store-one', player: 'personal-player', running: false },
+ backend: { current: { binaryPath: '/synthetic/cli', capabilities: { savedAccounts: true } } },
+ authJob: undefined, shutdownStarted: false,
+ accountRefresh: { invalidate: () => calls.push('invalidate') },
+ accountLibrary: { reset: () => calls.push('library-reset') },
+ gameActivities: { select: vi.fn() }, gameAchievements: { select: vi.fn() },
+ xboxSocial: { close: () => calls.push('close-social') },
+ nativeSocialBeforeAuth: [async () => { calls.push('prepare-social'); }],
+ resetNativeSocial: () => calls.push('reset-social'),
+ accountProfile: { select: async () => calls.push('clear-player-profile') },
+ licenseProfile: { select: async () => calls.push('clear-license-profile') },
+ emitSnapshot: () => {},
+ useSavedAccount: vi.fn(async () => { calls.push('use'); await mutation; }),
+ forgetSavedAccount: vi.fn(async () => { calls.push('forget'); await mutation; }),
+ refreshAccount: vi.fn(async () => { calls.push('refresh'); }),
+ };
+ context.ensureIdle = () => { if (context.authJob || context.authState.running) throw Error('busy'); };
+ const start = source.indexOf('function requestSavedAccount(');
+ const code = ts.transpileModule(source.slice(start, source.indexOf('async function startInstall(', start)), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ runInNewContext(code, context);
+ return { context, calls, finish, request: (action: string) => context.requestSavedAccount(action, 'store-two') as Promise<void> };
+}
+
+it.each(['use', 'forget'])('serializes %s before its first await and reconciles identity before unlocking', async action => {
+ const f = savedFixture();
+ const job = f.request(action);
+ expect(() => f.request('use')).toThrow('busy');
+ await vi.waitFor(() => expect(f.calls).toContain(action));
+ expect(f.context.authState.running).toBe(true);
+ expect(f.context.authState.player).toBe('personal-player');
+ expect(f.calls.indexOf('prepare-social')).toBeLessThan(f.calls.indexOf(action));
+ expect(f.calls.indexOf('clear-player-profile')).toBeLessThan(f.calls.indexOf(action));
+ f.finish(); await job; await Promise.resolve();
+ expect(f.calls.at(-1)).toBe('refresh');
+ expect(f.context.authState.running).toBe(false);
+ expect(f.context.authJob).toBeUndefined();
+});
+
+it('reconciles a failed switch and releases its auth reservation', async () => {
+ const f = savedFixture();
+ f.context.useSavedAccount.mockRejectedValueOnce(Error('expired'));
+ await expect(f.request('use')).rejects.toThrow('expired');
+ expect(f.context.refreshAccount).toHaveBeenCalled();
+ expect(f.context.authState.running).toBe(false);
+ expect(f.context.authJob).toBeUndefined();
+});
+
+it('parses only bounded valid saved identities and rejects malformed envelopes', async () => {
+ expect(parseSavedAccounts('diagnostic\n' + JSON.stringify({ accounts: ['one', 'one', '', '\nunsafe', 3, 'two'], active: 'one' }))).toEqual({ accounts: ['one', 'two'], active: 'one' });
+ expect(parseSavedAccounts('{"accounts":null}')).toBeNull();
+ expect(parseSavedAccounts('null')).toBeNull();
+ expect(parseSavedAccounts('{"accounts":[],"active":"bad\\nname"}')).toEqual({ accounts: [], active: undefined });
+ await expect(useSavedAccount('/never-executed', '\ninvalid')).rejects.toThrow('Invalid account');
+ await expect(forgetSavedAccount('/never-executed', '')).rejects.toThrow('Invalid account');
+});
+
+it.each([false,true])('automatically selects the install Store account without changing player identity (download busy: %s)', async busy => {
+ const use=vi.fn(async()=>{}),authState={stored:true,username:'other-store',player:'personal-player'};
+ const context:any={game:{licenseAccount:'install-store'},authState,savedAccounts:['install-store'],
+ backend:{current:{binaryPath:'/synthetic/cli',capabilities:{savedAccounts:true}}},
+ operations:new Map(),store:{downloads:[]},gameOperation:undefined,installQueue:{size:busy?1:0},
+ assertActivityCompatible,nativeSocialBeforeAuth:[],resetNativeSocial:vi.fn(),xboxSocial:{close:vi.fn()},
+ useSavedAccount:use,accountRefresh:{invalidate:vi.fn()},
+ refreshAccount:async()=>{authState.username='install-store';}};
+ const start=source.indexOf(' if (game.licenseAccount &&',source.indexOf('async function prepareGameLaunch('));
+ const block=source.slice(start,source.indexOf(' const inspected',start));
+ const code=ts.transpileModule('async function selectInstallAccount(){'+block+'}',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+ runInNewContext(code,context);
+ if(busy){await expect(context.selectInstallAccount()).rejects.toThrow('Another Xodus operation');expect(use).not.toHaveBeenCalled();}
+ else {await context.selectInstallAccount();expect(use).toHaveBeenCalledWith('/synthetic/cli','install-store');expect(authState.username).toBe('install-store');}
+ expect(authState.player).toBe('personal-player');
+});
diff --git a/src/main/offline-actions-ipc.test.ts b/src/main/offline-actions-ipc.test.ts
index 9620fd6..0ec0fda 100644
--- a/src/main/offline-actions-ipc.test.ts
+++ b/src/main/offline-actions-ipc.test.ts
@@ -19,7 +19,7 @@ function fixture(){
const status={enabled:true,requestSuccess:true};
const read=vi.fn(async()=>status),change=vi.fn(async()=>status),settle=vi.fn(async(value:unknown)=>value),wallet=vi.fn(async()=>{});
const context:any={path,ipcMain:{handle:(name:string,fn:Function)=>handlers.set(name,fn)},authState,backend,store,
- shutdownStarted:false,keyringSupport:{busy:false},downloadCancellations:new Set(),preparingInstall:false,preparingContent:false,preparingLaunch:false,finalizingGame:false,
+ authJob:undefined,shutdownStarted:false,keyringSupport:{busy:false},downloadCancellations:new Set(),preparingInstall:false,preparingContent:false,preparingLaunch:false,finalizingGame:false,
launcherUpdater:{state:{updating:false}},checkingGameUpdates:false,gameRemovalInProgress:false,assertActivityCompatible:vi.fn(),operations:new Map(),gameOperation:undefined,installQueue:{size:0},runtime:{current:{updating:false}},
accountRefresh:{invalidate:vi.fn()},prepareSystemWallet:wallet,offlineLaunchSupported:async()=>true,offlineLicenseCache:async()=>'/fixture/cache',backendRunner:(binary:string)=>binary,readOfflinePermissions:read,changeOfflinePermissions:change,settleOfflinePermissions:settle};
runInNewContext(code,context);
diff --git a/src/main/saved-accounts.ts b/src/main/saved-accounts.ts
new file mode 100644
index 0000000..5f1ac04
--- /dev/null
+++ b/src/main/saved-accounts.ts
@@ -0,0 +1,42 @@
+import { spawnTracked } from './process.js';
+
+/** Saved Store / Game Pass accounts kept by the backend (`saved-accounts`). */
+export interface SavedAccounts { accounts: string[]; active?: string }
+
+export const validAccountName = (name: unknown): name is string =>
+ typeof name === 'string' && Boolean(name.trim()) && name.length <= 128 && !/[\x00-\x1f\x7f]/.test(name);
+
+async function run(binary: string, args: string[]): Promise<{ code: number | null; output: string }> {
+ const tracked = spawnTracked(binary, ['saved-accounts', ...args], { maxOutput: 100_000, stdoutOnly: true, outputDrainMs: 250 });
+ tracked.child.stdin.end();
+ const timer = setTimeout(() => tracked.child.kill('SIGKILL'), 15_000); timer.unref();
+ try { const result = await tracked.result; return { code: result.code, output: result.output }; }
+ finally { clearTimeout(timer); }
+}
+
+export function parseSavedAccounts(output: string): SavedAccounts | null {
+ try {
+ const line = output.split('\n').map(entry => entry.trim()).reverse().find(entry => entry.startsWith('{'));
+ const value = JSON.parse(line ?? '') as { accounts?: unknown; active?: unknown };
+ if (!Array.isArray(value.accounts)) return null;
+ return { accounts: [...new Set(value.accounts.filter(validAccountName))].slice(0, 50), active: validAccountName(value.active) ? value.active : undefined };
+ } catch { return null; }
+}
+
+export async function listSavedAccounts(binary: string): Promise<SavedAccounts | null> {
+ const result = await run(binary, ['--json']);
+ return result.code === 0 ? parseSavedAccounts(result.output) : null;
+}
+
+/** Makes a saved account the active Store account, no sign-in and no device reset. */
+export async function useSavedAccount(binary: string, name: string): Promise<void> {
+ if (!validAccountName(name)) throw new Error('Invalid account.');
+ const result = await run(binary, ['--use', name, '--json']);
+ if (result.code !== 0) throw new Error('That saved account could not be activated. Sign in to it again.');
+}
+
+export async function forgetSavedAccount(binary: string, name: string): Promise<void> {
+ if (!validAccountName(name)) throw new Error('Invalid account.');
+ const result = await run(binary, ['--forget', name, '--json']);
+ if (result.code !== 0) throw new Error('The saved account could not be forgotten.');
+}
diff --git a/src/preload/index.cts b/src/preload/index.cts
index 7934b56..8355ad4 100644
--- a/src/preload/index.cts
+++ b/src/preload/index.cts
@@ -110,8 +110,10 @@ const api: LauncherApi = {
readBackendDiagnosticLog: () => ipcRenderer.invoke('read-backend-diagnostic-log'),
createDiagnosticReport: gameId => ipcRenderer.invoke('create-diagnostic-report', gameId),
saveDiagnosticReport: content => ipcRenderer.invoke('save-diagnostic-report', content),
- login: () => ipcRenderer.invoke('login'),
- logout: () => ipcRenderer.invoke('logout'),
+ login: (player?: boolean) => ipcRenderer.invoke('login', player === true),
+ logout: (player?: boolean) => ipcRenderer.invoke('logout', player === true),
+ useAccount: (name: string) => ipcRenderer.invoke('use-account', name),
+ forgetAccount: (name: string) => ipcRenderer.invoke('forget-account', name),
offlinePermissions: () => ipcRenderer.invoke('offline-permissions'),
setOfflinePermissions: (enabled: boolean) => ipcRenderer.invoke('set-offline-permissions', enabled),
searchCatalog: (query: string, cursor?: string) => ipcRenderer.invoke('catalog-search', query, cursor),
diff --git a/src/renderer/Achievements.tsx b/src/renderer/Achievements.tsx
index c638cb5..c6c00b5 100644
--- a/src/renderer/Achievements.tsx
+++ b/src/renderer/Achievements.tsx
@@ -95,7 +95,7 @@ export function Achievements({ gameId, target=gameId, title, data }: { gameId: s
void window.launcher.getGameAchievements(target, refresh).then(value => { if (request.current === id) setValue(value); })
.catch(() => { if (request.current === id) setValue({ status: 'error' }); })
.finally(() => { if (request.current === id) setLoading(false); });
- }, [target, data.auth.username, data.auth.stored, data.auth.running, data.backend.binaryPath, data.backend.capabilities.achievements, data.settings.market]);
+ }, [target, data.auth.username, data.auth.player, data.auth.stored, data.auth.running, data.backend.binaryPath, data.backend.capabilities.achievements, data.settings.market]);
useEffect(() => { setValue(undefined); load(); return () => { request.current++; }; }, [load]);
return <AchievementsContent title={title} value={value} loading={loading} refresh={() => load(true)} />;
}
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 4352d6b..de6f039 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -102,7 +102,7 @@ function NavItem({ active, icon, label, badge, onClick, autoSelect = false }: {
}
export function Sidebar({ data, page, go, openGame, openProfile, notifications, inert = false }: { data: AppSnapshot; page: Page; go: (page: Page) => void; openGame?: (id: string) => void; openProfile?: () => void; notifications?: React.ReactNode; inert?: boolean }) {
- const account = data.auth.gamertag ?? data.auth.username ?? (data.auth.stored === true ? ui("ui.microsoft_account_6c2b1f2") : ui("ui.sign_in_bfd402b"));
+ const account = data.auth.gamertag ?? data.auth.player ?? data.auth.username ?? (data.auth.stored === true ? ui("ui.microsoft_account_6c2b1f2") : ui("ui.sign_in_bfd402b"));
return <aside className="sidebar" ref={inertRef(inert)}>
<div className="account-header" data-gamepad-action-row><button className="account-summary" onClick={() => openProfile ? openProfile() : go('settings')}><AccountAvatar auth={data.auth} /><span><strong>{account}</strong><AccountMembership auth={data.auth} /></span></button>{notifications}</div>
<nav><NavItem autoSelect active={page === 'home'} icon={<Home />} label={ui("ui.home_3a78695")} onClick={() => go('home')} /><NavItem autoSelect active={page === 'library'} icon={<Library />} label={ui("ui.my_library_d931dba")} onClick={() => go('library')} /><NavItem autoSelect active={page === 'store'} icon={<Store />} label={ui("ui.store_ee7da93")} onClick={() => go('store')} /></nav>
@@ -117,11 +117,12 @@ function AccountMembership({ auth }: { auth: AppSnapshot['auth'] }) {
return auth.stored === true ? null : <small>{auth.stored === false ? ui("ui.not_signed_in_491fc91") : ui("ui.status_unavailable_7eb5af9")}</small>;
}
-function AccountAvatar({ auth, large = false }: { auth: AppSnapshot['auth']; large?: boolean }) {
+function AccountAvatar({ auth, large = false, license = false }: { auth: AppSnapshot['auth']; large?: boolean; license?: boolean }) {
+ const picture = license ? auth.licenseAvatarDataUrl : auth.avatarDataUrl;
const [failed, setFailed] = useState(false);
- useEffect(() => setFailed(false), [auth.avatarDataUrl]);
+ useEffect(() => setFailed(false), [picture]);
return <div className={`account-avatar${large ? ' large' : ''}`}>
- {auth.avatarDataUrl && !failed ? <img src={auth.avatarDataUrl} alt={ui("ui.xbox_profile_picture_f6ca315")} onError={() => setFailed(true)} /> : <CircleUserRound />}
+ {picture && !failed ? <img src={picture} alt={ui("ui.xbox_profile_picture_f6ca315")} onError={() => setFailed(true)} /> : <CircleUserRound />}
</div>;
}
@@ -380,7 +381,7 @@ function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshot; toast
label={installed ? ui("ui.installed_f8b32f4") : isQueued(product) ? ui("ui.in_install_queue_7c818f2") : busy === product.productId ? ui("ui.preparing_5d1fa38") : ui("ui.install_569ca49")}
select={selectProduct} install={install} />;
})}</div>;
- if(detailOpen&&selected)return <main ref={pageRef} className="page store-page library-detail-open"><CatalogGameDetails key={`${selected.productId}:${data.auth.username}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} product={selected} data={data} back={()=>setDetailOpen(false)} backLabel={ui('game.back_to_store')} toast={toast}/></main>;
+ if(detailOpen&&selected)return <main ref={pageRef} className="page store-page library-detail-open"><CatalogGameDetails key={`${selected.productId}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} product={selected} data={data} back={()=>setDetailOpen(false)} backLabel={ui('game.back_to_store')} toast={toast}/></main>;
return <main ref={pageRef} className="page store-page">
<header className="page-header"><div><h1>{ui("ui.store_ee7da93")}</h1></div><span className="catalog-source"><StatusDot />Microsoft Store</span></header>
{!catalog ? <section className="featured-catalog"><SectionTitle title={ui("ui.featured_c533caf")} />{featuredLoading ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : featured?.products.length ? <><div className="featured-rail">{featured.products.slice(0, 3).map((product) => <button className="featured-tile" key={product.productId} data-gamepad-detail-target={product.productId} onClick={() => selectProduct(product)}>{product.heroUrl || product.posterUrl ? <img src={product.heroUrl ?? product.posterUrl} alt="" /> : <div className="featured-tile-placeholder"><Gamepad2 /></div>}<span className="featured-tile-copy"><GameTitle title={product.title} /><small>{product.publisher ?? 'Microsoft Store'} · {product.installability === 'supported' ? ui('store.verified_pc') : ui("ui.check_package_support_79592da")}</small></span></button>)}</div><SectionTitle title={ui("ui.trending_pc_games_2025848")} />{productGrid(featured.products.slice(3))}</> : <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{featuredError ?? ui("ui.search_still_works_with_live_microsoft_store_dat_b3eeb72")}</p></div>}</section> : null}
@@ -675,7 +676,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,
const [diagnosticLog, setDiagnosticLog] = useState<{ log: DiagnosticLog; operationId: string }>();
const [contentGameId, setContentGameId] = useState<string>();
const [detailOpen, setDetailOpen] = useState(Boolean(selection));
- const catalogScope=JSON.stringify([data.auth.username,data.auth.stored,data.auth.running,data.backend.binaryPath,data.settings.market]);
+ const catalogScope=JSON.stringify([data.auth.username,data.auth.player,data.auth.stored,data.auth.running,data.backend.binaryPath,data.settings.market]);
const [catalogSelection,setCatalogSelection]=useState<{product:CatalogProduct;scope:string}>();
const catalogProduct=catalogSelection?.scope===catalogScope?catalogSelection.product:undefined;
const previousCatalogScope=useRef(catalogScope);
@@ -850,7 +851,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,
onContent: () => { setMenu(undefined); setContentGameId(game.id); },
contentDisabled: !game.storeId || data.auth.stored !== true || !data.backend.capabilities.library,
});
- const selectedPanel = catalogProduct&&detailVisible?<CatalogGameDetails key={catalogProduct.productId+catalogScope} product={catalogProduct} data={data} back={closeDetails} toast={toast}/>:!catalogSelection&&selected&&detailVisible ? <GameDetails key={`${selected.id}:${data.auth.username}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} game={selected} data={data} back={closeDetails} backLabel={returnHomeKey.current ? ui('game.back_to_home') : undefined} play={<>
+ const selectedPanel = catalogProduct&&detailVisible?<CatalogGameDetails key={catalogProduct.productId+catalogScope} product={catalogProduct} data={data} back={closeDetails} toast={toast}/>:!catalogSelection&&selected&&detailVisible ? <GameDetails key={`${selected.id}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} game={selected} data={data} back={closeDetails} backLabel={returnHomeKey.current ? ui('game.back_to_home') : undefined} play={<>
<button className="primary" data-gamepad-play disabled={gameBusy || selected.installState !== 'ready' || !data.backend.capabilities.run || !gameRuntimeAvailable(selected.runtime,selected.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[])} onClick={() => play()}>{gameBusy ? <LoaderCircle className="spin" /> : <Play fill="currentColor" />}{gameBusy ? ui("ui.working_5474eef") : ui("ui.play_436e610")}</button>
{gameBusy && !(selectedOperation?.kind === 'prerequisite' && selectedOperation.status === 'running') ? <button className="secondary danger" onClick={stopGame}><X />{ui("ui.stop_cae7d57")}</button> : null}
</>} manage={<GameMenuActions {...managementProps(selected)} />} technical={<dl><div><dt>{ui("ui.store_id_4a3eac6")}</dt><dd>{selected.storeId ?? ui("ui.not_found_e3ebaa1")}</dd></div><div><dt>{ui("ui.executable_72cd8a6")}</dt><dd>{selected.executable ?? ui("ui.not_found_e3ebaa1")}</dd></div><div><dt>{ui("ui.location_15b6197")}</dt><dd>{selected.path}</dd></div></dl>} notices={<>
@@ -1029,13 +1030,31 @@ export function SettingsPage({ data, toast }: { data: AppSnapshot; toast: (value
</section>
<section className="settings-card account-card">
- <div className="settings-heading"><AccountAvatar auth={data.auth} large /><div><span className="overline">{ui("ui.microsoft_account_90f90f6")}</span><h2>{data.auth.gamertag ?? data.auth.username ?? (data.auth.stored === false ? ui("ui.not_signed_in_491fc91") : ui("ui.account_status_unavailable_3b97a47"))}</h2><p>{data.auth.stored === true ? ui("ui.credentials_stored_by_xodus_bca3867") : ui("ui.authentication_uses_the_original_xodus_webview_cf2dcb9")}</p></div><span className={`status-label ${data.auth.stored === true ? 'ready' : data.auth.stored === false ? 'off' : 'unknown'}`}><StatusDot tone={data.auth.stored === true ? 'green' : data.auth.stored === false ? 'red' : 'amber'} />{data.auth.stored === true ? ui("ui.stored_1afc73e") : data.auth.stored === false ? ui("ui.signed_out_db8436b") : ui("ui.unknown_2375999")}</span></div>
+ <div className="settings-heading"><AccountAvatar auth={data.auth} large license={Boolean(data.auth.player)} /><div><span className="overline">{ui("ui.microsoft_account_90f90f6")}</span><h2>{(data.auth.player ? data.auth.username : data.auth.gamertag ?? data.auth.username) ?? (data.auth.stored === false ? ui("ui.not_signed_in_491fc91") : ui("ui.account_status_unavailable_3b97a47"))}</h2><p>{data.auth.stored === true ? ui("ui.credentials_stored_by_xodus_bca3867") : ui("ui.authentication_uses_the_original_xodus_webview_cf2dcb9")}</p></div><span className={`status-label ${data.auth.stored === true ? 'ready' : data.auth.stored === false ? 'off' : 'unknown'}`}><StatusDot tone={data.auth.stored === true ? 'green' : data.auth.stored === false ? 'red' : 'amber'} />{data.auth.stored === true ? ui("ui.stored_1afc73e") : data.auth.stored === false ? ui("ui.signed_out_db8436b") : ui("ui.unknown_2375999")}</span></div>
<div className="account-note"><CircleAlert /><span>{uiText(data.auth.note)}</span></div>
<KeyringSetup compact disabled={data.auth.running} />
- <div className="button-row"><button className="primary" disabled={!caps.login || data.auth.running} onClick={() => invoke('login', () => window.launcher.login(), ui("ui.xodus_sign_in_completed_8240737"))}>{data.auth.running ? <LoaderCircle className="spin" /> : <LogIn />}{data.auth.stored ? ui("ui.sign_in_again_51fbe1d") : ui("ui.sign_in_with_xodus_252572f")}</button><button className="secondary" disabled={!caps.logout || data.auth.running || data.auth.stored === false} title={ui("ui.remove_saved_sign_in_credentials_and_local_devic_6485324")} onClick={() => invoke('logout', () => window.launcher.logout(), ui("ui.saved_sign_in_credentials_and_local_device_regis_c9738bd"))}>{ui("ui.sign_out_48f0d3d")}</button><button className="secondary" disabled={!caps.account || data.auth.running} onClick={() => invoke('account', () => window.launcher.refreshAccount())}><RefreshCw />{ui("ui.refresh_status_442c4b8")}</button></div>
+ <div className="button-row"><button className="primary" disabled={!caps.login || data.auth.running} onClick={() => invoke('login', () => window.launcher.login(), ui("ui.xodus_sign_in_completed_8240737"))}>{data.auth.running ? <LoaderCircle className="spin" /> : <LogIn />}{data.auth.stored ? ui("ui.sign_in_again_51fbe1d") : ui("ui.sign_in_with_xodus_252572f")}</button><button className="secondary" disabled={!caps.logout || data.auth.running || (data.auth.stored === false && !data.auth.player)} title={caps.savedAccounts ? ui("auth.sign_out_active_help") : ui("ui.remove_saved_sign_in_credentials_and_local_devic_6485324")} onClick={() => invoke('logout', () => window.launcher.logout(), caps.savedAccounts ? ui("auth.active_signed_out") : ui("ui.saved_sign_in_credentials_and_local_device_regis_c9738bd"))}>{data.auth.player ? ui("auth.sign_out_all") : ui("ui.sign_out_48f0d3d")}</button><button className="secondary" disabled={!caps.account || data.auth.running} onClick={() => invoke('account', () => window.launcher.refreshAccount())}><RefreshCw />{ui("ui.refresh_status_442c4b8")}</button></div>
+ {(data.auth.saved?.length ?? 0) > 0 && caps.savedAccounts ? <div className="saved-accounts" role="list" aria-label={ui("ui.saved_store_accounts_a1c4e72")}>
+ <span className="overline">{ui("ui.saved_store_accounts_a1c4e72")}</span>
+ {data.auth.saved!.map(name => <div key={name} className="button-row" role="listitem">
+ <strong>{name}</strong>
+ {name === data.auth.username ? <span className="status-label ready">{ui("ui.account_in_use_5b09d3f")}</span>
+ : <button className="secondary" disabled={data.auth.running} onClick={() => invoke('use-account', () => window.launcher.useAccount(name), ui("ui.account_switched_6a2e91c"))}>{ui("ui.use_this_account_e71c0a8")}</button>}
+ <button className="secondary" disabled={data.auth.running} onClick={() => invoke('forget-account', () => window.launcher.forgetAccount(name), ui("ui.account_forgotten_c05d7e3"))}>{ui("ui.forget_account_3d8f6b1")}</button>
+ </div>)}
+ <small>{ui("ui.saved_store_accounts_help_94be2d0")}</small>
+ </div> : null}
<PasskeySignInNotice />
</section>
+ {caps.playerAccount && (data.auth.stored === true || data.auth.player) ? <section className="settings-card account-card">
+ <div className="settings-heading">{data.auth.player ? <AccountAvatar auth={data.auth} large /> : null}<div><span className="overline">{ui("ui.xbox_player_account_021c236")}</span><h2>{data.auth.player ? (data.auth.gamertag ? `${data.auth.gamertag} · ${data.auth.player}` : data.auth.player) : ui("ui.no_separate_player_account_44980b5")}</h2><p>{ui("ui.player_account_help_1d6f365")}</p></div></div>
+ <div className="button-row">
+ <button className="primary" disabled={data.auth.running} onClick={() => invoke('login-player', () => window.launcher.login(true), ui("ui.player_account_signed_in_ac36aa2"))}>{ui("ui.sign_in_player_account_c15aa58")}</button>
+ {data.auth.player ? <button className="secondary" disabled={data.auth.running} onClick={() => invoke('logout-player', () => window.launcher.logout(true), ui("ui.player_account_signed_out_6752e8f"))}>{ui("ui.sign_out_player_account_013bd34")}</button> : null}
+ </div>
+ </section> : null}
+
{caps.offlinePc && !data.auth.running ? <OfflinePermissionsCard key={`${data.auth.username}:${data.auth.stored}:${data.backend.binaryPath}:${data.settings.runtimeRoot}`} toast={toast} signedIn={data.auth.stored === true} /> : null}
<section className="settings-card">
@@ -1275,20 +1294,20 @@ export default function App() {
if (loading) return <div className="boot"><div className="brand-mark">X</div><LoaderCircle className="spin" /><span>{ui("ui.loading_xodus_nexus_2e92cfd")}</span></div>;
return <ConfirmationProvider><PackageInstallProvider><div className="app-shell">
{!data.settings.firstRunCompleted ? <FirstRunWizard data={data} toast={(value) => setToast(value)} /> : null}
- <Sidebar data={data} page={page} go={go} openGame={openLibraryGame} openProfile={() => data.auth.stored === true && data.backend.capabilities.nativeSocial ? action(() => window.launcher.nativeSocial.openXboxPlayerProfile('me')) : go('settings')} inert={socialOpen} notifications={<NotificationBell key={JSON.stringify([data.auth.username,data.backend.binaryPath])} notices={notifications.notices} failed={notifications.failed} unsupported={notifications.unsupported} onSelect={notice=>{
+ <Sidebar data={data} page={page} go={go} openGame={openLibraryGame} openProfile={() => data.auth.stored === true && data.backend.capabilities.nativeSocial ? action(() => window.launcher.nativeSocial.openXboxPlayerProfile('me')) : go('settings')} inert={socialOpen} notifications={<NotificationBell key={JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])} notices={notifications.notices} failed={notifications.failed} unsupported={notifications.unsupported} onSelect={notice=>{
notifications.acknowledge(notice);
if(notice.kind==='update')openLibraryGame(notice.target);
- else{setSocialChat(previous=>({id:(previous?.id??0)+1,xuid:notice.target,identity:JSON.stringify([data.auth.username,data.backend.binaryPath])}));setSocialMounted(true);setSocialOpen(true);}
+ else{setSocialChat(previous=>({id:(previous?.id??0)+1,xuid:notice.target,identity:JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])}));setSocialMounted(true);setSocialOpen(true);}
}}/>}/>
<section className="content-shell">
<header className="topbar" ref={inertRef(socialOpen)}><GlobalSearch games={data.games} page={page} query={search} change={setSearch} submit={value => { setSubmittedSearch(value); go('store'); }} select={openLibraryGame} /><TopStatus data={data} go={go} /></header>
<CloudSaveWarning operation={data.gameOperation} openGame={openLibraryGame} disabled={socialOpen} />
- <div data-gamepad-page={page} ref={inertRef(socialOpen)} className={'page-scroll'+(page==='social'?' social-full-page':'')}>{page === 'home' ? <HomePage data={data} go={go} action={action} openGame={openLibraryGame} returnFocusKey={homeReturnKey} /> : null}{page === 'store' ? <StorePage data={data} toast={setToast} go={go} initialQuery={submittedSearch} /> : null}{page === 'library' ? <LibraryPage data={data} toast={setToast} filters={libraryFilters} onFiltersChange={changeLibraryFilters} selection={librarySelection} onSelectionHandled={request => setLibrarySelection(current => current === request ? undefined : current)} returnHome={key => { setHomeReturnKey(key); go('home'); }} /> : null}{page === 'downloads' ? <DownloadsPage data={data} toast={setToast} /> : null}{page === 'settings' ? <SettingsPage data={data} toast={setToast} /> : null}{page === 'social' ? <div className="nexus-social-page"><Suspense fallback={<SocialLoading/>}><XboxSocial key={JSON.stringify([data.auth.username,data.backend.binaryPath])} auth={data.auth} api={window.launcher.nativeSocial} voice={data.backend.available&&data.backend.capabilities.nativeSocial?window.launcher:undefined} runtimeInvites={data.social} runtimeApi={window.launcher} expanded active={!socialOpen} readKeys={notifications.readKeys} onViewed={notifications.viewed} showProfile={desktopProfile}/></Suspense></div> : null}</div>
+ <div data-gamepad-page={page} ref={inertRef(socialOpen)} className={'page-scroll'+(page==='social'?' social-full-page':'')}>{page === 'home' ? <HomePage data={data} go={go} action={action} openGame={openLibraryGame} returnFocusKey={homeReturnKey} /> : null}{page === 'store' ? <StorePage data={data} toast={setToast} go={go} initialQuery={submittedSearch} /> : null}{page === 'library' ? <LibraryPage data={data} toast={setToast} filters={libraryFilters} onFiltersChange={changeLibraryFilters} selection={librarySelection} onSelectionHandled={request => setLibrarySelection(current => current === request ? undefined : current)} returnHome={key => { setHomeReturnKey(key); go('home'); }} /> : null}{page === 'downloads' ? <DownloadsPage data={data} toast={setToast} /> : null}{page === 'settings' ? <SettingsPage data={data} toast={setToast} /> : null}{page === 'social' ? <div className="nexus-social-page"><Suspense fallback={<SocialLoading/>}><XboxSocial key={JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])} auth={data.auth} api={window.launcher.nativeSocial} voice={data.backend.available&&data.backend.capabilities.nativeSocial?window.launcher:undefined} runtimeInvites={data.social} runtimeApi={window.launcher} expanded active={!socialOpen} readKeys={notifications.readKeys} onViewed={notifications.viewed} showProfile={desktopProfile}/></Suspense></div> : null}</div>
{socialOpen?<button className="nexus-social-scrim" aria-label={ui("social.close_social_shelf_09c6eb")} onClick={()=>setSocialOpen(false)}/>:null}
<aside id="nexus-social-shelf" role="dialog" aria-modal={socialOpen || undefined} data-gamepad-layer data-gamepad-social-shelf className={'nexus-social-shelf'+(socialOpen?' is-open':'')} aria-label={ui("social.xbox_social_shelf_bb6aaf")} aria-hidden={!socialOpen}
ref={inertRef(!socialOpen)}>
- {socialMounted?<Suspense fallback={<SocialLoading close={()=>setSocialOpen(false)}/>}><XboxSocial key={JSON.stringify([data.auth.username,data.backend.binaryPath])} auth={data.auth} api={window.launcher.nativeSocial} voice={data.backend.available&&data.backend.capabilities.nativeSocial?window.launcher:undefined} runtimeInvites={data.social} runtimeApi={window.launcher} shelf active={socialOpen} openChat={socialChat?.identity===JSON.stringify([data.auth.username,data.backend.binaryPath])?socialChat:undefined} readKeys={notifications.readKeys} onViewed={notifications.viewed} close={()=>setSocialOpen(false)}/></Suspense>:null}
+ {socialMounted?<Suspense fallback={<SocialLoading close={()=>setSocialOpen(false)}/>}><XboxSocial key={JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])} auth={data.auth} api={window.launcher.nativeSocial} voice={data.backend.available&&data.backend.capabilities.nativeSocial?window.launcher:undefined} runtimeInvites={data.social} runtimeApi={window.launcher} shelf active={socialOpen} openChat={socialChat?.identity===JSON.stringify([data.auth.player??data.auth.username,data.backend.binaryPath])?socialChat:undefined} readKeys={notifications.readKeys} onViewed={notifications.viewed} close={()=>setSocialOpen(false)}/></Suspense>:null}
</aside>
</section>
<button data-gamepad-social-toggle data-gamepad-key="social-toggle" className={'nexus-social-toggle'+(socialOpen?' is-open':'')} aria-label={ui("social.xbox_social_9dd063")} aria-expanded={socialOpen} aria-controls="nexus-social-shelf" onClick={()=>go('social')}><Copy aria-hidden="true"/><span>{ui("social.social_f1b750")}</span><ChevronRight/></button>
diff --git a/src/renderer/CatalogGameDetails.tsx b/src/renderer/CatalogGameDetails.tsx
index 8df8e66..d499cb1 100644
--- a/src/renderer/CatalogGameDetails.tsx
+++ b/src/renderer/CatalogGameDetails.tsx
@@ -21,7 +21,7 @@ export function CatalogGameDetails({product,data,back,backLabel,toast}:{product:
const [busy,setBusy]=useState(false),pending=useRef(false);
const installed=catalogGameInstalled(product,data),queued=catalogGameQueued(product,data);
const disabled=Boolean(installed)||queued||busy||product.installability!=='supported'||!data.backend.capabilities.streaming;
- const scope=JSON.stringify([data.auth.username,data.auth.stored,data.auth.running,data.backend.binaryPath,data.settings.market]);
+ const scope=JSON.stringify([data.auth.username, data.auth.player,data.auth.stored,data.auth.running,data.backend.binaryPath,data.settings.market]);
const identity=useRef(scope);identity.current=scope;
useEffect(()=>{identity.current=scope;return()=>{identity.current='';};},[scope]);
async function install(){
diff --git a/src/renderer/Friends.tsx b/src/renderer/Friends.tsx
index bb0d834..cf693fe 100644
--- a/src/renderer/Friends.tsx
+++ b/src/renderer/Friends.tsx
@@ -59,7 +59,7 @@ export function Friends({ data, close, docked=false }: { data: AppSnapshot; clos
.finally(()=>{if(generation.current===active){setBusy(false);pending.current=false;}});
}
return ()=>{generation.current++;void window.launcher.closeXboxSocial().catch(()=>{});};
- },[available,data.auth.username]);
+ },[available,data.auth.username,data.auth.player]);
function applyConversation(value:XboxConversation){
setConversation(value);
@@ -101,7 +101,7 @@ export function Friends({ data, close, docked=false }: { data: AppSnapshot; clos
const visible=()=>{if(document.visibilityState==='visible')polling.wake();};
document.addEventListener('visibilitychange',visible);
return()=>{polling.stop();document.removeEventListener('visibilitychange',visible);};
- },[available,data.auth.username]);
+ },[available,data.auth.username,data.auth.player]);
function choose(friend:XboxFriend){
if(pending.current)return;
setSelected(friend);currentFriend.current=friend;select.current=friend.xuid;setConversation(undefined);setDraft('');setUncertain(false);setAccepted(false);submission.current=undefined;void refresh(friend);
diff --git a/src/renderer/GameDetails.tsx b/src/renderer/GameDetails.tsx
index 3a12895..4710bb6 100644
--- a/src/renderer/GameDetails.tsx
+++ b/src/renderer/GameDetails.tsx
@@ -168,7 +168,7 @@ export function GameDetails(props: PageProps & { data: AppSnapshot }) {
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); });
- }, [target, data.auth.username, data.auth.stored, data.auth.running, data.backend.binaryPath, data.backend.capabilities.gameActivity, data.settings.market]);
+ }, [target, data.auth.username, data.auth.player, data.auth.stored, data.auth.running, data.backend.binaryPath, data.backend.capabilities.gameActivity, data.settings.market]);
const finishedSession = data.gameOperation?.gameId === game.id && data.gameOperation.kind !== 'prerequisite' ? data.gameOperation.finishedAt : undefined;
useEffect(() => { setActivity(undefined); loadActivity(Boolean(finishedSession)); return () => { request.current++; }; }, [loadActivity, finishedSession]);
return <GameDetailsContent {...props} details={details} activity={activity} metadataLoading={metadataLoading} metadataError={metadataError} activityLoading={activityLoading} refresh={() => loadActivity(true)} achievements={<Achievements gameId={game.id} target={target} title={game.title} data={data} />} />;
diff --git a/src/renderer/Notifications.tsx b/src/renderer/Notifications.tsx
index 16b83c9..5417272 100644
--- a/src/renderer/Notifications.tsx
+++ b/src/renderer/Notifications.tsx
@@ -7,8 +7,9 @@ import { ui } from './i18n';
import './notifications.css';
export function useNotifications(data:AppSnapshot) {
- const identity=JSON.stringify([data.auth.stored===true?data.auth.username:null,data.backend.binaryPath]);
- const storageKey=data.auth.stored===true&&data.auth.username?'nexus.notifications.v1.'+encodeURIComponent(data.auth.username):undefined;
+ const account=data.auth.player??data.auth.username;
+ const identity=JSON.stringify([data.auth.stored===true?account:null,data.backend.binaryPath]);
+ const storageKey=data.auth.stored===true&&account?'nexus.notifications.v1.'+encodeURIComponent(account):undefined;
const [reads,setReads]=useState<{identity:string;keys:string[]}>({identity:'',keys:[]});
const [inbox,setInbox]=useState<{identity:string;value:XboxConversation[]}>();
const [names,setNames]=useState<{identity:string;value:Map<string,string>}>();
@@ -36,7 +37,7 @@ export function useNotifications(data:AppSnapshot) {
if(!supported)return;
let active=true;
const receive=(state:Awaited<ReturnType<typeof window.launcher.getXboxChatReads>>)=>{
- if(active&&currentIdentity.current===identity&&state&&state.account===data.auth.username&&state.binary===data.backend.binaryPath)
+ if(active&&currentIdentity.current===identity&&state&&state.account===account&&state.binary===data.backend.binaryPath)
remember(parseNotificationReads(JSON.stringify(state.keys)));
};
const unsubscribe=window.launcher.onXboxChatReads(receive);
@@ -87,8 +88,8 @@ export function useNotifications(data:AppSnapshot) {
viewed:(peer:string,ids:string[])=>{
const keys=ids.map(id=>messageNoticeKey(peer,id));
lastViewed.current={identity,keys};remember(keys);
- if(supported&&data.auth.username&&data.backend.binaryPath)
- void window.launcher.viewedXboxChat(data.auth.username,data.backend.binaryPath,peer,ids).catch(()=>{/* Local read state is still retained. */});
+ if(supported&&account&&data.backend.binaryPath)
+ void window.launcher.viewedXboxChat(account,data.backend.binaryPath,peer,ids).catch(()=>{/* Local read state is still retained. */});
}};
}
diff --git a/src/renderer/XboxChatDesktop.tsx b/src/renderer/XboxChatDesktop.tsx
index 6803946..e3f292f 100644
--- a/src/renderer/XboxChatDesktop.tsx
+++ b/src/renderer/XboxChatDesktop.tsx
@@ -15,7 +15,7 @@ export function XboxChatDesktop({xuid}:{xuid:string}){
return()=>document.removeEventListener('visibilitychange',visible);
},[]);
const auth=snapshot?.auth;
- const account=auth?.stored===true&&!auth.running?auth.username:undefined;
+ const account=auth?.stored===true&&!auth.running?(auth.player??auth.username):undefined;
const binary=snapshot?.backend.binaryPath;
const supported=Boolean(snapshot?.backend.available&&snapshot.backend.capabilities.nativeSocial&&binary);
const problems={account:ui('social.desktop_account_failed'),close:ui('social.desktop_close_failed'),profile:ui('social.desktop_profile_failed')};
diff --git a/src/renderer/XboxSocial.tsx b/src/renderer/XboxSocial.tsx
index 9c244e5..f20a6ec 100644
--- a/src/renderer/XboxSocial.tsx
+++ b/src/renderer/XboxSocial.tsx
@@ -28,7 +28,7 @@ export function XboxSocial({auth,api,voice,overlay=false,shelf=false,close,openO
const [profiles,setProfiles]=useState<Record<string,XboxPlayerProfile>>({});
const [partyRecipient,setPartyRecipient]=useState<{xuid:string;gamertag:string}>();
const generation=useRef(0);
- const identity=auth.stored===true&&!auth.running?auth.username:undefined;
+ const identity=auth.stored===true&&!auth.running?(auth.player??auth.username):undefined;
const selectedPerson=friends.find(person=>person.xuid===selected);
const selectedConversation=inbox.find(row=>row.participants.includes(selected??''));
const selectedName=selectedPerson?.gamertag??selectedConversation?.gamertag??'Xbox player';
diff --git a/src/renderer/guide-main.tsx b/src/renderer/guide-main.tsx
index 660f294..63bae86 100644
--- a/src/renderer/guide-main.tsx
+++ b/src/renderer/guide-main.tsx
@@ -40,12 +40,12 @@ function XboxGameGuide(){
const languages=onGuideEvent('language',value=>setLanguage(typeof value==='string'?value:undefined));
return()=>{unsubscribe();profiles();preferences();invitations();visibility();languages();disconnect();};
},[]);
- useEffect(()=>{setChats([]);chatIds.current=[];setProfile(undefined);setExpanded(false);},[auth.username]);
- const account=auth.stored===true&&!auth.running?auth.username:undefined;
+ useEffect(()=>{setChats([]);chatIds.current=[];setProfile(undefined);setExpanded(false);},[auth.username,auth.player]);
+ const account=auth.stored===true&&!auth.running?(auth.player??auth.username):undefined;
return <main className={'game-guide-shell'+(overlay.overlaySide==='right'?' is-right':'')} aria-label={ui("social.in_game_xbox_guide_b68219")}>
<div className={'game-guide-panel'+(expanded?' is-expanded':'')}>
{expanded?<div className="game-guide-full-toolbar"><button onClick={()=>setExpanded(false)}>{overlay.overlaySide==='right'?<PanelRightClose/>:<PanelLeftClose/>}{ui("social.return_to_shelf_4df4fc")}</button><span>{ui("social.xbox_social_9dd063")}</span></div>:null}
- <XboxSocial key={auth.username} auth={auth} api={api} voice={guidePartyApi} active={active} runtimeInvites={runtimeInvites} runtimeApi={runtimeApi} overlay expanded={expanded} showProfile={profile} close={close}/>
+ <XboxSocial key={auth.player??auth.username} auth={auth} api={api} voice={guidePartyApi} active={active} runtimeInvites={runtimeInvites} runtimeApi={runtimeApi} overlay expanded={expanded} showProfile={profile} close={close}/>
{problem?<p className="game-guide-error" role="alert">{uiText(problem)}</p>:null}
<footer><span>{ui("social.xbox_guide_31c52d")}</span><span>{overlay.overlayShortcut} {ui("social._esc_back_to_game_a58ed5")}</span></footer>
</div><button className="game-guide-dismiss" aria-label={ui("social.return_to_game_1d6ce9")} onClick={close}/>
diff --git a/src/renderer/multi-account.test.tsx b/src/renderer/multi-account.test.tsx
new file mode 100644
index 0000000..acd0959
--- /dev/null
+++ b/src/renderer/multi-account.test.tsx
@@ -0,0 +1,50 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, it, vi } from 'vitest';
+import { SettingsPage } from './App';
+import { useNotifications } from './Notifications';
+import { demoSnapshot } from '../shared/demo-data';
+import { messageNoticeKey } from './notification-state';
+
+it('shows player credentials independently after Store sign-out and explains full sign-out retention', () => {
+ const data = demoSnapshot();
+ Object.assign(data.backend.capabilities, { playerAccount: true, savedAccounts: true });
+ data.auth = { ...data.auth, stored: false, username: undefined, player: '[email protected]', gamertag: 'PersonalPlayer', saved: ['[email protected]'] };
+ const html = renderToStaticMarkup(<SettingsPage data={data} toast={() => {}} />);
+ expect(html).toContain('PersonalPlayer · [email protected]');
+ expect(html).toContain('Sign out player account');
+ expect(html).toContain('Sign out all accounts');
+ expect(html).toContain('Saved Store accounts remain available until forgotten.');
+ expect(html).toContain('[email protected]');
+});
+
+it('keeps notification reads and broker acknowledgements scoped to the effective Xbox player', async () => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ const data = demoSnapshot();
+ data.auth = { ...data.auth, stored: true, username: 'shared-store', player: 'player-one' };
+ data.backend.capabilities.nativeSocial = true;
+ data.backend.binaryPath = '/synthetic/cli';
+ window.launcher = { getXboxChatReads: vi.fn(async () => undefined), onXboxChatReads: () => () => {}, viewedXboxChat: vi.fn(async () => {}) } as unknown as Window['launcher'];
+ localStorage.clear();
+ const key = messageNoticeKey('42', 'one');
+ localStorage.setItem('nexus.notifications.v1.player-one', JSON.stringify([key]));
+ let notices!: ReturnType<typeof useNotifications>;
+ function Fixture() { notices = useNotifications(data); return null; }
+ const element = document.createElement('div'); document.body.append(element);
+ const root = createRoot(element);
+ try {
+ await act(async () => root.render(<Fixture />));
+ expect(notices.readKeys).toEqual([key]);
+ await act(async () => notices.viewed('42', ['two']));
+ expect(window.launcher.viewedXboxChat).toHaveBeenLastCalledWith('player-one', '/synthetic/cli', '42', ['two']);
+ data.auth = { ...data.auth, player: 'player-two' };
+ await act(async () => root.render(<Fixture />));
+ expect(notices.readKeys).toEqual([]);
+ await act(async () => notices.viewed('43', ['three']));
+ expect(window.launcher.viewedXboxChat).toHaveBeenLastCalledWith('player-two', '/synthetic/cli', '43', ['three']);
+ expect(localStorage.getItem('nexus.notifications.v1.shared-store')).toBeNull();
+ expect(localStorage.getItem('nexus.notifications.v1.player-one')).not.toContain('three');
+ } finally { await act(async () => root.unmount()); element.remove(); localStorage.clear(); vi.unstubAllGlobals(); }
+});
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 0aa3b5a..30298e3 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -23,6 +23,10 @@ export interface BackendCapabilities {
offlinePc?: boolean;
/** `run --offline`: skip Microsoft entirely and launch on the stored offline license. */
offlineLaunch?: boolean;
+ /** `login --player` / `logout --player`: a second, separate Xbox player account. */
+ playerAccount?: boolean;
+ licenseProfile?: boolean;
+ savedAccounts?: boolean;
streamingControls?: boolean;
streamingBandwidthLimit?: boolean;
streamingUpdateRecovery?: boolean;
@@ -36,8 +40,12 @@ export interface AuthStatus {
running: boolean;
stored: boolean | null;
username?: string;
+ /** Separate Xbox player account, when the backend stores one next to the license account. */
+ player?: string;
gamertag?: string;
avatarDataUrl?: string;
+ licenseAvatarDataUrl?: string;
+ saved?: string[];
subscription?: GamePassSubscription;
lastResult?: 'success' | 'failed';
lastAction?: 'login' | 'logout';
@@ -114,6 +122,7 @@ export interface Game {
publisher?: string;
installedVersion?: string;
packageName?: string;
+ licenseAccount?: string; // Store account the game was installed with.
executable?: string;
winePath?: string; // Legacy saved field; ignored for launch.
runtime?: GameRuntimeSelection;
@@ -586,8 +595,10 @@ export interface LauncherApi {
readBackendDiagnosticLog(): Promise<DiagnosticLog>;
createDiagnosticReport(gameId?: string): Promise<DiagnosticReport>;
saveDiagnosticReport(content: string): Promise<boolean>;
- login(): Promise<void>;
- logout(): Promise<void>;
+ login(player?: boolean): Promise<void>;
+ logout(player?: boolean): Promise<void>;
+ useAccount(name: string): Promise<void>;
+ forgetAccount(name: string): Promise<void>;
offlinePermissions(): Promise<OfflinePermissions>;
setOfflinePermissions(enabled: boolean): Promise<OfflinePermissions>;
searchCatalog(query: string, cursor?: string): Promise<CatalogSearchResult>;