fix(xbox): show why Microsoft sign-in fails, and the gamertag instead of the email (#1322)

Sign-in sat on a black "Preparing Microsoft sign-in…" screen while the Xbox
components downloaded and the helper started, then only said "did not
complete" (#1300). The window now names each step (with download progress),
and a failure says which step failed and why. Our own messages are shown as
written; anything else is named by its exception type only. The line also goes
to the stores log, which the shared log zip carries.

The Stores page showed the account's sign-in email. It now shows the Xbox
gamertag, read with `xodus-cli profile` after the library sync on its own
thread (75 s limit: the command allows itself 45 s, plus PRoot start-up), once
per signed-in account. Until it is known the email is shown masked, and only
the store label while credentials are temporarily unreadable. The account key
used for caches and launches is unchanged.

Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
This commit is contained in:
The412BannerandxXJsonDeruloXx authored and GitHub committed 2026-10-22 14:30:38 -04:00
1 parent 633f66fd49
commit 58f0f27f39
8 files changed
+175 -6

No files matched your search

@@ -94,6 +94,20 @@ object StoreAccounts {
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
}
/** The name the Stores page shows. Xbox shows the gamertag, else the sign-in email with its name part masked. */
fun displayName(context: Context, store: Store): String? {
if (store != Store.XBOX) return signedInAs(context, store)
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
val signedIn = json.optString("username").takeIf { it.isNotBlank() } ?: return null
json.optString("gamertag").takeIf { it.isNotBlank() }?.let { return it }
return maskEmail(signedIn)
}
internal fun maskEmail(name: String): String {
val at = name.indexOf('@')
return if (at <= 0) name.take(1) + "•••" else name.take(1) + "•••" + name.substring(at)
}
private fun seal(f: File, json: JSONObject, retry: Boolean = false): File? {
if (keystoreFailed && !retry) return null
val text = json.toString()
@@ -79,7 +79,7 @@ object StoresState {
val app = context.applicationContext
com.droiddeck.launcher.stores.download.SavedQueue.restore(app)
background("stores-refresh") {
val found = Store.entries.mapNotNull { store -> StoreAccounts.signedInAs(app, store)?.let { store to it } }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled }?.let { InstalledStoreGame(it, folder) }
}
@@ -53,7 +53,7 @@ object XboxBackend : StoreBackend {
else StoresState.status.remove(store)
}
}
if (cached != null && !cached.needsRefresh(force)) return@Thread
if (cached != null && !cached.needsRefresh(force)) { XboxGamertag.ensure(app); return@Thread }
val response = Xodus.run(app, listOf("library", "--json", "--market", market))
val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") })
val products = XboxCatalog.rawProducts(licenses.keys.toList(), market)
@@ -73,6 +73,7 @@ object XboxBackend : StoreBackend {
StoresState.problems.remove(store)
}
}
if (current == generation) XboxGamertag.ensure(app)
} catch (e: Exception) {
StoresState.post {
if (current == generation) {
@@ -0,0 +1,51 @@
package com.droiddeck.launcher.stores.xbox
import android.content.Context
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoresState
/** Keeps the account's Xbox gamertag in its record so the Stores page can show it instead of the sign-in email. */
internal object XboxGamertag {
/** `xodus-cli profile` allows itself 45 s, and starting it through PRoot adds to that. */
private const val TIMEOUT_SECONDS = 75L
private val triedGeneration = java.util.concurrent.atomic.AtomicReference<String?>(null)
internal fun valid(value: String): Boolean = value.isNotEmpty() && value.length <= 64 && value.none { it.isISOControl() }
/** Reads the gamertag with `xodus-cli profile` and stores it; false when Xbox didn't return one. */
fun refresh(app: Context, credentialGeneration: String? = null): Boolean = try {
val gamertag = Xodus.run(app, listOf("profile", "--json"), timeout = TIMEOUT_SECONDS, credentialGeneration = credentialGeneration)
.optString("gamertag").trim()
require(valid(gamertag))
XboxCredentials.lifecycle(app, credentialGeneration) {
val record = StoreAccounts.read(app, Store.XBOX) ?: error("Xbox credentials missing")
record.put("gamertag", gamertag)
StoreAccounts.write(app, Store.XBOX, record)
}
StoresState.logLine("Xbox: gamertag read")
true
} catch (e: Exception) {
StoresState.logLine("Xbox: gamertag unavailable (${XboxLoginActivity.failure(e)})")
false
}
/** Fetches a missing gamertag once per signed-in account, on its own thread so it never holds up a library sync. */
fun ensure(app: Context) {
Thread({
runCatching {
val generation = XboxCredentials.lifecycle(app) { it }
if (!StoreAccounts.read(app, Store.XBOX)?.optString("gamertag").isNullOrBlank()) return@runCatching
if (!shouldTryRefresh(generation)) return@runCatching
if (refresh(app, generation)) StoresState.refresh(app)
}.onFailure { StoresState.logLine("Xbox: gamertag check failed (${it.javaClass.simpleName})") }
}, "xbox-gamertag").start()
}
internal fun shouldTryRefresh(generation: String): Boolean {
while (true) {
val previous = triedGeneration.get()
if (previous == generation) return false
if (triedGeneration.compareAndSet(previous, generation)) return true
}
}
}
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.webkit.CookieManager
import android.webkit.WebResourceRequest
import android.webkit.WebView
@@ -14,8 +15,11 @@ import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoreLogFiles
import com.droiddeck.launcher.stores.StoreLog
import org.json.JSONObject
import java.util.concurrent.TimeUnit
@@ -26,6 +30,7 @@ class XboxLoginActivity : ComponentActivity() {
@Volatile private var child: Xodus.Child? = null
@Volatile private var session = 0L
@Volatile private var closed = false
@Volatile private var step = "starting"
@SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
@@ -49,10 +54,17 @@ class XboxLoginActivity : ComponentActivity() {
if (closed) return@Thread
try {
val accountGeneration = XboxCredentials.lifecycle(applicationContext) { it }
progress("downloading the Xbox components", "Downloading Xbox components…")
check(AddonPack.XBOX.await(applicationContext, { !closed }) { state ->
if (state is AddonPack.State.Downloading) show("Downloading Xbox components… ${(state.progress * 100).toInt()}%")
}) { "Couldn't download the Xbox components. Check your connection and try again." }
if (closed) return@Thread
progress("starting the Xbox helper", "Starting the Xbox helper…")
Xodus.start(applicationContext, listOf("--external-webview-stdio", "login"), credentialGeneration = accountGeneration).use { process ->
child = process
if (closed) return@use
Xodus.diagnostics(process)
progress("waiting for the Xbox helper", "Waiting for the Xbox helper…")
val timer = Thread({
runCatching { if (!process.process.waitFor(10, TimeUnit.MINUTES)) process.process.destroy() }
}, "xbox-login-timeout").apply { start() }
@@ -68,16 +80,19 @@ class XboxLoginActivity : ComponentActivity() {
check(!ready && frame.getInt("version") == 1)
ready = true
process.send(JSONObject().put("type", "hello").put("version", 1))
progress("waiting for Microsoft's sign-in page", "Opening Microsoft sign-in…")
}
"open" -> {
val next = frame.getLong("session")
check(ready && next > latest && next <= 32 && trusted(frame.getString("url")))
latest = next; session = next
step = "loading Microsoft's sign-in page"
runOnUiThread { if (!closed) open(frame) }
}
"close" -> {
check(frame.getLong("session") == session)
session = 0L
step = "completing the sign-in"
runOnUiThread { disposeView(); status.text = "Completing Microsoft sign-in…" }
}
"context" -> {
@@ -95,26 +110,53 @@ class XboxLoginActivity : ComponentActivity() {
else -> error("Unsupported Xbox sign-in response")
}
}
check(process.process.waitFor(5, TimeUnit.SECONDS) && process.process.exitValue() == 0 && ready && latest > 0 && session == 0L)
if (closed) return@use
check(process.process.waitFor(5, TimeUnit.SECONDS)) { "the Xbox helper did not exit" }
val exit = process.process.exitValue()
check(exit == 0) { "the Xbox helper stopped with exit code $exit" }
check(ready) { "the Xbox helper never became ready" }
check(latest > 0) { "Microsoft's sign-in page was never requested" }
check(session == 0L) { "the sign-in page was closed before Microsoft finished" }
timer.interrupt()
}
child = null
if (closed) return@Thread
step = "saving the account"
val account = Xodus.run(applicationContext, listOf("account", "--json"), credentialGeneration = accountGeneration)
check(account.optBoolean("stored"))
check(account.optBoolean("stored")) { "Xbox did not save the account" }
XboxCredentials.lifecycle(this, accountGeneration) {
val record = StoreAccounts.read(this, Store.XBOX) ?: error("Xbox credentials missing")
record.put("username", account.getString("username"))
StoreAccounts.write(this, Store.XBOX, record)
}
logStep("signed in")
runOnUiThread { finish() }
} catch (e: Exception) {
child = null
if (!closed) runOnUiThread { disposeView(); status.text = "Microsoft sign-in did not complete. Close this window and try again." }
if (closed) return@Thread
val failed = step
val reason = failure(e)
logStep("failed while $failed: $reason")
runOnUiThread {
disposeView()
status.text = "Microsoft sign-in did not complete.\nFailed while $failed: $reason\nClose this window and try again."
}
}
}, "xbox-login").start()
}
private fun show(text: String) = runOnUiThread { if (!closed && view == null) status.text = text }
private fun progress(name: String, text: String) { step = name; show(text) }
/** Written to the stores log, which the shared log zip carries; the main process's log helpers don't run in this process. */
private fun logStep(line: String) {
val text = StoreLog.redactLine("Xbox sign-in: $line")
Log.i(TAG, text)
val time = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", java.util.Locale.US).format(java.util.Date())
StoreLogFiles.append(applicationContext, "$time $text")
}
@SuppressLint("SetJavaScriptEnabled")
private fun open(frame: JSONObject) {
disposeView()
@@ -172,6 +214,15 @@ class XboxLoginActivity : ComponentActivity() {
}
companion object {
private const val TAG = "XboxLogin"
/** Our own check messages are safe to show; anything else is named by its type, never its text, which may hold sign-in data. */
internal fun failure(e: Exception): String {
val message = e.message.orEmpty()
return if (e is IllegalStateException && message.isNotBlank() && message != "Check failed." && message.length <= 160) message
else e.javaClass.simpleName.ifBlank { "error" }
}
private val hosts = setOf("login.live.com", "account.live.com", "login.microsoftonline.com", "login.microsoft.com", "account.microsoft.com", "sisu.xboxlive.com")
private val origins = hosts.map { "https://$it" }.toSet()
private val allowedHeaders = setOf("cxh-capabilities", "cxh-correlationid", "cxh-msabinaryversion", "cxh-identityclientbinaryversion", "cxh-osversioninfo", "cxh-platform", "cxh-protocol", "cxh-source", "hostapp")
@@ -136,7 +136,7 @@ internal object Xodus {
fun diagnostics(child: Child): Thread = Thread({
runCatching {
child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line ->
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.")))
if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.")))
com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $line")
} }
}