aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--deckit/modules/xbox.py129
-rw-r--r--tests/test_xbox.py92
2 files changed, 221 insertions, 0 deletions
diff --git a/deckit/modules/xbox.py b/deckit/modules/xbox.py
index e9ca5a8..3989053 100644
--- a/deckit/modules/xbox.py
+++ b/deckit/modules/xbox.py
@@ -41,6 +41,65 @@ from pathlib import Path
from ..module import Module, ModuleError
+MS = "https://login.microsoftonline.com/consumers/oauth2/v2.0"
+SCOPE = "XboxLive.signin offline_access"
+USER_AUTH = "https://user.auth.xboxlive.com/user/authenticate"
+XSTS_AUTH = "https://xsts.auth.xboxlive.com/xsts/authorize"
+PRESENCE = "https://userpresence.xboxlive.com/users/me?level=all"
+XCCS = "https://xccs.xboxlive.com"
+DEVICES = XCCS + "/lists/devices?queryCurrentDevice=false&includeStorageDevices=true"
+TITLEHUB = "https://titlehub.xboxlive.com/users/xuid({})/titles/"
+PROFILE = "https://profile.xboxlive.com/users/me/profile/settings?settings=Gamertag,GameDisplayPicRaw,Gamerscore"
+ACHIEVEMENTS = ("https://achievements.xboxlive.com/users/xuid({})/achievements"
+ "?orderBy=UnlockTime&unlockedOnly=true&maxItems=10")
+FRIENDS = "https://peoplehub.xboxlive.com/users/me/people/friends/decoration/presenceDetail"
+USERSTATS = "https://userstats.xboxlive.com/batch"
+# titlehub answers only clients that name themselves; these are the Xbox app's.
+HUB = {"x-xbl-client-name": "XboxApp", "x-xbl-client-type": "UWA", "x-xbl-client-version": "39.39.22001.0"}
+SG = {"skillplatform": "RemoteManagement"}
+
+FAST = 30 # seconds between presence and console reads
+SLOW = 600 # seconds between profile, games, achievements and friends reads
+# ponytail: renewed by age, not by the XSTS NotAfter (about 16h); a 401 renews early too.
+XSTS_FOR = 8 * 3600
+TITLES = 12 # recent games shown
+
+TOKEN = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "deck-it" / "xbox-token.json"
+STATUS = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}") / "status.xbox"
+
+
+class HttpError(OSError):
+ """An HTTP error answer, with its JSON body when it had one."""
+
+ def __init__(self, status: int, body: dict | None):
+ super().__init__(f"HTTP {status}")
+ self.status, self.body = status, body or {}
+
+
+class SignedOut(Exception):
+ """No refresh token, or Microsoft no longer accepts it."""
+
+
+def _http(url, data=None, headers=None, timeout=10):
+ """A JSON answer. data: a dict or list goes as JSON, a str as a form."""
+ h = {"Accept": "application/json", **(headers or {})}
+ body = None
+ if isinstance(data, dict | list):
+ body, h["Content-Type"] = json.dumps(data).encode(), "application/json"
+ elif isinstance(data, str):
+ body, h["Content-Type"] = data.encode(), "application/x-www-form-urlencoded"
+ try:
+ with urllib.request.urlopen(urllib.request.Request(url, data=body, headers=h), timeout=timeout) as r:
+ raw = r.read()
+ except urllib.error.HTTPError as e:
+ try:
+ payload = json.loads(e.read() or b"{}")
+ except ValueError:
+ payload = {}
+ raise HttpError(e.code, payload if isinstance(payload, dict) else {}) from None
+ return json.loads(raw) if raw else {}
+
+
def foreground(presence: dict) -> dict | None:
"""The title filling a console's screen, if any."""
for dev in presence.get("devices") or []:
@@ -120,3 +179,73 @@ def summarize_friends(r: dict) -> list:
# Replaced in Task 4; here so module discovery (deckit.modules.build) keeps working.
def make(cfg: dict) -> Module:
return Module(name="xbox", title="Xbox", state=lambda: {"offline": True, "unconfigured": True})
+
+
+class Xbox:
+ def __init__(self, cfg: dict, http=_http, token=TOKEN, status=STATUS):
+ self.client_id = str(cfg.get("xbox", {}).get("client_id", "")).strip()
+ self.http, self.token_path, self.status_path = http, Path(token), Path(status)
+ self.refresh = self._load()
+ self.auth = None # {"header", "xuid", "at"} from the last XSTS
+ self.auth_lock = threading.Lock()
+ self.sg_session = str(uuid.uuid4())
+
+ # --- the refresh token file ----------------------------------------
+ def _load(self):
+ try:
+ return json.loads(self.token_path.read_text())["refresh_token"]
+ except (OSError, ValueError, KeyError, TypeError):
+ return None
+
+ def _save(self, refresh: str):
+ self.token_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = self.token_path.with_suffix(".tmp")
+ tmp.unlink(missing_ok=True)
+ with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as f:
+ json.dump({"refresh_token": refresh}, f)
+ os.replace(tmp, self.token_path)
+ self.refresh = refresh
+
+ # --- tokens ---------------------------------------------------------
+ def _form(self, **fields):
+ return self.http(MS + "/token", urllib.parse.urlencode({"client_id": self.client_id, **fields}))
+
+ def _authorize(self):
+ """Refresh token -> MS access token -> Xbox user token -> XSTS."""
+ if not self.refresh:
+ raise SignedOut
+ try:
+ tok = self._form(grant_type="refresh_token", refresh_token=self.refresh, scope=SCOPE)
+ except HttpError as e:
+ if e.body.get("error") in ("invalid_grant", "interaction_required"):
+ self.token_path.unlink(missing_ok=True)
+ self.refresh, self.auth = None, None
+ raise SignedOut from None
+ raise
+ if tok.get("refresh_token") and tok["refresh_token"] != self.refresh:
+ self._save(tok["refresh_token"])
+ v1 = {"x-xbl-contract-version": "1"}
+ user = self.http(USER_AUTH, {"RelyingParty": "http://auth.xboxlive.com", "TokenType": "JWT",
+ "Properties": {"AuthMethod": "RPS", "SiteName": "user.auth.xboxlive.com",
+ "RpsTicket": "d=" + tok["access_token"]}}, v1)
+ xsts = self.http(XSTS_AUTH, {"RelyingParty": "http://xboxlive.com", "TokenType": "JWT",
+ "Properties": {"UserTokens": [user["Token"]], "SandboxId": "RETAIL"}}, v1)
+ xui = xsts["DisplayClaims"]["xui"][0]
+ self.auth = {"header": f"XBL3.0 x={xui['uhs']};{xsts['Token']}", "xuid": xui["xid"],
+ "at": time.monotonic()}
+
+ def api(self, url, contract, data=None, extra=None):
+ """An Xbox Live call with the XSTS header; a 401 renews it once."""
+ with self.auth_lock:
+ if not self.auth or time.monotonic() - self.auth["at"] > XSTS_FOR:
+ self._authorize()
+ for retry in (True, False):
+ headers = {"Authorization": self.auth["header"], "x-xbl-contract-version": str(contract),
+ "Accept-Language": "en-US", **(extra or {})}
+ try:
+ return self.http(url, data, headers)
+ except HttpError as e:
+ if e.status != 401 or not retry:
+ raise
+ with self.auth_lock:
+ self._authorize()
diff --git a/tests/test_xbox.py b/tests/test_xbox.py
index 1143343..b53fe8f 100644
--- a/tests/test_xbox.py
+++ b/tests/test_xbox.py
@@ -14,7 +14,10 @@
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+import json
+import os
import sys
+import tempfile
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
@@ -50,6 +53,95 @@ FRIENDS = {"people": [
{"gamertag": "amy", "displayPicRaw": "a.png", "presenceState": "Online", "presenceText": "Home", "isFavorite": True}]}
+XSTS = {"Token": "XT", "DisplayClaims": {"xui": [{"uhs": "UHS", "xid": "1"}]}}
+
+
+class Fake:
+ """Answers by URL; `fail` maps a URL fragment to an HttpError to raise once."""
+
+ def __init__(self, **over):
+ self.calls, self.fail = [], {}
+ self.answers = {
+ "/oauth2/v2.0/token": {"access_token": "AT", "refresh_token": "RT2"},
+ "/oauth2/v2.0/devicecode": {"user_code": "ABCD-1234", "verification_uri": "https://microsoft.com/devicelogin",
+ "expires_in": 900, "interval": 0, "device_code": "DEV"},
+ "user.auth.xboxlive.com": {"Token": "UT"},
+ "xsts.auth.xboxlive.com": XSTS,
+ "userpresence": PRESENCE,
+ "/lists/devices": CONSOLES,
+ "profile.xboxlive.com": PROFILE,
+ "titlehistory": HISTORY,
+ "titleid(": {"titles": [{"type": "Game"}]},
+ "userstats": STATS,
+ "achievements.xboxlive.com": ACHIEVEMENTS,
+ "peoplehub": FRIENDS,
+ "/commands": {"status": {"errorCode": "OK"}, "opId": "op"},
+ }
+ self.answers.update(over)
+
+ def __call__(self, url, data=None, headers=None, timeout=10):
+ self.calls.append((url, data, headers or {}))
+ for frag, err in list(self.fail.items()):
+ if frag in url:
+ del self.fail[frag]
+ raise err
+ for frag, answer in self.answers.items():
+ if frag in url:
+ return answer
+ raise AssertionError(f"unexpected url {url}")
+
+ def urls(self, frag):
+ return [c for c in self.calls if frag in c[0]]
+
+
+class Base(unittest.TestCase):
+ def setUp(self):
+ self.dir = tempfile.TemporaryDirectory()
+ self.addCleanup(self.dir.cleanup)
+ self.token = Path(self.dir.name) / "cfg" / "xbox-token.json"
+ self.status = Path(self.dir.name) / "status.xbox"
+ self.fake = Fake()
+
+ def xbox(self, signed_in=True, client_id="CID"):
+ if signed_in:
+ self.token.parent.mkdir(parents=True, exist_ok=True)
+ self.token.write_text(json.dumps({"refresh_token": "RT"}))
+ return xb.Xbox({"xbox": {"client_id": client_id}}, self.fake, self.token, self.status)
+
+
+class Auth(Base):
+ def test_chain_builds_the_xbl3_header(self):
+ x = self.xbox()
+ x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
+ url, data, headers = self.fake.urls("userpresence")[0]
+ self.assertEqual(headers["Authorization"], "XBL3.0 x=UHS;XT")
+ self.assertEqual(headers["x-xbl-contract-version"], "3")
+ user = self.fake.urls("user.auth")[0][1]
+ self.assertEqual(user["Properties"]["RpsTicket"], "d=AT")
+ self.assertEqual(x.auth["xuid"], "1")
+
+ def test_a_rotated_refresh_token_is_saved_private(self):
+ x = self.xbox()
+ x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
+ self.assertEqual(json.loads(self.token.read_text()), {"refresh_token": "RT2"})
+ self.assertEqual(os.stat(self.token).st_mode & 0o777, 0o600)
+
+ def test_a_401_renews_once(self):
+ x = self.xbox()
+ x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
+ self.fake.fail["userpresence"] = xb.HttpError(401, {})
+ x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
+ self.assertEqual(len(self.fake.urls("xsts.auth")), 2)
+
+ def test_a_refused_refresh_token_signs_out(self):
+ x = self.xbox()
+ self.fake.fail["/oauth2/v2.0/token"] = xb.HttpError(400, {"error": "invalid_grant"})
+ with self.assertRaises(xb.SignedOut):
+ x.api("https://userpresence.xboxlive.com/users/me?level=all", 3)
+ self.assertFalse(self.token.exists())
+ self.assertIsNone(x.refresh)
+
+
class Summaries(unittest.TestCase):
def test_foreground_is_the_full_placement_title(self):
self.assertEqual(xb.foreground(PRESENCE),