Files
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

128 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Recovery, provisioning and routing for the explicitly authorized local Forever realm."""
import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
from local_tortoise import private
ROOT=Path(__file__).resolve().parents[1]
SERVER=Path('/home/praxis/Projects/WoW-Hybrid/servers/trinity-forever')
CLIENT=Path('/mnt/Games/Games/WoW-Forever/_classic_beta_')
PREFIX=Path('/home/praxis/Projects/WoW-Hybrid/wine-forever')
def connection():
text=(SERVER/'install/etc/worldserver.conf').read_text()
line=re.search(r'^LoginDatabaseInfo\s*=\s*"([^"]+)"',text,re.M)[1]
host,port,user,password,database=line.split(';')
if host!='127.0.0.1' or database!='forever_auth': raise RuntimeError('refusing nonlocal/provider DB')
env=os.environ.copy(); env['MYSQL_PWD']=password
args=['--host',host,'--port',port,'--user',user]
return line,args,env
def db(sql):
_,args,env=connection()
p=subprocess.run(['mariadb',*args,'--batch','--skip-column-names','forever_auth'],env=env,input=sql,capture_output=True,text=True)
if p.returncode: raise RuntimeError('local Forever SQL failed; query/credential details omitted')
return p.stdout.strip()
def registration(email,password):
source=(SERVER/'src/common/Cryptography/Authentication/SRP6.cpp').read_text()
n=int(re.search(r'BnetSRP6v2Base::N = "([A-F0-9]+)"',source)[1],16)
username=hashlib.sha256(email.upper().encode()).hexdigest().upper()
while True:
salt=secrets.token_bytes(32)
xbytes=hashlib.pbkdf2_hmac('sha512',(username+':'+password).encode(),salt,15000,64)
if xbytes[0]<128: break
return salt,pow(2,int.from_bytes(xbytes,'big')%(n-1),n).to_bytes(256,'little')
def prepare():
os.umask(0o077)
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
recovery=ROOT/'recovery'/('forever-'+stamp); recovery.mkdir(parents=True,mode=0o700)
for name in ('worldserver.conf','bnetserver.conf'):
shutil.copy2(SERVER/'install/etc'/name,recovery/name)
shutil.copy2(CLIENT/'WTF/Config.wtf',recovery/'Config.wtf')
for name in ('system.reg','user.reg','userdef.reg'):
if (PREFIX/name).exists(): shutil.copy2(PREFIX/name,recovery/name)
old_port=int(db('SELECT port FROM realmlist WHERE id=70 AND address="127.0.0.1" AND gamebuild=70334;'))
line,args,env=connection()
with (recovery/'forever-auth.sql').open('wb') as f:
p=subprocess.run(['mariadb-dump',*args,'--single-transaction','--skip-lock-tables','--databases','forever_auth'],env=env,stdout=f,stderr=subprocess.PIPE)
if p.returncode: raise RuntimeError('Forever backup failed; no changes made')
email='GW'+secrets.token_hex(5).upper()+'@FOREVER.LOCAL'; password=secrets.token_hex(16).upper()
salt,verifier=registration(email,password)
bnet_id=int(db(f"INSERT INTO battlenet_accounts(email,srp_version,salt,verifier) VALUES('{email}',2,UNHEX('{salt.hex()}'),UNHEX('{verifier.hex()}')); SELECT LAST_INSERT_ID();"))
game_name=str(bnet_id)+'#1'; game_pass=secrets.token_hex(16).upper(); game_salt=secrets.token_bytes(32)
grunt_n=int('894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7',16)
x=int.from_bytes(hashlib.sha1(game_salt+hashlib.sha1((game_name+':'+game_pass).encode()).digest()).digest(),'little')
game_v=pow(7,x,grunt_n).to_bytes(32,'little')
account_id=int(db(f"INSERT INTO account(username,salt,verifier,email,reg_mail,battlenet_account,battlenet_index,client_build,expansion) VALUES('{game_name}',UNHEX('{game_salt.hex()}'),UNHEX('{game_v.hex()}'),'{email}','{email}',{bnet_id},1,70334,0); SELECT LAST_INSERT_ID();"))
db(f"INSERT INTO account_access(AccountID,SecurityLevel,RealmID) VALUES({account_id},3,-1); INSERT INTO realmcharacters(realmid,acctid,numchars) SELECT id,{account_id},0 FROM realmlist;")
directory=ROOT/'secrets'/'forever-local'; directory.mkdir(mode=0o700)
private(directory/'password.txt',password.encode()); private(directory/'provider.txt',line.encode())
info={'email':email,'account_id':account_id,'bnet_id':bnet_id,'recovery':str(recovery),'original_realm_port':old_port,'relay_port':19085}
private(directory/'account.json',json.dumps(info,indent=2).encode())
private(recovery/'routing.json',json.dumps({'realm_id':70,'original_port':old_port},indent=2).encode())
for p in recovery.iterdir(): p.chmod(0o600)
print('Recovery point:',recovery)
print('New disposable Forever game account id:',account_id,'; private inputs:',directory)
print('Client binary, certificates, RAM-patching service and existing credentials unchanged.')
def upgrade_local_srp():
# Only the newly provisioned account; the working original account remains intact.
info=json.loads((ROOT/'secrets/forever-local/account.json').read_text())
_,args,env=connection(); recovery=Path(info['recovery'])/'disposable-before-srp2.sql'
with recovery.open('xb') as output:
result=subprocess.run(['mariadb-dump',*args,'--skip-lock-tables','forever_auth','battlenet_accounts',
'--where=id='+str(info['bnet_id'])],env=env,stdout=output,stderr=subprocess.PIPE)
recovery.chmod(0o600)
if result.returncode: raise RuntimeError('disposable account backup failed')
password=(ROOT/'secrets/forever-local/password.txt').read_text()
salt,verifier=registration(info['email'],password)
db(f"UPDATE battlenet_accounts SET srp_version=2,salt=UNHEX('{salt.hex()}'),verifier=UNHEX('{verifier.hex()}'),failed_logins=0 WHERE id={int(info['bnet_id'])};")
print("Upgraded only disposable Forever account to the working setup's SRP v2 format; credentials omitted.")
def route(enabled):
info=json.loads((ROOT/'secrets/forever-local/account.json').read_text())
desired=info['relay_port'] if enabled else info['original_realm_port']
db(f'UPDATE realmlist SET port={int(desired)} WHERE id=70 AND address="127.0.0.1" AND gamebuild=70334;')
print('Local Forever realm 70 now advertises port',desired)
def rotate_disposable_password():
"""Recover only the explicitly bound local test frontend credential."""
os.umask(0o077)
directory=ROOT/'secrets/forever-local';info=json.loads((directory/'account.json').read_text())
email=info['email'];bnet=int(info['bnet_id']);account=int(info['account_id'])
if not re.fullmatch(r'[A-Z0-9._-]+@FOREVER\.LOCAL',email.upper()):raise RuntimeError('Not a local disposable identity')
if db(f'SELECT battlenet_account FROM account WHERE id={account} AND client_build=70334;')!=str(bnet):raise RuntimeError('Disposable account binding mismatch')
stamp=datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
recovery=ROOT/'recovery'/('frontend-credential-'+stamp);recovery.mkdir(mode=0o700)
private(recovery/'password-before.txt',(directory/'password.txt').read_bytes())
_,args,env=connection()
with (recovery/'disposable-bnet-before.sql').open('xb') as output:
result=subprocess.run(['mariadb-dump',*args,'--skip-lock-tables','forever_auth','battlenet_accounts','--where=id='+str(bnet)],env=env,stdout=output,stderr=subprocess.PIPE)
if result.returncode:raise RuntimeError('Credential recovery snapshot failed; no account changes made')
password=secrets.token_hex(16).upper();salt,verifier=registration(email,password)
staged=directory/'password-rotation.tmp';private(staged,password.encode())
try:
rows=db(f"UPDATE battlenet_accounts SET srp_version=2,salt=UNHEX('{salt.hex()}'),verifier=UNHEX('{verifier.hex()}'),failed_logins=0 WHERE id={bnet}; SELECT ROW_COUNT();")
if rows!='1':raise RuntimeError('Disposable credential update did not affect exactly one row')
staged.replace(directory/'password.txt')
finally:staged.unlink(missing_ok=True)
private(recovery/'manifest.json',json.dumps({'bnet_id':bnet,'game_account':account,'reason':'credential-input diagnostic recovery','restore_warning':'Do not reuse the previous exposed test credential'},indent=2).encode())
print('Rotated only the bound disposable Forever credential; values omitted. Recovery:',recovery)
def main():
p=argparse.ArgumentParser(); p.add_argument('action',choices=['prepare','route','restore-routing','upgrade-srp','rotate-disposable-password']); a=p.parse_args()
if a.action=='prepare': prepare()
elif a.action=='upgrade-srp': upgrade_local_srp()
elif a.action=='rotate-disposable-password': rotate_disposable_password()
else: route(a.action=='route')
if __name__=='__main__': main()