Skip to content

armgit / soju

Public Imported from GitHub
0

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.

Fix Steam installation and library import in v1.6.4 (#38)

Mikeka55313972ee4
diff --git a/NOTICE b/NOTICE
index 65bef3b36fe..1464ff96fe2 100644
--- a/NOTICE
+++ b/NOTICE
@@ -9,6 +9,9 @@ Bundled in this repository:
Built or downloaded by the scripts (open-source component releases include corresponding sources):
- Wine 11.0: LGPL-2.1+ / GPL components, built from CodeWeavers' published sources
(media.codeweavers.com/pub/crossover/source/)
+- Steam Wine 11.0_1: upstream build by Gcenx (Wine LGPL-2.1+ / GPL components),
+ downloaded unchanged from github.com/Gcenx/macOS_Wine_builds/releases/tag/11.0_1;
+ pinned URL and checksum in resources/steam-wine.json
- DXMT pinned notpop fork: MIT, Copyright (c) 2023 Feifan He
(built from the notpop fork of github.com/3Shain/dxmt)
- wine-mono: MIT (dotnet parts MIT/BSD-like); MoltenVK: Apache-2.0; gnutls: LGPL-2.1+;
diff --git a/README.md b/README.md
index 9f74a0c2188..8a00a39f734 100644
--- a/README.md
+++ b/README.md
@@ -20,11 +20,11 @@ Epic and Battle.net account imports are not included yet. Compatibility varies b
[Account connections and store search](docs/ACCOUNTS.md) · Official Steam sign-in, no API key required. Account imports stay on your Mac.
The tools are free and open source. The main Wine engine is built from
-CodeWeavers' published sources; Steam uses a separate wine-stable setup.
+CodeWeavers' published sources; Steam uses a separate private Wine 11 setup.
Apple's proprietary GPTK/D3DMetal is downloaded separately. Games and store
clients are not included.
-**Current release: [v1.6.3](https://github.com/BCD1210/soju/releases/tag/v1.6.3).**
+**Current release: [v1.6.4](https://github.com/BCD1210/soju/releases/tag/v1.6.4).**
The compatibility examples below were verified on M4 Pro / macOS 26.5.
D2R and Hogwarts Legacy are examples of supported games, not the scope of the project.
@@ -52,7 +52,7 @@ All verified on an M4 Pro running macOS 26.5. Separate bottles for each launcher
| Battle.net | ✅ | ✅ | Agent works; `BLZBNTBNA00000005` fixed by the caller-signature seed |
| Epic Games Launcher | ✅ | ✅ | parks in the menu bar tray on close |
| GOG GALAXY | ✅ | ✅ | login + library; games not broadly tested yet |
-| Steam (Windows client) | ✅ | ✅ | separate `wine-stable` + DXMT bottle |
+| Steam (Windows client) | ✅ | ✅ | private Wine 11 + DXMT bottle |
| Game | Store | Graphics | Status | Notes |
| --- | --- | --- | :-: | --- |
@@ -94,7 +94,7 @@ soju install # then: soju battlenet / soju d2r / soju steam / soju epic / so
The installer asks which launchers you want **before downloading anything**. Steam-only installs skip the CX engine and Apple GPTK. Steam rendering components are downloaded with SHA-256 verification and installed in a Soju-owned Wine 11.0 runtime. Battle.net, Epic and GOG use the shared CX engine and your separately downloaded Apple GPTK. Each official client keeps its own bottle and shortcut in `~/Applications`.
-[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.6.3/Soju-1.6.3-macos-arm64.zip) — the native desktop preview includes installed and owned games, store search, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).
+[Download Soju for Mac](https://github.com/BCD1210/soju/releases/download/v1.6.4/Soju-1.6.4-macos-arm64.zip) — the native desktop preview includes installed and owned games, store search, favorites, game launching and platform management. See [desktop setup and requirements](docs/DESKTOP.md).
## Everyday commands
@@ -161,10 +161,10 @@ Games have not been broadly tested yet; anything that needs kernel anti-cheat (E
## 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 Homebrew's `wine-stable` 11 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:
+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:
```bash
-scripts/create-steam-bottle.sh # installs wine-stable + wrapper + official Valve installer
+scripts/create-steam-bottle.sh # installs private Wine 11 + wrapper + official Valve installer
scripts/play.sh steam # log in -> install & play
scripts/play.sh steam-kill # stop the Steam bottle (closing the window keeps Steam running; click the Dock icon to bring it back, Steam > Exit quits)
```
diff --git a/VERSION b/VERSION
index 266146b87cb..9edc58bb1dd 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.6.3
+1.6.4
diff --git a/app/Accounts.swift b/app/Accounts.swift
index 3fb9fe3b4af..7c79112b836 100644
--- a/app/Accounts.swift
+++ b/app/Accounts.swift
@@ -139,12 +139,12 @@ struct AccountsView: View {
GroupBox {
VStack(alignment: .leading, spacing: 12) {
accountHeader(.steam)
- Text("Sign in on Steam’s official page to import your games. No API key or profile URL is needed.")
+ Text("Sign in below to import your owned games. You do not need to install Windows Steam first.")
.font(.callout).foregroundStyle(.secondary)
Text("Steam handles your password, QR sign-in and Steam Guard. Your web session stays on this Mac.")
.font(.caption).foregroundStyle(.secondary)
HStack {
- Button("Open Steam") { model.launch(.steam) }.disabled(model.busy)
+ Button("Open Windows Steam") { model.launch(.steam) }.disabled(model.busy || !model.installed.contains(.steam))
if summary(.steam) == nil {
Button("Clear saved sign-in") { model.forgetAccount(.steam) }.disabled(model.accountBusy)
}
diff --git a/app/Library.swift b/app/Library.swift
index 02ea61caf98..d3b9df56828 100644
--- a/app/Library.swift
+++ b/app/Library.swift
@@ -83,8 +83,9 @@ extension SojuModel {
}
if game.platform == .steam {
let local = base.appendingPathComponent("steam-runtime/bin/wine").path
+ let upstream = base.appendingPathComponent("steam-wine/bin/wine").path
let stable = "/Applications/Wine Stable.app/Contents/Resources/wine/bin/wine"
- if !FileManager.default.isExecutableFile(atPath: local) && !FileManager.default.isExecutableFile(atPath: stable) {
+ if !FileManager.default.isExecutableFile(atPath: local) && !FileManager.default.isExecutableFile(atPath: upstream) && !FileManager.default.isExecutableFile(atPath: stable) {
return "Install Steam in Platforms to prepare its Windows environment."
}
} else {
diff --git a/app/SteamLogin.swift b/app/SteamLogin.swift
index 44ba7d6332d..2bde715ed04 100644
--- a/app/SteamLogin.swift
+++ b/app/SteamLogin.swift
@@ -20,6 +20,7 @@ enum SteamWebSession {
private var generation = UUID()
private var readingGeneration: UUID?
private var openedLibrary = false
+ private var failures = 0
private var active = true
init(root: URL) {
@@ -34,11 +35,18 @@ enum SteamWebSession {
}
func start(completion: @escaping ([String: Any]) -> Void) {
guard complete == nil else { return }
+ guard !reader.isEmpty else { message = "Steam import files are missing. Reinstall the latest Soju app."; return }
complete = completion
web.load(URLRequest(url: URL(string: "https://steamcommunity.com/login/home/?goto=my%2Fgames%2F%3Ftab%3Dall")!))
- timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { [weak self] _ in
+ startPolling()
+ }
+ private func startPolling() {
+ timer?.invalidate()
+ let poll = Timer(timeInterval: 3, repeats: true) { [weak self] _ in
Task { @MainActor in self?.checkLibrary() }
}
+ timer = poll
+ RunLoop.main.add(poll, forMode: .common)
}
func stop() {
active = false; generation = UUID(); complete = nil
@@ -46,7 +54,8 @@ enum SteamWebSession {
web.stopLoading()
}
func retry() {
- openedLibrary = false
+ openedLibrary = false; failures = 0
+ startPolling()
message = "Loading your Steam library…"
web.load(URLRequest(url: URL(string: "https://steamcommunity.com/my/games/?tab=all")!))
}
@@ -85,6 +94,11 @@ enum SteamWebSession {
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if (error as NSError).code != NSURLErrorCancelled { message = "Steam could not load. Check your connection and retry." }
}
+ private func importFailed() {
+ failures += 1
+ message = "Steam’s game list could not be read yet. Let the page load or choose Retry import. Your previous library is kept."
+ if failures >= 5 { timer?.invalidate(); timer = nil }
+ }
private func checkLibrary() {
guard active, !web.isLoading, readingGeneration == nil, !reader.isEmpty,
allowed(web.url), ["steamcommunity.com", "store.steampowered.com"].contains(web.url?.host ?? "") else { return }
@@ -93,7 +107,9 @@ enum SteamWebSession {
web.callAsyncJavaScript(reader, arguments: [:], in: nil, in: .page) { [weak self] result in
guard let self, self.active, self.generation == current else { return }
self.readingGeneration = nil
- guard case .success(let raw) = result, let value = raw as? [String: Any], let state = value["state"] as? String else { return }
+ guard case .success(let raw) = result, let value = raw as? [String: Any], let state = value["state"] as? String else {
+ self.importFailed(); return
+ }
switch state {
case "ready":
self.reading = true; self.message = "Importing your games…"
@@ -107,8 +123,9 @@ enum SteamWebSession {
self.web.load(URLRequest(url: URL(string: "https://steamcommunity.com/my/games/?tab=all")!))
} else { self.message = "Let your All Games page load, then choose Retry import if needed." }
case "unavailable":
- self.message = "Steam could not share a complete library. Retry import after the page loads. Your previous import is kept."
- self.timer?.invalidate(); self.timer = nil
+ self.importFailed()
+ case "sign-in":
+ self.message = "Finish signing in on Steam’s page. Your games will import automatically; installing Windows Steam is not required."
default: break
}
}
diff --git a/docs/DESKTOP.md b/docs/DESKTOP.md
index 6e991599a40..910301c261c 100644
--- a/docs/DESKTOP.md
+++ b/docs/DESKTOP.md
@@ -1,6 +1,6 @@
# Soju for Mac
-[Download v1.6.3](https://github.com/BCD1210/soju/releases/download/v1.6.3/Soju-1.6.3-macos-arm64.zip)
+[Download v1.6.4](https://github.com/BCD1210/soju/releases/download/v1.6.4/Soju-1.6.4-macos-arm64.zip)
1. Unzip and move **Soju.app** into Applications or ~/Applications.
2. Open **Platforms** to install or open Battle.net, Steam, Epic Games or GOG GALAXY.
@@ -24,12 +24,13 @@ Soju does not collect telemetry or upload diagnostic logs. Copy log is manual.
## Requirements
- Apple Silicon; the app UI runs on macOS 14 or later.
-- Rosetta 2, Apple's Command Line Tools and Homebrew for launcher installation.
+- Rosetta 2 and Python 3 (available with Apple's Command Line Tools) for launcher installation.
- The current Steam rendering package requires **macOS 26+ and Wine 11.0**.
It was verified on M4 Pro / macOS 26.5. D3D11 support is not a guarantee that
every game works; anti-cheat and individual game requirements still apply.
- Battle.net, Epic and GOG use the CX engine and a separate Apple GPTK download.
- Steam does not need either.
+ Steam does not need either. Its Wine runtime downloads directly from the upstream
+ release and is verified with a pinned SHA-256; no Homebrew Wine cask is needed.
For Apple GPTK, install the selected non-Steam launcher to prepare the engine,
download Apple's evaluation environment, open its DMG, then choose
@@ -48,7 +49,10 @@ This release detects games installed in Soju's four Windows environments:
- Battle.net: Agent's product database and installed game build records.
- GOG: Galaxy's installation database, with a fallback for standard game folders.
-Steam account imports use the official Steam website sign-in; no personal API key is needed. GOG imports
+Steam account imports use **Accounts → Sign in to Steam**; Windows Steam does not
+need to be installed first. After sign-in, the owned library imports automatically.
+If Steam has not finished loading, use **Retry import**. A failed import keeps the
+previous library. No personal API key is needed. GOG imports
read the owned library cached by Galaxy on this Mac. Both include uninstalled
games. **Accounts → Disconnect** removes the import and Soju’s saved Steam web session.
@@ -86,7 +90,8 @@ searches Steam and GOG without an account.
components. Get new app releases from the link at the bottom of the sidebar or Platforms → Project & releases.
The app does not replace itself automatically.
-Steam uses `~/.battlenet-macos/steam-runtime`; Homebrew's Wine app is preserved.
+Steam uses `~/.battlenet-macos/steam-runtime`; the pinned upstream download is stored
+in `~/.battlenet-macos/steam-wine`. Any existing Wine app is preserved.
Existing Steam users can migrate with `soju steam-games` after closing Steam.
The installer retains the previous private runtime and a dated prefix settings
backup. Failed setup restores the prefix settings automatically.
diff --git a/docs/STEAM-GAMES.md b/docs/STEAM-GAMES.md
index 2d7c3563f25..e994028649c 100644
--- a/docs/STEAM-GAMES.md
+++ b/docs/STEAM-GAMES.md
@@ -10,7 +10,7 @@ free software.
The modern Steam client's CEF UI does not render on CrossOver-source builds:
the GPU process crash-loops (sandbox faults, 0xC0000005), and DXMT's
cross-process swapchain limit ([DXMT #141](https://github.com/3Shain/dxmt/issues/141))
-blacks out the composer. Homebrew's `wine-stable` 11 cask works once the
+blacks out the composer. The pinned upstream Wine 11 build works once the
steamwebhelper wrapper forces `--disable-gpu --single-process`
(from [notpop/steam-on-m1-wine](https://github.com/notpop/steam-on-m1-wine), MIT,
vendored in `third_party/`).
@@ -87,7 +87,7 @@ Artifacts land in `~/.battlenet-macos/steam-support/` and
## Runbook
```bash
-scripts/create-steam-bottle.sh # wine-stable + wrapper + Steam
+scripts/create-steam-bottle.sh # private Wine 11 + wrapper + Steam
scripts/setup-steam-games.sh # verified download + private DXMT/winemac runtime
scripts/play.sh steam # play
```
diff --git a/docs/guides/steam-windows-client-apple-silicon.html b/docs/guides/steam-windows-client-apple-silicon.html
index 67ef1bb345b..99466f1aa5b 100644
--- a/docs/guides/steam-windows-client-apple-silicon.html
+++ b/docs/guides/steam-windows-client-apple-silicon.html
@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Run the Windows Steam client on Apple Silicon Macs (free, 2026)</title>
-<meta name="description" content="How to run the Windows Steam client and D3D11 games on M1/M2/M3/M4 Macs for free: wine-stable + a steamwebhelper wrapper + DXMT, with the black-screen and rendering problems actually explained.">
+<meta name="description" content="How to run the Windows Steam client and D3D11 games on M1/M2/M3/M4 Macs for free: Wine 11 + a steamwebhelper wrapper + DXMT, with the black-screen and rendering problems actually explained.">
<link rel="canonical" href="https://bcd1210.github.io/soju/guides/steam-windows-client-apple-silicon.html">
<meta property="og:title" content="Windows Steam client on Apple Silicon: the working free setup">
<meta property="og:description" content="Steam client login, library and D3D11 in-game rendering on M-series Macs, fully free.">
@@ -31,7 +31,7 @@ Windows client.</div>
<h2>The quick version</h2>
<pre><code>brew install BCD1210/soju/soju
-soju steam-install # wine-stable + wrapper + Steam
+soju steam-install # private Wine 11 + wrapper + Steam
soju steam # log in and play
soju steam-games # optional: wire DXMT so D3D11 games render</code></pre>
diff --git a/docs/index.html b/docs/index.html
index fe6cf3eb95d..fa9dd1e5bf3 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -102,7 +102,7 @@ its own login, purchases, downloads and game updates.</p>
<section id="install" aria-labelledby="install-title">
<h2 id="install-title">Choose your launchers. Get set up.</h2>
-<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.6.3/Soju-1.6.3-macos-arm64.zip">Download Soju for Mac</a></p>
+<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.6.4/Soju-1.6.4-macos-arm64.zip">Download Soju for Mac</a></p>
<p>The native desktop preview combines installed and imported owned games, searches stores and manages all four launchers.
Apple Silicon · app UI: macOS 14+ · Steam component build: macOS 26+.
<a href="https://github.com/BCD1210/soju/blob/main/docs/DESKTOP.md">Setup and signing notes</a>.</p>
@@ -162,7 +162,7 @@ game, store, Mac, macOS and setup. GitHub sign-in required; reports are public.<
<p>Soju's scripts and documentation are open source. Its Wine engine is built from
<a href="https://www.codeweavers.com/crossover/source">CodeWeavers' published sources</a>.
Battle.net, Epic and GOG share that engine; Steam uses a separate
-<code>wine-stable</code> setup with DXMT for supported D3D11 games.</p>
+private Wine 11 setup with DXMT for supported D3D11 games.</p>
<p>Apple's proprietary D3DMetal/GPTK components are a separate download, and the
store clients remain their publishers' software. Soju does not bundle them.</p>
<p>The <a href="https://github.com/BCD1210/soju/blob/main/docs/DIAGNOSIS.md">diagnosis notes</a>
diff --git a/install.sh b/install.sh
index ee4a3cb5751..45bf5279c53 100644
--- a/install.sh
+++ b/install.sh
@@ -27,7 +27,7 @@ else
say "[1/4] Which launchers do you want? (numbers separated by spaces, Enter = Battle.net only)"
cat <<'EOT'
1) Battle.net (Diablo II: Resurrected etc.)
- 2) Steam (Windows client on Homebrew wine-stable, D3D11 games via DXMT)
+ 2) Steam (Windows client on private Wine 11, D3D11 games via DXMT)
3) Epic Games Launcher
4) GOG GALAXY
EOT
@@ -202,7 +202,7 @@ for p in $PLATFORMS; do
if [ -f "$BASE/steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe" ]; then
say "Steam already installed - skipping"
else
- say "Steam: Homebrew wine-stable + Steam installer"
+ say "Steam: verified Wine runtime + Steam installer"
WINEPREFIX="$BASE/steam-bottle" bash "$SOJU_DIR/scripts/create-steam-bottle.sh"
fi
WINEPREFIX="$BASE/steam-bottle" bash "$SOJU_DIR/scripts/setup-steam-games.sh" ;;
diff --git a/resources/steam-library.js b/resources/steam-library.js
index bf2ad334762..626994730ac 100644
--- a/resources/steam-library.js
+++ b/resources/steam-library.js
@@ -1,4 +1,4 @@
-// Runs only inside the signed-in user's Steam page. No cookies or tokens leave WebKit.
+// Runs only inside the user's official Steam page. Sessions never leave WebKit.
if (location.protocol !== "https:" || !["steamcommunity.com", "store.steampowered.com"].includes(location.hostname)) {
return { state: "wrong-page" };
}
@@ -7,9 +7,11 @@ const attribute = name => {
try { return JSON.parse(config?.getAttribute(name) || "{}"); } catch { return {}; }
};
const user = attribute("data-userinfo");
-const steamid = String(window.g_steamID || user.steamid || "");
-if (!/^765[0-9]{14}$/.test(steamid)) return { state: "sign-in" };
-if (user.steamid && String(user.steamid) !== steamid) return { state: "unavailable" };
+const validID = value => /^765[0-9]{14}$/.test(String(value || ""));
+let steamid = String(window.g_steamID || user.steamid || "");
+if (validID(user.steamid) && validID(steamid) && String(user.steamid) !== steamid) {
+ return { state: "unavailable" };
+}
function snapshot(rows, count) {
if (!Array.isArray(rows) || !Number.isInteger(count) || count < 0 ||
@@ -29,33 +31,56 @@ function snapshot(rows, count) {
return { state: "ready", steamid, game_count: games.length, games };
}
-// The full All Games page carries names for unavailable/delisted titles as well.
+// Legacy All Games pages do not consistently include application_config or a
+// webapi_token. Read their complete list only when its owner matches this session.
const profile = String(window.g_rgProfileData?.steamid || "");
-if (location.hostname === "steamcommunity.com" && /\/games\/?$/.test(location.pathname) &&
- new URLSearchParams(location.search).get("tab") === "all" &&
- profile === steamid && Array.isArray(window.rgGames)) {
- return snapshot(window.rgGames, window.rgGames.length);
+const ownAllGames = () => validID(steamid) && location.hostname === "steamcommunity.com" &&
+ /\/games\/?$/.test(location.pathname) &&
+ new URLSearchParams(location.search).get("tab") === "all" && profile === steamid &&
+ Array.isArray(window.rgGames);
+if (ownAllGames()) return snapshot(window.rgGames, window.rgGames.length);
+if (validID(steamid) && validID(profile) && !ownAllGames() && !user.webapi_token) {
+ return { state: "open-library" };
}
+const signedInPage = !!document.querySelector?.("#account_pulldown");
-// Modern Steam pages use the website's own authenticated Web API session.
-// Keep it within this page's JS context; return only game IDs and names to Soju.
-const token = user.webapi_token;
-if (user.logged_in !== true || typeof token !== "string" || !token) return { state: "open-library" };
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 20000);
+async function readJSON(url, credentials, limit) {
+ const response = await fetch(url, {
+ signal: controller.signal, redirect: "error", credentials, cache: "no-store"
+ });
+ if (!response.ok) throw Error("request failed");
+ const raw = await response.text();
+ if (raw.length > limit) throw Error("response too large");
+ return JSON.parse(raw);
+}
try {
+ let token = user.logged_in === true && typeof user.webapi_token === "string" ? user.webapi_token : "";
+ // Steam's legacy community pages can omit both identity and the token.
+ // Ask Steam's own session endpoint on the same origin; do not scrape cookies.
+ const loginPage = /^\/(login|openid)(\/|$)/.test(location.pathname);
+ if (!token && location.hostname === "steamcommunity.com" && !loginPage &&
+ (validID(steamid) || user.logged_in === true || signedInPage)) {
+ const session = await readJSON("https://steamcommunity.com/chat/clientjstoken", "same-origin", 64 * 1024);
+ if (session.logged_in !== true || !validID(session.steamid)) {
+ return { state: validID(steamid) ? "open-library" : "sign-in" };
+ }
+ if (validID(steamid) && steamid !== String(session.steamid)) return { state: "unavailable" };
+ steamid = String(session.steamid);
+ if (ownAllGames()) return snapshot(window.rgGames, window.rgGames.length);
+ token = typeof session.token === "string" ? session.token : "";
+ }
+ if (!validID(steamid)) return { state: "sign-in" };
+ if (!token) return { state: "open-library" };
const params = new URLSearchParams({
access_token: token,
input_json: JSON.stringify({ steamid, include_appinfo: true, include_played_free_games: true })
});
- const response = await fetch("https://api.steampowered.com/IPlayerService/GetOwnedGames/v1/?" + params, {
- signal: controller.signal, redirect: "error", credentials: "omit", cache: "no-store"
- });
- if (!response.ok) return { state: "unavailable" };
- const raw = await response.text();
- if (raw.length > 8 * 1024 * 1024) return { state: "unavailable" };
- const value = JSON.parse(raw).response;
- if (!value || !Object.hasOwn(value, "game_count")) return { state: "unavailable" };
+ const payload = await readJSON("https://api.steampowered.com/IPlayerService/GetOwnedGames/v1/?" + params,
+ "omit", 8 * 1024 * 1024);
+ const value = payload.response;
+ if (!value || !Object.prototype.hasOwnProperty.call(value, "game_count")) return { state: "unavailable" };
return snapshot(value.games || [], value.game_count);
} catch {
return { state: "unavailable" };
diff --git a/resources/steam-wine.json b/resources/steam-wine.json
new file mode 100644
index 00000000000..b4519355b6d
--- /dev/null
+++ b/resources/steam-wine.json
@@ -0,0 +1,8 @@
+{
+ "version": "11.0_1",
+ "wine_version": "wine-11.0",
+ "url": "https://github.com/Gcenx/macOS_Wine_builds/releases/download/11.0_1/wine-stable-11.0_1-osx64.tar.xz",
+ "sha256": "b50dc50ec7f41d58b115a6b685d4d1315ba3c797bd3aa0f49213f2703cb82388",
+ "archive_root": "Wine Stable.app/Contents/Resources/wine",
+ "upstream": "https://github.com/Gcenx/macOS_Wine_builds/releases/tag/11.0_1"
+}
diff --git a/scripts/bootstrap-steam.py b/scripts/bootstrap-steam.py
new file mode 100644
index 00000000000..cf6893c07ef
--- /dev/null
+++ b/scripts/bootstrap-steam.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+"""Finish a new Steam client's update before installing its CEF wrapper."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+
+def client_ready(steam):
+ return ((steam / "steamui.dll").is_file() and
+ any((steam / "bin/cef").glob("cef.win*/steamwebhelper.exe")))
+
+def bootstrap(wine, prefix, timeout=900):
+ steam = prefix / "drive_c/Program Files (x86)/Steam"
+ if client_ready(steam):
+ return
+ env = {k: v for k, v in os.environ.items()
+ if not k.startswith(("DYLD_", "WINE", "CX_", "ROSETTA_"))}
+ env.update(WINEPREFIX=str(prefix), WINEDEBUG="-all")
+ server = str(wine.parent / "wineserver")
+ log = steam / "logs/bootstrap_log.txt"
+ start = log.stat().st_size if log.exists() else 0
+ print("==> Downloading the full Steam client before preparing its login screen…", flush=True)
+ process = subprocess.Popen([str(wine), str(steam / "steam.exe"),
+ "-silent", "-shutdown"], env=env, stdin=subprocess.DEVNULL)
+ complete = False
+ try:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ text = ""
+ if log.exists():
+ with log.open("rb") as stream:
+ if log.stat().st_size >= start:
+ stream.seek(start)
+ text = stream.read()[-65536:].decode("utf-8", errors="replace")
+ # The bootstrapper may exit with 42 and relaunch itself during an
+ # update. Wait for its final verification, not that first process.
+ if client_ready(steam) and verification_finished(text):
+ complete = True
+ break
+ time.sleep(1)
+ finally:
+ # This branch only runs for an incomplete client, before any sign-in or
+ # game launch. Stop this prefix alone so the wrapper can be installed.
+ subprocess.run([server, "-k"], env=env, timeout=20, check=False)
+ subprocess.run([server, "-w"], env=env, timeout=30, check=False)
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.terminate()
+ if not complete:
+ raise RuntimeError("Steam's first download did not finish. Check your connection and retry installation.")
+ print("==> Steam client downloaded; preparing the login screen", flush=True)
+
+def verification_finished(text):
+ verified = text.rfind("Verification complete")
+ pending = max(text.rfind("Startup - updater"), text.rfind("Downloading update"),
+ text.rfind("Extracting package"), text.rfind("Installing update"))
+ return verified >= 0 and verified > pending
+
+if __name__ == "__main__":
+ try:
+ bootstrap(Path(sys.argv[1]), Path(os.environ["WINEPREFIX"]))
+ except (OSError, RuntimeError, subprocess.SubprocessError) as error:
+ print("Steam setup: " + str(error), file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/create-steam-bottle.sh b/scripts/create-steam-bottle.sh
index 45e345b9450..ae0c817b867 100755
--- a/scripts/create-steam-bottle.sh
+++ b/scripts/create-steam-bottle.sh
@@ -1,12 +1,8 @@
#!/usr/bin/env bash
# Install the Windows Steam client and its verified rendering components.
#
-# Important: unlike Battle.net, Steam runs on Homebrew wine-stable, not the CX
-# source engine. CX-derived builds cannot render Steam's CEF UI (black screen);
-# the verified free combination is wine-stable 11 + the steamwebhelper wrapper.
-# Wrapper source: github.com/notpop/steam-on-m1-wine (MIT): source and license
-# vendored in third_party/.
-# Verified 2026-08-27 on M4 Pro / macOS 26.5: login screen renders.
+# Steam uses upstream Wine 11 plus the steamwebhelper wrapper and DXMT.
+# New installs use a checksum-pinned private runtime; legacy Wine apps are kept.
set -euo pipefail
BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"
@@ -14,22 +10,31 @@ export WINEPREFIX="${WINEPREFIX:-$BASE/steam-bottle}"
WORK="${WORK:-$BASE/build}"; mkdir -p "$WORK"
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source "$REPO_ROOT/scripts/steam-runtime.sh"
-WINESTABLE_APP="/Applications/Wine Stable.app"
+# ---------- 1. Pinned upstream Wine ----------
+python3 - "$REPO_ROOT/resources/steam-support.json" <<'PYVERSION'
+import json, platform, sys
+m=json.load(open(sys.argv[1]))
+version=lambda s: tuple(map(int,s.split('.')))
+if version(platform.mac_ver()[0]) < version(m['minimum_macos']):
+ sys.exit('Steam game support requires macOS '+m['minimum_macos']+' or later.')
+PYVERSION
+unset DYLD_FALLBACK_LIBRARY_PATH WINEDLLOVERRIDES WINEMSYNC ROSETTA_ADVERTISE_AVX
+unset CX_ACTIVE_GRAPHICS_BACKEND CX_GRAPHICS_BACKEND CX_APPLEGPTK_LIBD3DSHARED_PATH WINE_SIMULATE_WRITECOPY
WINE="$STEAM_WINE_ROOT/bin/wine"
-
-# ---------- 1. wine-stable ----------
-if [ ! -x "$WINE" ]; then
- echo "==> Installing Homebrew wine-stable (free, ~500MB)"
- # The gstreamer-runtime cask dependency demands sudo, so skip it (Steam's UI doesn't need it)
- brew install --cask --skip-cask-deps wine-stable
- echo "==> Removing the Gatekeeper quarantine flag (takes a few minutes)"
- xattr -dr com.apple.quarantine "$WINESTABLE_APP" 2>/dev/null || true
+if [ ! -x "$WINE" ] || [ "$("$WINE" --version 2>/dev/null || true)" != wine-11.0 ]; then
+ if [ -n "${SOJU_STEAM_WINE:-}" ]; then
+ echo "SOJU_STEAM_WINE must point to a working Wine 11.0 runtime."; exit 1
+ fi
+ python3 "$REPO_ROOT/scripts/fetch-steam-wine.py"
+ source "$REPO_ROOT/scripts/steam-runtime.sh"
+ WINE="$STEAM_WINE_ROOT/bin/wine"
fi
"$WINE" --version
# ---------- 2. Verified wrapper and rendering components ----------
python3 "$REPO_ROOT/scripts/fetch-steam-support.py"
if [ -f "$WINEPREFIX/drive_c/Program Files (x86)/Steam/steam.exe" ]; then
+ python3 "$REPO_ROOT/scripts/bootstrap-steam.py" "$WINE"
echo "Steam already installed."
exit 0
fi
@@ -46,7 +51,10 @@ echo "==> Installing Steam silently"
"$STEAM_WINE_ROOT/bin/wineserver" -w 2>/dev/null || true
[ -f "$WINEPREFIX/drive_c/Program Files (x86)/Steam/steam.exe" ] || { echo "Install failed"; exit 1; }
-# ---------- 4. Finish ----------
+# ---------- 4. Full client before configuring the renderer ----------
+python3 "$REPO_ROOT/scripts/bootstrap-steam.py" "$WINE"
+
+# ---------- 5. Finish ----------
cp -f /etc/ssl/cert.pem "$WINEPREFIX/drive_c/windows/cacert.pem" 2>/dev/null || true
echo "==> Done. Run: scripts/play.sh steam (play.sh deploys the wrapper automatically)"
echo " If typed text shows up as ??, switch the macOS input source to English (ABC)."
diff --git a/scripts/doctor.sh b/scripts/doctor.sh
index f6e7fc8c9be..3d0f0eb3cfe 100755
--- a/scripts/doctor.sh
+++ b/scripts/doctor.sh
@@ -92,8 +92,8 @@ if [ -f "$BASE/steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe" ]; then
else
warn "Steam game rendering not configured: soju steam-games"
fi
- [ -x "$WINESTABLE" ] && pass "Homebrew wine-stable present" \
- || fail "Steam bottle exists but wine-stable is gone: brew install --cask wine-stable"
+ [ -x "$WINESTABLE" ] && pass "Steam Wine runtime present" \
+ || fail "Steam runtime is missing: run soju steam-install"
else
info "Steam not installed (soju steam-install)"
fi
diff --git a/scripts/fetch-steam-wine.py b/scripts/fetch-steam-wine.py
new file mode 100644
index 00000000000..933ab1567e5
--- /dev/null
+++ b/scripts/fetch-steam-wine.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Install the pinned upstream Wine build privately; no Homebrew cask required."""
+import hashlib
+import json
+import os
+from pathlib import Path, PurePosixPath
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+
+MANIFEST = Path(__file__).resolve().parents[1] / "resources/steam-wine.json"
+
+def digest(path):
+ h = hashlib.sha256()
+ with path.open("rb") as f:
+ for block in iter(lambda: f.read(1024 * 1024), b""):
+ h.update(block)
+ return h.hexdigest()
+
+def unpack(archive, dest, manifest):
+ """Extract just Wine; links may only point to files within this runtime."""
+ root = manifest["archive_root"] + "/"
+ seen, links, total = set(), [], 0
+ with tarfile.open(archive, "r:xz") as tar:
+ for member in tar:
+ raw = member.name.removeprefix("./")
+ if PurePosixPath(raw).is_absolute() or ".." in PurePosixPath(raw).parts:
+ raise ValueError("Unsafe Wine archive path")
+ if not raw.startswith(root):
+ continue
+ name = raw[len(root):].rstrip("/")
+ if not name:
+ continue
+ if name in seen:
+ raise ValueError("Duplicate Wine archive entry")
+ seen.add(name)
+ target = dest / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if member.isdir():
+ target.mkdir(exist_ok=True)
+ elif member.isfile():
+ total += member.size
+ if member.size > 256 * 1024 * 1024 or total > 2 * 1024**3:
+ raise ValueError("Oversized Wine archive")
+ with tar.extractfile(member) as src, target.open("xb") as out:
+ shutil.copyfileobj(src, out)
+ target.chmod(0o755 if member.mode & 0o111 else 0o644)
+ elif member.issym():
+ # Delay links until regular files are written, so archive writes
+ # can never traverse an archive-supplied symlink.
+ links.append((target, member.linkname))
+ else:
+ raise ValueError("Unsupported Wine archive entry")
+ for target, link in links:
+ if PurePosixPath(link).is_absolute():
+ raise ValueError("Absolute Wine archive link")
+ resolved = (target.parent / link).resolve()
+ if dest.resolve() not in resolved.parents:
+ raise ValueError("Wine archive link escapes runtime")
+ target.symlink_to(link)
+ for target, _ in links:
+ resolved = target.resolve(strict=True)
+ if dest.resolve() not in resolved.parents or not resolved.is_file():
+ raise ValueError("Invalid Wine archive link")
+ for name in ("bin/wine", "bin/wineserver", "lib/wine/x86_64-unix/ntdll.so",
+ "lib/wine/x86_64-windows/ntdll.dll", "share/wine/wine.inf"):
+ if not (dest / name).is_file():
+ raise ValueError("Incomplete Wine runtime")
+
+def wine_version(target):
+ env = {k: v for k, v in os.environ.items()
+ if not k.startswith(("DYLD_", "WINE", "CX_", "ROSETTA_"))}
+ return subprocess.run([str(target / "bin/wine"), "--version"], env=env,
+ check=True, capture_output=True, text=True, timeout=20).stdout.strip()
+
+def ready(target, manifest):
+ try:
+ return ((target / ".soju-wine").read_text().strip() == manifest["sha256"]
+ and os.access(target / "bin/wineserver", os.X_OK)
+ and wine_version(target) == manifest["wine_version"])
+ except (OSError, subprocess.SubprocessError):
+ return False
+
+def fetch(base, manifest, archive_path=None):
+ target = base / "steam-wine"
+ if ready(target, manifest):
+ print("Steam Wine runtime ready (" + manifest["version"] + ")")
+ return target
+ base.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix=".steam-wine-", dir=base) as temp:
+ work = Path(temp)
+ archive = Path(archive_path) if archive_path else work / "wine.tar.xz"
+ if not archive_path:
+ print("Downloading Steam Wine runtime (" + manifest["version"] + ", 177 MB)…", flush=True)
+ subprocess.run(["/usr/bin/curl", "--fail", "--location", "--proto", "=https",
+ "--proto-redir", "=https", "--retry", "3", "--connect-timeout", "20",
+ "--max-time", "900", manifest["url"], "--output", str(archive)], check=True)
+ if digest(archive) != manifest["sha256"]:
+ raise ValueError("Wine download checksum mismatch; existing runtime unchanged")
+ stage = work / "runtime"
+ stage.mkdir()
+ unpack(archive, stage, manifest)
+ if wine_version(stage) != manifest["wine_version"]:
+ raise ValueError("Unexpected Wine version; existing runtime unchanged")
+ (stage / ".soju-wine").write_text(manifest["sha256"] + "\n")
+ backup = base / "steam-wine.previous"
+ if backup.exists():
+ shutil.rmtree(backup)
+ if target.exists():
+ target.rename(backup)
+ try:
+ stage.rename(target)
+ except OSError:
+ if backup.exists():
+ backup.rename(target)
+ raise
+ if backup.exists():
+ shutil.rmtree(backup)
+ print("Steam Wine runtime 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")))
+ fetch(base, manifest)
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError, tarfile.TarError) as error:
+ print("Steam Wine runtime: " + str(error), file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/play.sh b/scripts/play.sh
index d6f4cbf8fad..77b4383d976 100755
--- a/scripts/play.sh
+++ b/scripts/play.sh
@@ -201,9 +201,11 @@ case "$MODE" in
# vendored in third_party/.
WINESTABLE="$STEAM_WINE_ROOT/bin/wine"
WINESTABLE_SERVER="$STEAM_WINE_ROOT/bin/wineserver"
- [[ -x "$WINESTABLE" ]] || { echo "wine-stable not found, brew install --cask wine-stable"; exit 1; }
+ [[ -x "$WINESTABLE" ]] || { echo "Steam runtime not found. Reinstall Steam from Platforms or run: soju steam-install"; exit 1; }
ST="$WINEPREFIX/drive_c/Program Files (x86)/Steam/steam.exe"
[[ -f "$ST" ]] || { echo "Steam not found, run scripts/create-steam-bottle.sh first"; exit 1; }
+ # Repair a bootstrap-only installation before deploying the CEF wrapper.
+ python3 "$(dirname "${BASH_SOURCE[0]}")/bootstrap-steam.py" "$WINESTABLE"
# 1) Clean crash leftovers (a stale lock makes the next launch a windowless --silent one)
find "$WINEPREFIX/drive_c/users/"*/AppData/Local/Steam/htmlcache -maxdepth 2 \
\( -name "Singleton*" -o -name "*.lock" \) -delete 2>/dev/null || true
@@ -249,7 +251,13 @@ case "$MODE" in
fi
fi
# 6) Launch: plain wine-stable environment, without the CX engine env
- STEAM_CMD=("C:\\Program Files (x86)\\Steam\\steam.exe" -no-cef-sandbox -cef-single-process -noverifyfiles "${@:2}")
+ STEAM_CMD=("C:\\Program Files (x86)\\Steam\\steam.exe" -no-cef-sandbox -cef-single-process)
+ # SteamSetup only contains the bootstrapper: let first launch download the
+ # client, otherwise Steam fails with "Failed to load steamui.dll".
+ if [ -f "$WINEPREFIX/drive_c/Program Files (x86)/Steam/steamui.dll" ]; then
+ STEAM_CMD+=(-noverifyfiles)
+ fi
+ STEAM_CMD+=("${@:2}")
[[ -n "$VD" ]] && STEAM_CMD=(explorer.exe "/desktop=soju-steam,$VD" "${STEAM_CMD[@]}")
# Closing the Steam window parks it in a tray macOS does not show; the patched
# winemac runs WINE_DOCK_REOPEN_CMD on a Dock-icon click when no window is
diff --git a/scripts/setup-steam-games.sh b/scripts/setup-steam-games.sh
index e535f3e5ac2..1d978c7f848 100755
--- a/scripts/setup-steam-games.sh
+++ b/scripts/setup-steam-games.sh
@@ -49,7 +49,7 @@ if [ "${1:-}" != --repair ] && [ -f "$TARGET/.soju-runtime" ] && \
exit 0
fi
SOURCE="$STEAM_WINE_ROOT"
-[ -x "$SOURCE/bin/wine" ] || { echo "Install wine-stable first: soju steam-install"; exit 1; }
+[ -x "$SOURCE/bin/wine" ] || { echo "Prepare the Steam runtime first: soju steam-install"; exit 1; }
[ "$("$SOURCE/bin/wine" --version)" = wine-11.0 ] || {
echo "This Steam component release requires Wine 11.0. Existing runtime unchanged."; exit 1;
}
diff --git a/scripts/soju b/scripts/soju
index 07ab4673aa0..d6483cba0bc 100755
--- a/scripts/soju
+++ b/scripts/soju
@@ -34,7 +34,7 @@ Usage:
soju gog Launch GOG GALAXY
soju gog-kill Stop everything in the GOG bottle
- soju steam-install Set up the Steam bottle (wine-stable + wrapper + Steam)
+ soju steam-install Set up the Steam bottle (private Wine 11 + wrapper + Steam)
soju steam-games Download and configure verified D3D11 components
soju steam Launch Steam
soju steam-kill Stop everything in the Steam bottle
diff --git a/scripts/steam-runtime.sh b/scripts/steam-runtime.sh
index 998116ccf36..8af1bfd994d 100755
--- a/scripts/steam-runtime.sh
+++ b/scripts/steam-runtime.sh
@@ -1,9 +1,13 @@
#!/usr/bin/env bash
-# Existing users retain Wine Stable until a verified private runtime is ready.
+# Prefer the prepared renderer, then private upstream Wine, then a legacy install.
SOJU_STEAM_BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"
STEAM_WINE_ROOT="${SOJU_STEAM_WINE:-/Applications/Wine Stable.app/Contents/Resources/wine}"
-if [ -z "${SOJU_STEAM_WINE:-}" ] && [ -f "$SOJU_STEAM_BASE/steam-runtime/.soju-runtime" ]; then
- STEAM_WINE_ROOT="$SOJU_STEAM_BASE/steam-runtime"
+if [ -z "${SOJU_STEAM_WINE:-}" ]; then
+ if [ -f "$SOJU_STEAM_BASE/steam-runtime/.soju-runtime" ] && [ -x "$SOJU_STEAM_BASE/steam-runtime/bin/wine" ]; then
+ STEAM_WINE_ROOT="$SOJU_STEAM_BASE/steam-runtime"
+ elif [ -f "$SOJU_STEAM_BASE/steam-wine/.soju-wine" ] && [ -x "$SOJU_STEAM_BASE/steam-wine/bin/wine" ]; then
+ STEAM_WINE_ROOT="$SOJU_STEAM_BASE/steam-wine"
+ fi
fi
STEAM_SUPPORT="$SOJU_STEAM_BASE/steam-support"
if [ -d "$STEAM_SUPPORT/prebuilt" ]; then STEAM_SUPPORT="$STEAM_SUPPORT/prebuilt"; fi
diff --git a/tests/test_steam_login.cjs b/tests/test_steam_login.cjs
index 4ded441351a..f198755f570 100644
--- a/tests/test_steam_login.cjs
+++ b/tests/test_steam_login.cjs
@@ -63,3 +63,47 @@ test("conflicting account identity cannot import a stale profile", async () => {
() => { throw Error("must not fetch"); });
assert.deepEqual(value, {state:"unavailable"});
});
+
+test("legacy signed-in page without application_config imports via Steam's own session", async () => {
+ const ctx = context();
+ ctx[1] = {getElementById:()=>null, querySelector:selector=>selector==="#account_pulldown" ? {} : null};
+ const requests = [];
+ const result = await run(...ctx, async (url, options) => {
+ requests.push(url);
+ if (url === "https://steamcommunity.com/chat/clientjstoken") {
+ assert.equal(options.credentials, "same-origin");
+ return {ok:true,text:async()=>JSON.stringify({logged_in:true,steamid:id,token:"session-only"})};
+ }
+ assert.equal(new URL(url).origin, "https://api.steampowered.com");
+ assert.equal(options.credentials, "omit");
+ return {ok:true,text:async()=>JSON.stringify({response:{game_count:1,games:[{appid:10,name:"Owned"}]}})};
+ });
+ assert.equal(requests.length, 2);
+ assert.equal(result.state, "ready");
+ assert.equal(result.games.length, 1);
+ assert.ok(!JSON.stringify(result).includes("session-only"));
+});
+test("legacy session identity mismatch never fetches another account's games", async () => {
+ let requests = 0;
+ const result = await run(...context({}, {g_steamID:id}), async () => {
+ requests++;
+ return {ok:true,text:async()=>JSON.stringify({logged_in:true,steamid:"76561198000000001",token:"other"})};
+ });
+ assert.equal(result.state,"unavailable");
+ assert.equal(requests,1);
+});
+test("legacy expired session requests sign-in and preserves old import", async () => {
+ const ctx=context();
+ ctx[1].querySelector=()=>({});
+ const result=await run(...ctx, async()=>({ok:true,text:async()=>JSON.stringify({logged_in:false})}));
+ assert.deepEqual(result,{state:"sign-in"});
+});
+test("partial legacy page can retry after its data finishes loading", async () => {
+ const ctx=context({}, {g_steamID:id});
+ const failed=await run(...ctx, async()=>{throw Error("offline");});
+ assert.equal(failed.state,"unavailable");
+ ctx[0].g_rgProfileData={steamid:id};
+ ctx[0].rgGames=[{appid:10,name:"Owned"}];
+ const retried=await run(...ctx, ()=>{throw Error("not needed");});
+ assert.equal(retried.state,"ready");
+});
diff --git a/tests/test_steam_wine.py b/tests/test_steam_wine.py
new file mode 100644
index 00000000000..798fe455e2f
--- /dev/null
+++ b/tests/test_steam_wine.py
@@ -0,0 +1,200 @@
+import hashlib
+import importlib.util
+import io
+import json
+import os
+from pathlib import Path
+import subprocess
+import tarfile
+import tempfile
+import unittest
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location("steam_wine", ROOT / "scripts/fetch-steam-wine.py")
+wine = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(wine)
+
+class SteamWineTests(unittest.TestCase):
+ def archive(self, directory, extra=()):
+ archive = directory / "wine.tar.xz"
+ names = ["bin/wine", "bin/wineserver", "lib/wine/x86_64-unix/ntdll.so",
+ "lib/wine/x86_64-windows/ntdll.dll", "share/wine/wine.inf"]
+ with tarfile.open(archive, "w:xz") as tar:
+ for name in names:
+ info = tarfile.TarInfo("Wine.app/wine/" + name)
+ info.mode = 0o755
+ info.size = 4
+ tar.addfile(info, io.BytesIO(b"wine"))
+ for name, link in extra:
+ info = tarfile.TarInfo("Wine.app/wine/" + name)
+ if link is None:
+ info.size = 4
+ tar.addfile(info, io.BytesIO(b"wine"))
+ else:
+ info.type = tarfile.SYMTYPE
+ info.linkname = link
+ tar.addfile(info)
+ manifest = {"version": "test", "wine_version": "wine-11.0", "archive_root": "Wine.app/wine",
+ "sha256": wine.digest(archive), "url": "https://example.invalid/wine.tar.xz"}
+ return archive, manifest
+
+ def test_validated_private_runtime_installs_without_homebrew(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ archive, manifest = self.archive(base, [("bin/wine64", "wine")])
+ with patch.object(wine, "wine_version", return_value="wine-11.0"):
+ target = wine.fetch(base, manifest, archive)
+ self.assertTrue(wine.ready(target, manifest))
+ self.assertTrue((target / "bin/wine64").is_file())
+ with patch.object(wine.subprocess, "run", side_effect=AssertionError("no download")):
+ self.assertEqual(wine.fetch(base, manifest), target)
+
+ def test_checksum_failure_preserves_existing_runtime(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ archive, manifest = self.archive(base)
+ target = base / "steam-wine"
+ target.mkdir()
+ (target / "keep").write_text("previous")
+ manifest["sha256"] = "0" * 64
+ with self.assertRaisesRegex(ValueError, "checksum"):
+ wine.fetch(base, manifest, archive)
+ self.assertEqual((target / "keep").read_text(), "previous")
+
+ def test_rejects_traversal_external_links_and_duplicates(self):
+ for extra in [[("../escape", None)], [("bin/out", "/tmp/outside")],
+ [("bin/out", "../../outside")], [("bin/wine", None)],
+ [("bin/dir", "wine"), ("bin/dir/escape", None)]]:
+ with self.subTest(extra=extra), tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ archive, manifest = self.archive(base, extra)
+ dest = base / "stage"
+ dest.mkdir()
+ with self.assertRaises((ValueError, OSError)):
+ wine.unpack(archive, dest, manifest)
+
+ def test_failed_runtime_validation_preserves_previous(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ archive, manifest = self.archive(base)
+ target = base / "steam-wine"
+ target.mkdir()
+ (target / "keep").write_text("previous")
+ with patch.object(wine, "wine_version", return_value="wine-12.0"):
+ with self.assertRaisesRegex(ValueError, "Unexpected Wine version"):
+ wine.fetch(base, manifest, archive)
+ self.assertEqual((target / "keep").read_text(), "previous")
+
+ def test_private_runtime_selection_and_explicit_override(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ def select(override=None):
+ env = {**os.environ, "SOJU_BASE": str(base)}
+ env.pop("SOJU_STEAM_WINE", None)
+ if override: env["SOJU_STEAM_WINE"] = override
+ return subprocess.check_output(["/bin/bash", "-c",
+ 'source "$1"; printf "%s" "$STEAM_WINE_ROOT"', "test",
+ str(ROOT / "scripts/steam-runtime.sh")], env=env, text=True)
+ self.assertEqual(select(), "/Applications/Wine Stable.app/Contents/Resources/wine")
+ for name, marker in [("steam-wine", ".soju-wine"), ("steam-runtime", ".soju-runtime")]:
+ target = base / name
+ (target / "bin").mkdir(parents=True)
+ (target / marker).touch()
+ (target / "bin/wine").write_text("#!/bin/sh\nexit 0\n")
+ (target / "bin/wine").chmod(0o755)
+ self.assertEqual(select(), str(target))
+ (base / "steam-runtime/bin/wine").unlink()
+ self.assertEqual(select(), str(base / "steam-wine"))
+ self.assertEqual(select("/custom/wine"), "/custom/wine")
+
+class SteamFirstLaunchTests(unittest.TestCase):
+ def test_first_launch_downloads_client_and_existing_client_keeps_wrapper(self):
+ for installed in (False, True):
+ with self.subTest(installed=installed), tempfile.TemporaryDirectory() as tmp:
+ base = Path(tmp)
+ prefix = base / "steam-bottle"
+ steam = prefix / "drive_c/Program Files (x86)/Steam"
+ steam.mkdir(parents=True)
+ (steam / "steam.exe").touch()
+ if installed:
+ (steam / "steamui.dll").touch()
+ runtime = base / "wine"
+ (runtime / "bin").mkdir(parents=True)
+ log = base / "args"
+ binary = runtime / "bin/wine"
+ binary.write_text('#!/bin/bash\nprintf "%s\\n" "$@" >> "$SOJU_TEST_ARGS"\n')
+ binary.chmod(0o755)
+ stubs = base / "stubs"
+ stubs.mkdir()
+ for name in ("python3", "pgrep"):
+ script = stubs / name
+ script.write_text("#!/bin/bash\nexit 0\n")
+ script.chmod(0o755)
+ env = {**os.environ, "SOJU_BASE": str(base), "WINEPREFIX": str(prefix),
+ "SOJU_STEAM_WINE": str(runtime), "SOJU_TEST_ARGS": str(log),
+ "WINE_VIRTUAL_DESKTOP": "", "SOJU_KEYLOG": "0",
+ "PATH": str(stubs) + ":/usr/bin:/bin"}
+ result = subprocess.run(["/bin/bash", str(ROOT / "scripts/play.sh"), "steam"],
+ env=env, capture_output=True, text=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ args = log.read_text().splitlines()
+ self.assertEqual("-noverifyfiles" in args, installed)
+ self.assertIn("-cef-single-process", args)
+
+spec_bootstrap = importlib.util.spec_from_file_location("steam_bootstrap", ROOT / "scripts/bootstrap-steam.py")
+bootstrap = importlib.util.module_from_spec(spec_bootstrap)
+spec_bootstrap.loader.exec_module(bootstrap)
+
+class SteamBootstrapTests(unittest.TestCase):
+ def test_only_final_verification_finishes_initial_download(self):
+ verified = "[time] Startup - updater built old\n[time] Verification complete\n"
+ for phase in ["Downloading update", "Extracting package", "Installing update", "Startup - updater built new"]:
+ self.assertFalse(bootstrap.verification_finished(verified + phase))
+ self.assertTrue(bootstrap.verification_finished(verified + "Installing update\nStartup - updater built new\nVerification complete\n"))
+ self.assertFalse(bootstrap.verification_finished(""))
+
+ def test_complete_client_never_starts_or_stops_wine(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ prefix = Path(tmp)
+ steam = prefix / "drive_c/Program Files (x86)/Steam"
+ cef = steam / "bin/cef/cef.win7x64"
+ cef.mkdir(parents=True)
+ (steam / "steamui.dll").touch()
+ (cef / "steamwebhelper.exe").touch()
+ with patch.object(bootstrap.subprocess, "Popen", side_effect=AssertionError("existing Steam")), \
+ patch.object(bootstrap.subprocess, "run", side_effect=AssertionError("existing Steam")):
+ bootstrap.bootstrap(prefix / "wine/bin/wine", prefix)
+
+ def test_bootstrapper_relaunch_is_not_mistaken_for_completed_download(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ prefix = Path(tmp)
+ steam = prefix / "drive_c/Program Files (x86)/Steam"
+ (steam / "logs").mkdir(parents=True)
+ (steam / "steam.exe").touch()
+ from unittest.mock import Mock
+ process = Mock()
+ process.poll.return_value = 42
+ process.wait.return_value = 42
+ def start(*args, **kwargs):
+ cef = steam / "bin/cef/cef.win7x64"
+ cef.mkdir(parents=True)
+ (steam / "steamui.dll").touch()
+ (cef / "steamwebhelper.exe").touch()
+ (steam / "logs/bootstrap_log.txt").write_text("Startup - updater built new\nVerification complete\n")
+ return process
+ with patch.object(bootstrap.subprocess, "Popen", side_effect=start), \
+ patch.object(bootstrap.subprocess, "run") as stop:
+ bootstrap.bootstrap(prefix / "wine/bin/wine", prefix)
+ self.assertEqual(len(stop.call_args_list), 2)
+ for call in stop.call_args_list:
+ self.assertEqual(call.kwargs["env"]["WINEPREFIX"], str(prefix))
+
+ def test_incomplete_download_reports_failure_after_scoped_cleanup(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ prefix = Path(tmp)
+ with patch.object(bootstrap.subprocess, "Popen"), patch.object(bootstrap.subprocess, "run") as stop, \
+ patch.object(bootstrap.time, "monotonic", side_effect=[0, 1000]):
+ with self.assertRaisesRegex(RuntimeError, "did not finish"):
+ bootstrap.bootstrap(prefix / "wine/bin/wine", prefix, timeout=1)
+ self.assertEqual(stop.call_args.kwargs["env"]["WINEPREFIX"], str(prefix))