From e871557bf2492f05ed2b17a31d560a5ae62ca13d Mon Sep 17 00:00:00 2001 From: devSharaku Date: Thu, 29 Oct 2026 01:07:53 +0100 Subject: [PATCH] Update Xbox backend to 0.2.12 and accept compact JWE tickets (#1729) Some Microsoft accounts get a delegation-compact (d=) ticket, which the pinned Xbox backend (Nexus 0.2.8) rejected: the library stayed empty (store-ticket-format) and downloads failed. This moves the backend to Nexus 0.2.12, which has the upstream store-ticket fix, rebases the DroidDeck credentials, launch-view and cloud-token patches, and strips the d= prefix from compact JWE tickets so downloads work again. Tested by seven users in the Discord Xbox Store Issues thread on the pr-1729 build at d55e05a0. * Update Xbox backend to 0.2.12 * Fix cloud offering fallback and add regression tests * Fix Xbox authentication with compact JWE tickets --- tools/xbox/backend.lock.json | 122 +++++++++++++- tools/xbox/droiddeck-cloud-token.patch | 224 ++++++++++++++++++------- tools/xbox/droiddeck-credentials.patch | 208 ++++++++++++++++++++++- tools/xbox/droiddeck-launch-view.patch | 120 ++++++++----- tools/xbox/droiddeck-xbox-ticket.patch | 79 +++++++++ tools/xbox/prepare.py | 2 +- 6 files changed, 645 insertions(+), 110 deletions(-) create mode 100644 tools/xbox/droiddeck-xbox-ticket.patch diff --git a/tools/xbox/backend.lock.json b/tools/xbox/backend.lock.json index f1568f94d7..86a1c807e3 100644 --- a/tools/xbox/backend.lock.json +++ b/tools/xbox/backend.lock.json @@ -1,12 +1,12 @@ { "schema": 1, - "version": "0.2.8", + "version": "0.2.12", "repository": "https://github.com/xodus-gaming/xodus.git", "commit": "53ea781dcd073e31d7ea68e894134e9c959bff04", "rust": "1.99.0", "cargoLockSha256": "2259b343e00dadc263018beb7664b12e9d58a0b73bff502ad566f5f8619ce28a", - "patchId": "linux-run-v24", - "compatibility": "linux-run-v18", + "patchId": "linux-run-v54", + "compatibility": "linux-run-v25", "patches": [ { "file": "xodus-linux-run.patch", @@ -70,7 +70,7 @@ }, { "file": "xodus-package-selection.patch", - "sha256": "7507cb0535cd914d3607e7940d5e17b949d106d0b89c139b84372a1ee1732c54" + "sha256": "28a2b566afdc1a572cd5ec52027fb48cc1823a25e8f304f282d9bf61e8d46463" }, { "file": "xodus-package-metadata.patch", @@ -103,7 +103,119 @@ { "file": "xodus-content-response.patch", "sha256": "e9997951526cfa08e3dd8c5fc4c383bf630e7ab8992d9e211acee40fdc6422a4" + }, + { + "file": "xodus-streaming-recovery.patch", + "sha256": "7e8550d7b50faf3b3cb7cfcf6e47cff35a0369737d421ef454d4dcf0c9c8ffad" + }, + { + "file": "xodus-download-bandwidth.patch", + "sha256": "4655c51eb93811ea41500be05062a4ff0f64dde3d819dddde12e48d91b075293" + }, + { + "file": "xodus-ticket-diagnostics.patch", + "sha256": "6559c77e06f3c7f29caac95ed979b7644bd4082f9ff777f66713888969c3905e" + }, + { + "file": "xodus-auth-consistency.patch", + "sha256": "930dd88e5ecef2628973ebb4f1652f6888951d71e6531dda7d5d7a258eb435dd" + }, + { + "file": "xodus-metadata-recovery.patch", + "sha256": "b72c473615f2e5d359101cb5fae404aa3b54a34a73118b1c7f99238bd16860e3" + }, + { + "file": "xodus-streaming-handoff.patch", + "sha256": "3be60b5dbca7fae0cb97e18e64665662620b9527c4c1340acfb4c2e2d497e648" + }, + { + "file": "xodus-store-ticket.patch", + "sha256": "5302a699a06208c9b51809eea31261a2a53facce1af3177611ecfc050abb4eb5" + }, + { + "file": "xodus-keyring-encoding.patch", + "sha256": "fa6a0d4ce87f39fdb74950248f1dfd6ccecc4724c76773f5cbf84a8a003729b8" + }, + { + "file": "xodus-encrypted-resume.patch", + "sha256": "73629791cbd91e93664cd77908640484298fa0a17e42a5c1b94b71b2298e8e2c" + }, + { + "file": "xodus-launch-image-errors.patch", + "sha256": "180a4c094a81a6da55044fdc5be7be834575148c12e6789d11f67960d9a22ecf" + }, + { + "file": "xodus-keyring-unlock.patch", + "sha256": "7762a87353d4c1a25133c8c541678cec7e233a6f67589e3d16f66b4738975baa" + }, + { + "file": "xodus-keyring-session-stop.patch", + "sha256": "864e9e427f6298afa012cbbf7586b627e788bcbdc75cabf493274947dce0e8cd" + }, + { + "file": "xodus-keyring-persistence.patch", + "sha256": "78782b557ec3f5457b6e697bb9262ad2403497691d8f23814b42fdd9300b7b46" + }, + { + "file": "xodus-keyring-create.patch", + "sha256": "c79a46f387f7de54e3d3004d646f9e9b141c4d498eebd69a47144450b15442e6" + }, + { + "file": "xodus-bundle-membership.patch", + "sha256": "a5eacc683d006b40247fbf124a62078080685b814cb09a33756083ab99adb72d" + }, + { + "file": "xodus-licensing-jwe.patch", + "sha256": "6f0087e657f225e9a770405fbb34c2317f840615742c89b62f241f1b65c590ca" + }, + { + "file": "xodus-hosted-signin.patch", + "sha256": "f52b16944ca7dfc837337e0257be380467f01872706252d7c2e981db0c57a8bc" + }, + { + "file": "xodus-durable-content.patch", + "sha256": "3d2310fffb020396a68b99e217a81ae1b82920bfa425bf6fd8024c9ea1af6a55" + }, + { + "file": "xodus-conditional-entitlements.patch", + "sha256": "8acc3e079d6f8242d364e5d6cd88bddda7004016c12ed4c48bb353499b95f347" + }, + { + "file": "xodus-content-device-limit.patch", + "sha256": "d6a7115a6efd5d2acaf600590c61e38802632c7afad083639884212984fbccb7" + }, + { + "file": "xodus-authenticated-account-metadata.patch", + "sha256": "1c3845c44efcb4afa49d6618b89e15f39e06804182f281a975f2df14e5a2164d" + }, + { + "file": "xodus-social.patch", + "sha256": "c1571a719715df08fde865a4ec88e359dbeccf27ef3d990310692eb953d01484" + }, + { + "file": "xodus-social-send-receipt.patch", + "sha256": "5b1db84e7d5754b4d2f56771c6d931ecc0579e3a00f7678b4f870fe713d60bc0" + }, + { + "file": "xodus-social-session.patch", + "sha256": "96862af0bb672d6c7ed9575a21412ac68764b5c554f3aa9a380fba7b1fce235a" + }, + { + "file": "xodus-launch-filesystem.patch", + "sha256": "8c898a5756149e2205ad9091203d0953506256bb84bba9080308db840d3ad030" + }, + { + "file": "xodus-plain-launch-entry.patch", + "sha256": "6106f03e38d57f6d62f6662b3567dd5599a3e95b09d653d48e99eb5bba3d3fb8" + }, + { + "file": "xodus-package-storage.patch", + "sha256": "76c2c805a62cc3b424bd5b91c26402a1aee46f21efbd785402aa52aea7784510" + }, + { + "file": "xodus-social-stdout.patch", + "sha256": "9386eedd91d6ac48fd7c369565bb3c2f7c22688a87239ef434d3c6aeb45cf115" } ], - "nexusCommit": "396e7fb8fe0e5f00d956091195c614b8a0732ab1" + "nexusCommit": "ba0e191e1eb8088d00eee7bfe8da80f0a8c5ec72" } diff --git a/tools/xbox/droiddeck-cloud-token.patch b/tools/xbox/droiddeck-cloud-token.patch index 57a0b61727..606410a66e 100644 --- a/tools/xbox/droiddeck-cloud-token.patch +++ b/tools/xbox/droiddeck-cloud-token.patch @@ -1,21 +1,43 @@ -diff --git a/crates/xodus-cli/src/commands.rs b/crates/xodus-cli/src/commands.rs -index 5a66715..5b310e4 100644 --- a/crates/xodus-cli/src/commands.rs +++ b/crates/xodus-cli/src/commands.rs -@@ -6,6 +6,7 @@ pub mod license; +@@ -6,6 +6,7 @@ pub mod login; pub mod logout; pub mod profile; +pub mod cloud_token; + pub mod social; pub mod game_activity; pub mod achievements; - pub mod subscription; -diff --git a/crates/xodus-cli/src/commands/cloud_token.rs b/crates/xodus-cli/src/commands/cloud_token.rs -new file mode 100644 -index 0000000..fbd0ed0 +--- a/crates/xodus-cli/src/main.rs ++++ b/crates/xodus-cli/src/main.rs +@@ -70,6 +70,8 @@ + #[arg(long, default_value_t = false)] + json: bool, + }, ++ #[command(about = "Get an Xbox Cloud Gaming streaming token for the stored account")] ++ CloudToken, + #[command(about = "Read Xbox gamertag and gamerpic for the stored account")] + Profile { + #[arg(long, default_value_t = false)] +@@ -251,6 +253,7 @@ + args.command, + SubCommand::Account { .. } + | SubCommand::Profile { .. } ++ | SubCommand::CloudToken + | SubCommand::Social { .. } + | SubCommand::GameActivity { .. } + | SubCommand::Achievements { .. } +@@ -317,6 +320,7 @@ + } + }, + SubCommand::Profile { json } => commands::profile::run(&tokens, json).await, ++ SubCommand::CloudToken => commands::cloud_token::run(&tokens).await, + SubCommand::Social { .. } => commands::social::run(&tokens).await, + SubCommand::GameActivity { title_id, json } => commands::game_activity::run(&tokens, title_id, json).await, + SubCommand::Achievements { title_id, json } => commands::achievements::run(&tokens, title_id, json).await, --- /dev/null +++ b/crates/xodus-cli/src/commands/cloud_token.rs -@@ -0,0 +1,124 @@ +@@ -0,0 +1,237 @@ +//! Xbox Cloud Gaming streaming token for the stored account (DroidDeck). Same bearer +//! RPS -> Xbox user -> XSTS exchange as the profile read, for the cloud gaming relying party, +//! then the streaming service's user login (as xbox.com and Greenlight's xal-node do). @@ -41,7 +63,7 @@ index 0000000..fbd0ed0 + ExchangeUserTokenOutcome::Issued(soap::BodyContent::RequestSecurityTokenResponse(response)) => *response, + _ => return Err("msa-response"), + }; -+ // Token::from panics on token types it does not know; only take the compact forms here. The cloud ++ // Only accept compact forms here and reject incomplete token responses. The cloud + // transfer purpose answers with a login proof token, which is what /connect takes (Greenlight + // sends the MSAL response's "lpt"). + let kind = response.token_type.clone(); @@ -64,7 +86,7 @@ index 0000000..fbd0ed0 + eprintln!("NEXUS_SESSION_DIAGNOSTIC_V1 ticket-type-{slug}"); + return Err("msa-ticket"); + } -+ let Token::Compact(ticket) = Token::from(response) else { return Err("msa-ticket"); }; ++ let Token::Compact(ticket) = Token::try_from(response).map_err(|_| "msa-ticket")? else { return Err("msa-ticket"); }; + Ok((account, ticket)) +} + @@ -92,30 +114,53 @@ index 0000000..fbd0ed0 + }).take(32).collect()).unwrap_or_default() +} + ++fn offering_response(body: &[u8]) -> Result { ++ let value: Value = serde_json::from_slice(body).map_err(|_| "gssv-json")?; ++ value["gsToken"].as_str().filter(|token| !token.is_empty() && token.len() <= 16384).ok_or("gs-token")?; ++ Ok(value) ++} ++ ++async fn request_offering(client: &reqwest::Client, endpoint: &str, xsts: &str, offering: &str) -> Result { ++ let response = client.post(endpoint) ++ .header("x-gssv-client", "XboxComBrowser").header("Cache-Control", "no-store, must-revalidate, no-cache") ++ .json(&json!({ "token": xsts, "offeringId": offering })).send().await.map_err(|_| "gssv-request")?; ++ let body = super::profile::bounded(response, 256 * 1024).await.map_err(|_| "gssv-response")?; ++ offering_response(&body) ++} ++ ++async fn select_offering(mut request: F) -> Result<(&'static str, Value), String> ++where ++ F: FnMut(&'static str) -> Fut, ++ Fut: std::future::Future>, ++{ ++ let mut failures = Vec::new(); ++ for offering in OFFERINGS { ++ match request(offering).await { ++ Ok(value) => return Ok((offering, value)), ++ Err(stage) => failures.push(format!("{offering}:{stage}")), ++ } ++ } ++ Err(format!("gssv-login {}", failures.join(" "))) ++} ++ +async fn login(tokens: &TokenManager) -> Result { + let client = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()) + .timeout(super::session::REQUEST_TIMEOUT).user_agent("xodus-nexus-cloud/1").build().map_err(|_| "http-client")?; + let (account, xsts) = xsts(tokens, &client).await?; -+ let mut failures = Vec::new(); -+ for offering in OFFERINGS { -+ let response = client.post(format!("https://{offering}.gssv-play-prod.xboxlive.com/v2/login/user")) -+ .header("x-gssv-client", "XboxComBrowser").header("Cache-Control", "no-store, must-revalidate, no-cache") -+ .json(&json!({ "token": xsts, "offeringId": offering })).send().await.map_err(|_| "gssv-request")?; -+ let status = response.status().as_u16(); -+ let body = super::profile::bounded(response, 256 * 1024).await; -+ let Ok(body) = body else { failures.push(format!("{offering}:{status}")); continue; }; -+ let value: Value = serde_json::from_slice(&body).map_err(|_| "gssv-json")?; -+ let token = value["gsToken"].as_str().filter(|token| !token.is_empty() && token.len() <= 16384).ok_or("gs-token")?; -+ // Diagnostic lines are letters and dashes only (the app's allow-list). -+ eprintln!("NEXUS_SESSION_DIAGNOSTIC_V1 gssv-login-ok-{}", if offering == "xgpuweb" { "gamepass" } else { "free" }); -+ let transfer = transfer_token(tokens, &client).await; -+ eprintln!("NEXUS_SESSION_DIAGNOSTIC_V1 transfer-token-{}", if transfer.is_ok() { "ok" } else { "missing" }); -+ if tokens.get_user().map_err(|_| "account-changed")?.username != account { return Err("account-changed".into()); } -+ return Ok(json!({ "schema": 1, "account": account, "offering": offering, "gsToken": token, "userToken": transfer.ok(), -+ "durationInSeconds": value["durationInSeconds"].as_u64().unwrap_or(0), "market": value["market"].as_str().unwrap_or_default(), -+ "regions": regions(&value) })); -+ } -+ Err(format!("gssv-login {}", failures.join(" "))) ++ let (offering, value) = select_offering(|offering| { ++ let endpoint = format!("https://{offering}.gssv-play-prod.xboxlive.com/v2/login/user"); ++ let client = &client; ++ let xsts = &xsts; ++ async move { request_offering(client, &endpoint, xsts, offering).await } ++ }).await?; ++ // Diagnostic lines are letters and dashes only (the app's allow-list). ++ eprintln!("NEXUS_SESSION_DIAGNOSTIC_V1 gssv-login-ok-{}", if offering == "xgpuweb" { "gamepass" } else { "free" }); ++ let transfer = transfer_token(tokens, &client).await; ++ eprintln!("NEXUS_SESSION_DIAGNOSTIC_V1 transfer-token-{}", if transfer.is_ok() { "ok" } else { "missing" }); ++ if tokens.get_user().map_err(|_| "account-changed")?.username != account { return Err("account-changed".into()); } ++ Ok(json!({ "schema": 1, "account": account, "offering": offering, "gsToken": value["gsToken"], "userToken": transfer.ok(), ++ "durationInSeconds": value["durationInSeconds"].as_u64().unwrap_or(0), "market": value["market"].as_str().unwrap_or_default(), ++ "regions": regions(&value) })) +} + +pub async fn run(tokens: &TokenManager) -> ExitCode { @@ -139,33 +184,94 @@ index 0000000..fbd0ed0 + assert_eq!(list.len(), 1); + assert_eq!(list[0]["baseUri"], "https://weu.core.gssv-play-prod.xboxlive.com"); + } ++ #[tokio::test] ++ async fn cloud_fallback_first_success_does_not_call_second_offering() { ++ let mut calls = Vec::new(); ++ let (offering, value) = select_offering(|name| { ++ calls.push(name); ++ std::future::ready(Ok(json!({"gsToken":"synthetic"}))) ++ }).await.unwrap(); ++ assert_eq!(calls, vec!["xgpuweb"]); ++ assert_eq!(offering, "xgpuweb"); ++ assert_eq!(value["gsToken"], "synthetic"); ++ } ++ ++ #[tokio::test] ++ async fn cloud_fallback_request_failure_tries_second_offering() { ++ let mut calls = Vec::new(); ++ let (offering, _) = select_offering(|name| { ++ calls.push(name); ++ std::future::ready(if name == "xgpuweb" { Err("gssv-request") } ++ else { Ok(json!({"gsToken":"synthetic"})) }) ++ }).await.unwrap(); ++ assert_eq!(calls, OFFERINGS); ++ assert_eq!(offering, "xgpuwebf2p"); ++ } ++ ++ #[tokio::test] ++ async fn cloud_fallback_invalid_json_or_token_tries_second_offering() { ++ let invalid = vec![b"not-json".to_vec(), b"{}".to_vec(), ++ br#"{"gsToken":""}"#.to_vec(), br#"{"gsToken":17}"#.to_vec(), ++ serde_json::to_vec(&json!({"gsToken":"x".repeat(16385)})).unwrap()]; ++ for body in invalid { ++ let mut calls = Vec::new(); ++ let (offering, _) = select_offering(|name| { ++ calls.push(name); ++ std::future::ready(if name == "xgpuweb" { offering_response(&body) } ++ else { offering_response(br#"{"gsToken":"synthetic"}"#) }) ++ }).await.unwrap(); ++ assert_eq!(calls, OFFERINGS); ++ assert_eq!(offering, "xgpuwebf2p"); ++ } ++ assert!(offering_response(&serde_json::to_vec(&json!({"gsToken":"x".repeat(16384)})).unwrap()).is_ok()); ++ } ++ ++ #[tokio::test] ++ async fn cloud_fallback_all_failures_report_only_fixed_stages() { ++ let mut calls = Vec::new(); ++ let error = select_offering(|name| { ++ calls.push(name); ++ std::future::ready(offering_response(b"private response containing a token or URL")) ++ }).await.unwrap_err(); ++ assert_eq!(calls, OFFERINGS); ++ assert_eq!(error, "gssv-login xgpuweb:gssv-json xgpuwebf2p:gssv-json"); ++ } ++ ++ async fn http_fixture(status: u16, body: Vec) -> (String, tokio::task::JoinHandle<()>) { ++ use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::TcpListener}; ++ let server = TcpListener::bind("127.0.0.1:0").await.unwrap(); ++ let address = server.local_addr().unwrap(); ++ let task = tokio::spawn(async move { ++ let (mut socket, _) = server.accept().await.unwrap(); ++ let mut request = Vec::new(); ++ let mut buffer = [0u8; 4096]; ++ loop { ++ let n = socket.read(&mut buffer).await.unwrap(); ++ assert!(n > 0 && request.len() + n < 16384); ++ request.extend_from_slice(&buffer[..n]); ++ if let Some(end) = request.windows(4).position(|part| part == b"\r\n\r\n") { ++ let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase(); ++ let length: usize = headers.lines().find_map(|line| line.strip_prefix("content-length:").map(str::trim)).unwrap_or("0").parse().unwrap(); ++ if request.len() >= end + 4 + length { break; } ++ } ++ } ++ let header = format!("HTTP/1.1 {status} Fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); ++ if socket.write_all(header.as_bytes()).await.is_ok() { let _ = socket.write_all(&body).await; } ++ }); ++ (format!("http://{address}/login"), task) ++ } ++ ++ #[tokio::test] ++ async fn cloud_fallback_http_refusal_or_oversized_body_reaches_second_offering() { ++ let client = reqwest::Client::builder().no_proxy().timeout(Duration::from_secs(15)).build().unwrap(); ++ for (status, body) in [(403, b"Forbidden".to_vec()), (200, vec![b'x'; 256 * 1024 + 1])] { ++ let (first, first_task) = http_fixture(status, body).await; ++ let (second, second_task) = http_fixture(200, br#"{"gsToken":"synthetic"}"#.to_vec()).await; ++ let (offering, _) = select_offering(|name| request_offering(&client, ++ if name == "xgpuweb" { &first } else { &second }, "synthetic-xsts", name)).await.unwrap(); ++ assert_eq!(offering, "xgpuwebf2p"); ++ first_task.await.unwrap(); second_task.await.unwrap(); ++ } ++ } ++ +} -diff --git a/crates/xodus-cli/src/main.rs b/crates/xodus-cli/src/main.rs -index 1ae4167..4b0ac26 100644 ---- a/crates/xodus-cli/src/main.rs -+++ b/crates/xodus-cli/src/main.rs -@@ -68,6 +68,8 @@ enum SubCommand { - #[arg(long, default_value_t = false)] - json: bool, - }, -+ #[command(about = "Get an Xbox Cloud Gaming streaming token for the stored account")] -+ CloudToken, - #[command(about = "Read Xbox gamertag and gamerpic for the stored account")] - Profile { - #[arg(long, default_value_t = false)] -@@ -239,6 +241,7 @@ async fn main() -> ExitCode { - args.command, - SubCommand::Account { .. } - | SubCommand::Profile { .. } -+ | SubCommand::CloudToken - | SubCommand::GameActivity { .. } - | SubCommand::Achievements { .. } - | SubCommand::Library { .. } -@@ -304,6 +307,7 @@ async fn main() -> ExitCode { - } - }, - SubCommand::Profile { json } => commands::profile::run(&tokens, json).await, -+ SubCommand::CloudToken => commands::cloud_token::run(&tokens).await, - SubCommand::GameActivity { title_id, json } => commands::game_activity::run(&tokens, title_id, json).await, - SubCommand::Achievements { title_id, json } => commands::achievements::run(&tokens, title_id, json).await, - SubCommand::Login => commands::login::run(&client, &tokens).await, diff --git a/tools/xbox/droiddeck-credentials.patch b/tools/xbox/droiddeck-credentials.patch index bf92276e3a..7a94928b40 100644 --- a/tools/xbox/droiddeck-credentials.patch +++ b/tools/xbox/droiddeck-credentials.patch @@ -85,8 +85,44 @@ +pub fn destroy_secrets() {} --- a/crates/xodus/src/tokens/backend/keychain.rs +++ b/crates/xodus/src/tokens/backend/keychain.rs -@@ -1,22 +1,43 @@ +@@ -1,131 +1,43 @@ +-use base64::{Engine as _, engine::general_purpose::STANDARD}; +- use crate::tokens::store::{TokenBackend, TokenStoreError}; +- +-// GNOME Keyring's passwordless textual format writes secrets with +-// g_key_file_set_value but reads them with g_key_file_get_string. Backslash +-// escapes in JSON (notably XML token attributes) can therefore be rejected or +-// changed on reload. ASCII base64 avoids those escapes without changing the +-// selected keyring or its security policy. This is encoding, not encryption. +-const ENVELOPE: &[u8] = b"XODUS_KEYRING_BASE64_V1:"; +- +-fn encode_secret(value: &[u8]) -> Vec { +- let mut encoded = ENVELOPE.to_vec(); +- encoded.extend_from_slice(STANDARD.encode(value).as_bytes()); +- encoded +-} +- +-fn decode_secret(bytes: Vec) -> Result, TokenStoreError> { +- match bytes.strip_prefix(ENVELOPE) { +- Some(encoded) => STANDARD.decode(encoded).map_err(|_| { +- std::io::Error::new( +- std::io::ErrorKind::InvalidData, +- "Invalid encoded Xodus credential", +- ) +- .into() +- }), +- // Existing credentials are raw JSON. Do not rewrite or delete on reads. +- None => Ok(bytes), +- } +-} +- +-fn deletion_result(result: Result<(), keyring_core::Error>) -> Result<(), TokenStoreError> { +- match result { +- Ok(()) | Err(keyring_core::Error::NoEntry) => Ok(()), +- Err(error) => Err(error.into()), +- } +-} +use serde_json::{Value, json}; +use std::io::{BufRead, Read, Write}; +use std::os::linux::net::SocketAddrExt; @@ -118,7 +154,7 @@ fn get(&self, key: &str) -> Result>, TokenStoreError> { - let entry = crate::secrets::get_entry(key)?; - match entry.get_secret() { -- Ok(bytes) => Ok(Some(bytes)), +- Ok(bytes) => Ok(Some(decode_secret(bytes)?)), - Err(keyring_core::Error::NoEntry) => Ok(None), - Err(e) => Err(e.into()), - } @@ -128,27 +164,185 @@ } - fn set(&self, key: &str, value: &[u8]) -> Result<(), TokenStoreError> { -- Ok(crate::secrets::get_entry(key)?.set_secret(value)?) +- crate::secrets::get_entry(key)?.set_secret(&encode_secret(value))?; +- #[cfg(all(target_os = "linux", not(feature = "key-chain-file")))] +- crate::keyring_persistence::sync_after_write(); + request(json!({"op":"set", "key":key, "value":value}))?; -+ Ok(()) + Ok(()) } - fn remove(&self, key: &str) -> Result<(), TokenStoreError> { -- Ok(crate::secrets::get_entry(key)?.delete_credential()?) +- deletion_result(crate::secrets::get_entry(key)?.delete_credential())?; +- #[cfg(all(target_os = "linux", not(feature = "key-chain-file")))] +- crate::keyring_persistence::sync_after_write(); + request(json!({"op":"remove", "key":key}))?; -+ Ok(()) + Ok(()) } } +- +-#[cfg(test)] +-mod tests { +- use super::*; +- +- #[test] +- fn credential_encoding_preserves_xml_json_and_binary() { +- let xml_json = br#"{"token":"dummy","escapes":"a\\b\n\t\r"}"#; +- let binary: Vec = (0..=255).collect(); +- for value in [ +- xml_json.as_slice(), +- b"".as_slice(), +- binary.as_slice(), +- "synthetic-\u{00e9}".as_bytes(), +- ] { +- let encoded = encode_secret(value); +- assert!(encoded.starts_with(ENVELOPE)); +- // No GKeyFile escapes or physical line breaks can be introduced. +- assert!(encoded.is_ascii()); +- assert!( +- !encoded +- .iter() +- .any(|byte| matches!(byte, b'\\' | b'\n' | b'\r' | 0)) +- ); +- assert_eq!(decode_secret(encoded).unwrap(), value); +- } +- } +- +- #[test] +- fn credential_encoding_accepts_legacy_values_without_rewriting() { +- for value in [ +- br#"{"username":"synthetic"}"#.as_slice(), +- b"".as_slice(), +- b"invalid legacy JSON".as_slice(), +- ] { +- // Validation of legacy JSON remains the TokenManager's job. +- assert_eq!(decode_secret(value.to_vec()).unwrap(), value); +- } +- } +- +- #[test] +- fn credential_encoding_rejects_malformed_envelopes_without_leaking_values() { +- for bad in [ +- b"%%%synthetic-secret-never-print".as_slice(), +- b"YQ".as_slice(), +- ] { +- let mut encoded = ENVELOPE.to_vec(); +- encoded.extend_from_slice(bad); +- let error = decode_secret(encoded).unwrap_err(); +- assert!(matches!(error, TokenStoreError::Io(_))); +- assert!(!error.to_string().contains("synthetic-secret-never-print")); +- } +- } +- +- #[test] +- fn credential_deletion_is_idempotent_but_keeps_other_errors() { +- assert!(deletion_result(Ok(())).is_ok()); +- assert!(deletion_result(Err(keyring_core::Error::NoEntry)).is_ok()); +- assert!(matches!( +- deletion_result(Err(keyring_core::Error::Invalid( +- "synthetic".into(), +- "failure".into() +- ))), +- Err(TokenStoreError::Keychain(_)) +- )); +- } +-} --- a/crates/xodus/Cargo.toml +++ b/crates/xodus/Cargo.toml -@@ -43,8 +43,8 @@ +@@ -43,9 +43,9 @@ smbios-lib = "0.9.4" [target.'cfg(target_os = "linux")'.dependencies] -dbus = "=0.9.12" +-x11-dl = "=2.21.0" -dbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-openssl"]} +dbus = { version = "=0.9.12", optional = true } ++x11-dl = { version = "=2.21.0", optional = true } +dbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-openssl"], optional = true} [target.'cfg(target_os = "macos")'.dependencies] apple-native-keyring-store = { version = "1.0.2", features = ["keychain"]} +--- a/crates/xodus/src/lib.rs ++++ b/crates/xodus/src/lib.rs +@@ -2,12 +2,6 @@ + pub mod auth; + pub mod clep; + pub mod hardware; +-#[cfg(target_os = "linux")] +-mod keyring_persistence; +-#[cfg(target_os = "linux")] +-pub mod keyring_session; +-#[cfg(target_os = "linux")] +-pub mod keyring_unlock; + pub mod licensing; + pub mod models; + pub mod secrets; +--- a/crates/xodus-cli/src/main.rs ++++ b/crates/xodus-cli/src/main.rs +@@ -18,24 +18,6 @@ + + #[derive(Subcommand)] + enum SubCommand { +- #[cfg(target_os = "linux")] +- #[command(about = "Gracefully stop only a Nexus-owned session keyring without accessing credentials")] +- KeyringSessionStop { +- #[arg(long)] +- provider_pid: u32, +- }, +- #[cfg(target_os = "linux")] +- #[command(about = "Create the first default wallet using the provider's password dialog")] +- KeyringCreate { +- #[arg(long, default_value = "")] +- window_id: String, +- }, +- #[cfg(target_os = "linux")] +- #[command(about = "Unlock the default system wallet without reading credentials or signing in")] +- KeyringUnlock { +- #[arg(long, default_value = "")] +- window_id: String, +- }, + #[command(about = "Resolve public Store packages without sign-in or downloading")] + ResolvePackage { + product: String, +@@ -238,29 +220,6 @@ + .build() + .unwrap(); + let args = CliArgs::parse(); +- #[cfg(target_os = "linux")] +- if let SubCommand::KeyringSessionStop { provider_pid } = &args.command { +- let state = xodus::keyring_session::stop_session_provider(*provider_pid); +- println!("{}", serde_json::json!({"schema": 1, "state": state.as_str()})); +- return if state == xodus::keyring_session::StopState::Unavailable { ExitCode::FAILURE } else { ExitCode::SUCCESS }; +- } +- #[cfg(target_os = "linux")] +- if let SubCommand::KeyringUnlock { window_id } | SubCommand::KeyringCreate { window_id } = &args.command { +- use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; +- let cancelled = Arc::new(AtomicBool::new(false)); +- let signal = cancelled.clone(); +- let state = if ctrlc::set_handler(move || { signal.store(true, Ordering::SeqCst); }).is_err() { +- xodus::keyring_unlock::UnlockState::Unavailable +- } else { +- if matches!(&args.command, SubCommand::KeyringCreate { .. }) { +- xodus::keyring_unlock::create_default(window_id, &cancelled) +- } else { +- xodus::keyring_unlock::unlock_default(window_id, &cancelled) +- } +- }; +- println!("{}", serde_json::json!({"schema": 1, "state": state.as_str()})); +- return ExitCode::SUCCESS; +- } + #[cfg(not(feature = "native-webview"))] + if args.external_webview_stdio { + webview::enable_stdio(); +@@ -308,12 +267,6 @@ + } + + let code = match args.command { +- #[cfg(target_os = "linux")] +- SubCommand::KeyringSessionStop { .. } => unreachable!(), +- #[cfg(target_os = "linux")] +- SubCommand::KeyringUnlock { .. } => unreachable!(), +- #[cfg(target_os = "linux")] +- SubCommand::KeyringCreate { .. } => unreachable!(), + SubCommand::ResolvePackage { .. } => unreachable!(), + SubCommand::Download { + product, diff --git a/tools/xbox/droiddeck-launch-view.patch b/tools/xbox/droiddeck-launch-view.patch index 4f8836a18b..d3ca2d3df8 100644 --- a/tools/xbox/droiddeck-launch-view.patch +++ b/tools/xbox/droiddeck-launch-view.patch @@ -1,6 +1,6 @@ --- a/crates/xodus-cli/src/commands/run.rs +++ b/crates/xodus-cli/src/commands/run.rs -@@ -77,6 +77,7 @@ +@@ -146,6 +146,7 @@ launch_image: &Path, materialize_chain: bool, ) -> (String, String) { @@ -8,7 +8,7 @@ let source_nt = source.to_string_lossy().replace('/', "\\"); let source_nt = source_nt.trim_end_matches('\\'); let mirror_unix = mirror_nt_prefix.map(|prefix| prefix.replace('\\', "/")); -@@ -200,9 +201,7 @@ +@@ -303,9 +304,7 @@ let entry_path = checked_relative_path(entry_suffix)?; let mut decrypted = HashMap::new(); for (name, fd) in fds { @@ -19,22 +19,41 @@ } if !decrypted.contains_key(&entry_path) { return Err(std::io::Error::new( -@@ -222,11 +221,8 @@ +@@ -325,7 +324,8 @@ } } let decrypted_files: HashSet = decrypted.keys().cloned().collect(); -- let parent = source_root.parent().unwrap_or_else(|| Path::new("/tmp")); -- let mirror = Builder::new() -- .prefix(".xodus-chain-") -- .tempdir_in(parent) -- .or_else(|_| Builder::new().prefix("xodus-chain-").tempdir())?; +- let mirror = launch_view_directory(source_root, ".xodus-chain-")?; + let mirror = Builder::new().prefix("droiddeck-xbox-") + .permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)).tempdir()?; populate_launch_view( source_root, mirror.path(), -@@ -667,21 +663,15 @@ - use std::os::fd::AsRawFd; +@@ -725,6 +725,22 @@ + ); + } + ++ if wine == "droiddeck:prepare" { ++ use std::io::Write; ++ if !materialize_chain { return ExitCode::FAILURE; } ++ let ready = serde_json::json!({ ++ "exe": stub_path, ++ "playfab": playfab_auth_header(client, tokens).await, ++ }); ++ println!("DROIDDECK_LAUNCH_V1 {}", ready); ++ let _ = std::io::stdout().flush(); ++ let mut release = String::new(); ++ let _ = std::io::stdin().read_line(&mut release); ++ drop(launch_mirror); ++ cleanup().await; ++ return ExitCode::SUCCESS; ++ } ++ + let mut command = Command::new(wine); + command + .arg(&stub_path) +@@ -831,21 +847,15 @@ + } #[test] - fn full_launch_view_uses_real_executables_and_preserves_encrypted_dll_maps() { @@ -58,13 +77,10 @@ } #[test] -@@ -778,6 +768,25 @@ - .is_symlink()); - assert_eq!(std::fs::read(source.join("Dungeons.exe")).unwrap(), b"encrypted launcher"); - assert_eq!(std::fs::read(nested.join("Shipping.exe")).unwrap(), b"encrypted child"); -+ } -+ -+ #[test] +@@ -945,6 +955,44 @@ + } + + #[test] + fn launch_view_materializes_encrypted_dlls_in_private_storage() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("Game.exe"), b"encrypted").unwrap(); @@ -81,26 +97,54 @@ + assert_eq!(std::fs::read(root.path().join("Secret.dll")).unwrap(), b"encrypted-dll"); + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(view.path()).unwrap().permissions().mode() & 0o077, 0); - } - - #[test] ---- a/crates/xodus-cli/src/commands/run.rs -+++ b/crates/xodus-cli/src/commands/run.rs -@@ -618 +618,17 @@ -+ if wine == "droiddeck:prepare" { -+ use std::io::Write; -+ if !materialize_chain { return ExitCode::FAILURE; } -+ let ready = serde_json::json!({ -+ "exe": stub_path, -+ "playfab": playfab_auth_header(client, tokens).await, -+ }); -+ println!("DROIDDECK_LAUNCH_V1 {}", ready); -+ let _ = std::io::stdout().flush(); -+ let mut release = String::new(); -+ let _ = std::io::stdin().read_line(&mut release); -+ drop(launch_mirror); -+ cleanup().await; -+ return ExitCode::SUCCESS; + } + - let mut command = Command::new(wine); ++ ++ #[test] ++ fn launch_view_rejects_invalid_decrypted_library_without_changing_sources() { ++ let root = tempfile::tempdir().unwrap(); ++ std::fs::write(root.path().join("Game.exe"), b"encrypted executable").unwrap(); ++ std::fs::write(root.path().join("Bad.dll"), b"encrypted library").unwrap(); ++ let mut exe_image = tempfile::tempfile().unwrap(); ++ exe_image.write_all(&fake_pe()).unwrap(); ++ let mut dll_image = tempfile::tempfile().unwrap(); ++ dll_image.write_all(b"not a PE library").unwrap(); ++ let exe = String::from("Game.exe"); ++ let dll = String::from("Bad.dll"); ++ let images = [(&exe, exe_image.as_raw_fd()), (&dll, dll_image.as_raw_fd())]; ++ let error = create_launch_chain_mirror(root.path(), &exe, &images).unwrap_err(); ++ assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); ++ assert_eq!(std::fs::read(root.path().join("Game.exe")).unwrap(), b"encrypted executable"); ++ assert_eq!(std::fs::read(root.path().join("Bad.dll")).unwrap(), b"encrypted library"); ++ } ++ ++ #[test] + fn launch_chain_rejects_parent_path_components() { + assert!(checked_relative_path("..\\outside.exe").is_err()); + } +@@ -961,16 +1009,20 @@ + assert_eq!(name, "Bin\\MINECRAFT.WINDOWS.EXE"); + assert!(!fcntl_getfd(file.as_fd()).unwrap().contains(FdFlags::CLOEXEC)); + let dll_name = String::from("Encrypted.dll"); +- let mut dll = tempfile::tempfile().unwrap(); dll.write_all(b"synthetic decrypted library").unwrap(); ++ std::fs::write(root.path().join("Encrypted.dll"), b"encrypted library").unwrap(); ++ let mut dll = tempfile::tempfile().unwrap(); dll.write_all(&fake_pe()).unwrap(); + let images = [(&dll_name, dll.as_raw_fd()), (&name, file.as_raw_fd())]; + assert!(select_launch_entry(&images[..1], Some("bin/Minecraft.Windows.exe")).is_err()); + assert_eq!(select_launch_entry(&images, Some("bin/Minecraft.Windows.exe")).unwrap().1, file.as_raw_fd()); + let (mirror, entry, count, bytes) = create_launch_chain_mirror(root.path(), &name, &images).unwrap(); +- assert_eq!(count, 1); assert_eq!(bytes, original.len() as u64); ++ assert_eq!(count, 2); assert_eq!(bytes, 2 * original.len() as u64); + assert_eq!(std::fs::read(entry).unwrap(), original); +- let (nt, _) = launch_file_maps(&images, root.path(), Some("\\synthetic-view"), &name, file.as_raw_fd(), &mirror.path().join("Bin/MINECRAFT.WINDOWS.EXE"), true); +- assert!(nt.contains("synthetic-view\\Encrypted.dll")); +- assert!(!nt.contains("synthetic-view\\Bin\\MINECRAFT.WINDOWS.EXE")); ++ let (nt, unix) = launch_file_maps(&images, root.path(), Some("\\synthetic-view"), &name, file.as_raw_fd(), &mirror.path().join("Bin/MINECRAFT.WINDOWS.EXE"), true); ++ assert!(nt.is_empty()); ++ assert!(unix.is_empty()); ++ assert_eq!(std::fs::read(mirror.path().join("Encrypted.dll")).unwrap(), fake_pe()); ++ assert!(!std::fs::symlink_metadata(mirror.path().join("Encrypted.dll")).unwrap().file_type().is_symlink()); ++ assert_eq!(std::fs::read(root.path().join("Encrypted.dll")).unwrap(), b"encrypted library"); + assert_eq!(std::fs::read(root.path().join("Bin/MINECRAFT.WINDOWS.EXE")).unwrap(), original); + assert_eq!(std::fs::read(root.path().join("MicrosoftGame.config")).unwrap(), b"metadata unchanged"); + } diff --git a/tools/xbox/droiddeck-xbox-ticket.patch b/tools/xbox/droiddeck-xbox-ticket.patch new file mode 100644 index 0000000000..78093d74d3 --- /dev/null +++ b/tools/xbox/droiddeck-xbox-ticket.patch @@ -0,0 +1,79 @@ +--- a/crates/xodus/src/models/secrets.rs ++++ b/crates/xodus/src/models/secrets.rs +@@ -80,9 +80,17 @@ + } + } + +-/// Store and licensing services reject delegation-compact tickets in the "d=" +-/// form that Xbox Live sign-in needs (InvalidMsaTicketFormat) and accept the +-/// same value as "t=". Convert only where a ticket is sent to those services. ++// Xbox accepts compact JWE tickets without the delegation prefix; opaque ++// delegation tickets keep their original wire representation. ++pub fn xbox_ticket(ticket: String) -> String { ++ match ticket.strip_prefix("d=") { ++ Some(raw) if is_compact_jwe(raw) => raw.to_owned(), ++ _ => ticket, ++ } ++} ++ ++/// Store services accept delegation-compact tickets in the "t=" form. ++/// Convert only where a ticket is sent to those services. + pub fn store_ticket(ticket: String) -> String { + match ticket.strip_prefix("d=") { + Some(value) => format!("t={value}"), +--- a/crates/xodus/src/models/licensing_ticket_tests.rs ++++ b/crates/xodus/src/models/licensing_ticket_tests.rs +@@ -1,5 +1,5 @@ + //! Public synthetic data only, no account, keyring or network access. +-use super::{Token, licensing_ticket, store_ticket}; ++use super::{Token, licensing_ticket, store_ticket, xbox_ticket}; + use crate::models::soap; + use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; + use serde_json::json; +@@ -77,3 +77,35 @@ + let long_header = jwe(json!({"alg":"dir","enc":"A256GCM","kid":"a".repeat(9000)}), ""); + assert_eq!(licensing_ticket(format!("d={long_header}")), format!("t={long_header}")); + } ++ ++#[test] ++fn credential_xbox_ticket_compact_jwe_uses_bare_wire_format_without_changing_store_conversion() { ++ for raw in [ ++ jwe(json!({"alg":"dir","enc":"A128CBC-HS256"}), ""), ++ jwe(json!({"alg":"RSA-OAEP-256","enc":"A256GCM"}), "a2V5"), ++ ] { ++ let Token::Compact(original) = delegation(&raw) else { panic!("fixture"); }; ++ assert_eq!(original, format!("d={raw}")); ++ assert_eq!(store_ticket(original.clone()), format!("t={raw}")); ++ assert_eq!(xbox_ticket(original), raw); ++ assert_eq!(xbox_ticket(raw.clone()), raw); ++ assert_eq!(xbox_ticket(format!("t={raw}")), format!("t={raw}")); ++ } ++} ++ ++#[test] ++fn credential_xbox_ticket_opaque_and_malformed_tokens_are_preserved() { ++ let valid = jwe(json!({"alg":"dir","enc":"A256GCM"}), ""); ++ let mut cases = vec!["d=opaque".to_string(), "opaque".into(), "".into(), "d=".into(), ++ "d=opaque..iv.ciphertext.tag".into(), "d=eyJ..a.b.c".into(), ++ format!("d={valid}.extra"), format!("d={}", valid.replace("..", ".+.")), ++ format!("d={}", jwe(json!({"alg":"dir"}), "")), ++ format!("d={}", jwe(json!({"alg":"dir","enc":""}), "")), ++ format!("d={}", jwe(json!({"alg":"dir","enc":"A256GCM","kid":"a".repeat(9000)}), ""))]; ++ let mut parts: Vec<_> = valid.split('.').map(str::to_string).collect(); ++ for index in [2, 3, 4] { ++ let old = parts[index].clone(); parts[index].clear(); ++ cases.push(format!("d={}", parts.join("."))); parts[index] = old; ++ } ++ for ticket in cases { assert_eq!(xbox_ticket(ticket.clone()), ticket); } ++} +--- a/crates/xodus/src/api/xbox/auth.rs ++++ b/crates/xodus/src/api/xbox/auth.rs +@@ -12,7 +12,7 @@ + properties: UserAuthProperties { + auth_method: "RPS".to_string(), + site_name: "user.auth.xboxlive.com".to_string(), +- rps_ticket, ++ rps_ticket: crate::models::secrets::xbox_ticket(rps_ticket), + }, + }; + diff --git a/tools/xbox/prepare.py b/tools/xbox/prepare.py index 47564ad11a..8d435d34b0 100755 --- a/tools/xbox/prepare.py +++ b/tools/xbox/prepare.py @@ -10,7 +10,7 @@ recipe = Path(__file__).resolve().parent cache = Path(sys.argv[1]).resolve() lock = json.loads((recipe / 'backend.lock.json').read_text()) local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch', - 'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch'] + 'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', 'droiddeck-xbox-ticket.patch'] identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest() source = cache / ('source-' + identity[:16]) if not (source / '.prepared').is_file():