367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
105 lines
9.4 KiB
Python
105 lines
9.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Real Forever <-> separately authenticated local protocol-peer guild test.
|
|
|
|
The protocol peer is an ordinary, explicitly journaled disposable account. The
|
|
actual modified Forever executable remains the target; this is not a second
|
|
Forever/native-client claim. GM membership is fixture setup only, never a chat
|
|
substitute. No server rule changes, credential output, SQL writes or packet
|
|
injection into the target client.
|
|
"""
|
|
import argparse,json,queue,subprocess,threading,time
|
|
from pathlib import Path
|
|
from client_session import Session
|
|
import client_ui as ui
|
|
from local_tortoise import db
|
|
from native_engine_character_test import ROOT,Controller,local_listeners
|
|
from native_test_guard import require_local_turtle_ports,require_authenticated_turtle_realm,require_native_gameplay_policy,require_solo_test_character
|
|
from native_world_trace import WorldTrace
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--fixture',type=Path,required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args();out=a.output.resolve();fixture=a.fixture.resolve()
|
|
if not out.is_relative_to(ROOT/'runtime') or out.exists() or not fixture.is_relative_to(ROOT/'runtime'):p.error('Require existing private fixture and new runtime output')
|
|
f=json.loads(fixture.read_text());directory=Path(f['account_directory']).resolve()
|
|
if not directory.is_relative_to(ROOT/'secrets') or f.get('kind')!='disposable-local-guild-peer' or f.get('character_name')!='Chatpeer' or not f.get('created'):raise RuntimeError('Require journaled disposable peer, no unrelated account')
|
|
account=json.loads((directory/'account.json').read_text());peer_id=int(f['character_record'].split('\t')[0]);peer_account=int(f['account_id'])
|
|
if account['account_id']!=peer_account or db(f'SELECT account,name FROM tw_char.characters WHERE guid={peer_id};')!=f'{peer_account}\tChatpeer':raise RuntimeError('Peer identity mismatch')
|
|
require_local_turtle_ports(local_listeners());require_solo_test_character(4509,db('SELECT guid FROM tw_char.characters WHERE online<>0 ORDER BY guid;'))
|
|
if db('SELECT account FROM tw_char.characters WHERE guid=4509;')==str(peer_account):raise RuntimeError('Peer must authenticate a separate ordinary account')
|
|
if db(f'SELECT `rank`,active FROM tw_logon.account WHERE id={peer_account};')!='0\t1':raise RuntimeError('Peer must be an ordinary no-GM disposable account')
|
|
guild=int(f['guild_id']);membership=db(f'SELECT g.guildid,g.name FROM tw_char.guild g JOIN tw_char.guild_member m ON m.guildid=g.guildid WHERE m.guid=4509;')
|
|
if membership!=f'{guild}\tHybridLocalTest':raise RuntimeError('Primary does not own journaled local guild fixture')
|
|
previous_peer_guild=db(f'SELECT guildid FROM tw_char.guild_member WHERE guid={peer_id};')
|
|
if previous_peer_guild not in ('',str(guild)):raise RuntimeError('Preserve existing unrelated peer guild')
|
|
c=Controller(int((ROOT/'runtime/native-client.pid').read_text()));require_authenticated_turtle_realm(c.rpc('inspect-wire-account'));require_native_gameplay_policy(c.rpc('inspect-native-channel-policy'))
|
|
# Login calls SetGMVisible (which immediately writes19) before restoring
|
|
# GM.Chat/Whisper flags in memory to55. Save through the actual GM handler
|
|
# before baseline; do not mistake a later normal autosave for a mutation.
|
|
with WorldTrace(c) as setup:
|
|
with Session(c.pid) as s:
|
|
if s.state()!='world':raise RuntimeError('Require actual native world for source baseline save')
|
|
s.focus();s.macro('/s .save');saved_request=setup.wait(2,0x2d0023,4);saved_reply=setup.wait(1,0x96,4,after_index=saved_request['index'])
|
|
baseline=db('SELECT level,health,power2,money,extra_flags FROM tw_char.characters WHERE guid=4509;')
|
|
report=dict(pid=c.pid,character=4509,peer_character=peer_id,peer_is_protocol_reference=True,peer_is_separate_ordinary_account=True,external_gateway_running=False,guild_id=guild,before_state=baseline,baseline_save_request=saved_request,baseline_save_reply=saved_reply,peer_membership_before=previous_peer_guild,chat_attempted=False,multiplayer_wire_verified=False,actual_ui_review_required=True);failure=None;old=ui.KEY_DELAY
|
|
lines=[];events=queue.Queue()
|
|
peer=subprocess.Popen([str(ROOT/'build/local-guild-peer'),account['username'],str(directory/'password.txt'),str(directory/'version-hash.bin'),str(directory/'addon-tail.bin'),'Chatpeer'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,bufsize=1)
|
|
def collect():
|
|
for line in peer.stdout:
|
|
if len(lines)>=1024:events.put('OVERFLOW');return
|
|
lines.append(line.rstrip());events.put(line.rstrip())
|
|
thread=threading.Thread(target=collect,daemon=True);thread.start()
|
|
def wait_line(predicate,timeout):
|
|
end=time.monotonic()+timeout
|
|
while time.monotonic()<end:
|
|
if peer.poll() is not None and events.empty():raise RuntimeError('Peer exited; private inputs/details omitted')
|
|
try:line=events.get(timeout=min(.1,max(.001,end-time.monotonic())))
|
|
except queue.Empty:continue
|
|
if line=='OVERFLOW':raise RuntimeError('Peer diagnostic bound exceeded')
|
|
if predicate(line):return line
|
|
raise RuntimeError('Bounded peer observation expired; do not retry chat automatically')
|
|
with WorldTrace(c) as tr:
|
|
try:
|
|
report['peer_ready']=wait_line(lambda l:l==f'READY {peer_id}',15)
|
|
expected=sorted([4509,peer_id])
|
|
if db('SELECT guid FROM tw_char.characters WHERE online<>0 ORDER BY guid;').splitlines()!=[str(i) for i in expected]:raise RuntimeError('Unexpected third session; no input')
|
|
with Session(c.pid) as s:
|
|
if s.state()!='world':raise RuntimeError('Require actual native Forever world')
|
|
s.focus();ui.KEY_DELAY=.03
|
|
if not previous_peer_guild:
|
|
f['guild_join_attempted']=True;fixture.write_text(json.dumps(f,indent=2)+'\n');s.macro('/s .guild invite Chatpeer "HybridLocalTest"')
|
|
c.wait(lambda:db(f'SELECT guildid FROM tw_char.guild_member WHERE guid={peer_id};')==str(guild),6)
|
|
f['guild_joined']=True;fixture.write_text(json.dumps(f,indent=2)+'\n')
|
|
stamp=str(time.time_ns());outgoing='GW-peer-from-Forever-'+stamp;incoming='GW-peer-from-Chatpeer-'+stamp;report.update(outgoing=outgoing,incoming=incoming,chat_attempted=True)
|
|
s.macro('/g '+outgoing);request=tr.wait(2,0x2d000d,5);report['native_request']=request
|
|
report['peer_received_target']=wait_line(lambda l:l==f'RECEIVED 4509 {outgoing}',6)
|
|
echo=tr.wait(3,0x4c0001,5,after_index=request['index']);report['self_source_reply']=tr.source_before(echo,0x96,after_index=request['index'])
|
|
peer.stdin.write('send '+incoming+'\n');peer.stdin.flush();wait_line(lambda l:l=='SENT '+incoming,3)
|
|
remote=tr.wait(3,0x4c0001,6,after_index=echo['index']);report['remote_native_reply']=remote
|
|
# First unknown sender is emitted after real name51. Subsequent
|
|
# known senders use their genuine96 packet immediately.
|
|
try:report['remote_source_identity']=tr.source_before(remote,0x51,after_index=echo['index'])
|
|
except RuntimeError:report['remote_source_identity']=tr.source_before(remote,0x96,after_index=echo['index'])
|
|
report['peer_received_self']=wait_line(lambda l:l==f'RECEIVED {peer_id} {incoming}',3)
|
|
s.shot(out.with_suffix('.png'))
|
|
pipe=c.rpc('inspect-engine-pipe');report.update(pipe_error=pipe['error'],pipe_closed=pipe['closed'],after_state=db('SELECT level,health,power2,money,extra_flags FROM tw_char.characters WHERE guid=4509;'),peer_membership=db(f'SELECT guildid FROM tw_char.guild_member WHERE guid={peer_id};'))
|
|
if pipe['error'] or pipe['closed'] or report['after_state']!=baseline or report['peer_membership']!=str(guild):raise RuntimeError('Native connection/source state changed unexpectedly')
|
|
report['multiplayer_wire_verified']=True
|
|
except Exception as e:failure=type(e).__name__+': '+str(e)
|
|
finally:
|
|
ui.KEY_DELAY=old
|
|
try:
|
|
if peer.poll() is None:peer.stdin.write('quit\n');peer.stdin.flush()
|
|
peer.wait(timeout=35);thread.join(2)
|
|
report['peer_exit_code']=peer.returncode;report['peer_logged_out']='LOGGED_OUT' in lines
|
|
if peer.returncode or not report['peer_logged_out']:raise RuntimeError('Peer clean logout unverified')
|
|
except Exception as e:
|
|
report['peer_cleanup_error']=str(e)
|
|
if peer.poll() is None:peer.terminate();peer.wait(timeout=5)
|
|
failure=failure or 'Peer clean logout failed; inspect source saved state'
|
|
report.update(tr.report());report['peer_events']=lines
|
|
report['peer_saved_offline']=db(f'SELECT online FROM tw_char.characters WHERE guid={peer_id};')=='0'
|
|
if failure:report['failure']=failure
|
|
out.write_text(json.dumps(report,indent=2)+'\n');out.chmod(0o600)
|
|
print(json.dumps({k:report.get(k) for k in ('pid','peer_character','chat_attempted','multiplayer_wire_verified','actual_ui_review_required','peer_logged_out','peer_saved_offline','lost_metadata_rows','observer_error','failure')}))
|
|
return 0 if report['multiplayer_wire_verified'] and not tr.error and not failure and report['peer_saved_offline'] else 2
|
|
if __name__=='__main__':raise SystemExit(main())
|