Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Auto·Ka9# File : autoka/connectors/_resilient.py10# Module : autoka11# Repository : https://git.spboucher.ai/auto-ka12# Created : 2026-08-2213# Last Modified : 2026-09-1314#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# =============================================================================88# Connecteurs : chaîne de fetch anti-bot RÉSILIENTE (commune)89# Auteur : Simon-Pierre Boucher <contact@spboucher.ai>90# Fichier : connectors/_resilient.py91# -----------------------------------------------------------------------------92# But : rendre les connecteurs durables dans le temps. Quand un site jusque-là93# ouvert déploie un anti-bot (Cloudflare / Akamai / Incapsula / PerimeterX) ou94# renvoie 403/429/503, la requête directe N'ÉCHOUE PLUS silencieusement : elle95# ESCALADE automatiquement à travers une chaîne de secours :96#97# 1. Direct — la session du connecteur (curl_cffi impersonate si98# dispo, sinon requests) : rapide et gratuit.99# 2. Firecrawl — navigateur géré + proxy (FIRECRAWL_API_KEY) : premier100# recours dès qu'un site bloque (2026-11-26).101# 3. Oxylabs (résid.) — proxy résidentiel Canada (-cc-CA) : IP propre.102# 4. Scrapfly (ASP) — bypass anti-bot géré + rendu JS optionnel.103# 5. Bright Data — Web Unlocker : déblocage premium, dernier recours.104#105# Le premier backend qui renvoie un 200 non vide gagne. Si TOUS échouent, on106# renvoie la dernière réponse (avec son code d'erreur) pour que le connecteur107# journalise l'échec comme avant — aucun changement de comportement en cas108# d'échec total, aucun blocage silencieux.109#110# Conception :111# - Aucun effet de bord à l'import ; toute brique non configurée est sautée.112# - Les clés sont lues de os.environ, avec repli sur le .env de l'app puis113# ~/.claude/.env, et acceptent les deux noms Scrapfly (SCRAPFLY_KEY /114# SCRAPFLY_API_KEY). => aucune modif de .env nécessaire.115# - `_ResilientResponse` imite requests.Response (.text/.content/.status_code/116# .url/.headers/.json()/.ok/.raise_for_status()) : les connecteurs existants117# continuent de fonctionner sans modification.118# - Coupe-circuit par hôte : après plusieurs escalades totalement infructueuses119# sur un même hôte, on saute l'escalade payante pendant un temps de repos120# (évite de brûler du quota Scrapfly/Bright Data sur une source morte).121# =============================================================================122from __future__ import annotations123124import json as _json125import os126import time127from pathlib import Path128from urllib.parse import quote, urlsplit129130import requests131132# -- curl_cffi est OPTIONNEL (meilleur fingerprint TLS s'il est présent) ------133try: # pragma: no cover134 from curl_cffi import requests as _cffi # type: ignore135 _HAS_CFFI = True136except Exception: # noqa: BLE001137 _cffi = None138 _HAS_CFFI = False139140# Codes HTTP typiques d'un blocage anti-bot (≠ 401/404/410/500 « métier » :141# 401 = auth manquante, 403/429 = bot bloqué, 5xx CF = challenge/edge).142BLOCK_STATUS = {403, 429, 503, 520, 521, 522, 523, 524, 526, 1020}143144# Marqueurs de page-challenge (Cloudflare/Akamai/Incapsula/PerimeterX/DataDome/145# SiteGround sgcaptcha — ce dernier répond 202 + meta refresh vers146# /.well-known/sgcaptcha/ et l'en-tête `sg-captcha: challenge`).147_CHALLENGE_MARKERS = (148 "just a moment", "cf-browser-verification", "cf-challenge",149 "attention required", "access denied", "request unsuccessful",150 "px-captcha", "perimeterx", "incapsula", "_incapsula_", "datadome",151 "captcha-delivery", "please enable javascript and cookies",152 "checking your browser", "ddos protection by", "sgcaptcha",153 "robot challenge screen",154)155156_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "157 "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36")158159# Coupe-circuit en mémoire : hôte -> (timestamp_jusquà, échecs_consécutifs)160_COOLDOWN: dict[str, tuple[float, int]] = {}161_COOLDOWN_HITS = 3 # nb d'échecs totaux avant repos162_COOLDOWN_SECONDS = 900.0 # 15 min de repos pour un hôte « mort »163164# -- chargement paresseux des secrets ----------------------------------------165_ENV_CACHE: dict[str, str] | None = None166167168def _load_env_files() -> dict[str, str]:169 """Parse les .env candidats une seule fois (repli si os.environ vide)."""170 global _ENV_CACHE171 if _ENV_CACHE is not None:172 return _ENV_CACHE173 out: dict[str, str] = {}174 candidates = []175 # .env de l'app (remonte quelques niveaux depuis ce module)176 here = Path(__file__).resolve()177 for up in range(2, 6):178 try:179 candidates.append(here.parents[up] / ".env")180 except IndexError:181 break182 candidates.append(Path.home() / ".claude" / ".env")183 for path in candidates:184 try:185 if not path.is_file():186 continue187 for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():188 line = line.strip()189 if not line or line.startswith("#") or "=" not in line:190 continue191 k, _, v = line.partition("=")192 k, v = k.strip(), v.strip().strip('"').strip("'")193 # ne pas écraser une valeur déjà trouvée (priorité app > global)194 if k and k not in out:195 out[k] = v196 except Exception: # noqa: BLE001197 continue198 _ENV_CACHE = out199 return out200201202def _secret(*names: str) -> str | None:203 """Cherche une clé dans os.environ puis dans les .env (par ordre de noms)."""204 for n in names:205 v = os.environ.get(n)206 if v:207 return v208 env = _load_env_files()209 for n in names:210 v = env.get(n)211 if v:212 return v213 return None214215216# -- réponse compatible requests.Response ------------------------------------217class _ResilientResponse:218 """Imite le minimum utile d'une requests.Response pour les connecteurs."""219220 def __init__(self, url: str, status_code: int, text: str,221 headers: dict | None = None, via: str = "direct") -> None:222 self.url = url223 self.status_code = int(status_code or 0)224 self._text = text or ""225 self.headers = headers or {}226 self.encoding = "utf-8"227 self.via = via # backend gagnant (diagnostic)228229 @property230 def text(self) -> str:231 return self._text232233 @property234 def content(self) -> bytes:235 return self._text.encode("utf-8", errors="ignore")236237 @property238 def ok(self) -> bool:239 return 200 <= self.status_code < 400240241 def json(self, **kw):242 return _json.loads(self._text)243244 def raise_for_status(self):245 if 400 <= self.status_code < 600:246 raise requests.HTTPError(247 f"{self.status_code} via {self.via} pour {self.url}",248 response=self) # type: ignore[arg-type]249 return None250251 def __repr__(self) -> str: # pragma: no cover252 return f"<_ResilientResponse [{self.status_code}] via {self.via}>"253254255# -- détection de blocage -----------------------------------------------------256def is_blocked(resp) -> bool:257 """True si la réponse ressemble à un blocage anti-bot (≠ erreur métier)."""258 if resp is None:259 return True260 code = getattr(resp, "status_code", 0) or 0261 if code in BLOCK_STATUS:262 return True263 headers = getattr(resp, "headers", None) or {}264 try:265 if "challenge" in str(headers.get("sg-captcha", "")).lower():266 return True # SiteGround sgcaptcha (202)267 except Exception: # noqa: BLE001268 pass269 # 200/202 mais page-challenge servie270 if code in (200, 202):271 try:272 body = (resp.text or "")[:4000].lower()273 except Exception: # noqa: BLE001274 return False275 server = str(headers.get("Server", "")).lower()276 if any(m in body for m in _CHALLENGE_MARKERS):277 return True278 if "cloudflare" in server and ("captcha" in body or "challenge" in body):279 return True280 return False281282283def _host(url: str) -> str:284 try:285 return urlsplit(url).netloc.lower()286 except Exception: # noqa: BLE001287 return url288289290def _cooling(host: str) -> bool:291 until, _ = _COOLDOWN.get(host, (0.0, 0))292 return time.time() < until293294295def _note_failure(host: str) -> None:296 until, hits = _COOLDOWN.get(host, (0.0, 0))297 hits += 1298 if hits >= _COOLDOWN_HITS:299 _COOLDOWN[host] = (time.time() + _COOLDOWN_SECONDS, 0)300 else:301 _COOLDOWN[host] = (until, hits)302303304def _note_success(host: str) -> None:305 _COOLDOWN.pop(host, None)306307308# -- backends d'escalade ------------------------------------------------------309def _try_oxylabs(url: str, timeout: int, country: str,310 headers: dict | None) -> _ResilientResponse | None:311 endpoint = _secret("OXYLABS_PROXY") # pr.oxylabs.io:7777312 user = _secret("OXYLABS_PROXY_USER") # customer-... (sans -cc-XX)313 pwd = _secret("OXYLABS_PROXY_PASS")314 if not (endpoint and user and pwd):315 return None316 cc = (country or "ca").upper()317 puser = f"{user}-cc-{cc}"318 proxy = f"http://{quote(puser, safe='')}:{quote(pwd, safe='')}@{endpoint}"319 proxies = {"http": proxy, "https": proxy}320 hdrs = {"User-Agent": _UA}321 if headers:322 hdrs.update(headers)323 try:324 r = requests.get(url, proxies=proxies, headers=hdrs, timeout=timeout,325 verify=False) # noqa: S501 (proxy MITM du CA Oxylabs)326 return _ResilientResponse(url, r.status_code, r.text,327 dict(r.headers), via="oxylabs")328 except Exception: # noqa: BLE001329 return None330331332def _try_scrapfly(url: str, timeout: int, country: str, render_js: bool,333 headers: dict | None) -> _ResilientResponse | None:334 key = _secret("SCRAPFLY_KEY", "SCRAPFLY_API_KEY")335 if not key:336 return None337 params = {"key": key, "url": url, "country": country or "ca",338 "asp": "true", "proxy_pool": "public_residential_pool"}339 if render_js:340 params["render_js"] = "true"341 if headers:342 for k, v in headers.items():343 params[f"headers[{k}]"] = v344 try:345 r = requests.get("https://api.scrapfly.io/scrape", params=params,346 timeout=max(timeout, 180))347 result = (r.json() or {}).get("result") or {}348 return _ResilientResponse(349 url, result.get("status_code") or 0, result.get("content") or "",350 (result.get("response_headers") or {}), via="scrapfly")351 except Exception: # noqa: BLE001352 return None353354355def _try_brightdata(url: str, timeout: int,356 headers: dict | None) -> _ResilientResponse | None:357 key = _secret("BRIGHTDATA_API_KEY")358 zone = _secret("BRIGHTDATA_ZONE") or "web_unlocker1"359 if not key:360 return None361 try:362 r = requests.post(363 "https://api.brightdata.com/request",364 headers={"Authorization": f"Bearer {key}",365 "Content-Type": "application/json"},366 json={"zone": zone, "url": url, "format": "raw"},367 timeout=max(timeout, 120))368 return _ResilientResponse(url, r.status_code, r.text,369 dict(r.headers), via="brightdata")370 except Exception: # noqa: BLE001371 return None372373374def _unwrap_pre(text: str) -> str:375 """Une réponse JSON/texte chargée dans un navigateur revient enrobée dans376 `<html>…<pre>…</pre></html>` : on restitue le corps d'origine."""377 import html as _html378 import re as _re379 m = _re.match(r"\s*<html[^>]*>\s*<head>.*?</head>\s*<body[^>]*>\s*<pre[^>]*>(.*)</pre>"380 r"\s*(?:<div[^>]*>\s*</div>\s*)*</body>\s*</html>\s*$",381 text, _re.S | _re.I)382 return _html.unescape(m.group(1)) if m else text383384385FIRECRAWL_SCRAPE = "https://api.firecrawl.dev/v2/scrape"386387# Dernière erreur Firecrawl (diagnostic : message du connecteur, jamais de388# zéro silencieux) et coupe-circuit par hôte propre à Firecrawl : après389# plusieurs échecs consécutifs sur un hôte, `firecrawl_first` le saute pendant390# un temps de repos et l'ancien moyen (Scrapfly…) reprend sans délai ajouté.391LAST_FIRECRAWL_ERROR: dict[str, str] = {}392_FC_COOLDOWN: dict[str, tuple[float, int]] = {}393_FC_COOLDOWN_HITS = 3394_FC_COOLDOWN_SECONDS = 1800.0395396397def _try_firecrawl(url: str, timeout: int, country: str, render_js: bool,398 headers: dict | None, wait_ms: int = 0,399 proxy: str | None = None,400 fmt: str = "rawHtml") -> _ResilientResponse | None:401 """Firecrawl /v2/scrape : HTML après chargement navigateur.402403 Premier recours payant quand un site bloque la requête directe.404 `render_js` ajoute une attente pour les pages rendues côté client ;405 `proxy` = "basic" | "stealth" | "auto" ; `fmt` = "rawHtml" (octets servis,406 défaut) ou "html" (HTML nettoyé, liens absolus). Brique sautée si407 FIRECRAWL_API_KEY est absente.408 """409 key = _secret("FIRECRAWL_API_KEY")410 host = _host(url)411 if not key:412 LAST_FIRECRAWL_ERROR[host] = "FIRECRAWL_API_KEY manquant"413 return None414 payload: dict = {"url": url, "formats": [fmt],415 "onlyMainContent": False,416 "location": {"country": (country or "ca").upper()},417 "timeout": int(max(timeout, 60) * 1000)}418 wait = wait_ms or (2500 if render_js else 0)419 if wait:420 payload["waitFor"] = int(wait)421 if proxy:422 payload["proxy"] = proxy423 if headers:424 payload["headers"] = {str(k): str(v) for k, v in headers.items()}425 try:426 r = requests.post(427 FIRECRAWL_SCRAPE,428 headers={"Authorization": f"Bearer {key}",429 "Content-Type": "application/json"},430 json=payload, timeout=max(timeout, 60) + 30)431 body = r.json() or {}432 if not body.get("success"):433 LAST_FIRECRAWL_ERROR[host] = (434 f"HTTP {r.status_code} : {str(body.get('error') or body)[:200]}")435 return None436 data = body.get("data") or {}437 meta = data.get("metadata") or {}438 LAST_FIRECRAWL_ERROR.pop(host, None)439 return _ResilientResponse(440 meta.get("sourceURL") or url, meta.get("statusCode") or 0,441 _unwrap_pre(data.get(fmt) or ""), {}, via="firecrawl")442 except Exception as exc: # noqa: BLE001443 LAST_FIRECRAWL_ERROR[host] = f"{type(exc).__name__} : {exc}"[:200]444 return None445446447def firecrawl_first(url: str, *, timeout: int = 30, country: str = "ca",448 render_js: bool = False, headers: dict | None = None,449 wait_ms: int = 0, proxy: str | None = None,450 fmt: str = "rawHtml") -> _ResilientResponse | None:451 """Firecrawl AVANT l'ancien moyen (Scrapfly, Bright Data) d'un connecteur.452453 Renvoie la réponse seulement si elle est exploitable (HTTP 200, corps non454 vide, pas une page-challenge) ; sinon None et l'appelant se replie sur son455 ancien moyen. Coupe-circuit par hôte : un site que Firecrawl ne franchit456 pas n'est plus tenté pendant 30 min (aucun délai ni crédit gaspillé).457 """458 host = _host(url)459 until, hits = _FC_COOLDOWN.get(host, (0.0, 0))460 if time.time() < until:461 return None462 resp = _try_firecrawl(url, timeout, country, render_js, headers,463 wait_ms=wait_ms, proxy=proxy, fmt=fmt)464 if resp is not None and resp.status_code == 200 and resp.text \465 and not is_blocked(resp):466 _FC_COOLDOWN.pop(host, None)467 return resp468 if resp is not None:469 LAST_FIRECRAWL_ERROR.setdefault(470 host, f"réponse inexploitable (HTTP {resp.status_code}, "471 f"{len(resp.text)} octets)")472 hits += 1473 _FC_COOLDOWN[host] = ((time.time() + _FC_COOLDOWN_SECONDS, 0)474 if hits >= _FC_COOLDOWN_HITS else (0.0, hits))475 return None476477478# -- API publique -------------------------------------------------------------479def escalate(url: str, *, timeout: int = 30, country: str = "ca",480 render_js: bool = False, headers: dict | None = None,481 original=None):482 """Tente la chaîne de secours et renvoie la meilleure réponse.483484 Renvoie un `_ResilientResponse` 200 dès qu'un backend réussit ; sinon la485 dernière réponse tentée (ou `original`) pour préserver le comportement486 d'échec du connecteur. Respecte le coupe-circuit par hôte.487 """488 host = _host(url)489 if _cooling(host):490 return original # source au repos : on ne brûle pas de quota payant491492 last = original493 for backend in (494 lambda: _try_firecrawl(url, timeout, country, render_js, headers),495 lambda: _try_oxylabs(url, timeout, country, headers),496 lambda: _try_scrapfly(url, timeout, country, render_js, headers),497 lambda: _try_brightdata(url, timeout, headers),498 ):499 resp = backend()500 if resp is None:501 continue502 last = resp503 if resp.status_code == 200 and resp.text and not is_blocked(resp):504 _note_success(host)505 return resp506 time.sleep(0.4)507508 _note_failure(host)509 return last if last is not None else original510511512def escalate_if_blocked(resp, url: str, *, timeout: int = 30,513 country: str = "ca", render_js: bool = False,514 headers: dict | None = None):515 """Renvoie `resp` s'il est bon ; sinon lance l'escalade anti-bot."""516 if not is_blocked(resp):517 return resp518 better = escalate(url, timeout=timeout, country=country,519 render_js=render_js, headers=headers, original=resp)520 return better if better is not None else resp521