Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.
HTML apple-siliconbattle-netcrossover-alternatived3dmetaldiablo-ii-resurrecteddxmtea-appepic-gamesgame-porting-toolkitgogmac-gamingmacosmacos-gamingrockstar-gamessteamubisoft-connectwhisky-alternativewindows-gameswinewine-wrapper
Xbox PC / Microsoft Store through the Xodus backend (experimental) (#64)
Mikek7258e1a9ccbb
diff --git a/NOTICE b/NOTICEindex 1464ff96fe2..2e045fbd124 100644--- a/NOTICE+++ b/NOTICE@@ -21,7 +21,12 @@ Built or downloaded by the scripts (open-source component releases include corre- Blizzard Battle.net / game files and Valve Steam client: proprietary,installed by their own official installers into the user's prefix-Trademarks: Battle.net and Diablo are trademarks of Blizzard Entertainment.+- Xodus (xodus-cli): GPL-3.0, github.com/xodus-gaming/xodus. Built on the user's Mac from the+ pinned commit in resources/xodus-backend.json; the patched source stays in build/xodus-src.+- MACxus / Xodus Nexus backend patches: MIT, github.com/fladnaG86/MACxus (pinned commit,+ SHA-256 per patch); downloaded at build time, not stored in this repository.++Trademarks: Xbox is a trademark of Microsoft Corporation. Battle.net and Diablo are trademarks of Blizzard Entertainment.Steam is a trademark of Valve Corporation. This project is not affiliated withCodeWeavers, Apple, Blizzard, or Valve.diff --git a/README.ko.md b/README.ko.mdindex 87d7510f897..dee55230ba1 100644--- a/README.ko.md+++ b/README.ko.md@@ -145,6 +145,27 @@ scripts/play.sh gog-kill # GOG 보틀 종료 (창을 닫으면 메뉴게임은 아직 폭넓게 테스트하지 않았습니다. 커널 안티치트(EAC/BattlEye)가 필요한 게임은 Wine에서 돌지 않습니다.+## Xbox PC / Microsoft Store (Xodus 백엔드, 실험 기능)++Microsoft 계정으로 로그인해 보유 게임과 PC Game Pass 게임을 가져오고, Microsoft Store를 검색하고, 게임을 내려받고 실행할 수 있습니다. **게임 실행은 실험 기능이며 Soju에서 실제 게임으로는 아직 확인하지 않았습니다.** 실행 방식은 맥에서 여러 게임이 실행된 MACxus와 같습니다. 실행하려면 CX 엔진과 Apple GPTK가 필요합니다. Xbox PC를 설정하면 엔진이 설치되고, GPTK는 Battle.net·Epic·GOG처럼 Platforms에서 추가합니다.++실행 방식: `xodus-cli run`이 라이선스를 받아 게임을 임시 RAM 디스크에 풀고, `scripts/xbox-wine.sh`가 전용 보틀(`xbox-bottle`)에서 CX 엔진과 D3DMetal로 실행합니다. 이 보틀에는 Xbox 게임 런타임 DLL(xgameruntime 등, LGPL, `resources/xbox-runtime.json`에 고정, 처음 한 번 약 600MB)과 Microsoft VC++ 런타임이 들어갑니다. 게임 중에는 `xodus-service`가 로그인·라이선스·클라우드 저장을 맡고, 게임이 쓴 파일은 끝날 때 게임 폴더로 복사됩니다. Library의 **Stop**으로 게임을 닫으면 저장 파일을 먼저 복사합니다.++백엔드는 [Xodus](https://github.com/xodus-gaming/xodus)(GPL-3.0)입니다. macOS용 배포본이 없어서 `soju xbox-install`이 맥에서 직접 빌드합니다. 고정 커밋의 Xodus 소스에 [MACxus](https://github.com/fladnaG86/MACxus)(MIT)의 패치 44개를 적용합니다. 패치와 `Cargo.lock`은 모두 SHA-256으로 검사하고, rustup의 Rust 1.99로 빌드합니다. 첫 빌드는 몇 분 걸리고 임시 디스크가 1.5GB쯤 필요합니다. 고정값은 `resources/xodus-backend.json`에 있습니다.++```bash+soju xbox-install # 백엔드 빌드 (rustup·protobuf가 없으면 Homebrew로 설치)+soju xbox-login # Microsoft 공식 로그인 창+soju xbox-sync KR # 보유·Game Pass 게임 가져오기 (US, KR, GB, DE, JP)+soju xbox-download 9N116V0599HB # Store 상품 ID로 다운로드, 다시 실행하면 이어받기+soju xbox-logout # 로그아웃 (받은 게임은 유지)+```++- 다운로드 위치는 `~/.battlenet-macos/xbox-bottle/drive_c/XboxGames/<상품ID>`이고, 중단된 곳부터 이어받습니다.+- MSIXVC 형식의 GDK 게임만 받을 수 있습니다. MSIXVC2 게임은 *Not supported*로 표시됩니다 ([xodus#53](https://github.com/xodus-gaming/xodus/issues/53)).+- 로그인 정보는 macOS 키체인의 "Xodus Service" 항목에 저장됩니다. Soju는 게임 ID, 제목, 패키지 형식, 표지 이미지, 계정 표시용 Xbox 게이머태그만 저장하고 계정 이메일과 토큰은 저장하지 않습니다.+- 게임 실행용 Xbox 런타임 파일(xgameruntime 등, 약 600MB)과 Microsoft VC++ 런타임은 처음 한 번 받아서 체크섬을 확인합니다. MACxus가 일부 게임에 쓰는 PlayFab 저장 어댑터는 아직 없어서 그런 게임의 클라우드 저장은 동기화되지 않을 수 있습니다. Easy Anti-Cheat 게임은 맥에서 온라인 플레이가 안 됩니다.+## Steam 지원 (Steam판 D2R 포함)D2R은 2026년 2월 Steam에도 *Infernal Edition*으로 출시됐습니다. Steam은 **다른 무료 엔진**을 씁니다: 최신 Steam 클라이언트의 CEF UI는 CrossOver 소스 계열 빌드에서 렌더링되지 않지만(검은 창, 크로스 프로세스 스왑체인 + CEF 샌드박스 문제), homebrew `wine-stable` 11 + `steamwebhelper` 래퍼(`--disable-gpu --single-process` 강제)로는 동작합니다. 이 해법은 [notpop/steam-on-m1-wine](https://github.com/notpop/steam-on-m1-wine)(MIT, 래퍼 소스는 `third_party/`에 동봉)에서 왔습니다. Steam은 별도 보틀이라 두 스택이 서로 간섭하지 않습니다:diff --git a/README.md b/README.mdindex 1ca4416bea2..0bfc8342447 100644--- a/README.md+++ b/README.md@@ -10,7 +10,8 @@ component updates and diagnostics; the CLI and individual shortcuts remain availSign in to **Steam** to import your owned library, or import theowned library cached by **GOG GALAXY**. Installed and uninstalled games share thesame library, with availability filters and official-client install actions.-**Discover** searches Steam and GOG listings and prices, with links to buy from the stores. Purchases, downloads and updates stay with the official stores.+**Discover** searches Steam, GOG and Microsoft Store listings and prices, with links to buy from the stores.+**Xbox PC (experimental):** sign in to a Microsoft account to import owned and PC Game Pass games, download them through the [Xodus](https://github.com/xodus-gaming/xodus) backend and start them on Soju's engine. Game launch has not been verified with a game on Soju yet. Purchases, downloads and updates stay with the official stores.Epic and Battle.net account imports are not included yet. Compatibility varies by game.@@ -53,6 +54,7 @@ All verified on an M4 Pro running macOS 26.5. Separate bottles for each launcher| Epic Games Launcher | ✅ | ✅ | parks in the menu bar tray on close || GOG GALAXY | ✅ | ✅ | login + library; games not broadly tested yet || Steam (Windows client) | ✅ | ✅ | private Wine 11 + DXMT bottle |+| Xbox PC / Microsoft Store | ✅ | ✅ | Xodus backend; game launch experimental, not yet verified with a game || Game | Store | Graphics | Status | Notes || --- | --- | --- | :-: | --- |@@ -163,6 +165,28 @@ Verified 2026-08-30: install, login, library. GOG GALAXY 2.x is Qt6 + QtWebEnginGames have not been broadly tested yet; anything that needs kernel anti-cheat (EAC/BattlEye) will not run under Wine.+## Xbox PC / Microsoft Store (Xodus backend, experimental)++Soju can sign in to a Microsoft account, import owned and PC Game Pass games, search the Microsoft Store, download games and start them. **Starting games is experimental and has not been verified with a game on Soju yet.** The launch follows the path [MACxus](https://github.com/fladnaG86/MACxus) uses on macOS, where Vampire Survivors, TUNIC, Deep Rock Galactic and others reach gameplay on a CrossOver 26 based engine like Soju's.++How a launch works: `xodus-cli run` gets the licence and decrypts the game into a temporary RAM-disk view; `scripts/xbox-wine.sh` starts it on the CX engine with D3DMetal in its own prefix (`xbox-bottle`). That prefix gets the Xbox game runtime DLLs (xgameruntime and friends, LGPL, from the Xodus Nexus runtime as MACxus rebuilt them for macOS; pinned in `resources/xbox-runtime.json`, about 600 MB downloaded once) and Microsoft's VC++ runtime. `xodus-service` runs during the session for sign-in, licences and cloud saves; the game reaches it through a keyed 127.0.0.1 bridge. Files the game writes are copied back into its folder when it exits. Playing needs the CX engine and Apple GPTK; setting up Xbox PC installs the engine, and GPTK is added in Platforms like for Battle.net, Epic and GOG.++The backend is [Xodus](https://github.com/xodus-gaming/xodus) (GPL-3.0). It has no macOS release, so `soju xbox-install` builds it on your Mac: it clones Xodus at a pinned commit, applies 44 patches from [MACxus](https://github.com/fladnaG86/MACxus) (MIT; they add the library, package and progress commands and the macOS Keychain store), checks the SHA-256 of every patch and of `Cargo.lock`, and builds with Rust 1.99 through rustup. The first build takes a few minutes and needs about 1.5 GB of temporary disk. The pins are in `resources/xodus-backend.json`. The patched source is kept in `~/.battlenet-macos/build/xodus-src`.++```bash+soju xbox-install # build the backend (installs rustup/protobuf with Homebrew if missing)+soju xbox-login # Microsoft's own sign-in page in a window+soju xbox-sync US # import owned + Game Pass games (US, KR, GB, DE, JP)+soju xbox-download 9N116V0599HB # download by Store product ID; run again to resume+soju xbox-logout # sign out; downloaded games stay+```++- Downloads go to `~/.battlenet-macos/xbox-bottle/drive_c/XboxGames/<ProductId>` and resume from where they stopped.+- Only GDK games in the MSIXVC format can be downloaded. Games packaged as MSIXVC2 are marked *Not supported* ([xodus#53](https://github.com/xodus-gaming/xodus/issues/53)).+- The Microsoft sign-in is stored in the macOS Keychain as "Xodus Service". macOS may ask to allow access after a backend rebuild. Soju stores game IDs, titles, package format, box art and your Xbox gamertag (as the account label), never the account e-mail or tokens.+- The owned-library list comes from the same Microsoft endpoint the Xbox PC app uses. If Microsoft changes it, the import fails and the previous import is kept.+- Not set up yet: the PlayFab save adapter MACxus uses for some games, so cloud saves of those titles may not sync. Games with Easy Anti-Cheat cannot run online on macOS (EAC has no macOS Wine module).+## Steam (including the Steam version of D2R)D2R shipped on Steam in Feb 2026 as the *Infernal Edition*. Steam support uses a **different free engine**: the modern Steam client's CEF UI does not render on CrossOver-source builds (black window, cross-process swapchain + CEF sandbox issues), but it works on a pinned upstream Wine 11 build with a tiny `steamwebhelper` wrapper that forces `--disable-gpu --single-process`. That fix comes from [notpop/steam-on-m1-wine](https://github.com/notpop/steam-on-m1-wine) (MIT, wrapper source vendored in `third_party/`). Steam gets its own bottle so the two stacks never interfere:diff --git a/README.zh.md b/README.zh.mdindex e463abe6f1b..9b96f45ad6c 100644--- a/README.zh.md+++ b/README.zh.md@@ -148,6 +148,24 @@ scripts/play.sh gog-kill # 停止 GOG bottle(关窗口会缩到菜单游戏尚未大范围测试;需要内核级反作弊(EAC/BattlEye)的游戏在 Wine 下无法运行。+## Xbox PC / Microsoft Store(Xodus 后端,实验功能)++可以登录 Microsoft 账户,导入已拥有的游戏和 PC Game Pass 游戏,搜索 Microsoft Store 并下载游戏。也可以启动下载好的游戏(实验功能,尚未在 Soju 上用实际游戏验证)。启动需要 CX 引擎和 Apple GPTK:设置 Xbox PC 时会安装引擎,GPTK 与 Battle.net、Epic、GOG 一样在 Platforms 中添加。++启动流程:`xodus-cli run` 获取许可证并把游戏解密到临时 RAM 盘,`scripts/xbox-wine.sh` 在独立前缀(`xbox-bottle`)中用 CX 引擎和 D3DMetal 运行。该前缀包含 Xbox 游戏运行时 DLL(xgameruntime 等,LGPL,固定在 `resources/xbox-runtime.json`,首次下载约 600 MB)和 Microsoft VC++ 运行库。游戏期间 `xodus-service` 负责登录、许可证和云存档,游戏写入的文件在退出时复制回游戏目录。在 Library 中点 **Stop** 关闭游戏时会先复制存档。++后端是 [Xodus](https://github.com/xodus-gaming/xodus)(GPL-3.0),没有 macOS 发行版,所以 `soju xbox-install` 会在你的 Mac 上构建:固定提交的 Xodus 源码加上 [MACxus](https://github.com/fladnaG86/MACxus)(MIT)的 44 个补丁,补丁和 `Cargo.lock` 都校验 SHA-256,用 rustup 的 Rust 1.99 构建。++```bash+soju xbox-install # 构建后端+soju xbox-login # Microsoft 官方登录窗口+soju xbox-sync US # 导入已拥有和 Game Pass 游戏+soju xbox-download 9N116V0599HB # 按商店产品 ID 下载,再次运行可续传+soju xbox-logout # 退出登录(已下载的游戏保留)+```++只支持 MSIXVC 格式的 GDK 游戏,MSIXVC2 暂不支持([xodus#53](https://github.com/xodus-gaming/xodus/issues/53))。登录信息保存在 macOS 钥匙串的 "Xodus Service" 项中。Soju 只保存游戏 ID、标题、包格式、封面和用作账户标签的 Xbox 玩家代号,不保存账户邮箱和令牌。使用 Easy Anti-Cheat 的游戏无法在 macOS 上联机。+## Steam(包括 Steam 版 D2R)D2R 于 2026 年 2 月以 *Infernal Edition* 上架 Steam。Steam 支持用的是**另一个免费引擎**:新版 Steam 客户端的 CEF 界面在 CrossOver 源码构建上无法渲染(黑窗口,跨进程交换链 + CEF 沙箱问题),但在 Homebrew 的 `wine-stable` 11 上,配合一个强制 `--disable-gpu --single-process` 的小 `steamwebhelper` 包装器就能工作。该修复来自 [notpop/steam-on-m1-wine](https://github.com/notpop/steam-on-m1-wine)(MIT,包装器源码收录在 `third_party/`)。Steam 有自己独立的 bottle,两套栈互不干扰:diff --git a/app/Accounts.swift b/app/Accounts.swiftindex 95f64655301..4204e86ca26 100644--- a/app/Accounts.swift+++ b/app/Accounts.swift@@ -99,6 +99,29 @@ extension SojuModel {func forgetAccount(_ platform: Launcher) {guard !accountBusy else { return }do {+ if platform == .xbox {+ // Running downloads need the sign-in; pause them first. The import is+ // removed by xbox.sh only after the sign-out itself succeeded.+ for task in downloadTasks.values { task.terminate() }+ stoppingDownloads.formUnion(downloadTasks.keys)+ accountBusy = true; accountMessage = "Signing out of Microsoft…"+ let (p, _) = try task(["xbox", "logout"], logName: "xbox-account")+ p.terminationHandler = { [weak self] process in+ DispatchQueue.main.async {+ guard let self else { return }+ self.accountBusy = false+ switch process.terminationStatus {+ case 0: self.accountMessage = "Signed out of Microsoft. Downloaded games are kept."+ // xbox.sh: the import is gone, but the Keychain entry could not be removed.+ case 2: self.accountMessage = "The Xbox library was removed, but the Microsoft sign-in is still in the Keychain. Delete \"Xodus Service\" in Keychain Access, or sign out again."+ default: self.accountMessage = "Sign-out did not finish, so you are still signed in. Open Diagnostics in Library for details."+ }+ self.reloadAccountLibrary()+ }+ }+ try p.run()+ return+ }let url = base.appendingPathComponent("account-libraries/" + platform.rawValue + ".json")if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) }if platform == .steam {@@ -119,8 +142,96 @@ extension SojuModel {func installOwnedGame(_ game: InstalledGame) {guard !busy, !game.isInstalled else { return }if !installed.contains(game.platform) { libraryIssue = "Set up " + game.platform.title + " in Platforms first."; return }+ if game.platform == .xbox { download(game); return }run(["game-install", game.id], title: "Opening " + game.platform.title + " to install " + game.title + "…")}+ /// Xbox downloads can take hours, so they run beside other operations, one per game.+ func download(_ game: InstalledGame) {+ guard downloadTasks[game.id] == nil else { return }+ if game.downloadBlocked, let issue = game.issue { libraryIssue = issue; return }+ do {+ let name = "xbox-download-" + game.id.replacingOccurrences(of: ":", with: "-")+ let (p, url) = try task(["game-install", game.id], logName: name)+ downloadTasks[game.id] = p; downloads[game.id] = "Starting download…"+ downloadTimers[game.id] = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in+ DispatchQueue.main.async { self?.readProgress(game.id, url) }+ }+ p.terminationHandler = { [weak self] process in+ DispatchQueue.main.async {+ guard let self else { return }+ self.downloadTimers.removeValue(forKey: game.id)?.invalidate()+ self.downloadTasks.removeValue(forKey: game.id); self.downloads.removeValue(forKey: game.id)+ let stopped = self.stoppingDownloads.remove(game.id) != nil+ NSApp.dockTile.badgeLabel = self.downloadTasks.isEmpty ? nil : String(self.downloadTasks.count)+ // 130: stopped from outside the app (soju xbox-kill); the checkpoint is kept.+ if (stopped && process.terminationStatus != 0) || (process.terminationReason == .exit && process.terminationStatus == 130) {+ self.activity = "Download of " + game.title + " paused. Download again to resume it."+ } else if process.terminationReason == .exit && process.terminationStatus == 0 {+ self.activity = game.title + " is downloaded."+ NSApp.requestUserAttention(.informationalRequest)+ } else if process.terminationReason == .exit {+ let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""+ let reason = text.split(separator: "\n").last(where: { $0.hasPrefix("soju: ") }).map { String($0.dropFirst(6)) }+ self.issueTitle = "Couldn't download " + game.title+ self.libraryIssue = reason ?? "The download stopped. Download again to resume it."+ NSApp.requestUserAttention(.informationalRequest)+ self.log = String(text.suffix(60000))+ } else {+ self.activity = "Download of " + game.title + " stopped. Download again to resume it."+ }+ self.refreshLibrary()+ }+ }+ try p.run()+ NSApp.dockTile.badgeLabel = String(downloadTasks.count)+ activity = "Downloading " + game.title + "…"+ } catch {+ downloadTasks.removeValue(forKey: game.id); downloads.removeValue(forKey: game.id)+ libraryIssue = "Could not start the download: " + error.localizedDescription+ }+ }+ func pauseAllDownloads() {+ stoppingDownloads.formUnion(downloadTasks.keys)+ for task in downloadTasks.values { task.terminate() }+ }+ func stopDownload(_ game: InstalledGame) {+ guard let task = downloadTasks[game.id] else { return }+ stoppingDownloads.insert(game.id); task.terminate()+ }+ private func readProgress(_ id: String, _ url: URL) {+ guard downloadTasks[id] != nil, let handle = try? FileHandle(forReadingFrom: url) else { return }+ defer { try? handle.close() }+ let size = (try? handle.seekToEnd()) ?? 0+ try? handle.seek(toOffset: size > 2048 ? size - 2048 : 0)+ let text = String(decoding: handle.readDataToEndOfFile(), as: UTF8.self)+ if let line = text.split(separator: "\n").last(where: { $0.hasPrefix(" ") }) {+ downloads[id] = line.trimmingCharacters(in: .whitespaces)+ }+ }+ func cancelSignIn() { signInTask?.terminate() }+ func xboxSignIn(market: String) {+ guard !accountBusy else { return }+ accountBusy = true; accountMessage = "Finish signing in on the Microsoft page that opened…"+ do {+ let (p, url) = try task(["xbox", "login"], logName: "xbox-account")+ signInTask = p+ p.terminationHandler = { [weak self] process in+ DispatchQueue.main.async {+ guard let self else { return }+ self.accountBusy = false; self.signInTask = nil+ // 143: xbox.sh closed the sign-in window after Cancel and exited itself.+ if process.terminationReason == .uncaughtSignal || process.terminationStatus == 143 { self.accountMessage = "Sign-in cancelled."; return }+ if process.terminationStatus == 0 { self.syncAccount(.xbox, input: ["market": market]) }+ else {+ let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""+ self.accountMessage = text.contains("not completed") ? "Sign-in was not completed." : "Sign-in did not finish. Open Diagnostics in Library for details."+ self.log = String(text.suffix(60000))+ }+ }+ }+ try p.run()+ } catch { accountBusy = false; accountMessage = error.localizedDescription }+ }}struct AccountsView: View {@@ -130,6 +241,8 @@ struct AccountsView: View {@State private var userID = ""@State private var userTask: Process?@State private var usersMessage = ""+ @AppStorage("soju.store.region") private var market = "US"+ @State private var confirmDisconnect = falseprivate func summary(_ platform: Launcher) -> AccountSummary? { model.accountSummaries.first { $0.platform == platform } }var body: some View {ScrollView {@@ -175,6 +288,39 @@ struct AccountsView: View {}}.padding(12)}+ GroupBox {+ VStack(alignment: .leading, spacing: 12) {+ accountHeader(.xbox)+ Text("Sign in with your Microsoft account on Microsoft's own page. Soju imports the games you own and your PC Game Pass games, downloads them and starts them. Xbox PC support is experimental: not every game works.")+ .font(.callout).foregroundStyle(.secondary)+ Text("Your sign-in stays in the macOS Keychain; macOS may ask once to allow access. Some newer games can't be downloaded yet.")+ .font(.caption).foregroundStyle(.secondary)+ HStack {+ Picker("Store region", selection: $market) {+ Text("US · USD").tag("US"); Text("Korea · KRW").tag("KR"); Text("UK · GBP").tag("GB")+ Text("Germany · EUR").tag("DE"); Text("Japan · JPY").tag("JP")+ }.frame(width: 230)+ .help("Used for the Xbox library and Discover. A connected library syncs again when you change it.")+ .onChange(of: market) {+ if summary(.xbox) != nil && !model.accountBusy { model.syncAccount(.xbox, input: ["market": market]) }+ }+ if !model.installed.contains(.xbox) {+ Button("Set Up Xbox PC…") { model.requestedPage = "platforms" }.buttonStyle(.link)+ }+ Spacer()+ if model.signInTask != nil {+ Button("Cancel") { model.cancelSignIn() }+ }+ if summary(.xbox) != nil {+ Button("Sync Xbox Library") { model.syncAccount(.xbox, input: ["market": market]) }+ .buttonStyle(.borderedProminent).disabled(model.accountBusy || !model.installed.contains(.xbox))+ } else {+ Button("Sign In to Microsoft…") { model.xboxSignIn(market: market) }+ .buttonStyle(.borderedProminent).disabled(model.accountBusy || !model.installed.contains(.xbox))+ }+ }+ }.padding(12)+ }HStack(spacing: 12) {if model.accountBusy { ProgressView().controlSize(.small) }Text(model.accountMessage).font(.callout).textSelection(.enabled)@@ -189,10 +335,17 @@ struct AccountsView: View {}}.padding(12).frame(maxWidth: .infinity, alignment: .leading)}- Text("Imports are snapshots stored on this Mac. Sync again after purchases or account changes. Disconnect removes the import and Soju’s saved Steam web session, without removing installed games.")+ Text("Imports are snapshots stored on this Mac. Sync again after purchases or account changes. Disconnect removes the import (and Soju’s saved Steam web session or Microsoft sign-in), without removing installed games.").font(.caption).foregroundStyle(.secondary)}.padding(28)}.onAppear(perform: loadUsers)+ .confirmationDialog("Sign out of Xbox PC?", isPresented: $confirmDisconnect) {+ Button("Sign Out", role: .destructive) { model.forgetAccount(.xbox) }+ Button("Cancel", role: .cancel) {}+ } message: {+ Text(model.downloadTasks.isEmpty ? "Your imported Xbox library is removed. Downloaded games stay on this Mac."+ : "Running downloads are paused. Your imported Xbox library is removed; downloaded games stay on this Mac.")+ }.sheet(isPresented: $showSteamLogin) {SteamLoginView(root: model.root, completion: { value inshowSteamLogin = false@@ -206,7 +359,9 @@ struct AccountsView: View {if let value = summary(platform) {Text(verbatim: "\(value.label) · \(value.count) games · \(value.updatedAt.prefix(10))").font(.caption).foregroundStyle(.secondary)Spacer()- Button("Disconnect") { model.forgetAccount(platform) }.disabled(model.accountBusy)+ Button(platform == .xbox ? "Sign Out…" : "Disconnect") {+ if platform == .xbox { confirmDisconnect = true } else { model.forgetAccount(platform) }+ }.disabled(model.accountBusy)} else { Spacer(); Text("Not connected").font(.caption).foregroundStyle(.secondary) }}}diff --git a/app/Discover.swift b/app/Discover.swiftindex 7257a9eefa7..13d37f0c974 100644--- a/app/Discover.swift+++ b/app/Discover.swift@@ -55,7 +55,7 @@ struct DiscoverView: View {@EnvironmentObject var model: SojuModel@StateObject private var store = DiscoverModel()@State private var query = ""- @State private var country = "US"+ @AppStorage("soju.store.region") private var country = "US"@State private var platform = "all"@State private var purchaseLinks = PurchaseLinks.emptyprivate var shown: [StoreItem] { store.results.filter { platform == "all" || $0.platform.rawValue == platform } }@@ -64,7 +64,7 @@ struct DiscoverView: View {HStack {VStack(alignment: .leading, spacing: 7) {Text("Find your next game").font(.system(size: 30, weight: .bold, design: .rounded))- Text("Search Steam and GOG. Compare games and prices.").font(.callout).foregroundStyle(.secondary)+ Text("Search Steam, GOG and the Microsoft Store. Compare games and prices.").font(.callout).foregroundStyle(.secondary)}Spacer()}@@ -80,8 +80,8 @@ struct DiscoverView: View {}HStack {Picker("Store", selection: $platform) {- Text("Steam & GOG").tag("all"); Text("Steam").tag("steam"); Text("GOG").tag("gog")- }.pickerStyle(.segmented).frame(width: 270).accessibilityLabel("Store results filter")+ Text("All stores").tag("all"); Text("Steam").tag("steam"); Text("GOG").tag("gog"); Text("Microsoft Store").tag("xbox")+ }.pickerStyle(.segmented).frame(width: 380).accessibilityLabel("Store results filter")Spacer()if store.searching {ProgressView().controlSize(.small)@@ -101,7 +101,7 @@ struct DiscoverView: View {Image(systemName: "sparkle.magnifyingglass").font(.system(size: 42, weight: .light))Text(store.searching ? "Searching the stores…" : store.searchedQuery.isEmpty ? "What would you like to play?" : "No matching listings").font(.title3.bold())- Text("Purchases and downloads stay with the store.").foregroundStyle(.secondary)+ Text("Purchases happen in each store.").foregroundStyle(.secondary)}.frame(maxWidth: .infinity, maxHeight: .infinity)} else {ScrollView {@@ -130,18 +130,32 @@ struct DiscoverView: View {} placeholder: { Image(systemName: item.platform.symbol).font(.largeTitle).foregroundStyle(.secondary) }}.frame(height: 120).clipShape(RoundedRectangle(cornerRadius: 9))HStack {- Text(item.platform == .steam ? "STEAM" : "GOG").font(.caption.bold()).foregroundStyle(.secondary)+ Text(item.platform == .steam ? "STEAM" : item.platform == .xbox ? "MICROSOFT STORE" : "GOG").font(.caption.bold()).foregroundStyle(.secondary)Spacer()if let owned { Text(owned.isInstalled ? "Installed" : "In your library").font(.caption).foregroundStyle(.green) }}Text(item.title).font(.headline).lineLimit(2).frame(height: 38, alignment: .topLeading)HStack {- Text(item.price).font(.system(size: 17, weight: .semibold))+ if item.price == "View price in store" {+ Text("Price shown in the store").font(.callout).foregroundStyle(.secondary)+ } else {+ Text(item.price).font(.system(size: 17, weight: .semibold))+ }Spacer()if item.mac { Text("macOS listed").font(.caption).foregroundStyle(.secondary) }}HStack {- if let owned {+ if let owned, owned.platform == .xbox {+ if model.downloads[owned.id] != nil {+ Button("Pause Download") { model.stopDownload(owned) }+ } else if owned.downloadBlocked {+ Text("Can't be downloaded yet").font(.caption).foregroundStyle(.secondary).help(owned.issue ?? "")+ } else {+ Button(owned.isInstalled ? "Play" : owned.isPartialDownload ? "Resume Download" : "Download") {+ if owned.isInstalled { model.play(owned) } else { model.installOwnedGame(owned) }+ }.disabled(model.busy)+ }+ } else if let owned {Button(owned.isInstalled ? "Play" : owned.platform == .steam ? "Install in Steam" : "Open Galaxy") {if owned.isInstalled { model.play(owned) } else { model.installOwnedGame(owned) }}.disabled(model.busy)diff --git a/app/Library.swift b/app/Library.swiftindex d3b9df56828..3182245327c 100644--- a/app/Library.swift+++ b/app/Library.swift@@ -9,9 +9,15 @@ struct InstalledGame: Decodable, Identifiable {let artwork: String?let issue: String?let owned: Bool?- var isInstalled: Bool { !installPath.isEmpty }+ let downloaded: Bool?+ let format: String?+ /// Xbox PC: a folder with an unfinished download is not installed yet.+ var isInstalled: Bool { platform == .xbox ? downloaded == true : !installPath.isEmpty }+ var isPartialDownload: Bool { platform == .xbox && !installPath.isEmpty && downloaded != true }+ /// Owned but not downloadable (for example MSIXVC2 packages).+ var downloadBlocked: Bool { platform == .xbox && !isInstalled && !isPartialDownload && issue != nil }enum CodingKeys: String, CodingKey {- case id, platform, title, artwork, issue, owned+ case id, platform, title, artwork, issue, owned, downloaded, formatcase installPath = "install_path"}}@@ -112,8 +118,15 @@ extension SojuModel {self.gameLaunches.removeValue(forKey: game.id)self.launchingGames.remove(game.id)}- if process.terminationStatus != 0 {- self.libraryIssue = "Could not launch " + game.title + ". Use Diagnose or open " + game.platform.title + " to check its installation and login."+ if self.stoppingGames.remove(game.id) != nil {+ self.activity = game.title + " stopped."+ } else if process.terminationStatus != 0 {+ let text = (try? String(contentsOf: url, encoding: .utf8)) ?? ""+ let reason = text.split(separator: "\n").last(where: { $0.hasPrefix("soju: ") }).map { String($0.dropFirst(6)) }+ self.issueTitle = "Couldn't start " + game.title+ self.libraryIssue = reason ?? (game.platform.opensAWindow+ ? "Use Diagnose or open " + game.platform.title + " to check its installation and login."+ : "Use Diagnose to check the game and your Xbox sign-in.")if !self.busy {self.failed = true; self.activity = game.title + " needs attention."if let data = try? Data(contentsOf: url) { self.log = String(decoding: data.suffix(60000), as: UTF8.self) }@@ -125,16 +138,25 @@ extension SojuModel {failed = falsepreferences.opened[game.id] = Date(); savePreferences()activity = "Opening " + game.title + " through " + game.platform.title + "…"- // Clients may stay alive for hours: this is a launch request, not a game-running signal.- DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self, weak p] in+ // An Xbox game runs inside this process, so it counts as running until it exits.+ // Other clients may stay alive for hours: there it is only a launch request.+ if game.platform != .xbox { DispatchQueue.main.asyncAfter(deadline: .now() + 8) { [weak self, weak p] inguard let self, let p, self.gameLaunches[game.id] === p else { return }self.launchingGames.remove(game.id)- }+ } }} catch {launchingGames.remove(game.id); gameLaunches.removeValue(forKey: game.id)libraryIssue = "Could not start the game: " + error.localizedDescription}}+ /// An Xbox game runs inside Soju's task: SIGTERM reaches xbox-run.py, which asks the+ /// backend to close the game and copy its saves back (or stops first-launch setup).+ func stopGame(_ game: InstalledGame) {+ guard game.platform == .xbox, let p = gameLaunches[game.id], p.isRunning, !stoppingGames.contains(game.id) else { return }+ stoppingGames.insert(game.id)+ activity = "Stopping " + game.title + " and saving…"+ p.terminate()+ }}private extension Launcher {@@ -144,6 +166,7 @@ private extension Launcher {case .steam: return Color(red: 0.36, green: 0.67, blue: 0.77)case .epic: return Color(red: 0.82, green: 0.64, blue: 0.40)case .gog: return Color(red: 0.70, green: 0.47, blue: 0.87)+ case .xbox: return Color(red: 0.24, green: 0.66, blue: 0.33)}}}@@ -189,13 +212,16 @@ struct LibraryView: View {.background(Color(nsColor: .windowBackgroundColor)).sheet(item: $selected) { game in detail(game) }.sheet(isPresented: $showDiagnostics) { diagnostics }- .alert("Game needs attention", isPresented: Binding(get: { model.libraryIssue != nil }, set: { if !$0 { model.libraryIssue = nil } })) {- Button("View details") { model.libraryIssue = nil; showDiagnostics = true }+ .alert(model.issueTitle, isPresented: Binding(get: { model.libraryIssue != nil }, set: { if !$0 { model.libraryIssue = nil; model.issueTitle = "Game needs attention" } })) {+ Button("Show Log") { model.libraryIssue = nil; showDiagnostics = true }Button("OK", role: .cancel) { model.libraryIssue = nil }} message: { Text(model.libraryIssue ?? "") }.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ inmodel.refresh(); model.refreshLibrary()}+ .onChange(of: model.requestedPage) {+ if let next = model.requestedPage { selected = nil; page = next; model.requestedPage = nil }+ }}private var sidebar: some View {@@ -253,7 +279,7 @@ struct LibraryView: View {VStack(alignment: .leading, spacing: 7) {Text(page == "favorites" ? "Your favorites" : "Your library").font(.system(size: 30, weight: .bold, design: .rounded))- Text("Pick a game. Play it, or install it through its store.").font(.system(size: 13)).foregroundStyle(.secondary)+ Text("Pick a game. Play it, or install it from its store.").font(.system(size: 13)).foregroundStyle(.secondary)}Spacer()Button {@@ -294,7 +320,7 @@ struct LibraryView: View {.font(.system(size: 44, weight: .light)).foregroundStyle(green)Text(model.scanning ? "Finding your games…" : model.games.isEmpty ? "Your library starts here" : "No games to show").font(.system(size: 21, weight: .semibold))- Text(model.games.isEmpty ? "Connect a Steam or GOG library in Accounts,\nor install a game through one of your platforms." : page == "favorites" ? "Star a game in your library to keep it here." : "Try another search or platform filter.")+ Text(model.games.isEmpty ? "Connect a Steam, GOG or Xbox library in Accounts,\nor install a game through one of your platforms." : page == "favorites" ? "Star a game in your library to keep it here." : "Try another search or platform filter.").font(.system(size: 12)).foregroundStyle(.secondary).multilineTextAlignment(.center)Button(model.games.isEmpty ? "Connect accounts" : "Show all games") {if model.games.isEmpty { page = "accounts" }@@ -336,18 +362,37 @@ struct LibraryView: View {}Text(game.title).font(.system(size: 14, weight: .semibold)).lineLimit(2).frame(height: 36, alignment: .topLeading).frame(maxWidth: .infinity, alignment: .leading)+ if let fraction = downloadFraction(game) {+ ProgressView(value: fraction).controlSize(.small)+ .accessibilityLabel("Download progress for " + game.title)+ .accessibilityValue(model.downloads[game.id] ?? "")+ }HStack {- Text(!game.isInstalled ? "Not installed" : issue == nil ? "Installed" : "Needs attention").font(.system(size: 10))- .foregroundStyle(issue == nil ? Color.secondary : Color.orange)+ Text(status(game, issue: issue)).font(.system(size: 10)).lineLimit(1)+ .foregroundStyle(issue == nil || game.isPartialDownload ? Color.secondary : Color.orange)Spacer()- Button {- if !game.isInstalled { model.installOwnedGame(game) }- else if issue == nil { model.play(game) } else { selected = game }- } label: {- Label(!game.isInstalled ? (game.platform == .steam ? "Install" : "Galaxy") : model.launchingGames.contains(game.id) ? "Starting…" : issue == nil ? "Play" : "Details", systemImage: !game.isInstalled ? "arrow.down.circle" : issue == nil ? "play.fill" : "exclamationmark.circle")- }.buttonStyle(.borderedProminent).tint(green).controlSize(.small)- .disabled(model.busy || model.launchingGames.contains(game.id))- .accessibilityLabel((!game.isInstalled ? "Install " : issue == nil ? "Play " : "Check ") + game.title)+ if model.downloads[game.id] != nil {+ Button { model.stopDownload(game) } label: { Label("Pause", systemImage: "pause.fill") }+ .controlSize(.small).help("Pause the download. Download again later to continue.")+ .accessibilityLabel("Pause downloading " + game.title)+ } else if game.platform == .xbox && model.launchingGames.contains(game.id) {+ Button { model.stopGame(game) } label: { Label(model.stoppingGames.contains(game.id) ? "Stopping…" : "Stop", systemImage: "stop.fill") }+ .controlSize(.small).disabled(model.stoppingGames.contains(game.id))+ .help("Close the game. Soju copies its saves back first.")+ .accessibilityLabel("Stop " + game.title)+ } else if game.downloadBlocked {+ Button { selected = game } label: { Label("Details", systemImage: "info.circle") }+ .controlSize(.small).accessibilityLabel("Why " + game.title + " cannot be downloaded")+ } else {+ Button {+ if !game.isInstalled { model.installOwnedGame(game) }+ else if issue == nil { model.play(game) } else { selected = game }+ } label: {+ Label(!game.isInstalled ? (game.isPartialDownload ? "Resume" : game.platform.ownedActionTitle) : model.launchingGames.contains(game.id) ? (game.platform == .xbox ? "Running" : "Starting…") : issue == nil ? "Play" : "Details", systemImage: !game.isInstalled ? "arrow.down.circle" : issue == nil ? "play.fill" : "exclamationmark.circle")+ }.buttonStyle(.borderedProminent).tint(green).controlSize(.small)+ .disabled(model.busy || model.launchingGames.contains(game.id))+ .accessibilityLabel((!game.isInstalled ? (game.isPartialDownload ? "Resume downloading " : game.platform.ownedActionTitle + " ") : issue == nil ? "Play " : "Check ") + game.title)+ }}}.padding(14)}.background(Color(nsColor: .controlBackgroundColor), in: RoundedRectangle(cornerRadius: 14))@@ -356,11 +401,32 @@ struct LibraryView: View {.contextMenu {Button("Show details") { selected = game }Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled)- Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)+ if game.platform.opensAWindow {+ Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)+ }Button("Diagnose") { diagnose(game) }.disabled(model.busy)}}+ /// "42% · 3.1 GB / 7.4 GB · 48 MB/s" -> 0.42; nil while preparing or when not downloading.+ private func downloadFraction(_ game: InstalledGame) -> Double? {+ guard let progress = model.downloads[game.id], let head = progress.split(separator: "%").first,+ head.count < progress.count, let value = Double(head) else { return nil }+ return min(max(value / 100, 0), 1)+ }+ private func status(_ game: InstalledGame, issue: String?) -> String {+ // The bar shows the percentage; the caption keeps the size and speed.+ if let progress = model.downloads[game.id] {+ let parts = progress.components(separatedBy: " · ")+ return parts.count > 1 ? parts.dropFirst().joined(separator: " · ") : progress+ }+ if game.platform == .xbox {+ if game.isPartialDownload { return "Paused" }+ if game.downloadBlocked { return "Not supported" }+ }+ return !game.isInstalled ? "Not installed" : issue == nil ? "Installed" : "Needs attention"+ }+private func diagnose(_ game: InstalledGame) {selected = nilmodel.run(["game-doctor", game.id], title: "Checking " + game.title + "…")@@ -374,12 +440,15 @@ struct LibraryView: View {Text(game.platform.title).font(.system(size: 11, weight: .semibold)).foregroundStyle(game.platform.accent)Text(game.title).font(.system(size: 24, weight: .bold, design: .rounded))Label(game.isInstalled ? "Installed on this Mac" : "Owned · not installed", systemImage: game.isInstalled ? "internaldrive" : "cloud").font(.system(size: 12)).foregroundStyle(.secondary)- Text("Opens through " + game.platform.title + ". You may need to sign in or finish an update in the launcher.")+ Text(game.platform == .xbox ? "Downloaded from the Microsoft Store. Xbox PC support is experimental: not every game works. The first launch may download about 600 MB of Xbox runtime files and take a few minutes to set up." : "Opens through " + game.platform.title + ". You may need to sign in or finish an update in the launcher.").font(.system(size: 12)).foregroundStyle(.secondary)+ if game.downloadBlocked, let issue = game.issue {+ Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)+ }if let issue = model.launchIssue(for: game) {Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)}- Text(game.isInstalled ? "Installation detected. Compatibility varies by game and Mac." : "This game is in your imported library. Open its launcher to install it; compatibility varies by game.")+ Text(game.platform == .xbox ? (game.isInstalled ? "Files are in " + game.installPath + ". Saves sync with your Xbox account when the game exits." : "This game is in your Xbox library. Download it to play; compatibility varies by game.") : game.isInstalled ? "Installation detected. Compatibility varies by game and Mac." : "This game is in your imported library. Open its launcher to install it; compatibility varies by game.").font(.system(size: 11)).foregroundStyle(.secondary)Spacer()}@@ -387,7 +456,9 @@ struct LibraryView: View {HStack {Button("Show files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }.disabled(!game.isInstalled)Button("Diagnose") { diagnose(game) }.disabled(model.busy)- Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)+ if game.platform.opensAWindow {+ Button("Open " + game.platform.title) { model.launch(game.platform) }.disabled(model.busy)+ }Spacer()}Divider()@@ -395,15 +466,28 @@ struct LibraryView: View {Button("Platforms") { selected = nil; page = "platforms" }Spacer()Button("Close") { selected = nil }.keyboardShortcut(.cancelAction)- Button(game.isInstalled ? "Play" : game.platform == .steam ? "Install in Steam" : "Open Galaxy") {- selected = nil- if game.isInstalled { model.play(game) } else { model.installOwnedGame(game) }+ if model.downloads[game.id] != nil {+ Button("Pause Download") { model.stopDownload(game) }.keyboardShortcut(.defaultAction)+ } else if game.platform == .xbox && model.launchingGames.contains(game.id) {+ Button(model.stoppingGames.contains(game.id) ? "Stopping…" : "Stop Game") { model.stopGame(game) }+ .keyboardShortcut(.defaultAction).disabled(model.stoppingGames.contains(game.id))+ } else if !game.downloadBlocked {+ Button(primaryTitle(game)) {+ selected = nil+ if game.isInstalled { model.play(game) } else { model.installOwnedGame(game) }+ }+ .buttonStyle(.borderedProminent).tint(green).keyboardShortcut(.defaultAction)+ .disabled(model.busy || model.launchIssue(for: game) != nil || model.launchingGames.contains(game.id))}- .buttonStyle(.borderedProminent).tint(green)- .disabled(model.busy || model.launchIssue(for: game) != nil || model.launchingGames.contains(game.id))}}.padding(28).frame(width: 640)}+ private func primaryTitle(_ game: InstalledGame) -> String {+ if game.platform == .xbox {+ return game.isInstalled ? "Play" : game.isPartialDownload ? "Resume Download" : "Download"+ }+ return game.isInstalled ? "Play" : game.platform == .steam ? "Install in Steam" : "Open Galaxy"+ }private var diagnostics: some View {VStack(alignment: .leading, spacing: 16) {HStack {diff --git a/app/PurchaseLinks.swift b/app/PurchaseLinks.swiftindex 507dc4fa674..41a37379843 100644--- a/app/PurchaseLinks.swift+++ b/app/PurchaseLinks.swift@@ -35,7 +35,7 @@ struct PurchaseLinks: Decodable {func resolve(_ destination: String) -> Route? {guard let direct = Self.safeURL(destination, hosts: [- "store.steampowered.com", "www.gog.com", "store.epicgames.com", "us.shop.battle.net"+ "store.steampowered.com", "www.gog.com", "store.epicgames.com", "us.shop.battle.net", "www.xbox.com"]) else { return nil }if schema == 1, enabled, direct.host == "www.gog.com",let entry = links.first(where: { $0.destination == destination }),diff --git a/app/Soju.swift b/app/Soju.swiftindex b9e7eca67d3..af325799be8 100644--- a/app/Soju.swift+++ b/app/Soju.swift@@ -2,7 +2,7 @@ import SwiftUIimport AppKitenum Launcher: String, CaseIterable, Identifiable {- case battlenet, steam, epic, gog+ case battlenet, steam, epic, gog, xboxvar id: String { rawValue }var title: String {switch self {@@ -10,10 +10,35 @@ enum Launcher: String, CaseIterable, Identifiable {case .steam: return "Steam"case .epic: return "Epic Games"case .gog: return "GOG GALAXY"+ case .xbox: return "Xbox PC"}}var detail: String {- self == .steam ? "Windows library · D3D11 with DXMT" : "Windows library · Apple D3DMetal"+ switch self {+ case .steam: return "Windows library · D3D11 with DXMT"+ case .xbox: return "Microsoft Store library · experimental"+ default: return "Windows library · Apple D3DMetal"+ }+ }+ /// Xbox PC has no Windows client to open; sign-in and downloads run in Soju.+ var opensAWindow: Bool { self != .xbox }+ var accountName: String {+ switch self {+ case .steam: return "Steam account"+ case .gog: return "GOG account"+ case .epic: return "Epic account"+ case .battlenet: return "Blizzard account"+ case .xbox: return "Microsoft account"+ }+ }+ /// Action for an owned game that is not on this Mac yet.+ var ownedActionTitle: String {+ switch self {+ case .steam: return "Install"+ case .gog: return "Galaxy"+ case .xbox: return "Download"+ default: return "Open"+ }}var symbol: String {switch self {@@ -21,6 +46,7 @@ enum Launcher: String, CaseIterable, Identifiable {case .steam: return "gamecontroller.fill"case .epic: return "shield.lefthalf.filled"case .gog: return "square.grid.2x2.fill"+ case .xbox: return "xbox.logo"}}var executable: String {@@ -29,6 +55,7 @@ enum Launcher: String, CaseIterable, Identifiable {case .steam: return "steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe"case .epic: return "epic-bottle/drive_c/Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe"case .gog: return "gog-bottle/drive_c/Program Files/GOG Galaxy/GalaxyClient.exe"+ case .xbox: return "xbox-bottle/drive_c/ProgramData/Soju/xbox.json"}}}@@ -42,6 +69,7 @@ enum Launcher: String, CaseIterable, Identifiable {@Published var scanning = false@Published var scanWarnings: [String] = []@Published var launchingGames: Set<String> = []+ @Published var stoppingGames: Set<String> = []@Published var libraryIssue: String?@Published var preferences = LibraryPreferences.load()var gameLaunches: [String: Process] = [:]@@ -53,6 +81,13 @@ enum Launcher: String, CaseIterable, Identifiable {@Published var failed = false@Published var selection: Set<Launcher> = [.battlenet]@Published var launching: Set<Launcher> = []+ @Published var requestedPage: String?+ @Published var downloads: [String: String] = [:]+ var downloadTasks: [String: Process] = [:]+ var downloadTimers: [String: Timer] = [:]+ var stoppingDownloads: Set<String> = []+ @Published var signInTask: Process?+ @Published var issueTitle = "Game needs attention"let base = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".battlenet-macos")let root = Bundle.main.resourceURL!.appendingPathComponent("soju")private var operation: Process?@@ -71,9 +106,12 @@ enum Launcher: String, CaseIterable, Identifiable {func task(_ args: [String], logName: String) throws -> (Process, URL) {let dir = base.appendingPathComponent("logs")- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ // Logs can name games, paths and backend errors: keep them to this user.+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])+ try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: dir.path)let url = dir.appendingPathComponent(logName + ".log")try Data().write(to: url, options: .atomic)+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)let output = try FileHandle(forWritingTo: url)let p = Process()p.executableURL = URL(fileURLWithPath: "/bin/bash")@@ -139,6 +177,7 @@ enum Launcher: String, CaseIterable, Identifiable {}func launch(_ launcher: Launcher) {+ guard launcher.opensAWindow else { requestedPage = "accounts"; return }guard !launching.contains(launcher), !busy else { return }do {let (p, url) = try task(["launch", launcher.rawValue], logName: "desktop-" + launcher.rawValue)@@ -183,7 +222,8 @@ struct PlatformsView: View {@EnvironmentObject var model: SojuModel@Environment(\.colorScheme) private var schemeprivate var green: Color { scheme == .dark ? Color(red: 0.42, green: 0.83, blue: 0.67) : Color(red: 0.12, green: 0.34, blue: 0.28) }- private let columns = [GridItem(.flexible(), spacing: 16), GridItem(.flexible(), spacing: 16)]+ // Three columns keep five platforms in two rows, so the log stays on screen.+ private let columns = Array(repeating: GridItem(.flexible(), spacing: 14, alignment: .top), count: 3)var body: some View {VStack(alignment: .leading, spacing: 20) {@@ -196,7 +236,7 @@ struct PlatformsView: View {.padding(.horizontal, 9).padding(.vertical, 5).background(green.opacity(0.09), in: Capsule()).foregroundStyle(green)}- Text("Install and manage your official Windows launchers.").foregroundStyle(.secondary)+ Text("Install and manage your official Windows launchers and Xbox PC downloads.").foregroundStyle(.secondary)}Spacer()Menu {@@ -243,7 +283,7 @@ struct PlatformsView: View {}}.padding(14).background(Color.primary.opacity(0.035), in: RoundedRectangle(cornerRadius: 12))HStack {- Text("Accounts, purchases and updates stay with each official launcher.")+ Text("Accounts, purchases and updates stay with each official store.")Spacer()Text("v" + model.version)}.font(.system(size: 10)).foregroundStyle(.secondary)@@ -272,10 +312,13 @@ struct PlatformsView: View {}Text(launcher.detail).font(.system(size: 11)).foregroundStyle(.secondary)HStack {- Text(launcher == .steam ? "Steam account" : launcher == .gog ? "GOG account" : launcher == .epic ? "Epic account" : "Blizzard account")+ Text(launcher.accountName).font(.system(size: 10)).foregroundStyle(.tertiary)Spacer()- if installed {+ if installed && !launcher.opensAWindow {+ Button(model.accountSummaries.contains { $0.platform == launcher } ? "Manage…" : "Sign In…") { model.requestedPage = "accounts" }+ .accessibilityLabel("Open Accounts for " + launcher.title)+ } else if installed {Button(model.launching.contains(launcher) ? "Running" : "Open") { model.launch(launcher) }.disabled(model.busy || model.launching.contains(launcher)).accessibilityLabel("Open " + launcher.title)@@ -293,7 +336,18 @@ struct PlatformsView: View {final class SojuDelegate: NSObject, NSApplicationDelegate {var isBusy: (() -> Bool)?+ var downloads: (() -> Int)?+ var pauseDownloads: (() -> Void)?func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ if let count = downloads?(), count > 0 {+ let alert = NSAlert()+ alert.messageText = count == 1 ? "A download is in progress" : String(count) + " downloads are in progress"+ alert.informativeText = "Quitting pauses them. Download again later to continue where they stopped."+ alert.addButton(withTitle: "Pause and Quit")+ alert.addButton(withTitle: "Cancel")+ guard alert.runModal() == .alertFirstButtonReturn else { return .terminateCancel }+ pauseDownloads?()+ }if isBusy?() == true {let alert = NSAlert()alert.messageText = "An operation is still running"@@ -312,6 +366,8 @@ final class SojuDelegate: NSObject, NSApplicationDelegate {Window("Soju", id: "main") {LibraryView().environmentObject(model).onAppear {delegate.isBusy = { model.busy }+ delegate.downloads = { model.downloadTasks.count }+ delegate.pauseDownloads = { model.pauseAllDownloads() }NSApp.setActivationPolicy(.regular)NSApp.activate(ignoringOtherApps: true)}diff --git a/docs/ACCOUNTS.md b/docs/ACCOUNTS.mdindex f0bc92ff28c..e6dbcf13a2f 100644--- a/docs/ACCOUNTS.md+++ b/docs/ACCOUNTS.md@@ -46,13 +46,24 @@ It does not read passwords, authentication tokens, activation keys or product auGalaxy itself contacts GOG to refresh its account library; Soju imports the snapshot already saved on this Mac.If the database is busy, incomplete or has an unsupported schema, the previous import remains intact.+## Connect Xbox PC (Microsoft Store)++1. In **Platforms**, install **Xbox PC**. This builds the Xodus backend on your Mac (a few minutes the first time).+2. In **Accounts**, choose a store region and **Sign in to Microsoft**. Microsoft's own sign-in page opens in a separate window.+3. After sign-in, Soju imports the games you own and your PC Game Pass games. Use **Sync Xbox library** later to refresh.++Soju saves product IDs, titles, package format, box art and the Xbox gamertag (shown as the account label). It does not save the account e-mail. The sign-in itself+stays in the macOS Keychain ("Xodus Service"); **Sign Out…** signs out and removes the import, even when the Xbox PC backend was removed.+Owned Xbox games show **Download**. Downloads run beside other work, can be stopped and resume later.+Games packaged as MSIXVC2 cannot be downloaded yet. **Play** starts a downloaded game on Soju's engine (experimental; needs the CX engine and Apple GPTK). Quitting the game copies its saves back into the game folder.+## Use your library**All games**, **Installed** and **Not installed** filters distinguish local installations from imported ownership.When a game is both installed and imported, the current installation record wins, so it appears once.An imported entry alone is never treated as proof that a game is installed or runnable.-Steam's **Install** button opens the official Steam installation flow.+Steam's **Install** button opens the official Steam installation flow. Xbox PC's **Download** button downloads in Soju.GOG's **Galaxy** button opens Galaxy; choose the game there to install it.Set up the corresponding platform first if it is not installed. Return to Soju and refresh after installation.The ordinary Play action always rechecks the local installation record.diff --git a/install.sh b/install.shindex 180c7f57f42..c92ac9af294 100644--- a/install.sh+++ b/install.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Soju one-line installer: Battle.net, Steam, Epic and GOG launchers on Apple Silicon, no CrossOver.+# Soju one-line installer: Battle.net, Steam, Epic and GOG launchers (plus Xbox PC downloads) on Apple Silicon, no CrossOver.# curl -fsSL soju.snack-wrap.com/install.sh | bash# curl -fsSL https://soju.snack-wrap.com/install.sh | SOJU_PLATFORMS=battlenet,epic,gog bash (non-interactive selection)#@@ -66,7 +66,7 @@ latest_release(){}# ---------- 1. Choose launchers before any download -----------ALL="battlenet steam epic gog"+ALL="battlenet steam epic gog xbox"if [ -n "${SOJU_PLATFORMS:-}" ]; thenPLATFORMS="$(echo "$SOJU_PLATFORMS" | tr ',' ' ')"else@@ -76,6 +76,8 @@ else2) Steam (Windows client on private Wine 11, D3D11 games via DXMT)3) Epic Games Launcher4) GOG GALAXY+ 5) Xbox PC / Microsoft Store (Xodus backend, experimental: sign-in, library,+ downloads and play on the CX engine; builds from source, a few minutes)EOTread -r -p " Your choice [1]: " choice < "$TTY" || choice=1[ -n "$choice" ] || choice=1@@ -86,6 +88,7 @@ EOT2|steam) PLATFORMS="$PLATFORMS steam" ;;3|epic) PLATFORMS="$PLATFORMS epic" ;;4|gog) PLATFORMS="$PLATFORMS gog" ;;+ 5|xbox) PLATFORMS="$PLATFORMS xbox" ;;*) echo "Unknown choice: $c"; exit 64 ;;esacdone@@ -94,12 +97,13 @@ for p in $PLATFORMS; do case " $ALL " in *" $p "*) ;; *) echo "Unknown platform:[ -n "${PLATFORMS// /}" ] || { echo "Nothing selected."; exit 64; }echo " Installing:$PLATFORMS"-NEEDS_CX=0; NEEDS_STEAM=0+NEEDS_CX=0; NEEDS_STEAM=0; NEEDS_XODUS=0for p in $PLATFORMS; do- case "$p" in steam) NEEDS_STEAM=1 ;; *) NEEDS_CX=1 ;; esac+ # Xbox PC games run on the CX engine with D3DMetal, like Battle.net/Epic/GOG.+ case "$p" in steam) NEEDS_STEAM=1 ;; xbox) NEEDS_XODUS=1; NEEDS_CX=1 ;; *) NEEDS_CX=1 ;; esacdoneif [ "${1:-}" = "--plan" ]; then- printf 'platforms=%s\ncx_engine=%s\napple_gptk=%s\nsteam_runtime=%s\n' "$PLATFORMS" "$NEEDS_CX" "$NEEDS_CX" "$NEEDS_STEAM"+ printf 'platforms=%s\ncx_engine=%s\napple_gptk=%s\nsteam_runtime=%s\nxodus_backend=%s\n' "$PLATFORMS" "$NEEDS_CX" "$NEEDS_CX" "$NEEDS_STEAM" "$NEEDS_XODUS"exit 0fi@@ -265,6 +269,9 @@ for p in $PLATFORMS; dosay "GOG GALAXY: creating the bottle + running GOG's installer"WINEPREFIX="$BASE/gog-bottle" bash "$SOJU_DIR/scripts/create-gog-bottle.sh"fi ;;+ xbox)+ say "Xbox PC: building the Xodus backend from source (Rust; a few minutes the first time)"+ bash "$SOJU_DIR/scripts/xbox.sh" install ;;esac# The client EXE does not prove its helper build completed.case "$p" in@@ -303,6 +310,7 @@ for p in $PLATFORMS; dosteam) make_app "Steam (Windows)" steam app.soju.steam ;;epic) make_app "Epic Games Launcher" epic app.soju.epic ;;gog) make_app "GOG GALAXY" gog app.soju.gog ;;+ xbox) echo " Xbox PC has no launcher app: sign in from Soju > Accounts, or run soju xbox-login" ;;esacdonediff --git a/resources/xbox-runtime.json b/resources/xbox-runtime.jsonnew file mode 100644index 00000000000..a83fd02b067--- /dev/null+++ b/resources/xbox-runtime.json@@ -0,0 +1,26 @@+{+ "version": "xbox-runtime-v1",+ "runtime": "xodus-nexus-runtime-11.0-20261022-gf4adc821",+ "license": "LGPL-2.1-or-later (Wine 11.0 + xgameruntime); sources: Nexus runtime source tarball and MACxus assets/runtime-patches",+ "macxus": {+ "url": "https://github.com/fladnaG86/MACxus/releases/download/v0.3.11-mac.12/MACxus-0.3.11-arm64.dmg",+ "size": 234969830,+ "sha256": "beb561d3d533bef2bcdb985777a1a70302941d373d32e5feed8c719bc7704ee1",+ "asar": "MACxus.app/Contents/Resources/app.asar",+ "folder": "assets/mac-runtime-dlls"+ },+ "nexus": {+ "url": "https://github.com/domsvoboda/xodus-nexus/releases/download/runtime-11.0-20261022-gf4adc821/xodus-nexus-runtime-11.0-20261022-gf4adc821-x86_64.tar.xz",+ "size": 370856848,+ "sha256": "2874f6d4f6bed83985627a5d1ed7294d9cde77fbfbc8c0da22b0eaa080116735",+ "member": "xodus-nexus-runtime-11.0-20261022-gf4adc821/files/lib/wine/x86_64-windows/libnghttp2.dll"+ },+ "dlls": {+ "xgameruntime.dll": "f46bc9eb5f51e2f3d1d4c89eaf2b96be3695ee7339930cd552740a1063d88c0f",+ "windows.web.dll": "7be54bf8e319c0100d689caeb84354e6b5b0453df33d20c4988c4888839cd580",+ "twinapi.appcore.dll": "c6e7a618f9a98fb8d110c810712a5fd2412a9813cd0591b4c320e35e0dc06026",+ "gamingtcui.dll": "918cb47fb1efab7d2fbc6d6fe67bcae25033b12433cedc129d07632f0d129167",+ "winhttp.dll": "e1aec3bc2bf9d6f0718c1ea3ebd76c1b80d441da7e275fed7575ece35115068f",+ "libnghttp2.dll": "2d8a707b7210f326df887920c6059e92eafddf9196a3c9dd7f22fe3b4308add1"+ }+}diff --git a/resources/xodus-backend.json b/resources/xodus-backend.jsonnew file mode 100644index 00000000000..f6df4db6fea--- /dev/null+++ b/resources/xodus-backend.json@@ -0,0 +1,193 @@+{+ "version": "xodus-backend-v1",+ "repository": "https://github.com/xodus-gaming/xodus.git",+ "commit": "53ea781dcd073e31d7ea68e894134e9c959bff04",+ "rust": "1.99.0",+ "cargo_lock_sha256": "2259b343e00dadc263018beb7664b12e9d58a0b73bff502ad566f5f8619ce28a",+ "deployment_target": "13.0",+ "patch_source": {+ "repository": "https://github.com/fladnaG86/MACxus",+ "commit": "0ab2972cc25a56fcde84b8a8345025f7443b5dcd",+ "base_url": "https://raw.githubusercontent.com/fladnaG86/MACxus/0ab2972cc25a56fcde84b8a8345025f7443b5dcd/assets/",+ "license": "MIT",+ "lock_version": "0.2.11 (linux-run-v44, macos-run-v2)"+ },+ "patches": [+ {+ "file": "xodus-linux-run.patch",+ "sha256": "68f260ec2c6e9264c47ed1a650868511f5412a756725d4000a865804f4712e8b"+ },+ {+ "file": "xodus-offline-mirror.patch",+ "sha256": "c865fc2559c43a5b3eb2bc841035c076eae5c42a90fe488f90514384aa916986"+ },+ {+ "file": "xodus-account-status.patch",+ "sha256": "e2a718d16957733d140891fcdd26cc8cb3db0636307e6ff6e9ffbfa41a2d393c"+ },+ {+ "file": "xodus-streaming-cache-flush.patch",+ "sha256": "4dd7a129ab9b3aac74d46f926efe26f163741d50fe2853a07f292240ab522b05"+ },+ {+ "file": "xodus-launch-chain.patch",+ "sha256": "22dfbfc5cec911091351bb2d648f4b16bd274aa276ee4524be738a357c8b219a"+ },+ {+ "file": "xodus-memfd-path.patch",+ "sha256": "905cfda813f0a434a2c13fd2db973385f0311cbec5c86bc3549737a7838f49fd"+ },+ {+ "file": "xodus-real-launch-images.patch",+ "sha256": "95fc642e3adfa50414648e40df6ee94262964f5eea0f3762a34765f56d7824b7"+ },+ {+ "file": "xodus-store-license.patch",+ "sha256": "99a89821e15ba144126515b5e8ec70b0673caf694d9295f16cd6661564b7c579"+ },+ {+ "file": "xodus-store-updates.patch",+ "sha256": "554e3849122c8cd3c64c7f5904ac06931a088bc8fb4c522ec2c55b972b72ea8e"+ },+ {+ "file": "xodus-streaming-progress.patch",+ "sha256": "b5e22d8eb595502776c4d6f2a5451403647e31754fc6358bc4f338cab72642a0"+ },+ {+ "file": "xodus-case-insensitive-paths.patch",+ "sha256": "53dbfd6f734db100fff958e4a311155cad2cb374db456f73544ad76e3799ac8d"+ },+ {+ "file": "xodus-account-profile.patch",+ "sha256": "135166ff0cf9f95af92dad6fd1c958b6c57e939fbb5b398b5a603b730541554a"+ },+ {+ "file": "xodus-subscription-login.patch",+ "sha256": "6c3f32c905039948b3ff95a0ceaba9b2a09a9417606653bce9b741c8bba43eb0"+ },+ {+ "file": "xodus-external-auth.patch",+ "sha256": "0a22d5a84d328780e6f13ac07f8e1db6359ec70139ad4262e4c1ee988973e20e"+ },+ {+ "file": "xodus-keyring-activation.patch",+ "sha256": "8c71928e0b365f4770532ef968322450f1ebab3a1199e7a10d894119c48c925e"+ },+ {+ "file": "xodus-package-selection.patch",+ "sha256": "28a2b566afdc1a572cd5ec52027fb48cc1823a25e8f304f282d9bf61e8d46463"+ },+ {+ "file": "xodus-package-metadata.patch",+ "sha256": "43fccfbb2ea2a9809e7f0b3d9e2f506213e6245d3bbd4c1c631149a67bb2d661"+ },+ {+ "file": "xodus-license-sku.patch",+ "sha256": "b7c93b6ead7120c5b2af3616e80c0dadf56326a8bc81a2526a5e1f2700f58e20"+ },+ {+ "file": "xodus-keyring-credentials.patch",+ "sha256": "8b354f95b864ffd7eadb02f0d54eb1361bb92fde14ff8696fabfea5c43d03811"+ },+ {+ "file": "xodus-library-resilience.patch",+ "sha256": "0136157efe8a1419f91243c496656c4d043422e126c40e4a552e769c53de3545"+ },+ {+ "file": "xodus-game-activity.patch",+ "sha256": "89bfd422f951515dd393eb479901ff9613441c627d139918c233a19ec21f1e06"+ },+ {+ "file": "xodus-achievements.patch",+ "sha256": "55e4b56b943f491da4c9836a5d6655417ed63ab6383576a8e0f153ec986039b0"+ },+ {+ "file": "xodus-session-recovery.patch",+ "sha256": "fa67d768214247a5955716b9691616b45330ebda504703bf372fdda2252b0831"+ },+ {+ "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": "e0e78a7be9f6a2e3cf228160c603f91f079d60cf46cd5502be7c84010c841d6f"+ },+ {+ "file": "xodus-licensing-jwe.patch",+ "sha256": "6f0087e657f225e9a770405fbb34c2317f840615742c89b62f241f1b65c590ca"+ },+ {+ "file": "xodus-hosted-signin.patch",+ "sha256": "f52b16944ca7dfc837337e0257be380467f01872706252d7c2e981db0c57a8bc"+ },+ {+ "file": "xodus-macos-launch.patch",+ "sha256": "09e4e53d90ded4bc06745d30b960a4bd2f17750b98282521b3a4a13b5b8bd613"+ },+ {+ "file": "xodus-macos-keychain-bundle.patch",+ "sha256": "9e25544e196b8077893ad5b6835ffc6acde2646408cdc55fed3fc41273727c18"+ },+ {+ "file": "xodus-xbox-jwe.patch",+ "sha256": "e77a076406bfacedfef0ee4eb8629052c21f8312ce367724610b46e3bb468cfb"+ }+ ]+}diff --git a/scripts/desktop-action.sh b/scripts/desktop-action.shindex 6c76e05f3fe..851ecdb80d6 100755--- a/scripts/desktop-action.sh+++ b/scripts/desktop-action.sh@@ -15,6 +15,9 @@ case "$ACTION" inlaunch)case "${1:-}" in battlenet|steam|epic|gog) exec bash "$ROOT/scripts/play.sh" "$1" ;;*) echo "Choose one of the four launchers."; exit 64 ;; esac ;;+ xbox)+ case "${1:-}" in login|logout|kill|status) exec bash "$ROOT/scripts/xbox.sh" "$1" ;;+ *) echo "Unknown Xbox action."; exit 64 ;; esac ;;install)export SOJU_PLATFORMS="${1:?Choose at least one launcher}"if ! xcode-select -p >/dev/null 2>&1; then@@ -43,6 +46,10 @@ case "$ACTION" inif [ -f "$BASE/steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe" ]; thenbash "$ROOT/scripts/setup-steam-games.sh" || result=1fi+ # A changed backend recipe rebuilds Xodus; an unchanged one is only checked.+ if [ -d "$BASE/xodus" ] && [ -z "${SOJU_XODUS_BIN:-}" ]; then+ python3 "$ROOT/scripts/fetch-xodus-backend.py" || result=1+ fiecho "Component update finished."exit "$result" ;;*) echo "Unknown desktop action: $ACTION"; exit 64 ;;diff --git a/scripts/doctor.sh b/scripts/doctor.shindex 43f13768de4..c8fd65ff6d2 100755--- a/scripts/doctor.sh+++ b/scripts/doctor.sh@@ -19,7 +19,7 @@ fail(){ printf ' FAIL %s\n' "$*"; nfail=$((nfail+1)); }info(){ printf ' - %s\n' "$*"; }SCOPE="${1:-installed}"-case "$SCOPE" in installed|all|steam|battlenet|d2r|epic|gog) ;; *) echo "Usage: soju doctor [steam|battlenet|d2r|epic|gog|all]"; exit 64 ;; esac+case "$SCOPE" in installed|all|steam|battlenet|d2r|epic|gog|xbox) ;; *) echo "Usage: soju doctor [steam|battlenet|d2r|epic|gog|xbox|all]"; exit 64 ;; esacNEEDS_CX=0case "$SCOPE" inall|battlenet|d2r|epic|gog) NEEDS_CX=1 ;;@@ -116,6 +116,53 @@ fi[ -f "$BASE/gog-bottle/drive_c/Program Files/GOG Galaxy/GalaxyClient.exe" ] \&& pass "GOG GALAXY bottle" || info "GOG not installed (soju gog-install)"+CHECK_XBOX=0+case "$SCOPE" in+ all|xbox) CHECK_XBOX=1 ;;+ installed) if [ -d "$BASE/xodus" ] || [ -d "$BASE/xbox-bottle" ] || [ -n "${SOJU_XODUS_BIN:-}" ]; then CHECK_XBOX=1; fi ;;+esac+XODUS_CLI="${SOJU_XODUS_BIN:-$BASE/xodus/bin/xodus-cli}"+if [ "$CHECK_XBOX" = 1 ] && [ "$SCOPE" = all ] && [ ! -e "$XODUS_CLI" ] && [ ! -d "$BASE/xbox-bottle" ]; then+ info "Xbox PC not installed (soju xbox-install)"+elif [ "$CHECK_XBOX" = 1 ]; then+ echo+ echo "Xbox PC (Xodus backend)"+ if [ -x "$XODUS_CLI" ] && XODUS_LOG=error "$XODUS_CLI" --version >/dev/null 2>&1; then+ pass "xodus-cli runs ($XODUS_CLI)"+ if XODUS_LOG=error "$XODUS_CLI" library --help >/dev/null 2>&1; then pass "library and download commands present"+ else fail "xodus-cli lacks the library command (rebuild: soju xbox-install)"; fi+ if [ -z "${SOJU_XODUS_BIN:-}" ]; then+ python3 "$ROOT/scripts/fetch-xodus-backend.py" --check \+ && pass "backend matches the pinned recipe" || warn "backend recipe changed: run soju update or soju xbox-install"+ else+ info "custom backend from SOJU_XODUS_BIN"+ fi+ else+ fail "Xodus backend not built (run: soju xbox-install)"+ fi+ [ -f "$BASE/xbox-bottle/drive_c/ProgramData/Soju/xbox.json" ] && pass "Xbox PC folder prepared" \+ || warn "Xbox PC folder missing (run: soju xbox-install)"+ # The backend says only whether an account is stored; the account name is not printed.+ if [ -x "$XODUS_CLI" ] && XODUS_LOG=error "$XODUS_CLI" account --json 2>/dev/null | grep -q '"stored":true'; then+ pass "signed in to a Microsoft account"+ else+ info "not signed in to Microsoft (Accounts > Xbox PC, or soju xbox-login)"+ fi+ if [ -f "$BASE/account-libraries/xbox.json" ]; then+ n=$(python3 -c 'import json,sys;print(len(json.load(open(sys.argv[1]))["games"]))' "$BASE/account-libraries/xbox.json" 2>/dev/null || echo "?")+ info "imported Xbox library: $n games"+ fi+ partial=0+ for d in "$BASE"/xbox-bottle/drive_c/XboxGames/*/; do+ [ -f "$d.nexus-streaming-v1.jsonl" ] && [ ! -f "$d.soju-xbox-install.json" ] && partial=$((partial+1))+ done+ [ "$partial" = 0 ] || warn "$partial unfinished Xbox download(s): download again to resume"+ python3 "$ROOT/scripts/fetch-xbox-runtime.py" --check && pass "Xbox game runtime DLLs verified" \+ || info "Xbox game runtime not downloaded yet (first Play or soju xbox-install fetches it)"+ python3 "$ROOT/scripts/xbox-prefix.py" --check && pass "Xbox prefix ready to play" \+ || info "Xbox prefix not prepared yet (needs the CX engine and GPTK; first Play prepares it)"+fi+echoecho "Processes"# macOS pgrep has no -c: count lines instead.diff --git a/scripts/fetch-xbox-runtime.py b/scripts/fetch-xbox-runtime.pynew file mode 100755index 00000000000..8b710afb05b--- /dev/null+++ b/scripts/fetch-xbox-runtime.py@@ -0,0 +1,165 @@+#!/usr/bin/env python3+"""Fetch the Xbox game runtime DLLs (xgameruntime and friends) for the Xbox prefix.++GDK games need Xbox services inside Wine. Those come from the Xodus Nexus runtime+(Wine 11.0 + xgameruntime, LGPL-2.1-or-later). MACxus rebuilt five of its DLLs+for macOS Wine; they ship inside its signed release image, and libnghttp2.dll+comes from the Nexus runtime release. Both archives are pinned by size and+SHA-256 in resources/xbox-runtime.json, and every DLL is checked again after+extraction. The image is mounted read-only and nothing from it is executed.+"""+import hashlib+import json+import os+import signal+from pathlib import Path, PurePosixPath+import shutil+import struct+import subprocess+import sys+import tarfile+import tempfile++MANIFEST = Path(__file__).resolve().parents[1] / 'resources/xbox-runtime.json'+LIMIT = 32 * 1024 * 1024+++def digest_bytes(data):+ return hashlib.sha256(data).hexdigest()+++def digest(path):+ h = hashlib.sha256()+ with Path(path).open('rb') as f:+ for block in iter(lambda: f.read(1024 * 1024), b''):+ h.update(block)+ return h.hexdigest()+++def recipe(manifest):+ return digest_bytes(json.dumps(manifest, sort_keys=True).encode())+++def ready(target, manifest):+ try:+ if (target / '.soju-xbox-runtime').read_text().strip() != recipe(manifest):+ return False+ return all(digest(target / name) == value for name, value in manifest['dlls'].items())+ except OSError:+ return False+++def download(url, dest, size, sha256, label):+ print('Downloading ' + label + ' (' + str(size // 1000000) + ' MB)…', flush=True)+ subprocess.run(['/usr/bin/curl', '--fail', '--silent', '--show-error', '--location', '--proto', '=https',+ '--proto-redir', '=https', '--retry', '3', '--connect-timeout', '20', '--max-time', '1800',+ url, '--output', str(dest)], check=True)+ if dest.stat().st_size != size or digest(dest) != sha256:+ raise ValueError(label + ' checksum mismatch; nothing was changed')+++def asar_files(path, folder):+ """Read files under one folder of an Electron asar archive (header + concatenated data)."""+ with Path(path).open('rb') as f:+ _, header_size, _, length = struct.unpack('<IIII', f.read(16))+ if length > 64 * 1024 * 1024:+ raise ValueError('Unexpected archive header')+ header = json.loads(f.read(length))+ node = header+ for part in folder.split('/'):+ node = node['files'][part]+ result = {}+ for name, item in node['files'].items():+ if 'files' in item or item.get('unpacked') or '/' in name:+ continue+ size, offset = int(item['size']), int(item['offset'])+ if size > LIMIT:+ raise ValueError('Unexpected file size in archive')+ f.seek(8 + header_size + offset)+ result[name] = f.read(size)+ return result+++def from_image(image, manifest, stage):+ mount = Path(tempfile.mkdtemp(prefix='soju-xbox-image-'))+ try:+ subprocess.run(['/usr/bin/hdiutil', 'attach', '-readonly', '-nobrowse', '-noautoopen', '-noverify',+ '-mountpoint', str(mount), str(image)], check=True, capture_output=True)+ try:+ files = asar_files(mount / manifest['macxus']['asar'], manifest['macxus']['folder'])+ finally:+ subprocess.run(['/usr/bin/hdiutil', 'detach', '-force', str(mount)], capture_output=True)+ finally:+ shutil.rmtree(mount, ignore_errors=True)+ for name, value in manifest['dlls'].items():+ if name in files:+ if digest_bytes(files[name]) != value:+ raise ValueError(name + ' does not match the pinned runtime; nothing was changed')+ (stage / name).write_bytes(files[name])+++def from_runtime(archive, manifest, stage):+ member = manifest['nexus']['member']+ name = PurePosixPath(member).name+ with tarfile.open(archive, 'r:xz') as tar:+ for item in tar:+ if item.name == member and item.isfile() and item.size <= LIMIT:+ with tar.extractfile(item) as source:+ data = source.read()+ if digest_bytes(data) != manifest['dlls'][name]:+ raise ValueError(name + ' does not match the pinned runtime; nothing was changed')+ (stage / name).write_bytes(data)+ return+ raise ValueError(name + ' is missing from the runtime archive')+++def fetch(base, manifest):+ target = base / 'xbox-runtime'+ if ready(target, manifest):+ print('Xbox game runtime ready (' + manifest['runtime'] + ')')+ return target+ (base / 'build').mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix='.xbox-runtime-', dir=base / 'build') as temp:+ work = Path(temp)+ stage = work / 'runtime'+ stage.mkdir()+ image = work / 'macxus.dmg'+ download(manifest['macxus']['url'], image, manifest['macxus']['size'], manifest['macxus']['sha256'], 'MACxus runtime DLLs')+ from_image(image, manifest, stage)+ image.unlink()+ archive = work / 'runtime.tar.xz'+ download(manifest['nexus']['url'], archive, manifest['nexus']['size'], manifest['nexus']['sha256'], 'Xodus Nexus runtime')+ from_runtime(archive, manifest, stage)+ archive.unlink()+ missing = [n for n in manifest['dlls'] if not (stage / n).is_file()]+ if missing:+ raise ValueError('Runtime DLLs missing: ' + ', '.join(missing))+ (stage / '.soju-xbox-runtime').write_text(recipe(manifest) + '\n')+ backup = base / 'xbox-runtime.previous'+ shutil.rmtree(backup, ignore_errors=True)+ if target.exists():+ target.rename(backup)+ try:+ stage.rename(target)+ except OSError:+ if backup.exists():+ backup.rename(target)+ raise+ shutil.rmtree(backup, ignore_errors=True)+ print('Xbox game runtime installed in ' + str(target))+ return target+++if __name__ == '__main__':+ # Stop from Soju (SIGTERM to the process group): exit normally so temporary+ # folders and partial downloads are cleaned up.+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))+ try:+ manifest = json.loads(MANIFEST.read_text())+ base = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))+ if sys.argv[1:] == ['--check']:+ sys.exit(0 if ready(base / 'xbox-runtime', manifest) else 1)+ fetch(base, manifest)+ except (OSError, ValueError, KeyError, struct.error, tarfile.TarError, subprocess.SubprocessError) as error:+ print('Xbox game runtime: ' + str(error), file=sys.stderr)+ sys.exit(1)diff --git a/scripts/fetch-xodus-backend.py b/scripts/fetch-xodus-backend.pynew file mode 100755index 00000000000..5df8af1c379--- /dev/null+++ b/scripts/fetch-xodus-backend.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""Build the pinned Xodus backend (xodus-cli) from source on this Mac.++Xodus is GPL-3.0 and publishes no macOS binaries, so Soju never ships one:+the source is cloned at a fixed commit, the MIT-licensed Nexus/MACxus patches+that add the library, package and progress commands are downloaded from a+fixed commit and checked against SHA-256 values in resources/xodus-backend.json,+and the result is built locally with the pinned Rust toolchain. The patched+source tree stays in build/xodus-src as the corresponding source.+"""+import hashlib+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile++MANIFEST = Path(__file__).resolve().parents[1] / "resources/xodus-backend.json"+# Homebrew's rustup formula is keg-only, so its bin/ is listed explicitly.+PATH = os.pathsep.join([str(Path.home() / ".cargo/bin"), "/opt/homebrew/opt/rustup/bin", "/opt/homebrew/bin", "/usr/local/bin",+ "/usr/bin", "/bin", "/usr/sbin", "/sbin"])+++def digest(path):+ h = hashlib.sha256()+ with Path(path).open("rb") as f:+ for block in iter(lambda: f.read(1024 * 1024), b""):+ h.update(block)+ return h.hexdigest()+++def recipe(manifest):+ """One value for everything that decides the binary: commit, toolchain and patches."""+ keys = ("version", "repository", "commit", "rust", "cargo_lock_sha256", "deployment_target")+ value = {k: manifest[k] for k in keys}+ value["patches"] = [[p["file"], p["sha256"]] for p in manifest["patches"]]+ value["patch_commit"] = manifest["patch_source"]["commit"]+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()+++KEEP = ("HOME", "USER", "LOGNAME", "TMPDIR", "LANG", "LC_ALL", "LC_CTYPE", "SSL_CERT_FILE",+ "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy")+++def environment():+ """Only what the build needs: no inherited RUSTC_WRAPPER, RUSTFLAGS, CARGO_*, GIT_*+ or toolchain overrides, and no user/system git config (URL rewrites)."""+ env = {k: os.environ[k] for k in KEEP if k in os.environ}+ env.update(PATH=PATH, XODUS_LOG="error", GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL="/dev/null",+ GIT_TERMINAL_PROMPT="0")+ return env+++def run(args, **kwargs):+ kwargs.setdefault("env", environment())+ return subprocess.run(args, check=True, **kwargs)+++def works(cli):+ """The binary starts and carries the library command Soju imports from."""+ try:+ for args in (["--version"], ["library", "--help"], ["resolve-package", "--help"]):+ run([str(cli)] + args, capture_output=True, timeout=20)+ return True+ except (OSError, subprocess.SubprocessError):+ return False+++def marker(target):+ try:+ return (target / ".soju-xodus").read_text().split()+ except OSError:+ return []+++def ready(target, manifest):+ """The recipe matches and the binary is the one this recipe built (hash recorded at build)."""+ lines = marker(target)+ try:+ return (len(lines) == 2 and lines[0] == recipe(manifest) and lines[1] == digest(target / "bin/xodus-cli")+ and works(target / "bin/xodus-cli"))+ except OSError:+ return False+++def ensure_service(target):+ """xodus-service is the same binary as xodus-cli; the file name selects the role+ (as MACxus ships it), so both share one code signature and Keychain grant."""+ cli, service = target / "bin/xodus-cli", target / "bin/xodus-service"+ if service.is_file() and digest(service) == digest(cli):+ return+ temporary = service.with_name(".xodus-service.tmp")+ shutil.copy2(cli, temporary)+ temporary.chmod(0o755)+ os.replace(temporary, service)+++def tool(name, formula):+ if shutil.which(name, path=PATH):+ return+ if not shutil.which("brew", path=PATH):+ raise RuntimeError(name + " is required. Install Homebrew from https://brew.sh, then retry.")+ print("Installing " + formula + " with Homebrew (build dependency)…", flush=True)+ run(["brew", "install", formula])+ if not shutil.which(name, path=PATH):+ raise RuntimeError(name + " is still missing after brew install " + formula + ".")+++def download(url, dest):+ run(["/usr/bin/curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https",+ "--proto-redir", "=https", "--retry", "3", "--connect-timeout", "20", "--max-time", "300",+ url, "--output", str(dest)])+++def prepare_source(work, manifest):+ """Clone, verify and patch. Nothing outside work/ changes if any check fails."""+ src = work / "xodus-src"+ print("Fetching Xodus source at " + manifest["commit"][:12] + "…", flush=True)+ run(["git", "-c", "advice.detachedHead=false", "clone", "--quiet", "--filter=blob:none",+ manifest["repository"], str(src)])+ run(["git", "-C", str(src), "-c", "advice.detachedHead=false", "checkout", "--quiet", manifest["commit"]])+ head = run(["git", "-C", str(src), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()+ if head != manifest["commit"]:+ raise ValueError("Xodus source is not at the pinned commit; nothing was changed")+ if digest(src / "Cargo.lock") != manifest["cargo_lock_sha256"]:+ raise ValueError("Xodus Cargo.lock does not match the pinned recipe; nothing was changed")+ patches = work / "patches"+ patches.mkdir()+ print("Verifying " + str(len(manifest["patches"])) + " backend patches…", flush=True)+ for item in manifest["patches"]:+ name = item["file"]+ if "/" in name or not name.endswith(".patch"):+ raise ValueError("Invalid patch name in the backend recipe")+ path = patches / name+ download(manifest["patch_source"]["base_url"] + name, path)+ if digest(path) != item["sha256"]:+ raise ValueError("Patch checksum mismatch (" + name + "); nothing was changed")+ for item in manifest["patches"]:+ run(["git", "-C", str(src), "apply", "--whitespace=nowarn", str(patches / item["file"])])+ return src+++def build(src, manifest):+ tool("rustup", "rustup")+ tool("protoc", "protobuf")+ toolchains = run(["rustup", "toolchain", "list"], capture_output=True, text=True).stdout+ if not any(line.startswith(manifest["rust"]) for line in toolchains.splitlines()):+ print("Installing Rust " + manifest["rust"] + " (build toolchain)…", flush=True)+ run(["rustup", "toolchain", "install", manifest["rust"], "--profile", "minimal"])+ print("Building the Xodus backend. This takes a few minutes the first time…", flush=True)+ env = environment()+ env["MACOSX_DEPLOYMENT_TARGET"] = manifest["deployment_target"]+ env["CARGO_TARGET_DIR"] = str(src / "target")+ run(["rustup", "run", manifest["rust"], "cargo", "build", "--locked", "--release", "-p", "xodus-cli"],+ cwd=src, env=env)+ return src / "target/release/xodus-cli"+++def install(base, src, binary, manifest):+ target = base / "xodus"+ stage = base / ".xodus-stage"+ shutil.rmtree(stage, ignore_errors=True)+ (stage / "bin").mkdir(parents=True)+ cli = stage / "bin/xodus-cli"+ shutil.copy2(binary, cli)+ cli.chmod(0o755)+ run(["codesign", "-f", "-s", "-", str(cli)], capture_output=True)+ ensure_service(stage)+ if not works(cli):+ shutil.rmtree(stage, ignore_errors=True)+ raise RuntimeError("The new Xodus backend does not start; the previous one is unchanged")+ (stage / ".soju-xodus").write_text(recipe(manifest) + "\n" + digest(cli) + "\n")+ # The patched tree is the corresponding source of the installed binary.+ shutil.rmtree(src / "target", ignore_errors=True)+ sources = base / "build/xodus-src"+ sources.parent.mkdir(parents=True, exist_ok=True)+ shutil.rmtree(sources, ignore_errors=True)+ shutil.move(str(src), str(sources))+ backup = base / "xodus.previous"+ shutil.rmtree(backup, ignore_errors=True)+ if target.exists():+ target.rename(backup)+ try:+ stage.rename(target)+ except OSError:+ if backup.exists():+ backup.rename(target)+ raise+ shutil.rmtree(backup, ignore_errors=True)+++def fetch(base, manifest):+ target = base / "xodus"+ lines = marker(target)+ if len(lines) == 1 and lines[0] == recipe(manifest) and works(target / "bin/xodus-cli"):+ # Built by an earlier Soju that did not record the binary's hash yet.+ (target / ".soju-xodus").write_text(lines[0] + "\n" + digest(target / "bin/xodus-cli") + "\n")+ if ready(target, manifest):+ ensure_service(target)+ print("Xodus backend ready (" + manifest["version"] + ")")+ return target+ base.mkdir(parents=True, exist_ok=True)+ (base / "build").mkdir(exist_ok=True)+ with tempfile.TemporaryDirectory(prefix=".xodus-", dir=base / "build") as temp:+ work = Path(temp)+ src = prepare_source(work, manifest)+ binary = build(src, manifest)+ install(base, src, binary, manifest)+ print("Xodus backend installed in " + str(target))+ return target+++if __name__ == "__main__":+ try:+ manifest = json.loads(MANIFEST.read_text())+ base = Path(os.environ.get("SOJU_BASE", str(Path.home() / ".battlenet-macos")))+ if sys.argv[1:] == ["--check"]:+ sys.exit(0 if ready(base / "xodus", manifest) else 1)+ fetch(base, manifest)+ except (OSError, ValueError, RuntimeError, KeyError, subprocess.SubprocessError) as error:+ print("Xodus backend: " + str(error), file=sys.stderr)+ sys.exit(1)diff --git a/scripts/game-library.py b/scripts/game-library.pyindex db7fa8baddd..e113c4b3cf6 100644--- a/scripts/game-library.py+++ b/scripts/game-library.py@@ -17,13 +17,17 @@ from library_services import saved_accountsfrom urllib.parse import quoteFOLDERS = {'steam': 'steam-bottle', 'epic': 'epic-bottle',- 'battlenet': 'bottle', 'gog': 'gog-bottle'}+ 'battlenet': 'bottle', 'gog': 'gog-bottle', 'xbox': 'xbox-bottle'}CLIENTS = {'steam': 'Program Files (x86)/Steam/steam.exe','epic': 'Program Files/Epic Games/Launcher/Portal/Binaries/Win64/EpicGamesLauncher.exe','battlenet': 'Program Files (x86)/Battle.net/Battle.net.exe','gog': 'Program Files/GOG Galaxy/GalaxyClient.exe',+ # Xbox PC has no Windows client: `xbox.sh install` writes this marker.+ 'xbox': 'ProgramData/Soju/xbox.json',}+XBOX_ENGINE = 'Set up Xbox PC again in Platforms: it installs the engine Xbox PC games run on.'+XBOX_GPTK = "Add Apple's Game Porting Toolkit in Platforms before playing."# Product UIDs differ from the Battle.net launch command's product codes.BNET = {'osi': ('Diablo II: Resurrected', 'OSI'),@@ -282,6 +286,35 @@ class Library:except (OSError, ValueError, KeyError, TypeError):self.warn('gog', 'An installation record could not be read. Verify this game in Galaxy.')+ def xbox(self):+ games = self.base / FOLDERS['xbox'] / 'drive_c/XboxGames'+ if not games.is_dir(): return+ for location in sorted(p for p in games.iterdir() if p.is_dir()):+ uid = location.name+ if not re.fullmatch(r'[A-Z0-9]{12}', uid): continue+ try:+ record = location / '.soju-xbox-install.json'+ if record.is_file():+ item = read_json(record)+ if item.get('schema') != 1 or item.get('product_id') != uid: raise ValueError('mismatched Xbox ID')+ title, ready = item.get('title') or uid, True+ elif (location / '.nexus-streaming-v1.jsonl').is_file():+ title, ready = uid, False+ else: continue+ art = first_file([self.base / 'library-artwork' / ('xbox-' + uid + '.jpg')])+ self.add('xbox', uid, title, location, ['run', uid], art, ready)+ game = self.games['xbox:' + uid]+ if not ready:+ game['issue'] = 'This download is not finished. Download again to resume it.'+ elif game['issue'] is None:+ # The prefix itself is prepared on the first Play; the engine must exist.+ engine = self.base / 'cx26-engine'+ if not os.access(engine / 'bin/wine', os.X_OK): game['issue'] = XBOX_ENGINE+ elif not (engine / 'lib/external/libd3dshared.dylib').is_file(): game['issue'] = XBOX_GPTK+ game['downloaded'] = ready+ except (OSError, ValueError, KeyError, TypeError, AttributeError):+ self.warn('xbox', 'A download record could not be read. Download the game again to repair it.')+def scan(self):self.games = {}; self.warnings = []for platform in FOLDERS:@@ -293,6 +326,11 @@ class Library:for game in owned:if game['id'] in self.games:self.games[game['id']]['owned'] = True+ # A partial download shows under its Store name.+ if self.games[game['id']]['title'] == game['id'].split(':', 1)[1]:+ self.games[game['id']]['title'] = game['title']+ if game.get('artwork') and not self.games[game['id']]['artwork']:+ self.games[game['id']]['artwork'] = game['artwork']else:self.games[game['id']] = dict(game, arguments=[])return {'accounts': accounts, 'games': [{k: v for k, v in g.items() if k != 'arguments'}@@ -303,6 +341,18 @@ class Library:self.scan()game = self.games.get(game_id)if game is None: raise ValueError('This game is no longer installed. Refresh the library.')+ root = Path(__file__).resolve().parent+ if game['platform'] == 'xbox':+ if install:+ if game.get('downloaded'): raise ValueError('This game is already downloaded. Use Play instead.')+ if game.get('owned') is not True and not game['install_path']: raise ValueError('This game is not in your Xbox library.')+ if game['issue'] and not game['install_path']: raise ValueError(game['issue'])+ if not (self.base / FOLDERS['xbox'] / 'drive_c' / CLIENTS['xbox']).is_file():+ raise ValueError('Set up Xbox PC in Platforms first.')+ return ['/bin/bash', str(root / 'xbox.sh'), 'download', game_id.split(':', 1)[1]]+ if not game.get('downloaded'): raise ValueError(game['issue'] or 'This game is owned but not downloaded. Download it first.')+ if game['issue']: raise ValueError(game['issue'])+ return ['/bin/bash', str(root / 'xbox.sh')] + game['arguments']if install:if game['install_path']: raise ValueError('This game is installed. Use Play instead.')client = self.base / FOLDERS[game['platform']] / 'drive_c' / CLIENTS[game['platform']]@@ -311,7 +361,6 @@ class Library:return ['/bin/bash', str(Path(__file__).resolve().parent / 'play.sh'), game['platform']] + argsif not game['install_path']: raise ValueError('This game is owned but not installed. Open its launcher to install it.')if game['issue']: raise ValueError(game['issue'])- root = Path(__file__).resolve().parentreturn ['/bin/bash', str(root / 'play.sh'), game['platform']] + game['arguments']diff --git a/scripts/library-service.py b/scripts/library-service.pyindex 75c5f5307aa..b18b5459bb0 100644--- a/scripts/library-service.py+++ b/scripts/library-service.py@@ -6,10 +6,18 @@ import osfrom pathlib import Pathimport sqlite3import sys-from library_services import (ServiceError, search, steam_owned, gog_owned, gog_users,+from library_services import (ServiceError, search, steam_owned, gog_owned, gog_users, xbox_owned,save_account, account_path)+def stop(signum, frame):+ # subprocess.run kills its child when an exception interrupts it, so a request the+ # app cancels does not leave xodus-cli running.+ raise KeyboardInterrupt++def main():+ import signal+ signal.signal(signal.SIGTERM, stop)parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('action', choices=['search', 'sync', 'forget', 'gog-users'])parser.add_argument('value', nargs='?', default='')@@ -35,9 +43,12 @@ def main():games, label = steam_owned(settings)elif args.value == 'gog':games, label = gog_owned(args.base, settings)+ elif args.value == 'xbox':+ games, label = xbox_owned(args.base, settings)else:raise ServiceError('Unsupported account provider.')- result = save_account(args.base, args.value, games, label)+ market = settings.get('market') if args.value == 'xbox' else None+ result = save_account(args.base, args.value, games, label, market or None)print(json.dumps(result, ensure_ascii=False))except ServiceError as error:print(json.dumps({'error': str(error)}))diff --git a/scripts/library_services.py b/scripts/library_services.pyindex 6350f05da18..940bfd9e086 100644--- a/scripts/library_services.py+++ b/scripts/library_services.py@@ -6,6 +6,7 @@ import osfrom pathlib import Pathimport reimport sqlite3+import subprocessimport tempfileimport timeimport urllib.error@@ -14,7 +15,10 @@ import urllib.requestLIMIT = 8 * 1024 * 1024REGIONS = {'US': 'USD', 'KR': 'KRW', 'GB': 'GBP', 'DE': 'EUR', 'JP': 'JPY'}-STORES = {'steam': 'https://store.steampowered.com', 'gog': 'https://www.gog.com'}+STORES = {'steam': 'https://store.steampowered.com', 'gog': 'https://www.gog.com', 'xbox': 'https://www.xbox.com'}+XBOX_LOCALES = {'US': 'en-US', 'KR': 'ko-KR', 'GB': 'en-GB', 'DE': 'de-DE', 'JP': 'ja-JP'}+CATALOG = 'https://displaycatalog.mp.microsoft.com/v7.0/'+PLATFORMS = ('steam', 'gog', 'xbox')class ServiceError(ValueError):@@ -58,19 +62,33 @@ def numeric_id(value):return value+def xbox_id(value):+ value = str(value)+ if not re.fullmatch(r'[A-Z0-9]{12}', value):+ raise ServiceError('Invalid game identifier.')+ return value+++def platform_id(platform, value):+ return xbox_id(value) if platform == 'xbox' else numeric_id(value)++def safe_image(value, platform):if not isinstance(value, str):return Noneparsed = urllib.parse.urlsplit(value)allowed = {'steam': ('steamstatic.com', 'steamcdn-a.akamaihd.net'),- 'gog': ('gog-statics.com', 'gog.com')}+ 'gog': ('gog-statics.com', 'gog.com'),+ 'xbox': ('store-images.s-microsoft.com',)}host = (parsed.hostname or '').lower()if parsed.scheme != 'https' or parsed.username or parsed.password or parsed.port not in (None, 443):return Nonereturn value if any(host == h or host.endswith('.' + h) for h in allowed[platform]) else None-def store_url(platform, uid, slug=''):+def store_url(platform, uid, slug='', country='US'):+ if platform == 'xbox':+ return STORES['xbox'] + '/' + XBOX_LOCALES.get(country, 'en-US') + '/games/store/-/' + xbox_id(uid)if platform == 'steam':return STORES[platform] + '/app/' + numeric_id(uid) + '/'if slug and re.fullmatch(r'[a-zA-Z0-9_-]{1,200}', slug):@@ -130,6 +148,104 @@ def gog_search(query, country):return result+def xbox_image(value):+ """Store image URIs are protocol-relative; a width keeps downloads small."""+ if not isinstance(value, str) or not value.startswith('//'):+ return None+ return safe_image('https:' + value.split('?', 1)[0] + '?w=400', 'xbox')+++def xbox_catalog(ids, country, deadline=None):+ """Public Microsoft Store metadata: title, art, price and Windows package formats.+ Chunks of 20 IDs are fetched four at a time; with a deadline (time.monotonic())+ unfinished chunks are left out."""+ chunks = [ids[start:start + 20] for start in range(0, len(ids), 20)]+ if len(chunks) <= 1:+ return xbox_catalog_chunk(chunks[0] if chunks else [], country)+ result = {}+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=4)+ try:+ jobs = [pool.submit(xbox_catalog_chunk, chunk, country) for chunk in chunks]+ remaining = None if deadline is None else max(1, deadline - time.monotonic())+ try:+ for job in concurrent.futures.as_completed(jobs, timeout=remaining):+ try:+ result.update(job.result())+ except ServiceError:+ continue+ except concurrent.futures.TimeoutError:+ pass+ finally:+ pool.shutdown(wait=False, cancel_futures=True)+ return result+++def xbox_catalog_chunk(ids, country):+ result = {}+ for start in range(0, len(ids), 20):+ chunk = [xbox_id(i) for i in ids[start:start + 20]]+ data = get_json(CATALOG + 'products?' + urllib.parse.urlencode({+ 'bigIds': ','.join(chunk), 'market': country, 'languages': XBOX_LOCALES[country] + ',neutral'}))+ if not isinstance(data, dict) or not isinstance(data.get('Products'), list):+ raise ServiceError('Microsoft Store metadata is unavailable.')+ for item in data['Products']:+ try:+ uid = xbox_id(item['ProductId'])+ local = item['LocalizedProperties'][0]+ title = text(local.get('ProductTitle'))+ if not title:+ continue+ images = {i.get('ImagePurpose'): i.get('Uri') for i in local.get('Images') or [] if isinstance(i, dict)}+ art = next((xbox_image(images[k]) for k in ('BoxArt', 'Poster', 'Logo') if xbox_image(images.get(k))), None)+ formats, price, windows, bundled = set(), None, False, False+ for sku in item.get('DisplaySkuAvailabilities') or []:+ props = sku['Sku']['Properties']+ bundled = bundled or bool(props.get('BundledSkus'))+ for package in props.get('Packages') or []:+ targets = [d.get('PlatformName') for d in package.get('PlatformDependencies') or []]+ if 'Windows.Desktop' in targets:+ windows = True+ formats.add(text(package.get('PackageFormat'), 20))+ if props.get('IsTrial') or price is not None:+ continue+ for offer in sku.get('Availabilities') or []:+ # Delisted games keep a 0 list price without a Purchase action.+ if 'Purchase' not in (offer.get('Actions') or []):+ continue+ money = (offer.get('OrderManagementData') or {}).get('Price') or {}+ amount, currency = money.get('ListPrice'), money.get('CurrencyCode', '')+ if isinstance(amount, (int, float)) and amount >= 0 and re.fullmatch(r'[A-Z]{3}', currency):+ price = 'Free' if amount == 0 else currency + ' ' + format(amount, ',.2f')+ break+ fmt = 'MSIXVC' if 'MSIXVC' in formats else 'MSIXVC2' if 'MSIXVC2' in formats else (sorted(formats)[0] if formats else None)+ if not formats and bundled:+ # Editions and bundles list their packages on the bundled products;+ # the download resolves them (xodus resolve-package).+ windows, fmt = True, 'BUNDLE'+ result[uid] = dict(title=title, type=text(item.get('ProductType'), 40), artwork=art,+ price=price or 'View price in store', windows=windows, format=fmt)+ except (KeyError, IndexError, TypeError, ValueError, AttributeError):+ continue+ return result+++def xbox_search(query, country):+ data = get_json(CATALOG + 'productFamilies/autosuggest?' + urllib.parse.urlencode({+ 'market': country, 'languages': XBOX_LOCALES[country], 'query': query, 'productFamilyNames': 'Games'}))+ if not isinstance(data, dict) or not isinstance(data.get('Results'), list):+ raise ServiceError('Microsoft Store search is unavailable.')+ ids = []+ for family in data['Results']:+ for item in (family.get('Products') if isinstance(family, dict) else None) or []:+ uid = item.get('ProductId') if isinstance(item, dict) else None+ if isinstance(uid, str) and re.fullmatch(r'[A-Z0-9]{12}', uid) and uid not in ids:+ ids.append(uid)+ meta = xbox_catalog(ids[:24], country) if ids else {}+ return [dict(id='xbox:' + uid, platform='xbox', title=meta[uid]['title'], url=store_url('xbox', uid, country=country),+ artwork=meta[uid]['artwork'], price=meta[uid]['price'], mac=False, windows=meta[uid]['windows'])+ for uid in ids if uid in meta and meta[uid]['type'] == 'Game']++def search(query, country):query = text(query, 100)if len(query) < 2:@@ -137,13 +253,14 @@ def search(query, country):if country not in REGIONS:raise ServiceError('Choose a supported store region.')games, warnings = [], []- with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:- jobs = {pool.submit(fn, query, country): name for name, fn in [('steam', steam_search), ('gog', gog_search)]}+ names = {'steam': 'Steam', 'gog': 'GOG', 'xbox': 'Microsoft Store'}+ with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:+ jobs = {pool.submit(fn, query, country): name for name, fn in [('steam', steam_search), ('gog', gog_search), ('xbox', xbox_search)]}for job in concurrent.futures.as_completed(jobs):try:games.extend(job.result())except Exception:- warnings.append(jobs[job].title() + ' search is unavailable. Please retry later.')+ warnings.append(names[jobs[job]] + ' search is unavailable. Please retry later.')unique = {g['id']: g for g in games}def rank(game):title, term = game['title'].casefold(), query.casefold()@@ -235,17 +352,154 @@ def gog_owned(base, settings):return list(games.values()), 'Galaxy · …' + selected[-4:]+def xodus_cli(base):+ return os.environ.get('SOJU_XODUS_BIN') or str(Path(base) / 'xodus/bin/xodus-cli')+++def xodus(base, args, timeout):+ """Run the backend without a shell or stdin. Its stderr is never shown: only+ the documented credential code is read from it."""+ cli = xodus_cli(base)+ if not os.access(cli, os.X_OK):+ raise ServiceError('Set up Xbox PC in Platforms first.')+ env = {'PATH': '/usr/bin:/bin', 'HOME': os.environ.get('HOME', str(Path.home())), 'XODUS_LOG': 'error'}+ try:+ result = subprocess.run([cli] + args, env=env, stdin=subprocess.DEVNULL, capture_output=True,+ text=True, timeout=timeout)+ except subprocess.TimeoutExpired:+ raise ServiceError('Xbox did not answer in time. Your previous import is unchanged.') from None+ except OSError:+ raise ServiceError('The Xbox backend could not start. Run Diagnose in Platforms.') from None+ if result.returncode != 0:+ if re.search(r'NEXUS_CREDENTIAL_ERROR_V1 [A-Za-z0-9_-]+', result.stderr or ''):+ raise ServiceError('Sign in to your Microsoft account in Accounts. Your previous import is unchanged.')+ raise ServiceError('Xbox did not share your library. Sign in again in Accounts, or retry later. Your previous import is unchanged.')+ try:+ return json.loads(result.stdout)+ except ValueError:+ raise ServiceError('Xbox returned an unreadable library. Your previous import is unchanged.') from None+++def save_image(url, path):+ """Store art in library-artwork; only Microsoft's image host, bounded size, no redirects."""+ if safe_image(url, 'xbox') is None:+ return None+ try:+ request = urllib.request.Request(url, headers={'User-Agent': 'Soju/1.7 (+https://github.com/BCD1210/soju)'})+ with urllib.request.build_opener(NoRedirect).open(request, timeout=5) as response:+ data = response.read(4 * 1024 * 1024 + 1)+ if len(data) > 4 * 1024 * 1024 or not data.startswith((b'\xff\xd8', b'\x89PNG')):+ return None+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temporary = tempfile.mkstemp(prefix='.art', dir=path.parent)+ with os.fdopen(fd, 'wb') as stream:+ stream.write(data)+ os.replace(temporary, path)+ return str(path)+ except (OSError, ValueError, ServiceError):+ return None+++def entitlement_end(value):+ """RFC 3339 end date. Python 3.9 (macOS's own python3) cannot parse 7-digit+ fractions such as Microsoft's 9999-12-31T23:59:59.9999999Z, so trim them."""+ value = re.sub(r'(\.\d{6})\d+', r'\1', value.strip().replace('Z', '+00:00'))+ return datetime.datetime.fromisoformat(value)+++# PC Game Pass and other subscriptions are products whose IDs start with CFQ7TTC0;+# a game reached through one of them is a Game Pass game, not a purchase.+SUBSCRIPTION = re.compile(r'CFQ7TTC0[A-Z0-9]{4}')+++def xbox_owned(base, settings, deadline=40):+ # The app stops a service request after 50 s; every step uses what is left of this budget.+ """Owned and PC Game Pass games from the signed-in Microsoft account."""+ started = time.monotonic()+ country = settings.get('market') or 'US'+ if country not in REGIONS:+ raise ServiceError('Choose a supported store region.')+ data = xodus(base, ['library', '--json', '--market', country], timeout=20)+ if not isinstance(data, dict) or data.get('schema') != 1 or not isinstance(data.get('entitlements'), list):+ raise ServiceError('Xbox returned an incomplete library. Your previous import is unchanged.')+ if len(data['entitlements']) > 10000:+ raise ServiceError('This library exceeds the supported import size.')+ now = datetime.datetime.now(datetime.timezone.utc)+ rights = {}+ for item in data['entitlements']:+ try:+ uid = xbox_id(item['productId'])+ end = entitlement_end(item['endDate'])+ if item['status'] != 'Active' or item.get('special') or end <= now:+ continue+ parent = item.get('satisfiedByProductId') or ''+ source = 'gamepass' if SUBSCRIPTION.fullmatch(parent) else 'owned'+ # A purchase wins over the same game reached through Game Pass.+ if rights.get(uid, {}).get('source') != 'owned':+ rights[uid] = dict(source=source, trial=item.get('isTrial') is True)+ except (KeyError, TypeError, ValueError, AttributeError, ServiceError):+ continue+ meta = xbox_catalog(sorted(rights), country, started + 30) if rights else {}+ games, missing, art = [], 0, Path(base) / 'library-artwork'+ for uid, right in rights.items():+ item = meta.get(uid)+ if item is None:+ missing += 1+ continue+ if item['type'] != 'Game' or not item['windows']:+ continue+ games.append(dict(id='xbox:' + uid, platform='xbox', title=item['title'], format=item['format'],+ source=right['source'], artwork=item['artwork']))+ if missing and not games:+ raise ServiceError('The Microsoft Store did not return game names. Please retry. Your previous import is unchanged.')+ gamertag = ''+ left = started + deadline - time.monotonic()+ if left > 3:+ try:+ profile = xodus(base, ['profile', '--json'], timeout=min(8, left - 1))+ gamertag = text(profile.get('gamertag'), 40) if isinstance(profile, dict) else ''+ except ServiceError:+ pass+ # Art is optional: whatever is not fetched in time is retried on the next sync.+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=8)+ try:+ jobs = {}+ for game in games:+ path = art / ('xbox-' + game['id'][5:] + '.jpg')+ if path.is_file():+ game['artwork'] = str(path)+ elif game['artwork']:+ jobs[pool.submit(save_image, game['artwork'], path)] = game+ else:+ game['artwork'] = None+ remaining = max(1, deadline - (time.monotonic() - started))+ try:+ for job in concurrent.futures.as_completed(jobs, timeout=remaining):+ jobs[job]['artwork'] = job.result()+ except concurrent.futures.TimeoutError:+ pass+ for job, game in jobs.items():+ if not job.done() or not job.result():+ game['artwork'] = None+ job.cancel()+ finally:+ pool.shutdown(wait=False, cancel_futures=True)+ return games, 'Xbox · ' + gamertag if gamertag else 'Microsoft account'++def account_path(base, platform):- if platform not in ('steam', 'gog'):+ if platform not in PLATFORMS:raise ServiceError('Unsupported account provider.')return Path(base) / 'account-libraries' / (platform + '.json')-def save_account(base, platform, games, label):+def save_account(base, platform, games, label, market=None):path = account_path(base, platform)path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)payload = dict(schema=1, platform=platform, label=label,updated_at=datetime.datetime.now(datetime.timezone.utc).isoformat(), games=games)+ if market:+ payload['market'] = marketdata = json.dumps(payload, ensure_ascii=False).encode()if len(data) > LIMIT:raise ServiceError('This library exceeds the supported import size.')@@ -262,7 +516,8 @@ def save_account(base, platform, games, label):def saved_accounts(base):accounts, games, warnings = [], [], []- for platform in ('steam', 'gog'):+ art = (Path(base) / 'library-artwork').absolute()+ for platform in PLATFORMS:path = account_path(base, platform)if not path.is_file():continue@@ -276,13 +531,23 @@ def saved_accounts(base):raise ValueError()imported = {}for game in data['games']:- uid = numeric_id(game['id'].removeprefix(platform + ':'))+ uid = platform_id(platform, game['id'].removeprefix(platform + ':'))if game['id'] != platform + ':' + uid or not text(game.get('title')):raise ValueError()- imported[game['id']] = dict(id=game['id'], platform=platform, title=text(game['title']),- install_path='', artwork=None, issue=None, owned=True)+ entry = dict(id=game['id'], platform=platform, title=text(game['title']),+ install_path='', artwork=None, issue=None, owned=True)+ if platform == 'xbox':+ picture = Path(str(game.get('artwork') or ''))+ if picture.is_absolute() and picture.parent == art and picture.name == 'xbox-' + uid + '.jpg' and picture.is_file():+ entry['artwork'] = str(picture)+ entry['format'] = text(game.get('format'), 20) or None+ entry['source'] = 'gamepass' if game.get('source') == 'gamepass' else 'owned'+ if entry['format'] not in ('MSIXVC', 'BUNDLE'):+ entry['issue'] = ('This game uses a newer package format that Soju can\'t download yet.'+ if entry['format'] == 'MSIXVC2' else 'No Windows PC package that Soju can download.')+ imported[game['id']] = entrygames.extend(imported.values())accounts.append(dict(platform=platform, label=text(data.get('label')), updated_at=text(data.get('updated_at')), count=len(imported)))except (OSError, ValueError, TypeError, KeyError, AttributeError):- warnings.append(platform.title() + ' account import could not be read. Reconnect it in Accounts.')+ warnings.append({'steam': 'Steam', 'gog': 'Gog', 'xbox': 'Xbox'}[platform] + ' account import could not be read. Reconnect it in Accounts.')return accounts, games, warningsdiff --git a/scripts/soju b/scripts/sojuindex 38653930c8d..84258a9eb82 100755--- a/scripts/soju+++ b/scripts/soju@@ -16,12 +16,12 @@ usage() {soju: open-source Windows launchers on Apple SiliconUsage:- soju install Choose and install any of the four launchers+ soju install Choose and install any of the five platformssoju app Build, install and open the native Soju appsoju library List installed and imported games as JSONsoju game <id> Play a game from the unified librarysoju game-install <id> Open the official launcher to install an owned game- soju search <term> Search Steam and GOG (--country US|KR|GB|DE|JP)+ soju search <term> Search Steam, GOG and the Microsoft Store (--country US|KR|GB|DE|JP)soju --version Print the Soju versionsoju battlenet Launch Battle.net (default bottle)soju d2r Launch Diablo II: Resurrected directly@@ -35,6 +35,14 @@ Usage:soju gog Launch GOG GALAXYsoju gog-kill Stop everything in the GOG bottle+ soju xbox-install Build the Xodus backend for Xbox PC / Microsoft Store (Rust, a few minutes)+ soju xbox-login Sign in with your Microsoft account (official page in a window)+ soju xbox-logout Sign out (downloaded games are kept)+ soju xbox-sync [US|KR|GB|DE|JP] Import your owned and PC Game Pass games+ soju xbox-download <ProductId> Download an owned game (resumable)+ soju xbox-run <ProductId> Play a downloaded game (experimental)+ soju xbox-kill Stop a running Xbox download or game+soju steam-install Set up the Steam bottle (private Wine 11 + wrapper + Steam)soju steam-games Download and configure verified D3D11 componentssoju steam-games renderer <dxvk|dxmt|reset|status> <game.exe path>@@ -63,6 +71,16 @@ case "${1:-}" inepic-install) shift; exec bash "$ROOT/scripts/create-epic-bottle.sh" "$@" ;;gog-install) shift; exec bash "$ROOT/scripts/create-gog-bottle.sh" "$@" ;;steam-install) shift; export SOJU_PLATFORMS=steam; exec bash "$ROOT/install.sh" "$@" ;;+ xbox-install) exec bash "$ROOT/scripts/xbox.sh" install ;;+ xbox-login) exec bash "$ROOT/scripts/xbox.sh" login ;;+ xbox-logout) shift; exec bash "$ROOT/scripts/xbox.sh" logout "$@" ;;+ xbox-kill) exec bash "$ROOT/scripts/xbox.sh" kill ;;+ xbox-run) shift; exec python3 "$ROOT/scripts/game-library.py" launch "xbox:${1:?Choose a Store product ID}" ;;+ xbox-download) shift; exec python3 "$ROOT/scripts/game-library.py" install "xbox:${1:?Choose a Store product ID}" ;;+ xbox-sync)+ market="${2:-US}"+ case "$market" in US|KR|GB|DE|JP) ;; *) echo "soju: choose US, KR, GB, DE or JP" >&2; exit 64 ;; esac+ printf '{"market":"%s"}' "$market" | exec python3 "$ROOT/scripts/library-service.py" sync xbox ;;steam-games) shift; exec bash "$ROOT/scripts/setup-steam-games.sh" "$@" ;;gptk) shift; exec bash "$ROOT/scripts/get-gptk.sh" "$@" ;;sweep) shift; exec bash "$ROOT/scripts/soju-sweep.sh" "$@" ;;diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex 1fd15863082..90eb9cd9749 100755--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -48,11 +48,15 @@ if [ "${#apps[@]}" -gt 0 ]; thenfi# 3. Bottles (this is where installed games live; can be tens of GB).-for b in bottle steam-bottle epic-bottle gog-bottle; do+for b in bottle steam-bottle epic-bottle gog-bottle xbox-bottle; dod="$BASE/$b"[ -d "$d" ] || continuesz=$(du -sh "$d" 2>/dev/null | cut -f1)if ask "Remove bottle $b ($sz, includes installed games)?"; then+ if [ "$b" = xbox-bottle ]; then+ bash "$ROOT/scripts/xbox.sh" kill >/dev/null 2>&1 || true+ sh "$ROOT/scripts/xbox-wine.sh" --soju-stop-prefix 2>/dev/null || true+ fistop_bottle "$b"rm -rf "$d"; REMOVED=1; echo " removed"fi@@ -72,6 +76,25 @@ if [ "${#runtimes[@]}" -gt 0 ]; thenfifi+# The Xodus backend build (re-buildable from source with soju xbox-install).+xodus=()+for d in xodus xodus.previous .xodus-stage xbox-runtime xbox-runtime.previous run; do+ [ -e "$BASE/$d" ] && xodus+=("$BASE/$d")+done+if [ "${#xodus[@]}" -gt 0 ]; then+ printf 'Xbox PC backend and game runtime: %s\n' "${xodus[@]}"+ # Offer the Microsoft sign-in too while the backend that can remove it still exists.+ if [ -x "$BASE/xodus/bin/xodus-cli" ] && security find-generic-password -s "Xodus Service" >/dev/null 2>&1 &&+ ask "Sign out of Microsoft (removes the Xbox sign-in from the Keychain)?"; then+ XODUS_LOG=error "$BASE/xodus/bin/xodus-cli" logout --device >/dev/null 2>&1 && echo " signed out" || echo " sign-out failed; remove \"Xodus Service\" in Keychain Access"+ fi+ if ask "Remove the Xodus backend and Xbox game runtime (can be downloaded and built again)?"; then+ xodus_bin="$(printf '%s' "$BASE/xodus/bin/xodus-" | sed 's/[][\.*^$()+?{}|]/\\&/g')"+ pkill -f "^${xodus_bin}(cli|service)( |$)" 2>/dev/null || true+ rm -rf "${xodus[@]}"; REMOVED=1; echo " removed"+ fi+fi+# 4. Engine (+ the GPTK payload inside it).if [ -d "$ENGINE" ]; thensz=$(du -sh "$ENGINE" 2>/dev/null | cut -f1)@@ -108,5 +131,8 @@ Not removed by this script (they are Homebrew's):brew uninstall soju the soju CLI itself, if installed via brewbrew uninstall --cask wine-stable legacy Wine, only if separately installedbrew uninstall mingw-w64 the wrapper build dependency+ brew uninstall protobuf rustup Xodus build dependencies, if Soju installed them+If you kept the Microsoft sign-in, it stays in your Keychain as "Xodus Service"+(remove it in Keychain Access).EOTecho "Done."diff --git a/scripts/xbox-download.py b/scripts/xbox-download.pynew file mode 100755index 00000000000..610394435e4--- /dev/null+++ b/scripts/xbox-download.py@@ -0,0 +1,210 @@+#!/usr/bin/env python3+"""Download and extract one owned Xbox PC game with the Xodus backend.++Resumable: Xodus keeps a checkpoint in the game folder and continues from it.+The Soju install record is written only after Xodus reports a complete download.+Backend progress records are shown as one short line; URLs and JSON are not printed.+"""+import datetime+import json+import os+from pathlib import Path+import re+import signal+import subprocess+import sys++BASE = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))+CLI = os.environ.get('SOJU_XODUS_BIN') or str(BASE / 'xodus/bin/xodus-cli')+GAMES = BASE / 'xbox-bottle/drive_c/XboxGames'+MARKETS = ('US', 'KR', 'GB', 'DE', 'JP')+MARKER = '.soju-xbox-install.json'+++class DownloadError(Exception):+ pass+++def environment():+ env = {k: v for k, v in os.environ.items() if not k.startswith(('DYLD_', 'WINE', 'CX_'))}+ env['XODUS_LOG'] = 'error'+ return env+++def product_id(value):+ value = str(value).removeprefix('xbox:').upper()+ if not re.fullmatch(r'[A-Z0-9]{12}', value):+ raise DownloadError('Invalid Microsoft Store product ID.')+ return value+++def imported():+ try:+ value = json.loads((BASE / 'account-libraries/xbox.json').read_text())+ return value if isinstance(value, dict) else {}+ except (OSError, ValueError):+ return {}+++def market():+ value = os.environ.get('SOJU_XBOX_MARKET', '') or str(imported().get('market', ''))+ return value if value in MARKETS else 'US'+++def library_title(pid):+ """The name the library shows (an edition), not the package inside it."""+ for game in imported().get('games') or []:+ if isinstance(game, dict) and game.get('id') == 'xbox:' + pid and isinstance(game.get('title'), str):+ return game['title'].strip()[:300]+ return ''+++def choose(plan, pid):+ """Pick the one Windows PC package Xodus can install, or explain why not."""+ if not isinstance(plan, dict) or plan.get('schema') != 1 or not isinstance(plan.get('choices'), list):+ raise DownloadError('The Microsoft Store returned unexpected package data. Please retry later.')+ choices = [c for c in plan['choices'] if isinstance(c, dict)]+ usable = [c for c in choices if c.get('supported') is True and c.get('platform') == 'Windows.Desktop'+ and re.fullmatch(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', str(c.get('contentId', '')))]+ # An edition bundles the game with add-ons: the game package is the one to install.+ # An add-on is never picked as "the game".+ games = [c for c in usable if c.get('kind') == 'Game']+ if plan.get('status') in ('ready', 'choice') and len(games) == 1:+ return games[0]+ if plan.get('status') == 'choice' and len(games) > 1:+ names = sorted({str(c.get('title', ''))[:80] for c in games})+ raise DownloadError('This Store offer contains several games (' + ', '.join(names) ++ '). Download each one from its own entry in your library.')+ if any(c.get('packageFormat') == 'MSIXVC2' for c in choices):+ raise DownloadError("This game uses a newer package format (MSIXVC2) that Soju can't download yet.")+ raise DownloadError('No Windows PC package for ' + pid + ' can be downloaded from the Microsoft Store.')+++def resolve(pid, region):+ try:+ result = subprocess.run([CLI, 'resolve-package', pid, '--json', '--market', region], env=environment(),+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60)+ except (OSError, subprocess.SubprocessError):+ raise DownloadError('Could not reach the Microsoft Store. Check your connection and retry.') from None+ if result.returncode != 0:+ raise DownloadError('The Microsoft Store has no package information for this game right now. Please retry later.')+ try:+ return json.loads(result.stdout)+ except ValueError:+ raise DownloadError('The Microsoft Store returned unexpected package data. Please retry later.') from None+++def size(value):+ value = float(value)+ for unit in ('B', 'KB', 'MB', 'GB', 'TB'):+ if value < 1000 or unit == 'TB':+ return (format(value, '.0f') if unit in ('B', 'KB') else format(value, '.1f')) + ' ' + unit+ value /= 1000+++def clean(line):+ """Backend messages may carry request URLs (with query tokens); keep the words only."""+ line = re.sub(r'[a-z][a-z0-9+.-]*://\S+', '<url>', line.strip())+ return re.sub(r'\S+@\S+', '<account>', line)[:300]+++def describe(record):+ phase = record.get('phase')+ done, total, rate = record.get('completedBytes'), record.get('totalBytes'), record.get('bytesPerSecond')+ if phase == 'downloading' and isinstance(done, int) and isinstance(total, int) and total > 0:+ line = ' ' + str(min(100, done * 100 // total)) + '% · ' + size(done) + ' / ' + size(total)+ if isinstance(rate, int) and rate > 0:+ line += ' · ' + size(rate) + '/s'+ return line + (' (paused)' if record.get('paused') else '')+ return {'initializing': ' Preparing the download…', 'metadata': ' Reading the package…',+ 'finalizing': ' Finishing the files…', 'complete': ' Download complete.',+ 'failed': ' The download stopped.'}.get(phase)+++def stream(pid, choice, region, dest):+ args = [CLI, 'streaming', pid, str(dest), '--selected-content-id', choice['contentId'],+ '--market', region, '--progress-json']+ # stderr joins stdout so every backend line goes through clean().+ process = subprocess.Popen(args, env=environment(), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, bufsize=1, errors='replace')+ phase, shown, busy = None, None, False+ try:+ for line in process.stdout:+ if line.startswith('NEXUS_PROGRESS '):+ try:+ record = json.loads(line[15:])+ except ValueError:+ continue+ if not isinstance(record, dict) or record.get('schema') != 1:+ continue+ phase = record.get('phase')+ text = describe(record)+ # Whole percent steps keep the log short on a 100 GB download.+ key = text.split('·')[0] if text else None+ if text and key != shown:+ print(text, flush=True)+ shown = key+ elif line.strip():+ busy = busy or 'another download is using this folder' in line+ print(' ' + clean(line), flush=True)+ finally:+ # Stopping Soju's download also stops the backend; its checkpoint stays.+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ code = process.wait()+ if busy:+ raise DownloadError('This game is already downloading. Pause that download first, or wait for it to finish.')+ return code == 0 and phase == 'complete'+++def stop(signum, frame):+ raise KeyboardInterrupt+++def main():+ if len(sys.argv) != 2:+ print('Usage: xbox-download.py <ProductId>', file=sys.stderr)+ return 64+ pid_file = None+ signal.signal(signal.SIGTERM, stop)+ try:+ # xbox.sh kill signals only the pids recorded in run/ (no command-line matching).+ run_dir = BASE / 'run'+ run_dir.mkdir(mode=0o700, parents=True, exist_ok=True)+ os.chmod(run_dir, 0o700)+ pid_file = run_dir / ('xbox-dl-' + str(os.getpid()) + '.pid')+ pid_file.write_text(str(os.getpid()))+ pid_file.chmod(0o600)+ pid = product_id(sys.argv[1])+ if not os.access(CLI, os.X_OK):+ raise DownloadError('Set up Xbox PC in Platforms first (or run: soju xbox-install).')+ region = market()+ choice = choose(resolve(pid, region), pid)+ dest = GAMES / pid+ dest.mkdir(parents=True, exist_ok=True)+ title = library_title(pid) or str(choice.get('title') or pid).strip()[:300]+ print('Downloading ' + title + ' (' + str(choice.get('packageFormat')) + ') to ' + str(dest), flush=True)+ if not stream(pid, choice, region, dest):+ raise DownloadError('The download did not finish. Download again to resume it.')+ record = dict(schema=1, product_id=pid, content_id=choice['contentId'], title=title,+ installed_at=datetime.datetime.now(datetime.timezone.utc).isoformat())+ (dest / MARKER).write_text(json.dumps(record, ensure_ascii=False) + '\n')+ print(title + ' is downloaded. Press Play in Soju to start it.')+ return 0+ except (DownloadError, OSError) as error:+ print('soju: ' + str(error), file=sys.stderr)+ return 1+ except KeyboardInterrupt:+ print('soju: Download stopped. Download again to resume it.', file=sys.stderr)+ return 130+ finally:+ if pid_file:+ pid_file.unlink(missing_ok=True)+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/xbox-prefix.py b/scripts/xbox-prefix.pynew file mode 100755index 00000000000..daa7534637b--- /dev/null+++ b/scripts/xbox-prefix.py@@ -0,0 +1,155 @@+#!/usr/bin/env python3+"""Prepare the Xbox prefix (xbox-bottle) so GDK games can start.++- boots the prefix with Soju's CX engine (D3DMetal from the user's GPTK);+- copies the Xbox runtime DLLs (fetch-xbox-runtime.py) into system32 as native+ DLLs (Wine treats a file still carrying its "Wine builtin DLL" marker as a+ placeholder, so the marker is cleared);+- sets the DLL overrides and the Gaming Services version games check;+- installs Microsoft's VC++ 2015-2022 runtime (downloaded from Microsoft and+ checked by SHA-256; never redistributed), whose concrt140 games need.+A marker records what was applied, so later launches skip all of this.+"""+import hashlib+import json+import os+import signal+from pathlib import Path+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[1]+BASE = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))+ENGINE = Path(os.environ.get('ENGINE', str(BASE / 'cx26-engine')))+PREFIX = BASE / 'xbox-bottle'+RUNTIME = BASE / 'xbox-runtime'+RUNNER = ROOT / 'scripts/xbox-wine.sh'+MARKER = PREFIX / '.soju-xbox-prefix'+BUILTIN = b'Wine builtin DLL'+VC = dict(version='14.44.35211.0', sha256='cc0ff0eb1dc3f5188ae6300faef32bf5beeba4bdd6e8e445a9184072096b713b',+ url='https://download.visualstudio.microsoft.com/download/pr/bd1c8d9d-ba95-4eee-bc6e-df1fcc876373/'+ 'CC0FF0EB1DC3F5188AE6300FAEF32BF5BEEBA4BDD6E8E445A9184072096B713B/VC_redist.x64.exe')+++class PrefixError(Exception):+ pass+++def manifest():+ return json.loads((ROOT / 'resources/xbox-runtime.json').read_text())+++def overrides(names):+ keys = [n[:-4] for n in names] + ['concrt140']+ settings = [['reg', 'add', 'HKCU\\Software\\Wine\\DllOverrides', '/v', k, '/t', 'REG_SZ', '/d', 'native,builtin', '/f']+ for k in keys]+ # Gaming Services 38.117.27001.0, as the Nexus runtime writes it; some games check it.+ settings += [['reg', 'add', 'HKLM\\SOFTWARE\\Microsoft\\GamingServices', '/v', v, '/t', 'REG_QWORD',+ '/d', '0x0026007569790000', '/f', '/reg:64'] for v in ('CurrentVersion', 'AvailableVersion')]+ settings += [['reg', 'add', 'HKCU\\Software\\Wine\\WineDbg', '/v', 'ShowCrashDialog', '/t', 'REG_DWORD', '/d', '0', '/f']]+ return settings+++def state(m):+ return hashlib.sha256(json.dumps([m['dlls'], overrides(m['dlls']), VC['sha256']], sort_keys=True).encode()).hexdigest()+++def engine_problem():+ if not os.access(ENGINE / 'bin/wine', os.X_OK):+ return 'Set up Xbox PC again in Platforms: it installs the engine Xbox PC games run on.'+ if not (ENGINE / 'lib/external/libd3dshared.dylib').is_file():+ return "Add Apple's Game Porting Toolkit in Platforms before playing."+ return None+++def ready():+ try:+ return engine_problem() is None and MARKER.read_text().strip() == state(manifest()) and \+ subprocess.run([sys.executable, str(ROOT / 'scripts/fetch-xbox-runtime.py'), '--check'],+ capture_output=True).returncode == 0+ except OSError:+ return False+++def wine(args, timeout=600):+ env = {k: v for k, v in os.environ.items() if not k.startswith(('WINE', 'DYLD_'))}+ env.update(SOJU_BASE=str(BASE), ENGINE=str(ENGINE))+ result = subprocess.run(['/bin/sh', str(RUNNER)] + args, env=env, capture_output=True, timeout=timeout)+ return result.returncode+++def install_dlls(names):+ system32 = PREFIX / 'drive_c/windows/system32'+ system32.mkdir(parents=True, exist_ok=True)+ for name in names:+ data = bytearray((RUNTIME / name).read_bytes())+ if len(data) >= 80 and data[64:80] == BUILTIN:+ data[64:80] = bytes(16)+ target = system32 / name+ if target.is_file() and target.read_bytes() == bytes(data):+ continue+ temporary = target.with_name(target.name + '.soju')+ temporary.write_bytes(bytes(data))+ temporary.chmod(0o644)+ os.replace(temporary, target)+++def vc_runtime():+ cache = BASE / 'build'+ cache.mkdir(parents=True, exist_ok=True)+ exe = cache / ('vc_redist.x64-' + VC['version'] + '.exe')+ def good():+ try:+ return hashlib.sha256(exe.read_bytes()).hexdigest() == VC['sha256']+ except OSError:+ return False+ if not good():+ print('Downloading the Microsoft VC++ runtime…', flush=True)+ subprocess.run(['/usr/bin/curl', '--fail', '--silent', '--show-error', '--location', '--proto', '=https',+ '--proto-redir', '=https', '--max-time', '600', VC['url'], '--output', str(exe)], check=True)+ if not good():+ exe.unlink(missing_ok=True)+ raise PrefixError('The VC++ runtime download did not match its checksum.')+ print('Installing the VC++ runtime into the Xbox prefix…', flush=True)+ code = wine(['Z:' + str(exe).replace('/', '\\'), '/install', '/quiet', '/norestart'], timeout=900)+ # 1638: a same or newer version is installed; 3010: installed, restart pending.+ if code not in (0, 1638, 3010):+ raise PrefixError('The VC++ runtime did not install (code ' + str(code) + '). Run Diagnose and retry.')+++def prepare():+ problem = engine_problem()+ if problem:+ raise PrefixError(problem)+ m = manifest()+ if subprocess.run([sys.executable, str(ROOT / 'scripts/fetch-xbox-runtime.py')]).returncode != 0:+ raise PrefixError('The Xbox game runtime could not be installed.')+ if ready():+ print('Xbox prefix ready.')+ return+ PREFIX.mkdir(parents=True, exist_ok=True)+ if not (PREFIX / 'system.reg').is_file():+ print('Creating the Xbox prefix…', flush=True)+ wine(['wineboot', '-u'])+ if not (PREFIX / 'system.reg').is_file():+ raise PrefixError('The Xbox prefix could not be created.')+ install_dlls(m['dlls'])+ for args in overrides(m['dlls']):+ if wine(args) != 0:+ raise PrefixError('Could not apply ' + ' '.join(args[2:5]) + ' in the Xbox prefix.')+ vc_runtime()+ MARKER.write_text(state(m) + '\n')+ print('Xbox prefix ready.')+++if __name__ == '__main__':+ # Stop from Soju (SIGTERM to the process group): exit normally so temporary+ # folders and partial downloads are cleaned up.+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))+ try:+ if sys.argv[1:] == ['--check']:+ sys.exit(0 if ready() else 1)+ prepare()+ except (PrefixError, OSError, ValueError, subprocess.SubprocessError) as error:+ print('soju: ' + str(error), file=sys.stderr)+ sys.exit(1)diff --git a/scripts/xbox-run.py b/scripts/xbox-run.pynew file mode 100755index 00000000000..17d52921f80--- /dev/null+++ b/scripts/xbox-run.py@@ -0,0 +1,327 @@+#!/usr/bin/env python3+"""Start a downloaded Xbox PC game.++1. finds the game's executable in MicrosoftGame.config (or appxmanifest.xml);+2. prepares the Xbox prefix (runtime DLLs, overrides, VC++) when needed;+3. starts xodus-service (account, licensing and cloud saves for the game) on a+ private socket, plus a loopback TCP bridge: macOS Wine has no AF_UNIX+ Winsock, so the game's xgameruntime reaches the service over 127.0.0.1 with+ a random per-launch key (XODUS_BRIDGE_PORT / XODUS_BRIDGE_KEY);+4. runs `xodus-cli run`, which gets the licence, decrypts the game into a+ temporary RAM-disk view and starts it with scripts/xbox-wine.sh. Files the+ game writes there are copied back into its folder when it exits.+Stopping (Ctrl+C or SIGTERM) asks xodus-cli to stop the game so saves sync; if+the game is still running 20 s later, everything in the Xbox prefix is ended.+Only one session per game runs at a time.+"""+import fcntl+import hmac+import json+import os+from pathlib import Path, PurePosixPath, PureWindowsPath+import re+import secrets+import shutil+import signal+import socket+import subprocess+import sys+import tempfile+import threading+import time+import xml.etree.ElementTree as ET++ROOT = Path(__file__).resolve().parents[1]+BASE = Path(os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))+CLI = Path(os.environ.get('SOJU_XODUS_BIN') or str(BASE / 'xodus/bin/xodus-cli'))+GAMES = BASE / 'xbox-bottle/drive_c/XboxGames'+MARKETS = ('US', 'KR', 'GB', 'DE', 'JP')+++class LaunchError(Exception):+ pass+++def product_id(value):+ value = str(value).removeprefix('xbox:').upper()+ if not re.fullmatch(r'[A-Z0-9]{12}', value):+ raise LaunchError('Invalid Microsoft Store product ID.')+ return value+++def find(folder, name):+ return next((p for p in folder.iterdir() if p.name.casefold() == name.casefold() and p.is_file()), None)+++def local(tag):+ return tag.rsplit('}', 1)[-1].casefold()+++def executable(folder):+ """The launch entry the package declares; never a path outside the game folder."""+ for name, element, attribute in (('MicrosoftGame.config', 'executable', 'name'),+ ('appxmanifest.xml', 'application', 'executable')):+ path = find(folder, name)+ if not path or path.stat().st_size > 4 * 1024 * 1024:+ continue+ try:+ tree = ET.parse(path)+ except ET.ParseError:+ continue+ for node in tree.iter():+ if local(node.tag) != element:+ continue+ value = next((v for k, v in node.attrib.items() if local(k) == attribute), '').strip()+ parts = PureWindowsPath(value).parts+ if value and not PureWindowsPath(value).drive and not PureWindowsPath(value).root and '..' not in parts:+ return value+ raise LaunchError('The game package does not name its executable (MicrosoftGame.config).')+++def market():+ value = os.environ.get('SOJU_XBOX_MARKET', '')+ if not value:+ try:+ value = json.loads((BASE / 'account-libraries/xbox.json').read_text()).get('market', '')+ except (OSError, ValueError, AttributeError):+ value = ''+ return value if value in MARKETS else 'US'+++def clean(line):+ """Backend messages may carry request URLs (with query tokens); keep the words only."""+ line = re.sub(r'[a-z][a-z0-9+.-]*://\S+', '<url>', line.rstrip())+ return re.sub(r'\S+@\S+', '<account>', line)[:500]+++class Bridge:+ """127.0.0.1 TCP -> xodus-service socket. A client must send the key first.+ Only a few connections may wait for authentication at once, briefly, so other+ local processes cannot pile up threads during a game session."""+ PENDING = 8++ def __init__(self, socket_path):+ self.pending = threading.BoundedSemaphore(self.PENDING)+ self.socket_path = socket_path+ self.key = secrets.token_hex(32).encode()+ self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ self.server.bind(('127.0.0.1', 0))+ self.server.listen(16)+ self.port = self.server.getsockname()[1]+ self.closed = False+ threading.Thread(target=self.accept, daemon=True).start()++ def accept(self):+ while not self.closed:+ try:+ client, _ = self.server.accept()+ except OSError:+ return+ if not self.pending.acquire(blocking=False):+ client.close()+ continue+ threading.Thread(target=self.handle, args=(client,), daemon=True).start()++ def handle(self, client):+ upstream = None+ waiting = True+ try:+ client.settimeout(2)+ received = b''+ while len(received) < len(self.key):+ chunk = client.recv(len(self.key) - len(received))+ if not chunk:+ return+ received += chunk+ waiting = False+ self.pending.release()+ if not hmac.compare_digest(received, self.key):+ return+ client.settimeout(None)+ upstream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ upstream.connect(self.socket_path)+ threading.Thread(target=self.pipe, args=(upstream, client), daemon=True).start()+ self.pipe(client, upstream)+ except OSError:+ pass+ finally:+ if waiting:+ self.pending.release()+ for s in (client, upstream):+ if s:+ try:+ s.close()+ except OSError:+ pass++ @staticmethod+ def pipe(source, target):+ try:+ while True:+ data = source.recv(65536)+ if not data:+ break+ target.sendall(data)+ except OSError:+ pass+ finally:+ try:+ target.shutdown(socket.SHUT_WR)+ except OSError:+ pass++ def close(self):+ self.closed = True+ self.server.close()+++class Service:+ def __init__(self):+ binary = CLI.parent / 'xodus-service'+ if not os.access(binary, os.X_OK):+ raise LaunchError('The Xodus backend has no xodus-service. Run Update components in Platforms.')+ # macOS limits socket paths to 104 bytes, so the session lives in /tmp.+ self.directory = Path(tempfile.mkdtemp(prefix='soju-xbox-', dir='/tmp'))+ self.socket = str(self.directory / 'xodus.sock')+ env = {'PATH': '/usr/bin:/bin', 'HOME': str(Path.home()), 'XDG_RUNTIME_DIR': str(self.directory), 'XODUS_LOG': 'error'}+ self.process = subprocess.Popen([str(binary)], env=env, stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ # Drain stderr for the whole session (a full pipe would block the service);+ # keep only whether it reported a credential problem.+ self.credential_error = False+ threading.Thread(target=self.drain, daemon=True).start()+ self.bridge = None+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ if self.process.poll() is not None:+ time.sleep(0.2)+ self.stop()+ if self.credential_error:+ raise LaunchError('Sign in to your Microsoft account in Accounts, then press Play again.')+ raise LaunchError('The Xbox account service stopped. Check your connection and sign-in, then retry.')+ try:+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:+ probe.connect(self.socket)+ self.bridge = Bridge(self.socket)+ return+ except OSError:+ time.sleep(0.25)+ self.stop()+ raise LaunchError('The Xbox account service did not start within 90 seconds.')++ def drain(self):+ for line in self.process.stderr:+ if b'NEXUS_CREDENTIAL_ERROR_V1' in line:+ self.credential_error = True++ def stop(self):+ if self.bridge:+ self.bridge.close()+ # The service holds the account tokens: make sure it is gone.+ for send in (lambda: self.process.send_signal(signal.SIGINT), self.process.terminate, self.process.kill):+ if self.process.poll() is not None:+ break+ send()+ try:+ self.process.wait(timeout=4)+ except subprocess.TimeoutExpired:+ pass+ shutil.rmtree(self.directory, ignore_errors=True)+++def main():+ if len(sys.argv) != 2:+ print('Usage: xbox-run.py <ProductId>', file=sys.stderr)+ return 64+ service = game = prep = None+ stop = threading.Event()+ # xbox.sh kill signals only the pids recorded here (no command-line matching).+ run_dir = BASE / 'run'+ run_dir.mkdir(mode=0o700, parents=True, exist_ok=True)+ os.chmod(run_dir, 0o700)+ pid_file = run_dir / ('xbox-' + str(os.getpid()) + '.pid')+ pid_file.write_text(str(os.getpid()))+ pid_file.chmod(0o600)+ def force_stop():+ if not stop.wait() or game is None:+ return+ try:+ game.wait(timeout=20)+ except subprocess.TimeoutExpired:+ subprocess.run(['/bin/sh', str(ROOT / 'scripts/xbox-wine.sh'), '--soju-stop-prefix'],+ env=dict(os.environ, SOJU_BASE=str(BASE)), capture_output=True)+ def interrupt(signum, frame):+ if stop.is_set():+ return+ stop.set()+ # First launch may still be preparing the prefix (downloads, VC++ setup):+ # stop that whole process group too.+ if prep and prep.poll() is None:+ try:+ os.killpg(prep.pid, signal.SIGTERM)+ except OSError:+ pass+ if game and game.poll() is None:+ game.send_signal(signal.SIGINT)+ threading.Thread(target=force_stop, daemon=True).start()+ signal.signal(signal.SIGTERM, interrupt)+ signal.signal(signal.SIGINT, interrupt)+ try:+ pid = product_id(sys.argv[1])+ folder = GAMES / pid+ record = folder / '.soju-xbox-install.json'+ if not record.is_file():+ raise LaunchError('This game is not downloaded. Download it in Soju first.')+ if not (folder / '.xodus-streaming.msixvc').is_file():+ raise LaunchError('The game download is incomplete. Download it again to repair it.')+ lock = (folder / '.soju-xbox-run.lock').open('w')+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError:+ raise LaunchError('This game is already running.') from None+ exe = executable(folder)+ prep = subprocess.Popen([sys.executable, str(ROOT / 'scripts/xbox-prefix.py')], start_new_session=True)+ if stop.is_set(): # TERM arrived before prep was bound+ try:+ os.killpg(prep.pid, signal.SIGTERM)+ except OSError:+ pass+ prepared = prep.wait()+ if stop.is_set():+ print('soju: Stopped before the game started.', file=sys.stderr)+ return 130+ if prepared != 0:+ return 1+ title = json.loads(record.read_text()).get('title') or pid+ print('Starting ' + str(title)[:300] + ' (' + exe + ')…', flush=True)+ service = Service()+ if stop.is_set():+ return 130+ env = {k: v for k, v in os.environ.items() if not k.startswith(('DYLD_', 'WINE', 'CX_'))}+ env.update(SOJU_BASE=str(BASE), XODUS_LOG='error', XODUS_SOCKET=service.socket,+ XODUS_BRIDGE_PORT=str(service.bridge.port), XODUS_BRIDGE_KEY=service.bridge.key.decode(),+ XODUS_SAVE_SYNC='auto')+ game = subprocess.Popen([str(CLI), 'run', str(folder), str(ROOT / 'scripts/xbox-wine.sh'), '--exe', exe,+ '--materialize-chain', '--market', market()],+ cwd=str(folder), env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT, text=True, bufsize=1, errors='replace')+ if stop.is_set() and game.poll() is None: # TERM arrived before game was bound+ game.send_signal(signal.SIGINT)+ threading.Thread(target=force_stop, daemon=True).start()+ for line in game.stdout:+ if line.strip():+ print(clean(line), flush=True)+ code = game.wait()+ print('The game exited (code ' + str(code) + ').', flush=True)+ return 0 if code == 0 or stop.is_set() else code+ except LaunchError as error:+ print('soju: ' + str(error), file=sys.stderr)+ return 1+ finally:+ if service:+ service.stop()+ pid_file.unlink(missing_ok=True)+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/xbox-wine.sh b/scripts/xbox-wine.shnew file mode 100755index 00000000000..df70dc7670e--- /dev/null+++ b/scripts/xbox-wine.sh@@ -0,0 +1,44 @@+#!/bin/sh+# Wine runner for Xbox PC games: `xodus-cli run` calls this with the game's+# decrypted launch view (Z:\...\Game.exe). Same engine and environment as the+# other CX-engine platforms (wine 11.0 from CrossOver sources + D3DMetal),+# on the Xbox prefix that scripts/xbox-prefix.py prepared.+BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"+ENGINE="${ENGINE:-$BASE/cx26-engine}"+export WINEPREFIX="$BASE/xbox-bottle"+export WINEDEBUG="${WINEDEBUG:-fixme-all}"+export WINEMSYNC="${WINEMSYNC:-1}"+export ROSETTA_ADVERTISE_AVX="${ROSETTA_ADVERTISE_AVX:-1}"+[ "$ROSETTA_ADVERTISE_AVX" = 0 ] && unset ROSETTA_ADVERTISE_AVX+export WINE_SIMULATE_WRITECOPY=1+export CX_ACTIVE_GRAPHICS_BACKEND=d3dmetal+export CX_GRAPHICS_BACKEND=d3dmetal+export CX_APPLEGPTK_LIBD3DSHARED_PATH="$ENGINE/lib/external/libd3dshared.dylib"+export DYLD_FALLBACK_LIBRARY_PATH="$ENGINE/lib:/usr/lib"+if [ "${1:-}" = "--soju-stop-prefix" ]; then+ exec "$ENGINE/bin/wineserver" -k+fi+# xodus-cli stops a game by signalling this script. A shell waiting on a+# foreground child ignores SIGINT, so wine runs in the background and the+# signal is forwarded: the game gets a TERM, and anything still running in+# the prefix after a grace period is ended with wineserver -k.+stop() {+ kill -TERM "$wine_pid" 2>/dev/null+ ( sleep 10; "$ENGINE/bin/wineserver" -k ) >/dev/null 2>&1 &+ stopping=1+}+stopping=0+"$ENGINE/bin/wine" "$@" &+wine_pid=$!+trap stop INT TERM HUP+launch_status=0+wait "$wine_pid" || launch_status=$?+# wait returns early when a trapped signal arrives; wait for the real exit.+while kill -0 "$wine_pid" 2>/dev/null; do wait "$wine_pid" || launch_status=$?; done+trap - INT TERM HUP+# The game may hand off to child processes; the launch ends when the prefix is empty.+wait_status=0+"$ENGINE/bin/wineserver" -w || wait_status=$?+[ "$stopping" = 1 ] && exit 130+[ "$launch_status" -ne 0 ] && exit "$launch_status"+exit "$wait_status"diff --git a/scripts/xbox.sh b/scripts/xbox.shnew file mode 100755index 00000000000..be92767aeba--- /dev/null+++ b/scripts/xbox.sh@@ -0,0 +1,108 @@+#!/usr/bin/env bash+# Xbox PC / Microsoft Store through the Xodus backend: sign-in, downloads and play.+# xbox.sh install | prepare | login | logout [--device] | status | download <ProductId> | run <ProductId> | kill+set -euo pipefail+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"+export SOJU_BASE="$BASE"+XODUS_CLI="${SOJU_XODUS_BIN:-$BASE/xodus/bin/xodus-cli}"+XBOX_HOME="$BASE/xbox-bottle"+# Tokens go to the macOS Keychain ("Xodus Service"); keep backend logs quiet so+# nothing account-related reaches Soju's log files.+export XODUS_LOG=error++need_backend() {+ if [ -n "${SOJU_XODUS_BIN:-}" ]; then+ [ -x "$XODUS_CLI" ] || { echo "SOJU_XODUS_BIN must point to an xodus-cli build with the Nexus commands." >&2; exit 1; }+ return+ fi+ python3 "$ROOT/scripts/fetch-xodus-backend.py" --check || {+ echo "Set up Xbox PC in Platforms first (or run: soju xbox-install)." >&2; exit 1; }+}++case "${1:-}" in+ install)+ if [ -z "${SOJU_XODUS_BIN:-}" ]; then python3 "$ROOT/scripts/fetch-xodus-backend.py"; fi+ need_backend+ mkdir -p "$XBOX_HOME/drive_c/XboxGames" "$XBOX_HOME/drive_c/ProgramData/Soju"+ marker="$XBOX_HOME/drive_c/ProgramData/Soju/xbox.json"+ if [ ! -f "$marker" ]; then+ printf '{"schema":1,"backend":"%s","created":"%s"}\n' \+ "$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["version"])' "$ROOT/resources/xodus-backend.json")" \+ "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$marker"+ fi+ # Games run on the CX engine with Apple's D3DMetal; without them only downloads work for now.+ if [ -x "${ENGINE:-$BASE/cx26-engine}/bin/wine" ] && [ -f "${ENGINE:-$BASE/cx26-engine}/lib/external/libd3dshared.dylib" ]; then+ python3 "$ROOT/scripts/xbox-prefix.py"+ else+ if [ -x "${ENGINE:-$BASE/cx26-engine}/bin/wine" ]; then+ echo "Playing Xbox PC games needs Apple's Game Porting Toolkit: add it in Platforms (or: soju gptk)."+ else+ echo "Playing Xbox PC games needs the CX engine: set up Xbox PC again in Platforms (or: soju install)."+ fi+ fi+ echo "Xbox PC is ready. Sign in from Soju > Accounts (or: soju xbox-login)."+ echo "Downloads go to $XBOX_HOME/drive_c/XboxGames." ;;+ prepare)+ exec python3 "$ROOT/scripts/xbox-prefix.py" ;;+ run)+ need_backend+ exec python3 "$ROOT/scripts/xbox-run.py" "${2:?Choose a game (Store product ID)}" ;;+ login)+ need_backend+ echo "Opening the Microsoft sign-in page. Finish signing in there, then this window closes."+ # Cancel in Soju sends TERM here: close the sign-in window too, so nothing is stored afterwards.+ # Some backend lines name the account; keep e-mail addresses out of the log.+ "$XODUS_CLI" login > >(sed -E 's/[^[:space:]]+@[^[:space:]]+/<account>/g') 2>&1 &+ login_pid=$!+ trap 'kill -TERM "$login_pid" 2>/dev/null; wait "$login_pid" 2>/dev/null; exit 143' TERM INT HUP+ # A closed sign-in window ends login with an error; the stored-account check below reports it.+ wait "$login_pid" || true+ trap - TERM INT HUP+ "$XODUS_CLI" account --json | python3 -c 'import json,sys+v=json.load(sys.stdin)+sys.exit(0 if v.get("stored") else 1)' || { echo "Sign-in was not completed." >&2; exit 1; }+ echo "Signed in." ;;+ logout)+ # Signing out must work even when the backend is gone or its recipe changed:+ # any xodus-cli that still runs clears the Keychain entry, and Soju's own+ # copy of the library is removed either way.+ status=0+ if [ -x "$XODUS_CLI" ] && "$XODUS_CLI" --version >/dev/null 2>&1; then+ if [ "${2:-}" = "--device" ]; then "$XODUS_CLI" logout --device || status=$?; else "$XODUS_CLI" logout || status=$?; fi+ else+ echo "The Xbox PC backend is not installed; removing Soju's copy of the library only."+ fi+ rm -f "$BASE/account-libraries/xbox.json" "$BASE"/library-artwork/xbox-*.jpg+ if [ "$status" != 0 ]; then+ echo "soju: The Xbox library was removed from Soju, but the Microsoft sign-in is still in the Keychain. Delete \"Xodus Service\" in Keychain Access, or sign out again." >&2+ exit 2+ fi+ echo "Signed out. Downloaded games are kept." ;;+ status)+ need_backend+ # Only whether an account is stored; the account name is never printed.+ "$XODUS_CLI" account --json | python3 -c 'import json,sys+print("Signed in" if json.load(sys.stdin).get("stored") else "Not signed in")' ;;+ download)+ need_backend+ exec python3 "$ROOT/scripts/xbox-download.py" "${2:?Choose a game (Store product ID)}" ;;+ kill)+ # Downloads and games record their pid; only a live xbox-download.py or+ # xbox-run.py with that pid is signalled. SIGTERM lets the download keep its+ # checkpoint, and lets xbox-run.py stop the game and copy its saves back.+ stopped=0+ for f in "$BASE"/run/xbox-*.pid; do+ [ -f "$f" ] || continue+ p="$(cat "$f" 2>/dev/null)"+ case "$p" in ''|*[!0-9]*) continue ;; esac+ cmd="$(ps -p "$p" -o command= 2>/dev/null || true)"+ [ -n "$cmd" ] || { rm -f "$f"; continue; }+ case "$cmd" in+ *xbox-download.py*) kill -TERM "$p" && echo "Download stopped. Download again to resume." && stopped=1 ;;+ *xbox-run.py*) kill -TERM "$p" && echo "Game stop requested." && stopped=1 ;;+ esac+ done+ [ "$stopped" = 1 ] || echo "No Xbox download or game is running." ;;+ *) echo "Usage: xbox.sh install|prepare|login|logout [--device]|status|download <ProductId>|run <ProductId>|kill" >&2; exit 64 ;;+esacdiff --git a/tests/test_purchase_links.swift b/tests/test_purchase_links.swiftindex 0b058b963a7..399c3f2452f 100644--- a/tests/test_purchase_links.swift+++ b/tests/test_purchase_links.swift@@ -23,6 +23,10 @@ import Foundationassert(active.resolve(other)?.url.absoluteString == other)let steam = "https://store.steampowered.com/app/10/"assert(active.resolve(steam)?.url.absoluteString == steam)+ let xbox = "https://www.xbox.com/en-US/games/store/-/9N116V0599HB"+ assert(active.resolve(xbox)?.url.absoluteString == xbox)+ assert(active.resolve(xbox)?.isAffiliate == false)+ assert(active.resolve("https://www.xbox.com.evil.test/x") == nil)let disabled = try config([entry], enabled: false)assert(!disabled.hasAffiliateLinks)assert(disabled.resolve(direct)?.url.absoluteString == direct)diff --git a/tests/test_xbox.py b/tests/test_xbox.pynew file mode 100644index 00000000000..32238caeb8c--- /dev/null+++ b/tests/test_xbox.py@@ -0,0 +1,707 @@+"""Xbox PC / Microsoft Store through the Xodus backend: search, import, downloads, build recipe.++No network, Keychain or real backend: every Xodus call is a fake script or a mock.+"""+import datetime+import importlib.util+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import time+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / 'scripts'))+import library_services as svc+++def load(name, file):+ spec = importlib.util.spec_from_file_location(name, ROOT / 'scripts' / file)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++library = load('soju_xbox_library', 'game-library.py')+download = load('soju_xbox_download', 'xbox-download.py')+backend = load('soju_xodus_backend', 'fetch-xodus-backend.py')+runner = load('soju_xbox_run', 'xbox-run.py')+prefix = load('soju_xbox_prefix', 'xbox-prefix.py')+runtime = load('soju_xbox_runtime', 'fetch-xbox-runtime.py')++SILKSONG, VOID, PASS = '9N116V0599HB', '9MW9469V91LM', '9NBLGGH4R315'+FUTURE = (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=30)).isoformat()+PAST = '2020-01-01T00:00:00Z'+++def product(uid, title, kind='Game', fmt='MSIXVC', price=19.99, buy=True):+ return {'ProductId': uid, 'ProductType': kind,+ 'LocalizedProperties': [{'ProductTitle': title, 'Images': [+ {'ImagePurpose': 'BoxArt', 'Uri': '//store-images.s-microsoft.com/image/apps.1.' + uid}]}],+ 'DisplaySkuAvailabilities': [{'Sku': {'Properties': {'IsTrial': False, 'Packages': [+ {'PackageFormat': fmt, 'PlatformDependencies': [{'PlatformName': 'Windows.Desktop'}]},+ {'PackageFormat': 'XVC', 'PlatformDependencies': [{'PlatformName': 'Windows.Xbox'}]}]}},+ 'Availabilities': [{'Actions': ['Details', 'Purchase'] if buy else ['Details'],+ 'OrderManagementData': {'Price': {'ListPrice': price, 'CurrencyCode': 'USD'}}}]}]}+++class XboxStoreTests(unittest.TestCase):+ def test_search_uses_public_catalog_prices_and_xbox_links(self):+ suggest = {'Results': [{'Products': [{'ProductId': SILKSONG}, {'ProductId': VOID}, {'ProductId': 'bad id'}]}]}+ catalog = {'Products': [product(SILKSONG, 'Hollow Knight: Silksong'),+ product(VOID, 'Old edition', price=0, buy=False)]}+ with patch.object(svc, 'get_json', side_effect=[suggest, catalog]) as get:+ rows = svc.xbox_search('hollow', 'KR')+ self.assertIn('productFamilies/autosuggest', get.call_args_list[0].args[0])+ self.assertEqual([r['id'] for r in rows], ['xbox:' + SILKSONG, 'xbox:' + VOID])+ self.assertEqual(rows[0]['price'], 'USD 19.99')+ # A delisted game keeps a 0 list price but cannot be bought.+ self.assertEqual(rows[1]['price'], 'View price in store')+ self.assertEqual(rows[0]['url'], 'https://www.xbox.com/ko-KR/games/store/-/' + SILKSONG)+ self.assertTrue(rows[0]['artwork'].startswith('https://store-images.s-microsoft.com/'))+ self.assertTrue(rows[0]['windows'])++ def test_editions_without_own_packages_are_downloadable_bundles(self):+ bundle = product('9P1HX37NMJLT', 'Deluxe Edition')+ props = bundle['DisplaySkuAvailabilities'][0]['Sku']['Properties']+ props['Packages'] = []+ props['BundledSkus'] = [{'BigId': '9NKX70BBCDRN'}]+ with patch.object(svc, 'get_json', return_value={'Products': [bundle]}):+ meta = svc.xbox_catalog(['9P1HX37NMJLT'], 'US')['9P1HX37NMJLT']+ self.assertEqual((meta['format'], meta['windows']), ('BUNDLE', True))+ with tempfile.TemporaryDirectory() as temp:+ svc.save_account(temp, 'xbox', [dict(id='xbox:9P1HX37NMJLT', platform='xbox', title='Deluxe', format='BUNDLE')], 'Xbox')+ self.assertIsNone(svc.saved_accounts(temp)[1][0]['issue'])++ def test_artwork_must_come_from_microsoft_image_host(self):+ self.assertIsNone(svc.xbox_image('https://evil.test/x.png'))+ self.assertIsNone(svc.xbox_image('//store-images.s-microsoft.com.evil.test/x'))+ self.assertEqual(svc.xbox_image('//store-images.s-microsoft.com/image/a?w=9'),+ 'https://store-images.s-microsoft.com/image/a?w=400')++ def test_three_store_failure_isolation(self):+ game = dict(id='steam:1', platform='steam', title='Hollow')+ with patch.object(svc, 'steam_search', return_value=[game]), patch.object(svc, 'gog_search', return_value=[]), \+ patch.object(svc, 'xbox_search', side_effect=svc.ServiceError('offline')):+ data = svc.search('hollow', 'US')+ self.assertEqual(data['games'], [game])+ self.assertEqual(data['warnings'], ['Microsoft Store search is unavailable. Please retry later.'])+++class XboxImportTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.base = Path(self.temp.name)+ cli = self.base / 'xodus/bin/xodus-cli'+ cli.parent.mkdir(parents=True)+ cli.write_text('#!/bin/sh\nexit 0\n')+ cli.chmod(0o755)++ def fake(self, library, stderr='', code=0):+ def run(args, **kwargs):+ self.assertNotIn('shell', kwargs)+ self.assertEqual(kwargs['stdin'], subprocess.DEVNULL)+ if args[1] == 'profile':+ return subprocess.CompletedProcess(args, 0, json.dumps({'schema': 1, 'account': '[email protected]', 'gamertag': 'Tester'}), '')+ return subprocess.CompletedProcess(args, code, json.dumps(library), stderr)+ return run++ def entitlements(self):+ row = dict(status='Active', isTrial=False, sharingSource='None', endDate=FUTURE, satisfiedByProductId=None, special=False)+ return {'schema': 1, 'account': '[email protected]', 'market': 'US', 'checkedAt': FUTURE, 'entitlements': [+ dict(row, productId=SILKSONG),+ dict(row, productId=VOID, satisfiedByProductId='CFQ7TTC0KGQ8'),+ dict(row, productId='9PASTPASTPAS', endDate=PAST),+ dict(row, productId='9INACTIVEXXX', status='Expired'),+ dict(row, productId='9SPECIALXXXX', special=True),+ dict(row, productId='lowercase-id'),+ dict(row, productId=PASS)]}++ def test_owned_and_game_pass_games_are_imported_without_the_account_name(self):+ meta = {SILKSONG: dict(title='Silksong', type='Game', windows=True, format='MSIXVC', artwork=None, price=''),+ VOID: dict(title='Voidheart', type='Game', windows=True, format='MSIXVC2', artwork=None, price=''),+ PASS: dict(title='A subscription', type='Pass', windows=False, format=None, artwork=None, price='')}+ with patch.object(svc.subprocess, 'run', side_effect=self.fake(self.entitlements())), \+ patch.object(svc, 'xbox_catalog', return_value=meta) as catalog:+ games, label = svc.xbox_owned(self.base, {'market': 'US'})+ self.assertEqual(sorted(catalog.call_args.args[0]), sorted([SILKSONG, VOID, PASS]))+ self.assertEqual(label, 'Xbox · Tester')+ self.assertEqual({g['id']: g['source'] for g in games}, {'xbox:' + SILKSONG: 'owned', 'xbox:' + VOID: 'gamepass'})+ svc.save_account(self.base, 'xbox', games, label, 'US')+ saved = (self.base / 'account-libraries/xbox.json').read_text()+ self.assertNotIn('example.test', saved)+ self.assertEqual(json.loads(saved)['market'], 'US')+ accounts, owned, warnings = svc.saved_accounts(self.base)+ self.assertEqual(warnings, [])+ issues = {g['id']: g['issue'] for g in owned}+ self.assertIsNone(issues['xbox:' + SILKSONG])+ self.assertIn('newer package format', issues['xbox:' + VOID])++ def test_backend_failure_hides_its_output(self):+ secret = 'eyJhbGciOi.secret-token'+ with patch.object(svc.subprocess, 'run', side_effect=self.fake({}, stderr=secret, code=1)):+ with self.assertRaises(svc.ServiceError) as error:+ svc.xbox_owned(self.base, {'market': 'US'})+ self.assertNotIn(secret, str(error.exception))+ with patch.object(svc.subprocess, 'run', side_effect=self.fake({}, stderr='NEXUS_CREDENTIAL_ERROR_V1 missing ' + secret, code=1)):+ with self.assertRaises(svc.ServiceError) as error:+ svc.xbox_owned(self.base, {'market': 'US'})+ self.assertIn('Sign in', str(error.exception))+ self.assertNotIn(secret, str(error.exception))++ def test_missing_backend_and_bad_market_are_reported(self):+ with self.assertRaises(svc.ServiceError):+ svc.xbox_owned(self.base, {'market': 'XX'})+ (self.base / 'xodus/bin/xodus-cli').unlink()+ with self.assertRaises(svc.ServiceError) as error:+ svc.xbox_owned(self.base, {'market': 'US'})+ self.assertIn('Platforms', str(error.exception))++ def test_saved_art_must_be_soju_art_for_that_game(self):+ art = self.base / 'library-artwork'+ art.mkdir()+ (art / ('xbox-' + SILKSONG + '.jpg')).write_bytes(b'\xff\xd8')+ outside = self.base / 'elsewhere.jpg'+ outside.write_bytes(b'\xff\xd8')+ svc.save_account(self.base, 'xbox', [+ dict(id='xbox:' + SILKSONG, platform='xbox', title='A', format='MSIXVC', source='owned', artwork=str(art / ('xbox-' + SILKSONG + '.jpg'))),+ dict(id='xbox:' + VOID, platform='xbox', title='B', format='MSIXVC', source='owned', artwork=str(outside))], 'Xbox')+ _, owned, _ = svc.saved_accounts(self.base)+ art_by_id = {g['id']: g['artwork'] for g in owned}+ self.assertTrue(art_by_id['xbox:' + SILKSONG].endswith('xbox-' + SILKSONG + '.jpg'))+ self.assertIsNone(art_by_id['xbox:' + VOID])++ def test_invalid_saved_xbox_id_rejects_the_import(self):+ svc.save_account(self.base, 'xbox', [dict(id='xbox:9n116v0599hb', platform='xbox', title='A')], 'Xbox')+ _, owned, warnings = svc.saved_accounts(self.base)+ self.assertEqual(owned, [])+ self.assertEqual(warnings, ['Xbox account import could not be read. Reconnect it in Accounts.'])+++class XboxLibraryTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.addCleanup(self.temp.cleanup)+ self.base = Path(self.temp.name)+ self.games = self.base / 'xbox-bottle/drive_c/XboxGames'+ marker = self.base / 'xbox-bottle/drive_c' / library.CLIENTS['xbox']+ marker.parent.mkdir(parents=True)+ marker.write_text('{}')+ self.lib = library.Library(self.base)++ def downloaded(self, uid=SILKSONG, title='Silksong'):+ folder = self.games / uid+ folder.mkdir(parents=True)+ (folder / '.soju-xbox-install.json').write_text(json.dumps(dict(schema=1, product_id=uid, title=title)))+ return folder++ def engine(self, gptk=True):+ wine = self.base / 'cx26-engine/bin/wine'+ wine.parent.mkdir(parents=True)+ wine.write_text('#!/bin/sh\n')+ wine.chmod(0o755)+ if gptk:+ art = self.base / 'cx26-engine/lib/external/libd3dshared.dylib'+ art.parent.mkdir(parents=True)+ art.write_text('')++ def test_downloaded_game_plays_through_xbox_script(self):+ folder = self.downloaded()+ self.engine()+ game = {g['id']: g for g in self.lib.scan()['games']}['xbox:' + SILKSONG]+ self.assertTrue(game['downloaded'])+ self.assertEqual(game['install_path'], str(folder))+ self.assertIsNone(game['issue'])+ self.assertEqual(self.lib.command('xbox:' + SILKSONG), ['/bin/bash', str(ROOT / 'scripts/xbox.sh'), 'run', SILKSONG])+ with self.assertRaisesRegex(ValueError, 'already downloaded'):+ self.lib.command('xbox:' + SILKSONG, install=True)++ def test_play_needs_the_engine_and_gptk(self):+ self.downloaded()+ with self.assertRaisesRegex(ValueError, 'installs the engine'):+ self.lib.command('xbox:' + SILKSONG)+ self.engine(gptk=False)+ with self.assertRaisesRegex(ValueError, 'Game Porting Toolkit'):+ self.lib.command('xbox:' + SILKSONG)++ def test_owned_game_downloads_through_xbox_script(self):+ svc.save_account(self.base, 'xbox', [dict(id='xbox:' + SILKSONG, platform='xbox', title='Silksong', format='MSIXVC')], 'Xbox')+ command = self.lib.command('xbox:' + SILKSONG, install=True)+ self.assertEqual(command[1:], [str(ROOT / 'scripts/xbox.sh'), 'download', SILKSONG])++ def test_msixvc2_game_cannot_start_a_download(self):+ svc.save_account(self.base, 'xbox', [dict(id='xbox:' + VOID, platform='xbox', title='Void', format='MSIXVC2')], 'Xbox')+ with self.assertRaisesRegex(ValueError, 'newer package format'):+ self.lib.command('xbox:' + VOID, install=True)++ def test_unfinished_download_can_resume_and_takes_the_store_name(self):+ folder = self.games / SILKSONG+ folder.mkdir(parents=True)+ (folder / '.nexus-streaming-v1.jsonl').write_text('{}\n')+ svc.save_account(self.base, 'xbox', [dict(id='xbox:' + SILKSONG, platform='xbox', title='Silksong', format='MSIXVC')], 'Xbox')+ game = {g['id']: g for g in self.lib.scan()['games']}['xbox:' + SILKSONG]+ self.assertFalse(game['downloaded'])+ self.assertEqual(game['title'], 'Silksong')+ self.assertIn('resume', game['issue'])+ self.assertEqual(self.lib.command('xbox:' + SILKSONG, install=True)[-1], SILKSONG)++ def test_mismatched_or_foreign_folders_are_ignored(self):+ folder = self.downloaded()+ (folder / '.soju-xbox-install.json').write_text(json.dumps(dict(schema=1, product_id=VOID, title='x')))+ (self.games / 'not-a-store-id').mkdir()+ result = self.lib.scan()+ self.assertEqual(result['games'], [])+ self.assertTrue(any(w.startswith('xbox:') for w in result['warnings']))++ def test_missing_setup_blocks_download(self):+ (self.base / 'xbox-bottle/drive_c' / library.CLIENTS['xbox']).unlink()+ svc.save_account(self.base, 'xbox', [dict(id='xbox:' + SILKSONG, platform='xbox', title='Silksong', format='MSIXVC')], 'Xbox')+ with self.assertRaisesRegex(ValueError, 'Platforms'):+ self.lib.command('xbox:' + SILKSONG, install=True)+++class XboxDownloadTests(unittest.TestCase):+ CHOICE = dict(contentId='807c7d6a-409f-48be-8190-30b09baf7cd4', kind='Game', packageFormat='MSIXVC',+ platform='Windows.Desktop', productId=SILKSONG, supported=True, title='Silksong')++ def plan(self, status, *choices):+ return dict(schema=1, status=status, choices=list(choices))++ def test_package_choice(self):+ console = dict(self.CHOICE, platform='Windows.Xbox', packageFormat='XVC', supported=False, contentId='b6efa75d-2a92-4de8-bfc6-5d61787fa333')+ self.assertEqual(download.choose(self.plan('ready', self.CHOICE, console), SILKSONG), self.CHOICE)+ self.assertEqual(download.choose(self.plan('choice', self.CHOICE, console), SILKSONG), self.CHOICE)+ other = dict(self.CHOICE, contentId='11111111-1111-4111-8111-111111111111', title='Other')+ with self.assertRaisesRegex(download.DownloadError, 'several games'):+ download.choose(self.plan('choice', self.CHOICE, other), SILKSONG)+ with self.assertRaisesRegex(download.DownloadError, 'newer package format'):+ download.choose(self.plan('unavailable', dict(self.CHOICE, packageFormat='MSIXVC2', supported=False)), SILKSONG)+ with self.assertRaises(download.DownloadError):+ download.choose(self.plan('ready', dict(self.CHOICE, contentId='--evil')), SILKSONG)+ with self.assertRaises(download.DownloadError):+ download.choose({'schema': 2}, SILKSONG)+ with self.assertRaises(download.DownloadError):+ download.product_id('../etc')+ self.assertEqual(download.product_id('xbox:' + SILKSONG.lower()), SILKSONG)++ def run_download(self, phase):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp)+ cli = base / 'xodus-cli'+ progress = [dict(schema=1, event='progress', sequence=0, phase='initializing'),+ dict(schema=1, event='progress', sequence=1, phase='downloading', completedBytes=50, totalBytes=100,+ bytesPerSecond=10, paused=False, url='https://secret.example/token'),+ dict(schema=1, event='progress', sequence=2, phase=phase, completedBytes=100, totalBytes=100)]+ lines = ''.join("printf '%s\\n' " + repr('NEXUS_PROGRESS ' + json.dumps(p)) + '\n' for p in progress)+ plan = json.dumps(self.plan('ready', self.CHOICE))+ cli.write_text('#!/bin/sh\n[ "$1" = resolve-package ] && { printf "%s\\n" ' + repr(plan) + '; exit 0; }\n'+ '[ "$1" = streaming ] || exit 9\n' + lines + 'echo plain backend line\nexit 0\n')+ cli.chmod(0o755)+ svc.save_account(base, 'xbox', [dict(id='xbox:' + SILKSONG, platform='xbox', title='Silksong Deluxe')], 'Xbox', 'KR')+ env = dict(os.environ, SOJU_BASE=str(base), SOJU_XODUS_BIN=str(cli))+ result = subprocess.run([sys.executable, str(ROOT / 'scripts/xbox-download.py'), SILKSONG],+ env=env, capture_output=True, text=True, timeout=30)+ marker = base / 'xbox-bottle/drive_c/XboxGames' / SILKSONG / '.soju-xbox-install.json'+ return result, (json.loads(marker.read_text()) if marker.exists() else None)++ def test_marker_only_after_a_complete_download(self):+ result, marker = self.run_download('complete')+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertEqual(marker['product_id'], SILKSONG)+ self.assertEqual(marker['content_id'], self.CHOICE['contentId'])+ self.assertEqual(marker['title'], 'Silksong Deluxe')+ self.assertIn('50% · 50 B / 100 B', result.stdout)+ self.assertIn('plain backend line', result.stdout)+ self.assertNotIn('NEXUS_PROGRESS', result.stdout)+ self.assertNotIn('secret.example', result.stdout)+ result, marker = self.run_download('failed')+ self.assertEqual(result.returncode, 1)+ self.assertIsNone(marker)+ self.assertIn('resume', result.stderr)+++class XodusBackendRecipeTests(unittest.TestCase):+ def setUp(self):+ self.manifest = json.loads(backend.MANIFEST.read_text())++ def test_manifest_pins_source_toolchain_and_every_patch(self):+ m = self.manifest+ self.assertRegex(m['commit'], r'^[0-9a-f]{40}$')+ self.assertRegex(m['patch_source']['commit'], r'^[0-9a-f]{40}$')+ self.assertIn(m['patch_source']['commit'], m['patch_source']['base_url'])+ self.assertTrue(m['patch_source']['base_url'].startswith('https://raw.githubusercontent.com/'))+ self.assertRegex(m['rust'], r'^[0-9]+\.[0-9]+\.[0-9]+$')+ self.assertRegex(m['cargo_lock_sha256'], r'^[0-9a-f]{64}$')+ self.assertEqual(len(m['patches']), 44)+ self.assertEqual(len({p['file'] for p in m['patches']}), 44)+ for p in m['patches']:+ self.assertRegex(p['sha256'], r'^[0-9a-f]{64}$')+ self.assertRegex(p['file'], r'^[a-z0-9-]+\.patch$')++ def test_recipe_changes_with_any_patch(self):+ changed = json.loads(json.dumps(self.manifest))+ changed['patches'][5]['sha256'] = '0' * 64+ self.assertNotEqual(backend.recipe(self.manifest), backend.recipe(changed))++ def test_ready_backend_is_offline_and_detects_a_changed_recipe(self):+ with tempfile.TemporaryDirectory() as temp:+ target = Path(temp) / 'xodus'+ (target / 'bin').mkdir(parents=True)+ cli = target / 'bin/xodus-cli'+ cli.write_text('#!/bin/sh\nexit 0\n')+ cli.chmod(0o755)+ self.assertFalse(backend.ready(target, self.manifest))+ (target / '.soju-xodus').write_text(backend.recipe(self.manifest) + '\n')+ self.assertFalse(backend.ready(target, self.manifest)) # no binary hash recorded+ (target / '.soju-xodus').write_text(backend.recipe(self.manifest) + '\n' + backend.digest(cli) + '\n')+ self.assertTrue(backend.ready(target, self.manifest))+ cli.write_text('#!/bin/sh\nexit 0 # swapped\n')+ self.assertFalse(backend.ready(target, self.manifest))+ (target / '.soju-xodus').write_text(backend.recipe(self.manifest) + '\n' + backend.digest(cli) + '\n')+ with patch.object(backend, 'prepare_source') as prepare:+ backend.fetch(Path(temp), self.manifest)+ prepare.assert_not_called()+ changed = json.loads(json.dumps(self.manifest))+ changed['commit'] = '1' * 40+ self.assertFalse(backend.ready(target, changed))++ def test_patch_checksum_mismatch_aborts_before_build(self):+ def run(args, **kwargs):+ if args[:2] == ['git', '-c'] and 'clone' in args:+ src = Path(args[-1])+ src.mkdir()+ (src / 'Cargo.lock').write_text('lock')+ if args[0] == 'git' and 'rev-parse' in args:+ return subprocess.CompletedProcess(args, 0, self.manifest['commit'] + '\n', '')+ if args[0] == '/usr/bin/curl':+ Path(args[args.index('--output') + 1]).write_text('tampered')+ return subprocess.CompletedProcess(args, 0, '', '')+ manifest = json.loads(json.dumps(self.manifest))+ manifest['cargo_lock_sha256'] = backend.hashlib.sha256(b'lock').hexdigest()+ with tempfile.TemporaryDirectory() as temp, patch.object(backend, 'run', side_effect=run), \+ patch.object(backend, 'build') as build:+ with self.assertRaisesRegex(ValueError, 'checksum mismatch'):+ backend.fetch(Path(temp), manifest)+ build.assert_not_called()+ self.assertFalse((Path(temp) / 'xodus').exists())++ def test_wrong_commit_or_lock_aborts(self):+ def run(args, **kwargs):+ if args[:2] == ['git', '-c'] and 'clone' in args:+ Path(args[-1]).mkdir()+ (Path(args[-1]) / 'Cargo.lock').write_text('other')+ if 'rev-parse' in args:+ return subprocess.CompletedProcess(args, 0, self.manifest['commit'] + '\n', '')+ return subprocess.CompletedProcess(args, 0, '', '')+ with tempfile.TemporaryDirectory() as temp, patch.object(backend, 'run', side_effect=run):+ with self.assertRaisesRegex(ValueError, 'Cargo.lock'):+ backend.prepare_source(Path(temp), self.manifest)+++class XboxInstallerPlanTests(unittest.TestCase):+ def test_xbox_needs_the_backend_and_the_cx_engine(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp) / 'untouched'+ result = subprocess.run(['/bin/bash', str(ROOT / 'install.sh'), '--plan'],+ env={**os.environ, 'SOJU_PLATFORMS': 'xbox', 'SOJU_BASE': str(base)},+ capture_output=True, text=True)+ self.assertFalse(base.exists())+ self.assertEqual(result.returncode, 0, result.stderr)+ # Games run on the CX engine with D3DMetal, so Xbox needs those too.+ for line in ('cx_engine=1', 'apple_gptk=1', 'steam_runtime=0', 'xodus_backend=1'):+ self.assertIn(line, result.stdout)++ def test_cli_lists_xbox_commands(self):+ result = subprocess.run(['/bin/bash', str(ROOT / 'scripts/soju'), '--help'], capture_output=True, text=True)+ for command in ('xbox-install', 'xbox-login', 'xbox-sync', 'xbox-download', 'xbox-logout'):+ self.assertIn(command, result.stdout)+ bad = subprocess.run(['/bin/bash', str(ROOT / 'scripts/soju'), 'xbox-sync', 'XX'], capture_output=True, text=True)+ self.assertEqual(bad.returncode, 64)+++class XboxLaunchTests(unittest.TestCase):+ def test_executable_comes_from_the_package_manifest(self):+ with tempfile.TemporaryDirectory() as temp:+ folder = Path(temp)+ (folder / 'microsoftgame.config').write_text(+ '<?xml version="1.0"?><Game configVersion="1"><ExecutableList>'+ '<Executable Name="Binaries\\Win64\\Game.exe" Id="Game"/></ExecutableList></Game>')+ self.assertEqual(runner.executable(folder), 'Binaries\\Win64\\Game.exe')+ (folder / 'microsoftgame.config').write_text('<Game><Executable Name="..\\..\\evil.exe"/></Game>')+ with self.assertRaises(runner.LaunchError):+ runner.executable(folder)+ (folder / 'microsoftgame.config').unlink()+ (folder / 'AppxManifest.xml').write_text(+ '<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">'+ '<Applications><Application Id="App" Executable="Game.exe"/></Applications></Package>')+ self.assertEqual(runner.executable(folder), 'Game.exe')++ def test_bridge_requires_the_key_and_relays_to_the_service_socket(self):+ import socket, threading+ directory = tempfile.mkdtemp(prefix='sx', dir='/tmp')+ self.addCleanup(lambda: __import__('shutil').rmtree(directory, ignore_errors=True))+ path = directory + '/s.sock'+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ server.bind(path)+ server.listen(4)+ def echo():+ while True:+ try:+ conn, _ = server.accept()+ except OSError:+ return+ data = conn.recv(100)+ conn.sendall(b'echo:' + data)+ conn.close()+ threading.Thread(target=echo, daemon=True).start()+ bridge = runner.Bridge(path)+ self.addCleanup(bridge.close)+ self.addCleanup(server.close)+ with socket.create_connection(('127.0.0.1', bridge.port), timeout=5) as client:+ client.sendall(bridge.key + b'hello')+ self.assertEqual(client.recv(100), b'echo:hello')+ with socket.create_connection(('127.0.0.1', bridge.port), timeout=5) as client:+ client.sendall(b'0' * len(bridge.key) + b'hello')+ try:+ answer = client.recv(100)+ except ConnectionResetError:+ answer = b''+ self.assertEqual(answer, b'') # closed, nothing relayed++ def test_runtime_dlls_lose_the_builtin_marker(self):+ with tempfile.TemporaryDirectory() as temp, patch.object(prefix, 'RUNTIME', Path(temp) / 'rt'), \+ patch.object(prefix, 'PREFIX', Path(temp) / 'pfx'):+ (Path(temp) / 'rt').mkdir()+ dll = bytearray(200)+ dll[64:80] = prefix.BUILTIN+ (Path(temp) / 'rt/xgameruntime.dll').write_bytes(bytes(dll))+ prefix.install_dlls(['xgameruntime.dll'])+ copied = (Path(temp) / 'pfx/drive_c/windows/system32/xgameruntime.dll').read_bytes()+ self.assertEqual(copied[64:80], bytes(16))+ self.assertEqual(len(copied), 200)++ def test_prefix_settings_cover_every_runtime_dll(self):+ names = json.loads((ROOT / 'resources/xbox-runtime.json').read_text())['dlls']+ values = {args[4] for args in prefix.overrides(names) if args[2].endswith('DllOverrides')}+ self.assertEqual(values, {n[:-4] for n in names} | {'concrt140'})+ self.assertTrue(any('GamingServices' in args[2] for args in prefix.overrides(names)))++ def test_runtime_manifest_pins_every_download(self):+ m = json.loads((ROOT / 'resources/xbox-runtime.json').read_text())+ for source in (m['macxus'], m['nexus']):+ self.assertTrue(source['url'].startswith('https://github.com/'))+ self.assertRegex(source['sha256'], r'^[0-9a-f]{64}$')+ self.assertGreater(source['size'], 0)+ self.assertEqual(len(m['dlls']), 6)+ for value in m['dlls'].values():+ self.assertRegex(value, r'^[0-9a-f]{64}$')++ def test_asar_reader_returns_only_the_requested_folder(self):+ import struct+ files = {'a.dll': b'AAAA', 'b.txt': b'BB'}+ offsets, body = {}, b''+ for name, data in files.items():+ offsets[name] = dict(size=len(data), offset=str(len(body)))+ body += data+ header = json.dumps({'files': {'assets': {'files': {'dlls': {'files': offsets}}},+ 'other': {'files': {}}}}).encode()+ pickle = struct.pack('<II', len(header) + 4, len(header)) + header+ with tempfile.TemporaryDirectory() as temp:+ path = Path(temp) / 'app.asar'+ path.write_bytes(struct.pack('<II', 4, len(pickle)) + pickle + body)+ self.assertEqual(runtime.asar_files(path, 'assets/dlls'), files)+++class XboxReviewRegressionTests(unittest.TestCase):+ GAME = dict(contentId='807c7d6a-409f-48be-8190-30b09baf7cd4', kind='Game', packageFormat='MSIXVC',+ platform='Windows.Desktop', supported=True, title='Game')+ ADDON = dict(GAME, contentId='11111111-1111-4111-8111-111111111111', kind='GameAddOn', title='Soundtrack')++ def test_edition_downloads_the_game_not_its_add_on(self):+ plan = dict(schema=1, status='choice', choices=[self.GAME, self.ADDON])+ self.assertEqual(download.choose(plan, SILKSONG)['kind'], 'Game')++ def test_add_on_is_never_downloaded_as_the_game(self):+ base = dict(self.GAME, packageFormat='MSIXVC2', supported=False)+ plan = dict(schema=1, status='choice', choices=[base, self.ADDON])+ with self.assertRaisesRegex(download.DownloadError, 'newer package format'):+ download.choose(plan, SILKSONG)++ def test_seven_digit_fractions_parse_on_every_python(self):+ self.assertEqual(svc.entitlement_end('9999-12-31T23:59:59.9999999Z').year, 9999)+ self.assertEqual(svc.entitlement_end('2026-11-30T00:00:00Z').month, 11)++ def test_only_subscriptions_mark_game_pass(self):+ self.assertTrue(svc.SUBSCRIPTION.fullmatch('CFQ7TTC0KGQ8'))+ self.assertIsNone(svc.SUBSCRIPTION.fullmatch('9NBLGGH4R315'))++ def test_folder_lock_reports_a_running_download(self):+ with tempfile.TemporaryDirectory() as temp:+ cli = Path(temp) / 'xodus-cli'+ cli.write_text('#!/bin/sh\necho "another download is using this folder" >&2\nexit 1\n')+ cli.chmod(0o755)+ with patch.object(download, 'CLI', str(cli)):+ with self.assertRaisesRegex(download.DownloadError, 'already downloading'):+ download.stream(SILKSONG, self.GAME, 'US', Path(temp))++++class XboxStopAndSignOutTests(unittest.TestCase):+ """Sign-out without a backend, stopping downloads and setup, no e-mail in logs."""++ def xbox_sh(self, base, *args, cli=None):+ env = {k: v for k, v in os.environ.items() if k != 'SOJU_XODUS_BIN'}+ env['SOJU_BASE'] = str(base)+ if cli:+ env['SOJU_XODUS_BIN'] = str(cli)+ return subprocess.run(['/bin/bash', str(ROOT / 'scripts/xbox.sh'), *args], env=env,+ capture_output=True, text=True, timeout=30)++ def test_sign_out_works_without_a_backend(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp)+ (base / 'account-libraries').mkdir()+ (base / 'account-libraries/xbox.json').write_text('{}')+ (base / 'library-artwork').mkdir()+ (base / 'library-artwork/xbox-9N116V0599HB.jpg').write_bytes(b'jpg')+ (base / 'library-artwork/steam-1.jpg').write_bytes(b'jpg')+ result = self.xbox_sh(base, 'logout')+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertFalse((base / 'account-libraries/xbox.json').exists())+ self.assertFalse((base / 'library-artwork/xbox-9N116V0599HB.jpg').exists())+ self.assertTrue((base / 'library-artwork/steam-1.jpg').exists())++ def test_kill_stops_a_recorded_download_only(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp); run = base / 'run'; run.mkdir()+ fake = base / 'xbox-download.py'+ fake.write_text('import signal, sys, time\n'+ 'signal.signal(signal.SIGTERM, lambda *a: sys.exit(130))\n'+ 'print("ready", flush=True)\n'+ 'time.sleep(30)\n')+ other = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])+ child = subprocess.Popen([sys.executable, str(fake)], stdout=subprocess.PIPE, text=True)+ try:+ # The handler is installed before "ready", so TERM cannot hit the default action.+ self.assertEqual(child.stdout.readline().strip(), 'ready')+ (run / ('xbox-dl-' + str(child.pid) + '.pid')).write_text(str(child.pid))+ (run / ('xbox-dl-' + str(other.pid) + '.pid')).write_text(str(other.pid))+ result = self.xbox_sh(base, 'kill')+ self.assertIn('Download stopped', result.stdout)+ self.assertEqual(child.wait(timeout=10), 130)+ self.assertIsNone(other.poll(), 'a pid that is not a Soju download must be left alone')+ finally:+ for p in (child, other):+ if p.poll() is None:+ p.kill()+ p.wait()++ def test_kill_reports_when_nothing_runs(self):+ with tempfile.TemporaryDirectory() as temp:+ result = self.xbox_sh(Path(temp), 'kill')+ self.assertEqual(result.returncode, 0)+ self.assertIn('No Xbox download or game is running', result.stdout)++ def test_download_records_and_removes_its_pid(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp)+ with patch.object(download, 'BASE', base), patch.object(sys, 'argv', ['x', 'bad id']):+ self.assertEqual(download.main(), 1)+ self.assertTrue((base / 'run').is_dir())+ self.assertEqual(list((base / 'run').iterdir()), [])+ self.assertIn("'xbox-dl-'", (ROOT / 'scripts/xbox-download.py').read_text())++ def test_logs_never_show_an_e_mail(self):+ for clean in (download.clean, runner.clean):+ line = clean('Signed in as [email protected] via https://login.example/?t=secret')+ self.assertNotIn('[email protected]', line)+ self.assertNotIn('secret', line)+ self.assertIn('<account>', line)+ script = (ROOT / 'scripts/xbox.sh').read_text()+ self.assertIn('<account>', script)++ def test_failed_keychain_sign_out_still_removes_the_import(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp)+ (base / 'account-libraries').mkdir()+ (base / 'account-libraries/xbox.json').write_text('{}')+ cli = base / 'xodus-cli'+ cli.write_text('#!/bin/sh\n[ "$1" = --version ] && exit 0\n[ "$1" = logout ] && exit 1\nexit 9\n')+ cli.chmod(0o755)+ result = self.xbox_sh(base, 'logout', cli=cli)+ self.assertEqual(result.returncode, 2, result.stdout + result.stderr)+ self.assertIn('Keychain', result.stderr)+ self.assertFalse((base / 'account-libraries/xbox.json').exists())++ def test_closed_sign_in_window_reports_not_completed(self):+ with tempfile.TemporaryDirectory() as temp:+ base = Path(temp)+ cli = base / 'xodus-cli'+ cli.write_text('#!/bin/sh\ncase "$1" in login) exit 1 ;; account) echo \'{"stored": false}\' ;; esac\n')+ cli.chmod(0o755)+ result = self.xbox_sh(base, 'login', cli=cli)+ self.assertEqual(result.returncode, 1)+ self.assertIn('Sign-in was not completed', result.stderr)++ def test_stop_during_first_launch_setup_ends_the_setup(self):+ with tempfile.TemporaryDirectory() as temp:+ root = Path(temp) / 'repo'+ (root / 'scripts').mkdir(parents=True)+ (root / 'scripts/xbox-run.py').write_text((ROOT / 'scripts/xbox-run.py').read_text())+ # Stand-in for xbox-prefix.py: a long download running in a child process.+ (root / 'scripts/xbox-prefix.py').write_text(+ 'import subprocess, sys\n'+ 'child = subprocess.Popen(["/bin/sleep", "60"])\n'+ 'open(sys.argv[0] + ".pid", "w").write(str(child.pid))\n'+ 'print("ready", flush=True)\n'+ 'child.wait()\n')+ base = Path(temp) / 'base'+ game = base / 'xbox-bottle/drive_c/XboxGames' / SILKSONG+ game.mkdir(parents=True)+ (game / '.soju-xbox-install.json').write_text('{"title": "Test"}')+ (game / '.xodus-streaming.msixvc').write_bytes(b'')+ (game / 'MicrosoftGame.config').write_text(+ '<Game><ExecutableList><Executable Name="game.exe"/></ExecutableList></Game>')+ env = dict(os.environ, SOJU_BASE=str(base), SOJU_XODUS_BIN='/usr/bin/false')+ run = subprocess.Popen([sys.executable, str(root / 'scripts/xbox-run.py'), SILKSONG], env=env,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ try:+ self.assertEqual(run.stdout.readline().strip(), 'ready', run.stderr.read() if run.poll() is not None else '')+ helper = int(Path(str(root / 'scripts/xbox-prefix.py') + '.pid').read_text())+ run.terminate()+ self.assertEqual(run.wait(timeout=20), 130)+ for _ in range(50):+ try:+ os.kill(helper, 0)+ except ProcessLookupError:+ break+ time.sleep(0.1)+ else:+ os.kill(helper, 9)+ self.fail('first-launch setup kept running after Stop')+ finally:+ if run.poll() is None:+ run.kill()+ run.wait()+ run.stdout.close()+ run.stderr.close()++ def test_stop_during_setup_reaches_the_prefix_process_group(self):+ source = (ROOT / 'scripts/xbox-run.py').read_text()+ self.assertIn('start_new_session=True', source)+ self.assertIn('os.killpg(prep.pid, signal.SIGTERM)', source)+ self.assertNotIn("subprocess.run([sys.executable, str(ROOT / 'scripts/xbox-prefix.py')]", source)++ def test_engine_hint_matches_the_installer(self):+ for name in ('xbox-prefix.py', 'game-library.py', 'xbox.sh'):+ self.assertNotIn('Install Battle.net, Epic or GOG', (ROOT / 'scripts' / name).read_text(), name)+ self.assertNotIn('install Battle.net, Epic or GOG', (ROOT / 'scripts' / name).read_text(), name)+++if __name__ == '__main__':+ unittest.main()