Xbox Cloud Gaming app for PS5 Homebrew
C
fix(auth): improve login resilience, storage durability, and network timeouts
Rafael Abud Ferreirabd9928721410
diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 4be88b2..e860cef 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -694,9 +694,9 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {} else if (err.find("user interaction is required") != std::string::npos ||err.find("invalid_grant") != std::string::npos ||err.find("authorization_declined") != std::string::npos) {- g_ui->showError(ui::tr(ui::Str::SignInInteractionRequired));+ g_ui->showError(ui::tr(ui::Str::SignInInteractionRequired), am.redirectUrl());} else {- g_ui->showError(ui::trf(ui::Str::SignInFailed, err));+ g_ui->showError(ui::trf(ui::Str::SignInFailed, err), am.redirectUrl());}if (!g_autoplay.title.empty()) XC_LOGI("AUTOPLAY END: sign-in failed");return;diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cppindex 42fbec8..9a24317 100644--- a/src/auth/auth_manager.cpp+++ b/src/auth/auth_manager.cpp@@ -69,6 +69,7 @@ bool AuthManager::save() const {void AuthManager::signOut() {signedIn_ = false;+ redirectUrl_.clear();tokens_ = {};profile_ = {};gssvXsts_ = {};@@ -116,15 +117,15 @@ bool AuthManager::xboxChain(xcloud::GssvClient* gssv, std::string& err, bool fulXblToken user;// login.live.com tokens for a custom client id use the "t=" ticket form;// fall back to "d=" in case the service expects the MSAL form.- if (!xblUserToken(tokens_.accessToken, "t=", user, err)) {+ if (!xblUserToken(tokens_.accessToken, "t=", user, err, &redirectUrl_)) {std::string err2;- if (!xblUserToken(tokens_.accessToken, "d=", user, err2)) return false;+ if (!xblUserToken(tokens_.accessToken, "d=", user, err2, &redirectUrl_)) return false;err.clear();}XblToken profileXsts;std::string perr;- if (xstsToken(user, rp::kXboxLive, profileXsts, perr)) {+ if (xstsToken(user, rp::kXboxLive, profileXsts, perr, &redirectUrl_)) {profile_.gamertag = profileXsts.gamertag;profile_.xuid = profileXsts.xuid;profile_.xblAuthorization = profileXsts.authorizationHeader();@@ -133,7 +134,7 @@ bool AuthManager::xboxChain(xcloud::GssvClient* gssv, std::string& err, bool fulXC_LOGW("profile XSTS: %s", perr.c_str());}- if (!xstsToken(user, rp::kGssv, gssvXsts_, err)) return false;+ if (!xstsToken(user, rp::kGssv, gssvXsts_, err, &redirectUrl_)) return false;if (gssv && !gssv->login(gssvXsts_, err)) return false;if (full) fetchSubscription(user, gssv ? gssv->session().market : std::string());return true;@@ -391,21 +392,25 @@ void AuthManager::fetchGamerpic(const XblToken& xsts) {bool AuthManager::signIn(xcloud::GssvClient& gssv, const DeviceCodeCallback& onCode, std::string& err,const std::atomic<bool>* cancel) {signedIn_ = false;+ redirectUrl_.clear();bool fresh = false;if (!tokens_.refreshToken.empty()) {MsaTokens t;bool networkError = false;- if (msa_.refresh(tokens_.refreshToken, t, err, {}, &networkError)) {+ bool invalidGrant = false;+ if (msa_.refresh(tokens_.refreshToken, t, err, {}, &networkError, &invalidGrant)) {tokens_ = t;// Microsoft hands out a new refresh token each time: saved at// once, so an app closed before the Xbox sign-in ends still// starts with the newest one.if (!save()) XC_LOGW("the renewed sign-in could not be saved");- } else if (networkError) {- // Offline or the service is down: keep the stored account.+ } else if (!invalidGrant) {+ // Offline, 5xx, or transient error: keep the stored account.+ XC_LOGW("sign-in refresh failed: %s; keeping stored account", err.c_str());return false;} else {- XC_LOGW("stored sign-in no longer valid (%s); asking again", err.c_str());+ // Only when Microsoft explicitly returns invalid_grant (revoked or expired).+ XC_LOGW("stored sign-in no longer valid (invalid_grant: %s); asking again", err.c_str());tokens_ = {};std::remove(storePath_.c_str());}diff --git a/src/auth/auth_manager.h b/src/auth/auth_manager.hindex 2404476..5b93ad9 100644--- a/src/auth/auth_manager.h+++ b/src/auth/auth_manager.h@@ -86,6 +86,7 @@ public:void signOut();const Profile& profile() const { return profile_; }+ const std::string& redirectUrl() const { return redirectUrl_; }private:bool load();@@ -103,6 +104,7 @@ private:MsaTokens tokens_;Profile profile_;XblToken gssvXsts_; // in memory only, for loginOffering()+ std::string redirectUrl_;bool signedIn_ = false;};diff --git a/src/auth/msa.cpp b/src/auth/msa.cppindex 3a67195..ad546bb 100644--- a/src/auth/msa.cpp+++ b/src/auth/msa.cpp@@ -3,6 +3,7 @@#include "auth/msa.h"#include "net/http.h"+#include "platform/platform.h"#include "util/json.h"#include "util/log.h"@@ -24,6 +25,7 @@ net::Response postForm(const char* url, const std::vector<std::pair<std::string,return net::perform(req);}+bool readTokens(const json::Value& v, MsaTokens& out) {// The console-transfer purpose answers with "lpt" instead of access_token.out.accessToken = v["access_token"].str(v["lpt"].str());@@ -92,14 +94,26 @@ PollResult MsaClient::pollDeviceCode(const DeviceCode& dc, MsaTokens& out, std::}bool MsaClient::refresh(const std::string& refreshToken, MsaTokens& out, std::string& err,- const std::string& scope, bool* networkError) const {- auto r = postForm(kTokenUrl, {{"client_id", cfg_.clientId},- {"grant_type", "refresh_token"},- {"refresh_token", refreshToken},- {"scope", scope.empty() ? cfg_.scope : scope}});+ const std::string& scope, bool* networkError, bool* invalidGrant) const {+ net::Response r;+ constexpr int kTries = 3;+ for (int attempt = 1; attempt <= kTries; ++attempt) {+ r = postForm(kTokenUrl, {{"client_id", cfg_.clientId},+ {"grant_type", "refresh_token"},+ {"refresh_token", refreshToken},+ {"scope", scope.empty() ? cfg_.scope : scope}});+ bool transient = r.status == 0 || r.status == 408 || r.status == 429 || r.status >= 500;+ if (!transient || attempt == kTries) break;+ XC_LOGW("token refresh: %s, trying again (%d/%d)", describe(r).c_str(), attempt + 1, kTries);+ platform::sleepMs(1000u << (attempt - 1));+ }// Throttled or timed out isn't a sign-in gone bad: the stored one stays.if (networkError) *networkError = r.status == 0 || r.status >= 500 || r.status == 429 || r.status == 408;auto j = json::parse(r.body);+ if (invalidGrant) {+ std::string e = j ? (*j)["error"].str() : std::string();+ *invalidGrant = (e == "invalid_grant");+ }if (!r.ok() || !j || !readTokens(*j, out)) {err = "token refresh failed: " + describe(r);return false;diff --git a/src/auth/msa.h b/src/auth/msa.hindex ea78e37..af2424e 100644--- a/src/auth/msa.h+++ b/src/auth/msa.h@@ -41,9 +41,11 @@ public:bool startDeviceCode(DeviceCode& out, std::string& err) const;PollResult pollDeviceCode(const DeviceCode& dc, MsaTokens& out, std::string& err) const;// `scope` empty = the configured sign-in scope. `networkError` (optional)- // tells a transport failure apart from a rejected token.+ // tells a transport failure apart from a rejected token. `invalidGrant`+ // (optional) is true only when Microsoft explicitly returned "invalid_grant".bool refresh(const std::string& refreshToken, MsaTokens& out, std::string& err,- const std::string& scope = {}, bool* networkError = nullptr) const;+ const std::string& scope = {}, bool* networkError = nullptr,+ bool* invalidGrant = nullptr) const;const MsaConfig& config() const { return cfg_; }diff --git a/src/auth/xbox_live.cpp b/src/auth/xbox_live.cppindex 04ee186..ff1886f 100644--- a/src/auth/xbox_live.cpp+++ b/src/auth/xbox_live.cpp@@ -3,6 +3,7 @@#include "auth/xbox_live.h"#include "net/http.h"+#include "platform/platform.h"#include "util/json.h"#include "util/log.h"@@ -17,10 +18,22 @@ net::Response postJson(const std::string& url, const json::Value& body) {req.url = url;req.headers = {{"Content-Type", "application/json"}, {"x-xbl-contract-version", "1"}};req.body = body.dump();- return net::perform(req);+ net::Response r;+ constexpr int kTries = 3;+ for (int attempt = 1; attempt <= kTries; ++attempt) {+ r = net::perform(req);+ bool transient = r.status == 0 || r.status == 408 || r.status == 429 || r.status >= 500;+ if (!transient || attempt == kTries) break;+ XC_LOGW("%s: %s, trying again (%d/%d)", url.c_str(),+ r.status ? ("HTTP " + std::to_string(r.status)).c_str() : r.error.c_str(),+ attempt + 1, kTries);+ platform::sleepMs(1000u << (attempt - 1));+ }+ return r;}-bool readXbl(const net::Response& r, XblToken& out, std::string& err, const char* what) {+bool readXbl(const net::Response& r, XblToken& out, std::string& err, const char* what,+ std::string* redirectUrl = nullptr) {auto j = json::parse(r.body);if (!r.ok() || !j || !(*j)["Token"].isString()) {err = std::string(what) + " failed: ";@@ -33,6 +46,11 @@ bool readXbl(const net::Response& r, XblToken& out, std::string& err, const charif (x == 2148916235) err += " (Xbox Live is not available in this account's country)";if (x == 2148916238) err += " (child account: needs to be added to a family by an adult)";}+ if (j && (*j)["Redirect"].isString()) {+ std::string red = (*j)["Redirect"].str();+ if (redirectUrl) *redirectUrl = red;+ if (!red.empty()) err += " [Redirect: " + red + "]";+ }return false;}out.token = (*j)["Token"].str();@@ -46,7 +64,7 @@ bool readXbl(const net::Response& r, XblToken& out, std::string& err, const char} // namespacebool xblUserToken(const std::string& msaAccessToken, const std::string& rpsPrefix, XblToken& out,- std::string& err) {+ std::string& err, std::string* redirectUrl) {json::Value props = json::Value::object();props.set("AuthMethod", "RPS");props.set("SiteName", "user.auth.xboxlive.com");@@ -56,11 +74,11 @@ bool xblUserToken(const std::string& msaAccessToken, const std::string& rpsPrefibody.set("TokenType", "JWT");body.set("Properties", props);return readXbl(postJson("https://user.auth.xboxlive.com/user/authenticate", body), out, err,- "Xbox user authentication");+ "Xbox user authentication", redirectUrl);}bool xstsToken(const XblToken& userToken, const std::string& relyingParty, XblToken& out,- std::string& err) {+ std::string& err, std::string* redirectUrl) {json::Value users = json::Value::array();users.push(userToken.token);json::Value props = json::Value::object();@@ -71,7 +89,7 @@ bool xstsToken(const XblToken& userToken, const std::string& relyingParty, XblTobody.set("TokenType", "JWT");body.set("Properties", props);return readXbl(postJson("https://xsts.auth.xboxlive.com/xsts/authorize", body), out, err,- ("XSTS authorization for " + relyingParty).c_str());+ ("XSTS authorization for " + relyingParty).c_str(), redirectUrl);}int64_t parseIsoUtc(const std::string& iso) {diff --git a/src/auth/xbox_live.h b/src/auth/xbox_live.hindex cf6634e..fe1c0f5 100644--- a/src/auth/xbox_live.h+++ b/src/auth/xbox_live.h@@ -27,11 +27,11 @@ constexpr const char* kMarketplace = "http://mp.microsoft.com/"; // store / sub} // namespace rp// `rpsPrefix` is "t=" for login.live.com tokens issued to a custom client id,-// "d=" for MSAL/v2.0 tokens.+// "d=" for MSAL/v2.0 tokens. `redirectUrl` (optional) extracts Microsoft's Redirect URL on refusal.bool xblUserToken(const std::string& msaAccessToken, const std::string& rpsPrefix, XblToken& out,- std::string& err);+ std::string& err, std::string* redirectUrl = nullptr);bool xstsToken(const XblToken& userToken, const std::string& relyingParty, XblToken& out,- std::string& err);+ std::string& err, std::string* redirectUrl = nullptr);// An ISO-8601 UTC time ("2026-10-19T09:12:34.1234567Z", a token's NotAfter)// as unix seconds; 0 when it can't be read.diff --git a/src/net/http.cpp b/src/net/http.cppindex 20bca6e..39db7dc 100644--- a/src/net/http.cpp+++ b/src/net/http.cpp@@ -18,6 +18,7 @@#include <netdb.h>#include <netinet/in.h>#include <netinet/tcp.h>+#include <sys/ioctl.h>#include <sys/socket.h>#include <sys/time.h>#include <poll.h>@@ -131,11 +132,38 @@ int connectTcp(const std::string& host, int port, int timeoutMs, std::string& er// A larger window: catalog responses are hundreds of KB from far away.int buf = 1 << 20;::setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buf, sizeof buf);- if (::connect(fd, reinterpret_cast<sockaddr*>(&sa), sizeof sa) != 0) {- err = "connect failed to " + host + ":" + std::to_string(port) + " (errno " + std::to_string(errno) + ")";- ::close(fd);- return -1;++ int on = 1;+ ::ioctl(fd, FIONBIO, &on);+ int rc = ::connect(fd, reinterpret_cast<sockaddr*>(&sa), sizeof sa);+ if (rc != 0) {+ if (errno == EINPROGRESS || errno == EWOULDBLOCK) {+ struct pollfd pfd{};+ pfd.fd = fd;+ pfd.events = POLLOUT;+ int connectTimeout = (timeoutMs > 0) ? std::min(timeoutMs, 10000) : 10000;+ int pr = ::poll(&pfd, 1, connectTimeout);+ if (pr <= 0) {+ err = (pr == 0) ? "connect timed out to " + host + ":" + std::to_string(port)+ : "poll failed connecting to " + host + ":" + std::to_string(port) + " (errno " + std::to_string(errno) + ")";+ ::close(fd);+ return -1;+ }+ int so_error = 0;+ socklen_t len = sizeof so_error;+ if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &so_error, &len) < 0 || so_error != 0) {+ err = "connect failed to " + host + ":" + std::to_string(port) + " (errno " + std::to_string(so_error ? so_error : errno) + ")";+ ::close(fd);+ return -1;+ }+ } else {+ err = "connect failed to " + host + ":" + std::to_string(port) + " (errno " + std::to_string(errno) + ")";+ ::close(fd);+ return -1;+ }}+ on = 0;+ ::ioctl(fd, FIONBIO, &on);return fd;}diff --git a/src/platform/posix_common.cpp b/src/platform/posix_common.cppindex c6ebda0..b698ec3 100644--- a/src/platform/posix_common.cpp+++ b/src/platform/posix_common.cpp@@ -3,6 +3,7 @@// File helpers shared by both platforms (the PS5 libc is POSIX enough).#include "platform/platform.h"+#include <cerrno>#include <cstdio>#include <pthread.h>#include <time.h>@@ -27,9 +28,15 @@ bool writeFileAtomic(const std::string& path, const std::string& data) {if (!f) return false;bool ok = std::fwrite(data.data(), 1, data.size(), f) == data.size();ok = (std::fflush(f) == 0) && ok;+ int fd = ::fileno(f);+ if (fd >= 0) {+ ok = (::fsync(fd) == 0) && ok;+ }ok = (std::fclose(f) == 0) && ok;if (!ok || std::rename(tmp.c_str(), path.c_str()) != 0) {+ int err = errno;std::remove(tmp.c_str());+ errno = err;return false;}return true;diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cppindex fb3f6c0..fca59a0 100644--- a/src/platform/ps5/platform_ps5.cpp+++ b/src/platform/ps5/platform_ps5.cpp@@ -187,8 +187,8 @@ bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err) {return false;}uint32_t a = 0;- // timeout/retry 0: the library defaults.- int rc = sceNetResolverStartNtoa(rid, host.c_str(), &a, 0, 0, 0);+ // timeout 5s (5000000 us), 2 retries (prevents 20-30s DNS freezes).+ int rc = sceNetResolverStartNtoa(rid, host.c_str(), &a, 5000000, 2, 0);sceNetResolverDestroy(rid);if (rc < 0) {char buf[64];diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex 5e56bad..b060c41 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -1004,10 +1004,11 @@ void AppUi::showStreaming() {screen_ = Screen::Streaming;}-void AppUi::showError(const std::string& message) {+void AppUi::showError(const std::string& message, const std::string& url) {std::lock_guard<std::mutex> lock(mutex_);screen_ = Screen::Error;error_ = message;+ errorUrl_ = url;errorGame_ = {};regionRefused_ = countryPickerOpen_ = false;dirty_ = true;@@ -1017,6 +1018,7 @@ void AppUi::showRegionRefused(const std::string& message) {std::lock_guard<std::mutex> lock(mutex_);screen_ = Screen::Error;error_ = message;+ errorUrl_.clear();errorGame_ = {};regionRefused_ = true;countryPickerOpen_ = false;@@ -1027,6 +1029,7 @@ void AppUi::showPlayError(const std::string& message, const GameTile& game) {std::lock_guard<std::mutex> lock(mutex_);screen_ = Screen::Error;error_ = message;+ errorUrl_.clear();errorGame_ = game;regionRefused_ = countryPickerOpen_ = false;dirty_ = true;@@ -3806,9 +3809,12 @@ void AppUi::drawLaunching(Canvas& c, uint64_t nowMs) {void AppUi::drawError(Canvas& c) {drawBackground(c);- auto lines = fonts_.regular.wrap(error_, 26, 1040 - 112, 6);+ int panelW = errorUrl_.empty() ? 1040 : 1300;+ int maxTextW = errorUrl_.empty() ? (panelW - 112) : (panelW - 460);+ auto lines = fonts_.regular.wrap(error_, 26, maxTextW, 8);int h = 132 + static_cast<int>(lines.size()) * 38 + 56;- Rect panel{(kW - 1040) / 2, (kH - h) / 2 - 40, 1040, h};+ if (!errorUrl_.empty() && h < 460) h = 460;+ Rect panel{(kW - panelW) / 2, (kH - h) / 2 - 40, panelW, h};c.fillRect(panel, kPanel, 24);fonts_.bold.draw(c, tr(Str::ErrorTitle), panel.x + 56, panel.y + 52, 44, kWhite);int y = panel.y + 132;@@ -3816,6 +3822,14 @@ void AppUi::drawError(Canvas& c) {fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);y += 38;}+ if (!errorUrl_.empty()) {+ y += 16;+ for (const auto& line : fonts_.regular.wrap(tr(Str::ScanQrToResolve), 24, maxTextW, 4)) {+ fonts_.regular.draw(c, line, panel.x + 56, y, 24, rgba(220, 220, 255));+ y += 34;+ }+ drawQr(c, errorUrl_, panel.x + panel.w - 56, panel.y + 56, 320, qrcodegen_Ecc_LOW);+ }if (!errorGame_.titleId.empty())drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconTriangle, tr(Str::ReportProblem)}, {kIconCircle, tr(Str::Back)}});else if (regionRefused_)diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex fac5c3f..fd32aeb 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -306,7 +306,7 @@ public:void showLaunching(const GameTile& game, const std::string& status);void setLaunchStatus(const std::string& status);void showStreaming();- void showError(const std::string& message);+ void showError(const std::string& message, const std::string& url = {});// A game that could not start but may on another try (a free game got// on the phone meanwhile): Cross plays it again, Circle opens its page.void showPlayError(const std::string& message, const GameTile& game);@@ -570,6 +570,7 @@ private:GameTile detail_; // the game the details page showsGameTile launching_;std::string error_;+ std::string errorUrl_;GameTile errorGame_; // showPlayError()'s game; empty for other errorsSettingsChoice settings_;bool displayModeChanged_ = false; // the Display mode row changed: handle() sends the settingsdiff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex c3c938c..9be5056 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -333,6 +333,7 @@ constexpr Column kEnglish = {"Decode & display latency", // StatsIndicatorDelay"Video quality (QP)", // StatsIndicatorQp"Microphone status", // StatsIndicatorMic+ "Scan the QR code on your phone to resolve this with Microsoft, then press Cross to try again", // ScanQrToResolve};constexpr Column kPortugueseBR = {@@ -636,6 +637,7 @@ constexpr Column kPortugueseBR = {"Atraso de decodificação e exibição", // StatsIndicatorDelay"Qualidade do vídeo (QP)", // StatsIndicatorQp"Status do microfone", // StatsIndicatorMic+ "Use seu celular para ler o código QR ao lado e resolver na Microsoft, depois pressione Cruz para tentar novamente", // ScanQrToResolve};constexpr Column kSpanish = {@@ -939,6 +941,7 @@ constexpr Column kSpanish = {"Retardo de decodificación y pantalla", // StatsIndicatorDelay"Calidad de vídeo (QP)", // StatsIndicatorQp"Estado del micrófono", // StatsIndicatorMic+ "Usa tu teléfono para escanear el código QR y resolver con Microsoft, luego presiona Cruz para reintentar", // ScanQrToResolve};constexpr Column kFrench = {@@ -1242,6 +1245,7 @@ constexpr Column kFrench = {"Latence de décodage et d'affichage", // StatsIndicatorDelay"Qualité vidéo (QP)", // StatsIndicatorQp"État du microphone", // StatsIndicatorMic+ "Scannez le code QR avec votre téléphone pour résoudre ceci chez Microsoft, puis appuyez sur Croix pour réessayer", // ScanQrToResolve};constexpr Column kGerman = {@@ -1545,6 +1549,7 @@ constexpr Column kGerman = {"Dekodier- und Anzeigelatenz", // StatsIndicatorDelay"Videoqualität (QP)", // StatsIndicatorQp"Mikrofonstatus", // StatsIndicatorMic+ "Scannen Sie den QR-Code mit dem Smartphone, um dies bei Microsoft zu beheben, und drücken Sie dann Kreuz zum Wiederholen", // ScanQrToResolve};constexpr Column kItalian = {@@ -1848,6 +1853,7 @@ constexpr Column kItalian = {"Latenza di decodifica e visualizzazione", // StatsIndicatorDelay"Qualità video (QP)", // StatsIndicatorQp"Stato microfono", // StatsIndicatorMic+ "Inquadra il codice QR con lo smartphone per risolvere con Microsoft, poi premi Croce per riprovare", // ScanQrToResolve};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex c5be3a6..3f23076 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -310,6 +310,7 @@ enum class Str {StatsIndicatorDelay,StatsIndicatorQp,StatsIndicatorMic,+ ScanQrToResolve, // Error screen with redirect URL: scan QR to fix accountCount};diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 18b7a24..94d8bd4 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -38,6 +38,7 @@#include "input/sdl_mapping.h"#include "platform/platform.h"#include "auth/msa.h"+#include "auth/xbox_live.h"#include "ui/image_cache.h"#include "xcloud/catalog.h"#include "xcloud/gssv.h"@@ -886,10 +887,26 @@ static void testPrivacyAndRobustness() {status = 400, answer = R"({"error":"authorization_pending"})";CHECK(msa.pollDeviceCode(dc, tokens, err) == auth::PollResult::Pending);bool networkError = false;+ bool isInvalidGrant = false;status = 429, answer = "";- CHECK(!msa.refresh("r", tokens, err, {}, &networkError) && networkError);+ CHECK(!msa.refresh("r", tokens, err, {}, &networkError, &isInvalidGrant) && networkError && !isInvalidGrant);status = 400, answer = R"({"error":"invalid_grant"})";- CHECK(!msa.refresh("r", tokens, err, {}, &networkError) && !networkError);+ isInvalidGrant = false;+ CHECK(!msa.refresh("r", tokens, err, {}, &networkError, &isInvalidGrant) && !networkError && isInvalidGrant);+ status = 500, answer = "Internal Server Error";+ isInvalidGrant = false;+ CHECK(!msa.refresh("r", tokens, err, {}, &networkError, &isInvalidGrant) && !isInvalidGrant);++ // XSTS Redirect URL parsing test+ auth::XblToken userToken{"user_token", "uhs"};+ auth::XblToken xstsOut;+ std::string redir;+ status = 401;+ answer = R"({"Identity":"0","XErr":2148916238,"Message":"","Redirect":"https://start.ui.xboxlive.com/AddChild"})";+ CHECK(!auth::xstsToken(userToken, auth::rp::kGssv, xstsOut, err, &redir));+ CHECK(redir == "https://start.ui.xboxlive.com/AddChild");+ CHECK(err.find("Redirect: https://start.ui.xboxlive.com/AddChild") != std::string::npos);+ CHECK(err.find("child account") != std::string::npos);// A title list whose server always says "more" with the same token ends.status = 200, answer = R"({"results":[{"titleId":"GAME1","details":{"productId":"P1"}}],"continuationToken":"same"})";@@ -1058,6 +1075,28 @@ static void testTokenRefresh() {CHECK(err.find("token refresh failed") != std::string::npos);CHECK(storedRefresh() == before && am.hasStoredAccount());CHECK(err.find(before) == std::string::npos); // no token in the message++ // signIn failure: 500 error preserves account.json; invalid_grant deletes it+ {+ AuthManager amTransient(store);+ net::setTestTransport([&](const net::Request&) {+ net::Response r;+ r.status = 500;+ r.body = "Internal Server Error";+ return r;+ });+ CHECK(!amTransient.signIn(gssv, {}, err));+ CHECK(storedRefresh() == before && amTransient.hasStoredAccount());++ net::setTestTransport([&](const net::Request&) {+ net::Response r;+ r.status = 400;+ r.body = R"({"error":"invalid_grant"})";+ return r;+ });+ CHECK(!amTransient.signIn(gssv, {}, err));+ CHECK(storedRefresh().empty() && !amTransient.hasStoredAccount());+ }}net::setTestTransport({});std::system(("rm -rf " + dir).c_str());