From fc1e930c2e4acf0e9df27a90e6ee47159e64a82d Mon Sep 17 00:00:00 2001 From: "Danilo M." Date: Mon, 16 Nov 2026 17:15:53 +0100 Subject: feat(xbox): Xbox Live auth chain and token file Co-Authored-By: Claude Opus 5.5 --- deckit/modules/xbox.py | 129 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) (limited to 'deckit/modules/xbox.py') 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() -- cgit v1.2.3