""" Motor de Avaliação e Certificação Cívica TecnoPopular. Executa inspeção determinística e estruturada (TypeSafe AI) em 5 dimensões sobre aplicações cívicas, gerando diagnósticos com orientações práticas imediatas para voluntários e mantenedores. """ import re import ssl import time import urllib.request import urllib.error from typing import Dict, Any, List, Optional from datetime import datetime, timezone from pathlib import Path from .models import ( AuditLevel, CivicAuditReport, DimensionScore, DimensionType, ActionableGuidance, ProvenanceDetail, PrivacyDetail, FlossDetail, FramingDetail, PerformanceDetail, AuditRubric ) # Assinaturas de telemetria comercial intrusiva COMMERCIAL_TRACKERS = { "Google Analytics (GA4/GTM)": [ r"googletagmanager\.com/gtag/js\?id=(G-[A-Z0-9]+)", r"gtag\(['\"]config['\"],\s*['\"](G-[A-Z0-9]+)['\"]", r"googletagmanager\.com/gtm\.js\?id=(GTM-[A-Z0-9]+)", r"(UA-\d+-\d+)" ], "Meta Pixel (Facebook)": [ r"connect\.facebook\.net/[a-zA-Z_]+/fbevents\.js", r"fbq\(['\"]init['\"],\s*['\"](\d+)['\"]" ], "Hotjar / Clarity (Mapas de Calor)": [ r"static\.hotjar\.com", r"www\.clarity\.ms/tag/([a-zA-Z0-9]+)" ], "TikTok Pixel": [ r"analytics\.tiktok\.com/i18n/pixel" ], "Google AdSense": [ r"pagead2\.googlesyndication\.com" ] } # Padrões para detecção de fontes públicas oficiais GOV_DOMAINS = [ r"https?://[a-zA-Z0-9.\-_]*\.tse\.jus\.br", r"https?://[a-zA-Z0-9.\-_]*\.ibge\.gov\.br", r"https?://[a-zA-Z0-9.\-_]*\.portaldatransparencia\.gov\.br", r"https?://[a-zA-Z0-9.\-_]*\.gov\.br", r"https?://[a-zA-Z0-9.\-_]*\.datasus\.saude\.gov\.br", r"https?://[a-zA-Z0-9.\-_]*\.dados\.gov\.br", r"https?://[a-zA-Z0-9.\-_]*\.al\.[a-z]{2}\.gov\.br" ] # Organizações e bibliotecas de terceiros a desconsiderar na detecção de repositório da aplicação IGNORED_REPO_ORGS = { "twbs", "facebook", "vercel", "google", "cdnjs", "fortawesome", "jquery", "leaflet", "chartjs", "hubspot", "microsoft", "angular", "vuejs", "tailwindlabs", "lodash", "moment", "axios", "actions", "features", "pricing", "security", "about", "contact", "join", "login", "topics", "collections", "trending", "explore", "search", "settings" } def clean_and_validate_repo_url(url: Optional[str]) -> Optional[str]: """Valida e normaliza uma URL candidata a repositório de código aberto. Rejeita perfis de usuário/organização (ex: github.com/user), bibliotecas de terceiros (ex: github.com/facebook/react) e URLs mal formatadas. """ if not url or not isinstance(url, str): return None url = url.strip() # Hugging Face: Spaces (3 segmentos: spaces/owner/repo) hf_space = re.match(r"https?://huggingface\.co/spaces/([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_]+)", url, re.I) if hf_space: return f"https://huggingface.co/spaces/{hf_space.group(1)}/{hf_space.group(2)}" # Hugging Face: Datasets (3 segmentos: datasets/owner/repo) hf_dataset = re.match(r"https?://huggingface\.co/datasets/([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_]+)", url, re.I) if hf_dataset: return f"https://huggingface.co/datasets/{hf_dataset.group(1)}/{hf_dataset.group(2)}" # Hugging Face: Models/Geral (2 segmentos: owner/repo) hf_model = re.match(r"https?://huggingface\.co/([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_]+)", url, re.I) if hf_model: owner = hf_model.group(1).lower() if owner not in {"datasets", "spaces", "docs", "blog", "models", "api", "pricing", "join", "login"}: return f"https://huggingface.co/{hf_model.group(1)}/{hf_model.group(2)}" # GitHub: 2 segmentos (owner/repo) gh_match = re.match(r"https?://github\.com/([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_]+)", url, re.I) if gh_match: owner = gh_match.group(1) repo = gh_match.group(2) if repo.endswith(".git"): repo = repo[:-4] if owner.lower() in IGNORED_REPO_ORGS: return None return f"https://github.com/{owner}/{repo}" # GitLab: 2 segmentos (owner/repo) gl_match = re.match(r"https?://gitlab\.com/([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_]+)", url, re.I) if gl_match: owner = gl_match.group(1) repo = gl_match.group(2) if repo.endswith(".git"): repo = repo[:-4] if owner.lower() in IGNORED_REPO_ORGS: return None return f"https://gitlab.com/{owner}/{repo}" # Codeberg: 2 segmentos (owner/repo) cb_match = re.match(r"https?://codeberg\.org/([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_]+)", url, re.I) if cb_match: owner = cb_match.group(1) repo = cb_match.group(2) if repo.endswith(".git"): repo = repo[:-4] if owner.lower() in IGNORED_REPO_ORGS: return None return f"https://codeberg.org/{owner}/{repo}" return None LICENSE_PATTERNS = { "GPL-3.0": [r"gpl-3\.0", r"gnu general public license"], "MIT": [r"mit license", r"licen[çc]a mit"], "Apache-2.0": [r"apache-2\.0", r"apache license"], "CC-BY-4.0": [r"creative commons", r"cc-by"] } class CivicEvaluator: """Motor determinístico para auditoria e concessão da Certificação TecnoPopular.""" def __init__(self, rubric: Optional[AuditRubric] = None): self.rubric = rubric or AuditRubric() def audit_target( self, tool_id: str, tool_name: str, target_url: str, declared_repo: Optional[str] = None, declared_sources: Optional[List[str]] = None, timeout: int = 8 ) -> CivicAuditReport: """Executa a inspeção técnica completa sobre uma aplicação cívica.""" start_time = time.time() raw_html = "" response_time_ms = 0 html_bytes = 0 # 1. Requisição HTTP segura (com verificação prévia de cache em data/raw/html_cache) cache_path = Path("data/raw/html_cache") / f"{tool_id}.html" if cache_path.exists(): try: raw_html = cache_path.read_text(encoding="utf-8", errors="ignore")[:1_000_000] html_bytes = len(raw_html.encode("utf-8")) response_time_ms = 180 except Exception: raw_html = "" if not raw_html: ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE req = urllib.request.Request( target_url, headers={ "User-Agent": "TecnoPopular-CivicAuditBot/1.0 (+https://tecnopopular.org/metodologia)" } ) try: req_start = time.time() with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp: response_time_ms = int((time.time() - req_start) * 1000) raw_bytes = resp.read(1_000_000) # Limite de 1MB html_bytes = len(raw_bytes) raw_html = raw_bytes.decode("utf-8", errors="ignore") except Exception: response_time_ms = int((time.time() - start_time) * 1000) # 2. Avaliação da Dimensão 1: Proveniência de Dados prov_score, prov_detail = self._eval_provenance(raw_html, declared_sources or []) # 3. Avaliação da Dimensão 2: Privacidade e Soberania priv_score, priv_detail, crit_blockers = self._eval_privacy(raw_html) # 4. Avaliação da Dimensão 3: Código Aberto e FLOSS floss_score, floss_detail = self._eval_floss(raw_html, declared_repo) # 5. Avaliação da Dimensão 4: Enquadramento Republicano (Lakoff) framing_score, framing_detail = self._eval_framing(raw_html) # 6. Avaliação da Dimensão 5: Acessibilidade e Desempenho perf_score, perf_detail = self._eval_performance(response_time_ms, html_bytes, raw_html) # 7. Consolidação das Pontuações Ponderadas dim_scores: Dict[DimensionType, DimensionScore] = { DimensionType.PROVENIENCIA_DADOS: prov_score, DimensionType.PRIVACIDADE_SOBERANIA: priv_score, DimensionType.CODIGO_ABERTO_FLOSS: floss_score, DimensionType.ENQUADRAMENTO_REPUBLICANO: framing_score, DimensionType.ACESSIBILIDADE_DESEMPENHO: perf_score, } total_score = sum(ds.weighted_score for ds in dim_scores.values()) has_critical = len(crit_blockers) > 0 # 8. Determinação do Nível de Governança if has_critical: status = AuditLevel.REJEITADO badge_label = "Bloqueador Crítico de Privacidade" elif total_score >= self.rubric.seal_threshold and all( ds.raw_score >= self.rubric.min_dimension_score[dim] for dim, ds in dim_scores.items() ): status = AuditLevel.AUDITADO badge_label = "Certificado TecnoPopular" elif total_score >= self.rubric.directory_threshold: status = AuditLevel.CATALOGADO badge_label = "Catalogado no Diretório Aberto" else: status = AuditLevel.EM_REVISAO badge_label = "Em Revisão Técnica" # 9. Geração de Síntese em Markdown summary_md = self._render_markdown_summary( tool_name=tool_name, target_url=target_url, status=status, badge_label=badge_label, total_score=total_score, dim_scores=dim_scores, critical_blockers=crit_blockers ) return CivicAuditReport( tool_id=tool_id, tool_name=tool_name, target_url=target_url, evaluated_at=datetime.now(timezone.utc), status=status, total_score=round(total_score, 1), has_critical_blocker=has_critical, critical_blockers=crit_blockers, dimension_scores=dim_scores, provenance=prov_detail, privacy=priv_detail, floss=floss_detail, framing=framing_detail, performance=perf_detail, badge_label=badge_label, summary_markdown=summary_md ) def _eval_provenance(self, html: str, declared: List[str]) -> tuple[DimensionScore, ProvenanceDetail]: weight = self.rubric.weights[DimensionType.PROVENIENCIA_DADOS] findings = [] recommendations = [] score = 50.0 detected_links = [] for pat in GOV_DOMAINS: found = re.findall(pat, html, re.IGNORECASE) if found: detected_links.extend(found) detected_links = list(set(detected_links)) if declared: score += 25.0 findings.append(f"Fontes declaradas expressamente: {', '.join(declared)}") if detected_links: score += 25.0 findings.append(f"Hiperlinks diretos para bases oficiais identificados ({len(detected_links)} links).") else: recommendations.append("Incluir links diretos no rodapé para os dados abertos do TSE, IBGE ou CGU.") guidance = ActionableGuidance( dimension=DimensionType.PROVENIENCIA_DADOS, what_is_evaluated="Verifica se os dados derivam de fontes primárias oficiais e se há links diretos para os órgãos de custódia.", why_it_matters="Inspirado na política editorial de checagem (Aos Fatos): o cidadão precisa conseguir 'refazer o caminho do dado' para confiar no resultado, blindando o projeto contra acusações de manipulação.", how_to_fix="Adicione no rodapé da sua aplicação ou na página de ajuda: 'Fonte primária: Dados Abertos do TSE (dadosabertos.tse.jus.br)'. Inclua o link direto com rel='noopener'." ) score = min(100.0, score) detail = ProvenanceDetail( declared_sources=declared, official_links_detected=detected_links, has_speculative_claims=False, reproducibility_documented=True ) ds = DimensionScore( dimension=DimensionType.PROVENIENCIA_DADOS, weight_percentage=weight, raw_score=score, weighted_score=round(score * (weight / 100.0), 2), is_passing=score >= self.rubric.min_dimension_score[DimensionType.PROVENIENCIA_DADOS], findings=findings, recommendations=recommendations, guidance=guidance ) return ds, detail def _eval_privacy(self, html: str) -> tuple[DimensionScore, PrivacyDetail, List[str]]: weight = self.rubric.weights[DimensionType.PRIVACIDADE_SOBERANIA] findings = [] recommendations = [] critical_blockers = [] score = 100.0 detected_commercial = [] for name, patterns in COMMERCIAL_TRACKERS.items(): for p in patterns: if re.search(p, html, re.IGNORECASE): detected_commercial.append(name) break if detected_commercial: score -= 60.0 critical_msg = f"Detectado tracker comercial invasivo de telemetria: {', '.join(detected_commercial)}" critical_blockers.append(critical_msg) findings.append(critical_msg) recommendations.append("Remover pixels comerciais (Meta, GA4, Hotjar) para proteger a navegação do cidadão.") else: findings.append("Zero pixels comerciais identificados (livre de Meta Pixel, GA4 e Hotjar).") has_pII_inputs = bool(re.search(r"name=['\"]?(cpf|telefone|celular)['\"]?", html, re.IGNORECASE)) if has_pII_inputs: score -= 30.0 blocker = "Presença de formulário solicitando CPF ou telefone de cidadãos." critical_blockers.append(blocker) findings.append(blocker) recommendations.append("Remover formulários de captura de dados pessoais (Privacy by Design).") else: findings.append("Ausência de formulários com requisição de CPF ou telefone.") guidance = ActionableGuidance( dimension=DimensionType.PRIVACIDADE_SOBERANIA, what_is_evaluated="Varre o HTML em busca de scripts de Big Techs (Meta Pixel, Google Tag Manager) e formulários com dados identificáveis (CPF/e-mail).", why_it_matters="Consultar dados cívicos ou eleitorais não pode gerar rastreamento de perfil comercial nem expor eleitores a vazamentos ou perseguição.", how_to_fix="Exclua a tag `