from contextlib import asynccontextmanager from fastapi import FastAPI, Depends, HTTPException, Header, Query from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import ORJSONResponse from bs4 import BeautifulSoup import httpx import asyncio import time import re import hashlib import hmac import jwt import logging import os from jwt import PyJWKClient from starlette.concurrency import run_in_threadpool import history import stats logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) # ────────────────────────────────────────────── # Cache + locks anti-thundering-herd # ────────────────────────────────────────────── _cache: dict = {} BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al día) P2P_TTL = 60 * 2 # 2 minutos # Throttle del webhook: aunque llegue con token válido, no se re-scrapea el BCV # más de una vez cada N segundos. Neutraliza un flood con token válido (evita # martillar a bcv.org.ve y quemar CPU). El cron legítimo (cada 2 min) nunca lo toca. _last_forced_refresh = 0.0 FORCED_REFRESH_MIN_INTERVAL = 30 # segundos # ────────────────────────────────────────────── # v2 — Constantes (aislamiento total respecto a v1) # ────────────────────────────────────────────── P2P_V2_TTL = 60 * 10 BINANCE_P2P_URL = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search" COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$") # ISO 3166-1 alpha-2 → ISO 4217 (fiat para Binance P2P) SUPPORTED_COUNTRIES: dict[str, str] = { "AR": "ARS", # Argentina "BO": "BOB", # Bolivia "BR": "BRL", # Brasil "CL": "CLP", # Chile "CO": "COP", # Colombia "CR": "CRC", # Costa Rica "DO": "DOP", # República Dominicana "GT": "GTQ", # Guatemala "HN": "HNL", # Honduras "MX": "MXN", # México "NI": "NIO", # Nicaragua "PY": "PYG", # Paraguay "PE": "PEN", # Perú "UY": "UYU", # Uruguay "VE": "VES", # Venezuela (caso especial: local = null) "ES": "EUR", # España } # Un Lock por clave: si el caché vence y llegan 1000 requests simultáneas, # solo la primera hace el fetch — las demás esperan y consumen el caché. _locks: dict[str, asyncio.Lock] = {} def _lock(key: str) -> asyncio.Lock: if key not in _locks: _locks[key] = asyncio.Lock() return _locks[key] def _cached(key: str, ttl: int): entry = _cache.get(key) if entry and (time.time() - entry["ts"]) < ttl: return entry["data"] return None def _store(key: str, data: dict): _cache[key] = {"ts": time.time(), "data": data} # ────────────────────────────────────────────── # Clientes HTTP persistentes (reutilizan conexiones TCP/TLS) # ────────────────────────────────────────────── _http: httpx.AsyncClient | None = None # Binance / general _http_nv: httpx.AsyncClient | None = None # BCV (verify=False — cert roto del BCV) @asynccontextmanager async def lifespan(app: FastAPI): global _http, _http_nv limits = httpx.Limits(max_connections=10, max_keepalive_connections=5) _http = httpx.AsyncClient(timeout=10, limits=limits) _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits) history.init() sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None stats_task = stats.start(history.get_db) appcheck_cleanup_task = asyncio.create_task(_appcheck_cache_cleanup()) yield if sampler: sampler.cancel() if stats_task: stats_task.cancel() appcheck_cleanup_task.cancel() await _http.aclose() await _http_nv.aclose() app = FastAPI( title="Tazas API", version="1.0.0", lifespan=lifespan, default_response_class=ORJSONResponse, # orjson: serialización JSON en C (5-10x más rápido) ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"], ) _known_paths: set[str] | None = None def _tracked_path(path: str) -> str: """Colapsa cualquier path que no sea una ruta real de la app a 'other'. Sin esto, byPath/latencyByPath en stats crecen sin límite: un escáner probando /wp-admin, /.env, etc. crea una entrada nueva en el dict por cada intento, hasta reventar el límite de 1 MiB por documento de Firestore.""" global _known_paths if _known_paths is None: _known_paths = {route.path for route in app.routes if hasattr(route, "path")} return path if path in _known_paths else "other" @app.middleware("http") async def _stats_middleware(request, call_next): # Mide throughput/latencia/errores por endpoint. Si call_next lanza, cuenta 500. started = time.perf_counter() status = 500 try: response = await call_next(request) status = response.status_code return response finally: stats.record(_tracked_path(request.url.path), status, time.perf_counter() - started) # DEBUG TEMPORAL: guarda el detalle de los fallos de App Check para diagnosticarlos. # verify_app_check ahora devuelve 404 (no 401) en cualquier fallo, así que # el disparador de esta captura tiene que ser 404, no 401. p = request.url.path if status == 404 and (p.startswith("/v1") or p.startswith("/v2")): await _capture_401(request) # ────────────────────────────────────────────── # Firebase App Check # ────────────────────────────────────────────── PROJECT_NUMBER = "748155614527" APP_ID = "1:748155614527:android:c29d203cf594986dda8f8a" JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks" _jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600) # ────────────────────────────────────────────── # Cache de validez de App Check # ────────────────────────────────────────────── # El token de App Check dura 7 días (config del cliente, fuera de este repo). # Verificar la firma RSA (CPU-bound) en cada request de esos 7 días es # desperdicio: el mismo patrón _cached/_lock/_store que usa el resto del # archivo no aplica igual acá porque no queremos guardar el token crudo como # clave, así que este cache vive aparte con la clave hasheada. # Clave: sha256(token) — nunca el token crudo. Valor: timestamp valido_hasta. _appcheck_cache: dict[str, float] = {} APPCHECK_CACHE_MAX_TTL = 3 * 24 * 3600 # techo: nunca cachear más de 3 días APPCHECK_CACHE_CLEANUP_INTERVAL = 60 * 60 # limpieza cada 1 hora def invalidate_appcheck_token(token: str) -> None: """Borra manualmente un token del cache de App Check (p.ej. si se detecta que fue comprometido y no se quiere esperar a que expire su entrada). No falla si el token no estaba cacheado.""" _appcheck_cache.pop(hashlib.sha256(token.encode()).hexdigest(), None) async def _appcheck_cache_cleanup(): """Tarea periódica (cada 1 hora, ciclo independiente del flush de 120s de stats.py) que purga del cache las entradas ya vencidas. Sin esto el dict crece indefinidamente con tokens que ya no van a volver a usarse.""" while True: await asyncio.sleep(APPCHECK_CACHE_CLEANUP_INTERVAL) ahora = time.time() vencidos = [k for k, valido_hasta in _appcheck_cache.items() if valido_hasta <= ahora] for k in vencidos: _appcheck_cache.pop(k, None) async def verify_app_check(x_firebase_appcheck: str = Header(None)): # DISABLE_APP_CHECK tiene tres estados: # "1" → desactivado del todo (parche histórico): no valida nada. # "shadow" → valida y clasifica el motivo igual que en modo estricto, pero # NUNCA bloquea. Sirve para medir cuánta gente fallaría antes de # activar el bloqueo real, sin arriesgar usuarios reales (caso # conocido: redes WiFi que bloquean el alcance a Play Integrity). # (nada) → modo estricto: bloquea con 404. mode = os.getenv("DISABLE_APP_CHECK") if mode == "1": return shadow = mode == "shadow" # 404 en vez de 401 en modo estricto: a quien golpee sin token válido, el # endpoint le parece inexistente. Un 401 delata que hay algo ahí protegido y # digno de atacar; un 404 no invita a insistir. def _reject(reason: str): stats.record_auth_failure(reason) if shadow: return raise HTTPException(status_code=404, detail="Not Found") if not x_firebase_appcheck: return _reject("sin_token") token_hash = hashlib.sha256(x_firebase_appcheck.encode()).hexdigest() # Cache-hit: este token ya se verificó antes y sigue vigente. No hace falta # volver a validar la firma RSA (CPU-bound) ni pasar por el threadpool — se # resuelve directo en el event loop. Este es el camino que toma la mayoría # de los requests una vez que el cache se calienta. valido_hasta = _appcheck_cache.get(token_hash) if valido_hasta is not None and valido_hasta > time.time(): stats.record_accepted_request() stats.record_appcheck_hit() return # Cache-miss: token nuevo o vencido en el cache. La verificación de firma es # CPU-bound y cara, así que se manda al threadpool para no bloquear el event # loop mientras se calcula. def _verificar_firma(): signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck) return jwt.decode( x_firebase_appcheck, signing_key.key, algorithms=["RS256"], audience=f"projects/{PROJECT_NUMBER}", issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}", ) try: claims = await run_in_threadpool(_verificar_firma) if claims.get("sub") != APP_ID: return _reject("sub_no_coincide") except jwt.exceptions.PyJWTError as e: # Nombre real de la excepción de PyJWT (ExpiredSignatureError, DecodeError, # InvalidAudienceError, PyJWKClientError...) en vez de adivinar el motivo. return _reject(type(e).__name__) # Llegar hasta acá significa que no pasó por ningún _reject(): token presente, # firma/audience/issuer válidos y sub coincide con la app. Request aceptada. # Se cachea el éxito (nunca los fallos) hasta el mínimo entre el exp real del # token y el techo de 3 días — nunca le damos al cache más vida que la que el # token realmente tiene según su propio claim. _appcheck_cache[token_hash] = min(claims["exp"], time.time() + APPCHECK_CACHE_MAX_TTL) stats.record_accepted_request() stats.record_appcheck_miss() # ────────────────────────────────────────────── # DEBUG TEMPORAL — App Check: por qué fallan los 401 # ────────────────────────────────────────────── # Ante un 401 en /v1|/v2, guarda el detalle en la colección rodante `appcheck_401` # (30 slots que se reescriben), con el MOTIVO clasificado para ver el patrón: # sin_token → la app no consiguió token (red bloquea Google / Play Integrity) # token_no_jwt → dummy/error de App Check (no obtuvo token real) # token_expirado → token vencido # sub_no_coincide → token de otra app # firma_o_aud_iss → JWT en forma OK pero rechazado (firma/audience/issuer) # Throttle 2s para no floodear Firestore. QUITAR cuando se resuelva. _last_401_capture = 0.0 async def _capture_401(request) -> None: global _last_401_capture db = history.get_db() if db is None: return now = time.time() if now - _last_401_capture < 2: return _last_401_capture = now token = request.headers.get("x-firebase-appcheck") info = { "ts": int(now), "path": request.url.path, "userAgent": request.headers.get("user-agent"), "hasToken": token is not None, "disableAppCheck": os.getenv("DISABLE_APP_CHECK"), } reason = "sin_token" if token: info["tokenLen"] = len(token) try: claims = jwt.decode(token, options={"verify_signature": False}) info["claims"] = {k: claims.get(k) for k in ("sub", "aud", "iss", "exp", "iat")} sub_ok = claims.get("sub") == APP_ID exp = claims.get("exp") expired = bool(exp and exp < int(now)) info["subMatches"] = sub_ok info["expired"] = expired reason = ( "token_expirado" if expired else "sub_no_coincide" if not sub_ok else "firma_o_aud_iss" ) except Exception as e: info["decodeError"] = f"{type(e).__name__}: {e}" info["tokenPreview"] = token[:48] reason = "token_no_jwt" info["reason"] = reason slot = int(now) % 30 try: await db.collection("appcheck_401").document(f"slot_{slot:02d}").set(info) except Exception as e: logger.error("captura 401 falló: %s", e) # ────────────────────────────────────────────── # Helpers # ────────────────────────────────────────────── def _parse_bcv_rate(text: str) -> float | None: """Convierte '36,85' o '36.853,12' a float.""" cleaned = text.strip().replace("Bs.", "").replace("S", "").strip() # Formato venezolano: punto como separador de miles, coma como decimal cleaned = cleaned.replace(".", "").replace(",", ".") try: return float(cleaned) except ValueError: return None def _classify_fetch_error(e: Exception) -> str: """Clasifica el fallo de un fetcher externo (BCV, P2P) en un motivo legible para las stats — así el dashboard distingue timeout de caída de conexión de un cambio de formato en la respuesta.""" if isinstance(e, httpx.TimeoutException): return "timeout" if isinstance(e, httpx.HTTPStatusError): return f"http_error_{e.response.status_code}" if isinstance(e, httpx.RequestError): return "connection_error" return type(e).__name__ # ────────────────────────────────────────────── # Fetchers # ────────────────────────────────────────────── async def fetch_bcv(force: bool = False) -> dict: # force=True omite el caché: lo usa el webhook cuando changedetection.io # avisa que la página del BCV cambió, para traer la tasa nueva de inmediato. if not force: cached = _cached("bcv", BCV_TTL) if cached: return cached async with _lock("bcv"): # Double-check: mientras esperábamos el lock, otro ya pudo haber refrescado if not force: cached = _cached("bcv", BCV_TTL) if cached: return cached headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept-Language": "es-VE,es;q=0.9", } # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV) try: response = await _http_nv.get("https://www.bcv.org.ve/", headers=headers) response.raise_for_status() except (httpx.TimeoutException, httpx.RequestError, httpx.HTTPStatusError) as e: reason = _classify_fetch_error(e) stats.record_fetch_error("bcv", reason, str(e)) logger.warning("BCV fetch falló (%s): %s", reason, e) raise HTTPException(status_code=503, detail="No se pudo contactar al BCV") from e soup = BeautifulSoup(response.text, "lxml") currency_ids = { "Usd": "dolar", "Eur": "euro", "Cny": "yuan", "Try": "lira", "Rub": "rublo", } rates = {} for suffix, div_id in currency_ids.items(): div = soup.find(id=div_id) tag = div.find("strong") if div else None rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None if all(v is None for v in rates.values()): stats.record_fetch_error("bcv", "parse_error", "todas las tasas dieron None") logger.error("BCV: all rates are None — scraping failed") raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV") stats.record_fetch_success("bcv") updated_tag = soup.find("span", {"class": re.compile(r"date-display")}) updated_at = updated_tag.text.strip() if updated_tag else None data = {**rates, "updatedAt": updated_at} _store("bcv", data) # Mantiene {current, previous} para la "tasa del viernes". Solo corre en un # scrape real (no en cache hits) y con fecha valor presente, así que el costo # en Firestore es raro y no se corrompe el estado si falla leer la fecha. if history.is_enabled() and data.get("updatedAt"): try: previous = await history.update_bcv_state(data) _store("bcv_previous", previous or {}) except Exception as e: logger.warning("update_bcv_state falló: %s", e) return data async def _bcv_previous() -> dict | None: """Tasa BCV inmediatamente anterior (la 'del viernes' durante el fin de semana). Cacheada en memoria; se relee de Firestore al vencer el TTL del BCV. {} = sin dato.""" cached = _cached("bcv_previous", BCV_TTL) if cached is not None: return cached or None previous = await history.get_bcv_previous() _store("bcv_previous", previous or {}) return previous async def fetch_p2p() -> dict: cached = _cached("p2p", P2P_TTL) if cached: return cached async with _lock("p2p"): # Double-check: mientras esperábamos el lock, otro ya pudo haber refrescado cached = _cached("p2p", P2P_TTL) if cached: return cached headers = { "User-Agent": "Mozilla/5.0", "Content-Type": "application/json", } body_base = { "fiat": "VES", "page": 1, "rows": 20, "asset": "USDT", "countries": [], "proMerchantAds": False, "shieldMerchantAds": False, "publisherType": None, "payTypes": [], "classifies": ["mass", "profession"], } # BUY = compradores de USDT (tab "Vender" en Binance, ordenado de mayor a menor) # SELL = vendedores de USDT (tab "Comprar" en Binance, ordenado de menor a mayor) buy_ads_res, sell_ads_res = await asyncio.gather( _http.post( "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", json={**body_base, "tradeType": "BUY"}, headers=headers, ), _http.post( "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", json={**body_base, "tradeType": "SELL"}, headers=headers, ), ) buy_ads_res.raise_for_status() sell_ads_res.raise_for_status() def first_eligible_price(ads: list) -> float | None: """ 1. Salta los primeros 3 anuncios y promedia precios de ads[3..5] como referencia. 2. fiat_ref = promedio * 20 (~20 USDT en VES). 3. Devuelve el primer anuncio donde minSingleTransAmount <= fiat_ref <= maxSingleTransAmount. Fallback: primer anuncio desde índice 3 con min <= fiat_ref (sin chequeo de max). """ if not ads: return None sample = [] for item in ads[3:6]: try: sample.append(float(item["adv"]["price"])) except (KeyError, ValueError, TypeError): pass if not sample: return None return round(sum(sample) / len(sample), 2) p2p_buy = first_eligible_price(sell_ads_res.json().get("data", [])) p2p_sell = first_eligible_price(buy_ads_res.json().get("data", [])) data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell} _store("p2p", data) return data async def fetch_p2p_safe() -> dict: try: data = await fetch_p2p() stats.record_fetch_success("p2p") return data except Exception as e: reason = _classify_fetch_error(e) stats.record_fetch_error("p2p", reason, str(e)) logger.error("fetch_p2p failed: %s", e, exc_info=True) return {"p2pBuyMax": None, "p2pSellMax": None} # ────────────────────────────────────────────── # v2 — Fetchers aislados (no afectan a /v1) # ────────────────────────────────────────────── async def fetch_p2p_v2(fiat: str) -> dict: cache_key = f"p2p_v2:{fiat}" cached = _cached(cache_key, P2P_V2_TTL) if cached: return cached async with _lock(cache_key): cached = _cached(cache_key, P2P_V2_TTL) if cached: return cached headers = { "User-Agent": "Mozilla/5.0", "Content-Type": "application/json", } body_base = { "fiat": fiat, "page": 1, "rows": 20, "asset": "USDT", "countries": [], "proMerchantAds": False, "shieldMerchantAds": False, "publisherType": None, "payTypes": [], "classifies": ["mass", "profession"], } logger.info("fetch_p2p_v2 fiat=%s", fiat) buy_ads_res, sell_ads_res = await asyncio.gather( _http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "BUY"}, headers=headers), _http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "SELL"}, headers=headers), ) buy_ads_res.raise_for_status() sell_ads_res.raise_for_status() def first_eligible_price(ads: list) -> float | None: if not ads: return None sample = [] for item in ads[3:6]: try: sample.append(float(item["adv"]["price"])) except (KeyError, ValueError, TypeError): pass if not sample: return None return round(sum(sample) / len(sample), 2) p2p_buy = first_eligible_price(sell_ads_res.json().get("data", [])) p2p_sell = first_eligible_price(buy_ads_res.json().get("data", [])) data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell} _store(cache_key, data) return data async def fetch_p2p_v2_safe(fiat: str) -> dict: try: data = await fetch_p2p_v2(fiat) stats.record_fetch_success("p2p_v2") return data except Exception as e: reason = _classify_fetch_error(e) stats.record_fetch_error("p2p_v2", reason, f"fiat={fiat}: {e}") logger.error("fetch_p2p_v2(%s) failed: %s", fiat, e, exc_info=True) return {"p2pBuyMax": None, "p2pSellMax": None} # ────────────────────────────────────────────── # v2 — Caso especial BR: Binance P2P no sirve anuncios públicos para USDT/BRL # (confirmado en vivo: `data: []` de forma consistente). En vez de un fallback # genérico para todos los países, se usa el ticker spot público de OKX # (sin autenticación) solo para este país, igual que VE tiene su propia rama # especial más abajo en rates_v2. # ────────────────────────────────────────────── OKX_TICKER_URL = "https://www.okx.com/api/v5/market/ticker" async def fetch_okx_brl() -> dict: cache_key = "okx_v2:BRL" cached = _cached(cache_key, P2P_V2_TTL) if cached: return cached async with _lock(cache_key): # Double-check: mientras esperábamos el lock, otro ya pudo haber refrescado cached = _cached(cache_key, P2P_V2_TTL) if cached: return cached logger.info("fetch_okx_brl instId=USDT-BRL") response = await _http.get(OKX_TICKER_URL, params={"instId": "USDT-BRL"}) response.raise_for_status() payload = response.json() if payload.get("code") != "0": raise ValueError(f"OKX code={payload.get('code')!r} msg={payload.get('msg')!r}") rows = payload.get("data") or [] if not rows: raise ValueError("OKX devolvió data vacío para USDT-BRL") ticker = rows[0] try: ask = float(ticker["askPx"]) bid = float(ticker["bidPx"]) except (KeyError, ValueError, TypeError) as e: raise ValueError(f"OKX ticker con campos inválidos: {ticker}") from e # askPx = precio al que alguien COMPRA USDT (análogo a p2pBuyMax). # bidPx = precio al que alguien VENDE USDT (análogo a p2pSellMax). # Mismo contrato de salida que fetch_p2p_v2 para que rates_v2 no tenga # que distinguir el origen del dato al armar la respuesta. data = {"p2pBuyMax": round(ask, 4), "p2pSellMax": round(bid, 4)} _store(cache_key, data) return data async def fetch_okx_brl_safe() -> dict: try: data = await fetch_okx_brl() stats.record_fetch_success("okx_brl") return data except Exception as e: reason = _classify_fetch_error(e) stats.record_fetch_error("okx_brl", reason, str(e)) logger.error("fetch_okx_brl failed: %s", e, exc_info=True) return {"p2pBuyMax": None, "p2pSellMax": None} # ────────────────────────────────────────────── # Muestreador de histórico: cada 15 min registra BCV + USDT de TODAS las fiats, # sin depender de que un usuario de ese país pida tasas. Los fetchers ya hacen # el registro (con dedupe por valor), así que aquí solo se fuerza el fetch. # # Notas de operación: # - Con --workers 2 el bucle corre en ambos procesos: el jitter inicial los # desincroniza y la identidad por bucket de 5 min evita duplicados en la DB. # El costo extra son ~4 llamadas/min a Binance en el peor caso — irrelevante. # - Si el Space duerme (sin tráfico), el muestreo se pausa: quedan huecos en el # histórico, no errores. Con usuarios activos el Space casi nunca duerme. # ────────────────────────────────────────────── HISTORY_SAMPLE_INTERVAL = 60 * 15 HISTORY_SAMPLE_SPACING = 2 # segundos entre fiats para no ametrallar a Binance async def _history_sampler(): import random await asyncio.sleep(random.uniform(5, 120)) # desincronizar los 2 workers fiats = sorted(set(SUPPORTED_COUNTRIES.values())) while True: try: bcv = await fetch_bcv() history.record_bcv(bcv) # dedupe por valor: solo graba si la tasa cambió except Exception as e: logger.warning("sampler: fetch_bcv falló: %s", e) for fiat in fiats: # BR: mismo caso especial que en rates_v2 — Binance P2P no tiene # anuncios para USDT/BRL, se usa el ticker spot de OKX en su lugar. data = await fetch_okx_brl_safe() if fiat == "BRL" else await fetch_p2p_v2_safe(fiat) history.record_p2p(fiat, data.get("p2pBuyMax"), data.get("p2pSellMax")) await asyncio.sleep(HISTORY_SAMPLE_SPACING) await asyncio.sleep(HISTORY_SAMPLE_INTERVAL) def validate_country(country: str | None) -> str: if not country: raise HTTPException(status_code=400, detail="Query param 'country' es requerido") if not COUNTRY_CODE_PATTERN.match(country): raise HTTPException( status_code=400, detail="Código de país debe ser ISO 3166-1 alpha-2 (2 letras mayúsculas)", ) if country not in SUPPORTED_COUNTRIES: raise HTTPException(status_code=400, detail=f"País '{country}' no está soportado en esta versión") return country # ────────────────────────────────────────────── # Endpoints # ────────────────────────────────────────────── @app.get("/") async def root(): return {"status": "ok", "service": "Tazas API"} @app.get("/v1/rates", dependencies=[Depends(verify_app_check)]) async def rates(): bcv_data, p2p_data = await asyncio.gather( fetch_bcv(), fetch_p2p_safe(), ) return {**bcv_data, **p2p_data} @app.get("/v1/bcv", dependencies=[Depends(verify_app_check)]) async def bcv(): return await fetch_bcv() @app.get("/v1/p2p", dependencies=[Depends(verify_app_check)]) async def p2p(): return await fetch_p2p() # ────────────────────────────────────────────── # v2 — Endpoint multi-país (aislado de /v1) # ────────────────────────────────────────────── @app.get("/v2/rates", dependencies=[Depends(verify_app_check)]) async def rates_v2(country: str | None = None): cc = validate_country(country) fiat = SUPPORTED_COUNTRIES[cc] logger.info("/v2/rates country=%s fiat=%s", cc, fiat) if cc == "VE": bcv_data, ve_p2p, prev = await asyncio.gather( fetch_bcv(), fetch_p2p_v2_safe("VES"), _bcv_previous(), ) return { "venezuela": {**bcv_data, **ve_p2p, "previous": prev}, "local": None, } # BR: Binance P2P no sirve anuncios públicos para USDT/BRL (data: [] confirmado # en vivo). Caso especial: se consulta el ticker spot de OKX en su lugar. local_fetch = fetch_okx_brl_safe() if cc == "BR" else fetch_p2p_v2_safe(fiat) bcv_data, ve_p2p, local_p2p, prev = await asyncio.gather( fetch_bcv(), fetch_p2p_v2_safe("VES"), local_fetch, _bcv_previous(), ) return { "venezuela": {**bcv_data, **ve_p2p, "previous": prev}, "local": { "countryCode": cc, "currency": fiat, "usdtBuy": local_p2p.get("p2pBuyMax"), "usdtSell": local_p2p.get("p2pSellMax"), "updatedAt": None, }, } # ────────────────────────────────────────────── # v2 — Histórico (persistido en Firestore) # ────────────────────────────────────────────── @app.get("/v2/history", dependencies=[Depends(verify_app_check)]) async def history_v2(country: str | None = None, days: int = 30): """ Histórico de tasas de los últimos `days` días (máx 35). - bcv: puntos {t, usd, eur, cny, try, rub} — el BCV cambia ~1 vez/día. - p2p: puntos {t, buy, sell} de USDT/VES — fluctúa durante el día. - local: puntos {t, buy, sell} de USDT/{fiat} — null para VE/dolarizados. `t` es epoch en segundos (UTC), redondeado a buckets de 5 minutos. """ cc = validate_country(country) if not history.is_enabled(): raise HTTPException(status_code=503, detail="Histórico no disponible") days = max(1, min(days, 35)) fiat = SUPPORTED_COUNTRIES[cc] include_local = cc != "VE" tasks = [history.get_history("BCV", days), history.get_history("VES", days)] if include_local: tasks.append(history.get_history(fiat, days)) results = await asyncio.gather(*tasks) return { "days": days, "bcv": results[0], "p2p": results[1], "local": { "countryCode": cc, "currency": fiat, "points": results[2], } if include_local else None, } # ────────────────────────────────────────────── # Webhook — refresco inmediato del BCV (disparado por changedetection.io) # ────────────────────────────────────────────── # GET + POST para que sirva cualquier pinger externo gratuito (cron-job.org, # UptimeRobot, GitHub Actions, etc.), incluidos los que solo hacen GET. @app.api_route("/webhook/bcv-refresh", methods=["GET", "POST"]) async def bcv_refresh_webhook( token: str | None = Query(default=None), x_webhook_token: str | None = Header(default=None), ): """ Un servicio externo (cron gratuito) golpea este endpoint cada pocos minutos. Fuerza un scrape fresco del BCV (ignora el caché de 4h) y registra el valor nuevo en el histórico de inmediato. record_bcv deduplica por valor: si el BCV no cambió, no escribe nada. De paso, el ping mantiene despierto el Space (para que el muestreador interno de USDT también corra). Protegido por secreto compartido (env WEBHOOK_SECRET), vía query `?token=` o header `X-Webhook-Token`. No usa App Check: el llamador es externo. """ secret = os.getenv("WEBHOOK_SECRET") if not secret: raise HTTPException(status_code=404, detail="Not Found") provided = x_webhook_token or token or "" # compare_digest: comparación de tiempo constante (no filtra el secreto por timing). # 404 en vez de 401: a un escáner sin el token, el endpoint le parece inexistente. if not hmac.compare_digest(provided, secret): raise HTTPException(status_code=404, detail="Not Found") # Throttle: con token válido pero llamadas muy seguidas, servir el último valor # sin re-scrapear. Acota el scrape a 1 cada FORCED_REFRESH_MIN_INTERVAL seg. global _last_forced_refresh now = time.time() if now - _last_forced_refresh < FORCED_REFRESH_MIN_INTERVAL: cached = _cached("bcv", BCV_TTL) or {} return {"status": "throttled", "bcvUsd": cached.get("bcvUsd")} _last_forced_refresh = now data = await fetch_bcv(force=True) history.record_bcv(data) return { "status": "refreshed", "bcvUsd": data.get("bcvUsd"), "updatedAt": data.get("updatedAt"), }