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

124 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""Prepare an owned local character through real SRP/world character creation.
This source-protocol fixture peer does not verify Forever's creation UI. No
character login, progression, inventory or database writes are performed here.
An unknown create outcome requires reconciliation, never automatic retry.
"""
import argparse,json,os,re,stat,subprocess,sys,time
from pathlib import Path
from native_test_guard import require_local_turtle_ports
from turtle_login_profile import snapshot_pairs
ROOT=Path(__file__).resolve().parents[1]
def private_file(path,minimum=1,maximum=65536):
path=Path(path)
if path.is_symlink() or not path.is_file():raise ValueError('Private input is not a regular file')
info=path.stat()
if info.st_uid!=os.getuid() or info.st_mode&0o077 or not minimum<=info.st_size<=maximum:
raise ValueError('Private input ownership, permissions or size differs')
return path
def public_identity(name,race,gender,class_id=1):
if not isinstance(name,str) or not re.fullmatch(r'[A-Za-z]{1,12}',name):raise ValueError('Use an ASCII character name of 1..12 letters')
if type(race) is not int or not 1<=race<=32 or type(class_id) is not int or not 1<=class_id<=11 or type(gender) is not int or gender not in (0,1):raise ValueError('Unsupported source character identity')
profile=json.loads((ROOT/'docs/evidence/data/turtle-playercreateinfo-pairs.json').read_text())
if [race,class_id] not in snapshot_pairs(profile):raise ValueError('Race/class pair absent from pinned local source data')
return name[0].upper()+name[1:].lower()
def listeners():
ports=set()
for name in ('tcp','tcp6'):
for line in Path('/proc/net',name).read_text().splitlines()[1:]:
row=line.split()
if row[3]=='0A':ports.add(int(row[1].split(':')[1],16))
return ports
def private_input():
config=json.loads(private_file(ROOT/'secrets/native-roster-host.json').read_text())
configured=Path(config['account_directory'])
directory=configured.resolve()
if configured.is_symlink() or not directory.is_relative_to(ROOT/'secrets') or not directory.is_dir():raise ValueError('Private account directory outside the workspace')
account=json.loads(private_file(directory/'account.json').read_text())
username=account.get('username')
if not isinstance(username,str) or not re.fullmatch(r'[A-Za-z0-9_]{1,32}',username):raise ValueError('Invalid private account input')
for key,expected in (('auth_port',3724),('world_port',8090)):
if key in config and config[key]!=expected:raise ValueError('Private configuration is not local Tortoise')
password=private_file(directory/'password.txt',1,128)
version=private_file(directory/'version-hash.bin',20,20)
addons=private_file(directory/'addon-tail.bin',1,10000)
lines=['GW_LOCAL_WARRIOR_FIXTURE_V1',username,str(password),str(version),str(addons)]
if any('\n' in value or '\r' in value or '\0' in value for value in lines):raise ValueError('Invalid private input framing')
return '\n'.join(lines)+'\n'
def interpret(stdout,returncode):
"""Keep only the bounded, public machine contract, never raw child logs."""
if len(stdout)>4096:raise ValueError('Fixture public response exceeds bound')
rows=stdout.splitlines();attempt=False;outcome=None;result=None
for row in rows:
if row=='CREATE_ATTEMPT' and not attempt and outcome is None and result is None:attempt=True
elif re.fullmatch(r'CREATE_RESULT [0-9]{1,3}',row) and attempt and outcome is None and result is None:
outcome=int(row.split()[1])
if outcome>255:raise ValueError('Source result exceeds byte domain')
elif re.fullmatch(r'RESULT (created|reused) [1-9][0-9]{0,19} [1-9][0-9]? [1-9][0-9]? [01] [1-9][0-9]?',row) and result is None:
_,status,guid,race,cls,gender,level=row.split()
if int(guid)>=2**64 or int(level)>60:raise ValueError('Returned roster identity exceeds source domain')
public_identity('Fixture',int(race),int(gender),int(cls))
if (status=='created' and (not attempt or outcome!=0x2e)) or (status=='reused' and (attempt or outcome is not None)):
raise ValueError('Returned roster result lacks its source creation sequence')
result=dict(status=status,guid=int(guid),race=int(race),class_id=int(cls),gender=int(gender),level=int(level))
else:raise ValueError('Unrecognized fixture public response')
if returncode==0 and result is None:raise ValueError('Successful process lacks actual roster result')
if returncode!=0 and result is not None:raise ValueError('Failed process returned inconsistent success')
return dict(creation_attempted=attempt,source_create_result=outcome,roster=result,
creation_outcome_unknown=attempt and outcome is None,
roster_confirmation_missing=attempt and outcome==0x2e and result is None)
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--name',required=True);p.add_argument('--race',required=True,type=int);p.add_argument('--gender',type=int,default=0)
p.add_argument('--class',dest='class_id',type=int,default=1)
p.add_argument('--output',required=True,type=Path)
p.add_argument('--executable',type=Path,default=ROOT/'build/local-character-fixture')
args=p.parse_args();name=public_identity(args.name,args.race,args.gender,args.class_id)
path=args.output.resolve()
if not path.is_relative_to(ROOT/'runtime') or not path.parent.is_dir() or path.exists() or args.output.is_symlink():raise ValueError('Use a NEW existing-parent runtime journal path')
executable=args.executable.resolve()
if not executable.is_relative_to(ROOT/'build') or args.executable.is_symlink() or not executable.is_file() or not os.access(executable,os.X_OK):raise ValueError('Require the locally built fixture executable')
require_local_turtle_ports(listeners())
from local_tortoise import db
if db('SELECT COUNT(*) FROM tw_char.characters WHERE online <> 0;').strip()!='0':raise ValueError('Require all local characters offline before fixture creation')
payload=private_input()
record=dict(schema=1,kind='authorized-local-source-character-fixture',name=name,race=args.race,class_id=args.class_id,gender=args.gender,
state='pending',source_protocol_fixture_peer=True,native_creation_ui_verified=False,
world_login_performed=False,progression_modified=False,created_at=time.time(),
automatic_retry_permitted=False)
fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
with os.fdopen(fd,'w') as stream:json.dump(record,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno())
try:
completed=subprocess.run([str(executable),'--name',name,'--race',str(args.race),'--class',str(args.class_id),'--gender',str(args.gender)],
input=payload,text=True,capture_output=True,timeout=40)
summary=interpret(completed.stdout,completed.returncode)
roster=summary.get('roster')
if roster and (roster['race']!=args.race or roster['class_id']!=args.class_id or roster['gender']!=args.gender):raise ValueError('Roster identity differs from requested fixture')
record.update(summary,process_returncode=completed.returncode,state='verified-roster' if completed.returncode==0 else 'failed')
except BaseException:
# A killed/interrupted child can have completed server-side creation.
# Retain this name and reconcile the real roster; never create another.
record.update(state='failed-outcome-unknown',creation_outcome_unknown=True)
raise
finally:
payload=None
record['finished_at']=time.time()
with path.open('w') as stream:json.dump(record,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno())
print(json.dumps(record,sort_keys=True))
return 0 if record['state']=='verified-roster' else 1
if __name__=='__main__':
try:sys.exit(main())
except Exception:
# Avoid traceback paths, account names or arbitrary captured child text.
print('Local fixture failed; private inputs omitted. Preserve its runtime journal and reconcile the owned roster before retrying.',file=sys.stderr)
sys.exit(1)