Update app.py
Browse files
app.py
CHANGED
|
@@ -4,10 +4,12 @@ import json
|
|
| 4 |
import time
|
| 5 |
import logging
|
| 6 |
import requests
|
|
|
|
| 7 |
from flask import Flask, request, jsonify, render_template_string
|
| 8 |
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
|
| 9 |
-
from playwright_stealth import stealth_sync
|
| 10 |
import traceback
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Configuração de logging
|
| 13 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
@@ -15,7 +17,7 @@ logger = logging.getLogger(__name__)
|
|
| 15 |
|
| 16 |
app = Flask(__name__)
|
| 17 |
|
| 18 |
-
# Template HTML
|
| 19 |
HTML_TEMPLATE = """
|
| 20 |
<!DOCTYPE html>
|
| 21 |
<html>
|
|
@@ -24,6 +26,7 @@ HTML_TEMPLATE = """
|
|
| 24 |
<meta charset="utf-8">
|
| 25 |
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 26 |
<style>
|
|
|
|
| 27 |
body {
|
| 28 |
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
| 29 |
max-width: 1200px;
|
|
@@ -129,6 +132,14 @@ HTML_TEMPLATE = """
|
|
| 129 |
margin: 10px 0;
|
| 130 |
border-radius: 4px;
|
| 131 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
</style>
|
| 133 |
</head>
|
| 134 |
<body>
|
|
@@ -136,7 +147,7 @@ HTML_TEMPLATE = """
|
|
| 136 |
<h1>🛡️ Bypass AWS WAF - STF Jurisprudência</h1>
|
| 137 |
|
| 138 |
<div class="info-box">
|
| 139 |
-
<strong>📌 Sobre:</strong> Teste de bypass do AWS WAF usando Playwright
|
| 140 |
<br>
|
| 141 |
<strong>🔗 API Alvo:</strong> https://jurisprudencia.stf.jus.br/api/search/search
|
| 142 |
</div>
|
|
@@ -203,9 +214,9 @@ HTML_TEMPLATE = """
|
|
| 203 |
let resultHtml = '<div class="success">✅ Teste executado com sucesso!</div>';
|
| 204 |
resultHtml += '<pre>' + JSON.stringify(data.data, null, 2) + '</pre>';
|
| 205 |
|
| 206 |
-
if (data.
|
| 207 |
resultHtml += '<div class="info-box"><strong>🔑 Token AWS WAF obtido:</strong><br>' +
|
| 208 |
-
'<code style="word-break: break-all;">' + data.
|
| 209 |
}
|
| 210 |
|
| 211 |
resultDiv.innerHTML = resultHtml;
|
|
@@ -213,8 +224,16 @@ HTML_TEMPLATE = """
|
|
| 213 |
failCount++;
|
| 214 |
document.getElementById('failCount').textContent = failCount;
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
}
|
| 219 |
} catch (error) {
|
| 220 |
failCount++;
|
|
@@ -231,121 +250,117 @@ HTML_TEMPLATE = """
|
|
| 231 |
</html>
|
| 232 |
"""
|
| 233 |
|
| 234 |
-
# Dados da requisição
|
| 235 |
URL_API = "https://jurisprudencia.stf.jus.br/api/search/search"
|
| 236 |
HEADERS = {
|
| 237 |
"Accept": "application/json, text/plain, */*",
|
| 238 |
"Content-Type": "application/json",
|
| 239 |
-
"User-Agent": "Mozilla/5.0 (
|
| 240 |
-
"Referer": "https://jurisprudencia.stf.jus.br/pages/search
|
| 241 |
"Accept-Encoding": "gzip, deflate, br",
|
| 242 |
"Connection": "keep-alive",
|
| 243 |
"Origin": "https://jurisprudencia.stf.jus.br"
|
| 244 |
}
|
| 245 |
|
| 246 |
-
# Payload
|
| 247 |
PAYLOAD = {
|
| 248 |
"query": {
|
| 249 |
-
"
|
| 250 |
-
"
|
| 251 |
-
{"
|
| 252 |
-
|
| 253 |
-
],
|
| 254 |
-
"query": {
|
| 255 |
-
"bool": {
|
| 256 |
-
"filter": [
|
| 257 |
-
{"query_string": {
|
| 258 |
-
"default_operator": "AND",
|
| 259 |
-
"fields": ["ementa_texto.plural^3", "acordao_ata.plural^3"],
|
| 260 |
-
"query": "*",
|
| 261 |
-
"type": "cross_fields",
|
| 262 |
-
"fuzziness": "AUTO:4,7"
|
| 263 |
-
}}
|
| 264 |
-
],
|
| 265 |
-
"should": []
|
| 266 |
-
}
|
| 267 |
-
}
|
| 268 |
}
|
| 269 |
},
|
| 270 |
-
"_source": ["id", "titulo", "ementa_texto", "processo_numero"
|
| 271 |
-
"size":
|
| 272 |
"from": 0,
|
| 273 |
"sort": [{"_score": "desc"}]
|
| 274 |
}
|
| 275 |
|
| 276 |
-
def
|
| 277 |
-
"""
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
def test_with_requests():
|
| 294 |
-
"""Testa acesso direto com requests"""
|
| 295 |
-
logger.info("Tentando acesso direto com requests...")
|
| 296 |
|
| 297 |
try:
|
| 298 |
-
#
|
| 299 |
session = requests.Session()
|
|
|
|
| 300 |
|
| 301 |
-
#
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
| 303 |
headers_page = HEADERS.copy()
|
| 304 |
headers_page.pop("Content-Type", None)
|
| 305 |
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
# Tentar
|
| 315 |
api_response = session.post(
|
| 316 |
URL_API,
|
| 317 |
headers=HEADERS,
|
| 318 |
json=PAYLOAD,
|
| 319 |
-
timeout=30
|
|
|
|
| 320 |
)
|
| 321 |
|
| 322 |
logger.info(f"API Response: status {api_response.status_code}")
|
| 323 |
|
| 324 |
if api_response.status_code == 200:
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
"response_text": api_response.text[:500]
|
| 341 |
-
}
|
| 342 |
else:
|
| 343 |
return {
|
| 344 |
"success": False,
|
| 345 |
"method": "requests",
|
| 346 |
"status_code": api_response.status_code,
|
| 347 |
-
"error": f"Status
|
| 348 |
-
"response_text": api_response.text[:500]
|
| 349 |
}
|
| 350 |
|
| 351 |
except Exception as e:
|
|
@@ -357,99 +372,76 @@ def test_with_requests():
|
|
| 357 |
"traceback": traceback.format_exc()
|
| 358 |
}
|
| 359 |
|
| 360 |
-
def
|
| 361 |
-
"""
|
| 362 |
-
logger.info("Tentando acesso com Playwright
|
| 363 |
-
|
| 364 |
-
token = None
|
| 365 |
-
playwright = None
|
| 366 |
|
| 367 |
try:
|
| 368 |
with sync_playwright() as p:
|
| 369 |
-
#
|
| 370 |
browser = p.chromium.launch(
|
| 371 |
headless=True,
|
| 372 |
-
args=[
|
| 373 |
-
'--disable-blink-features=AutomationControlled',
|
| 374 |
-
'--disable-dev-shm-usage',
|
| 375 |
-
'--no-sandbox',
|
| 376 |
-
'--disable-setuid-sandbox',
|
| 377 |
-
'--disable-web-security',
|
| 378 |
-
'--disable-features=IsolateOrigins,site-per-process',
|
| 379 |
-
'--start-maximized'
|
| 380 |
-
]
|
| 381 |
)
|
| 382 |
|
| 383 |
context = browser.new_context(
|
| 384 |
viewport={'width': 1920, 'height': 1080},
|
| 385 |
-
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
|
| 386 |
-
locale='pt-BR',
|
| 387 |
-
timezone_id='America/Sao_Paulo',
|
| 388 |
-
permissions=['geolocation']
|
| 389 |
)
|
| 390 |
|
| 391 |
page = context.new_page()
|
| 392 |
|
| 393 |
-
#
|
| 394 |
-
stealth_sync(page)
|
| 395 |
-
|
| 396 |
-
# Navegar para página principal
|
| 397 |
-
logger.info("Navegando para página de busca...")
|
| 398 |
response = page.goto(
|
| 399 |
"https://jurisprudencia.stf.jus.br/pages/search",
|
| 400 |
-
wait_until='
|
| 401 |
timeout=30000
|
| 402 |
)
|
| 403 |
|
| 404 |
if not response:
|
| 405 |
-
raise Exception("Sem resposta
|
| 406 |
|
| 407 |
logger.info(f"Página carregada: status {response.status}")
|
| 408 |
|
| 409 |
-
# Aguardar um pouco
|
| 410 |
-
page.wait_for_timeout(
|
| 411 |
|
| 412 |
-
#
|
| 413 |
cookies = context.cookies()
|
|
|
|
| 414 |
for cookie in cookies:
|
| 415 |
if cookie.get('name') == 'aws-waf-token':
|
| 416 |
token = cookie.get('value')
|
| 417 |
-
|
| 418 |
|
| 419 |
-
|
| 420 |
-
# Tentar extrair do localStorage
|
| 421 |
-
token = page.evaluate("""
|
| 422 |
-
() => {
|
| 423 |
-
for(let i=0; i<localStorage.length; i++) {
|
| 424 |
-
let key = localStorage.key(i);
|
| 425 |
-
if(key.includes('waf') || key.includes('token')) {
|
| 426 |
-
return localStorage.getItem(key);
|
| 427 |
-
}
|
| 428 |
-
}
|
| 429 |
-
return null;
|
| 430 |
-
}
|
| 431 |
-
""")
|
| 432 |
-
if token:
|
| 433 |
-
logger.info(f"Token encontrado no localStorage: {token[:30]}...")
|
| 434 |
-
|
| 435 |
-
# Fazer requisição à API via JavaScript
|
| 436 |
-
logger.info("Executando requisição à API via JavaScript...")
|
| 437 |
api_result = page.evaluate("""
|
| 438 |
-
async (
|
| 439 |
try {
|
| 440 |
const response = await fetch('https://jurisprudencia.stf.jus.br/api/search/search', {
|
| 441 |
method: 'POST',
|
| 442 |
-
headers:
|
| 443 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
});
|
| 445 |
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
} catch (error) {
|
| 454 |
return {
|
| 455 |
success: false,
|
|
@@ -457,7 +449,7 @@ def test_with_playwright():
|
|
| 457 |
};
|
| 458 |
}
|
| 459 |
}
|
| 460 |
-
"""
|
| 461 |
|
| 462 |
browser.close()
|
| 463 |
|
|
@@ -465,7 +457,6 @@ def test_with_playwright():
|
|
| 465 |
return {
|
| 466 |
"success": True,
|
| 467 |
"method": "playwright",
|
| 468 |
-
"status_code": api_result.get('status'),
|
| 469 |
"token": token,
|
| 470 |
"data": api_result.get('data')
|
| 471 |
}
|
|
@@ -477,15 +468,6 @@ def test_with_playwright():
|
|
| 477 |
"token": token
|
| 478 |
}
|
| 479 |
|
| 480 |
-
except PlaywrightTimeoutError:
|
| 481 |
-
error_msg = "Timeout ao carregar página"
|
| 482 |
-
logger.error(error_msg)
|
| 483 |
-
return {
|
| 484 |
-
"success": False,
|
| 485 |
-
"method": "playwright",
|
| 486 |
-
"error": error_msg,
|
| 487 |
-
"traceback": traceback.format_exc()
|
| 488 |
-
}
|
| 489 |
except Exception as e:
|
| 490 |
logger.error(f"Erro no Playwright: {str(e)}")
|
| 491 |
return {
|
|
@@ -510,34 +492,28 @@ def test_bypass():
|
|
| 510 |
"attempts": []
|
| 511 |
}
|
| 512 |
|
| 513 |
-
# Tentar
|
| 514 |
requests_result = test_with_requests()
|
| 515 |
result["attempts"].append(requests_result)
|
| 516 |
|
| 517 |
# Se requests falhou, tentar com playwright
|
| 518 |
if not requests_result.get("success"):
|
| 519 |
logger.info("Requests falhou, tentando Playwright...")
|
| 520 |
-
time.sleep(
|
| 521 |
|
| 522 |
-
playwright_result =
|
| 523 |
result["attempts"].append(playwright_result)
|
| 524 |
|
| 525 |
if playwright_result.get("success"):
|
| 526 |
result["success"] = True
|
| 527 |
result["method"] = "playwright"
|
| 528 |
-
result["
|
| 529 |
result["data"] = playwright_result.get("data")
|
| 530 |
-
else:
|
| 531 |
-
result["success"] = True
|
| 532 |
-
result["method"] = "requests"
|
| 533 |
-
result["token"] = requests_result.get("token")
|
| 534 |
-
result["data"] = requests_result.get("data")
|
| 535 |
|
| 536 |
-
# Preparar resposta
|
| 537 |
response_data = {
|
| 538 |
"success": result["success"],
|
| 539 |
"timestamp": time.time(),
|
| 540 |
-
"method": result.get("method"),
|
| 541 |
"attempts": [
|
| 542 |
{
|
| 543 |
"method": a.get("method"),
|
|
@@ -549,50 +525,87 @@ def test_bypass():
|
|
| 549 |
]
|
| 550 |
}
|
| 551 |
|
| 552 |
-
if result.get("success")
|
| 553 |
-
response_data["data"] = result
|
| 554 |
-
response_data["token_preview"] = result.get("
|
| 555 |
-
|
| 556 |
-
if not result["success"]:
|
| 557 |
response_data["error"] = "Todas as tentativas falharam"
|
| 558 |
-
response_data["details"] =
|
| 559 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 560 |
|
| 561 |
return jsonify(response_data)
|
| 562 |
|
| 563 |
@app.route('/api/health', methods=['GET'])
|
| 564 |
def health():
|
| 565 |
"""Endpoint de health check"""
|
|
|
|
| 566 |
return jsonify({
|
| 567 |
"status": "healthy",
|
| 568 |
"timestamp": time.time(),
|
| 569 |
-
"
|
| 570 |
"python_version": sys.version
|
| 571 |
})
|
| 572 |
|
| 573 |
-
@app.route('/api/
|
| 574 |
-
def
|
| 575 |
-
"""
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 580 |
|
| 581 |
if __name__ == '__main__':
|
| 582 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
logger.info("Iniciando aplicação de bypass AWS WAF")
|
| 584 |
logger.info(f"Python version: {sys.version}")
|
| 585 |
|
| 586 |
-
#
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
except Exception as e:
|
| 593 |
-
logger.error(f"Erro ao iniciar Playwright: {str(e)}")
|
| 594 |
-
logger.error("Verifique se as dependências do sistema estão instaladas")
|
| 595 |
|
| 596 |
-
# Iniciar servidor
|
| 597 |
port = int(os.environ.get('PORT', 7860))
|
| 598 |
app.run(host='0.0.0.0', port=port, debug=False)
|
|
|
|
| 4 |
import time
|
| 5 |
import logging
|
| 6 |
import requests
|
| 7 |
+
import subprocess
|
| 8 |
from flask import Flask, request, jsonify, render_template_string
|
| 9 |
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
|
|
|
|
| 10 |
import traceback
|
| 11 |
+
import ssl
|
| 12 |
+
import certifi
|
| 13 |
|
| 14 |
# Configuração de logging
|
| 15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
|
|
| 17 |
|
| 18 |
app = Flask(__name__)
|
| 19 |
|
| 20 |
+
# Template HTML (mesmo do código anterior)
|
| 21 |
HTML_TEMPLATE = """
|
| 22 |
<!DOCTYPE html>
|
| 23 |
<html>
|
|
|
|
| 26 |
<meta charset="utf-8">
|
| 27 |
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 28 |
<style>
|
| 29 |
+
/* Mesmo CSS do código anterior */
|
| 30 |
body {
|
| 31 |
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
| 32 |
max-width: 1200px;
|
|
|
|
| 132 |
margin: 10px 0;
|
| 133 |
border-radius: 4px;
|
| 134 |
}
|
| 135 |
+
.warning {
|
| 136 |
+
color: #ff9800;
|
| 137 |
+
background: #fff3e0;
|
| 138 |
+
border-left: 4px solid #ff9800;
|
| 139 |
+
padding: 15px;
|
| 140 |
+
margin: 10px 0;
|
| 141 |
+
border-radius: 4px;
|
| 142 |
+
}
|
| 143 |
</style>
|
| 144 |
</head>
|
| 145 |
<body>
|
|
|
|
| 147 |
<h1>🛡️ Bypass AWS WAF - STF Jurisprudência</h1>
|
| 148 |
|
| 149 |
<div class="info-box">
|
| 150 |
+
<strong>📌 Sobre:</strong> Teste de bypass do AWS WAF usando Playwright para acessar a API de jurisprudência do STF.
|
| 151 |
<br>
|
| 152 |
<strong>🔗 API Alvo:</strong> https://jurisprudencia.stf.jus.br/api/search/search
|
| 153 |
</div>
|
|
|
|
| 214 |
let resultHtml = '<div class="success">✅ Teste executado com sucesso!</div>';
|
| 215 |
resultHtml += '<pre>' + JSON.stringify(data.data, null, 2) + '</pre>';
|
| 216 |
|
| 217 |
+
if (data.token_preview) {
|
| 218 |
resultHtml += '<div class="info-box"><strong>🔑 Token AWS WAF obtido:</strong><br>' +
|
| 219 |
+
'<code style="word-break: break-all;">' + data.token_preview + '</code></div>';
|
| 220 |
}
|
| 221 |
|
| 222 |
resultDiv.innerHTML = resultHtml;
|
|
|
|
| 224 |
failCount++;
|
| 225 |
document.getElementById('failCount').textContent = failCount;
|
| 226 |
|
| 227 |
+
let errorHtml = '<div class="error">❌ Falha no teste</div>';
|
| 228 |
+
|
| 229 |
+
if (data.attempts) {
|
| 230 |
+
data.attempts.forEach(attempt => {
|
| 231 |
+
errorHtml += `<div class="warning"><strong>Tentativa (${attempt.method}):</strong> ${attempt.error || 'Sem erro detalhado'}</div>`;
|
| 232 |
+
});
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
errorHtml += '<pre>' + JSON.stringify(data.details || data, null, 2) + '</pre>';
|
| 236 |
+
resultDiv.innerHTML = errorHtml;
|
| 237 |
}
|
| 238 |
} catch (error) {
|
| 239 |
failCount++;
|
|
|
|
| 250 |
</html>
|
| 251 |
"""
|
| 252 |
|
| 253 |
+
# Dados da requisição
|
| 254 |
URL_API = "https://jurisprudencia.stf.jus.br/api/search/search"
|
| 255 |
HEADERS = {
|
| 256 |
"Accept": "application/json, text/plain, */*",
|
| 257 |
"Content-Type": "application/json",
|
| 258 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
| 259 |
+
"Referer": "https://jurisprudencia.stf.jus.br/pages/search",
|
| 260 |
"Accept-Encoding": "gzip, deflate, br",
|
| 261 |
"Connection": "keep-alive",
|
| 262 |
"Origin": "https://jurisprudencia.stf.jus.br"
|
| 263 |
}
|
| 264 |
|
| 265 |
+
# Payload simplificado para teste
|
| 266 |
PAYLOAD = {
|
| 267 |
"query": {
|
| 268 |
+
"bool": {
|
| 269 |
+
"filter": [
|
| 270 |
+
{"term": {"base": "acordaos"}}
|
| 271 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
}
|
| 273 |
},
|
| 274 |
+
"_source": ["id", "titulo", "ementa_texto", "processo_numero"],
|
| 275 |
+
"size": 5,
|
| 276 |
"from": 0,
|
| 277 |
"sort": [{"_score": "desc"}]
|
| 278 |
}
|
| 279 |
|
| 280 |
+
def verify_playwright_dependencies():
|
| 281 |
+
"""Verifica e tenta instalar dependências do Playwright"""
|
| 282 |
+
try:
|
| 283 |
+
# Tentar importar para ver se já está funcionando
|
| 284 |
+
with sync_playwright() as p:
|
| 285 |
+
p.chromium.launch(headless=True).close()
|
| 286 |
+
return True
|
| 287 |
+
except Exception as e:
|
| 288 |
+
logger.warning(f"Playwright não está pronto: {e}")
|
| 289 |
+
|
| 290 |
+
# Tentar instalar dependências
|
| 291 |
+
try:
|
| 292 |
+
logger.info("Tentando instalar dependências do Playwright...")
|
| 293 |
+
subprocess.run(["python", "-m", "playwright", "install", "chromium"], check=True)
|
| 294 |
+
subprocess.run(["python", "-m", "playwright", "install-deps"], check=True)
|
| 295 |
+
logger.info("Dependências instaladas com sucesso")
|
| 296 |
+
return True
|
| 297 |
+
except Exception as install_error:
|
| 298 |
+
logger.error(f"Falha ao instalar dependências: {install_error}")
|
| 299 |
+
return False
|
| 300 |
|
| 301 |
def test_with_requests():
|
| 302 |
+
"""Testa acesso direto com requests (ignorando SSL)"""
|
| 303 |
+
logger.info("Tentando acesso direto com requests (SSL ignorado)...")
|
| 304 |
|
| 305 |
try:
|
| 306 |
+
# Configurar sessão ignorando verificação SSL
|
| 307 |
session = requests.Session()
|
| 308 |
+
session.verify = False # Ignorar SSL
|
| 309 |
|
| 310 |
+
# Suprimir warnings de SSL
|
| 311 |
+
import urllib3
|
| 312 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 313 |
+
|
| 314 |
+
# Headers sem Content-Type para página
|
| 315 |
headers_page = HEADERS.copy()
|
| 316 |
headers_page.pop("Content-Type", None)
|
| 317 |
|
| 318 |
+
# Tentar página principal
|
| 319 |
+
try:
|
| 320 |
+
page_response = session.get(
|
| 321 |
+
"https://jurisprudencia.stf.jus.br/pages/search",
|
| 322 |
+
headers=headers_page,
|
| 323 |
+
timeout=30,
|
| 324 |
+
verify=False
|
| 325 |
+
)
|
| 326 |
+
logger.info(f"Página principal: status {page_response.status_code}")
|
| 327 |
+
except Exception as page_error:
|
| 328 |
+
logger.warning(f"Erro ao acessar página principal: {page_error}")
|
| 329 |
|
| 330 |
+
# Tentar API diretamente
|
| 331 |
api_response = session.post(
|
| 332 |
URL_API,
|
| 333 |
headers=HEADERS,
|
| 334 |
json=PAYLOAD,
|
| 335 |
+
timeout=30,
|
| 336 |
+
verify=False
|
| 337 |
)
|
| 338 |
|
| 339 |
logger.info(f"API Response: status {api_response.status_code}")
|
| 340 |
|
| 341 |
if api_response.status_code == 200:
|
| 342 |
+
try:
|
| 343 |
+
data = api_response.json()
|
| 344 |
+
return {
|
| 345 |
+
"success": True,
|
| 346 |
+
"method": "requests",
|
| 347 |
+
"status_code": api_response.status_code,
|
| 348 |
+
"data": data
|
| 349 |
+
}
|
| 350 |
+
except:
|
| 351 |
+
return {
|
| 352 |
+
"success": True,
|
| 353 |
+
"method": "requests",
|
| 354 |
+
"status_code": api_response.status_code,
|
| 355 |
+
"data": {"text": api_response.text[:500]}
|
| 356 |
+
}
|
|
|
|
|
|
|
| 357 |
else:
|
| 358 |
return {
|
| 359 |
"success": False,
|
| 360 |
"method": "requests",
|
| 361 |
"status_code": api_response.status_code,
|
| 362 |
+
"error": f"Status {api_response.status_code}",
|
| 363 |
+
"response_text": api_response.text[:500] if api_response.text else ""
|
| 364 |
}
|
| 365 |
|
| 366 |
except Exception as e:
|
|
|
|
| 372 |
"traceback": traceback.format_exc()
|
| 373 |
}
|
| 374 |
|
| 375 |
+
def test_with_playwright_simple():
|
| 376 |
+
"""Versão simplificada do Playwright para teste"""
|
| 377 |
+
logger.info("Tentando acesso com Playwright...")
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
try:
|
| 380 |
with sync_playwright() as p:
|
| 381 |
+
# Configuração mínima
|
| 382 |
browser = p.chromium.launch(
|
| 383 |
headless=True,
|
| 384 |
+
args=['--no-sandbox']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
)
|
| 386 |
|
| 387 |
context = browser.new_context(
|
| 388 |
viewport={'width': 1920, 'height': 1080},
|
| 389 |
+
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
|
|
|
|
|
|
|
|
|
| 390 |
)
|
| 391 |
|
| 392 |
page = context.new_page()
|
| 393 |
|
| 394 |
+
# Navegar
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
response = page.goto(
|
| 396 |
"https://jurisprudencia.stf.jus.br/pages/search",
|
| 397 |
+
wait_until='domcontentloaded',
|
| 398 |
timeout=30000
|
| 399 |
)
|
| 400 |
|
| 401 |
if not response:
|
| 402 |
+
raise Exception("Sem resposta")
|
| 403 |
|
| 404 |
logger.info(f"Página carregada: status {response.status}")
|
| 405 |
|
| 406 |
+
# Aguardar um pouco
|
| 407 |
+
page.wait_for_timeout(3000)
|
| 408 |
|
| 409 |
+
# Tentar extrair token dos cookies
|
| 410 |
cookies = context.cookies()
|
| 411 |
+
token = None
|
| 412 |
for cookie in cookies:
|
| 413 |
if cookie.get('name') == 'aws-waf-token':
|
| 414 |
token = cookie.get('value')
|
| 415 |
+
break
|
| 416 |
|
| 417 |
+
# Fazer requisição à API via página
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
api_result = page.evaluate("""
|
| 419 |
+
async () => {
|
| 420 |
try {
|
| 421 |
const response = await fetch('https://jurisprudencia.stf.jus.br/api/search/search', {
|
| 422 |
method: 'POST',
|
| 423 |
+
headers: {
|
| 424 |
+
'Content-Type': 'application/json',
|
| 425 |
+
'Accept': 'application/json'
|
| 426 |
+
},
|
| 427 |
+
body: JSON.stringify({
|
| 428 |
+
query: {bool: {filter: [{term: {base: "acordaos"}}]}},
|
| 429 |
+
size: 5
|
| 430 |
+
})
|
| 431 |
});
|
| 432 |
|
| 433 |
+
if (response.ok) {
|
| 434 |
+
return {
|
| 435 |
+
success: true,
|
| 436 |
+
data: await response.json()
|
| 437 |
+
};
|
| 438 |
+
} else {
|
| 439 |
+
return {
|
| 440 |
+
success: false,
|
| 441 |
+
status: response.status,
|
| 442 |
+
statusText: response.statusText
|
| 443 |
+
};
|
| 444 |
+
}
|
| 445 |
} catch (error) {
|
| 446 |
return {
|
| 447 |
success: false,
|
|
|
|
| 449 |
};
|
| 450 |
}
|
| 451 |
}
|
| 452 |
+
""")
|
| 453 |
|
| 454 |
browser.close()
|
| 455 |
|
|
|
|
| 457 |
return {
|
| 458 |
"success": True,
|
| 459 |
"method": "playwright",
|
|
|
|
| 460 |
"token": token,
|
| 461 |
"data": api_result.get('data')
|
| 462 |
}
|
|
|
|
| 468 |
"token": token
|
| 469 |
}
|
| 470 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
except Exception as e:
|
| 472 |
logger.error(f"Erro no Playwright: {str(e)}")
|
| 473 |
return {
|
|
|
|
| 492 |
"attempts": []
|
| 493 |
}
|
| 494 |
|
| 495 |
+
# Tentar com requests (ignorando SSL)
|
| 496 |
requests_result = test_with_requests()
|
| 497 |
result["attempts"].append(requests_result)
|
| 498 |
|
| 499 |
# Se requests falhou, tentar com playwright
|
| 500 |
if not requests_result.get("success"):
|
| 501 |
logger.info("Requests falhou, tentando Playwright...")
|
| 502 |
+
time.sleep(1)
|
| 503 |
|
| 504 |
+
playwright_result = test_with_playwright_simple()
|
| 505 |
result["attempts"].append(playwright_result)
|
| 506 |
|
| 507 |
if playwright_result.get("success"):
|
| 508 |
result["success"] = True
|
| 509 |
result["method"] = "playwright"
|
| 510 |
+
result["token_preview"] = str(playwright_result.get("token", ""))[:50] + "..." if playwright_result.get("token") else None
|
| 511 |
result["data"] = playwright_result.get("data")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
|
| 513 |
+
# Preparar resposta simplificada
|
| 514 |
response_data = {
|
| 515 |
"success": result["success"],
|
| 516 |
"timestamp": time.time(),
|
|
|
|
| 517 |
"attempts": [
|
| 518 |
{
|
| 519 |
"method": a.get("method"),
|
|
|
|
| 525 |
]
|
| 526 |
}
|
| 527 |
|
| 528 |
+
if result.get("success"):
|
| 529 |
+
response_data["data"] = result.get("data")
|
| 530 |
+
response_data["token_preview"] = result.get("token_preview")
|
| 531 |
+
else:
|
|
|
|
| 532 |
response_data["error"] = "Todas as tentativas falharam"
|
| 533 |
+
response_data["details"] = [
|
| 534 |
+
{
|
| 535 |
+
"method": a["method"],
|
| 536 |
+
"error": a.get("error", "Erro desconhecido"),
|
| 537 |
+
"traceback": a.get("traceback", "") if a.get("traceback") else None
|
| 538 |
+
}
|
| 539 |
+
for a in result["attempts"]
|
| 540 |
+
]
|
| 541 |
|
| 542 |
return jsonify(response_data)
|
| 543 |
|
| 544 |
@app.route('/api/health', methods=['GET'])
|
| 545 |
def health():
|
| 546 |
"""Endpoint de health check"""
|
| 547 |
+
playwright_status = verify_playwright_dependencies()
|
| 548 |
return jsonify({
|
| 549 |
"status": "healthy",
|
| 550 |
"timestamp": time.time(),
|
| 551 |
+
"playwright_ready": playwright_status,
|
| 552 |
"python_version": sys.version
|
| 553 |
})
|
| 554 |
|
| 555 |
+
@app.route('/api/install-deps', methods=['POST'])
|
| 556 |
+
def install_deps():
|
| 557 |
+
"""Endpoint para instalar dependências manualmente"""
|
| 558 |
+
try:
|
| 559 |
+
result = subprocess.run(
|
| 560 |
+
["python", "-m", "playwright", "install", "chromium"],
|
| 561 |
+
capture_output=True,
|
| 562 |
+
text=True,
|
| 563 |
+
timeout=60
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
deps_result = subprocess.run(
|
| 567 |
+
["python", "-m", "playwright", "install-deps"],
|
| 568 |
+
capture_output=True,
|
| 569 |
+
text=True,
|
| 570 |
+
timeout=120
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
return jsonify({
|
| 574 |
+
"success": True,
|
| 575 |
+
"install_output": result.stdout,
|
| 576 |
+
"deps_output": deps_result.stdout,
|
| 577 |
+
"install_error": result.stderr if result.stderr else None,
|
| 578 |
+
"deps_error": deps_result.stderr if deps_result.stderr else None
|
| 579 |
+
})
|
| 580 |
+
except Exception as e:
|
| 581 |
+
return jsonify({
|
| 582 |
+
"success": False,
|
| 583 |
+
"error": str(e)
|
| 584 |
+
}), 500
|
| 585 |
|
| 586 |
if __name__ == '__main__':
|
| 587 |
+
# Configurar SSL
|
| 588 |
+
try:
|
| 589 |
+
import certifi
|
| 590 |
+
os.environ['SSL_CERT_FILE'] = certifi.where()
|
| 591 |
+
os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
|
| 592 |
+
except:
|
| 593 |
+
pass
|
| 594 |
+
|
| 595 |
+
# Suprimir warnings de SSL
|
| 596 |
+
import urllib3
|
| 597 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 598 |
+
|
| 599 |
logger.info("Iniciando aplicação de bypass AWS WAF")
|
| 600 |
logger.info(f"Python version: {sys.version}")
|
| 601 |
|
| 602 |
+
# Verificar Playwright
|
| 603 |
+
playwright_ready = verify_playwright_dependencies()
|
| 604 |
+
if playwright_ready:
|
| 605 |
+
logger.info("✅ Playwright pronto para uso")
|
| 606 |
+
else:
|
| 607 |
+
logger.warning("⚠️ Playwright pode não estar totalmente configurado")
|
|
|
|
|
|
|
|
|
|
| 608 |
|
| 609 |
+
# Iniciar servidor
|
| 610 |
port = int(os.environ.get('PORT', 7860))
|
| 611 |
app.run(host='0.0.0.0', port=port, debug=False)
|