Files
WoW-Hybrid-gateway/ops/windows_launcher_backend.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

214 lines
15 KiB
Python

"""Native Windows supervisor using the existing engine host and protocol contracts."""
from __future__ import annotations
import argparse,concurrent.futures,ctypes,hashlib,importlib,json,os,queue,sys,threading,time,traceback
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
if str(ROOT/'ops') not in sys.path:sys.path.insert(0,str(ROOT/'ops'))
import native_runtime_paths
READERS={'inspect-wire-frame':('engine_wire_host','inspect'),'inspect-wire-account':('engine_wire_host','inspect_account'),'inspect-native-engine-realm':('engine_wire_host','inspect_engine_realm'),'inspect-engine-pipe':('engine_pipe_host','inspect'),'inspect-engine-listener':('engine_listener_host','inspect'),'inspect-native-channel-policy':('engine_channel_policy_host','inspect')}
ACTIONS={'install-engine-listener-observer':('engine_listener_host','install'),'restore-engine-listener-observer':('engine_listener_host','restore'),'install-engine-wire-ping':('engine_wire_host','install_ping'),'start-engine-wire-account':('engine_wire_host','start_account'),'probe-engine-wire-channel':('engine_wire_host','probe_channel'),'open-native-engine-realm':('engine_wire_host','open_engine_realm'),'open-native-engine-realm-with-pipe':('engine_wire_host','open_engine_realm'),'restore-engine-pipe':('engine_pipe_host','restore'),'enable-native-channel-policy':('engine_channel_policy_host','enable'),'disable-native-channel-policy':('engine_channel_policy_host','disable')}
class InstanceLease:
def __init__(self,root):self.root=Path(root);self.handle=None
def __enter__(self):
if os.name!='nt':raise RuntimeError('Native Windows runtime required')
api=ctypes.WinDLL('kernel32',use_last_error=True)
api.CreateMutexW.argtypes=[ctypes.c_void_p,ctypes.c_int,ctypes.c_wchar_p];api.CreateMutexW.restype=ctypes.c_void_p
api.CloseHandle.argtypes=[ctypes.c_void_p];api.CloseHandle.restype=ctypes.c_int
key=hashlib.sha256(str(self.root.resolve()).casefold().encode()).hexdigest()[:24]
self.api=api;self.handle=api.CreateMutexW(None,False,'Local\\WoWHybrid-'+key)
if not self.handle:raise ctypes.WinError(ctypes.get_last_error())
if ctypes.get_last_error()==183:
api.CloseHandle(self.handle);self.handle=None;raise RuntimeError('This client already has a launcher owner')
return self
def __exit__(self,*unused):
if self.handle:self.api.CloseHandle(self.handle);self.handle=None
def emit(phase,message,**fields):
print(json.dumps(dict(schema=1,phase=phase,message=message,**fields)),flush=True)
def _function(pair):return getattr(importlib.import_module(pair[0]),pair[1])
def realm_choice(account,readline=None):
rows=account.get('realms')
if account.get('state')!=5 or account.get('server_proof_verified')!=1 or account.get('auth_result') or account.get('error') or not isinstance(rows,list)or len(rows)>64:raise RuntimeError('Unverified realm selection')
emit('realms','Choose a realm returned by the authenticated server.',realms=[dict(index=r['index'],name=r['name'],offline=bool(r['flags']&2))for r in rows])
pending=queue.Queue(maxsize=1)
def read():
try:pending.put((readline or sys.stdin.readline)(257))
except BaseException:pending.put('')
threading.Thread(target=read,daemon=True).start()
try:raw=pending.get(timeout=90)
except queue.Empty:raise RuntimeError('Realm choice expired')
if len(raw)>256:raise ValueError('Invalid realm choice')
value=json.loads(raw)
if not isinstance(value,dict)or set(value)!={'realm_index'}or type(value['realm_index'])is not int:raise ValueError('Invalid realm choice')
matches=[r for r in rows if r['index']==value['realm_index']and not r['flags']&2]
if len(matches)!=1:raise ValueError('Chosen realm is not available')
return value['realm_index']
class Owner:
def __init__(self,root,owned):
self.root=Path(root);self.owned=owned;self.pid=owned['pid'];self._busy=threading.Lock()
for name in ('windows_frame_probe','windows_process_access','engine_poll_host','engine_wire_host','engine_pipe_host','engine_listener_host','engine_channel_policy_host','engine_login_input_binding','engine_session_retirement'):
mod=importlib.import_module(name)
if hasattr(mod,'ROOT'):mod.ROOT=self.root
def inspect(self,operation,**fields):
if operation not in READERS:raise ValueError('Unknown read operation')
fn=_function(READERS[operation])
if operation=='inspect-engine-pipe':return fn(self.pid,fields.get('entity_offset',0),fields.get('unit_fields_only',False))
return fn(self.pid)
def wait(self,predicate,timeout):
end=time.monotonic()+timeout
while True:
result=predicate()
if result:return result
if time.monotonic()>=end:raise TimeoutError('Native transition did not complete; client preserved')
time.sleep(0.05)
def action(self,operation):
if operation not in ACTIONS:raise ValueError('Unknown native action')
import windows_frame_probe as probe
fn=_function(ACTIONS[operation]);followup=None
if operation=='open-native-engine-realm-with-pipe':
import engine_pipe_host as pipe
import engine_wire_host as wire
fn=wire.preflight_pipe_open(self.pid)
followup=(pipe.ENTRY,pipe.PREFIX,lambda caller:pipe.bind_setup_return(self.pid,caller))
if not self._busy.acquire(blocking=False):raise RuntimeError('Owned native transition already active')
try:
path=native_runtime_paths.state_file(self.root,operation+'-windows-trace.json')
bindings={'install-engine-listener-observer':('engine-listener-binding.json',),
'install-engine-wire-ping':('engine-poll-binding.json',)}.get(operation,())
def require_completed(proof):
if (proof.get('pid')!=self.pid or proof.get('starttime')!=self.owned['starttime']
or proof.get('status')!='observed' or proof.get('callback_invoked')is not True
or proof.get('debug_registers_restored')is not True or proof.get('detached')is not True):
raise RuntimeError('Required native action did not complete: '+operation)
for name in bindings:
record=json.loads((native_runtime_paths.state_file(self.root,name)).read_text())
if (record.get('pid')!=self.pid or type(record.get('starttime'))is not int
or record['starttime']!=self.owned['starttime'] or record.get('restored')is not False):
raise RuntimeError('Required native action binding generation differs: '+operation)
# A successful startup binding belongs to one exact owned lifetime. Reuse
# that completed transaction; never reinstall a live listener/poll clone.
if bindings and path.exists():
saved=json.loads(path.read_text())
if saved.get('pid')==self.pid and saved.get('starttime')==self.owned['starttime']:
require_completed(saved)
return saved
def invoke(caller):
if operation=='open-native-engine-realm-with-pipe':
frame=self.inspect('inspect-wire-frame')
if frame.get('command')!=6 or any(frame.get(k) not in (0,'0x0')for k in ('error','api_result','call_status','initialize_status')) or not 1<=frame.get('borrowed_world_port',0)<=65535:raise RuntimeError('Native channel borrow did not succeed')
return fn(self.pid,caller)
proof=probe.observe(self.pid,invoke,timeout=8,expected_image=Path(self.owned['imagepath']),expected_thread_id=self.owned.get('thread_id'),followup=followup)
proof['starttime']=self.owned['starttime']
path.write_text(json.dumps(proof,indent=2)+'\n')
require_completed(proof)
return proof
finally:self._busy.release()
def arm_login(self,context,timeout=120):
import windows_frame_probe as probe
import engine_login_input_binding as binding
if not self._busy.acquire(blocking=False):raise RuntimeError('Owned native transition already active')
armed=threading.Event();out=concurrent.futures.Future()
def observe():
try:
result=probe.observe(self.pid,None,timeout=timeout,expected_image=Path(self.owned['imagepath']),expected_thread_id=self.owned.get('thread_id'),entry=probe.LOGIN,on_registers=lambda registers:binding.capture(self.pid,registers,context),on_armed=armed.set)
out.set_result(result)
except BaseException as error:out.set_exception(error);armed.set()
finally:self._busy.release()
threading.Thread(target=observe,daemon=True).start()
if not armed.wait(15):raise TimeoutError('Original login observation was not armed')
if out.done():out.result()
return out
def wait_stock_login(self,timeout=30):
import struct
from windows_process_access import Access
end=time.monotonic()+timeout
while True:
access=Access(self.pid)
try:
owner=access.u64(0x145e7a098)
if owner and access.allowed(owner,0x240,'r') and access.u64(owner)==0x144efa998 and struct.unpack('<I',access.read(owner+0x98,4))[0]==2 and not any(access.read(owner+0x1a0,32)):
listener=access.u64(owner+0x220)
if listener and access.allowed(listener,16,'r') and struct.unpack('<QQ',access.read(listener,16))==(0x144e5a748,owner):return
finally:access.close()
if time.monotonic()>=end:raise TimeoutError('Original disconnected login owner is not ready; client preserved')
time.sleep(0.2)
def request_gameplay(self):
import engine_channel_policy_host as policy
return policy.request_enable(self.pid)
def supervise(root,profile,endpoint='octo'):
if os.name!='nt':raise RuntimeError('Native Windows runtime required')
if endpoint!='octo':raise ValueError('This Windows preview exposes only the direct Octo endpoint')
from windows_native_bootstrap import launch_owned,reviewed_preauth_stage
stage=reviewed_preauth_stage(profile)
diagnostic_listener=profile.get('diagnostic_listener_observer',False)
if type(diagnostic_listener)is not bool:raise ValueError('Invalid diagnostic listener observation option')
stage_receipt=native_runtime_paths.state_file(root,'windows-preauth-module-stage.json')
if stage is not None and stage_receipt.exists():raise ValueError('Existing preauth stage preserved; no replay')
import engine_login_input_binding as login
login.ROOT=root
context=login.prepare_context(endpoint)
emit('starting','Starting the native Windows client.')
owned=launch_owned(root,profile)
if stage is not None:
from windows_native_bootstrap import atomic_json
# Preserve the actual full launcher/lease/context/creator/module-load prefix.
# This diagnostic boundary stops before any debugger or engine callback;
# it is never Login readiness and never enters account handling.
atomic_json(stage_receipt,dict(schema=1,kind='reviewed-Windows-preauth-module-stage-v1',
stage={'bridge-loaded-v1':'bridge-loaded','before-modules-v1':'before-modules'}.get(stage,'modules-loaded'),owned=owned,
source_context={key:context.get(key)for key in('profile','hostname','auth_port','wire_version_profile')},debug_observation_started=False,
native_callbacks_installed=False,credentials_submitted=False,full_startup_verified=False))
emit('preauth-paused','Owned module-load stage preserved; no Login readiness claim.',pid=owned['pid'],starttime=owned['starttime'])
return 0
owner=Owner(root,owned)
emit('host','Preparing the original native login path.')
owner.wait_stock_login()
# Original listener dispatch remains intact in production. Its interception
# records diagnostics only; the functional frame/receive binding is separate.
if diagnostic_listener:owner.action('install-engine-listener-observer')
owner.action('install-engine-wire-ping')
frame=owner.wait(lambda:r if (r:=owner.inspect('inspect-wire-frame')).get('completed') else False,5)
if frame.get('error')or frame.get('api_result')or frame.get('initialize_status')!='0x0'or frame.get('call_status')!='0x0'or frame.get('abi_echo')!=1:raise RuntimeError('Native backend ABI not verified')
observation=owner.arm_login(context,timeout=None)
emit('login','Ready: enter your account and password in the game once.')
proof=observation.result()
if proof.get('status')=='client-exited':
emit('closed','Native client closed before manual login; no credentials were sent.');return 0
if (proof.get('status')!='observed' or proof.get('callback_invoked')is not True
or proof.get('debug_registers_restored')is not True or proof.get('detached')is not True):
raise RuntimeError('Original Login observation ended without a completed capture; no automatic retry')
account=owner.wait(lambda:r if (r:=owner.inspect('inspect-wire-account')).get('state')in(2,5)or r.get('error')else False,30)
if account.get('server_proof_verified')!=1 or account.get('error')or account.get('auth_result'):raise RuntimeError('Server authentication was not verified; no automatic retry')
if account['state']==5:
index=realm_choice(account)
import engine_wire_host as wire
wire.select_realm(owner.pid,index)
account=owner.wait(lambda:r if (r:=owner.inspect('inspect-wire-account')).get('state')==2 or r.get('error')else False,20)
if account.get('state')!=2 or account.get('transport_prepared')!=1:raise RuntimeError('Authenticated realm was not prepared')
owner.action('probe-engine-wire-channel');owner.wait(lambda:owner.inspect('inspect-wire-frame').get('command')==6,5)
owner.action('open-native-engine-realm-with-pipe')
roster=owner.wait(lambda:r if (r:=owner.inspect('inspect-engine-pipe')).get('roster_queued')or r.get('error')or r.get('closed')else False,20)
if roster.get('error')or roster.get('closed')or not roster.get('roster_queued'):raise RuntimeError('Native roster was not delivered; client preserved')
emit('characters','Authenticated roster delivered. Choose a character in the game.')
enabled=False
while True:
state=owner.inspect('inspect-engine-pipe')
if state.get('closed'):emit('closed','Native session ended. Close the game before another launch.');return 0
if state.get('error'):raise RuntimeError('Native session failed; client preserved, no credential replay')
world=state.get('world',{})
if not enabled and state.get('world_auth')and world.get('login_sent')==1 and world.get('self_create'):
owner.request_gameplay()
policy=owner.wait(lambda:r if (r:=owner.inspect('inspect-native-channel-policy')).get('enabled')or r.get('error')else False,10)
if policy.get('error')or not policy.get('enabled'):raise RuntimeError('Native gameplay route was not accepted; client preserved')
enabled=True;emit('world','Authenticated world route enabled inside the native client.')
time.sleep(0.5)
def main():
parser=argparse.ArgumentParser();parser.add_argument('--endpoint-profile',default='octo');parser.add_argument('--root',type=Path,default=ROOT);args=parser.parse_args();root=args.root.resolve()
try:
profile=json.loads((root/'compat/windows-native.json').read_text())
with InstanceLease(root):return supervise(root,profile,args.endpoint_profile)
except Exception:
folder=native_runtime_paths.prepare_state_directory(root)
with (folder/'windows-backend-error.log').open('a')as stream:traceback.print_exc(file=stream)
emit('blocked','Native Windows transition did not complete; client preserved. See the private runtime log.');return 2
if __name__=='__main__':raise SystemExit(main())