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
Didim Labs Store: buy through Polar, enter the license key, download, verify and install native games; didimlabs.com turns a key into a download link
mikey929c36a52ca0fb
diff --git a/README.ko.md b/README.ko.mdindex 48063b39f5c..b9241e9a396 100644--- a/README.ko.md+++ b/README.ko.md@@ -146,9 +146,9 @@ scripts/play.sh gog-kill # GOG 보틀 종료 (창을 닫으면 메뉴게임은 아직 폭넓게 테스트하지 않았습니다. 커널 안티치트(EAC/BattlEye)가 필요한 게임은 Wine에서 돌지 않습니다.-## Didim Labs 게임 (맥 네이티브)+## Didim Labs Store (맥 네이티브 게임)-Didim Labs가 만든 애플 실리콘 네이티브 게임은 내려받은 .zip으로 설치합니다(Library → Add Didim Labs game, 또는 `soju didim install <zip>`). 설치 전에 게임 서명을 확인하고, Windows나 Wine 없이 바로 실행됩니다. 세이브는 `~/Library/Application Support`에 남습니다.+Didim Labs가 만든 애플 실리콘 네이티브 게임을 소주의 Didim Labs Store 탭에서 삽니다. 결제(Polar)를 마치고 영수증 메일의 라이선스 키를 넣으면 소주가 내려받아 확인하고 설치합니다. Windows나 Wine 없이 실행되고, 키는 macOS 키체인에 저장돼 다시 설치할 때 쓰입니다. 내려받은 .zip은 Library → Add Didim Labs game 또는 `soju didim install <zip>`으로도 설치할 수 있습니다. 세이브는 `~/Library/Application Support`에 남습니다.## Xbox PC / Microsoft Store (Xodus 백엔드, 실험 기능)diff --git a/README.md b/README.mdindex 4ab8ea653e3..3ce7af41cc9 100644--- a/README.md+++ b/README.md@@ -12,7 +12,7 @@ owned library cached by **GOG GALAXY**. Installed and uninstalled games share thsame library, with availability filters and official-client install actions.**Discover** searches Steam, GOG and Microsoft Store listings and prices, with links to buy from the stores.**Xbox PC (experimental):** sign in to a Microsoft account to import owned and PC Game Pass games, download them through the [Xodus](https://github.com/xodus-gaming/xodus) backend and start them on Soju's engine. Retro Classics reaches its main menu on Soju; other games are untested. Purchases, downloads and updates stay with the official stores.-**Didim Labs games:** native Apple Silicon games from Didim Labs install from their downloaded .zip (Library → Add Didim Labs game, or `soju didim install <zip>`) and run without Windows or Wine; Soju checks the game's signature first.+**Didim Labs Store:** native Apple Silicon games made by Didim Labs. Buy through the store's checkout (Polar), paste the license key from the receipt, and Soju downloads, checks and installs the game; it runs without Windows or Wine. The key is kept in the macOS Keychain for reinstalls. A downloaded .zip also installs with Library → Add Didim Labs game or `soju didim install <zip>`.Epic and Battle.net account imports are not included yet. Compatibility varies by game.diff --git a/app/Library.swift b/app/Library.swiftindex 236d3d18bee..d5841123ede 100644--- a/app/Library.swift+++ b/app/Library.swift@@ -267,6 +267,7 @@ struct LibraryView: View {Divider()if page == "platforms" { PlatformsView().frame(maxWidth: .infinity, maxHeight: .infinity) }else if page == "discover" { DiscoverView() }+ else if page == "store" { StoreView() }else if page == "accounts" { AccountsView() }else { library }}@@ -297,6 +298,7 @@ struct LibraryView: View {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)+ nav("store", "Didim Labs Store", "bag", count: nil)Divider().padding(.vertical, 16)nav("accounts", "Accounts", "person.crop.circle", count: nil)nav("platforms", "Platforms", "square.stack.3d.up", count: nil)diff --git a/app/Soju.swift b/app/Soju.swiftindex d2ab79d71dc..3639796bd81 100644--- a/app/Soju.swift+++ b/app/Soju.swift@@ -116,7 +116,7 @@ enum Launcher: String, CaseIterable, Identifiable {})}- func task(_ args: [String], logName: String) throws -> (Process, URL) {+ func task(_ args: [String], logName: String, environment extra: [String: String] = [:]) throws -> (Process, URL) {let dir = base.appendingPathComponent("logs")// Logs can name games, paths and backend errors: keep them to this user.try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])@@ -136,6 +136,7 @@ enum Launcher: String, CaseIterable, Identifiable {env["PYTHONDONTWRITEBYTECODE"] = "1"env["TERM"] = "dumb"for key in ["ENGINE", "WINEPREFIX", "WINEDLLOVERRIDES", "DYLD_FALLBACK_LIBRARY_PATH"] { env.removeValue(forKey: key) }+ env.merge(extra) { _, new in new }p.environment = envp.standardInput = FileHandle.nullDevicep.standardOutput = output@@ -143,11 +144,11 @@ enum Launcher: String, CaseIterable, Identifiable {return (p, url)}- func run(_ args: [String], title: String) {+ func run(_ args: [String], title: String, environment: [String: String] = [:]) {guard !busy else { return }busy = true; failed = false; activity = title; log = ""do {- let (p, url) = try task(args, logName: "desktop")+ let (p, url) = try task(args, logName: "desktop", environment: environment)logReader = try FileHandle(forReadingFrom: url)operation = pp.terminationHandler = { [weak self] process indiff --git a/app/Store.swift b/app/Store.swiftnew file mode 100644index 00000000000..a24574ffdc5--- /dev/null+++ b/app/Store.swift@@ -0,0 +1,163 @@+import SwiftUI+import AppKit++/// Didim Labs games sold through Polar and installed natively (scripts/didim_games.py).+/// The catalog comes from didimlabs.com/store/catalog.json, with the copy shipped in the app as fallback.+struct StoreGame: Decodable, Identifiable {+ let id: String+ let title: String+ let publisher: String+ let price: String+ let checkout: String+ let cover: String?+ let summary: String+ let details: String+ let requires: String+ let steam: String?+}++struct StoreCatalog: Decodable {+ let schema: Int+ let games: [StoreGame]++ static func bundled(root: URL) -> [StoreGame] {+ guard let data = try? Data(contentsOf: root.appendingPathComponent("resources/didim-store.json")) else { return [] }+ return decode(data) ?? []+ }+ static func decode(_ data: Data) -> [StoreGame]? {+ guard data.count <= 512 * 1024, let catalog = try? JSONDecoder().decode(StoreCatalog.self, from: data),+ catalog.schema == 1 else { return nil }+ // Only https links to the store's own checkout and images are used.+ return catalog.games.filter { game in+ game.id.range(of: "^[a-z0-9][a-z0-9-]{0,63}$", options: .regularExpression) != nil+ && safe(game.checkout, hosts: ["buy.polar.sh", "polar.sh"]) != nil+ && (game.cover == nil || safe(game.cover!, hosts: ["didimlabs.com"]) != nil)+ && (game.steam == nil || safe(game.steam!, hosts: ["store.steampowered.com"]) != nil)+ }+ }+ static func safe(_ value: String, hosts: Set<String>) -> URL? {+ guard let url = URL(string: value), url.scheme == "https", let host = url.host, hosts.contains(host),+ url.user == nil, url.password == nil else { return nil }+ return url+ }+}++@MainActor final class StoreModel: ObservableObject {+ @Published var games: [StoreGame] = []+ @Published var offline = false++ func load(root: URL) {+ if games.isEmpty { games = StoreCatalog.bundled(root: root) }+ var request = URLRequest(url: URL(string: "https://didimlabs.com/store/catalog.json")!)+ request.cachePolicy = .reloadIgnoringLocalCacheData+ request.timeoutInterval = 15+ URLSession.shared.dataTask(with: request) { data, response, _ in+ let fresh = (response as? HTTPURLResponse)?.statusCode == 200 ? data.flatMap(StoreCatalog.decode) : nil+ DispatchQueue.main.async {+ if let fresh, !fresh.isEmpty { self.games = fresh; self.offline = false } else { self.offline = true }+ }+ }.resume()+ }+}++struct StoreView: View {+ @EnvironmentObject var model: SojuModel+ @StateObject private var store = StoreModel()+ @State private var keyFor: StoreGame?+ @State private var key = ""+ private let accent = Color(red: 0.79, green: 0.36, blue: 0.27)++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ VStack(alignment: .leading, spacing: 7) {+ Text("Didim Labs Store").font(.system(size: 30, weight: .bold, design: .rounded))+ Text("Games made by Didim Labs, built natively for Apple Silicon. Buy once, then install and play them here.")+ .font(.callout).foregroundStyle(.secondary)+ }+ if model.busy || !model.activity.isEmpty && model.activity != "Ready when you are." {+ HStack(spacing: 8) {+ if model.busy { ProgressView().controlSize(.small) }+ else { Image(systemName: model.failed ? "exclamationmark.circle" : "checkmark.circle").foregroundStyle(model.failed ? .orange : .green) }+ Text(model.busy ? lastLine : (model.failed ? lastLine : model.activity)).font(.system(size: 12)).lineLimit(2)+ }+ }+ ScrollView {+ VStack(spacing: 18) {+ ForEach(store.games) { card($0) }+ if store.games.isEmpty {+ Text(store.offline ? "The store is unavailable right now. Check the internet connection." : "Loading the store…")+ .foregroundStyle(.secondary).padding(.top, 40)+ }+ }+ }+ Text("Payments are handled by Polar, Didim Labs' reseller. The license key from your receipt email is saved in this Mac's Keychain.")+ .font(.system(size: 11)).foregroundStyle(.secondary)+ }+ .padding(28).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .onAppear { store.load(root: model.root) }+ .sheet(item: $keyFor) { game in keySheet(game) }+ }++ private var lastLine: String {+ model.log.split(separator: "\n").last.map { String($0).replacingOccurrences(of: "soju: ", with: "") } ?? model.activity+ }++ private func installed(_ game: StoreGame) -> InstalledGame? {+ model.games.first { $0.id == "didim:" + game.id && $0.isInstalled }+ }++ private func card(_ game: StoreGame) -> some View {+ HStack(alignment: .top, spacing: 22) {+ ZStack {+ LinearGradient(colors: [accent.opacity(0.5), .black], startPoint: .topLeading, endPoint: .bottomTrailing)+ if let cover = game.cover, let url = URL(string: cover) {+ AsyncImage(url: url) { image in image.resizable().scaledToFill() } placeholder: { Image(systemName: "cat.fill").font(.largeTitle) }+ }+ }.frame(width: 320, height: 150).clipped().clipShape(RoundedRectangle(cornerRadius: 12))+ VStack(alignment: .leading, spacing: 9) {+ Text(game.publisher.uppercased()).font(.system(size: 10, weight: .bold)).tracking(0.8).foregroundStyle(accent)+ Text(game.title).font(.system(size: 22, weight: .bold, design: .rounded))+ Text(game.summary).font(.system(size: 12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ Text(game.details).font(.system(size: 11))+ Text(game.requires).font(.system(size: 11)).foregroundStyle(.secondary)+ HStack(spacing: 10) {+ if let game = installed(game) {+ Button { model.play(game) } label: { Label("Play", systemImage: "play.fill") }+ .buttonStyle(.borderedProminent).tint(.green).disabled(model.launchingGames.contains(game.id))+ } else {+ Button { if let url = StoreCatalog.safe(game.checkout, hosts: ["buy.polar.sh", "polar.sh"]) { NSWorkspace.shared.open(url) } } label: {+ Label("Buy · " + game.price, systemImage: "cart")+ }.buttonStyle(.borderedProminent).tint(accent)+ }+ Button(installed(game) == nil ? "Enter license key…" : "Reinstall latest version") {+ if installed(game) == nil { key = ""; keyFor = game }+ else { model.run(["didim", "activate", game.id], title: "Updating " + game.title + "…") }+ }.disabled(model.busy)+ if let steam = game.steam, let url = URL(string: steam) {+ Link("Windows on Steam", destination: url).font(.system(size: 12))+ }+ }.padding(.top, 4)+ }+ Spacer(minLength: 0)+ }.padding(18).background(Color.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 16))+ }++ private func keySheet(_ game: StoreGame) -> some View {+ VStack(alignment: .leading, spacing: 14) {+ Text("Install " + game.title).font(.system(size: 18, weight: .bold))+ Text("Paste the license key from your purchase email (it starts with DSTC-). Soju checks it, downloads the game and installs it.")+ .font(.system(size: 12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)+ TextField("License key", text: $key).textFieldStyle(.roundedBorder).font(.system(.body, design: .monospaced))+ HStack {+ Spacer()+ Button("Cancel") { keyFor = nil }+ Button("Install") {+ let value = key.trimmingCharacters(in: .whitespacesAndNewlines)+ keyFor = nil+ model.run(["didim", "activate", game.id], title: "Installing " + game.title + "…", environment: ["SOJU_DIDIM_KEY": value])+ }.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction)+ .disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).range(of: "^[A-Za-z0-9-]{8,100}$", options: .regularExpression) == nil)+ }+ }.padding(24).frame(width: 460)+ }+}diff --git a/docs/store/catalog.json b/docs/store/catalog.jsonnew file mode 100644index 00000000000..2c4a73aa802--- /dev/null+++ b/docs/store/catalog.json@@ -0,0 +1,17 @@+{+ "schema": 1,+ "games": [+ {+ "id": "dont-sell-the-cat",+ "title": "Don't Sell the Cat",+ "publisher": "Didim Labs",+ "price": "$6.99",+ "checkout": "https://buy.polar.sh/polar_cl_RUBxcP2f3cFwGAUA0yXiuQcMm12Mu0kMaTJEB2yhNh2",+ "cover": "https://didimlabs.com/store/dont-sell-the-cat-wide.jpg",+ "summary": "Seven nights behind the counter of a pawnshop that opened in 1958. Check what people bring in with a loupe, a UV lamp, a scale and the shop cat. Pay the rent. The ledger writes lines you didn't write, and someone knocks on the back shutter after closing. Don't open it.",+ "details": "First-person horror · about 2 hours · 10 endings · English and Korean",+ "requires": "Apple Silicon Mac, macOS 12 or later · 369 MB",+ "steam": "https://store.steampowered.com/app/5584970"+ }+ ]+}diff --git a/docs/store/dont-sell-the-cat-wide.jpg b/docs/store/dont-sell-the-cat-wide.jpgnew file mode 100644index 00000000000..0410a306fc3Binary files /dev/null and b/docs/store/dont-sell-the-cat-wide.jpg differdiff --git a/docs/store/dont-sell-the-cat.jpg b/docs/store/dont-sell-the-cat.jpgnew file mode 100644index 00000000000..f23210b13bcBinary files /dev/null and b/docs/store/dont-sell-the-cat.jpg differdiff --git a/resources/didim-store.json b/resources/didim-store.jsonnew file mode 100644index 00000000000..2c4a73aa802--- /dev/null+++ b/resources/didim-store.json@@ -0,0 +1,17 @@+{+ "schema": 1,+ "games": [+ {+ "id": "dont-sell-the-cat",+ "title": "Don't Sell the Cat",+ "publisher": "Didim Labs",+ "price": "$6.99",+ "checkout": "https://buy.polar.sh/polar_cl_RUBxcP2f3cFwGAUA0yXiuQcMm12Mu0kMaTJEB2yhNh2",+ "cover": "https://didimlabs.com/store/dont-sell-the-cat-wide.jpg",+ "summary": "Seven nights behind the counter of a pawnshop that opened in 1958. Check what people bring in with a loupe, a UV lamp, a scale and the shop cat. Pay the rent. The ledger writes lines you didn't write, and someone knocks on the back shutter after closing. Don't open it.",+ "details": "First-person horror · about 2 hours · 10 endings · English and Korean",+ "requires": "Apple Silicon Mac, macOS 12 or later · 369 MB",+ "steam": "https://store.steampowered.com/app/5584970"+ }+ ]+}diff --git a/scripts/build-app.sh b/scripts/build-app.shindex ccc1baf7afe..ef76e86c7a9 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" "$ROOT/app/Accounts.swift" "$ROOT/app/Discover.swift" "$ROOT/app/PurchaseLinks.swift" "$ROOT/app/SteamLogin.swift" -o "$APP/Contents/MacOS/Soju"+ "$ROOT/app/Soju.swift" "$ROOT/app/Library.swift" "$ROOT/app/Accounts.swift" "$ROOT/app/Discover.swift" "$ROOT/app/PurchaseLinks.swift" "$ROOT/app/SteamLogin.swift" "$ROOT/app/Store.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 867ea97f63e..bee3eee6913 100755--- a/scripts/desktop-action.sh+++ b/scripts/desktop-action.sh@@ -22,6 +22,7 @@ case "$ACTION" indidim)case "${1:-}" in install) exec python3 "$ROOT/scripts/didim_games.py" install "${2:?Choose the game zip}" ;;remove) exec python3 "$ROOT/scripts/didim_games.py" remove "${2:?Choose a game}" ;;+ activate) exec python3 "$ROOT/scripts/didim_games.py" activate "${2:?Choose a game}" ;;*) echo "Unknown Didim Labs action."; exit 64 ;; esac ;;xbox)case "${1:-}" in login|logout|kill|status) exec bash "$ROOT/scripts/xbox.sh" "$1" ;;diff --git a/scripts/didim_games.py b/scripts/didim_games.pyindex aa11aee334a..2b83e386869 100755--- a/scripts/didim_games.py+++ b/scripts/didim_games.py@@ -7,6 +7,7 @@ A game zip holds one .app whose Contents/Resources/soju-game.json names it:Games install to $SOJU_BASE/didim-games/<id>/. No network, no accounts."""import argparse+import hashlibimport jsonimport osfrom pathlib import Path@@ -17,6 +18,9 @@ import sysimport tempfileID = re.compile(r'[a-z0-9][a-z0-9-]{0,63}')+STORE = os.environ.get('SOJU_DIDIM_STORE', 'https://didimlabs.com')+KEYCHAIN_SERVICE = 'Soju Didim Labs license'+KEY = re.compile(r'[A-Za-z0-9-]{8,100}')MAX_MANIFEST = 64 * 1024@@ -57,7 +61,7 @@ def inside(root, path):return False-def install(archive):+def install(archive, expect=None):archive = Path(archive).expanduser().absolute()if not archive.is_file() or archive.suffix.lower() != '.zip':raise ValueError('Choose the game .zip you downloaded.')@@ -75,6 +79,8 @@ def install(archive):raise ValueError('The archive must contain exactly one .app.')app = apps[0]item = read_manifest(app)+ if expect and item['id'] != expect:+ raise ValueError('The download is a different game than the one bought.')# Downloads carry quarantine; the bundle is checked before it is trusted.subprocess.run(['/usr/bin/xattr', '-dr', 'com.apple.quarantine', str(app)], check=False,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)@@ -115,6 +121,72 @@ def installed(soju_base=None):return games+def saved_key(uid):+ found = subprocess.run(['/usr/bin/security', 'find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', uid, '-w'],+ capture_output=True, text=True)+ return found.stdout.strip() if found.returncode == 0 else ''+++def save_key(uid, key):+ # Stored in the login keychain so a reinstall or update needs no key; never written to logs or files.+ subprocess.run(['/usr/bin/security', 'add-generic-password', '-U', '-s', KEYCHAIN_SERVICE, '-a', uid,+ '-l', 'Soju: ' + uid, '-w', key], check=True, capture_output=True)+++def fetch_json(url, body):+ import urllib.request, urllib.error+ request = urllib.request.Request(url, data=json.dumps(body).encode(), method='POST',+ headers={'Content-Type': 'application/json', 'User-Agent': 'Soju'})+ try:+ with urllib.request.urlopen(request, timeout=30) as response:+ return json.loads(response.read(1024 * 1024))+ except urllib.error.HTTPError as error:+ try: message = json.loads(error.read(65536)).get('error')+ except (ValueError, AttributeError): message = None+ raise ValueError(message or 'The store answered with an error (' + str(error.code) + ').')+ except urllib.error.URLError:+ raise ValueError('Could not reach the store. Check the internet connection.')+++def activate(uid):+ """Download and install a bought game. The key comes from SOJU_DIDIM_KEY or the keychain."""+ import urllib.request+ if not ID.fullmatch(uid or ''): raise ValueError('Choose a game.')+ key = os.environ.pop('SOJU_DIDIM_KEY', '').strip() or saved_key(uid)+ if not key: raise ValueError('Enter the license key from your purchase email.')+ if not KEY.fullmatch(key): raise ValueError('That license key does not look right.')+ print('Checking the license key…', flush=True)+ info = fetch_json(STORE + '/api/didim/download', {'game': uid, 'key': key})+ name, size, digest, url = info.get('name'), info.get('size'), info.get('sha256'), info.get('url')+ if not (isinstance(name, str) and name.endswith('.zip') and '/' not in name and isinstance(size, int)+ and isinstance(digest, str) and re.fullmatch(r'[0-9a-f]{64}', digest)+ and isinstance(url, str) and url.startswith('https://')):+ raise ValueError('The store sent an unexpected answer.')+ save_key(uid, key)+ folder = games_dir() / '.downloads'+ folder.mkdir(parents=True, exist_ok=True, mode=0o700)+ target = folder / name+ print('Downloading ' + name + ' (' + str(size // (1024 * 1024)) + ' MB)…', flush=True)+ sha = hashlib.sha256(); done = 0; shown = -1+ request = urllib.request.Request(url, headers={'User-Agent': 'Soju'})+ with urllib.request.urlopen(request, timeout=60) as response, target.open('wb') as out:+ while True:+ chunk = response.read(1024 * 1024)+ if not chunk: break+ out.write(chunk); sha.update(chunk); done += len(chunk)+ if done > size: raise ValueError('The download is larger than expected.')+ percent = done * 100 // size+ if percent // 5 != shown:+ shown = percent // 5+ print('Downloading… ' + str(percent) + '%', flush=True)+ try:+ if done != size or sha.hexdigest() != digest:+ raise ValueError('The download was damaged. Try again.')+ install(target, expect=uid)+ finally:+ target.unlink(missing_ok=True)++def remove(uid):if not ID.fullmatch(uid or ''): raise ValueError('Choose a game ID.')dest = games_dir() / uid@@ -125,12 +197,13 @@ def remove(uid):def main():parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument('action', choices=['install', 'list', 'remove'])+ parser.add_argument('action', choices=['install', 'activate', 'list', 'remove'])parser.add_argument('target', nargs='?')args = parser.parse_args()try:if args.action == 'install': install(args.target or '')elif args.action == 'remove': remove(args.target)+ elif args.action == 'activate': activate(args.target)else: print(json.dumps(installed(), ensure_ascii=False))except (OSError, ValueError, json.JSONDecodeError, subprocess.CalledProcessError) as error:print('soju: ' + str(error), file=sys.stderr); sys.exit(1)diff --git a/site-worker/worker.js b/site-worker/worker.jsindex 77bd4216a70..78c11e59971 100644--- a/site-worker/worker.js+++ b/site-worker/worker.js@@ -1,13 +1,72 @@// didimlabs.com: serves the GitHub Pages site (docs/) under a short domain.// curl -fsSL didimlabs.com/install.sh | bash// The old soju.snack-wrap.com address (and www) redirect here so existing links and install commands keep working.+//+// POST /api/didim/download {"game": "<id>", "key": "<license key>"} is how Soju turns a Didim Labs+// license key (sold through Polar) into a short-lived download link. Needs the POLAR_TOKEN secret+// (organization token with license_keys:read and customer_sessions:write) on the didimlabs.com worker.const HOME = "didimlabs.com";+const POLAR = "https://api.polar.sh/v1";+const ORG = "e7dd3a2e-a0ac-4b52-ad53-b7c7d7064420";+// Game ID (soju-game.json) -> the Polar benefits that grant it.+const GAMES = {+ "dont-sell-the-cat": {+ license: "e8fc1b75-2c42-4808-9486-14aab05e3bdb",+ download: "4c51886f-92d5-4620-868e-ce6aeb01adfb",+ },+};++const json = (body, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });++async function download(request, env) {+ if (request.method !== "POST") return json({ error: "Use POST." }, 405);+ if (!env.POLAR_TOKEN) return json({ error: "The store is not configured yet." }, 503);+ let input;+ try { input = await request.json(); } catch { return json({ error: "Send JSON." }, 400); }+ const game = GAMES[input && input.game];+ const key = typeof input?.key === "string" ? input.key.trim() : "";+ if (!game) return json({ error: "Unknown game." }, 404);+ if (!/^[A-Za-z0-9-]{8,100}$/.test(key)) return json({ error: "That license key does not look right." }, 400);++ const check = await fetch(POLAR + "/customer-portal/license-keys/validate", {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ key, organization_id: ORG }),+ });+ if (check.status === 404 || check.status === 422) return json({ error: "This license key was not found." }, 403);+ if (!check.ok) return json({ error: "The store could not check the key. Try again shortly." }, 502);+ const license = await check.json();+ if (license.status !== "granted") return json({ error: "This license key is no longer active." }, 403);+ if (license.benefit_id !== game.license) return json({ error: "This key is for a different game." }, 403);++ const session = await fetch(POLAR + "/customer-sessions/", {+ method: "POST", headers: { "content-type": "application/json", authorization: "Bearer " + env.POLAR_TOKEN },+ body: JSON.stringify({ customer_id: license.customer_id }),+ });+ if (!session.ok) return json({ error: "The store could not prepare the download. Try again shortly." }, 502);+ const { token } = await session.json();+ const list = await fetch(POLAR + "/customer-portal/downloadables/?limit=100&benefit_id=" + game.download, {+ headers: { authorization: "Bearer " + token },+ });+ if (!list.ok) return json({ error: "The store could not list the download. Try again shortly." }, 502);+ const files = ((await list.json()).items || []).filter((item) => item.benefit_id === game.download && item.file);+ // The newest upload is the current build.+ files.sort((a, b) => String(b.file.created_at || "").localeCompare(String(a.file.created_at || "")));+ const file = files[0] && files[0].file;+ if (!file) return json({ error: "No download is attached to this game yet." }, 404);+ return json({+ name: file.name, size: file.size, sha256: file.checksum_sha256_hex,+ url: file.download.url, expires_at: file.download.expires_at,+ });+}+export default {- async fetch(request) {+ async fetch(request, env) {const url = new URL(request.url);if (url.hostname !== HOME) {return Response.redirect("https://" + HOME + url.pathname + url.search, 301);}+ if (url.pathname === "/api/didim/download") return download(request, env);const upstream = new URL("https://bcd1210.github.io/soju" + url.pathname + url.search);const res = await fetch(upstream, { headers: { "User-Agent": "soju-site" }, cf: { cacheTtl: 300 } });const headers = new Headers(res.headers);diff --git a/tests/test_didim.py b/tests/test_didim.pyindex ecce6d7e12b..a9823c71917 100644--- a/tests/test_didim.py+++ b/tests/test_didim.py@@ -87,3 +87,31 @@ class DidimGames(unittest.TestCase):if __name__ == '__main__':unittest.main()+++class DidimStore(unittest.TestCase):+ """activate() talks to the store; these cover the paths that never touch the network or keychain."""+ def run_activate(self, key, store='http://127.0.0.1:9'):+ env = dict(os.environ, SOJU_BASE=tempfile.mkdtemp(), SOJU_DIDIM_STORE=store, SOJU_DIDIM_KEY=key)+ return subprocess.run([sys.executable, str(SCRIPT), 'activate', 'no-such-game-for-tests'], env=env,+ capture_output=True, text=True)++ def test_malformed_key_is_rejected_before_any_request(self):+ result = self.run_activate('not a key!')+ self.assertNotEqual(result.returncode, 0)+ self.assertIn('does not look right', result.stderr)++ def test_unreachable_store_is_reported(self):+ result = self.run_activate('DSTC-TEST-0000-0000')+ self.assertNotEqual(result.returncode, 0)+ self.assertIn('Could not reach the store', result.stderr)++ def test_catalog_copies_match_and_are_valid(self):+ bundled = json.loads((ROOT / 'resources/didim-store.json').read_text())+ public = json.loads((ROOT / 'docs/store/catalog.json').read_text())+ self.assertEqual(bundled, public)+ self.assertEqual(bundled['schema'], 1)+ for game in bundled['games']:+ self.assertTrue(game['checkout'].startswith('https://buy.polar.sh/'))+ self.assertTrue(game['cover'].startswith('https://didimlabs.com/store/'))+ self.assertTrue((ROOT / 'docs/store' / game['cover'].rsplit('/', 1)[1]).is_file())