From 276237211558517532070e6b27956636c6330815 Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 21 Jul 2026 19:03:41 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20TG-=D1=83=D0=B2=D0=B5=D0=B4=D0=BE=D0=BC?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D1=83=20=D0=BE=20=D0=BD=D0=BE=D0=B2=D0=BE?= =?UTF-8?q?=D0=B9=20=D1=80=D0=B5=D0=B3=D0=B8=D1=81=D1=82=D1=80=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D0=B8=20(=D1=82=D0=BE=D1=82=20=D0=B6=D0=B5=20=D0=BA?= =?UTF-8?q?=D0=B0=D0=BD=D0=B0=D0=BB,=20=D1=87=D1=82=D0=BE=20=D0=BA=D0=B0?= =?UTF-8?q?=D0=BD=D0=B0=D1=80=D0=B5=D0=B9=D0=BA=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Запрос: слать новые регистрации в «К-смета бот» (Telegram). Переиспользуем alerts.send_tg (ключи ALERT_TG_*, что и канарейка). Через FastAPI BackgroundTasks — шлётся ПОСЛЕ ответа юзеру (не тормозит регистрацию), send_tg никогда не raise / no-op без ключей. Только на успешной регистрации (после log_action); отказы (disposable/captcha/IP) не шлют. Telegram сам ставит время. 2 red-green теста (успех→1 алерт с email; отказ→0). Бамп 2026-07-21b. Co-Authored-By: Claude Opus 4.8 (1M context) --- main.py | 16 +++++++++++++--- tests/test_register_antibot.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 4bce976..fa3748d 100644 --- a/main.py +++ b/main.py @@ -11,7 +11,7 @@ from pathlib import Path logger = logging.getLogger("smeta_web") -from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile +from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Request, UploadFile from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse from fastapi.staticfiles import StaticFiles @@ -187,7 +187,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-07-21a" +APP_VERSION = "2026-07-21b" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -564,7 +564,7 @@ async def refresh_token(request: Request): @app.post("/api/register") -async def register(request: Request): +async def register(request: Request, background: BackgroundTasks): body = await request.json() email = body.get("email", "") password = body.get("password", "") @@ -592,6 +592,16 @@ async def register(request: Request): log_action(email, "register", "POST", "/api/register", None, client_ip, 200) + # Уведомление оператору о новой регистрации — в тот же Telegram-канал, что канарейка + # (alerts.send_tg, ключи ALERT_TG_*). BackgroundTasks: шлётся ПОСЛЕ ответа юзеру (не + # добавляет задержки), send_tg никогда не raise (без ключей — no-op). Telegram сам + # проставит время сообщения, потому в тексте его не дублируем. + import alerts + background.add_task( + alerts.send_tg, + f"🆕 smeta-web: новая регистрация — {email} " + f"(IP {client_ip or '—'}, ожидает подтверждения email)") + # Send verification code via email code = result.get("code", "") if code: diff --git a/tests/test_register_antibot.py b/tests/test_register_antibot.py index 8153e47..cc795c5 100644 --- a/tests/test_register_antibot.py +++ b/tests/test_register_antibot.py @@ -125,3 +125,32 @@ def test_register_normal_ok_without_captcha_keys(client_env, monkeypatch): "email": "human@yandex.ru", "password": "secret1", "invite": invite}) assert r.status_code == 200 assert db.get_user_by_email("human@yandex.ru") is not None + + +def test_register_sends_tg_notification(client_env, monkeypatch): + """Успешная регистрация → TG-алерт оператору (тот же канал, что канарейка) с email. + Через BackgroundTasks (не блокирует ответ; TestClient дожидается фоновых задач). + Mutation: убрать background.add_task → send_tg не вызван → упадёт.""" + db, auth, client, invite = client_env + monkeypatch.setattr("email_service.send_verification_code", lambda e, c: True) + sent = [] + import alerts + monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True) + r = client.post("/api/register", json={ + "email": "newbie@yandex.ru", "password": "secret1", "invite": invite}) + assert r.status_code == 200 + assert len(sent) == 1 # ровно один алерт на регистрацию + assert "newbie@yandex.ru" in sent[0] # с email нового юзера + + +def test_failed_register_no_tg_notification(client_env, monkeypatch): + """Отклонённая регистрация (disposable) НЕ шлёт алерт — не спамим оператора отказами. + Mutation: слать алерт до проверки успеха → упадёт.""" + db, auth, client, invite = client_env + sent = [] + import alerts + monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True) + r = client.post("/api/register", json={ + "email": "bot@mailinator.com", "password": "secret1", "invite": invite}) + assert r.status_code == 400 + assert sent == []