caarleexx commited on
Commit
13362dd
·
verified ·
1 Parent(s): 27460b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +571 -660
app.py CHANGED
@@ -6,9 +6,11 @@ import time
6
  import logging
7
  import requests
8
  import urllib3
9
- from flask import Flask, request, jsonify, render_template_string
10
  from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
11
  import traceback
 
 
12
 
13
  # Suprimir warnings de SSL
14
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
@@ -20,509 +22,92 @@ logger = logging.getLogger(__name__)
20
  app = Flask(__name__)
21
 
22
  # ============================================
23
- # PAYLOAD COMPLETO (extraído do curl)
24
  # ============================================
25
- PAYLOAD_COMPLETO = {
26
  "query": {
27
  "function_score": {
28
  "functions": [
29
- {"exp": {"julgamento_data": {"origin": "now", "scale": "47450d", "offset": "1095d", "decay": 0.1}}},
30
- {"filter": {"term": {"orgao_julgador.keyword": "Tribunal Pleno"}}, "weight": 1.15},
31
- {"filter": {"term": {"is_repercussao_geral": True}}, "weight": 1.1}
32
  ],
33
  "query": {
34
  "bool": {
35
  "filter": [
36
  {"query_string": {
37
  "default_operator": "AND",
38
- "fields": [
39
- "processo_codigo_completo.plural",
40
- "acordao_ata.plural^3",
41
- "documental_acordao_mesmo_sentido_lista_texto.plural",
42
- "documental_doutrina_texto.plural",
43
- "documental_indexacao_texto.plural",
44
- "documental_jurisprudencia_citada_texto.plural",
45
- "documental_legislacao_citada_texto.plural",
46
- "documental_observacao_texto.plural",
47
- "documental_publicacao_lista_texto.plural",
48
- "documental_tese_tema_texto.plural^3",
49
- "documental_tese_texto.plural^3",
50
- "ementa_texto.plural^3",
51
- "ministro_facet.plural",
52
- "revisor_processo_nome.plural",
53
- "orgao_julgador.plural",
54
- "partes_lista_texto.plural",
55
- "procedencia_geografica_completo.plural",
56
- "processo_classe_processual_unificada_extenso.plural",
57
- "titulo.plural^6",
58
- "colac_numero.plural",
59
- "colac_pagina.plural",
60
- "decisao_texto.plural^2",
61
- "documental_decisao_mesmo_sentido_lista_texto.plural",
62
- "processo_precedente_texto.plural",
63
- "sumula_texto.plural^3",
64
- "ramo_direito.plural^1",
65
- "situacao_sumula.plural^1",
66
- "materia_noticia.plural^1",
67
- "titulo_noticia.plural^3",
68
- "resumo_noticia.plural^3",
69
- "conteudo_noticia.plural^1",
70
- "ramo_noticia.plural^1"
71
- ],
72
  "query": "*",
73
  "type": "cross_fields",
74
- "fuzziness": "AUTO:4,7",
75
- "analyzer": "legal_search_analyzer",
76
- "quote_analyzer": "legal_index_analyzer"
77
  }}
78
- ],
79
- "must": [],
80
- "should": [
81
- {
82
- "query_string": {
83
- "default_operator": "AND",
84
- "fields": [
85
- "acordao_ata.plural^3",
86
- "documental_doutrina_texto.plural",
87
- "documental_indexacao_texto.plural",
88
- "documental_jurisprudencia_citada_texto.plural",
89
- "documental_observacao_texto.plural",
90
- "documental_tese_tema_texto.plural^3",
91
- "documental_tese_texto.plural^3",
92
- "ementa_texto.plural^3",
93
- "titulo.plural^6",
94
- "decisao_texto.plural^2",
95
- "sumula_texto.plural^3",
96
- "ramo_direito.plural^1",
97
- "situacao_sumula.plural^1",
98
- "materia_noticia.plural^1",
99
- "titulo_noticia.plural^3",
100
- "resumo_noticia.plural^3",
101
- "conteudo_noticia.plural^1",
102
- "ramo_noticia.plural^1"
103
- ],
104
- "query": "*",
105
- "tie_breaker": 1,
106
- "fuzziness": "AUTO:4,7",
107
- "analyzer": "legal_search_analyzer",
108
- "quote_analyzer": "legal_index_analyzer"
109
- }
110
- },
111
- {
112
- "query_string": {
113
- "default_operator": "and",
114
- "type": "phrase",
115
- "tie_breaker": 1,
116
- "phrase_slop": 20,
117
- "fields": [
118
- "acordao_ata.plural^3",
119
- "documental_tese_tema_texto.plural^3",
120
- "documental_tese_texto.plural^3",
121
- "ementa_texto.plural^3",
122
- "decisao_texto.plural^2",
123
- "situacao_sumula.plural^1",
124
- "titulo_noticia.plural^3",
125
- "resumo_noticia.plural^3",
126
- "conteudo_noticia.plural^1"
127
- ],
128
- "query": "*",
129
- "fuzziness": "AUTO:4,7",
130
- "analyzer": "legal_search_analyzer",
131
- "quote_analyzer": "legal_index_analyzer"
132
- }
133
- },
134
- {
135
- "query_string": {
136
- "default_operator": "and",
137
- "type": "phrase",
138
- "tie_breaker": 1,
139
- "phrase_slop": 5,
140
- "fields": [
141
- "documental_acordao_mesmo_sentido_lista_texto.plural",
142
- "documental_doutrina_texto.plural",
143
- "documental_indexacao_texto.plural",
144
- "documental_jurisprudencia_citada_texto.plural",
145
- "documental_legislacao_citada_texto.plural",
146
- "documental_observacao_texto.plural",
147
- "partes_lista_texto.plural",
148
- "processo_precedente_texto.plural",
149
- "documental_decisao_mesmo_sentido_lista_texto.plural"
150
- ],
151
- "query": "*",
152
- "fuzziness": "AUTO:4,7",
153
- "analyzer": "legal_search_analyzer",
154
- "quote_analyzer": "legal_index_analyzer"
155
- }
156
- },
157
- {
158
- "query_string": {
159
- "default_operator": "and",
160
- "type": "phrase",
161
- "phrase_slop": 1,
162
- "fields": [
163
- "documental_publicacao_lista_texto.plural",
164
- "ministro_facet.plural",
165
- "revisor_processo_nome.plural",
166
- "orgao_julgador.plural",
167
- "ramo_direito.plural^1",
168
- "ramo_noticia.plural^1",
169
- "procedencia_geografica_completo.plural",
170
- "processo_classe_processual_unificada_extenso.plural",
171
- "titulo.plural^6",
172
- "colac_numero.plural",
173
- "colac_pagina.plural",
174
- "sumula_texto.plural^3"
175
- ],
176
- "query": "*",
177
- "fuzziness": "AUTO:4,7",
178
- "boost": 0,
179
- "analyzer": "legal_search_analyzer",
180
- "quote_analyzer": "legal_index_analyzer"
181
- }
182
- }
183
  ]
184
  }
185
  }
186
  }
187
  },
188
  "_source": [
189
- "base", "_id", "id", "dg_unique", "titulo", "ministro_facet",
190
- "procedencia_geografica_completo", "procedencia_geografica_pais_sigla",
191
- "procedencia_geografica_uf_sigla", "procedencia_geografica_uf_extenso",
192
- "processo_codigo_completo", "processo_classe_processual_unificada_extenso",
193
- "processo_classe_processual_unificada_classe_sigla",
194
- "processo_classe_processual_unificada_incidente_sigla", "processo_numero",
195
- "julgamento_data", "publicacao_data", "is_decisao_presidencia",
196
- "relator_processo_nome", "presidente_nome", "relator_decisao_nome",
197
- "acordao_ata", "decisao_texto", "partes_lista_texto",
198
- "acompanhamento_processual_url", "dje_url",
199
- "documental_publicacao_lista_texto", "documental_decisao_mesmo_sentido_lista_texto",
200
- "documental_decisao_mesmo_sentido_lista_html",
201
- "documental_decisao_mesmo_sentido_is_secundario",
202
- "documental_legislacao_citada_texto", "documental_indexacao_texto",
203
- "documental_observacao_texto", "documental_observacao_html",
204
- "documental_doutrina_texto", "externo_seq_objeto_incidente",
205
- "dg_atualizado_em", "dg_unique", "volume_informativo", "ramo_noticia",
206
- "materia_noticia", "titulo_noticia", "resumo_noticia", "conteudo_noticia",
207
- "is_covid", "tipo_julgamento", "acompanhamento_processual_url",
208
- "informativo_url", "pesquisa_url", "audio_url", "video_url",
209
- "numero_noticias_url", "numero_noticias_processo", "informativo_url",
210
- "periodo_inicio_data", "periodo_fim_data", "processo_lista_texto",
211
- "sumula_numero", "orgao_julgador", "is_vinculante", "sumula_texto",
212
- "situacao_sumula", "ramo_direito", "aprovacao_url",
213
- "processo_precedente_texto", "processo_precedente_html",
214
- "processo_classe_processual_unificada_sigla", "is_questao_ordem",
215
- "is_repercussao_geral_admissibilidade", "is_repercussao_geral_merito",
216
- "is_repercussao_geral_recurso_interno", "is_repercussao_geral",
217
- "is_processo_antigo", "is_colac", "colac_numero", "colac_pagina",
218
- "revisor_processo_nome", "relator_acordao_nome",
219
- "julgamento_is_sessao_virtual", "republicacao_data", "ementa_texto",
220
- "inteiro_teor_url", "documental_acordao_mesmo_sentido_lista_texto",
221
- "documental_acordao_mesmo_sentido_lista_html",
222
- "documental_acordao_mesmo_sentido_is_secundario",
223
- "documental_jurisprudencia_citada_texto", "documental_assunto_texto",
224
- "documental_tese_tipo", "documental_tese_texto", "documental_tese_tema_texto",
225
- "old_seq_colac", "old_seq_repercussao_geral", "old_seq_sjur", "ods_onu"
226
  ],
227
  "aggs": {
228
  "base_agg": {
229
  "filters": {
230
  "filters": {
231
- "acordaos": {"match": {"base": "acordaos"}},
232
- "sumulas": {"match": {"base": "sumulas"}},
233
- "decisoes": {"match": {"base": "decisoes"}},
234
- "informativos": {"match": {"base": "novo_informativo"}}
235
- }
236
- }
237
- },
238
- "is_repercussao_geral_agg": {
239
- "filters": {
240
- "filters": {
241
- "true": {
242
- "bool": {
243
- "must": [
244
- {"match": {"is_repercussao_geral": True}},
245
- {"term": {"base": "acordaos"}}
246
- ]
247
- }
248
- },
249
- "false": {
250
- "bool": {
251
- "must": [
252
- {"match": {"is_repercussao_geral": False}},
253
- {"term": {"base": "acordaos"}}
254
- ]
255
- }
256
- }
257
  }
258
  }
259
- },
260
- "is_repercussao_geral_admissibilidade_agg": {
261
- "filters": {
262
- "filters": {
263
- "true": {"match": {"is_repercussao_geral_admissibilidade": True}},
264
- "false": {"match": {"is_repercussao_geral_admissibilidade": False}}
265
- }
266
- }
267
- },
268
- "is_repercussao_geral_merito_agg": {
269
- "filters": {
270
- "filters": {
271
- "true": {"match": {"is_repercussao_geral_merito": True}},
272
- "false": {"match": {"is_repercussao_geral_merito": False}}
273
- }
274
- }
275
- },
276
- "is_repercussao_geral_recurso_interno_agg": {
277
- "filters": {
278
- "filters": {
279
- "true": {"match": {"is_repercussao_geral_recurso_interno": True}},
280
- "false": {"match": {"is_repercussao_geral_recurso_interno": False}}
281
- }
282
- }
283
- },
284
- "is_questao_ordem_agg": {
285
- "filters": {
286
- "filters": {
287
- "true": {"match": {"is_questao_ordem": True}},
288
- "false": {"match": {"is_questao_ordem": False}}
289
- }
290
- }
291
- },
292
- "is_colac_agg": {
293
- "filters": {
294
- "filters": {
295
- "true": {"match": {"is_colac": True}},
296
- "false": {"match": {"is_colac": False}}
297
- }
298
- }
299
- },
300
- "orgao_julgador_agg": {
301
- "aggs": {
302
- "orgao_julgador_agg": {
303
- "terms": {"field": "orgao_julgador.keyword", "size": 200, "execution_hint": "map"}
304
- }
305
- },
306
- "filter": {"bool": {"must": [{"term": {"base": "acordaos"}}]}}
307
- },
308
- "ministro_facet_agg": {
309
- "aggs": {
310
- "ministro_facet_agg": {
311
- "terms": {"field": "ministro_facet.keyword", "size": 200, "execution_hint": "map"}
312
- }
313
- },
314
- "filter": {"bool": {"must": [{"term": {"base": "acordaos"}}]}}
315
- },
316
- "processo_classe_processual_unificada_classe_sigla_agg": {
317
- "aggs": {
318
- "processo_classe_processual_unificada_classe_sigla_agg": {
319
- "terms": {"field": "processo_classe_processual_unificada_classe_sigla.keyword", "size": 200, "execution_hint": "map"}
320
- }
321
- },
322
- "filter": {"bool": {"must": [{"term": {"base": "acordaos"}}]}}
323
- },
324
- "procedencia_geografica_uf_sigla_agg": {
325
- "aggs": {
326
- "procedencia_geografica_uf_sigla_agg": {
327
- "terms": {"field": "procedencia_geografica_uf_sigla", "size": 200, "execution_hint": "map"}
328
- }
329
- },
330
- "filter": {"bool": {"must": [{"term": {"base": "acordaos"}}]}}
331
  }
332
  },
333
  "size": 250,
334
  "from": 0,
335
- "post_filter": {
336
- "bool": {
337
- "must": [{"term": {"base": "acordaos"}}],
338
- "should": []
339
- }
340
- },
341
- "sort": [{"_score": "desc"}],
342
- "highlight": {
343
- "highlight_query": {
344
- "bool": {
345
- "filter": [
346
- {"query_string": {
347
- "default_operator": "AND",
348
- "fields": [
349
- "processo_codigo_completo.plural",
350
- "acordao_ata.plural^3",
351
- "documental_acordao_mesmo_sentido_lista_texto.plural",
352
- "documental_doutrina_texto.plural",
353
- "documental_indexacao_texto.plural",
354
- "documental_jurisprudencia_citada_texto.plural",
355
- "documental_legislacao_citada_texto.plural",
356
- "documental_observacao_texto.plural",
357
- "documental_publicacao_lista_texto.plural",
358
- "documental_tese_tema_texto.plural^3",
359
- "documental_tese_texto.plural^3",
360
- "ementa_texto.plural^3",
361
- "ministro_facet.plural",
362
- "revisor_processo_nome.plural",
363
- "orgao_julgador.plural",
364
- "partes_lista_texto.plural",
365
- "procedencia_geografica_completo.plural",
366
- "processo_classe_processual_unificada_extenso.plural",
367
- "titulo.plural^6",
368
- "colac_numero.plural",
369
- "colac_pagina.plural",
370
- "decisao_texto.plural^2",
371
- "documental_decisao_mesmo_sentido_lista_texto.plural",
372
- "processo_precedente_texto.plural",
373
- "sumula_texto.plural^3",
374
- "ramo_direito.plural^1",
375
- "situacao_sumula.plural^1",
376
- "materia_noticia.plural^1",
377
- "titulo_noticia.plural^3",
378
- "resumo_noticia.plural^3",
379
- "conteudo_noticia.plural^1",
380
- "ramo_noticia.plural^1"
381
- ],
382
- "query": "*",
383
- "type": "cross_fields",
384
- "fuzziness": "AUTO:4,7",
385
- "analyzer": "legal_search_analyzer",
386
- "quote_analyzer": "legal_index_analyzer"
387
- }}
388
- ],
389
- "must": [],
390
- "should": [
391
- {
392
- "query_string": {
393
- "default_operator": "AND",
394
- "fields": [
395
- "acordao_ata.plural^3",
396
- "documental_doutrina_texto.plural",
397
- "documental_indexacao_texto.plural",
398
- "documental_jurisprudencia_citada_texto.plural",
399
- "documental_observacao_texto.plural",
400
- "documental_tese_tema_texto.plural^3",
401
- "documental_tese_texto.plural^3",
402
- "ementa_texto.plural^3",
403
- "titulo.plural^6",
404
- "decisao_texto.plural^2",
405
- "sumula_texto.plural^3",
406
- "ramo_direito.plural^1",
407
- "situacao_sumula.plural^1",
408
- "materia_noticia.plural^1",
409
- "titulo_noticia.plural^3",
410
- "resumo_noticia.plural^3",
411
- "conteudo_noticia.plural^1",
412
- "ramo_noticia.plural^1"
413
- ],
414
- "query": "*",
415
- "tie_breaker": 1,
416
- "fuzziness": "AUTO:4,7",
417
- "analyzer": "legal_search_analyzer",
418
- "quote_analyzer": "legal_index_analyzer"
419
- }
420
- },
421
- {
422
- "query_string": {
423
- "default_operator": "and",
424
- "type": "phrase",
425
- "tie_breaker": 1,
426
- "phrase_slop": 20,
427
- "fields": [
428
- "acordao_ata.plural^3",
429
- "documental_tese_tema_texto.plural^3",
430
- "documental_tese_texto.plural^3",
431
- "ementa_texto.plural^3",
432
- "decisao_texto.plural^2",
433
- "situacao_sumula.plural^1",
434
- "titulo_noticia.plural^3",
435
- "resumo_noticia.plural^3",
436
- "conteudo_noticia.plural^1"
437
- ],
438
- "query": "*",
439
- "fuzziness": "AUTO:4,7",
440
- "analyzer": "legal_search_analyzer",
441
- "quote_analyzer": "legal_index_analyzer"
442
- }
443
- },
444
- {
445
- "query_string": {
446
- "default_operator": "and",
447
- "type": "phrase",
448
- "tie_breaker": 1,
449
- "phrase_slop": 5,
450
- "fields": [
451
- "documental_acordao_mesmo_sentido_lista_texto.plural",
452
- "documental_doutrina_texto.plural",
453
- "documental_indexacao_texto.plural",
454
- "documental_jurisprudencia_citada_texto.plural",
455
- "documental_legislacao_citada_texto.plural",
456
- "documental_observacao_texto.plural",
457
- "partes_lista_texto.plural",
458
- "processo_precedente_texto.plural",
459
- "documental_decisao_mesmo_sentido_lista_texto.plural"
460
- ],
461
- "query": "*",
462
- "fuzziness": "AUTO:4,7",
463
- "analyzer": "legal_search_analyzer",
464
- "quote_analyzer": "legal_index_analyzer"
465
- }
466
- },
467
- {
468
- "query_string": {
469
- "default_operator": "and",
470
- "type": "phrase",
471
- "phrase_slop": 1,
472
- "fields": [
473
- "documental_publicacao_lista_texto.plural",
474
- "ministro_facet.plural",
475
- "revisor_processo_nome.plural",
476
- "orgao_julgador.plural",
477
- "ramo_direito.plural^1",
478
- "ramo_noticia.plural^1",
479
- "procedencia_geografica_completo.plural",
480
- "processo_classe_processual_unificada_extenso.plural",
481
- "titulo.plural^6",
482
- "colac_numero.plural",
483
- "colac_pagina.plural",
484
- "sumula_texto.plural^3"
485
- ],
486
- "query": "*",
487
- "fuzziness": "AUTO:4,7",
488
- "boost": 0,
489
- "analyzer": "legal_search_analyzer",
490
- "quote_analyzer": "legal_index_analyzer"
491
- }
492
- }
493
- ]
494
- }
495
- },
496
- "number_of_fragments": 64,
497
- "fragment_size": 300,
498
- "order": "score",
499
- "pre_tags": ["<em>"],
500
- "post_tags": ["</em>"],
501
- "fields": {
502
- "ementa_texto": {"fragment_size": 24000, "matched_fields": ["ementa_texto.plural"], "type": "fvh"},
503
- "sumula_texto": {"number_of_fragments": 0, "matched_fields": ["sumula_texto.plural"], "type": "fvh"},
504
- "materia_noticia": {"matched_fields": ["materia_noticia.plural"], "type": "fvh"},
505
- "titulo_noticia": {"matched_fields": ["titulo_noticia.plural"], "type": "fvh"},
506
- "resumo_noticia": {"fragment_size": 5000, "matched_fields": ["resumo_noticia.plural"], "type": "fvh"},
507
- "conteudo_noticia": {"fragment_size": 50000, "matched_fields": ["conteudo_noticia.plural"], "type": "fvh"},
508
- "acordao_ata": {"fragment_size": 600, "matched_fields": ["acordao_ata.plural"], "type": "fvh"},
509
- "decisao_texto": {"fragment_size": 1200, "matched_fields": ["decisao_texto.plural"], "type": "fvh"},
510
- "documental_tese_texto": {"fragment_size": 2000, "matched_fields": ["documental_tese_texto.plural"], "type": "fvh"},
511
- "documental_tese_tema_texto": {"fragment_size": 2000, "matched_fields": ["documental_tese_tema_texto.plural"], "type": "fvh"},
512
- "documental_observacao_texto": {"matched_fields": ["documental_observacao_texto.plural"], "type": "fvh"},
513
- "documental_indexacao_texto": {"matched_fields": ["documental_indexacao_texto.plural"], "type": "fvh"},
514
- "documental_legislacao_citada_texto": {"matched_fields": ["documental_legislacao_citada_texto.plural"], "type": "fvh"},
515
- "documental_jurisprudencia_citada_texto": {"matched_fields": ["documental_jurisprudencia_citada_texto.plural"], "type": "fvh"},
516
- "documental_doutrina_texto": {"matched_fields": ["documental_doutrina_texto.plural"], "type": "fvh"},
517
- "partes_lista_texto": {"matched_fields": ["partes_lista_texto.plural"], "type": "fvh"},
518
- "documental_publicacao_lista_texto": {"matched_fields": ["documental_publicacao_lista_texto.plural"], "type": "fvh"},
519
- "documental_acordao_mesmo_sentido_lista_texto": {"matched_fields": ["documental_acordao_mesmo_sentido_lista_texto.plural"], "type": "fvh"},
520
- "documental_decisao_mesmo_sentido_lista_texto": {"matched_fields": ["documental_decisao_mesmo_sentido_lista_texto.plural"], "type": "fvh"},
521
- "processo_precedente_texto": {"matched_fields": ["processo_precedente_texto.plural"], "type": "fvh"},
522
- "procedencia_geografica_completo": {"matched_fields": ["procedencia_geografica_completo.plural"], "type": "fvh"}
523
  }
524
  },
525
- "track_total_hits": True
 
526
  }
527
 
528
  # Constantes da API
@@ -530,178 +115,516 @@ URL_API = "https://jurisprudencia.stf.jus.br/api/search/search"
530
  HEADERS = {
531
  "Accept": "application/json, text/plain, */*",
532
  "Content-Type": "application/json",
533
- "User-Agent": "Mozilla/5.0 (Linux; Android 10; Pixel 4a Build/QD4A.200805.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/129.0.6668.71 Mobile Safari/537.36",
534
- "Referer": "https://jurisprudencia.stf.jus.br/pages/search?base=acordaos&pesquisa_inteiro_teor=false&sinonimo=true&plural=true&radicais=false&buscaExata=true&page=1&pageSize=250&queryString=*&sort=_score&sortBy=desc&isAdvanced=true",
535
- "Accept-Encoding": "gzip, deflate, br",
536
- "Connection": "keep-alive",
537
  "Origin": "https://jurisprudencia.stf.jus.br"
538
  }
539
 
540
- # Template HTML (mantido igual ao anterior)
 
 
 
 
 
 
541
  HTML_TEMPLATE = """
542
  <!DOCTYPE html>
543
  <html>
544
  <head>
545
- <title>Bypass AWS WAF - STF Jurisprudência</title>
546
  <meta charset="utf-8">
547
  <meta name="viewport" content="width=device-width, initial-scale=1">
548
  <style>
549
- /* Mesmo CSS anterior */
550
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
551
- .container { background: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
552
- h1 { color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }
553
- .info-box { background: #e3f2fd; border-left: 4px solid #2196F3; padding: 15px; margin: 20px 0; border-radius: 4px; }
554
- button { background: #4CAF50; color: white; border: none; padding: 12px 30px; font-size: 16px; border-radius: 5px; cursor: pointer; transition: background 0.3s; }
555
- button:hover { background: #45a049; }
556
- button:disabled { background: #cccccc; cursor: not-allowed; }
557
- pre { background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 15px; overflow: auto; max-height: 500px; font-size: 12px; }
558
- .loading { display: inline-block; width: 20px; height: 20px; border: 3px solid #f3f3f3; border-top: 3px solid #4CAF50; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 10px; vertical-align: middle; }
 
 
 
 
 
 
 
 
559
  @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
560
- .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0; }
561
- .stat-card { background: white; border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; text-align: center; }
562
- .stat-value { font-size: 24px; font-weight: bold; color: #2196F3; }
563
- .stat-label { color: #666; font-size: 14px; margin-top: 5px; }
564
- .error { color: #f44336; background: #ffebee; border-left: 4px solid #f44336; padding: 15px; margin: 10px 0; border-radius: 4px; }
565
- .success { color: #4CAF50; background: #e8f5e8; border-left: 4px solid #4CAF50; padding: 15px; margin: 10px 0; border-radius: 4px; }
566
- .warning { color: #ff9800; background: #fff3e0; border-left: 4px solid #ff9800; padding: 15px; margin: 10px 0; border-radius: 4px; }
 
 
 
 
 
 
567
  </style>
568
  </head>
569
  <body>
570
  <div class="container">
571
- <h1>🛡️ Bypass AWS WAF - STF Jurisprudência</h1>
 
572
  <div class="info-box">
573
- <strong>📌 Sobre:</strong> Teste de bypass do AWS WAF usando Playwright para acessar a API de jurisprudência do STF.<br>
574
- <strong>🔗 API Alvo:</strong> https://jurisprudencia.stf.jus.br/api/search/search
 
 
575
  </div>
576
- <div class="stats">
577
- <div class="stat-card"><div class="stat-value" id="requestsCount">0</div><div class="stat-label">Total de Requisições</div></div>
 
578
  <div class="stat-card"><div class="stat-value" id="successCount">0</div><div class="stat-label">Sucessos</div></div>
579
  <div class="stat-card"><div class="stat-value" id="failCount">0</div><div class="stat-label">Falhas</div></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  </div>
581
- <div style="margin: 20px 0;">
 
582
  <button id="testBtn" onclick="runTest()">
583
  <span class="loading" id="loading" style="display: none;"></span>
584
- <span id="btnText">🚀 Executar Teste de Bypass</span>
 
 
 
 
 
 
585
  </button>
586
  </div>
587
- <div id="result" style="margin-top: 20px;"></div>
 
 
 
 
 
 
588
  </div>
589
 
590
  <script>
591
- let requestsCount = 0, successCount = 0, failCount = 0;
 
 
 
592
  async function runTest() {
593
  const btn = document.getElementById('testBtn');
594
  const loading = document.getElementById('loading');
595
- const btnText = document.getElementById('btnText');
596
  const resultDiv = document.getElementById('result');
 
 
 
 
597
  btn.disabled = true;
598
  loading.style.display = 'inline-block';
599
- btnText.textContent = ' Executando teste...';
600
- resultDiv.innerHTML = '<div class="info-box">⏳ Aguardando resposta do servidor...</div>';
601
  try {
602
- const response = await fetch('/api/test-bypass', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
 
 
 
 
 
603
  const data = await response.json();
604
  requestsCount++;
605
  document.getElementById('requestsCount').textContent = requestsCount;
 
606
  if (data.success) {
607
  successCount++;
608
  document.getElementById('successCount').textContent = successCount;
609
- let resultHtml = '<div class="success">✅ Teste executado com sucesso!</div>';
610
- resultHtml += '<pre>' + JSON.stringify(data.data, null, 2) + '</pre>';
611
- if (data.token_preview) {
612
- resultHtml += '<div class="info-box"><strong>🔑 Token AWS WAF obtido:</strong><br>' +
613
- '<code style="word-break: break-all;">' + data.token_preview + '</code></div>';
 
 
 
614
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615
  resultDiv.innerHTML = resultHtml;
616
  } else {
617
  failCount++;
618
  document.getElementById('failCount').textContent = failCount;
619
- let errorHtml = '<div class="error">❌ Falha no teste</div>';
 
620
  if (data.attempts) {
621
  data.attempts.forEach(attempt => {
622
- errorHtml += `<div class="warning"><strong>Tentativa (${attempt.method}):</strong> ${attempt.error || 'Sem erro detalhado'}</div>`;
623
  });
624
  }
625
- errorHtml += '<pre>' + JSON.stringify(data.details || data, null, 2) + '</pre>';
626
  resultDiv.innerHTML = errorHtml;
627
  }
628
  } catch (error) {
629
  failCount++;
630
  document.getElementById('failCount').textContent = failCount;
631
- resultDiv.innerHTML = '<div class="error">❌ Erro na requisição: ' + error.message + '</div>';
632
  } finally {
633
  btn.disabled = false;
634
  loading.style.display = 'none';
635
- btnText.textContent = '🚀 Executar Teste de Bypass';
636
  }
637
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  </script>
639
  </body>
640
  </html>
641
  """
642
 
643
- # ------------------------------------------------------------
644
  # Funções auxiliares
645
- # ------------------------------------------------------------
646
- def test_with_requests():
647
- """Testa acesso direto com requests (ignorando SSL)"""
648
- logger.info("Tentando acesso direto com requests (SSL ignorado)...")
 
 
 
 
 
 
 
 
649
  try:
650
- session = requests.Session()
651
- session.verify = False
652
- headers_page = HEADERS.copy()
653
- headers_page.pop("Content-Type", None)
654
- try:
655
- page_response = session.get(
656
- "https://jurisprudencia.stf.jus.br/pages/search",
657
- headers=headers_page,
658
- timeout=30,
659
- verify=False
660
  )
661
- logger.info(f"Página principal: status {page_response.status_code}")
662
- except Exception as page_error:
663
- logger.warning(f"Erro ao acessar página principal: {page_error}")
664
- api_response = session.post(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665
  URL_API,
666
- headers=HEADERS,
667
- json=PAYLOAD_COMPLETO, # <-- usando o payload completo
668
- timeout=30,
669
- verify=False
670
  )
671
- logger.info(f"API Response: status {api_response.status_code}")
672
- if api_response.status_code == 200:
673
- try:
674
- data = api_response.json()
675
- return {"success": True, "method": "requests", "status_code": api_response.status_code, "data": data}
676
- except:
677
- return {"success": True, "method": "requests", "status_code": api_response.status_code, "data": {"text": api_response.text[:500]}}
678
  else:
679
- return {"success": False, "method": "requests", "status_code": api_response.status_code, "error": f"Status {api_response.status_code}", "response_text": api_response.text[:500] if api_response.text else ""}
 
680
  except Exception as e:
681
- logger.error(f"Erro no requests: {str(e)}")
682
- return {"success": False, "method": "requests", "error": str(e), "traceback": traceback.format_exc()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
683
 
684
- def test_with_playwright_simple():
685
- """Versão simplificada do Playwright para teste"""
686
  logger.info("Tentando acesso com Playwright...")
 
687
  try:
688
  with sync_playwright() as p:
689
  browser = p.chromium.launch(headless=True, args=['--no-sandbox'])
690
- context = browser.new_context(viewport={'width': 1920, 'height': 1080},
691
- user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
 
 
692
  page = context.new_page()
693
- response = page.goto("https://jurisprudencia.stf.jus.br/pages/search", wait_until='domcontentloaded', timeout=30000)
694
- if not response:
695
- raise Exception("Sem resposta")
696
- logger.info(f"Página carregada: status {response.status}")
697
  page.wait_for_timeout(3000)
 
698
  cookies = context.cookies()
699
  token = None
700
  for cookie in cookies:
701
  if cookie.get('name') == 'aws-waf-token':
702
  token = cookie.get('value')
703
  break
704
- # Fazer requisição à API via página (usando o payload completo)
 
705
  api_result = page.evaluate("""
706
  async (payload) => {
707
  try {
@@ -713,124 +636,105 @@ def test_with_playwright_simple():
713
  },
714
  body: JSON.stringify(payload)
715
  });
 
716
  if (response.ok) {
717
  return { success: true, data: await response.json() };
718
  } else {
719
- return { success: false, status: response.status, statusText: response.statusText };
720
  }
721
  } catch (error) {
722
  return { success: false, error: error.toString() };
723
  }
724
  }
725
- """, PAYLOAD_COMPLETO)
 
726
  browser.close()
 
727
  if api_result.get('success'):
728
- return {"success": True, "method": "playwright", "token": token, "data": api_result.get('data')}
 
 
 
 
 
 
 
 
 
 
 
729
  else:
730
- return {"success": False, "method": "playwright", "error": api_result.get('error', 'Falha desconhecida'), "token": token}
 
 
 
 
 
 
731
  except Exception as e:
732
  logger.error(f"Erro no Playwright: {str(e)}")
733
- return {"success": False, "method": "playwright", "error": str(e), "traceback": traceback.format_exc()}
 
 
 
 
 
734
 
735
- def verify_playwright_dependencies():
736
- """Verifica se Playwright está funcionando"""
 
 
737
  try:
738
  with sync_playwright() as p:
739
  p.chromium.launch(headless=True).close()
740
- return True
741
  except:
742
- return False
743
-
744
- # ------------------------------------------------------------
745
- # Rotas da aplicação
746
- # ------------------------------------------------------------
747
- @app.route('/')
748
- def index():
749
- return render_template_string(HTML_TEMPLATE)
750
-
751
- @app.route('/api/test-bypass', methods=['POST'])
752
- def test_bypass():
753
- logger.info("Requisição de teste recebida")
754
- result = {"success": False, "attempts": []}
755
- # Tentar requests
756
- requests_result = test_with_requests()
757
- result["attempts"].append(requests_result)
758
- if not requests_result.get("success"):
759
- logger.info("Requests falhou, tentando Playwright...")
760
- time.sleep(1)
761
- playwright_result = test_with_playwright_simple()
762
- result["attempts"].append(playwright_result)
763
- if playwright_result.get("success"):
764
- result["success"] = True
765
- result["method"] = "playwright"
766
- result["token_preview"] = str(playwright_result.get("token", ""))[:50] + "..." if playwright_result.get("token") else None
767
- result["data"] = playwright_result.get("data")
768
- else:
769
- result["success"] = True
770
- result["method"] = "requests"
771
- result["data"] = requests_result.get("data")
772
- # Preparar resposta
773
- response_data = {
774
- "success": result["success"],
775
- "timestamp": time.time(),
776
- "attempts": [
777
- {"method": a.get("method"), "success": a.get("success", False),
778
- "status_code": a.get("status_code"), "error": a.get("error") if not a.get("success") else None}
779
- for a in result["attempts"]
780
- ]
781
- }
782
- if result.get("success"):
783
- response_data["data"] = result.get("data")
784
- response_data["token_preview"] = result.get("token_preview")
785
- else:
786
- response_data["error"] = "Todas as tentativas falharam"
787
- response_data["details"] = [
788
- {"method": a["method"], "error": a.get("error", "Erro desconhecido")}
789
- for a in result["attempts"]
790
- ]
791
- return jsonify(response_data)
792
-
793
- @app.route('/api/search', methods=['POST'])
794
- def search_with_token():
795
- """
796
- Endpoint para realizar buscas usando um token já obtido.
797
- Espera um JSON com:
798
- - token: string (obrigatório)
799
- - payload: dict (opcional, se não fornecido usa o payload completo)
800
- Retorna o resultado da API.
801
- """
802
- data = request.json
803
- if not data or 'token' not in data:
804
- return jsonify({"error": "Token não fornecido"}), 400
805
- token = data['token']
806
- payload = data.get('payload', PAYLOAD_COMPLETO)
807
- headers = HEADERS.copy()
808
- headers['Cookie'] = f'aws-waf-token={token}'
809
- try:
810
- response = requests.post(
811
- URL_API,
812
- headers=headers,
813
- json=payload,
814
- verify=False,
815
- timeout=30
816
- )
817
- if response.status_code == 200:
818
- return jsonify({"status": "ok", "data": response.json()})
819
- else:
820
- return jsonify({"status": "error", "code": response.status_code, "text": response.text[:500]}), response.status_code
821
- except Exception as e:
822
- return jsonify({"error": str(e)}), 500
823
-
824
- @app.route('/api/health', methods=['GET'])
825
- def health():
826
- playwright_status = verify_playwright_dependencies()
827
  return jsonify({
828
  "status": "healthy",
829
  "timestamp": time.time(),
830
  "playwright_ready": playwright_status,
 
 
 
831
  "python_version": sys.version
832
  })
833
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
834
  if __name__ == '__main__':
835
  # Configurar SSL
836
  try:
@@ -839,13 +743,20 @@ if __name__ == '__main__':
839
  os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
840
  except:
841
  pass
842
- logger.info("Iniciando aplicação de bypass AWS WAF com payload completo")
843
- logger.info(f"Python version: {sys.version}")
844
- playwright_ready = verify_playwright_dependencies()
845
- if playwright_ready:
 
 
 
 
 
 
 
846
  logger.info("✅ Playwright pronto para uso")
847
- else:
848
- logger.warning("⚠️ Playwright pode não estar totalmente configurado")
 
849
  port = int(os.environ.get('PORT', 7860))
850
  app.run(host='0.0.0.0', port=port, debug=False)
851
-
 
6
  import logging
7
  import requests
8
  import urllib3
9
+ from flask import Flask, request, jsonify, render_template_string, send_file
10
  from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
11
  import traceback
12
+ import io
13
+ from datetime import datetime
14
 
15
  # Suprimir warnings de SSL
16
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
 
22
  app = Flask(__name__)
23
 
24
  # ============================================
25
+ # PAYLOAD OTIMIZADO - Apenas campos necessários
26
  # ============================================
27
+ PAYLOAD_OTIMIZADO = {
28
  "query": {
29
  "function_score": {
30
  "functions": [
31
+ {"exp": {"julgamento_data": {"origin": "now", "scale": "47450d", "offset": "1095d", "decay": 0.1}}}
 
 
32
  ],
33
  "query": {
34
  "bool": {
35
  "filter": [
36
  {"query_string": {
37
  "default_operator": "AND",
38
+ "fields": ["ementa_texto.plural^3", "acordao_ata.plural^3"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  "query": "*",
40
  "type": "cross_fields",
41
+ "fuzziness": "AUTO:4,7"
 
 
42
  }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  ]
44
  }
45
  }
46
  }
47
  },
48
  "_source": [
49
+ # Identificação
50
+ "id", "dg_unique", "base",
51
+
52
+ # Metadados principais
53
+ "titulo", "processo_codigo_completo", "processo_numero",
54
+ "processo_classe_processual_unificada_sigla",
55
+ "processo_classe_processual_unificada_extenso",
56
+
57
+ # Data e órgão julgador
58
+ "julgamento_data", "publicacao_data", "orgao_julgador",
59
+ "relator_processo_nome", "relator_acordao_nome", "ministro_facet",
60
+
61
+ # Textos completos (MAIS IMPORTANTE)
62
+ "ementa_texto", # Ementa completa
63
+ "acordao_ata", # Acórdão (ata do julgamento)
64
+ "decisao_texto", # Decisão
65
+ "inteiro_teor_url", # Link para PDF/HTML completo
66
+
67
+ # Informações complementares importantes
68
+ "partes_lista_texto", # Partes envolvidas
69
+ "procedencia_geografica_completo",
70
+ "procedencia_geografica_uf_sigla",
71
+
72
+ # URLs úteis
73
+ "acompanhamento_processual_url",
74
+ "dje_url",
75
+
76
+ # Campos de legislação e jurisprudência citada
77
+ "documental_legislacao_citada_texto",
78
+ "documental_jurisprudencia_citada_texto",
79
+ "documental_indexacao_texto",
80
+ "documental_observacao_texto",
81
+
82
+ # Teses e repercussão geral
83
+ "is_repercussao_geral",
84
+ "documental_tese_texto",
85
+ "documental_tese_tema_texto"
86
  ],
87
  "aggs": {
88
  "base_agg": {
89
  "filters": {
90
  "filters": {
91
+ "acordaos": {"match": {"base": "acordaos"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  }
93
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  }
95
  },
96
  "size": 250,
97
  "from": 0,
98
+ "sort": [{"julgamento_data": {"order": "desc"}}], # Mais recentes primeiro
99
+ "track_total_hits": True
100
+ }
101
+
102
+ # Payload para busca de um documento específico por ID
103
+ PAYLOAD_POR_ID = {
104
+ "query": {
105
+ "ids": {
106
+ "values": [] # Será preenchido dinamicamente
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  }
108
  },
109
+ "_source": PAYLOAD_OTIMIZADO["_source"],
110
+ "size": 1
111
  }
112
 
113
  # Constantes da API
 
115
  HEADERS = {
116
  "Accept": "application/json, text/plain, */*",
117
  "Content-Type": "application/json",
118
+ "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",
119
+ "Referer": "https://jurisprudencia.stf.jus.br/pages/search",
 
 
120
  "Origin": "https://jurisprudencia.stf.jus.br"
121
  }
122
 
123
+ # Cache simples para tokens
124
+ token_cache = {
125
+ "token": None,
126
+ "expires_at": 0
127
+ }
128
+
129
+ # Template HTML com botão de download
130
  HTML_TEMPLATE = """
131
  <!DOCTYPE html>
132
  <html>
133
  <head>
134
+ <title>⚖️ STF Jurisprudência - Bypass AWS WAF</title>
135
  <meta charset="utf-8">
136
  <meta name="viewport" content="width=device-width, initial-scale=1">
137
  <style>
138
+ body { font-family: 'Segoe UI', Roboto, system-ui, sans-serif; max-width: 1400px; margin: 0 auto; padding: 20px; background: #f0f2f5; }
139
+ .container { background: white; border-radius: 12px; padding: 30px; box-shadow: 0 8px 20px rgba(0,0,0,0.1); }
140
+ h1 { color: #1a1a2e; border-bottom: 3px solid #4CAF50; padding-bottom: 15px; display: flex; align-items: center; gap: 10px; }
141
+ h1:before { content: "⚖️"; font-size: 1.2em; }
142
+ .info-box { background: #e8f0fe; border-left: 5px solid #2196F3; padding: 15px 20px; margin: 20px 0; border-radius: 8px; }
143
+ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 25px 0; }
144
+ .stat-card { background: white; border: 1px solid #e0e0e0; border-radius: 10px; padding: 20px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
145
+ .stat-value { font-size: 32px; font-weight: bold; color: #1a73e8; }
146
+ .stat-label { color: #5f6368; font-size: 14px; margin-top: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
147
+ .button-group { display: flex; gap: 15px; flex-wrap: wrap; margin: 25px 0; }
148
+ button { background: #1a73e8; color: white; border: none; padding: 14px 28px; font-size: 16px; font-weight: 500; border-radius: 8px; cursor: pointer; transition: all 0.3s; display: inline-flex; align-items: center; gap: 10px; box-shadow: 0 2px 8px rgba(26,115,232,0.3); }
149
+ button:hover { background: #1557b0; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(26,115,232,0.4); }
150
+ button:disabled { background: #a0a0a0; cursor: not-allowed; transform: none; box-shadow: none; }
151
+ button.secondary { background: #34a853; }
152
+ button.secondary:hover { background: #2d8745; }
153
+ button.download { background: #f9ab00; color: #1a1a2e; }
154
+ button.download:hover { background: #e69c00; }
155
+ .loading { display: inline-block; width: 20px; height: 20px; border: 3px solid rgba(255,255,255,0.3); border-top: 3px solid white; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 10px; vertical-align: middle; }
156
  @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
157
+ pre { background: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 10px; padding: 20px; overflow: auto; max-height: 600px; font-size: 13px; font-family: 'Consolas', 'Monaco', monospace; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05); }
158
+ .success { color: #0f9d58; background: #e6f4ea; border-left: 5px solid #34a853; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
159
+ .error { color: #d93025; background: #fce8e6; border-left: 5px solid #ea4335; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
160
+ .warning { color: #e37400; background: #fef7e0; border-left: 5px solid #f9ab00; padding: 15px 20px; margin: 15px 0; border-radius: 8px; font-weight: 500; }
161
+ .token-box { background: #1a1a2e; color: #e0e0e0; padding: 15px; border-radius: 8px; font-family: 'Consolas', monospace; word-break: break-all; margin: 15px 0; border: 1px solid #2a2a3e; }
162
+ .token-label { color: #f9ab00; font-weight: bold; margin-bottom: 8px; display: block; }
163
+ .filters { background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 20px 0; border: 1px solid #e0e0e0; }
164
+ .filter-group { display: flex; gap: 15px; flex-wrap: wrap; align-items: flex-end; }
165
+ .filter-item { flex: 1; min-width: 200px; }
166
+ .filter-item label { display: block; margin-bottom: 8px; color: #5f6368; font-size: 14px; font-weight: 500; }
167
+ .filter-item input, .filter-item select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; }
168
+ .filter-item input:focus, .filter-item select:focus { outline: none; border-color: #1a73e8; box-shadow: 0 0 0 2px rgba(26,115,232,0.2); }
169
+ .badge { display: inline-block; background: #e8f0fe; color: #1a73e8; padding: 4px 12px; border-radius: 20px; font-size: 13px; font-weight: 500; margin: 2px; }
170
  </style>
171
  </head>
172
  <body>
173
  <div class="container">
174
+ <h1>STF Jurisprudência - Bypass AWS WAF</h1>
175
+
176
  <div class="info-box">
177
+ <strong>📌 API de Jurisprudência do STF</strong><br>
178
+ • Acesso via bypass do AWS WAF usando Playwright<br>
179
+ • Retorna ementa completa, inteiro teor (URL) e metadados<br>
180
+ • Total de documentos disponíveis: <span id="totalDocs">carregando...</span>
181
  </div>
182
+
183
+ <div class="stats-grid">
184
+ <div class="stat-card"><div class="stat-value" id="requestsCount">0</div><div class="stat-label">Requisições</div></div>
185
  <div class="stat-card"><div class="stat-value" id="successCount">0</div><div class="stat-label">Sucessos</div></div>
186
  <div class="stat-card"><div class="stat-value" id="failCount">0</div><div class="stat-label">Falhas</div></div>
187
+ <div class="stat-card"><div class="stat-value" id="docsCount">0</div><div class="stat-label">Docs Obtidos</div></div>
188
+ </div>
189
+
190
+ <div class="filters">
191
+ <h3 style="margin-top: 0;">🔍 Filtros de Busca</h3>
192
+ <div class="filter-group">
193
+ <div class="filter-item">
194
+ <label>Quantidade</label>
195
+ <select id="pageSize">
196
+ <option value="10">10 resultados</option>
197
+ <option value="25">25 resultados</option>
198
+ <option value="50">50 resultados</option>
199
+ <option value="100" selected>100 resultados</option>
200
+ <option value="250">250 resultados</option>
201
+ </select>
202
+ </div>
203
+ <div class="filter-item">
204
+ <label>Ordenar por</label>
205
+ <select id="sortOrder">
206
+ <option value="desc">Mais recentes</option>
207
+ <option value="asc">Mais antigos</option>
208
+ </select>
209
+ </div>
210
+ <div class="filter-item">
211
+ <label>Base</label>
212
+ <select id="base">
213
+ <option value="acordaos">Acórdãos</option>
214
+ <option value="decisoes">Decisões</option>
215
+ <option value="sumulas">Súmulas</option>
216
+ <option value="informativos">Informativos</option>
217
+ </select>
218
+ </div>
219
+ </div>
220
  </div>
221
+
222
+ <div class="button-group">
223
  <button id="testBtn" onclick="runTest()">
224
  <span class="loading" id="loading" style="display: none;"></span>
225
+ <span>🚀 Executar Busca</span>
226
+ </button>
227
+ <button id="downloadBtn" class="download" onclick="downloadJSON()" disabled>
228
+ 📥 Download JSON
229
+ </button>
230
+ <button id="copyBtn" class="secondary" onclick="copyToken()">
231
+ 🔑 Copiar Token
232
  </button>
233
  </div>
234
+
235
+ <div id="tokenDisplay" style="display: none;" class="token-box">
236
+ <span class="token-label">🔐 Token AWS WAF</span>
237
+ <span id="tokenValue"></span>
238
+ </div>
239
+
240
+ <div id="result" style="margin-top: 25px;"></div>
241
  </div>
242
 
243
  <script>
244
+ let lastResult = null;
245
+ let lastToken = null;
246
+ let requestsCount = 0, successCount = 0, failCount = 0, docsCount = 0;
247
+
248
  async function runTest() {
249
  const btn = document.getElementById('testBtn');
250
  const loading = document.getElementById('loading');
 
251
  const resultDiv = document.getElementById('result');
252
+ const pageSize = document.getElementById('pageSize').value;
253
+ const sortOrder = document.getElementById('sortOrder').value;
254
+ const base = document.getElementById('base').value;
255
+
256
  btn.disabled = true;
257
  loading.style.display = 'inline-block';
258
+ resultDiv.innerHTML = '<div class="info-box">⏳ Executando busca no STF...</div>';
259
+
260
  try {
261
+ const response = await fetch('/api/search-advanced', {
262
+ method: 'POST',
263
+ headers: { 'Content-Type': 'application/json' },
264
+ body: JSON.stringify({ pageSize: parseInt(pageSize), sortOrder, base })
265
+ });
266
+
267
  const data = await response.json();
268
  requestsCount++;
269
  document.getElementById('requestsCount').textContent = requestsCount;
270
+
271
  if (data.success) {
272
  successCount++;
273
  document.getElementById('successCount').textContent = successCount;
274
+
275
+ if (data.data && data.data.result && data.data.result.hits) {
276
+ docsCount = data.data.result.hits.hits.length;
277
+ document.getElementById('docsCount').textContent = docsCount;
278
+
279
+ if (data.data.result.hits.total && data.data.result.hits.total.value) {
280
+ document.getElementById('totalDocs').textContent = data.data.result.hits.total.value.toLocaleString();
281
+ }
282
  }
283
+
284
+ lastResult = data.data;
285
+ lastToken = data.token;
286
+
287
+ if (lastToken) {
288
+ document.getElementById('tokenValue').textContent = lastToken;
289
+ document.getElementById('tokenDisplay').style.display = 'block';
290
+ document.getElementById('downloadBtn').disabled = false;
291
+ }
292
+
293
+ let resultHtml = '<div class="success">✅ Busca realizada com sucesso!</div>';
294
+
295
+ if (data.data && data.data.result) {
296
+ const total = data.data.result.hits.total?.value || 0;
297
+ const hits = data.data.result.hits.hits || [];
298
+
299
+ resultHtml += `<div class="badge">📊 Total encontrado: ${total.toLocaleString()} documentos</div>`;
300
+ resultHtml += `<div class="badge">📄 Exibindo: ${hits.length} resultados</div>`;
301
+
302
+ if (hits.length > 0) {
303
+ resultHtml += '<h4>📋 Primeiro resultado:</h4>';
304
+ resultHtml += '<pre>' + JSON.stringify(hits[0]._source, null, 2) + '</pre>';
305
+
306
+ if (hits.length > 1) {
307
+ resultHtml += `<p><em>... e mais ${hits.length - 1} resultados (veja no JSON completo)</em></p>`;
308
+ }
309
+ }
310
+ }
311
+
312
  resultDiv.innerHTML = resultHtml;
313
  } else {
314
  failCount++;
315
  document.getElementById('failCount').textContent = failCount;
316
+
317
+ let errorHtml = '<div class="error">❌ Falha na busca</div>';
318
  if (data.attempts) {
319
  data.attempts.forEach(attempt => {
320
+ errorHtml += `<div class="warning"><strong>${attempt.method}:</strong> ${attempt.error || 'Erro'}</div>`;
321
  });
322
  }
323
+ errorHtml += '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
324
  resultDiv.innerHTML = errorHtml;
325
  }
326
  } catch (error) {
327
  failCount++;
328
  document.getElementById('failCount').textContent = failCount;
329
+ resultDiv.innerHTML = '<div class="error">❌ Erro: ' + error.message + '</div>';
330
  } finally {
331
  btn.disabled = false;
332
  loading.style.display = 'none';
 
333
  }
334
  }
335
+
336
+ function downloadJSON() {
337
+ if (!lastResult) {
338
+ alert('Nenhum resultado para download');
339
+ return;
340
+ }
341
+
342
+ const dataStr = JSON.stringify(lastResult, null, 2);
343
+ const blob = new Blob([dataStr], { type: 'application/json' });
344
+ const url = URL.createObjectURL(blob);
345
+ const a = document.createElement('a');
346
+ a.href = url;
347
+ a.download = `stf_jurisprudencia_${new Date().toISOString().slice(0,10)}.json`;
348
+ document.body.appendChild(a);
349
+ a.click();
350
+ document.body.removeChild(a);
351
+ URL.revokeObjectURL(url);
352
+ }
353
+
354
+ function copyToken() {
355
+ if (!lastToken) {
356
+ alert('Nenhum token disponível. Execute uma busca primeiro.');
357
+ return;
358
+ }
359
+
360
+ navigator.clipboard.writeText(lastToken).then(() => {
361
+ alert('✅ Token copiado para área de transferência!');
362
+ }).catch(() => {
363
+ alert('❌ Erro ao copiar token');
364
+ });
365
+ }
366
+
367
+ // Carregar total de documentos ao iniciar
368
+ window.onload = async () => {
369
+ try {
370
+ const response = await fetch('/api/health');
371
+ const data = await response.json();
372
+ if (data.total_docs) {
373
+ document.getElementById('totalDocs').textContent = data.total_docs.toLocaleString();
374
+ }
375
+ } catch (e) {
376
+ document.getElementById('totalDocs').textContent = 'indisponível';
377
+ }
378
+ };
379
  </script>
380
  </body>
381
  </html>
382
  """
383
 
384
+ # ============================================
385
  # Funções auxiliares
386
+ # ============================================
387
+
388
+ def get_fresh_token():
389
+ """Obtém um token novo via Playwright"""
390
+ global token_cache
391
+
392
+ # Verificar cache (válido por 55 minutos)
393
+ if token_cache["token"] and time.time() < token_cache["expires_at"]:
394
+ logger.info("Usando token em cache")
395
+ return token_cache["token"]
396
+
397
+ logger.info("Obtendo novo token via Playwright")
398
  try:
399
+ with sync_playwright() as p:
400
+ browser = p.chromium.launch(headless=True, args=['--no-sandbox'])
401
+ context = browser.new_context(
402
+ viewport={'width': 1920, 'height': 1080},
403
+ user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
 
 
 
 
 
404
  )
405
+ page = context.new_page()
406
+
407
+ page.goto("https://jurisprudencia.stf.jus.br/pages/search",
408
+ wait_until='domcontentloaded', timeout=30000)
409
+ page.wait_for_timeout(3000)
410
+
411
+ cookies = context.cookies()
412
+ token = None
413
+ for cookie in cookies:
414
+ if cookie.get('name') == 'aws-waf-token':
415
+ token = cookie.get('value')
416
+ break
417
+
418
+ browser.close()
419
+
420
+ if token:
421
+ # Cache por 55 minutos (tokens AWS WAF geralmente duram 1h)
422
+ token_cache["token"] = token
423
+ token_cache["expires_at"] = time.time() + 3300
424
+ logger.info(f"Token obtido: {token[:30]}...")
425
+ return token
426
+ else:
427
+ logger.warning("Token não encontrado nos cookies")
428
+ return None
429
+
430
+ except Exception as e:
431
+ logger.error(f"Erro ao obter token: {str(e)}")
432
+ return None
433
+
434
+ def search_with_token(token, custom_payload=None):
435
+ """Faz busca usando token"""
436
+ if not token:
437
+ return {"success": False, "error": "Token não fornecido"}
438
+
439
+ payload = custom_payload or PAYLOAD_OTIMIZADO
440
+
441
+ headers = HEADERS.copy()
442
+ headers['Cookie'] = f'aws-waf-token={token}'
443
+
444
+ try:
445
+ response = requests.post(
446
  URL_API,
447
+ headers=headers,
448
+ json=payload,
449
+ verify=False,
450
+ timeout=30
451
  )
452
+
453
+ if response.status_code == 200:
454
+ return {"success": True, "data": response.json()}
455
+ elif response.status_code == 403:
456
+ # Token expirado, limpar cache
457
+ token_cache["token"] = None
458
+ return {"success": False, "error": "Token expirado", "status": 403}
459
  else:
460
+ return {"success": False, "error": f"HTTP {response.status_code}", "text": response.text[:500]}
461
+
462
  except Exception as e:
463
+ return {"success": False, "error": str(e)}
464
+
465
+ def get_document_by_id(token, doc_id):
466
+ """Busca um documento específico por ID"""
467
+ payload = PAYLOAD_POR_ID.copy()
468
+ payload["query"]["ids"]["values"] = [doc_id]
469
+
470
+ return search_with_token(token, payload)
471
+
472
+ # ============================================
473
+ # Rotas da aplicação
474
+ # ============================================
475
+
476
+ @app.route('/')
477
+ def index():
478
+ return render_template_string(HTML_TEMPLATE)
479
+
480
+ @app.route('/api/search-advanced', methods=['POST'])
481
+ def search_advanced():
482
+ """Endpoint de busca avançada com parâmetros"""
483
+ data = request.json or {}
484
+ page_size = data.get('pageSize', 100)
485
+ sort_order = data.get('sortOrder', 'desc')
486
+ base = data.get('base', 'acordaos')
487
+
488
+ # Construir payload dinâmico
489
+ payload = PAYLOAD_OTIMIZADO.copy()
490
+ payload["size"] = min(page_size, 250) # Máximo 250
491
+ payload["sort"] = [{"julgamento_data": {"order": sort_order}}]
492
+
493
+ # Ajustar base na query
494
+ if base != "acordaos":
495
+ payload["aggs"]["base_agg"]["filters"]["filters"] = {
496
+ base: {"match": {"base": base}}
497
+ }
498
+ payload["post_filter"] = {
499
+ "bool": {
500
+ "must": [{"term": {"base": base}}]
501
+ }
502
+ }
503
+
504
+ # Obter token
505
+ token = get_fresh_token()
506
+ if not token:
507
+ # Se não conseguiu token, tentar com Playwright completo
508
+ return test_with_playwright_full(payload)
509
+
510
+ # Tentar busca com token
511
+ result = search_with_token(token, payload)
512
+
513
+ if result.get("success"):
514
+ return jsonify({
515
+ "success": True,
516
+ "token": token,
517
+ "data": result["data"],
518
+ "timestamp": time.time()
519
+ })
520
+ else:
521
+ # Se token expirou, tentar renovar e buscar
522
+ if result.get("status") == 403:
523
+ token_cache["token"] = None
524
+ token = get_fresh_token()
525
+ if token:
526
+ result = search_with_token(token, payload)
527
+ if result.get("success"):
528
+ return jsonify({
529
+ "success": True,
530
+ "token": token,
531
+ "data": result["data"],
532
+ "timestamp": time.time()
533
+ })
534
+
535
+ # Fallback para Playwright
536
+ return test_with_playwright_full(payload)
537
+
538
+ @app.route('/api/search', methods=['POST'])
539
+ def search():
540
+ """Endpoint simples para busca (mantido para compatibilidade)"""
541
+ data = request.json or {}
542
+ token = data.get('token') or get_fresh_token()
543
+ custom_payload = data.get('payload', PAYLOAD_OTIMIZADO)
544
+
545
+ if not token:
546
+ return jsonify({"error": "Não foi possível obter token"}), 500
547
+
548
+ result = search_with_token(token, custom_payload)
549
+
550
+ if result.get("success"):
551
+ return jsonify({
552
+ "success": True,
553
+ "data": result["data"]
554
+ })
555
+ else:
556
+ return jsonify({
557
+ "success": False,
558
+ "error": result.get("error")
559
+ }), 500
560
+
561
+ @app.route('/api/document/<doc_id>', methods=['GET'])
562
+ def get_document(doc_id):
563
+ """Obtém um documento específico por ID"""
564
+ token = get_fresh_token()
565
+ if not token:
566
+ return jsonify({"error": "Não foi possível obter token"}), 500
567
+
568
+ result = get_document_by_id(token, doc_id)
569
+
570
+ if result.get("success") and result["data"].get("hits", {}).get("hits"):
571
+ doc = result["data"]["hits"]["hits"][0] if result["data"]["hits"]["hits"] else None
572
+ return jsonify({
573
+ "success": True,
574
+ "document": doc
575
+ })
576
+ else:
577
+ return jsonify({
578
+ "success": False,
579
+ "error": result.get("error", "Documento não encontrado")
580
+ }), 404
581
+
582
+ @app.route('/api/test-bypass', methods=['POST'])
583
+ def test_bypass():
584
+ """Endpoint de teste com fallback para Playwright"""
585
+ logger.info("Requisição de teste recebida")
586
+
587
+ # Tentar primeiro com token
588
+ token = get_fresh_token()
589
+ if token:
590
+ result = search_with_token(token, PAYLOAD_OTIMIZADO)
591
+ if result.get("success"):
592
+ return jsonify({
593
+ "success": True,
594
+ "method": "token",
595
+ "token": token,
596
+ "data": result["data"],
597
+ "timestamp": time.time()
598
+ })
599
+
600
+ # Fallback para Playwright
601
+ return test_with_playwright_full(PAYLOAD_OTIMIZADO)
602
 
603
+ def test_with_playwright_full(payload):
604
+ """Versão completa do Playwright para fallback"""
605
  logger.info("Tentando acesso com Playwright...")
606
+
607
  try:
608
  with sync_playwright() as p:
609
  browser = p.chromium.launch(headless=True, args=['--no-sandbox'])
610
+ context = browser.new_context(
611
+ viewport={'width': 1920, 'height': 1080},
612
+ user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
613
+ )
614
  page = context.new_page()
615
+
616
+ page.goto("https://jurisprudencia.stf.jus.br/pages/search",
617
+ wait_until='domcontentloaded', timeout=30000)
 
618
  page.wait_for_timeout(3000)
619
+
620
  cookies = context.cookies()
621
  token = None
622
  for cookie in cookies:
623
  if cookie.get('name') == 'aws-waf-token':
624
  token = cookie.get('value')
625
  break
626
+
627
+ # Fazer requisição à API via página
628
  api_result = page.evaluate("""
629
  async (payload) => {
630
  try {
 
636
  },
637
  body: JSON.stringify(payload)
638
  });
639
+
640
  if (response.ok) {
641
  return { success: true, data: await response.json() };
642
  } else {
643
+ return { success: false, status: response.status };
644
  }
645
  } catch (error) {
646
  return { success: false, error: error.toString() };
647
  }
648
  }
649
+ """, payload)
650
+
651
  browser.close()
652
+
653
  if api_result.get('success'):
654
+ # Atualizar cache com o novo token
655
+ if token:
656
+ token_cache["token"] = token
657
+ token_cache["expires_at"] = time.time() + 3300
658
+
659
+ return jsonify({
660
+ "success": True,
661
+ "method": "playwright",
662
+ "token": token,
663
+ "data": api_result.get('data'),
664
+ "timestamp": time.time()
665
+ })
666
  else:
667
+ return jsonify({
668
+ "success": False,
669
+ "error": api_result.get('error', 'Falha desconhecida'),
670
+ "method": "playwright",
671
+ "token": token
672
+ }), 500
673
+
674
  except Exception as e:
675
  logger.error(f"Erro no Playwright: {str(e)}")
676
+ return jsonify({
677
+ "success": False,
678
+ "error": str(e),
679
+ "method": "playwright",
680
+ "traceback": traceback.format_exc()
681
+ }), 500
682
 
683
+ @app.route('/api/health', methods=['GET'])
684
+ def health():
685
+ """Health check com estatísticas"""
686
+ playwright_status = False
687
  try:
688
  with sync_playwright() as p:
689
  p.chromium.launch(headless=True).close()
690
+ playwright_status = True
691
  except:
692
+ pass
693
+
694
+ # Tentar obter total de documentos
695
+ total_docs = None
696
+ token = get_fresh_token()
697
+ if token:
698
+ try:
699
+ result = search_with_token(token, {"size": 0, "track_total_hits": True})
700
+ if result.get("success") and result["data"].get("hits", {}).get("total"):
701
+ total_docs = result["data"]["hits"]["total"]["value"]
702
+ except:
703
+ pass
704
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
705
  return jsonify({
706
  "status": "healthy",
707
  "timestamp": time.time(),
708
  "playwright_ready": playwright_status,
709
+ "token_cached": bool(token_cache["token"]),
710
+ "token_expires_in": max(0, token_cache["expires_at"] - time.time()) if token_cache["expires_at"] else 0,
711
+ "total_docs": total_docs,
712
  "python_version": sys.version
713
  })
714
 
715
+ @app.route('/api/token', methods=['GET'])
716
+ def get_token():
717
+ """Endpoint para obter token manualmente"""
718
+ token = get_fresh_token()
719
+ if token:
720
+ return jsonify({
721
+ "success": True,
722
+ "token": token,
723
+ "expires_in": max(0, token_cache["expires_at"] - time.time())
724
+ })
725
+ else:
726
+ return jsonify({
727
+ "success": False,
728
+ "error": "Não foi possível obter token"
729
+ }), 500
730
+
731
+ @app.route('/api/clear-cache', methods=['POST'])
732
+ def clear_cache():
733
+ """Limpa o cache de token"""
734
+ global token_cache
735
+ token_cache = {"token": None, "expires_at": 0}
736
+ return jsonify({"success": True, "message": "Cache limpo"})
737
+
738
  if __name__ == '__main__':
739
  # Configurar SSL
740
  try:
 
743
  os.environ['REQUESTS_CA_BUNDLE'] = certifi.where()
744
  except:
745
  pass
746
+
747
+ logger.info("="*50)
748
+ logger.info("🚀 Iniciando aplicação STF Jurisprudência")
749
+ logger.info("📦 Payload otimizado - campos essenciais")
750
+ logger.info(f"📋 Campos selecionados: {len(PAYLOAD_OTIMIZADO['_source'])}")
751
+ logger.info("="*50)
752
+
753
+ # Verificar Playwright
754
+ try:
755
+ with sync_playwright() as p:
756
+ p.chromium.launch(headless=True).close()
757
  logger.info("✅ Playwright pronto para uso")
758
+ except Exception as e:
759
+ logger.warning(f"⚠️ Playwright pode não estar configurado: {e}")
760
+
761
  port = int(os.environ.get('PORT', 7860))
762
  app.run(host='0.0.0.0', port=port, debug=False)