import threading
import argparse, base64, hashlib, json, os, pathlib, subprocess, time, urllib.request, urllib.error, urllib.parse
from PIL import Image, ImageDraw, ImageFont
p=argparse.ArgumentParser(); p.add_argument('--checkout',required=True); p.add_argument('--home',required=True); p.add_argument('--port',required=True); p.add_argument('--side',required=True); p.add_argument('--commit',required=True); p.add_argument('--out',required=True); a=p.parse_args()
out=pathlib.Path(a.out)/str(time.time_ns()); out.mkdir(parents=True)
origin='http://127.0.0.1:'+a.port
lines=[]; events=[]; started=time.monotonic()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
def frame(shown):
    im=Image.new('RGB',(1600,1000),'#0d1723'); d=ImageDraw.Draw(im)
    for i,line in enumerate(shown): d.text((24,24+i*29),line,fill='#cce8ed' if i>2 else '#72dfbe',font=font)
    return im
# Record the driver's displayed output continuously while the real requests execute.
proc=subprocess.Popen(['ffmpeg','-y','-loglevel','error','-f','rawvideo','-pix_fmt','rgb24','-s','1600x1000','-r','5','-i','-','-an','-c:v','libx264','-pix_fmt','yuv420p',str(out/'recording.mp4')],stdin=subprocess.PIPE)
stop=threading.Event()
def record():
    while not stop.is_set():
        tick=time.monotonic(); proc.stdin.write(frame(list(lines)).tobytes())
        stop.wait(max(0,.2-(time.monotonic()-tick)))
recorder=threading.Thread(target=record,daemon=True); recorder.start()
def log(s):
    print(s,flush=True); lines.append(s); events.append([round(time.monotonic()-started,3),s]); time.sleep(.6)
def cli(*args):
    return subprocess.check_output(['node','apps/server/src/bin.ts',*args,'--base-dir',a.home],cwd=a.checkout,text=True,stderr=subprocess.PIPE)
def http(path,body=None,token=None,method='POST',session=None,form=False):
    headers={'accept':'application/json, text/event-stream'}
    if token: headers['authorization']='Bearer '+token
    if session: headers.update({'mcp-session-id':session,'mcp-protocol-version':'2025-06-18'})
    data=None
    if body is not None:
        headers['content-type']='application/x-www-form-urlencoded' if form else 'application/json'
        data=(urllib.parse.urlencode(body) if form else json.dumps(body)).encode()
    try: r=urllib.request.urlopen(urllib.request.Request(origin+path,data=data,headers=headers,method=method),timeout=20)
    except urllib.error.HTTPError as e: r=e
    raw=r.read().decode(); return r.status,dict(r.headers),raw

def credential(label):
    pair=json.loads(cli('auth','pairing','create','--label',label,'--json'))['credential']
    st,_,raw=http('/oauth/mcp/register',{'client_name':label,'redirect_uris':['http://localhost:51234/callback'],'grant_types':['authorization_code'],'token_endpoint_auth_method':'none'})
    if st!=200 and st!=201: raise RuntimeError('register '+str(st)+' '+raw)
    client=json.loads(raw)['client_id']; verifier=base64.urlsafe_b64encode(os.urandom(48)).decode().rstrip('='); challenge=base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
    auth={'response_type':'code','client_id':client,'redirect_uri':'http://localhost:51234/callback','code_challenge':challenge,'code_challenge_method':'S256','state':'proof','resource':origin+'/mcp'}
    st,_,raw=http('/oauth/mcp/decision',{'authorization':auth,'decision':{'_tag':'pairing-code','access':'full-access','code':pair}})
    if st!=200: raise RuntimeError('decision '+str(st)+' '+raw)
    code=urllib.parse.parse_qs(urllib.parse.urlparse(json.loads(raw)['redirectTo']).query)['code'][0]
    st,_,raw=http('/oauth/mcp/token',{'grant_type':'authorization_code','code':code,'redirect_uri':auth['redirect_uri'],'client_id':client,'code_verifier':verifier,'resource':origin+'/mcp'},form=True)
    if st!=200: raise RuntimeError('token '+str(st)+' '+raw)
    log(label+': separate MCP OAuth credential issued via registration + pairing + PKCE (HTTP 200)')
    return json.loads(raw)['access_token']

log('MCP transport ownership | '+a.side.upper()+' | '+a.commit)
log('Environment: Linux; real Node server; loopback HTTP; fresh isolated database')
log('Protocol: 2025-06-18 | secrets and session IDs omitted')
A=credential('Owner A'); B=credential('Other B')
id=0
results={}
def req(label,token,session=None,method='tools/list',verb='POST'):
    global id
    id+=1
    body=None if verb!='POST' else {'jsonrpc':'2.0','id':id,'method':method,'params':{}}
    st,h,raw=http('/mcp',body,token,verb,session)
    summary=''
    if method=='tools/list' and st==200:
        # The server returns SSE for JSON-RPC responses.
        payload=json.loads(next(x[6:] for x in raw.splitlines() if x.startswith('data: '))) if raw.startswith('event:') else json.loads(raw)
        tools=payload.get('result',{}).get('tools',[])
        summary='; '+str(len(tools))+' tools returned'
    elif raw: summary='; '+raw.replace('\n',' ')[:150]
    log(label+' -> HTTP '+str(st)+summary); results[label]=st
    return st,h,raw

def initialize(label):
    st,h,raw=http('/mcp',{'jsonrpc':'2.0','id':1,'method':'initialize','params':{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'ownership-proof','version':'1'}}},A)
    sid=next((v for k,v in h.items() if k.lower()=='mcp-session-id'),None)
    log(label+' A initialize -> HTTP '+str(st)+'; Mcp-Session-Id '+('received' if sid else 'MISSING'))
    if st!=200 or not sid: raise RuntimeError('initialize failed')
    st,_,_=http('/mcp',{'jsonrpc':'2.0','method':'notifications/initialized'},A,session=sid)
    log(label+' A notifications/initialized -> HTTP '+str(st)); return sid
s=initialize('Session 1')
req('A POST tools/list before attack',A,s)
req('B POST tools/list with A session',B,s)
req('B GET with A session',B,s,verb='GET')
req('B DELETE with A session',B,s,verb='DELETE')
req('A POST tools/list after B DELETE',A,s)
req('A DELETE own session',A,s,verb='DELETE')
s=initialize('Control session')
req('Control A POST tools/list',A,s)
req('Control A DELETE',A,s,verb='DELETE')
req('No credential POST',None,s)
req('Junk credential POST','invalid-proof-credential',s)
# Revoke the actual OAuth session through the shipped CLI, then try the same token.
sessions=json.loads(cli('auth','session','list','--json'))
if isinstance(sessions,dict): sessions=sessions.get('sessions',[])
b=max(sessions,key=lambda x:x['issuedAt'])
cli('auth','session','revoke',b['sessionId'])
req('Revoked B credential POST',B,s)
log('END: same request sequence completed; HTTP responses above are from the real server')
(out/'transcript.txt').write_text('\n'.join(lines)+'\n')
(out/'responses.json').write_text(json.dumps({'side':a.side,'commit':a.commit,'statuses':results,'events':events},indent=2))
im=frame(list(lines)); im.save(out/'capture.png'); time.sleep(.5)
assert frame(list(lines)).tobytes()==im.tobytes()
time.sleep(2)
stop.set(); recorder.join(); proc.stdin.close(); assert proc.wait()==0
print('Artifacts: '+str(out))
