#!/usr/bin/env python3
import asyncio, json, ssl, subprocess, re
import websockets

SID = open('/tmp/opencode/redteam/script_id.txt').read().strip()
URL = 'wss://209.50.60.133.sslip.io/ws?role=secroauth&script_id=%s&bin=1' % SID
BASE = open('/tmp/opencode/redteam/run_hget5.lua','rb').read().decode('latin-1')
KEY = open('/tmp/opencode/redteam/key.txt').read().strip()

def run_loader(hello, hwid):
    src = re.sub(r"local _HELLO = '.*?'\n", "local _HELLO = %s\n" % json.dumps(hello), BASE, count=1)
    src = src.replace("return 'HWID-TEST-0001'", "return %s" % json.dumps(hwid))
    open('/tmp/opencode/redteam/run_sess.lua','w').write(src)
    p = subprocess.run(['/tmp/opencode/redteam/luau_bin/luau','/tmp/opencode/redteam/run_sess.lua'],
                       capture_output=True, text=True, timeout=20)
    out = p.stdout + p.stderr
    msgs = [l.split('[SB] WS.SEND ',1)[1] for l in out.splitlines() if '[SB] WS.SEND ' in l]
    return (msgs[-1] if msgs else None), out

def ctx():
    c = ssl.create_default_context(); c.check_hostname=False; c.verify_mode=ssl.CERT_NONE
    return c

async def legit(hwid):
    async with websockets.connect(URL, ssl=ctx(), open_timeout=10) as ws:
        hello = await asyncio.wait_for(ws.recv(), timeout=5)
        payload, out = run_loader(hello, hwid)
        if not payload:
            print('gen failed', '\n'.join(out.splitlines()[-5:])); return None
        await ws.send(payload)
        msgs = []
        try:
            while True:
                r = await asyncio.wait_for(ws.recv(), timeout=4)
                msgs.append(r)
                if isinstance(r, str) and ('auth_ok' in r or 'error' in r):
                    break
        except Exception as e:
            print('recv ended:', type(e).__name__)
        print('AUTH HWID', hwid, '->', [ (m[:200] if isinstance(m,str) else m[:20]) for m in msgs])
        return msgs

async def reuse(session_id):
    print('==== session reuse', session_id)
    async with websockets.connect(URL, ssl=ctx(), open_timeout=10) as ws:
        hello = await asyncio.wait_for(ws.recv(), timeout=5)
        for msg in [
            {'type':'chunk','session_id':session_id},
            {'type':'resume','session_id':session_id},
            {'type':'auth','session_id':session_id,'v':3},
        ]:
            print('SEND', msg)
            await ws.send(json.dumps(msg))
            try:
                r = await asyncio.wait_for(ws.recv(), timeout=4)
                print('RECV', repr(r)[:300])
            except asyncio.TimeoutError:
                print('(timeout)')

async def main():
    m1 = await legit('HWID-SPOOFED-9999')
    sid = None
    if m1:
        for r in m1:
            if isinstance(r, str) and 'auth_ok' in r:
                try: sid = json.loads(r).get('session_id')
                except Exception: pass
    if sid:
        await reuse(sid)

asyncio.run(main())
