Files
WoW-Hybrid-gateway/ops/bootstrap_popup_ack.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

256 lines
15 KiB
Python

"""One guarded original-Okay click during local pre-world bootstrap.
This does not classify the native error's cause, clear it through an API, or
establish readiness. UI work is in bounded subprocesses, and only modal text is
OCR'd in memory. The original button retains its original callback semantics.
"""
import csv
import fcntl
import hashlib
import io
import json
import os
from pathlib import Path
import re
import subprocess
import stat
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
EXE_SHA='c49ce22c3e0aaeb7a7007a5c5cb792e4c3e6cdecc55a1145a5933fc113e3e57f'
MAX_BYTES=32*1024*1024
def process_identity(pid,root=ROOT):
"""Exact private PE, live owner UID/start time and exact PE command token."""
if type(pid)is not int or pid<=0:raise ValueError('Owned PID required')
root=Path(root).resolve();exe=root/'runtime/native-client/_classic_beta_/WowB.exe'
if exe.resolve()!=exe or not exe.is_file()or exe.stat().st_uid!=os.getuid():raise ValueError('Owned image required')
if not 0<exe.stat().st_size<=256*1024*1024:raise ValueError('Image bound')
h=hashlib.sha256()
with exe.open('rb')as f:
for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
if h.hexdigest()!=EXE_SHA:raise ValueError('Pinned image required')
proc=Path('/proc')/str(pid)
if proc.stat().st_uid!=os.getuid():raise ValueError('Owned process required')
stat=(proc/'stat').read_text();end=stat.rfind(')');fields=stat[end+2:].split()
if end<0 or len(fields)<20 or fields[0]in('Z','X'):raise ValueError('Live process required')
start=int(fields[19]);cmd=(proc/'cmdline').read_bytes()
if len(cmd)>16384:raise ValueError('Process identity bound')
expected={str(exe).encode(),('Z:'+str(exe).replace('/','\\')).encode()}
if not expected.intersection(cmd.split(b'\0')):raise ValueError('Exact owned PE token required')
profile=root/'runtime/native-engine-pe.json'
if profile.resolve()!=profile or profile.stat().st_uid!=os.getuid():raise ValueError('Owned module profile required')
return dict(pid=pid,start_time=start,exe_sha256=EXE_SHA,module_profile_sha256=hashlib.sha256(profile.read_bytes()).hexdigest())
def recognize_tsv(text,width,height):
"""Strict English original two-button modal; no fuzzy code or coordinates."""
if not 320<=width<=8192 or not 200<=height<=4320 or len(text)>1024*1024:return None
tokens=[]
try:
for r in csv.DictReader(io.StringIO(text),delimiter='\t'):
word=r.get('text','').strip();confidence=float(r['conf'])
if not word or not 85<=confidence<=100:continue
box=tuple(int(r[k])for k in('left','top','width','height'))
x,y,w,h=box
if x<0 or y<0 or w<=0 or h<=0 or x+w>width or y+h>height:return None
tokens.append((word,box))
except (ValueError,TypeError,KeyError):return None
codes=[b for s,b in tokens if s.strip('()[]{}:.,')=='BLZ51901016']
okay=[b for s,b in tokens if s.casefold()=='okay']
help_=[b for s,b in tokens if s.casefold()=='help']
if len(codes)!=1 or len(okay)!=1 or len(help_)!=1:return None
code,button,left= codes[0],okay[0],help_[0]
cx,cy,cw,ch=code;bx,by,bw,bh=button;lx,ly,lw,lh=left
if not(3<=bh<=height*.12 and 8<=bw<=width*.25 and by>cy+ch and by-(cy+ch)<=height*.45):return None
if not(lx+lw<bx and abs((ly+lh/2)-(by+bh/2))<=max(bh,lh) and bx+ bw/2>=cx-width*.25 and bx+bw/2<=cx+cw+width*.25):return None
boxes=[tuple((max(0,x-2),max(0,y-2),min(width,x+w+2),min(height,y+h+2)))for x,y,w,h in(code,button,left)]
return dict(point=[bx+bw//2,by+bh//2],boxes=boxes)
def modal_ocr_bytes(image):
# Original gold glyphs on red buttons have poor raw OCR contrast. Fixed
# luminance threshold preserves geometry and uses only declared Pillow.
from PIL import ImageOps
out=io.BytesIO()
ImageOps.grayscale(image).point(lambda value:0 if value>=150 else 255).save(out,format='PNG')
return out.getvalue()
class X11Driver:
"""Parent side: every X11/OCR operation is bounded, no Spectacle or uinput."""
def __init__(self,pid,identity,root=ROOT):
self.pid=pid;self.identity=identity;self.root=Path(root);self.deadline=time.monotonic()+8;self.captured=False
def _worker(self,request,timeout):
remaining=self.deadline-time.monotonic()
if remaining<=0:raise TimeoutError('UI budget exhausted')
r=subprocess.run([sys.executable,str(Path(__file__).resolve()),'--x11-worker'],input=json.dumps(request).encode(),stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,timeout=min(timeout,remaining),check=True)
if len(r.stdout)>MAX_BYTES:raise ValueError('UI response bound')
return json.loads(r.stdout)
def observe(self):
import base64
from PIL import Image
capture=self._worker(dict(op='capture',pid=self.pid,identity=self.identity,root=str(self.root)),3)
data=base64.b64decode(capture.pop('png'),validate=True)
image=Image.open(io.BytesIO(data));image.load();self.captured=True
ocr_data=modal_ocr_bytes(image)
remaining=self.deadline-time.monotonic()
if remaining<=0:raise TimeoutError('UI budget exhausted')
r=subprocess.run(['tesseract','stdin','stdout','--psm','11','tsv'],input=ocr_data,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,timeout=min(2,remaining),check=True,env={**os.environ,'OMP_THREAD_LIMIT':'1'})
if len(r.stdout)>1024*1024:raise ValueError('OCR output bound')
match=recognize_tsv(r.stdout.decode('utf8'),*image.size)
if match is None:return None
capture.update(match)
capture['patch_sha256']=[hashlib.sha256(image.crop(b).tobytes()).hexdigest()for b in match['boxes']]
return capture
def click(self,observation):
return self._worker(dict(op='click',pid=self.pid,identity=self.identity,root=str(self.root),observation=observation),3).get('clicked')is True
def _episode_digest(account):
"""Keep stable ownership identity, excluding the advancing heartbeat count."""
index=account['selected_index']
lease=account.get('engine_session_lease')
if isinstance(lease,dict):
lease={key:value for key,value in lease.items() if key!='heartbeats'}
return hashlib.sha256(json.dumps([index,account['realms'][index],lease],sort_keys=True).encode()).hexdigest()
class BootstrapPopupAck:
def __init__(self,pid,profile,root=ROOT,*,identify=process_identity,driver=X11Driver,clock=time.monotonic):
self.pid=pid;self.profile=profile;self.root=Path(root);self.identify=identify;self.driver_factory=driver;self.clock=clock
self.retired=False;self.consumed=False;self.probes=0;self.last_probe=-1e9;self.identity=None;self.episode=None;self.budget_deadline=None
self.receipt={'status':'not-observed','click_attempted':False,'readiness_asserted':False,'in_memory_capture_obtained':False,'screenshots_saved':False}
def _identity(self):
current=self.identify(self.pid,self.root)
if self.identity is None:self.identity=current
if current!=self.identity:raise ValueError('Owned process changed')
return current
def _token(self):
r=self.root/'runtime'
if r.resolve()!=r or r.stat().st_uid!=os.getuid():raise ValueError('Owned runtime required')
return r/f'bootstrap-popup-ack-{self.pid}-{self.identity["start_time"]}.json'
def _retire(self,why):self.retired=True;self.receipt['status']=why
def _write_token(self,status):
token=self._token();data=json.dumps({'kind':'one-original-bootstrap-okay','identity':self.identity,'status':status},sort_keys=True).encode()
fd=os.open(token,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'wb')as f:f.write(data);f.flush();os.fsync(f.fileno())
def retire_world(self):
self._retire('world-seen')
try:
self._identity();self._write_token('world-seen')
except Exception:pass
def _consume(self):
self._write_token('consumed')
self.consumed=True;self.receipt['click_attempted']=True
def try_ack(self,sample,transport_ready,world_ready,binding_guard):
"""Samples contain only existing owner RPC results; never supplies login."""
if self.retired or self.consumed or self.profile!='local-explicit':return self.receipt
lockfd=None;driver=None
try:
account,pipe=sample()
if world_ready(account,self.profile,pipe):self.retire_world();return self.receipt
if not transport_ready(account,self.profile,pipe):self._retire('transport-not-ready');return self.receipt
if not pipe.get('roster_queued'):return self.receipt
binding_guard();identity=self._identity()
if self._token().exists():self._retire('already-consumed');return self.receipt
selected=account['selected_index'];realm=account['realms'][selected]
episode=_episode_digest(account)
if self.episode is None:self.episode=episode
if episode!=self.episode:self._retire('episode-changed');return self.receipt
now=self.clock()
if self.budget_deadline is None:self.budget_deadline=now+8
if now>=self.budget_deadline:self._retire('ui-budget-exhausted');return self.receipt
if self.probes>=3 or now-self.last_probe<1:return self.receipt
lockfd=os.open(self.root/'runtime/client-session.lock',os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600)
lockstat=os.fstat(lockfd)
if lockstat.st_uid!=os.getuid()or lockstat.st_mode&0o022 or not stat.S_ISREG(lockstat.st_mode)or lockstat.st_nlink!=1:raise ValueError('Owned UI lock required')
try:fcntl.flock(lockfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError:
self.receipt['status']='ui-busy'
return self.receipt
self.probes+=1;self.last_probe=now
driver=self.driver_factory(self.pid,identity,self.root);driver.deadline=self.budget_deadline
observation=driver.observe()
if observation is None:self.receipt['status']='modal-not-recognized';return self.receipt
# Proof is refreshed after bounded screenshot/OCR, immediately before
# dispatching the final pixel/identity check and sole original click.
self._identity()
account,pipe=sample();binding_guard()
current=_episode_digest(account)
if world_ready(account,self.profile,pipe):self.retire_world();return self.receipt
if not transport_ready(account,self.profile,pipe)or not pipe.get('roster_queued')or current!=self.episode:self._retire('proof-changed');return self.receipt
if self.clock()>=self.budget_deadline:self._retire('ui-budget-exhausted');return self.receipt
self._consume() # A timeout/uncertain outcome must never cause a replay.
self.receipt['status']='original-okay-clicked'if driver.click(observation)else'click-refused'
except Exception:
# No OCR, account values or arbitrary exception text enters reports.
self._retire('unavailable-or-changed')
finally:
if driver is not None:self.receipt['in_memory_capture_obtained']=self.receipt['in_memory_capture_obtained']or bool(getattr(driver,'captured',False))
if lockfd is not None:os.close(lockfd)
return self.receipt
def _x11_worker(request):
"""One exact original X11 window. Never focuses or selects another window."""
import base64
from PIL import Image
from Xlib import X,display
from Xlib.ext import xtest
pid=request['pid'];identity=request['identity'];root=Path(request['root'])
if process_identity(pid,root)!=identity:raise ValueError('Identity changed')
from contextlib import closing
with closing(display.Display())as d:
atom=lambda name:d.intern_atom(name)
prop=d.screen().root.get_full_property(atom('_NET_CLIENT_LIST'),X.AnyPropertyType)
candidates=[];blocked=False
for wid in ([]if prop is None else prop.value):
w=d.create_resource_object('window',int(wid));p=w.get_full_property(atom('_NET_WM_PID'),X.AnyPropertyType)
if p is None or len(p.value)!=1 or int(p.value[0])!=pid:continue
if w.get_attributes().map_state!=X.IsViewable:continue
cls=w.get_wm_class()or();g=w.get_geometry()
if any('blizzarderror'in c.lower()for c in cls):blocked=True
if any('wowb'in c.lower()for c in cls):candidates.append((w,g))
if blocked or len(candidates)!=1:raise ValueError('Unambiguous original main window required')
w,g=candidates[0]
if getattr(d.get_input_focus().focus,'id',None)!=w.id:raise ValueError('Original window not focused')
if not 640<=g.width<=8192 or not 400<=g.height<=4320:raise ValueError('Window bound')
# Central modal only; never OCR the complete account form or save pixels.
region=(g.width//5,g.height//4,4*g.width//5,3*g.height//4);x,y,x2,y2=region
if (x2-x)*(y2-y)*4>MAX_BYTES:raise ValueError('Capture bound')
raw=w.get_image(x,y,x2-x,y2-y,X.ZPixmap,0xffffffff)
if raw is None or g.depth not in(24,32):raise ValueError('Unsupported X11 capture')
if len(raw.data)!=(x2-x)*(y2-y)*4:raise ValueError('Unsupported X11 pixel format')
image=Image.frombytes('RGB',(x2-x,y2-y),raw.data,'raw','BGRX')
identity_now=dict(window_id=w.id,width=g.width,height=g.height,region=list(region))
if request['op']=='capture':
data=io.BytesIO();image.save(data,format='PNG');return dict(identity_now,captured_ns=time.monotonic_ns(),png=base64.b64encode(data.getvalue()).decode())
if request['op']!='click':raise ValueError('Unknown UI operation')
obs=request['observation']
stamp=obs.get('captured_ns')
if type(stamp)is not int or not 0<=time.monotonic_ns()-stamp<=5_000_000_000:raise ValueError('Stale modal capture')
if any(obs[k]!=v for k,v in identity_now.items()):raise ValueError('Window geometry changed')
boxes=obs['boxes'];point=obs['point']
if len(boxes)!=3 or len(point)!=2 or not 0<=point[0]<image.width or not 0<=point[1]<image.height:raise ValueError('Modal geometry bound')
if [hashlib.sha256(image.crop(tuple(b)).tobytes()).hexdigest()for b in boxes]!=obs['patch_sha256']:raise ValueError('Modal pixels changed')
if process_identity(pid,root)!=identity:raise ValueError('Identity changed')
if getattr(d.get_input_focus().focus,'id',None)!=w.id:raise ValueError('Focus changed')
pos=d.screen().root.translate_coords(w,point[0]+x,point[1]+y)
# Queue motion+press+release together. No blocking request occurs while
# the button is down, even if the following sync times out externally.
xtest.fake_input(d,X.MotionNotify,x=pos.x,y=pos.y)
try:xtest.fake_input(d,X.ButtonPress,detail=1)
finally:xtest.fake_input(d,X.ButtonRelease,detail=1)
d.sync();return {'clicked':True}
if __name__=='__main__':
if sys.argv[1:]!=['--x11-worker']:raise SystemExit(2)
try:
raw=sys.stdin.buffer.read(1024*1024+1)
if len(raw)>1024*1024:raise ValueError('Request bound')
print(json.dumps(_x11_worker(json.loads(raw))))
except Exception:raise SystemExit(1)