- antibot.py: disposable-домены (вендор 8k, github disposable-email-domains, обновление curl); validate_captcha (только при SMARTCAPTCHA_SERVER_KEY; API лёг → fail-open, режим CAPTCHA_FAIL_MODE=closed для активной атаки); per-IP 5 регистраций/час - /api/register: порядок дешёвое→дорогое (IP → disposable → капча), каждая причина в audit - /api/captcha-config + условный виджет в register.html; CSP расширяется на smartcaptcha.yandexcloud.net ТОЛЬКО при заданном ключе (иначе строгий self) - 8 red-green тестов; без env-ключей поведение регистрации НЕ меняется (фичефлаг спит) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
85 lines
3.7 KiB
Python
85 lines
3.7 KiB
Python
"""Ф4 публичного запуска: анти-бот регистрации. Все механизмы за фичефлагами —
|
|
без env-ключей поведение регистрации НЕ меняется (invite-only режим сегодня).
|
|
|
|
1) Disposable-домены: data/disposable_domains.txt (вендор github
|
|
disposable-email-domains, 8k доменов; обновление — curl, см. шапку файла).
|
|
2) Yandex SmartCaptcha: серверная валидация ТОЛЬКО при SMARTCAPTCHA_SERVER_KEY.
|
|
Недоступность API Яндекса → fail-open + warning: лёгшая капча не должна
|
|
устраивать DoS нашей регистрации (обратный выбор — fail-closed — оправдан
|
|
только под активной бот-атакой; тогда переключить CAPTCHA_FAIL_MODE=closed).
|
|
3) Per-IP лимит регистраций 5/час: sync-dict (один event loop → атомарно,
|
|
тот же паттерн, что _chat_rate в main).
|
|
"""
|
|
|
|
import logging
|
|
import os
|
|
import time
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
_log = logging.getLogger("smeta_web")
|
|
|
|
_DOMAINS_FILE = Path(__file__).parent / "data" / "disposable_domains.txt"
|
|
|
|
REG_IP_LIMIT = 5
|
|
REG_IP_WINDOW = 3600
|
|
_reg_rate: dict[str, list[float]] = {}
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def _disposable_set() -> frozenset[str]:
|
|
try:
|
|
lines = _DOMAINS_FILE.read_text(encoding="utf-8").splitlines()
|
|
return frozenset(l.strip().lower() for l in lines
|
|
if l.strip() and not l.startswith("#"))
|
|
except OSError:
|
|
_log.warning("antibot: %s не читается — disposable-блок выключен", _DOMAINS_FILE)
|
|
return frozenset()
|
|
|
|
|
|
def is_disposable_email(email: str) -> bool:
|
|
if "@" not in (email or ""):
|
|
return False
|
|
domain = email.rsplit("@", 1)[1].strip().lower()
|
|
return domain in _disposable_set()
|
|
|
|
|
|
def _captcha_api(server_key: str, token: str, ip: str) -> dict:
|
|
"""Выделено для тестов. POST к SmartCaptcha validate."""
|
|
import httpx
|
|
r = httpx.post("https://smartcaptcha.yandexcloud.net/validate",
|
|
data={"secret": server_key, "token": token, "ip": ip},
|
|
timeout=5)
|
|
return r.json()
|
|
|
|
|
|
def validate_captcha(token: str, ip: str) -> bool | None:
|
|
"""None = капча выключена (нет ключа) — вызывающий пропускает проверку.
|
|
True/False = вердикт; исключение API → fail-open True (см. docstring модуля)."""
|
|
server_key = os.environ.get("SMARTCAPTCHA_SERVER_KEY", "").strip()
|
|
if not server_key:
|
|
return None
|
|
try:
|
|
resp = _captcha_api(server_key, token or "", ip or "")
|
|
return resp.get("status") == "ok"
|
|
except Exception: # noqa: BLE001
|
|
if os.environ.get("CAPTCHA_FAIL_MODE", "open").strip().lower() == "closed":
|
|
_log.warning("antibot: SmartCaptcha недоступна → fail-CLOSED (регистрация отклонена)")
|
|
return False
|
|
_log.warning("antibot: SmartCaptcha недоступна → fail-open (регистрация пропущена)")
|
|
return True
|
|
|
|
|
|
def register_ip_allowed(ip: str) -> bool:
|
|
"""5 регистраций/час/IP. Пустой ip (нет заголовка) — пропускаем (не группируем всех в '')."""
|
|
if not ip:
|
|
return True
|
|
now = time.time()
|
|
times = [t for t in _reg_rate.get(ip, []) if now - t < REG_IP_WINDOW]
|
|
if len(times) >= REG_IP_LIMIT:
|
|
_reg_rate[ip] = times
|
|
return False
|
|
times.append(now)
|
|
_reg_rate[ip] = times
|
|
return True
|