Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

fix(auth): renew the xCloud login and Xbox tokens before they expire

Rafael Abud Ferreirafc87b2e045fe
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index b733128..4ba3f9f 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -314,6 +314,26 @@ std::string stream(xcloud::GssvClient& gssv) {
// Queue -> /connect -> Provisioned -> stream. Returns a status line; sets
// `failed` when the user should see an error rather than the home screen.
// `regionName` overrides the settings' region (empty: as set).
+// Profile token for titlehub (memory only).
+std::string g_xblAuth;
+
+// The sign-in renewed when it is about to expire (AuthManager::ensureFresh;
+// `force`: a request was refused), before the xCloud calls. What other
+// threads hold follows a renewal: titlehub's token, and the copy of the
+// cloud client the queue estimates use.
+bool keepSignedIn(auth::AuthManager& am, xcloud::GssvClient& gssv, std::string& err, bool force = false) {
+ bool renewed = false;
+ if (!am.ensureFresh(&gssv, err, force, &renewed)) return false;
+ if (renewed) {
+ {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ g_xblAuth = am.profile().xblAuthorization;
+ }
+ if (!gssv.isHome()) setQueueClient(&gssv);
+ }
+ return true;
+}
+
std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::GameTile& game, bool& failed,
const std::string& regionName = {}) {
failed = true;
@@ -323,6 +343,10 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
g_ui->showLaunching(game, regionName.empty() ? ui::tr(ui::Str::Connecting)
: ui::trf(ui::Str::TryingRegion, ui::prettyRegion(regionName)));
std::string err;
+ // A login about to expire is renewed first (its region kept); if that
+ // fails the start is tried all the same.
+ if (!keepSignedIn(am, gssv, err)) XC_LOGW("sign-in renewal: %s", err.c_str());
+ err.clear();
std::string streamLocale = ui::gameLocale();
{
std::lock_guard<std::mutex> lock(g_settingsMutex);
@@ -373,7 +397,16 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
// For a crash marker: what is being started (a console's id stays out).
g_stageTitle = game.titleId;
crash::setStage(gssv.isHome() ? "starting own Xbox" : ("starting " + game.titleId).c_str());
- if (!gssv.startSession(game.titleId, streamLocale, err)) {
+ int status = 0;
+ bool started = gssv.startSession(game.titleId, streamLocale, err, &status);
+ if (!started && status == 401 && !g_cancel) {
+ // The token refused before its time: renewed once, asked again.
+ XC_LOGW("%s; renewing the sign-in and asking again", err.c_str());
+ std::string renewErr;
+ if (keepSignedIn(am, gssv, renewErr, true)) started = gssv.startSession(game.titleId, streamLocale, err, &status);
+ else XC_LOGW("sign-in renewal: %s", renewErr.c_str());
+ }
+ if (!started) {
if (err.find("0x87DD043A") != std::string::npos || err.find("MonthlyLimitExceeded") != std::string::npos) {
return std::string(ui::tr(ui::Str::MonthlyLimitExceeded));
}
@@ -468,10 +501,7 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
return result;
}
-void loadLibrary(xcloud::GssvClient& gssv);
-
-// Profile token for titlehub (memory only).
-std::string g_xblAuth;
+void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv);
// --- Updates -------------------------------------------------------------------
@@ -578,8 +608,9 @@ std::string endedToast(const std::string& result) {
void loadConsoles(auth::AuthManager& am, xcloud::GssvClient& home) {
std::string err;
std::vector<xcloud::Console> consoles;
- bool fresh = home.session().expiresAt > auth::unixNow() + 120;
- if ((!fresh && !am.loginOffering(home, err)) || !home.listConsoles(consoles, err)) {
+ // Logged in to the xhome offering with the same Xbox token (renewed
+ // first when it is about to expire).
+ if (!keepSignedIn(am, home, err) || !home.listConsoles(consoles, err)) {
XC_LOGW("consoles: %s", err.c_str());
g_ui->setConsoles({}, true);
return;
@@ -718,11 +749,13 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
for (const auto& r : gssv.session().regions) regions.push_back(r.name);
const xcloud::Region* def = gssv.session().defaultRegion();
g_ui->setRegions(regions, def ? def->name : std::string());
- loadLibrary(gssv);
+ loadLibrary(am, gssv);
}
-void loadLibrary(xcloud::GssvClient& gssv) {
+void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv) {
std::string err;
+ if (!keepSignedIn(am, gssv, err)) XC_LOGW("sign-in renewal: %s", err.c_str());
+ err.clear();
if (g_ui->screen() != ui::Screen::Home) {
g_ui->showSplash(ui::tr(ui::Str::LoadingGames));
} else {
@@ -877,7 +910,7 @@ void worker() {
break;
case kConsoles: loadConsoles(am, home); break;
case kUpdate: runUpdate(); break;
- case kReloadLibrary: loadLibrary(gssv); break; // e.g. after a language change
+ case kReloadLibrary: loadLibrary(am, gssv); break; // e.g. after a language change
case kSignOut:
// Nothing of this account stays for the next one: its library
// stops loading, its cache goes, the lists empty.
@@ -1000,7 +1033,21 @@ void worker() {
autoplayFinished(result);
break;
}
- default: platform::sleepMs(50); break;
+ default: {
+ // Idle and signed in: the sign-in renewed before it expires
+ // (a clock check once a minute, the network only when due),
+ // so the queue estimates and titlehub keep working.
+ static uint64_t nextCheckAt = 0;
+ uint64_t now = platform::nowMs();
+ if (am.signedIn() && now >= nextCheckAt) {
+ std::string err;
+ bool ok = keepSignedIn(am, gssv, err);
+ if (!ok) XC_LOGW("sign-in renewal: %s", err.c_str());
+ nextCheckAt = now + (ok ? 60000 : 300000); // offline: not every minute
+ }
+ platform::sleepMs(50);
+ break;
+ }
}
}
// Closing: the stream (if any) was stopped and its session closed by
diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cpp
index 2af560a..42fbec8 100644
--- a/src/auth/auth_manager.cpp
+++ b/src/auth/auth_manager.cpp
@@ -68,6 +68,7 @@ bool AuthManager::save() const {
}
void AuthManager::signOut() {
+ signedIn_ = false;
tokens_ = {};
profile_ = {};
gssvXsts_ = {};
@@ -111,7 +112,7 @@ bool AuthManager::deviceCodeSignIn(const DeviceCodeCallback& onCode, std::string
return false;
}
-bool AuthManager::xboxChain(xcloud::GssvClient& gssv, std::string& err) {
+bool AuthManager::xboxChain(xcloud::GssvClient* gssv, std::string& err, bool full) {
XblToken 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.
@@ -127,14 +128,50 @@ bool AuthManager::xboxChain(xcloud::GssvClient& gssv, std::string& err) {
profile_.gamertag = profileXsts.gamertag;
profile_.xuid = profileXsts.xuid;
profile_.xblAuthorization = profileXsts.authorizationHeader();
- fetchGamerpic(profileXsts);
+ if (full) fetchGamerpic(profileXsts);
} else {
XC_LOGW("profile XSTS: %s", perr.c_str());
}
if (!xstsToken(user, rp::kGssv, gssvXsts_, err)) return false;
- if (!gssv.login(gssvXsts_, err)) return false;
- fetchSubscription(user, gssv.session().market);
+ if (gssv && !gssv->login(gssvXsts_, err)) return false;
+ if (full) fetchSubscription(user, gssv ? gssv->session().market : std::string());
+ return true;
+}
+
+bool refreshDue(int64_t expiresAt, int64_t now, int64_t marginSec) { return expiresAt - now <= marginSec; }
+
+bool AuthManager::ensureFresh(xcloud::GssvClient* gssv, std::string& err, bool force, bool* renewed) {
+ if (renewed) *renewed = false;
+ if (gssvXsts_.token.empty() || tokens_.refreshToken.empty()) {
+ err = "not signed in"; // only a sign-in made is kept up
+ return false;
+ }
+ int64_t now = unixNow();
+ // An unreadable NotAfter: left to the login's own expiry and to a
+ // refused request (`force`).
+ int64_t xstsUntil = parseIsoUtc(gssvXsts_.notAfter);
+ bool xstsDue = force || (xstsUntil > 0 && refreshDue(xstsUntil, now));
+ bool loginDue = gssv && (xstsDue || refreshDue(gssv->session().expiresAt, now));
+ if (!xstsDue && !loginDue) return true;
+ std::string region = gssv ? gssv->region().name : std::string();
+ if (xstsDue) {
+ XC_LOGI("sign-in: renewing the Xbox tokens (%s)", force ? "a request was refused" : "about to expire");
+ MsaTokens t;
+ if (!msa_.refresh(tokens_.refreshToken, t, err)) return false; // the stored account stays
+ if (t.userId.empty()) t.userId = tokens_.userId;
+ tokens_ = t;
+ // A new refresh token each time: saved at once, as signIn() does.
+ if (!save()) XC_LOGW("the renewed sign-in could not be saved");
+ if (!xboxChain(gssv, err, false)) return false;
+ } else {
+ XC_LOGI("sign-in: renewing the xCloud login (%s)", gssv->isHome() ? "own Xbox" : "cloud");
+ if (!gssv->login(gssvXsts_, err)) return false;
+ }
+ if (gssv && !region.empty()) // login() picked the default region: the chosen one back
+ for (const auto& r : gssv->session().regions)
+ if (r.name == region) gssv->setRegion(r);
+ if (renewed) *renewed = true;
return true;
}
@@ -353,6 +390,7 @@ 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;
bool fresh = false;
if (!tokens_.refreshToken.empty()) {
MsaTokens t;
@@ -376,7 +414,7 @@ bool AuthManager::signIn(xcloud::GssvClient& gssv, const DeviceCodeCallback& onC
if (!deviceCodeSignIn(onCode, err, cancel)) return false;
fresh = true;
}
- if (!xboxChain(gssv, err)) {
+ if (!xboxChain(&gssv, err)) {
// A just-granted token that fails means the account itself is the
// problem (no Xbox profile, no Game Pass...): keep it for diagnosis.
if (!fresh) XC_LOGW("Xbox sign-in failed with stored token: %s", err.c_str());
@@ -384,6 +422,7 @@ bool AuthManager::signIn(xcloud::GssvClient& gssv, const DeviceCodeCallback& onC
return false;
}
save();
+ signedIn_ = true;
XC_LOGI("signed in%s", profile_.gamertag.empty() ? " (no gamertag)" : ""); // the gamertag isn't logged
return true;
}
diff --git a/src/auth/auth_manager.h b/src/auth/auth_manager.h
index 375de7d..2404476 100644
--- a/src/auth/auth_manager.h
+++ b/src/auth/auth_manager.h
@@ -39,6 +39,12 @@ std::string subscriptionRenewal(const std::string& entitlementsJson, int64_t now
// Parses playtime limit from JSON or Protobuf response
bool parsePlaytimeLimit(const std::string& body, int64_t& remaining, int64_t& max);
+// The tokens are renewed this long before they expire.
+constexpr int64_t kRefreshMarginSec = 600;
+// Whether a token that expires at `expiresAt` (unix seconds; 0: none yet)
+// is to be renewed at `now`.
+bool refreshDue(int64_t expiresAt, int64_t now, int64_t marginSec = kRefreshMarginSec);
+
class AuthManager {
public:
// Called while waiting for the user to sign in on another device.
@@ -47,6 +53,8 @@ public:
explicit AuthManager(std::string storePath, MsaConfig cfg = {});
bool hasStoredAccount() const { return !tokens_.refreshToken.empty(); }
+ // The last signIn() went through (until signOut()).
+ bool signedIn() const { return signedIn_; }
// False when the last sign-in couldn't be written to the store file: the
// next start asks for a code again.
bool saved() const { return saved_; }
@@ -65,6 +73,17 @@ public:
// the user's own consoles) in with the same Xbox token.
bool loginOffering(xcloud::GssvClient& other, std::string& err) const;
+ // After signIn(): keeps the sign-in usable. When the XSTS token expires
+ // within kRefreshMarginSec (or `force`: a request was refused), the chain
+ // runs again from the stored refresh token: MSA refresh (the rotated
+ // refresh token saved at once) -> Xbox user token -> XSTS (the profile's
+ // too: profile().xblAuthorization) -> `gssv`'s login. When only `gssv`'s
+ // login is due, just that login. `gssv`'s region stays as chosen; it may
+ // be null (the XSTS only). True when nothing was due or the renewal
+ // worked; `renewed` says whether anything was renewed. A refused refresh
+ // keeps the stored account (the next start decides). No token is logged.
+ bool ensureFresh(xcloud::GssvClient* gssv, std::string& err, bool force = false, bool* renewed = nullptr);
+
void signOut();
const Profile& profile() const { return profile_; }
@@ -73,7 +92,8 @@ private:
bool save() const;
mutable bool saved_ = true;
bool deviceCodeSignIn(const DeviceCodeCallback& onCode, std::string& err, const std::atomic<bool>* cancel);
- bool xboxChain(xcloud::GssvClient& gssv, std::string& err);
+ // `full`: the profile's extras too (gamerpic, plan, playtime): not on a renewal.
+ bool xboxChain(xcloud::GssvClient* gssv, std::string& err, bool full = true);
void fetchGamerpic(const XblToken& xsts);
void fetchSubscription(const XblToken& userToken, const std::string& market);
void fetchPlaytimeLimit(const XblToken& mp, const std::string& market);
@@ -83,6 +103,7 @@ private:
MsaTokens tokens_;
Profile profile_;
XblToken gssvXsts_; // in memory only, for loginOffering()
+ bool signedIn_ = false;
};
} // namespace xc::auth
diff --git a/src/auth/xbox_live.cpp b/src/auth/xbox_live.cpp
index f16ad68..04ee186 100644
--- a/src/auth/xbox_live.cpp
+++ b/src/auth/xbox_live.cpp
@@ -6,6 +6,8 @@
#include "util/json.h"
#include "util/log.h"
+#include <cstdio>
+
namespace xc::auth {
namespace {
@@ -72,4 +74,16 @@ bool xstsToken(const XblToken& userToken, const std::string& relyingParty, XblTo
("XSTS authorization for " + relyingParty).c_str());
}
+int64_t parseIsoUtc(const std::string& iso) {
+ int y = 0, mo = 0, d = 0, h = 0, mi = 0, sec = 0;
+ if (std::sscanf(iso.c_str(), "%d-%d-%dT%d:%d:%d", &y, &mo, &d, &h, &mi, &sec) != 6) return 0;
+ if (y < 1970 || mo < 1 || mo > 12 || d < 1 || d > 31 || h > 23 || mi > 59 || sec > 60) return 0;
+ // Days since 1970-01-01 (the PS5's libc has no timegm).
+ y -= mo <= 2;
+ int64_t era = y / 400, yoe = y - era * 400;
+ int64_t doy = (153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
+ int64_t days = era * 146097 + doe - 719468;
+ return days * 86400 + h * 3600 + mi * 60 + sec;
+}
+
} // namespace xc::auth
diff --git a/src/auth/xbox_live.h b/src/auth/xbox_live.h
index 3ba9b25..cf6634e 100644
--- a/src/auth/xbox_live.h
+++ b/src/auth/xbox_live.h
@@ -4,6 +4,7 @@
// token for a relying party (gssv for xCloud, xboxlive.com for profile data).
#pragma once
+#include <cstdint>
#include <string>
namespace xc::auth {
@@ -32,4 +33,8 @@ bool xblUserToken(const std::string& msaAccessToken, const std::string& rpsPrefi
bool xstsToken(const XblToken& userToken, const std::string& relyingParty, XblToken& out,
std::string& err);
+// 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.
+int64_t parseIsoUtc(const std::string& iso);
+
} // namespace xc::auth
diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cpp
index 5318a80..ba744b2 100644
--- a/src/xcloud/gssv.cpp
+++ b/src/xcloud/gssv.cpp
@@ -455,7 +455,7 @@ bool GssvClient::listConsoles(std::vector<Console>& out, std::string& err) {
return true;
}
-bool GssvClient::startSession(const std::string& titleId, const std::string& locale, std::string& err) {
+bool GssvClient::startSession(const std::string& titleId, const std::string& locale, std::string& err, int* status) {
json::Value settings = json::Value::object();
settings.set("nanoVersion", "V3;WebrtcTransport.dll");
settings.set("enableTextToSpeech", false);
@@ -490,6 +490,7 @@ bool GssvClient::startSession(const std::string& titleId, const std::string& loc
std::string kind = offering_ == "xhome" ? "home" : "cloud";
auto r = net::perform(authed(resolution_, login_, "POST", url("/v5/sessions/" + kind + "/play"), body.dump()));
+ if (status) *status = r.status;
auto j = json::parse(r.body);
if (!r.ok() || !j || !(*j)["sessionPath"].isString()) {
err = "session start failed: " + describe(r);
diff --git a/src/xcloud/gssv.h b/src/xcloud/gssv.h
index b6cc5de..9680698 100644
--- a/src/xcloud/gssv.h
+++ b/src/xcloud/gssv.h
@@ -123,7 +123,8 @@ public:
// --- Session lifecycle -------------------------------------------------
// `titleId` for a cloud game; for the xhome offering, the console's serverId.
- bool startSession(const std::string& titleId, const std::string& locale, std::string& err);
+ // `status`: the answer's HTTP status (0: none), e.g. 401 for a token refused.
+ bool startSession(const std::string& titleId, const std::string& locale, std::string& err, int* status = nullptr);
bool hasSession() const { return !sessionPath_.empty(); }
bool sessionState(SessionStatus& out, std::string& err);
// Before a session: the estimated wait to start `titleId` (xCloud title
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 41301cb..18b7a24 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -53,6 +53,8 @@
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>
+#include <ctime>
+#include <map>
#include <vector>
#include <string>
@@ -946,6 +948,121 @@ static void testPrivacyAndRobustness() {
CHECK(!app::unzip(storedZip({{"PPSA99810/eboot.bin", "a"}, {"PPSA99810/eboot.bin", "b"}}), "PPSA99810/", files, err));
}
+// The sign-in kept up: renewed before it expires (10 minutes ahead), only
+// the xCloud login when only it is due, the whole chain when the XSTS is
+// (or a request was refused), the region kept, the rotated refresh token
+// saved at once, a refused refresh keeping the stored account.
+static void testTokenRefresh() {
+ using namespace xc::auth;
+ CHECK(refreshDue(0, 1000)); // never logged in
+ CHECK(refreshDue(900, 1000)); // expired
+ CHECK(refreshDue(1000 + 600, 1000)); // within the margin
+ CHECK(!refreshDue(1000 + 601, 1000));
+ CHECK(parseIsoUtc("1970-01-02T00:00:00Z") == 86400);
+ CHECK(parseIsoUtc("2026-10-19T09:12:34.1234567Z") == 1792401154);
+ CHECK(parseIsoUtc("2024-02-29T23:59:59Z") == 1709251199);
+ CHECK(parseIsoUtc("") == 0 && parseIsoUtc("soon") == 0 && parseIsoUtc("2026-13-01T00:00:00Z") == 0);
+
+ std::string dir = "/tmp/xcloud-auth-test";
+ std::system(("rm -rf " + dir + " && mkdir -p " + dir).c_str());
+ std::string store = dir + "/account.json";
+ xc::platform::writeFileAtomic(store, R"({"version":1,"clientId":"000000004c20a908","refreshToken":"rt-0"})");
+ int64_t xstsLife = 16 * 3600, loginLife = 300;
+ int serial = 0, logins = 0;
+ bool refuseRefresh = false;
+ std::map<std::string, int> hits;
+ auto iso = [](int64_t t) {
+ std::time_t tt = static_cast<std::time_t>(t);
+ std::tm utc{};
+ gmtime_r(&tt, &utc);
+ char text[40];
+ std::strftime(text, sizeof text, "%Y-%m-%dT%H:%M:%S.0000000Z", &utc);
+ return std::string(text);
+ };
+ net::setTestTransport([&](const net::Request& req) {
+ net::Response r;
+ r.status = 200;
+ const std::string& u = req.url;
+ if (u.find("login.live.com/oauth20_token.srf") != std::string::npos) {
+ ++hits["msa"];
+ if (refuseRefresh) {
+ r.status = 400;
+ r.body = R"({"error":"invalid_grant"})";
+ } else {
+ r.body = R"({"access_token":"at","expires_in":3600,"refresh_token":"rt-)" + std::to_string(++serial) + R"("})";
+ }
+ } else if (u.find("user.auth.xboxlive.com") != std::string::npos) {
+ ++hits["user"];
+ r.body = R"({"Token":"ut","NotAfter":")" + iso(unixNow() + 14 * 86400) + R"(","DisplayClaims":{"xui":[{"uhs":"h"}]}})";
+ } else if (u.find("xsts.auth.xboxlive.com") != std::string::npos) {
+ ++hits["xsts"];
+ r.body = R"({"Token":"xt)" + std::to_string(serial) + R"(","NotAfter":")" + iso(unixNow() + xstsLife) +
+ R"(","DisplayClaims":{"xui":[{"uhs":"h","gtg":"Tester","xid":"1"}]}})";
+ } else if (u.find("gssv-play-prod.xboxlive.com/v2/login/user") != std::string::npos) {
+ ++hits["login"];
+ r.body = R"({"gsToken":"gs)" + std::to_string(++logins) + R"(","market":"US","durationInSeconds":)" +
+ std::to_string(loginLife) +
+ R"(,"offeringSettings":{"regions":[{"name":"EastUS","baseUri":"https://eus.example","isDefault":true},)"
+ R"({"name":"BrazilSouth","baseUri":"https://brs.example","isDefault":false}]}})";
+ } else {
+ ++hits["other"]; // gamerpic, plan, playtime: optional
+ r.status = 404;
+ r.body = "{}";
+ }
+ return r;
+ });
+ auto storedRefresh = [&] {
+ std::string text;
+ xc::platform::readFile(store, text);
+ auto j = json::parse(text);
+ return j ? (*j)["refreshToken"].str() : std::string();
+ };
+ std::string err;
+ bool renewed = true;
+ {
+ AuthManager am(store);
+ xcloud::GssvClient gssv;
+ CHECK(!am.ensureFresh(&gssv, err, false, &renewed) && !renewed && hits.empty()); // not signed in: nothing sent
+ CHECK(am.signIn(gssv, {}, err) && am.signedIn());
+ CHECK(storedRefresh() == "rt-1");
+ // The xCloud login expires in 5 minutes: only it is renewed, in the region chosen.
+ gssv.setRegion(gssv.session().regions[1]);
+ std::string token = gssv.session().gsToken;
+ loginLife = 14400;
+ hits.clear();
+ CHECK(am.ensureFresh(&gssv, err, false, &renewed) && renewed);
+ CHECK(hits.size() == 1 && hits["login"] == 1);
+ CHECK(gssv.session().gsToken != token && gssv.region().name == "BrazilSouth");
+ // Nothing due: nothing sent.
+ hits.clear();
+ CHECK(am.ensureFresh(&gssv, err, false, &renewed) && !renewed && hits.empty());
+ CHECK(am.ensureFresh(nullptr, err, false, &renewed) && !renewed && hits.empty());
+ // A refused request: the whole chain, without the profile's extras;
+ // the rotated refresh token saved at once.
+ CHECK(am.ensureFresh(&gssv, err, true, &renewed) && renewed);
+ CHECK(hits["msa"] == 1 && hits["user"] == 1 && hits["xsts"] == 2 && hits["login"] == 1 && hits["other"] == 0);
+ CHECK(storedRefresh() == "rt-2" && !am.profile().xblAuthorization.empty());
+ CHECK(gssv.region().name == "BrazilSouth");
+ // The XSTS about to expire: renewed without being asked.
+ xstsLife = 120;
+ CHECK(am.ensureFresh(&gssv, err, true, &renewed)); // now holds a 2-minute XSTS
+ xstsLife = 16 * 3600;
+ hits.clear();
+ CHECK(am.ensureFresh(&gssv, err, false, &renewed) && renewed && hits["msa"] == 1 && hits["login"] == 1);
+ hits.clear();
+ CHECK(am.ensureFresh(&gssv, err, false, &renewed) && !renewed && hits.empty());
+ // The refresh refused: false, and the stored account stays.
+ refuseRefresh = true;
+ std::string before = storedRefresh();
+ CHECK(!am.ensureFresh(&gssv, err, true, &renewed) && !renewed);
+ 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
+ }
+ net::setTestTransport({});
+ std::system(("rm -rf " + dir).c_str());
+}
+
// Kept-alive connections: the end of a chunked body from its framing, and a
// connection kept only when the server keeps it and the body ended exactly.
static void testHttpKeepAlive() {
@@ -2201,6 +2318,7 @@ int main() {
testScancodeToVk();
testSdlSensorUnits();
testLoginRetry();
+ testTokenRefresh();
testGyro();
testReport();
testCrashGuard();