Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,11 +3,16 @@ import re
|
|
| 3 |
import json
|
| 4 |
import base64
|
| 5 |
import logging
|
|
|
|
| 6 |
from typing import List, Dict, Any
|
| 7 |
from fastapi import FastAPI
|
| 8 |
from pydantic import BaseModel
|
| 9 |
-
import
|
| 10 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# -------------------------
|
| 13 |
# Logging
|
|
@@ -52,115 +57,173 @@ def try_decode_jwt(token: str) -> Dict[str, Any]:
|
|
| 52 |
return {}
|
| 53 |
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
# -------------------------
|
| 56 |
-
# Scraper
|
| 57 |
# -------------------------
|
| 58 |
-
def
|
| 59 |
-
"""Scrape
|
|
|
|
| 60 |
try:
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
"Chrome/118.0 Safari/537.36"
|
| 65 |
-
}
|
| 66 |
-
r = requests.get(url, headers=headers, timeout=30)
|
| 67 |
-
r.raise_for_status()
|
| 68 |
-
html = r.text
|
| 69 |
-
soup = BeautifulSoup(html, "html.parser")
|
| 70 |
-
|
| 71 |
-
title = soup.title.get_text(strip=True) if soup.title else "No title"
|
| 72 |
-
visible_text = soup.get_text(separator=" ", strip=True)[:6000]
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
hidden_values: List[str] = []
|
| 75 |
jwt_data: Dict[str, Any] = {}
|
| 76 |
|
| 77 |
-
#
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
value = inp.get("value", "")
|
| 81 |
-
if value:
|
| 82 |
-
hidden_values.append(f"hidden_input {name}={value}")
|
| 83 |
-
|
| 84 |
-
# Elements with display:none
|
| 85 |
-
for elem in soup.find_all(attrs={"style": re.compile(r"display\s*:\s*none", re.I)}):
|
| 86 |
-
txt = elem.get_text(" ", strip=True)
|
| 87 |
-
if txt:
|
| 88 |
-
hidden_values.append(f"display_none {txt}")
|
| 89 |
-
|
| 90 |
-
# HTML comments
|
| 91 |
-
for comment in soup.find_all(string=lambda t: isinstance(t, str) and ("<!--" in t or "-->" in t)):
|
| 92 |
-
c = str(comment).strip()
|
| 93 |
-
if c:
|
| 94 |
-
hidden_values.append(f"comment {c}")
|
| 95 |
-
|
| 96 |
-
# data-* attributes
|
| 97 |
-
for tag in soup.find_all():
|
| 98 |
-
for k, v in tag.attrs.items():
|
| 99 |
-
if k.startswith("data-") and isinstance(v, str) and v.strip():
|
| 100 |
-
hidden_values.append(f"{k}={v.strip()}")
|
| 101 |
-
|
| 102 |
-
# Script tags (look for JSON-like challenge info and completion codes)
|
| 103 |
-
for script in soup.find_all("script"):
|
| 104 |
-
txt = script.get_text(" ", strip=True)
|
| 105 |
-
if txt:
|
| 106 |
-
# Look for completion codes or challenge codes
|
| 107 |
-
completion_matches = re.findall(r"(completion[_\s]*code|challenge[_\s]*code|code)\s*[:=]\s*['\"]?([A-Za-z0-9\-_]{6,})['\"]?", txt, flags=re.I)
|
| 108 |
-
for k, v in completion_matches:
|
| 109 |
-
hidden_values.append(f"script completion_code={v}")
|
| 110 |
-
|
| 111 |
-
# General matches for challenge info
|
| 112 |
-
matches = re.findall(r"(challenge\w*|code|completion)\s*[:=]\s*['\"]?([A-Za-z0-9\-_]+)['\"]?", txt, flags=re.I)
|
| 113 |
-
for k, v in matches:
|
| 114 |
-
hidden_values.append(f"script {k}={v}")
|
| 115 |
-
|
| 116 |
-
# ✅ Enhanced JWT token detection and decoding
|
| 117 |
-
# Look for JWT patterns in the entire HTML content
|
| 118 |
jwt_patterns = [
|
| 119 |
-
r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
|
| 120 |
-
r"[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}"
|
| 121 |
]
|
| 122 |
|
| 123 |
for pattern in jwt_patterns:
|
| 124 |
-
jwt_matches = re.findall(pattern,
|
| 125 |
for token in jwt_matches:
|
| 126 |
-
logger.info(f"Found
|
| 127 |
data = try_decode_jwt(token)
|
| 128 |
if data:
|
| 129 |
jwt_data.update(data)
|
| 130 |
for k, v in data.items():
|
| 131 |
hidden_values.append(f"jwt {k}={v}")
|
| 132 |
|
| 133 |
-
# Look for completion codes in
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
r"
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
logger.info(f"Found {len(hidden_values)} hidden values")
|
| 152 |
logger.info(f"JWT data: {jwt_data}")
|
| 153 |
|
| 154 |
return {
|
| 155 |
-
"title": title,
|
| 156 |
-
"visible_text":
|
| 157 |
-
"hidden_values": hidden_values
|
| 158 |
"jwt_data": jwt_data,
|
|
|
|
|
|
|
| 159 |
}
|
| 160 |
|
| 161 |
except Exception as e:
|
| 162 |
-
logger.error(f"
|
| 163 |
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
|
| 166 |
# -------------------------
|
|
@@ -169,57 +232,69 @@ def scrape_with_requests(url: str) -> Dict[str, Any]:
|
|
| 169 |
def answer_question(question: str, content: Dict[str, Any]) -> str:
|
| 170 |
"""Enhanced rule-based extraction for Round 5 questions."""
|
| 171 |
ql = question.lower()
|
| 172 |
-
title = content.get("title", "")
|
| 173 |
hidden = content.get("hidden_values", [])
|
| 174 |
jwt_data = content.get("jwt_data", {})
|
|
|
|
| 175 |
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
if "challenge id" in ql or "challengeid" in ql:
|
| 178 |
# First check JWT data directly
|
| 179 |
if "challengeID" in jwt_data:
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
| 182 |
for h in hidden:
|
| 183 |
if "challengeid" in h.lower():
|
| 184 |
-
|
|
|
|
|
|
|
| 185 |
|
|
|
|
| 186 |
if "completion" in ql and "code" in ql:
|
| 187 |
-
# Look for completion codes
|
| 188 |
for h in hidden:
|
| 189 |
if "completion_code" in h.lower():
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
return
|
| 193 |
|
| 194 |
-
#
|
| 195 |
-
for
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
|
|
|
| 199 |
if "challenge name" in ql:
|
| 200 |
-
# Check JWT data first
|
| 201 |
if "coolGuy" in jwt_data:
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
if "challenge" in h.lower() and "name" in h.lower():
|
| 206 |
-
return h.split("=", 1)[-1].strip()
|
| 207 |
-
|
| 208 |
-
# Fallbacks
|
| 209 |
-
if "challenge name" in ql and title:
|
| 210 |
-
return title.strip()
|
| 211 |
|
| 212 |
-
#
|
| 213 |
if jwt_data:
|
| 214 |
-
# For challenge ID questions, return challengeID if present
|
| 215 |
-
if "challenge" in ql and "id" in ql and "challengeID" in jwt_data:
|
| 216 |
-
return str(jwt_data["challengeID"])
|
| 217 |
-
|
| 218 |
-
# For other questions, return the first non-standard field
|
| 219 |
for key, value in jwt_data.items():
|
| 220 |
-
if key not in ["iat", "exp"
|
|
|
|
| 221 |
return str(value)
|
| 222 |
|
|
|
|
| 223 |
return "Challenge information not found"
|
| 224 |
|
| 225 |
|
|
@@ -229,7 +304,7 @@ def answer_question(question: str, content: Dict[str, Any]) -> str:
|
|
| 229 |
@app.get("/")
|
| 230 |
def root():
|
| 231 |
return {
|
| 232 |
-
"message": "HackRx Round 5 API - Ready",
|
| 233 |
"endpoints": {"challenge": "POST /challenge", "health": "GET /health"},
|
| 234 |
}
|
| 235 |
|
|
@@ -242,7 +317,7 @@ def health():
|
|
| 242 |
@app.post("/challenge", response_model=ChallengeResponse)
|
| 243 |
def challenge(req: ChallengeRequest):
|
| 244 |
logger.info(f"Round 5 request: url={req.url}, questions={req.questions}")
|
| 245 |
-
content =
|
| 246 |
if not content:
|
| 247 |
return ChallengeResponse(answers=["Challenge information not found" for _ in req.questions])
|
| 248 |
|
|
|
|
| 3 |
import json
|
| 4 |
import base64
|
| 5 |
import logging
|
| 6 |
+
import time
|
| 7 |
from typing import List, Dict, Any
|
| 8 |
from fastapi import FastAPI
|
| 9 |
from pydantic import BaseModel
|
| 10 |
+
from selenium import webdriver
|
| 11 |
+
from selenium.webdriver.common.by import By
|
| 12 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 13 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 14 |
+
from selenium.webdriver.chrome.options import Options
|
| 15 |
+
from selenium.webdriver.chrome.service import Service
|
| 16 |
|
| 17 |
# -------------------------
|
| 18 |
# Logging
|
|
|
|
| 57 |
return {}
|
| 58 |
|
| 59 |
|
| 60 |
+
def setup_chrome_driver():
|
| 61 |
+
"""Setup Chrome driver with appropriate options."""
|
| 62 |
+
chrome_options = Options()
|
| 63 |
+
chrome_options.add_argument("--headless") # Run in background
|
| 64 |
+
chrome_options.add_argument("--no-sandbox")
|
| 65 |
+
chrome_options.add_argument("--disable-dev-shm-usage")
|
| 66 |
+
chrome_options.add_argument("--disable-gpu")
|
| 67 |
+
chrome_options.add_argument("--window-size=1920,1080")
|
| 68 |
+
chrome_options.add_argument("--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0 Safari/537.36")
|
| 69 |
+
|
| 70 |
+
# Enable logging to capture console messages
|
| 71 |
+
chrome_options.add_argument("--enable-logging")
|
| 72 |
+
chrome_options.add_argument("--log-level=0")
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
driver = webdriver.Chrome(options=chrome_options)
|
| 76 |
+
return driver
|
| 77 |
+
except Exception as e:
|
| 78 |
+
logger.error(f"Failed to create Chrome driver: {e}")
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
# -------------------------
|
| 83 |
+
# Interactive Scraper
|
| 84 |
# -------------------------
|
| 85 |
+
def scrape_with_selenium(url: str) -> Dict[str, Any]:
|
| 86 |
+
"""Scrape webpage with Selenium, click Start Challenge, and extract data."""
|
| 87 |
+
driver = None
|
| 88 |
try:
|
| 89 |
+
driver = setup_chrome_driver()
|
| 90 |
+
if not driver:
|
| 91 |
+
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
logger.info(f"Loading URL: {url}")
|
| 94 |
+
driver.get(url)
|
| 95 |
+
|
| 96 |
+
# Wait for page to load
|
| 97 |
+
WebDriverWait(driver, 10).until(
|
| 98 |
+
EC.presence_of_element_located((By.TAG_NAME, "body"))
|
| 99 |
+
)
|
| 100 |
+
time.sleep(2)
|
| 101 |
+
|
| 102 |
+
# Look for and click "Start Challenge" button
|
| 103 |
+
start_button_selectors = [
|
| 104 |
+
"button:contains('Start Challenge')",
|
| 105 |
+
"button[id*='start']",
|
| 106 |
+
"button[class*='start']",
|
| 107 |
+
"input[value*='Start']",
|
| 108 |
+
"a[href*='start']",
|
| 109 |
+
".btn:contains('Start')",
|
| 110 |
+
"[onclick*='start']"
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
button_clicked = False
|
| 114 |
+
for selector in start_button_selectors:
|
| 115 |
+
try:
|
| 116 |
+
if "contains" in selector:
|
| 117 |
+
# Use XPath for text-based selection
|
| 118 |
+
xpath_selector = f"//button[contains(text(), 'Start Challenge')] | //button[contains(text(), 'Start')] | //input[contains(@value, 'Start')]"
|
| 119 |
+
elements = driver.find_elements(By.XPATH, xpath_selector)
|
| 120 |
+
else:
|
| 121 |
+
elements = driver.find_elements(By.CSS_SELECTOR, selector)
|
| 122 |
+
|
| 123 |
+
if elements:
|
| 124 |
+
logger.info(f"Found start button with selector: {selector}")
|
| 125 |
+
elements[0].click()
|
| 126 |
+
button_clicked = True
|
| 127 |
+
time.sleep(3) # Wait for challenge to start
|
| 128 |
+
break
|
| 129 |
+
except Exception as e:
|
| 130 |
+
logger.debug(f"Selector {selector} failed: {e}")
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
if not button_clicked:
|
| 134 |
+
logger.warning("Could not find Start Challenge button, proceeding with current page")
|
| 135 |
+
|
| 136 |
+
# Get page source after interaction
|
| 137 |
+
html = driver.page_source
|
| 138 |
+
|
| 139 |
+
# Get console logs
|
| 140 |
+
console_logs = []
|
| 141 |
+
try:
|
| 142 |
+
logs = driver.get_log('browser')
|
| 143 |
+
for log in logs:
|
| 144 |
+
console_logs.append(log['message'])
|
| 145 |
+
logger.info(f"Console log: {log['message']}")
|
| 146 |
+
except Exception as e:
|
| 147 |
+
logger.warning(f"Could not get console logs: {e}")
|
| 148 |
+
|
| 149 |
+
# Extract data from HTML
|
| 150 |
hidden_values: List[str] = []
|
| 151 |
jwt_data: Dict[str, Any] = {}
|
| 152 |
|
| 153 |
+
# Look for JWT tokens in HTML and console logs
|
| 154 |
+
all_text = html + " ".join(console_logs)
|
| 155 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
jwt_patterns = [
|
| 157 |
+
r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
|
| 158 |
+
r"[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}"
|
| 159 |
]
|
| 160 |
|
| 161 |
for pattern in jwt_patterns:
|
| 162 |
+
jwt_matches = re.findall(pattern, all_text)
|
| 163 |
for token in jwt_matches:
|
| 164 |
+
logger.info(f"Found JWT token: {token[:50]}...")
|
| 165 |
data = try_decode_jwt(token)
|
| 166 |
if data:
|
| 167 |
jwt_data.update(data)
|
| 168 |
for k, v in data.items():
|
| 169 |
hidden_values.append(f"jwt {k}={v}")
|
| 170 |
|
| 171 |
+
# Look for completion codes in console logs
|
| 172 |
+
for log in console_logs:
|
| 173 |
+
# Look for completion codes
|
| 174 |
+
completion_matches = re.findall(r"completion[_\s]*code[:\s]*([A-Za-z0-9\-_]{6,})", log, flags=re.I)
|
| 175 |
+
for code in completion_matches:
|
| 176 |
+
hidden_values.append(f"completion_code {code}")
|
| 177 |
+
|
| 178 |
+
# Look for challenge completion messages
|
| 179 |
+
if "challenge" in log.lower() and ("complete" in log.lower() or "finished" in log.lower()):
|
| 180 |
+
hidden_values.append(f"console_message {log}")
|
| 181 |
+
|
| 182 |
+
# Execute JavaScript to check for global variables or challenge data
|
| 183 |
+
try:
|
| 184 |
+
js_result = driver.execute_script("""
|
| 185 |
+
var data = {};
|
| 186 |
+
if (window.challengeData) data.challengeData = window.challengeData;
|
| 187 |
+
if (window.challenge) data.challenge = window.challenge;
|
| 188 |
+
if (window.completionCode) data.completionCode = window.completionCode;
|
| 189 |
+
return data;
|
| 190 |
+
""")
|
| 191 |
+
if js_result:
|
| 192 |
+
for k, v in js_result.items():
|
| 193 |
+
hidden_values.append(f"js_global {k}={v}")
|
| 194 |
+
logger.info(f"Found JS global: {k} = {v}")
|
| 195 |
+
except Exception as e:
|
| 196 |
+
logger.debug(f"JS execution failed: {e}")
|
| 197 |
+
|
| 198 |
+
# Look for data in local storage
|
| 199 |
+
try:
|
| 200 |
+
local_storage = driver.execute_script("return window.localStorage;")
|
| 201 |
+
if local_storage:
|
| 202 |
+
for k, v in local_storage.items():
|
| 203 |
+
if any(keyword in k.lower() for keyword in ['challenge', 'code', 'completion']):
|
| 204 |
+
hidden_values.append(f"localStorage {k}={v}")
|
| 205 |
+
except Exception as e:
|
| 206 |
+
logger.debug(f"LocalStorage check failed: {e}")
|
| 207 |
|
| 208 |
logger.info(f"Found {len(hidden_values)} hidden values")
|
| 209 |
logger.info(f"JWT data: {jwt_data}")
|
| 210 |
|
| 211 |
return {
|
| 212 |
+
"title": driver.title,
|
| 213 |
+
"visible_text": driver.find_element(By.TAG_NAME, "body").text[:6000],
|
| 214 |
+
"hidden_values": hidden_values,
|
| 215 |
"jwt_data": jwt_data,
|
| 216 |
+
"console_logs": console_logs,
|
| 217 |
+
"button_clicked": button_clicked
|
| 218 |
}
|
| 219 |
|
| 220 |
except Exception as e:
|
| 221 |
+
logger.error(f"Selenium scraping failed for {url}: {e}")
|
| 222 |
return {}
|
| 223 |
+
|
| 224 |
+
finally:
|
| 225 |
+
if driver:
|
| 226 |
+
driver.quit()
|
| 227 |
|
| 228 |
|
| 229 |
# -------------------------
|
|
|
|
| 232 |
def answer_question(question: str, content: Dict[str, Any]) -> str:
|
| 233 |
"""Enhanced rule-based extraction for Round 5 questions."""
|
| 234 |
ql = question.lower()
|
|
|
|
| 235 |
hidden = content.get("hidden_values", [])
|
| 236 |
jwt_data = content.get("jwt_data", {})
|
| 237 |
+
console_logs = content.get("console_logs", [])
|
| 238 |
|
| 239 |
+
logger.info(f"Answering question: {question}")
|
| 240 |
+
logger.info(f"Available JWT data: {jwt_data}")
|
| 241 |
+
logger.info(f"Hidden values count: {len(hidden)}")
|
| 242 |
+
|
| 243 |
+
# Challenge ID extraction
|
| 244 |
if "challenge id" in ql or "challengeid" in ql:
|
| 245 |
# First check JWT data directly
|
| 246 |
if "challengeID" in jwt_data:
|
| 247 |
+
result = str(jwt_data["challengeID"])
|
| 248 |
+
logger.info(f"Found challengeID in JWT: {result}")
|
| 249 |
+
return result
|
| 250 |
+
|
| 251 |
+
# Check hidden values
|
| 252 |
for h in hidden:
|
| 253 |
if "challengeid" in h.lower():
|
| 254 |
+
result = h.split("=", 1)[-1].strip()
|
| 255 |
+
logger.info(f"Found challengeID in hidden values: {result}")
|
| 256 |
+
return result
|
| 257 |
|
| 258 |
+
# Completion code extraction
|
| 259 |
if "completion" in ql and "code" in ql:
|
| 260 |
+
# Look for explicit completion codes
|
| 261 |
for h in hidden:
|
| 262 |
if "completion_code" in h.lower():
|
| 263 |
+
result = h.split("=", 1)[-1].strip()
|
| 264 |
+
logger.info(f"Found completion code: {result}")
|
| 265 |
+
return result
|
| 266 |
|
| 267 |
+
# Look in console logs for completion codes
|
| 268 |
+
for log in console_logs:
|
| 269 |
+
completion_matches = re.findall(r"completion[_\s]*code[:\s]*([A-Za-z0-9\-_]{6,})", log, flags=re.I)
|
| 270 |
+
if completion_matches:
|
| 271 |
+
result = completion_matches[0]
|
| 272 |
+
logger.info(f"Found completion code in console: {result}")
|
| 273 |
+
return result
|
| 274 |
+
|
| 275 |
+
# Look for any long tokens that might be completion codes
|
| 276 |
+
for h in hidden:
|
| 277 |
+
if "token" in h.lower() or "code" in h.lower():
|
| 278 |
+
token = h.split("=", 1)[-1].strip()
|
| 279 |
+
if len(token) > 15: # Assuming completion codes are reasonably long
|
| 280 |
+
logger.info(f"Found potential completion code: {token}")
|
| 281 |
+
return token
|
| 282 |
|
| 283 |
+
# Challenge name extraction
|
| 284 |
if "challenge name" in ql:
|
|
|
|
| 285 |
if "coolGuy" in jwt_data:
|
| 286 |
+
result = str(jwt_data["coolGuy"])
|
| 287 |
+
logger.info(f"Found challenge name in JWT: {result}")
|
| 288 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
+
# Fallback: return any relevant data from JWT
|
| 291 |
if jwt_data:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
for key, value in jwt_data.items():
|
| 293 |
+
if key not in ["iat", "exp"] and isinstance(value, str):
|
| 294 |
+
logger.info(f"Fallback: returning JWT field {key}: {value}")
|
| 295 |
return str(value)
|
| 296 |
|
| 297 |
+
logger.warning("No matching data found for question")
|
| 298 |
return "Challenge information not found"
|
| 299 |
|
| 300 |
|
|
|
|
| 304 |
@app.get("/")
|
| 305 |
def root():
|
| 306 |
return {
|
| 307 |
+
"message": "HackRx Round 5 API - Ready (with Selenium support)",
|
| 308 |
"endpoints": {"challenge": "POST /challenge", "health": "GET /health"},
|
| 309 |
}
|
| 310 |
|
|
|
|
| 317 |
@app.post("/challenge", response_model=ChallengeResponse)
|
| 318 |
def challenge(req: ChallengeRequest):
|
| 319 |
logger.info(f"Round 5 request: url={req.url}, questions={req.questions}")
|
| 320 |
+
content = scrape_with_selenium(req.url)
|
| 321 |
if not content:
|
| 322 |
return ChallengeResponse(answers=["Challenge information not found" for _ in req.questions])
|
| 323 |
|