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
Add Steam sign-in, owned libraries and store discovery (#34)
Mikek683ac3defc6d
diff --git a/.github/workflows/check.yml b/.github/workflows/check.ymlindex eb57db3fcc9..d5e65ce5fea 100644--- a/.github/workflows/check.yml+++ b/.github/workflows/check.yml@@ -15,5 +15,6 @@ jobs:bash -n install.shfor script in scripts/*.sh scripts/soju; do bash -n "$script"; donepython3 -m unittest discover -s tests -q+ node --test tests/test_steam_login.cjs- name: Build and verify the native apprun: bash scripts/build-app.shdiff --git a/README.ko.md b/README.ko.mdindex a92f1aeb293..410ca627d11 100644--- a/README.ko.md+++ b/README.ko.md@@ -1,6 +1,7 @@# Soju (한국어)-**v1.5.0:** 설치된 게임을 한 라이브러리에서 검색·필터·즐겨찾기하고 실행할 수 있습니다. 런처 설치와 업데이트는 Platforms에서 관리합니다. 미설치 보유 게임 동기화와 스토어 검색은 아직 포함되지 않습니다.+**1.6.0 추가:** Steam 공식 로그인으로 보유 게임 가져오기(API 키 불필요), GOG Galaxy 로컬 보유 목록 가져오기, Steam·GOG 상품/가격 검색과 공식 스토어 연결. [설정 안내](docs/ACCOUNTS.md).+**v1.6.0:** 설치된 게임을 한 라이브러리에서 검색·필터·즐겨찾기하고 실행할 수 있습니다. 런처 설치와 업데이트는 Platforms에서 관리합니다. Steam·GOG 보유 게임을 가져오고 Discover에서 상품과 가격을 검색할 수 있습니다. Epic·Battle.net 전체 보유 목록 연동은 아직 지원하지 않습니다.[Desktop / download](docs/DESKTOP.md)diff --git a/README.md b/README.mdindex 7ca11e8472b..121fc7ccf03 100644--- a/README.md+++ b/README.md@@ -7,19 +7,25 @@ into one native Mac library. Search, filter, favorite and launch games throughtheir official Windows clients. The Platforms page handles launcher setup,component updates and diagnostics; the CLI and individual shortcuts remain available.-The library reads local installation records in Soju's Windows environments.-Accounts, purchases, downloads and game updates stay with each official client.-Uninstalled owned games and store search are not included in this release.-Compatibility varies by game and system.+Sign in to **Steam** to import your owned library, or import the+owned library cached by **GOG GALAXY**. Installed and uninstalled games share the+same library, with availability filters and official-client install actions.+**Discover** searches Steam and GOG listings and prices, with direct search links+for all four stores. Purchases, downloads and updates stay with the official stores.+Epic and Battle.net account imports are not included yet. Compatibility varies by game.+++[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 fromCodeWeavers' published sources; Steam uses a separate wine-stable setup.Apple's proprietary GPTK/D3DMetal is downloaded separately. Games and storeclients are not included.-**Current release: [v1.5.0](https://github.com/BCD1210/soju/releases/tag/v1.5.0).**+**Current release: [v1.6.0](https://github.com/BCD1210/soju/releases/tag/v1.6.0).**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.@@ -85,7 +91,7 @@ soju install # then: soju battlenet / soju d2r / soju steam / soju epic / soThe 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.5.0/Soju-1.5.0-macos-arm64.zip) — the native desktop preview includes a unified installed-game library, 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.0/Soju-1.6.0-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 commandsdiff --git a/README.zh.md b/README.zh.mdindex 54bdb0c433b..9f511084a67 100644--- a/README.zh.md+++ b/README.zh.md@@ -1,6 +1,7 @@# Soju(简体中文)-**v1.5.0:** 在统一游戏库中搜索、筛选、收藏和启动已安装的游戏。通过 Platforms 管理启动器安装与更新。此版本暂不包含未安装游戏的账户同步或商店搜索。+**1.6.0 新增:** 通过 Steam 官方登录导入已购游戏(无需 API 密钥)、GOG Galaxy 本地游戏库导入,以及 Steam/GOG 商店搜索与官方购买链接。[设置说明](docs/ACCOUNTS.md)。+**v1.6.0:** 在统一游戏库中搜索、筛选、收藏和启动已安装的游戏。通过 Platforms 管理启动器安装与更新。支持导入 Steam/GOG 已购游戏,并在 Discover 中搜索商品与价格。暂不支持 Epic/Battle.net 的完整账户游戏库导入。[Desktop / download](docs/DESKTOP.md)diff --git a/VERSION b/VERSIONindex bc80560fad6..dc1e644a101 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.5.0+1.6.0diff --git a/app/Accounts.swift b/app/Accounts.swiftnew file mode 100644index 00000000000..9ac7de7ce38--- /dev/null+++ b/app/Accounts.swift@@ -0,0 +1,228 @@+import SwiftUI+import AppKit++struct AccountSummary: Decodable, Identifiable {+ let platform: Launcher+ let label: String+ let updatedAt: String+ let count: Int+ var id: String { platform.rawValue }+ enum CodingKeys: String, CodingKey { case platform, label, count; case updatedAt = "updated_at" }+}+struct GalaxyAccount: Decodable, Identifiable { let id: String; let label: String; let count: Int }+struct ServiceFailure: LocalizedError {+ let message: String+ var errorDescription: String? { message }+}++enum ServiceBridge {+ @discardableResult static func start(root: URL, base: URL, args: [String], input: [String: String] = [:],+ completion: @escaping (Result<Data, Error>) -> Void) -> Process? {+ let p = Process()+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("soju-service-" + UUID().uuidString + ".json")+ do {+ try Data().write(to: url)+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)+ let output = try FileHandle(forWritingTo: url)+ let pipe = Pipe()+ let inputData = try JSONEncoder().encode(input)+ guard inputData.count <= 8 * 1024 * 1024 else { throw ServiceFailure(message: "Account settings are too large.") }+ p.executableURL = URL(fileURLWithPath: "/usr/bin/env")+ p.arguments = ["python3", root.appendingPathComponent("scripts/library-service.py").path] + args+ p.environment = ["PATH": "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin", "HOME": FileManager.default.homeDirectoryForCurrentUser.path,+ "SOJU_BASE": base.path, "PYTHONIOENCODING": "utf-8"]+ p.standardInput = pipe; p.standardOutput = output; p.standardError = FileHandle.nullDevice+ p.terminationHandler = { process in+ defer { try? FileManager.default.removeItem(at: url) }+ let result: Result<Data, Error>+ do {+ let handle = try FileHandle(forReadingFrom: url)+ defer { try? handle.close() }+ let data = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data()+ guard data.count <= 8 * 1024 * 1024 else { throw ServiceFailure(message: "The response is too large.") }+ if process.terminationStatus != 0 {+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ throw ServiceFailure(message: object?["error"] as? String ?? "Request interrupted or unavailable. Please retry.")+ }+ result = .success(data)+ } catch { result = .failure(error) }+ DispatchQueue.main.async { completion(result) }+ }+ try p.run()+ try? output.close()+ // A large library must not block the main thread on the pipe buffer.+ DispatchQueue.global(qos: .userInitiated).async {+ try? pipe.fileHandleForWriting.write(contentsOf: inputData)+ try? pipe.fileHandleForWriting.close()+ }+ DispatchQueue.main.asyncAfter(deadline: .now() + 50) { [weak p] in+ if let p, p.isRunning { p.terminate() }+ }+ return p+ } catch {+ p.terminationHandler = nil+ if p.isRunning { p.terminate() }+ try? FileManager.default.removeItem(at: url)+ completion(.failure(error))+ return nil+ }+ }+}++extension SojuModel {+ func reloadAccountLibrary() {+ scanner?.terminate(); scanner = nil; scanning = false+ refreshLibrary()+ }+ func syncAccount(_ platform: Launcher, input: [String: String] = [:]) {+ guard !accountBusy else { return }+ accountBusy = true; accountMessage = "Importing your games…"+ accountTask = ServiceBridge.start(root: root, base: base, args: ["sync", platform.rawValue], input: input) { [weak self] result in+ guard let self else { return }+ self.accountBusy = false; self.accountTask = nil+ switch result {+ case .success(let data):+ let response = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ self.accountMessage = response?["message"] as? String ?? "Library imported."+ self.reloadAccountLibrary()+ case .failure(let error): self.accountMessage = error.localizedDescription+ }+ }+ }+ func importSteam(_ snapshot: [String: Any]) {+ do {+ let data = try JSONSerialization.data(withJSONObject: snapshot)+ guard let value = String(data: data, encoding: .utf8) else { throw ServiceFailure(message: "Steam returned an unreadable library.") }+ syncAccount(.steam, input: ["snapshot": value])+ } catch { accountMessage = error.localizedDescription }+ }+ func forgetAccount(_ platform: Launcher) {+ guard !accountBusy else { return }+ do {+ 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 {+ accountBusy = true+ SteamWebSession.clear { [weak self] in+ DispatchQueue.main.async {+ self?.accountBusy = false+ self?.accountMessage = "Steam disconnected. Installed games are kept."+ self?.reloadAccountLibrary()+ }+ }+ } else {+ accountMessage = "Account import removed. Installed games are kept."+ reloadAccountLibrary()+ }+ } catch { accountMessage = error.localizedDescription }+ }+ 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 }+ run(["game-install", game.id], title: "Opening " + game.platform.title + " to install " + game.title + "…")+ }+}++struct AccountsView: View {+ @EnvironmentObject var model: SojuModel+ @State private var showSteamLogin = false+ @State private var users: [GalaxyAccount] = []+ @State private var userID = ""+ @State private var userTask: Process?+ @State private var usersMessage = ""+ private func summary(_ platform: Launcher) -> AccountSummary? { model.accountSummaries.first { $0.platform == platform } }+ var body: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 22) {+ Text("Your accounts").font(.system(size: 30, weight: .bold, design: .rounded))+ Text("Bring owned games into your library, including games you have not installed.").foregroundStyle(.secondary)+ 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.")+ .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)+ if summary(.steam) == nil {+ Button("Clear saved sign-in") { model.forgetAccount(.steam) }.disabled(model.accountBusy)+ }+ Spacer()+ Button(summary(.steam) == nil ? "Sign in to Steam" : "Sync Steam library") { showSteamLogin = true }+ .buttonStyle(.borderedProminent).disabled(model.accountBusy)+ }+ }.padding(12)+ }+ GroupBox {+ VStack(alignment: .leading, spacing: 12) {+ accountHeader(.gog)+ Text("Import the owned library saved by GOG GALAXY on this Mac. Open Galaxy and let it finish refreshing before importing.")+ .font(.callout).foregroundStyle(.secondary)+ if users.count > 1 {+ Picker("Galaxy account", selection: $userID) {+ Text("Choose an account").tag("")+ ForEach(users) { user in Text(user.label + " · " + String(user.count) + " games").tag(user.id) }+ }+ }+ if !usersMessage.isEmpty { Text(usersMessage).font(.caption).foregroundStyle(.secondary) }+ HStack {+ Button("Open Galaxy") { model.launch(.gog) }.disabled(model.busy)+ Button("Refresh account list", action: loadUsers).disabled(userTask != nil)+ Spacer()+ Button("Import from Galaxy") { model.syncAccount(.gog, input: userID.isEmpty ? [:] : ["user_id": userID]) }+ .buttonStyle(.borderedProminent).disabled(model.accountBusy || (users.count > 1 && userID.isEmpty))+ }+ }.padding(12)+ }+ HStack(spacing: 12) {+ if model.accountBusy { ProgressView().controlSize(.small) }+ Text(model.accountMessage).font(.callout).textSelection(.enabled)+ }+ GroupBox("Epic Games & Battle.net") {+ VStack(alignment: .leading, spacing: 10) {+ Text("Installed games already appear in Soju. Full account imports for these platforms are not available yet. Open the official launcher to browse your owned games.")+ .font(.callout).foregroundStyle(.secondary)+ HStack {+ Button("Open Epic Games") { model.launch(.epic) }.disabled(model.busy)+ Button("Open Battle.net") { model.launch(.battlenet) }.disabled(model.busy)+ }+ }.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.")+ .font(.caption).foregroundStyle(.secondary)+ }.padding(28)+ }.onAppear(perform: loadUsers)+ .sheet(isPresented: $showSteamLogin) {+ SteamLoginView(root: model.root, completion: { value in+ showSteamLogin = false+ model.importSteam(value)+ }, cancel: { showSteamLogin = false })+ }+ }+ private func accountHeader(_ platform: Launcher) -> some View {+ HStack {+ Label(platform.title, systemImage: platform.symbol).font(.headline)+ if let value = summary(platform) {+ Text(value.label + " · " + String(value.count) + " games · " + String(value.updatedAt.prefix(10))).font(.caption).foregroundStyle(.secondary)+ Spacer()+ Button("Disconnect") { model.forgetAccount(platform) }.disabled(model.accountBusy)+ } else { Spacer(); Text("Not connected").font(.caption).foregroundStyle(.secondary) }+ }+ }+ private func loadUsers() {+ guard userTask == nil else { return }+ userTask = ServiceBridge.start(root: model.root, base: model.base, args: ["gog-users"]) { result in+ userTask = nil+ switch result {+ case .success(let data):+ struct Response: Decodable { let users: [GalaxyAccount] }+ users = (try? JSONDecoder().decode(Response.self, from: data).users) ?? []+ if users.count == 1 { userID = users[0].id }+ else if !users.contains(where: { $0.id == userID }) { userID = "" }+ usersMessage = users.isEmpty ? "No owned Galaxy library found yet." : ""+ case .failure(let error): usersMessage = error.localizedDescription+ }+ }+ }+}diff --git a/app/Discover.swift b/app/Discover.swiftnew file mode 100644index 00000000000..234f654da75--- /dev/null+++ b/app/Discover.swift@@ -0,0 +1,178 @@+import SwiftUI+import AppKit++struct StoreItem: Decodable, Identifiable {+ let id: String+ let platform: Launcher+ let title: String+ let url: String+ let artwork: String?+ let price: String+ let mac: Bool+ let windows: Bool+}+struct StoreResponse: Decodable {+ let games: [StoreItem]+ let warnings: [String]+ let country: String+}++@MainActor final class DiscoverModel: ObservableObject {+ @Published var results: [StoreItem] = []+ @Published var warnings: [String] = []+ @Published var searching = false+ @Published var searchedQuery = ""+ @Published var searchedCountry = ""+ private var task: Process?+ private var generation = UUID()+ func search(_ query: String, country: String, app: SojuModel) {+ let query = query.trimmingCharacters(in: .whitespacesAndNewlines)+ guard query.count >= 2, query.count <= 100 else { warnings = ["Enter 2–100 characters to search."]; return }+ generation = UUID()+ let current = generation+ task?.terminate()+ searching = true; results = []; warnings = []+ searchedQuery = query; searchedCountry = country+ task = ServiceBridge.start(root: app.root, base: app.base, args: ["search", query, "--country", country]) { [weak self] result in+ guard let self, self.generation == current else { return }+ self.searching = false; self.task = nil+ switch result {+ case .success(let data):+ do {+ let value = try JSONDecoder().decode(StoreResponse.self, from: data)+ self.results = value.games; self.warnings = value.warnings+ } catch { self.warnings = ["The stores returned an unreadable response. Please retry."] }+ case .failure(let error): self.warnings = [error.localizedDescription]+ }+ }+ }+ func cancel() {+ generation = UUID(); task?.terminate(); task = nil; searching = false+ }+}++struct DiscoverView: View {+ @EnvironmentObject var model: SojuModel+ @StateObject private var store = DiscoverModel()+ @State private var query = ""+ @State private var country = "US"+ @State private var platform = "all"+ private var shown: [StoreItem] { store.results.filter { platform == "all" || $0.platform.rawValue == platform } }+ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ 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 listings, then visit the official store.").font(.callout).foregroundStyle(.secondary)+ }+ Spacer()+ }+ HStack(spacing: 10) {+ TextField("Search games and add-ons", text: $query).textFieldStyle(.roundedBorder).accessibilityLabel("Search stores")+ .onSubmit { store.search(query, country: country, app: model) }+ Picker("Region", selection: $country) {+ 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")+ }.labelsHidden().frame(width: 145).accessibilityLabel("Store region")+ Button("Search") { store.search(query, country: country, app: model) }+ .buttonStyle(.borderedProminent).disabled(query.trimmingCharacters(in: .whitespacesAndNewlines).count < 2)+ }+ 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")+ Spacer()+ if store.searching {+ ProgressView().controlSize(.small)+ Button("Cancel") { store.cancel() }+ } else if !store.searchedQuery.isEmpty {+ Text(String(shown.count) + " results · " + store.searchedCountry).font(.caption).foregroundStyle(.secondary)+ }+ }+ if !store.searchedQuery.isEmpty {+ Text("Results for “" + store.searchedQuery + "”").font(.callout.bold())+ }+ if !store.warnings.isEmpty {+ Text(store.warnings.joined(separator: "\n")).font(.caption).foregroundStyle(.orange).textSelection(.enabled)+ }+ if shown.isEmpty {+ VStack(spacing: 14) {+ 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)+ }.frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ ScrollView {+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 285), spacing: 16)], spacing: 16) {+ ForEach(shown) { item in listing(item) }+ }.padding(.vertical, 3)+ }+ }+ Divider()+ HStack(spacing: 14) {+ Text("Search directly:").font(.caption).foregroundStyle(.secondary)+ ForEach(Launcher.allCases) { launcher in+ Button(launcher == .gog ? "GOG" : launcher.title) { openSearch(launcher) }+ .buttonStyle(.link)+ }+ }+ Text("Prices are for the selected region and may change at checkout. Listings can include add-ons and bundles. Store availability does not confirm compatibility with Soju.")+ .font(.caption).foregroundStyle(.secondary)+ }.padding(28).onDisappear { store.cancel() }+ }+ private func listing(_ item: StoreItem) -> some View {+ let owned = model.games.first { $0.id == item.id }+ return VStack(alignment: .leading, spacing: 12) {+ ZStack {+ Color.primary.opacity(0.04)+ AsyncImage(url: item.artwork.flatMap(URL.init(string:))) { image in+ image.resizable().scaledToFit()+ } 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)+ 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))+ Spacer()+ if item.mac { Text("macOS listed").font(.caption).foregroundStyle(.secondary) }+ }+ HStack {+ 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)+ }+ Spacer()+ Button("View in store") {+ if let url = URL(string: item.url), url.scheme == "https",+ ["store.steampowered.com", "www.gog.com"].contains(url.host ?? "") { NSWorkspace.shared.open(url) }+ }.buttonStyle(.borderedProminent)+ }+ }.padding(16).frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.primary.opacity(0.035), in: RoundedRectangle(cornerRadius: 13))+ }+ private func openSearch(_ launcher: Launcher) {+ var url: URLComponents+ let query = query.trimmingCharacters(in: .whitespacesAndNewlines)+ switch launcher {+ case .steam:+ url = URLComponents(string: "https://store.steampowered.com/search/")!+ url.queryItems = [URLQueryItem(name: "term", value: query), URLQueryItem(name: "cc", value: country)]+ case .gog:+ url = URLComponents(string: "https://www.gog.com/en/games")!+ url.queryItems = [URLQueryItem(name: "query", value: query)]+ case .epic:+ url = URLComponents(string: "https://store.epicgames.com/en-US/browse")!+ url.queryItems = [URLQueryItem(name: "q", value: query), URLQueryItem(name: "sortBy", value: "relevancy")]+ case .battlenet:+ url = URLComponents(string: "https://us.shop.battle.net/en-us/search")!+ url.queryItems = [URLQueryItem(name: "q", value: query)]+ }+ if let url = url.url { NSWorkspace.shared.open(url) }+ }+}diff --git a/app/Library.swift b/app/Library.swiftindex 6e434bff071..ba334485484 100644--- a/app/Library.swift+++ b/app/Library.swift@@ -8,13 +8,16 @@ struct InstalledGame: Decodable, Identifiable {let installPath: Stringlet artwork: String?let issue: String?+ let owned: Bool?+ var isInstalled: Bool { !installPath.isEmpty }enum CodingKeys: String, CodingKey {- case id, platform, title, artwork, issue+ case id, platform, title, artwork, issue, ownedcase installPath = "install_path"}}extension Launcher: Decodable {}struct LibrarySnapshot: Decodable {+ let accounts: [AccountSummary]?let games: [InstalledGame]let warnings: [String]}@@ -54,6 +57,7 @@ extension SojuModel {self.scanning = false; self.scanner = nilif process.terminationStatus == 0, let result {self.games = result.games; self.scanWarnings = result.warnings+ self.accountSummaries = result.accounts ?? []} else {self.scanWarnings = ["Could not refresh your library. Check that Python 3 is installed, then retry."]}@@ -72,6 +76,7 @@ extension SojuModel {}}func launchIssue(for game: InstalledGame) -> String? {+ if !game.isInstalled { return nil }if let issue = game.issue { return issue }if !FileManager.default.fileExists(atPath: game.installPath) {return "This game folder is unavailable. Reconnect its drive and refresh."@@ -93,6 +98,7 @@ extension SojuModel {return nil}func play(_ game: InstalledGame) {+ guard game.isInstalled else { libraryIssue = "Install this game through its official launcher first."; return }guard !busy, !launchingGames.contains(game.id) else { return }if let issue = launchIssue(for: game) { libraryIssue = issue; return }do {@@ -147,6 +153,7 @@ struct LibraryView: View {@State private var query = ""@State private var platform = "all"@State private var order = "name"+ @State private var availability = "all"@State private var selected: InstalledGame?@State private var showDiagnostics = false@Environment(\.colorScheme) private var scheme@@ -155,6 +162,7 @@ struct LibraryView: View {model.games.filter {(page != "favorites" || model.preferences.favorites.contains($0.id)) &&(platform == "all" || $0.platform.rawValue == platform) &&+ (availability == "all" || (availability == "installed") == $0.isInstalled) &&(query.isEmpty || $0.title.localizedStandardContains(query))}.sorted {if order == "recent" {@@ -172,6 +180,8 @@ struct LibraryView: View {sidebarDivider()if page == "platforms" { PlatformsView().frame(maxWidth: .infinity, maxHeight: .infinity) }+ else if page == "discover" { DiscoverView() }+ else if page == "accounts" { AccountsView() }else { library }}.frame(minWidth: 1010, minHeight: 710)@@ -197,12 +207,14 @@ struct LibraryView: View {.font(.system(size: 8, weight: .semibold)).tracking(1).foregroundStyle(.secondary).padding(.bottom, 30)nav("library", "Library", "square.grid.2x2", count: model.games.count)nav("favorites", "Favorites", "star", count: model.games.filter { model.preferences.favorites.contains($0.id) }.count)+ nav("discover", "Discover", "magnifyingglass", count: nil)Divider().padding(.vertical, 16)+ nav("accounts", "Accounts", "person.crop.circle", count: nil)nav("platforms", "Platforms", "square.stack.3d.up", count: nil)Spacer()VStack(alignment: .leading, spacing: 9) {Label("On your Mac", systemImage: "desktopcomputer").font(.system(size: 12, weight: .medium))- Text("Installed games appear automatically. Your accounts stay with each platform.")+ Text("Installed games appear automatically. Connect accounts to add your owned library.").font(.system(size: 11)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)}.padding(13).background(green.opacity(0.07), in: RoundedRectangle(cornerRadius: 12))HStack {@@ -235,7 +247,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. We’ll open the right launcher.").font(.system(size: 13)).foregroundStyle(.secondary)+ Text("Pick a game. Play it, or install it through its store.").font(.system(size: 13)).foregroundStyle(.secondary)}Spacer()Button {@@ -260,6 +272,11 @@ struct LibraryView: View {Text("Recently opened").tag("recent")}.labelsHidden().frame(width: 145).accessibilityLabel("Sort games")}+ Picker("Availability", selection: $availability) {+ Text("All games").tag("all")+ Text("Installed").tag("installed")+ Text("Not installed").tag("owned")+ }.pickerStyle(.segmented).frame(width: 340).accessibilityLabel("Game availability")if !model.scanWarnings.isEmpty {Label(model.scanWarnings.joined(separator: "\n"), systemImage: "exclamationmark.triangle").font(.system(size: 11)).foregroundStyle(.orange).textSelection(.enabled)@@ -271,11 +288,11 @@ 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 ? "Install a game through one of your platforms, then refresh.\nThis library shows games installed in Soju’s Windows environments." : 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 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.").font(.system(size: 12)).foregroundStyle(.secondary).multilineTextAlignment(.center)- Button(model.games.isEmpty ? "Manage platforms" : "Show all games") {- if model.games.isEmpty { page = "platforms" }- else { page = "library"; query = ""; platform = "all" }+ Button(model.games.isEmpty ? "Connect accounts" : "Show all games") {+ if model.games.isEmpty { page = "accounts" }+ else { page = "library"; query = ""; platform = "all"; availability = "all" }}.buttonStyle(.borderedProminent).tint(green)}.frame(maxWidth: .infinity)Spacer()@@ -288,7 +305,7 @@ struct LibraryView: View {}HStack(spacing: 8) {Circle().fill(model.failed ? Color.orange : green).frame(width: 5, height: 5)- Text(model.activity == "Ready when you are." ? "\(model.games.count) installed games · Stored locally" : model.activity)+ Text(model.activity == "Ready when you are." ? "\(model.games.count) games · \(model.games.filter { $0.isInstalled }.count) installed · Stored locally" : model.activity).lineLimit(1)Spacer()Button("Diagnostics") { showDiagnostics = true }.buttonStyle(.plain)@@ -314,16 +331,17 @@ struct LibraryView: View {Text(game.title).font(.system(size: 14, weight: .semibold)).lineLimit(2).frame(height: 36, alignment: .topLeading).frame(maxWidth: .infinity, alignment: .leading)HStack {- Text(issue == nil ? "Installed" : "Needs attention").font(.system(size: 10))+ Text(!game.isInstalled ? "Not installed" : issue == nil ? "Installed" : "Needs attention").font(.system(size: 10)).foregroundStyle(issue == nil ? Color.secondary : Color.orange)Spacer()Button {- if issue == nil { model.play(game) } else { selected = game }+ if !game.isInstalled { model.installOwnedGame(game) }+ else if issue == nil { model.play(game) } else { selected = game }} label: {- Label(model.launchingGames.contains(game.id) ? "Starting…" : issue == nil ? "Play" : "Details", systemImage: issue == nil ? "play.fill" : "exclamationmark.circle")+ 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((issue == nil ? "Play " : "Check ") + game.title)+ .accessibilityLabel((!game.isInstalled ? "Install " : issue == nil ? "Play " : "Check ") + game.title)}}.padding(14)}.background(Color(nsColor: .controlBackgroundColor), in: RoundedRectangle(cornerRadius: 14))@@ -331,7 +349,7 @@ struct LibraryView: View {.overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.primary.opacity(0.07), lineWidth: 1)).contextMenu {Button("Show details") { selected = game }- Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }+ 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)Button("Diagnose") { diagnose(game) }.disabled(model.busy)}@@ -349,19 +367,19 @@ struct LibraryView: View {VStack(alignment: .leading, spacing: 13) {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("Installed on this Mac", systemImage: "internaldrive").font(.system(size: 12)).foregroundStyle(.secondary)+ 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.").font(.system(size: 12)).foregroundStyle(.secondary)if let issue = model.launchIssue(for: game) {Label(issue, systemImage: "exclamationmark.triangle").font(.system(size: 12)).foregroundStyle(.orange)}- Text("Installation detected. Compatibility varies by game and Mac.")+ 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.").font(.system(size: 11)).foregroundStyle(.secondary)Spacer()}}HStack {- Button("Show files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: game.installPath) }+ 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)Spacer()@@ -371,7 +389,10 @@ struct LibraryView: View {Button("Platforms") { selected = nil; page = "platforms" }Spacer()Button("Close") { selected = nil }.keyboardShortcut(.cancelAction)- Button("Play") { selected = nil; model.play(game) }+ Button(game.isInstalled ? "Play" : game.platform == .steam ? "Install in Steam" : "Open Galaxy") {+ selected = nil+ if game.isInstalled { model.play(game) } else { model.installOwnedGame(game) }+ }.buttonStyle(.borderedProminent).tint(green).disabled(model.busy || model.launchIssue(for: game) != nil || model.launchingGames.contains(game.id))}diff --git a/app/Soju.swift b/app/Soju.swiftindex 4ca7c30fff6..b41747155af 100644--- a/app/Soju.swift+++ b/app/Soju.swift@@ -34,6 +34,10 @@ enum Launcher: String, CaseIterable, Identifiable {}@MainActor final class SojuModel: ObservableObject {+ @Published var accountSummaries: [AccountSummary] = []+ @Published var accountBusy = false+ @Published var accountMessage = ""+ var accountTask: Process?@Published var games: [InstalledGame] = []@Published var scanning = false@Published var scanWarnings: [String] = []diff --git a/app/SteamLogin.swift b/app/SteamLogin.swiftnew file mode 100644index 00000000000..44ba7d6332d--- /dev/null+++ b/app/SteamLogin.swift@@ -0,0 +1,151 @@+import SwiftUI+import WebKit++enum SteamWebSession {+ // WebKit's store belongs to Soju, separate from Safari and the Steam client.+ static let dataStore = WKWebsiteDataStore.default()+ static func clear(completion: @escaping () -> Void) {+ dataStore.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast, completionHandler: completion)+ }+}++@MainActor final class SteamLoginController: NSObject, ObservableObject, WKNavigationDelegate, WKUIDelegate {+ @Published var message = "Sign in on Steam's official page. Steam Guard and QR sign-in stay with Steam."+ @Published var host = "steamcommunity.com"+ @Published var reading = false+ let web: WKWebView+ private let reader: String+ private var complete: (([String: Any]) -> Void)?+ private var timer: Timer?+ private var generation = UUID()+ private var readingGeneration: UUID?+ private var openedLibrary = false+ private var active = true++ init(root: URL) {+ let config = WKWebViewConfiguration()+ config.websiteDataStore = SteamWebSession.dataStore+ config.preferences.javaScriptCanOpenWindowsAutomatically = false+ web = WKWebView(frame: .zero, configuration: config)+ reader = (try? String(contentsOf: root.appendingPathComponent("resources/steam-library.js"), encoding: .utf8)) ?? ""+ super.init()+ web.navigationDelegate = self+ web.uiDelegate = self+ }+ func start(completion: @escaping ([String: Any]) -> Void) {+ guard complete == nil else { 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+ Task { @MainActor in self?.checkLibrary() }+ }+ }+ func stop() {+ active = false; generation = UUID(); complete = nil+ timer?.invalidate(); timer = nil+ web.stopLoading()+ }+ func retry() {+ openedLibrary = false+ message = "Loading your Steam library…"+ web.load(URLRequest(url: URL(string: "https://steamcommunity.com/my/games/?tab=all")!))+ }+ private func allowed(_ url: URL?) -> Bool {+ guard let url, url.scheme == "https", url.user == nil, url.password == nil,+ url.port == nil || url.port == 443 else { return false }+ return ["steamcommunity.com", "store.steampowered.com", "login.steampowered.com", "help.steampowered.com"].contains(url.host?.lowercased() ?? "")+ }+ func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {+ let main = action.targetFrame?.isMainFrame ?? true+ // Steam may use third-party HTTPS CAPTCHA frames. They cannot become the main page.+ if !main {+ decisionHandler(action.request.url?.scheme == "https" || action.request.url?.absoluteString == "about:blank" ? .allow : .cancel)+ return+ }+ guard allowed(action.request.url) else {+ message = "This window only opens official Steam pages."+ decisionHandler(.cancel); return+ }+ if action.targetFrame == nil {+ decisionHandler(.cancel); webView.load(action.request); return+ }+ decisionHandler(.allow)+ }+ func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {+ generation = UUID(); readingGeneration = nil; reading = false+ host = allowed(webView.url) ? webView.url!.host! : "Steam"+ }+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {+ host = allowed(webView.url) ? webView.url!.host! : "Steam"+ checkLibrary()+ }+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {+ if (error as NSError).code != NSURLErrorCancelled { message = "Steam could not load. Check your connection and retry." }+ }+ 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 checkLibrary() {+ guard active, !web.isLoading, readingGeneration == nil, !reader.isEmpty,+ allowed(web.url), ["steamcommunity.com", "store.steampowered.com"].contains(web.url?.host ?? "") else { return }+ let current = generation+ readingGeneration = current+ 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 }+ switch state {+ case "ready":+ self.reading = true; self.message = "Importing your games…"+ self.timer?.invalidate(); self.timer = nil+ let callback = self.complete+ self.complete = nil; self.active = false+ callback?(value)+ case "open-library":+ if !self.openedLibrary {+ self.openedLibrary = true+ 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+ default: break+ }+ }+ }+}++struct SteamLoginWebView: NSViewRepresentable {+ let controller: SteamLoginController+ func makeNSView(context: Context) -> WKWebView { controller.web }+ func updateNSView(_ nsView: WKWebView, context: Context) {}+}++struct SteamLoginView: View {+ @StateObject private var controller: SteamLoginController+ let completion: ([String: Any]) -> Void+ let cancel: () -> Void+ init(root: URL, completion: @escaping ([String: Any]) -> Void, cancel: @escaping () -> Void) {+ _controller = StateObject(wrappedValue: SteamLoginController(root: root))+ self.completion = completion; self.cancel = cancel+ }+ var body: some View {+ VStack(spacing: 0) {+ HStack {+ VStack(alignment: .leading, spacing: 5) {+ Text("Sign in to Steam").font(.headline)+ Label("https://" + controller.host, systemImage: "lock.fill").font(.caption).foregroundStyle(.secondary)+ }+ Spacer()+ Button("Retry import") { controller.retry() }.disabled(controller.reading)+ Button("Cancel", action: cancel).keyboardShortcut(.cancelAction)+ }.padding(16)+ Divider()+ SteamLoginWebView(controller: controller)+ Divider()+ Text(controller.message).font(.callout).frame(maxWidth: .infinity, alignment: .leading).padding(16)+ }.frame(width: 940, height: 680)+ .onAppear { controller.start(completion: completion) }+ .onDisappear { controller.stop() }+ }+}diff --git a/docs/ACCOUNTS.md b/docs/ACCOUNTS.mdnew file mode 100644index 00000000000..f0bc92ff28c--- /dev/null+++ b/docs/ACCOUNTS.md@@ -0,0 +1,96 @@+# Accounts and Discover++Soju 1.6 adds owned-library imports and store discovery to the native app.++| Feature | Steam | GOG | Epic Games | Battle.net |+| --- | --- | --- | --- | --- |+| Installed games in Soju environments | Yes | Yes | Yes | Yes |+| Owned, uninstalled games | Official Steam sign-in | Galaxy local library import | Not yet | Not yet |+| Search results inside Soju | Yes | Yes | Official store link | Official store link |+| Purchases and downloads | Official client/store | Official client/store | Official client/store | Official client/store |++## Connect Steam++1. Open **Accounts → Sign in to Steam** in Soju.+2. Complete sign-in on the official Steam page, including QR sign-in or Steam Guard if requested.+3. Soju imports the signed-in account's game list when it becomes available.+4. Later, **Sync Steam library** opens the same flow and reuses the web session while Steam allows it.+ If the page cannot finish loading, choose **Retry import**. Cancel keeps the previous import.++No personal API key or profile URL is required. The sign-in window shows the current official Steam host.+Your password and Steam Guard entries go to Steam's own page; Soju does not provide a password form or read its fields.+WebKit keeps the web session in Soju's local website data, separate from your browser and Steam client.+Disconnect removes this local session. It does not log out other browsers or the official launcher.++The importer reads the signed-in user's All Games page or calls Valve's+[GetOwnedGames service](https://partner.steamgames.com/doc/webapi/iplayerservice#GetOwnedGames)+within Steam's web page using that page's existing session. Only the Steam account ID, game IDs and names+are passed to the local library helper; the saved account label is masked. Session cookies and web tokens are never sent to the helper,+written into the library snapshot or logged by Soju.++This is an embedded official website sign-in, not a Valve-approved OAuth integration.+Steam's website data format can change. An unavailable, private, incomplete or failed response leaves the+last imported library unchanged. Free games the account has played are included when Steam returns them.+Purchases, installations and the Windows Steam client's login still belong to the official client/store.++## Import GOG GALAXY++1. Open **GOG GALAXY**, sign in, and let the owned game library finish loading.+2. Return to **Accounts** in Soju and choose **Refresh account list**.+3. If Galaxy has cached multiple accounts, choose the account to import.+4. Choose **Import from Galaxy**.++The importer reads Galaxy's local database in read-only mode. It checks the selected account's ownership records,+excludes DLC records, and obtains game titles from local product/title metadata.+It does not read passwords, authentication tokens, activation keys or product authorization secrets.+Galaxy 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.++## 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.+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.++Account snapshots are saved under `~/.battlenet-macos/account-libraries` with private file permissions.+Favorites and recently opened game requests remain local. **Disconnect** removes the selected import and, for Steam,+its saved Soju web session. Installed games are preserved. Imports are manual snapshots; they do not update automatically in the background.++## Discover++Enter a game name and choose the store region: US/USD, Korea/KRW, UK/GBP, Germany/EUR or Japan/JPY.+Soju searches the public Steam and GOG catalog endpoints in parallel.+Results include titles, store artwork, prices where returned, and an installed/owned badge for matching platform IDs.+A failed store does not hide results from the other store. Missing prices are labeled **View price in store**.++**View in store** opens the official product page in your default browser. Search links are also available for+Steam, GOG, Epic Games and Battle.net. No purchases are submitted by Soju.++Listings may include DLC and bundles. Prices are region-dependent and can change at checkout.+Store availability or a listed macOS version is not a compatibility guarantee for the Windows version running through Soju.+Search queries go to Steam/GOG and result artwork loads from their CDNs. Your library is not uploaded to either store+to produce ownership badges, and no telemetry or analytics are added.++## CLI and maintenance++```bash+soju library+soju game <installed-id>+soju game-install <owned-id>+soju search "The Witcher 3" --country US+```++The Steam library reader executes inside the official Steam page and returns a metadata-only snapshot.+The local service bridge accepts that snapshot through stdin and validates it before replacing the saved import.+No Steam password, cookie, token or API key is accepted by the helper.+`library_services.py` owns provider parsing, bounded responses, read-only Galaxy queries and atomic local imports.++Steam's website, store catalogs and Galaxy's local schema can change independently of Soju.+Provider failures are shown as recoverable errors rather than empty successful account imports.+Tests cover account separation, ownership/DLC filtering, private Steam responses, cache preservation, secret-free errors,+private cache permissions, safe product/artwork URLs, partial search failures and installed/owned merging.diff --git a/docs/DESKTOP.md b/docs/DESKTOP.mdindex fb1d4bcfdf9..664c0369b4d 100644--- a/docs/DESKTOP.md+++ b/docs/DESKTOP.md@@ -1,13 +1,17 @@# Soju for Mac-[Download v1.5.0](https://github.com/BCD1210/soju/releases/download/v1.5.0/Soju-1.5.0-macos-arm64.zip)+[Download v1.6.0](https://github.com/BCD1210/soju/releases/download/v1.6.0/Soju-1.6.0-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.3. Install games through the official clients and return to **Library**.4. Search, filter by platform, star favorites and click a game's **Play** button.Use **Refresh** after installing a game or reconnecting an external game drive.-5. Open a game's details for **Diagnose**, **Show files** and its official launcher.+5. Open **Accounts** to connect Steam or import the owned library saved by Galaxy.+ Use the **Installed / Not installed** filter to choose what to play or install.+6. Open **Discover** to search Steam and GOG, select a price region, and visit+ the official product page. Epic and Battle.net have direct store search links.+7. Open a game's details for **Diagnose**, **Show files** and its official launcher.@@ -44,8 +48,16 @@ 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.-Native Mac games, other Wine managers, uninstalled owned games, account syncing,-store search and purchases inside Soju are outside this release's library scope.+Steam account imports use the official Steam website sign-in; 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.++Discover shows Steam and GOG listings, including add-ons and bundles, with prices+for US, Korea, UK, Germany or Japan. Purchases finish at the official store.+See [account setup and privacy](ACCOUNTS.md) for details.++Native Mac games, other Wine managers, and full Epic/Battle.net account imports+are outside this release's library scope.Unknown Battle.net product codes are shown with a shortcut to the official client;Soju does not guess how to launch them. **Installed** does not mean compatibilityhas been verified. Anti-cheat, game requirements, store logins and updates still apply.@@ -53,14 +65,20 @@ has been verified. Anti-cheat, game requirements, store logins and updates stillArtwork comes from Steam's local cache or icons already installed with games.Extracted icons are cached under `~/.battlenet-macos/library-artwork`.Favorites and recent launch requests stay in the app's local preferences.-Scanning does not read store passwords or tokens and does not contact store APIs.+Local scanning does not read store passwords or tokens and does not contact store APIs.+Explicit Steam sync contacts Valve; Discover contacts Steam/GOG and their artwork+CDNs. Steam authentication stays in Soju's local WebKit session. Only game metadata+is passed to the helper; Soju does not log cookies or tokens. Account snapshots are stored locally with private+file permissions in `~/.battlenet-macos/account-libraries`.Play sends the official launcher a request; Soju does not claim to track whethera game is running or how many hours were played.-CLI equivalents: `soju library` prints installed games as JSON;+CLI equivalents: `soju library` prints installed and imported owned games as JSON;`soju game <id>` launches an ID from that list. Each launch rechecks the currentinstallation record. `python3 scripts/game-library.py launch <id> --dry-run`-prints the argument list without starting a game.+prints the argument list without starting a game. `soju game-install <id>` opens+the official client to install an owned game. `soju search "Witcher" --country US`+searches Steam and GOG without an account.## Updates and recoverydiff --git a/docs/assets/soju-discover.png b/docs/assets/soju-discover.pngnew file mode 100644index 00000000000..d8a5873a0f8Binary files /dev/null and b/docs/assets/soju-discover.png differdiff --git a/docs/assets/soju-library.png b/docs/assets/soju-library.pngindex 7313647e163..2a32967f360 100644Binary files a/docs/assets/soju-library.png and b/docs/assets/soju-library.png differdiff --git a/docs/index.html b/docs/index.htmlindex 7005428a2c1..1ae7bf388c9 100644--- a/docs/index.html+++ b/docs/index.html@@ -4,7 +4,7 @@<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Soju — Free, open-source game library for Apple Silicon Macs</title>-<meta name="description" content="One native Mac library for games installed through Battle.net, Steam, Epic and GOG. Search, favorite, launch and diagnose games on Apple Silicon with Soju.">+<meta name="description" content="One native Mac library for games installed through Battle.net, Steam, Epic and GOG. Import Steam and GOG owned games, search store listings and play through official launchers on Apple Silicon."><link rel="canonical" href="https://bcd1210.github.io/soju/"><meta property="og:title" content="Soju — Your games, one home on your Mac"><meta property="og:description" content="A free, open-source launcher toolkit for Apple Silicon. Battle.net, Steam, Epic and GOG — with documented setup and compatibility.">@@ -22,6 +22,7 @@<nav aria-label="Main navigation"><div class="inner"><a class="brand" href="./">🍶 Soju</a><a href="#demo">Demo</a>+ <a href="#discover">Discover</a><a href="#launchers">Launchers</a><a href="#install">Install</a><a href="#compatibility">Compatibility</a>@@ -34,7 +35,7 @@<h1>Your games.<br>One home on your Mac.</h1><p class="lead">A free, open-source game library for Apple Silicon.Find installed games from Battle.net, Steam, Epic and GOG in one native Mac app.-Search your library, save favorites and play through the official launchers.</p>+Connect Steam or GOG owned libraries, find your next game and play through the official launchers.</p><p>Set up and manage your platforms in Soju. Accounts, purchases and game updatesstay with each store. Compatibility depends on the game and your Mac.</p><div class="actions"><a class="btn" href="#install">Install Soju</a>@@ -43,10 +44,21 @@ stay with each store. Compatibility depends on the game and your Mac.</p><section id="library" aria-labelledby="library-title"><h2 id="library-title">Installed games, together.</h2><p>Local detection, platform filters, favorites and game-specific diagnostics.-No new Soju account. No library uploads. Uninstalled owned games and store search are planned separately.</p>+Sign in to Steam to import your owned library, or read the owned games cached by GOG GALAXY. No API key required. No new Soju account. No library uploads.</p><img src="assets/soju-library.png" width="1140" height="780" style="width:100%;height:auto;border-radius:16px" alt="Soju's unified library showing four installed games across Battle.net, Steam, Epic and GOG"></section>+<section id="discover" aria-labelledby="discover-title">+<h2 id="discover-title">Find your next game.</h2>+<p>Search Steam and GOG listings with prices for your selected region. See which+listings are already in your library, then visit the official store to buy.+Direct search links also open Epic Games and Battle.net.</p>+<img src="assets/soju-discover.png" width="1140" height="780" style="width:100%;height:auto;border-radius:16px" alt="Soju Discover showing live Steam and GOG search results with store prices">+<p class="note">Store results may include add-ons and bundles. Final prices and+compatibility should be checked before purchase. Epic and Battle.net account+imports are not available yet. <a href="https://github.com/BCD1210/soju/blob/main/docs/ACCOUNTS.md">Account setup and privacy</a>.</p>+</section>+<section id="demo" aria-labelledby="demo-title"><h2 id="demo-title">See the games running on a Mac.</h2><p>A 30-second gameplay demo: Hogwarts Legacy through Epic and Guilt Free through Steam,@@ -88,8 +100,8 @@ 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.5.0/Soju-1.5.0-macos-arm64.zip">Download Soju for Mac</a></p>-<p>The native desktop preview combines your installed games and manages all four launchers.+<p><a class="btn" href="https://github.com/BCD1210/soju/releases/download/v1.6.0/Soju-1.6.0-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><p>Prefer the terminal? Select launchers before any downloads. Steam-only installs skip the CX engine and Apple GPTK.</p>diff --git a/resources/steam-library.js b/resources/steam-library.jsnew file mode 100644index 00000000000..bf2ad334762--- /dev/null+++ b/resources/steam-library.js@@ -0,0 +1,64 @@+// Runs only inside the signed-in user's Steam page. No cookies or tokens leave WebKit.+if (location.protocol !== "https:" || !["steamcommunity.com", "store.steampowered.com"].includes(location.hostname)) {+ return { state: "wrong-page" };+}+const config = document.getElementById("application_config");+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" };++function snapshot(rows, count) {+ if (!Array.isArray(rows) || !Number.isInteger(count) || count < 0 ||+ count > 20000 || rows.length !== count) return { state: "unavailable" };+ const games = [];+ const seen = new Set();+ for (const row of rows) {+ if (!row || !/^[1-9][0-9]{0,9}$/.test(String(row.appid)) ||+ typeof row.name !== "string" || !row.name.trim() || row.name.length > 1000) {+ return { state: "unavailable" };+ }+ const appid = String(row.appid);+ if (seen.has(appid)) return { state: "unavailable" };+ seen.add(appid);+ games.push({ appid, name: row.name.trim().slice(0, 300) });+ }+ return { state: "ready", steamid, game_count: games.length, games };+}++// The full All Games page carries names for unavailable/delisted titles as well.+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);+}++// 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);+try {+ 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" };+ return snapshot(value.games || [], value.game_count);+} catch {+ return { state: "unavailable" };+} finally {+ clearTimeout(timer);+}diff --git a/scripts/build-app.sh b/scripts/build-app.shindex 8e28741ed4a..ae16ee0107c 100755--- a/scripts/build-app.sh+++ b/scripts/build-app.sh@@ -10,7 +10,7 @@ trap 'rm -rf "$STAGE"' EXITAPP="$STAGE/Soju.app"mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/soju"swiftc -swift-version 5 -parse-as-library -O -target arm64-apple-macosx14.0 \- "$ROOT/app/Soju.swift" "$ROOT/app/Library.swift" -o "$APP/Contents/MacOS/Soju"+ "$ROOT/app/Soju.swift" "$ROOT/app/Library.swift" "$ROOT/app/Accounts.swift" "$ROOT/app/Discover.swift" "$ROOT/app/SteamLogin.swift" -o "$APP/Contents/MacOS/Soju"for dir in scripts tools patches third_party resources; doditto "$ROOT/$dir" "$APP/Contents/Resources/soju/$dir"donediff --git a/scripts/desktop-action.sh b/scripts/desktop-action.shindex e305cd301ea..efa465fed2f 100755--- a/scripts/desktop-action.sh+++ b/scripts/desktop-action.sh@@ -6,6 +6,8 @@ BASE="${SOJU_BASE:-$HOME/.battlenet-macos}"export SOJU_BASE="$BASE"ACTION="${1:-}"; shift || truecase "$ACTION" in+ service) exec python3 "$ROOT/scripts/library-service.py" "$@" ;;+ game-install) exec python3 "$ROOT/scripts/game-library.py" install "${1:?Choose a game}" ;;library) exec python3 "$ROOT/scripts/game-library.py" list ;;game) exec python3 "$ROOT/scripts/game-library.py" launch "${1:?Choose a game}" ;;game-doctor) exec python3 "$ROOT/scripts/game-library.py" diagnose "${1:?Choose a game}" ;;diff --git a/scripts/game-library.py b/scripts/game-library.pyindex df34c7484e4..24c600cde08 100644--- a/scripts/game-library.py+++ b/scripts/game-library.py@@ -13,6 +13,7 @@ import sqlite3import syssys.path.insert(0, str(Path(__file__).resolve().parent))from game_artwork import executable_icon+from library_services import saved_accountsfrom urllib.parse import quoteFOLDERS = {'steam': 'steam-bottle', 'epic': 'epic-bottle',@@ -287,14 +288,28 @@ class Library:try: getattr(self, platform)()except (OSError, ValueError, KeyError, TypeError, sqlite3.Error):self.warn(platform, 'Installation records are temporarily unavailable. Open the launcher and refresh.')- return {'games': [{k: v for k, v in g.items() if k != 'arguments'}+ accounts, owned, warnings = saved_accounts(self.base)+ self.warnings.extend(warnings)+ for game in owned:+ if game['id'] in self.games:+ self.games[game['id']]['owned'] = True+ else:+ self.games[game['id']] = dict(game, arguments=[])+ return {'accounts': accounts, 'games': [{k: v for k, v in g.items() if k != 'arguments'}for g in sorted(self.games.values(), key=lambda g: (g['title'].casefold(), g['id']))],'warnings': self.warnings}- def command(self, game_id):+ def command(self, game_id, install=False):self.scan()game = self.games.get(game_id)if game is None: raise ValueError('This game is no longer installed. Refresh the library.')+ 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']]+ if not client.is_file(): raise ValueError('Install this launcher in Platforms first.')+ args = ['steam://install/' + game_id.split(':', 1)[1]] if game['platform'] == 'steam' else []+ return ['/bin/bash', str(Path(__file__).resolve().parent / 'play.sh'), game['platform']] + args+ if 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']@@ -302,7 +317,7 @@ class Library:def main():parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument('action', choices=['list', 'launch', 'diagnose'], nargs='?', default='list')+ parser.add_argument('action', choices=['list', 'launch', 'diagnose', 'install'], nargs='?', default='list')parser.add_argument('game_id', nargs='?')parser.add_argument('--base', default=os.environ.get('SOJU_BASE', str(Path.home() / '.battlenet-macos')))parser.add_argument('--dry-run', action='store_true', help='Print launch argv without starting anything')@@ -319,7 +334,7 @@ def main():print(game['title'] + ' — ' + game['platform'], flush=True)print(game['issue'] or 'Installation found. Checking the platform environment…', flush=True)command = ['/bin/bash', str(Path(__file__).resolve().parent / 'doctor.sh'), game['platform']]- else: command = lib.command(args.game_id)+ else: command = lib.command(args.game_id, install=args.action == 'install')if args.dry_run: print(json.dumps(command)); returnenv = dict(os.environ, SOJU_BASE=str(lib.base))for key in ['WINEPREFIX', 'ENGINE']: env.pop(key, None)diff --git a/scripts/library-service.py b/scripts/library-service.pynew file mode 100644index 00000000000..75c5f5307aa--- /dev/null+++ b/scripts/library-service.py@@ -0,0 +1,55 @@+#!/usr/bin/env python3+"""Soju service bridge. Account library snapshots are accepted only on stdin."""+import argparse+import json+import os+from pathlib import Path+import sqlite3+import sys+from library_services import (ServiceError, search, steam_owned, gog_owned, gog_users,+ save_account, account_path)++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('action', choices=['search', 'sync', 'forget', 'gog-users'])+ parser.add_argument('value', nargs='?', default='')+ parser.add_argument('--country', default='US')+ parser.add_argument('--base', default=os.environ.get('SOJU_BASE', str(Path.home()/'.battlenet-macos')))+ args = parser.parse_args()+ try:+ if args.action == 'search':+ result = search(args.value, args.country)+ elif args.action == 'gog-users':+ result = {'users': gog_users(args.base)}+ elif args.action == 'forget':+ account_path(args.base, args.value).unlink(missing_ok=True)+ result = {'message': 'Account import removed. Installed games are kept.'}+ else:+ payload = sys.stdin.read(8 * 1024 * 1024 + 1)+ if len(payload) > 8 * 1024 * 1024:+ raise ServiceError('Account settings are too large.')+ settings = json.loads(payload or '{}')+ if not isinstance(settings, dict):+ raise ServiceError('Invalid account settings.')+ if args.value == 'steam':+ games, label = steam_owned(settings)+ elif args.value == 'gog':+ games, label = gog_owned(args.base, settings)+ else:+ raise ServiceError('Unsupported account provider.')+ result = save_account(args.base, args.value, games, label)+ print(json.dumps(result, ensure_ascii=False))+ except ServiceError as error:+ print(json.dumps({'error': str(error)}))+ return 1+ except sqlite3.Error:+ print(json.dumps({'error': 'Galaxy library is busy or its format changed. Let Galaxy finish loading, then retry.'}))+ return 1+ except Exception:+ # Do not include raw exceptions, response bodies or credentials in logs.+ print(json.dumps({'error': 'Could not complete this request. Your previous account import is unchanged.'}))+ return 1+ return 0++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/library_services.py b/scripts/library_services.pynew file mode 100644index 00000000000..efe949dcafc--- /dev/null+++ b/scripts/library_services.py@@ -0,0 +1,288 @@+"""Public store search and locally saved account libraries. Python 3.9+."""+import concurrent.futures+import datetime+import json+import os+from pathlib import Path+import re+import sqlite3+import tempfile+import time+import urllib.error+import urllib.parse+import urllib.request++LIMIT = 8 * 1024 * 1024+REGIONS = {'US': 'USD', 'KR': 'KRW', 'GB': 'GBP', 'DE': 'EUR', 'JP': 'JPY'}+STORES = {'steam': 'https://store.steampowered.com', 'gog': 'https://www.gog.com'}+++class ServiceError(ValueError):+ pass+++class NoRedirect(urllib.request.HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ raise ServiceError('The service redirected the request. Please retry later.')+++def get_json(url):+ # Keep provider errors concise; never log response bodies or request details.+ try:+ request = urllib.request.Request(url, headers={'User-Agent': 'Soju/1.6 (+https://github.com/BCD1210/soju)', 'Accept': 'application/json'})+ with urllib.request.build_opener(NoRedirect).open(request, timeout=15) as response:+ data = response.read(LIMIT + 1)+ if len(data) > LIMIT:+ raise ServiceError('The service returned too much data.')+ return json.loads(data)+ except urllib.error.HTTPError as error:+ if error.code in (401, 403):+ raise ServiceError('Access was not granted. Check your account settings or use the official store.') from None+ if error.code == 429:+ raise ServiceError('Too many requests. Please retry in a few minutes.') from None+ raise ServiceError('The service is temporarily unavailable.') from None+ except (OSError, ValueError) as error:+ if isinstance(error, ServiceError):+ raise+ raise ServiceError('Could not read the service response. Check your connection and retry.') from None+++def text(value, limit=300):+ return value.strip()[:limit] if isinstance(value, str) else ''+++def numeric_id(value):+ value = str(value)+ if not re.fullmatch(r'[0-9]{1,20}', value) or int(value) == 0:+ raise ServiceError('Invalid game identifier.')+ return value+++def safe_image(value, platform):+ if not isinstance(value, str):+ return None+ parsed = urllib.parse.urlsplit(value)+ allowed = {'steam': ('steamstatic.com', 'steamcdn-a.akamaihd.net'),+ 'gog': ('gog-statics.com', 'gog.com')}+ host = (parsed.hostname or '').lower()+ if parsed.scheme != 'https' or parsed.username or parsed.password or parsed.port not in (None, 443):+ return None+ return value if any(host == h or host.endswith('.' + h) for h in allowed[platform]) else None+++def store_url(platform, uid, slug=''):+ if platform == 'steam':+ return STORES[platform] + '/app/' + numeric_id(uid) + '/'+ if slug and re.fullmatch(r'[a-zA-Z0-9_-]{1,200}', slug):+ return STORES['gog'] + '/en/game/' + slug+ return STORES['gog'] + '/game/' + numeric_id(uid)+++def steam_search(query, country):+ url = STORES['steam'] + '/api/storesearch/?' + urllib.parse.urlencode({'term': query, 'l': 'english', 'cc': country})+ data = get_json(url)+ if not isinstance(data, dict) or not isinstance(data.get('items'), list):+ raise ServiceError('Steam search is unavailable.')+ result = []+ for item in data['items'][:24]:+ try:+ uid = numeric_id(item['id'])+ if item.get('type') != 'app' or not text(item.get('name')):+ continue+ price = item.get('price') or {}+ amount, currency = price.get('final'), price.get('currency')+ label = 'View price in store'+ if isinstance(amount, int) and amount >= 0 and re.fullmatch(r'[A-Z]{3}', currency or ''):+ label = 'Free' if amount == 0 else currency + ' ' + format(amount / 100, ',.2f')+ result.append(dict(id='steam:' + uid, platform='steam', title=text(item['name']),+ url=store_url('steam', uid), artwork=safe_image(item.get('tiny_image'), 'steam'),+ price=label, mac=bool(item.get('platforms', {}).get('mac')), windows=bool(item.get('platforms', {}).get('windows'))))+ except (KeyError, TypeError, ValueError, AttributeError):+ continue+ return result+++def gog_search(query, country):+ url = 'https://catalog.gog.com/v1/catalog?' + urllib.parse.urlencode({+ 'query': query, 'limit': 24, 'locale': 'en-US', 'countryCode': country,+ 'currencyCode': REGIONS[country], 'productType': 'in:game,pack'})+ data = get_json(url)+ if not isinstance(data, dict) or not isinstance(data.get('products'), list):+ raise ServiceError('GOG search is unavailable.')+ result = []+ for item in data['products'][:24]:+ try:+ uid = numeric_id(item['id'])+ if not text(item.get('title')):+ continue+ price = item.get('price') or {}+ money = price.get('finalMoney') or {}+ label = 'View price in store'+ if re.fullmatch(r'[0-9]+(?:\.[0-9]+)?', str(money.get('amount', ''))) and re.fullmatch(r'[A-Z]{3}', money.get('currency', '')):+ label = 'Free' if float(money['amount']) == 0 else money['currency'] + ' ' + str(money['amount'])+ systems = item.get('operatingSystems') or []+ result.append(dict(id='gog:' + uid, platform='gog', title=text(item['title']),+ url=store_url('gog', uid, item.get('slug', '')),+ artwork=safe_image(item.get('coverHorizontal'), 'gog'), price=label,+ mac='osx' in systems or 'mac' in systems, windows='windows' in systems))+ except (KeyError, TypeError, ValueError, AttributeError):+ continue+ return result+++def search(query, country):+ query = text(query, 100)+ if len(query) < 2:+ raise ServiceError('Enter at least two characters.')+ 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)]}+ for job in concurrent.futures.as_completed(jobs):+ try:+ games.extend(job.result())+ except Exception:+ warnings.append(jobs[job].title() + ' search is unavailable. You can still open its official store below.')+ unique = {g['id']: g for g in games}+ def rank(game):+ title, term = game['title'].casefold(), query.casefold()+ score = 0 if title == term else 1 if title.startswith(term) else 2 if term in title else 3 if all(word in title for word in term.split()) else 4+ return score, title, game['platform']+ return dict(games=sorted(unique.values(), key=rank), warnings=sorted(warnings), country=country)+++def steam_owned(settings):+ """Validate the metadata-only snapshot returned by Steam's signed-in web page."""+ try:+ value = json.loads(settings.get('snapshot', ''))+ except (ValueError, TypeError):+ raise ServiceError('Sign in to Steam in Accounts to import your library.') from None+ if not isinstance(value, dict) or value.get('state') != 'ready':+ raise ServiceError('Steam did not share a complete library. Your previous import is unchanged.')+ profile = value.get('steamid')+ if not isinstance(profile, str) or not re.fullmatch(r'765[0-9]{14}', profile):+ raise ServiceError('Steam could not confirm the signed-in account.')+ source, count = value.get('games'), value.get('game_count')+ if not isinstance(source, list) or type(count) is not int or not 0 <= count <= 20000 or len(source) != count:+ raise ServiceError('Steam returned an incomplete library. Please retry.')+ games, seen = [], set()+ for item in source:+ if not isinstance(item, dict):+ raise ServiceError('Steam returned invalid game metadata.')+ uid, title = numeric_id(item.get('appid')), text(item.get('name'))+ if not title or uid in seen:+ raise ServiceError('Steam returned incomplete game names. Please retry.')+ seen.add(uid)+ games.append(dict(id='steam:' + uid, platform='steam', title=title))+ return games, 'Steam · …' + profile[-4:]+++def gog_database(base):+ path = Path(base) / 'gog-bottle/drive_c/ProgramData/GOG.com/Galaxy/storage/galaxy-2.0.db'+ if not path.is_file():+ raise ServiceError('Open GOG GALAXY, sign in and let your library load, then retry.')+ db = sqlite3.connect(path.absolute().as_uri() + '?mode=ro', uri=True, timeout=1)+ db.execute('PRAGMA query_only=ON')+ deadline = time.monotonic() + 4+ db.set_progress_handler(lambda: int(time.monotonic() > deadline), 10000)+ return db+++def gog_users(base):+ db = gog_database(base)+ try:+ rows = db.execute("""SELECT r.userId, COUNT(*) FROM LibraryReleases r+ JOIN LicensedReleases l ON l.libraryId=r.id+ WHERE l.isOwned=1 AND r.releaseKey GLOB 'gog_[0-9]*'+ GROUP BY r.userId ORDER BY r.userId""").fetchall()+ return [dict(id=str(uid), label='Galaxy · …' + str(uid)[-4:], count=count) for uid, count in rows]+ finally:+ db.close()+++def gog_owned(base, settings):+ users = gog_users(base)+ selected = settings.get('user_id') or (users[0]['id'] if len(users) == 1 else None)+ if not selected or selected not in {u['id'] for u in users}:+ raise ServiceError('Select a Galaxy account. If none appear, open Galaxy and let your owned library load.')+ db = gog_database(base)+ try:+ # releaseKey is a platform/game identifier. No auth, license-key or token columns are read.+ rows = db.execute("""SELECT r.releaseKey, p.name, gp.value FROM LibraryReleases r+ JOIN LicensedReleases l ON l.libraryId=r.id AND l.isOwned=1+ LEFT JOIN ReleaseProperties rp ON rp.releaseKey=r.releaseKey+ LEFT JOIN ProductsToReleaseKeys pr ON pr.releaseKey=r.releaseKey+ LEFT JOIN Products p ON p.id=pr.gogId+ LEFT JOIN GamePieces gp ON gp.releaseKey=r.releaseKey+ AND gp.gamePieceTypeId=(SELECT id FROM GamePieceTypes WHERE type='originalTitle')+ WHERE r.userId=? AND r.releaseKey GLOB 'gog_[0-9]*'+ AND COALESCE(rp.isDlc,0)=0 LIMIT 40001""", (selected,)).fetchall()+ finally:+ db.close()+ if len(rows) > 40000:+ raise ServiceError('Galaxy returned too much metadata.')+ games = {}+ for release, name, value in rows:+ uid = numeric_id(release.removeprefix('gog_'))+ title = text(name)+ if not title and value:+ parsed = json.loads(value)+ title = text(parsed.get('title')) if isinstance(parsed, dict) else text(parsed)+ if not title:+ raise ServiceError('Galaxy is still loading game names. Open its library and retry. Your previous import is unchanged.')+ games[uid] = dict(id='gog:' + uid, platform='gog', title=title)+ return list(games.values()), 'Galaxy · …' + selected[-4:]+++def account_path(base, platform):+ if platform not in ('steam', 'gog'):+ raise ServiceError('Unsupported account provider.')+ return Path(base) / 'account-libraries' / (platform + '.json')+++def save_account(base, platform, games, label):+ 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)+ data = json.dumps(payload, ensure_ascii=False).encode()+ if len(data) > LIMIT:+ raise ServiceError('This library exceeds the supported import size.')+ fd, temporary = tempfile.mkstemp(prefix='.' + platform, dir=path.parent)+ try:+ with os.fdopen(fd, 'wb') as stream:+ stream.write(data)+ os.replace(temporary, path)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+ return dict(message='Imported ' + str(len(games)) + ' games.', count=len(games))+++def saved_accounts(base):+ accounts, games, warnings = [], [], []+ for platform in ('steam', 'gog'):+ path = account_path(base, platform)+ if not path.is_file():+ continue+ try:+ with path.open('rb') as stream:+ data = stream.read(LIMIT + 1)+ if len(data) > LIMIT:+ raise ValueError()+ data = json.loads(data)+ if data.get('schema') != 1 or data.get('platform') != platform or not isinstance(data.get('games'), list):+ raise ValueError()+ imported = {}+ for game in data['games']:+ uid = numeric_id(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)+ games.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.')+ return accounts, games, warningsdiff --git a/scripts/soju b/scripts/sojuindex d88a3e6acac..07ab4673aa0 100755--- a/scripts/soju+++ b/scripts/soju@@ -18,8 +18,10 @@ soju: open-source Windows launchers on Apple SiliconUsage:soju install Choose and install any of the four launcherssoju app Build, install and open the native Soju app- soju library List installed games as JSON+ soju library List installed and imported games as JSONsoju game <id> Play a game from the unified library+ soju 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 --version Print the Soju versionsoju battlenet Launch Battle.net (default bottle)soju d2r Launch Diablo II: Resurrected directly@@ -48,6 +50,8 @@ EOF}case "${1:-}" in+ search) shift; exec python3 "$ROOT/scripts/library-service.py" search "$@" ;;+ game-install) shift; exec python3 "$ROOT/scripts/game-library.py" install "$@" ;;library) exec python3 "$ROOT/scripts/game-library.py" list ;;game) shift; exec python3 "$ROOT/scripts/game-library.py" launch "$@" ;;--version) cat "$ROOT/VERSION" ;;diff --git a/tests/test_library.py b/tests/test_library.pyindex 6a8b6551f44..b22ee701929 100644--- a/tests/test_library.py+++ b/tests/test_library.py@@ -176,7 +176,7 @@ class LibraryTests(unittest.TestCase):self.assertIn('drive is unavailable', result['warnings'][0])def test_no_installations_is_valid_empty_library(self):- self.assertEqual(self.lib.scan(), {'games': [], 'warnings': []})+ self.assertEqual(self.lib.scan(), {'accounts': [], 'games': [], 'warnings': []})if __name__ == '__main__': unittest.main()diff --git a/tests/test_services.py b/tests/test_services.pynew file mode 100644index 00000000000..f1ba2b9e1a4--- /dev/null+++ b/tests/test_services.py@@ -0,0 +1,195 @@+import importlib.util+import json+import os+from pathlib import Path+import sqlite3+import stat+import subprocess+import sys+import tempfile+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+spec = importlib.util.spec_from_file_location('soju_account_scanner', ROOT/'scripts/game-library.py')+scanner = importlib.util.module_from_spec(spec)+spec.loader.exec_module(scanner)+++class StoreTests(unittest.TestCase):+ def test_steam_prices_and_missing_price(self):+ payload = {'items': [+ {'type': 'app', 'id': 10, 'name': 'Game', 'price': {'final': 0, 'currency': 'USD'}},+ {'type': 'app', 'id': 20, 'name': 'Unpriced'},+ {'type': 'app', 'id': 30, 'name': 'Paid', 'price': {'final': 1999, 'currency': 'USD'}}]}+ with patch.object(svc, 'get_json', return_value=payload):+ rows = svc.steam_search('game', 'US')+ self.assertEqual([x['price'] for x in rows], ['Free', 'View price in store', 'USD 19.99'])+ self.assertEqual(rows[0]['url'], 'https://store.steampowered.com/app/10/')++ def test_gog_currency_and_fixed_store_host(self):+ payload = {'products': [{'id': '10', 'title': 'A game', 'slug': '../../evil',+ 'price': {'finalMoney': {'amount': '14.99', 'currency': 'EUR'}},+ 'coverHorizontal': 'https://evil.example/art.png', 'operatingSystems': ['windows']}]}+ with patch.object(svc, 'get_json', return_value=payload):+ game = svc.gog_search('game', 'DE')[0]+ self.assertEqual(game['price'], 'EUR 14.99')+ self.assertEqual(game['url'], 'https://www.gog.com/game/10')+ self.assertIsNone(game['artwork'])++ def test_artwork_host_validation(self):+ for value in ['file:///etc/passwd', 'https://steamstatic.com.evil.test/x',+ 'https://[email protected]/x', 'http://shared.steamstatic.com/x',+ 'https://shared.steamstatic.com:8080/x']:+ self.assertIsNone(svc.safe_image(value, 'steam'))+ self.assertEqual(svc.safe_image('https://shared.steamstatic.com/x', 'steam'), 'https://shared.steamstatic.com/x')++ def test_one_store_failure_keeps_other_results(self):+ game = dict(id='steam:10', platform='steam', title='Witcher')+ with patch.object(svc, 'steam_search', return_value=[game]), patch.object(svc, 'gog_search', side_effect=svc.ServiceError('offline')):+ data = svc.search('witcher', 'US')+ self.assertEqual(data['games'], [game])+ self.assertEqual(len(data['warnings']), 1)++ def test_relevance_precedes_alphabetical_order(self):+ games = [dict(id='steam:1', platform='steam', title='An unrelated game'),+ dict(id='steam:2', platform='steam', title='The Witcher 3')]+ with patch.object(svc, 'steam_search', return_value=games), patch.object(svc, 'gog_search', return_value=[]):+ self.assertEqual(svc.search('witcher', 'US')['games'][0]['id'], 'steam:2')++ def test_invalid_search_does_not_send_request(self):+ with patch.object(svc, 'get_json') as fetch:+ for query, region in [('x', 'US'), ('game', '../')]:+ with self.assertRaises(svc.ServiceError): svc.search(query, region)+ fetch.assert_not_called()++ def test_redirects_are_not_followed(self):+ with self.assertRaises(svc.ServiceError):+ svc.NoRedirect().redirect_request(None, None, 302, '', {}, 'https://other.example/')+++class AccountTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.base = Path(self.tmp.name)++ def tearDown(self):+ self.tmp.cleanup()++ def create_galaxy(self):+ path = self.base/'gog-bottle/drive_c/ProgramData/GOG.com/Galaxy/storage/galaxy-2.0.db'+ path.parent.mkdir(parents=True)+ db = sqlite3.connect(path)+ db.executescript("""+ CREATE TABLE LibraryReleases(id INTEGER,userId INTEGER,releaseKey TEXT);+ CREATE TABLE LicensedReleases(libraryId INTEGER,isOwned INTEGER);+ CREATE TABLE ReleaseProperties(releaseKey TEXT,isDlc INTEGER);+ CREATE TABLE ProductsToReleaseKeys(releaseKey TEXT,gogId INTEGER);+ CREATE TABLE Products(id INTEGER,name TEXT);+ CREATE TABLE GamePieceTypes(id INTEGER,type TEXT);+ CREATE TABLE GamePieces(releaseKey TEXT,gamePieceTypeId INTEGER,value TEXT);+ INSERT INTO GamePieceTypes VALUES(1,'originalTitle');+ INSERT INTO LibraryReleases VALUES(1,111,'gog_10'),(2,111,'gog_20'),(3,111,'gog_30'),(4,222,'gog_40');+ INSERT INTO LicensedReleases VALUES(1,1),(2,0),(3,1),(4,1);+ INSERT INTO ReleaseProperties VALUES('gog_30',1);+ INSERT INTO ProductsToReleaseKeys VALUES('gog_10',10);+ INSERT INTO Products VALUES(10,'Owned Game');+ INSERT INTO GamePieces VALUES('gog_40',1,'{"title":"Another Account Game"}');+ """)+ db.commit(); db.close()+ return path++ def test_gog_requires_account_choice_and_excludes_unowned_dlc(self):+ self.create_galaxy()+ with self.assertRaises(svc.ServiceError): svc.gog_owned(self.base, {})+ games, _ = svc.gog_owned(self.base, {'user_id': '111'})+ self.assertEqual([g['id'] for g in games], ['gog:10'])++ def test_gog_uninstalled_game_metadata_and_readonly(self):+ path = self.create_galaxy()+ before = path.read_bytes()+ games, _ = svc.gog_owned(self.base, {'user_id': '222'})+ self.assertEqual(games[0]['title'], 'Another Account Game')+ self.assertEqual(path.read_bytes(), before)++ def test_steam_snapshot_valid_empty_and_incomplete(self):+ value = dict(state='ready', steamid='76561198000000000', game_count=1, games=[dict(appid=10, name='Owned', token='ignored')])+ games, label = svc.steam_owned({'snapshot': json.dumps(value)})+ self.assertEqual(games, [dict(id='steam:10', platform='steam', title='Owned')])+ self.assertNotIn(value['steamid'], label)+ value.update(game_count=0, games=[])+ self.assertEqual(svc.steam_owned({'snapshot': json.dumps(value)})[0], [])+ for bad in [dict(value, state='sign-in'), dict(value, game_count=1), dict(value, steamid='invalid'), dict(value, game_count=True)]:+ with self.assertRaises(svc.ServiceError):+ svc.steam_owned({'snapshot': json.dumps(bad)})++ def test_steam_snapshot_rejects_duplicate_or_unsafe_ids(self):+ for games in [[dict(appid=10, name='A'), dict(appid=10, name='A')], [dict(appid='../10', name='A')], [dict(appid=10, name='')]]:+ value = dict(state='ready', steamid='76561198000000000', game_count=len(games), games=games)+ with self.assertRaises(svc.ServiceError):+ svc.steam_owned({'snapshot': json.dumps(value)})++ def test_steam_snapshot_cli_accepts_libraries_larger_than_pipe_buffer(self):+ value = dict(state='ready', steamid='76561198000000000', game_count=2000,+ games=[dict(appid=i + 1, name='Owned game ' + str(i)) for i in range(2000)])+ result = subprocess.run([sys.executable, str(ROOT/'scripts/library-service.py'), 'sync', 'steam', '--base', str(self.base)],+ input=json.dumps({'snapshot': json.dumps(value)}), text=True, capture_output=True, timeout=10)+ self.assertEqual(result.returncode, 0, result.stdout)+ self.assertEqual(json.loads(result.stdout)['count'], 2000)+ self.assertEqual(len(svc.saved_accounts(self.base)[1]), 2000)++ def test_failed_sync_does_not_disclose_settings_or_replace_cache(self):+ svc.save_account(self.base, 'steam', [{'id': 'steam:10', 'title': 'Kept'}], 'Steam')+ path = svc.account_path(self.base, 'steam')+ before = path.read_bytes()+ secret = 'THIS_VALUE_MUST_NOT_APPEAR'+ result = subprocess.run([sys.executable, str(ROOT/'scripts/library-service.py'), 'sync', 'steam', '--base', str(self.base)],+ input=json.dumps({'snapshot': secret}),+ text=True, capture_output=True)+ self.assertNotEqual(result.returncode, 0)+ self.assertNotIn(secret, result.stdout + result.stderr)+ self.assertEqual(before, path.read_bytes())++ def test_account_cache_is_private_and_rejects_commands(self):+ svc.save_account(self.base, 'steam', [{'id': 'steam:10', 'title': 'Owned', 'arguments': ['sh', '-c', 'bad']}], 'Steam')+ self.assertEqual(stat.S_IMODE(svc.account_path(self.base, 'steam').stat().st_mode), 0o600)+ accounts, games, warnings = svc.saved_accounts(self.base)+ self.assertEqual(accounts[0]['count'], 1)+ self.assertFalse(warnings)+ self.assertNotIn('arguments', games[0])+ self.assertEqual(games[0]['install_path'], '')++ def test_imported_game_cannot_play_until_installed(self):+ svc.save_account(self.base, 'steam', [{'id': 'steam:10', 'title': 'Owned'}], 'Steam')+ lib = scanner.Library(self.base)+ self.assertEqual(lib.scan()['games'][0]['title'], 'Owned')+ with self.assertRaisesRegex(ValueError, 'not installed'): lib.command('steam:10')+ with self.assertRaisesRegex(ValueError, 'Install this launcher'): lib.command('steam:10', install=True)+ client = self.base/'steam-bottle/drive_c/Program Files (x86)/Steam/steam.exe'+ client.parent.mkdir(parents=True); client.touch()+ self.assertEqual(lib.command('steam:10', install=True)[-1], 'steam://install/10')++ def test_installed_manifest_wins_over_owned_snapshot(self):+ client = self.base/'steam-bottle/drive_c/Program Files (x86)/Steam'+ (client/'steamapps/common/Owned').mkdir(parents=True)+ (client/'steam.exe').touch()+ (client/'steamapps/appmanifest_10.acf').write_text('"AppState" {"appid" "10" "name" "Installed title" "installdir" "Owned" "StateFlags" "4"}')+ svc.save_account(self.base, 'steam', [{'id': 'steam:10', 'title': 'Old title'}], 'Steam')+ data = scanner.Library(self.base).scan()+ self.assertEqual(len(data['games']), 1)+ self.assertEqual(data['games'][0]['title'], 'Installed title')+ self.assertTrue(data['games'][0]['install_path'])+ self.assertTrue(data['games'][0]['owned'])++ def test_malformed_import_is_isolated(self):+ svc.save_account(self.base, 'steam', [{'id': 'steam:10', 'title': 'Kept'}], 'Steam')+ svc.account_path(self.base, 'gog').write_text('{"schema":1,"platform":"gog","games":[{"id":"gog:../../evil","title":"Bad"}]}')+ _, games, warnings = svc.saved_accounts(self.base)+ self.assertEqual([g['id'] for g in games], ['steam:10'])+ self.assertEqual(len(warnings), 1)+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_steam_login.cjs b/tests/test_steam_login.cjsnew file mode 100644index 00000000000..4ded441351a--- /dev/null+++ b/tests/test_steam_login.cjs@@ -0,0 +1,65 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;+const code = fs.readFileSync(path.join(__dirname, "../resources/steam-library.js"), "utf8");+const run = new AsyncFunction("window", "document", "location", "fetch", code);+const id = "76561198000000000";+function context(user = {}, window = {}, url = "https://steamcommunity.com/my/games/?tab=all") {+ return [window, { getElementById: () => ({ getAttribute: key => JSON.stringify(key === "data-userinfo" ? user : {}) }) }, new URL(url)];+}+test("signed-out and foreign pages never request account data", async () => {+ const fetch = () => { throw Error("must not fetch"); };+ assert.deepEqual(await run(...context(), fetch), {state:"sign-in"});+ assert.deepEqual(await run(...context({}, {}, "https://steamcommunity.com.evil.test/"), fetch), {state:"wrong-page"});+});+test("the own All Games page returns only metadata", async () => {+ const w = {g_steamID:id, g_rgProfileData:{steamid:id}, rgGames:[{appid:10, name:" Owned ", auth:"do-not-export"}]};+ const value = await run(...context({}, w), () => { throw Error("unnecessary request"); });+ assert.deepEqual(value, {state:"ready", steamid:id, game_count:1, games:[{appid:"10", name:"Owned"}]});+});+test("another profile and recent-only views cannot replace the owned library", async () => {+ const w = {g_steamID:id, g_rgProfileData:{steamid:"76561198000000001"}, rgGames:[{appid:10,name:"Not mine"}]};+ assert.equal((await run(...context({}, w))).state, "open-library");+ w.g_rgProfileData.steamid=id;+ assert.equal((await run(...context({}, w, "https://steamcommunity.com/my/games/?tab=recent"))).state, "open-library");+});+test("the web session stays in the Steam request and never the returned snapshot", async () => {+ const user = {logged_in:true, steamid:id, webapi_token:"test-session-only"};+ let requests = 0;+ const value = await run(...context(user), async (url, options) => {+ requests++;+ const parsed = new URL(url);+ assert.equal(parsed.origin, "https://api.steampowered.com");+ assert.equal(parsed.searchParams.get("access_token"), user.webapi_token);+ assert.equal(JSON.parse(parsed.searchParams.get("input_json")).steamid, id);+ assert.equal(options.redirect, "error");+ assert.equal(options.credentials, "omit");+ return {ok:true, text:async () => JSON.stringify({response:{game_count:1,games:[{appid:10,name:"Owned"}]}})};+ });+ assert.equal(requests, 1);+ assert.equal(value.state, "ready");+ assert.ok(!JSON.stringify(value).includes(user.webapi_token));+});+test("private, incomplete, duplicate and invalid responses do not become empty libraries", async () => {+ for (const response of [{}, {game_count:1,games:[]}, {game_count:2,games:[{appid:10,name:"A"},{appid:10,name:"A"}]},+ {game_count:1,games:[{appid:"../10",name:"A"}]}, {game_count:1,games:[{appid:10,name:""}]}]) {+ const value = await run(...context({logged_in:true,steamid:id,webapi_token:"test"}), async () => ({ok:true,text:async()=>JSON.stringify({response})}));+ assert.equal(value.state, "unavailable");+ }+});+test("an explicitly empty owned library is valid", async () => {+ const value = await run(...context({logged_in:true,steamid:id,webapi_token:"test"}), async()=>({ok:true,text:async()=>JSON.stringify({response:{game_count:0}})}));+ assert.equal(value.state, "ready"); assert.deepEqual(value.games, []);+});+test("request failures return no raw URL, session or exception", async () => {+ const value = await run(...context({logged_in:true,steamid:id,webapi_token:"test-secret"}), async()=>{throw Error("test-secret");});+ assert.deepEqual(value, {state:"unavailable"});+});++test("conflicting account identity cannot import a stale profile", async () => {+ const value = await run(...context({logged_in:true, steamid:"76561198000000001", webapi_token:"test"}, {g_steamID:id}),+ () => { throw Error("must not fetch"); });+ assert.deepEqual(value, {state:"unavailable"});+});