66 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
486 lines
24 KiB
Python
486 lines
24 KiB
Python
#!/usr/bin/env python3
|
|
"""Octo launcher with startup readiness. Credentials are entered only in Forever.
|
|
|
|
The backend is a replaceable startup/session supervisor, never a packet gateway.
|
|
Run --check without a display to inspect a deployment without starting the game.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import platform
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import uuid
|
|
|
|
SCHEMA = 1
|
|
PLATFORMS = {"Linux": "linux", "Windows": "windows"}
|
|
ENDPOINTS = {"Local Tortoise": "local-explicit", "OctoWoW": "octo"}
|
|
|
|
|
|
def app_directory():
|
|
return Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent
|
|
|
|
|
|
def default_profile():
|
|
"""Allow a separate Windows profile without changing the Linux package."""
|
|
directory = app_directory() / "compat"
|
|
if platform.system() == "Windows":
|
|
windows_profile = directory / "windows-launcher.json"
|
|
if windows_profile.exists():
|
|
return windows_profile
|
|
return directory / "launcher.json"
|
|
|
|
|
|
def load_profile(path, system=None):
|
|
path = Path(path).resolve()
|
|
if path.stat().st_size > 65536:
|
|
raise ValueError("Launcher profile exceeds 64 KiB")
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
if data.get("schema") != SCHEMA or set(data) - {"schema", "runtime_root", "platforms", "character_guid"}:
|
|
raise ValueError("Unsupported launcher profile")
|
|
# No account, password, arbitrary launch arguments, shell or update URLs.
|
|
target = PLATFORMS.get(system or platform.system())
|
|
if target is None:
|
|
raise ValueError("This launcher supports Windows and Linux")
|
|
root = (path.parent / data["runtime_root"]).resolve()
|
|
spec = data.get("platforms", {}).get(target)
|
|
if not isinstance(spec, dict) or set(spec) - {"backend", "sha256", "python", "status"}:
|
|
raise ValueError("Missing or unsupported platform backend")
|
|
guid = data.get("character_guid")
|
|
if guid is not None and (type(guid) is not int or not 0 < guid < 2**32):
|
|
raise ValueError("Invalid optional local character save guard")
|
|
return root, target, spec, guid
|
|
|
|
|
|
def launch_plan(path, endpoint, system=None, runtime_override=None):
|
|
if endpoint not in ENDPOINTS.values():
|
|
raise ValueError("Choose a supported endpoint")
|
|
root, target, spec, guid = load_profile(path, system)
|
|
if runtime_override is not None:
|
|
root = Path(runtime_override).resolve()
|
|
if spec.get("status") != "available":
|
|
raise ValueError(f"{target.title()} compatibility runtime is not installed/verified; client was not started")
|
|
relative = Path(spec.get("backend", ""))
|
|
backend = (root / relative).resolve()
|
|
if relative.is_absolute() or not backend.is_relative_to(root) or not backend.is_file():
|
|
raise ValueError("Backend must be an installed file inside the runtime folder")
|
|
digest = hashlib.sha256(backend.read_bytes()).hexdigest()
|
|
if digest != spec.get("sha256"):
|
|
raise ValueError("Backend checksum differs; preserve installation and rebuild its launcher profile")
|
|
if target == "linux":
|
|
python = shutil.which(spec.get("python", "python3"))
|
|
if not python or not shutil.which("wine"):
|
|
raise ValueError("Python 3 and Wine are required by this development runtime")
|
|
command = [python, "-u", str(backend)]
|
|
else:
|
|
if backend.suffix.lower() != ".exe":
|
|
raise ValueError("Windows requires a native bootstrap executable; Wine libraries are incompatible")
|
|
command = [str(backend)]
|
|
command += ["--endpoint-profile", endpoint]
|
|
if guid is not None and endpoint == "local-explicit":
|
|
command += ["--character-guid", str(guid)]
|
|
return command, root
|
|
|
|
|
|
def locate_installation(selected):
|
|
"""Recognize a prepared installation, never patch an arbitrary original."""
|
|
selected = Path(selected).resolve()
|
|
for root in (selected, *list(selected.parents)[:3]):
|
|
client = root / "runtime/native-client"
|
|
if (selected in (root, client, client / "_classic_beta_")
|
|
and (client / "_classic_beta_/WowB.exe").is_file()
|
|
and (root / "ops/forever_launcher_backend.py").is_file()):
|
|
return root, client
|
|
raise ValueError("This folder is not a prepared WoW-Hybrid Forever installation. Select its native-client folder; original clients were left unchanged.")
|
|
|
|
|
|
def public_event(line):
|
|
"""Only display the backend's bounded, enumerated status protocol."""
|
|
if len(line) > 4096:
|
|
return None
|
|
try:
|
|
event = json.loads(line)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
if not isinstance(event, dict) or event.get("schema") != SCHEMA:
|
|
return None
|
|
if set(event) - {"schema", "phase", "message", "realms", "manual_login_stage"}:
|
|
return None
|
|
phases = {"starting", "host", "preparing", "login", "authenticating", "realms", "characters", "world", "closed", "blocked", "error"}
|
|
if event.get("phase") not in phases or not isinstance(event.get("message"), str) or len(event["message"]) > 512:
|
|
return None
|
|
if "manual_login_stage" in event and (event["phase"]!="login" or event["manual_login_stage"]not in ("switch-intent","switch-capture")):
|
|
return None
|
|
if event["phase"] == "realms":
|
|
rows = event.get("realms")
|
|
if not isinstance(rows, list) or not 1 <= len(rows) <= 64:
|
|
return None
|
|
seen = set()
|
|
for row in rows:
|
|
if (not isinstance(row, dict) or set(row) != {"index", "name", "offline"}
|
|
or type(row["index"]) is not int or not 0 <= row["index"] < 64
|
|
or row["index"] in seen or type(row["offline"]) is not bool
|
|
or not isinstance(row["name"], str) or not 1 <= len(row["name"]) <= 127
|
|
or row["name"] != row["name"].strip()
|
|
or not row["name"].isprintable() or any(c in row["name"] for c in "<>")):
|
|
return None
|
|
seen.add(row["index"])
|
|
elif "realms" in event:
|
|
return None
|
|
return event
|
|
|
|
|
|
def child_environment():
|
|
env = dict(os.environ, PYTHONUNBUFFERED="1")
|
|
if getattr(sys, "frozen", False) and platform.system() == "Linux":
|
|
original = env.pop("LD_LIBRARY_PATH_ORIG", None)
|
|
if original is None:
|
|
env.pop("LD_LIBRARY_PATH", None)
|
|
else:
|
|
env["LD_LIBRARY_PATH"] = original
|
|
return env
|
|
|
|
|
|
def notify_error(message):
|
|
"""Keep startup failures visible when launched without a terminal."""
|
|
if platform.system() == "Windows":
|
|
import ctypes
|
|
ctypes.windll.user32.MessageBoxW(None, message, "WoW-Hybrid launcher", 0x10)
|
|
else:
|
|
for program, arguments in (("kdialog", ["--error", message, "--title", "WoW-Hybrid launcher"]),
|
|
("zenity", ["--error", "--title=WoW-Hybrid launcher", "--text=" + message])):
|
|
if shutil.which(program):
|
|
subprocess.run([program, *arguments], env=child_environment(), check=False)
|
|
return
|
|
if sys.stderr:
|
|
print(message, file=sys.stderr)
|
|
|
|
|
|
class LoginReadinessPanel:
|
|
"""Three completed startup stages, never an estimated download/time percent.
|
|
|
|
KDialog owns the OS window. The preparation panel stays above the game;
|
|
only the validated backend login event replaces it with a ready message.
|
|
No account input, game input interception or global input grab is used.
|
|
"""
|
|
interface = "org.kde.kdialog.ProgressDialog"
|
|
preparing_text = "Preparing login — please wait before entering account details."
|
|
|
|
def __init__(self):
|
|
self.kdialog = shutil.which("kdialog")
|
|
self.qdbus = shutil.which("qdbus6") or shutil.which("qdbus")
|
|
if not self.kdialog or not self.qdbus or not os.environ.get("DISPLAY"):
|
|
raise ValueError("Visible login readiness requires kdialog, qdbus6 (or qdbus), and an X11/XWayland display. The game was not started.")
|
|
self.title = "WoW-Hybrid login preparation " + uuid.uuid4().hex[:8]
|
|
self.reference = None
|
|
self.ready_process = None
|
|
self.value = 0
|
|
self.ready = False
|
|
self.manual_login_stage = None
|
|
self.keep_above = threading.Event()
|
|
self.thread = None
|
|
|
|
def call(self, method, *arguments):
|
|
return subprocess.run([self.qdbus, *self.reference, method, *map(str, arguments)],
|
|
env=child_environment(), stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL, check=True, timeout=5)
|
|
|
|
def open(self):
|
|
result = subprocess.run([self.kdialog, "--title", self.title, "--progressbar",
|
|
"0 of 3 startup stages complete.\n" + self.preparing_text, "3"],
|
|
env=child_environment(), capture_output=True, text=True,
|
|
check=True, timeout=10)
|
|
parts = result.stdout.strip().split()
|
|
if (len(parts) != 2 or not re.fullmatch(r"(?:org\.kde\.kdialog[-.][A-Za-z0-9_.-]+|:[0-9]+\.[0-9]+)", parts[0])
|
|
or parts[1] != "/ProgressDialog"):
|
|
raise ValueError("Login readiness dialog did not return its expected OS window reference; game was not started.")
|
|
self.reference = parts
|
|
try:
|
|
self.call("org.freedesktop.DBus.Properties.Set", self.interface, "autoClose", "false")
|
|
self.call("showCancelButton", "false")
|
|
self.keep_above.set()
|
|
self.thread = threading.Thread(target=self.raise_preparation, daemon=True)
|
|
self.thread.start()
|
|
except Exception:
|
|
self.close()
|
|
raise
|
|
|
|
def raise_preparation(self):
|
|
# Only our random-title window is raised. No focus theft, key capture,
|
|
# credential access or changes to any game/system window properties.
|
|
try:
|
|
from Xlib import X, display, protocol
|
|
connection = display.Display()
|
|
try:
|
|
root = connection.screen().root
|
|
atom = connection.intern_atom("_NET_WM_STATE")
|
|
above = connection.intern_atom("_NET_WM_STATE_ABOVE")
|
|
while self.keep_above.is_set():
|
|
pending = [(root, 0)]; count = 0
|
|
while pending and count < 4096:
|
|
window, depth = pending.pop(); count += 1
|
|
try:
|
|
if window.get_wm_name() == self.title:
|
|
event = protocol.event.ClientMessage(window=window, client_type=atom,
|
|
data=(32, [1, above, 0, 1, 0]))
|
|
root.send_event(event, event_mask=X.SubstructureRedirectMask | X.SubstructureNotifyMask)
|
|
window.configure(stack_mode=X.Above)
|
|
break
|
|
if depth < 3:pending.extend((child, depth+1) for child in window.query_tree().children)
|
|
except Exception:
|
|
continue
|
|
connection.flush()
|
|
# Event.wait returns immediately when set; use a separate
|
|
# timed wait to avoid a busy loop while preparation is active.
|
|
threading.Event().wait(.4)
|
|
finally:
|
|
connection.close()
|
|
except Exception:
|
|
# KDialog still supplies the visible stage bar if the WM refuses
|
|
# above-state requests. Readiness itself never depends on the WM.
|
|
return
|
|
|
|
def update(self, event):
|
|
phase = event["phase"]
|
|
stage=event.get('manual_login_stage')
|
|
if stage in ('switch-intent','switch-capture')and stage!=self.manual_login_stage:
|
|
self.close();self.ready=False;self.manual_login_stage=stage
|
|
if phase in {"blocked", "error", "closed", "characters", "world", "realms", "authenticating"}:
|
|
self.close()
|
|
return
|
|
if self.ready:
|
|
return
|
|
completed = {"starting": 0, "host": 1, "preparing": 2, "login": 3}.get(phase)
|
|
if completed is None:
|
|
return
|
|
self.value = max(self.value, completed)
|
|
label = ("3 of 3 startup stages complete.\nReady — enter your account and password in Forever, then press Enter once."
|
|
if phase == "login" else str(self.value) + " of 3 startup stages complete.\n" + self.preparing_text + "\n" + event["message"])
|
|
if self.reference:
|
|
try:
|
|
self.call("setLabelText", label)
|
|
self.call("org.freedesktop.DBus.Properties.Set", self.interface, "value", self.value)
|
|
except (OSError, subprocess.SubprocessError):
|
|
# Closing the preparation window never stops the owner/game
|
|
# or suppresses the later, genuinely armed ready notification.
|
|
self.close_progress()
|
|
if phase == "login":
|
|
self.ready = True
|
|
self.close_progress()
|
|
title="WoW-Hybrid — login ready"
|
|
message="Ready to log in.\n\nEnter your account and password in the Forever game window, then press Enter once."
|
|
if stage=='switch-intent':
|
|
title="WoW-Hybrid — account switch"
|
|
message="Enter the new account and password in Forever, then press Log In once.\n\nThis first press observes your account-switch intent only. The original form clears the password; enter it again when asked."
|
|
elif stage=='switch-capture':
|
|
message="Previous session cleared.\n\nRe-enter the new account and password in the original Forever form, then press Log In again. No credentials were reused."
|
|
self.ready_process = subprocess.Popen([self.kdialog, "--title", title,
|
|
"--msgbox", message,
|
|
"--ok-label", "Continue in game"], env=child_environment(), stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
|
|
def close_progress(self):
|
|
self.keep_above.clear()
|
|
if self.thread:
|
|
self.thread.join(timeout=1)
|
|
self.thread = None
|
|
if self.reference:
|
|
try:self.call("close")
|
|
except (OSError, subprocess.SubprocessError):pass
|
|
self.reference = None
|
|
|
|
def close(self):
|
|
self.close_progress()
|
|
if self.ready_process and self.ready_process.poll() is None:
|
|
self.ready_process.terminate()
|
|
try:self.ready_process.wait(timeout=2)
|
|
except subprocess.TimeoutExpired:self.ready_process.kill();self.ready_process.wait(timeout=2)
|
|
self.ready_process = None
|
|
|
|
|
|
class WindowsLoginReadinessPanel:
|
|
def __init__(self):
|
|
self.window=None
|
|
def open(self):
|
|
import tkinter as tk
|
|
from tkinter import ttk
|
|
self.window=tk.Tk();self.window.title('WoW-Hybrid login preparation')
|
|
self.window.attributes('-topmost',True)
|
|
self.label=ttk.Label(self.window,text='Preparing login. Please wait before entering account details.',padding=20)
|
|
self.label.pack();self.progress=ttk.Progressbar(self.window,length=440,maximum=3)
|
|
self.progress.pack(padx=20,pady=(0,20));self.window.protocol('WM_DELETE_WINDOW',lambda:None)
|
|
self.window.update()
|
|
def update(self,event):
|
|
phase=event['phase']
|
|
if phase in {'blocked','error','closed','characters','world','realms','authenticating'}:
|
|
self.close();return
|
|
if self.window is None:return
|
|
value={'starting':0,'host':1,'preparing':2,'login':3}.get(phase)
|
|
if value is not None:
|
|
self.progress['value']=value;self.label['text']=event['message'];self.window.update()
|
|
if phase=='login':
|
|
from tkinter import messagebox
|
|
messagebox.showinfo('WoW-Hybrid — login ready','Ready to log in. Enter your account and password in the game, then press Enter once.',parent=self.window)
|
|
self.close()
|
|
def close(self):
|
|
if self.window is not None:
|
|
self.window.destroy();self.window=None
|
|
|
|
def choose_windows_realm(available):
|
|
import tkinter as tk
|
|
from tkinter import ttk
|
|
window=tk.Tk();window.title('OctoWoW — choose realm');window.attributes('-topmost',True)
|
|
ttk.Label(window,text='Choose an online realm returned by OctoWoW:',padding=12).pack()
|
|
tags=list(available);choice=tk.StringVar(value=tags[0]);result=[]
|
|
for tag in tags:
|
|
ttk.Radiobutton(window,text='['+tag+'] '+available[tag]['name'],variable=choice,value=tag).pack(anchor='w',padx=16,pady=3)
|
|
def accept():
|
|
tag=choice.get()
|
|
if tag in available:result.append(available[tag]['index']);window.destroy()
|
|
ttk.Button(window,text='Select realm',command=accept).pack(pady=12)
|
|
window.after(80000,window.destroy);window.mainloop()
|
|
return result[0] if result else None
|
|
|
|
|
|
def choose_authenticated_realm(event):
|
|
"""Ask only about the real realm list emitted after authentication.
|
|
|
|
Menu tags preserve exact server indices. Names are bounded printable text;
|
|
they never become shell text, option tags, addresses or authentication data.
|
|
"""
|
|
checked = public_event(json.dumps(event, ensure_ascii=False))
|
|
if checked is None or checked["phase"] != "realms":
|
|
raise ValueError("Authenticated realm selection event is invalid; client preserved.")
|
|
available = {str(row["index"]): row for row in checked["realms"] if not row["offline"]}
|
|
if not available:
|
|
raise ValueError("OctoWoW returned no online realms. Authenticated client preserved; no password resent.")
|
|
if platform.system()=="Windows":
|
|
return choose_windows_realm(available)
|
|
dialog = shutil.which("kdialog")
|
|
if not dialog:
|
|
raise ValueError("Realm selection requires the installed desktop dialog. Authenticated client preserved.")
|
|
command = [dialog, "--title", "OctoWoW — choose realm", "--menu",
|
|
"Choose an online realm returned by OctoWoW:"]
|
|
for tag, row in available.items():
|
|
command += [tag, "[" + tag + "] " + row["name"]]
|
|
try:
|
|
result = subprocess.run(command, env=child_environment(), stdin=subprocess.DEVNULL,
|
|
capture_output=True, text=True, encoding="utf-8", errors="strict",
|
|
timeout=80)
|
|
except subprocess.TimeoutExpired:
|
|
return None
|
|
if result.returncode == 1:
|
|
return None # The user cancelled; no realm is guessed.
|
|
if result.returncode != 0:
|
|
raise ValueError("The realm dialog could not complete. Authenticated client preserved.")
|
|
output = result.stdout
|
|
if not isinstance(output, str) or len(output) > 32:
|
|
raise ValueError("The realm dialog returned an invalid selection; client preserved.")
|
|
tag = output[:-1] if output.endswith("\n") else output
|
|
if tag not in available:
|
|
raise ValueError("The selected realm is unavailable or invalid; client preserved.")
|
|
return available[tag]["index"]
|
|
|
|
|
|
def supervise(command, root, panel_factory=LoginReadinessPanel):
|
|
"""Observe startup and forward one explicit authenticated realm choice.
|
|
|
|
The input pipe accepts only a bounded realm-index JSON message. Credentials
|
|
remain in the original game form; cancellation closes this pipe, never the
|
|
authenticated client and never starts a new authentication attempt.
|
|
"""
|
|
last = "The startup supervisor ended before readiness was verified."
|
|
realm_replied = False
|
|
realm_cancelled = False
|
|
readiness_observed = False
|
|
kwargs = {"creationflags": subprocess.CREATE_NO_WINDOW} if platform.system() == "Windows" else {}
|
|
panel = panel_factory()
|
|
try:
|
|
panel.open()
|
|
with subprocess.Popen(command, cwd=root, env=child_environment(), stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
|
|
encoding="utf-8", errors="replace", bufsize=1, **kwargs) as child:
|
|
while line := child.stdout.readline(4097):
|
|
event = public_event(line)
|
|
if not event:
|
|
try:
|
|
rejected = json.loads(line) if len(line) <= 4096 else None
|
|
except ValueError:
|
|
rejected = None
|
|
if isinstance(rejected, dict) and rejected.get("schema") == SCHEMA and rejected.get("phase") == "realms":
|
|
raise ValueError("The authenticated realm list is invalid; client preserved without retry.")
|
|
continue
|
|
panel.update(event)
|
|
if event["phase"] in {"login", "characters", "world", "closed"}:
|
|
readiness_observed = True
|
|
if event["phase"] == "realms":
|
|
if realm_replied or realm_cancelled or child.poll() is not None:
|
|
raise ValueError("Authenticated realm selection is no longer pending; client preserved.")
|
|
index = choose_authenticated_realm(event)
|
|
if index is None:
|
|
realm_cancelled = True
|
|
last = "Realm selection cancelled or expired. Authenticated client preserved; no password resent."
|
|
child.stdin.close()
|
|
continue
|
|
if type(index) is not int or not any(row["index"] == index and not row["offline"] for row in event["realms"]):
|
|
raise ValueError("The selected realm is unavailable or invalid; client preserved without retry.")
|
|
reply = json.dumps({"realm_index": index}, separators=(",", ":")) + "\n"
|
|
if len(reply) > 256:
|
|
raise ValueError("Realm selection exceeds the input bound; client preserved.")
|
|
try:
|
|
child.stdin.write(reply)
|
|
child.stdin.flush()
|
|
child.stdin.close() # Exactly one choice, no other input.
|
|
except (OSError, ValueError):
|
|
raise ValueError("Realm selection could not reach the authenticated session; client preserved.") from None
|
|
realm_replied = True
|
|
last = "Realm selected. Waiting for the existing authenticated session."
|
|
elif not realm_cancelled:
|
|
last = event["message"]
|
|
code = child.wait()
|
|
if code == 0 and (realm_cancelled or not readiness_observed):
|
|
code = 2
|
|
finally:
|
|
panel.close()
|
|
return code, last
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--profile", type=Path, default=default_profile(),
|
|
help="Development/install manifest; normal launch needs no arguments")
|
|
parser.add_argument("--check", action="store_true", help="Offline check only; do not launch or resolve any server")
|
|
args = parser.parse_args()
|
|
try:
|
|
# Normal launches are always OctoWoW. There is no server selector and
|
|
# no launcher credential form; test the local backend separately.
|
|
command, root = launch_plan(args.profile, "octo")
|
|
if args.check:
|
|
if sys.stdout:
|
|
print(json.dumps(dict(ready=True, endpoint="play.octowow.st", launch_performed=False,
|
|
gateway_required=False, launcher_owned_bootstrap_required=True), indent=2))
|
|
return 0
|
|
code, message = supervise(command, root, WindowsLoginReadinessPanel if platform.system()=="Windows" else LoginReadinessPanel)
|
|
if code:
|
|
notify_error(message)
|
|
return code
|
|
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as error:
|
|
message = str(error)
|
|
if args.check:
|
|
if sys.stdout:
|
|
print(json.dumps(dict(ready=False, reason=message, launch_performed=False), indent=2))
|
|
else:
|
|
notify_error(message)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|