Harden Telegram login, callback spinner and Mini App escaping
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

- skin: tg_login rejects cross-site Origin; hash compared as bytes; tg_* cookies Secure
- bot: answer callback on fast handler failure; cap MENU_OWNER; image retries stop on
  terminal errors; upstream error texts sent without HTML parse mode
- Mini App: escape ids in action buttons and task rows; refresh in Neurolab empty state
- tests for spinner and tg login hardening
This commit is contained in:
2026-10-31 02:16:16 +03:00
parent af292ff15d
commit a05a36aa7b
5 changed files with 122 additions and 15 deletions
+23 -6
View File
@@ -2362,6 +2362,10 @@ async def gw_image(prompt, model="gpt-image-1"):
break
last_try = e
log.warning(f"gw_image attempt fail [{m}]: {str(e)[:80]}")
# 403 «no access to model» / 503 «модель недоступна» не лечатся паузой 3+8с —
# сразу в фолбэк-цепочку, без двух бесполезных повторов на каждую модель.
if getattr(e, "terminal", False) or getattr(e, "status", None) in (400, 401, 403, 404, 503):
break
if d is None:
last = last_try or last
continue
@@ -2813,6 +2817,8 @@ async def render_menu(bot, uid, chat_id, message=None):
if sent is None:
sent = await bot.send_message(chat_id, txt, reply_markup=kb, parse_mode=ParseMode.HTML)
if sent is not None and chat_id != uid: # группа: кнопки этого меню — только автору
if len(MENU_OWNER) > 5000: # пишется на каждое групповое меню и нигде не чистился — утечка
MENU_OWNER.clear()
MENU_OWNER[(chat_id, sent.message_id)] = uid
return sent
@@ -2882,6 +2888,14 @@ async def _cb_spinner_mw(handler, event, data):
_t = asyncio.create_task(_late_answer())
try:
return await handler(event, data)
except Exception:
# хендлер упал раньше 2с (битый callback_data, Telegram 400 и т.п.) — finally снимет
# _late_answer, и у юзера навсегда крутится часик. Гасим спиннер сразу, ошибку пробрасываем.
try:
await event.answer()
except Exception:
pass
raise
finally:
_t.cancel()
@@ -8860,7 +8874,10 @@ async def group_reply(m: Message):
db_refund(uid, "chat")
msg = (str(e) if getattr(e, "stability_code", None) else
"Модель сейчас не ответила. Попробуй позже или выбери другую модель в личном чате с ботом.")
await m.reply(msg, parse_mode=None)
try:
await m.reply(msg, parse_mode=None)
except Exception:
pass # исходное сообщение удалено/чат закрыт — не плодим второй traceback
return
_task = asyncio.create_task(chat_summary_refresh(m.chat.id))
_VIDEO_TASKS.add(_task)
@@ -8967,7 +8984,7 @@ async def _music_process(job):
res = await _afm.generate_music(arg, instrumental=instrumental)
if not res.get("ok"):
_persona_kv(kvk, str(used)) # возврат лимита
await m.answer("❌ Не вышло сгенерировать: %s" % (res.get("error") or "?"))
await m.answer("❌ Не вышло сгенерировать: %s" % (res.get("error") or "?"), parse_mode=None) # текст апстрима, может быть <html>
return
for t in res["tracks"][:2]:
try:
@@ -8976,10 +8993,10 @@ async def _music_process(job):
performer="Udio · иишко",
message_thread_id=m.message_thread_id)
except Exception as e:
await m.answer("❌ Аудио не отправилось: %s\n%s" % (str(e)[:80], t["audioUrl"]))
await m.answer("❌ Аудио не отправилось: %s\n%s" % (str(e)[:80], t["audioUrl"]), parse_mode=None)
except Exception as e:
try:
await m.answer("❌ Ошибка: %s" % str(e)[:100])
await m.answer("❌ Ошибка: %s" % str(e)[:100], parse_mode=None)
except Exception:
pass
@@ -14363,7 +14380,7 @@ async def _file_intake(m: Message, uid: int):
except Exception as e:
log.exception("file_intake fail uid=%s", uid)
try:
await m.answer("📎 Ошибка загрузки файла: " + str(e)[:120])
await m.answer("📎 Ошибка загрузки файла: " + str(e)[:120], parse_mode=None)
except Exception:
pass
@@ -14502,7 +14519,7 @@ async def sb_upload(m: Message, uid: int):
except Exception as e:
log.exception("sb_upload fail")
try:
await m.answer("📎 Ошибка загрузки: " + str(e)[:120])
await m.answer("📎 Ошибка загрузки: " + str(e)[:120], parse_mode=None)
except Exception:
pass
+4 -4
View File
@@ -2627,7 +2627,7 @@ const ceLabels={open:'Свободно',claimed:'В работе',submitted:'Н
const ceActions={create:'Разместить задание',transfer:'Перевести монеты',grant:'Выдать из фонда',claim:'Взять в работу',release:'Отказаться',submit:'Сдать результат',accept:'Принять и оплатить',cancel:'Отменить задание',dispute:'Открыть спор',resolve:'Решить спор'};
const ceStorage=(uid=ceState?.uid)=>`community-pending:${uid}`;
function cePending(uid){try{return JSON.parse(localStorage.getItem(ceStorage(uid))||'null')}catch{return null}}
function ceButton(action,id=0){return `<button class="button ghost" type="button" data-ce="${action}" data-ce-id="${id}">${ceActions[action]}</button>`}
function ceButton(action,id=0){return `<button class="button ghost" type="button" data-ce="${action}" data-ce-id="${esc(id)}">${ceActions[action]}</button>`}
function questsView(data,showIntro=true){
const rows=(data.quests||[]).map(q=>{
const target=Math.max(1,num(q.target)),progress=Math.max(0,num(q.progress));
@@ -2678,10 +2678,10 @@ if(worker&&t.status==='claimed')actions+=ceButton('submit',t.id)+ceButton('relea
if(owner&&t.status==='submitted')actions+=ceButton('accept',t.id);
if((owner||worker)&&['claimed','submitted'].includes(t.status))actions+=ceButton('dispute',t.id);
if(data.is_admin&&t.status==='disputed'&&!owner&&!worker)actions+=ceButton('resolve',t.id);
return `<article class="section" style="overflow-wrap:anywhere"><div class="row"><h3>#${t.id} · ${esc(t.title)}</h3><span class="tag">${esc(ceLabels[t.status]||t.status)}</span></div><p><strong>${fmt(t.reward)} монет</strong> · заказчик ${t.creator}${t.worker?' · исполнитель '+t.worker:''}</p><p class="small"><strong>Приёмка:</strong> ${esc(t.criteria)}</p>${t.proof?`<p class="small"><strong>Результат:</strong> ${esc(t.proof)}</p>`:''}${t.dispute?`<p class="small"><strong>Спор:</strong> ${esc(t.dispute)}</p>`:''}${t.resolution?`<p class="small"><strong>Решение:</strong> ${esc(t.resolution)}</p>`:''}<div style="display:flex;flex-wrap:wrap;gap:8px">${actions}</div></article>`;
return `<article class="section" style="overflow-wrap:anywhere"><div class="row"><h3>#${esc(t.id)} · ${esc(t.title)}</h3><span class="tag">${esc(ceLabels[t.status]||t.status)}</span></div><p><strong>${fmt(t.reward)} монет</strong> · заказчик ${esc(t.creator)}${t.worker?' · исполнитель '+esc(t.worker):''}</p><p class="small"><strong>Приёмка:</strong> ${esc(t.criteria)}</p>${t.proof?`<p class="small"><strong>Результат:</strong> ${esc(t.proof)}</p>`:''}${t.dispute?`<p class="small"><strong>Спор:</strong> ${esc(t.dispute)}</p>`:''}${t.resolution?`<p class="small"><strong>Решение:</strong> ${esc(t.resolution)}</p>`:''}<div style="display:flex;flex-wrap:wrap;gap:8px">${actions}</div></article>`;
}).join('');
const kinds={grant:'Из фонда',transfer:'Перевод',escrow:'Резерв задания',refund:'Возврат резерва',payout:'Принятая работа',resolution:'Решение спора'};
const history=(data.history||[]).map(t=>`<div class="tx" style="display:block;overflow-wrap:anywhere;padding:12px 0"><strong>${t.dst===uid?'+':'−'}${fmt(t.amount)} монет</strong> · ${esc(kinds[t.kind]||t.kind)}${t.task_id?' #'+t.task_id:''}<p class="small">${esc(t.reason)}</p></div>`).join('');
const history=(data.history||[]).map(t=>`<div class="tx" style="display:block;overflow-wrap:anywhere;padding:12px 0"><strong>${t.dst===uid?'+':'−'}${fmt(t.amount)} монет</strong> · ${esc(kinds[t.kind]||t.kind)}${t.task_id?' #'+esc(t.task_id):''}<p class="small">${esc(t.reason)}</p></div>`).join('');
return (showIntro?intro('Монеты и задания.','За полезный результат — награда. Чат, бот и Mini App используют один журнал.',true):'')+
`<section class="hero"><span class="eyebrow">Монеты сообщества · не деньги</span><div class="money">${fmt(data.balance)}</div><p>Доступно · ещё ${fmt(data.reserved)} в резерве твоих заданий</p><p class="small">${esc(data.rules)}</p><div style="display:flex;flex-wrap:wrap;gap:8px">${ceButton('create')}${ceButton('transfer')}${data.is_admin?ceButton('grant'):''}</div></section>
${cePending(uid)?'<section class="section" role="status"><p>Ответ на последнюю операцию не подтверждён. Проверка с тем же номером не спишет монеты дважды.</p><button class="button" data-ce-retry>Проверить последнюю операцию</button></section>':''}
@@ -3229,7 +3229,7 @@ return {text:d.chapter?.objective||'Продолжи расследование.
function nlView(d){
const top='<div class="nl-gamehead"><strong>Протокол «Тишина»</strong><small>НЕЙРОЛАБ / ДЕЛО 01</small></div>';
const status='<p class="small muted" id="nl-status" role="status" aria-live="polite"></p>';
if(!d||typeof d.revision!=='number'||!Array.isArray(d.rooms))return top+status+empty('Нейролаб недоступен','Сервер вернул пустое состояние. Нажми «Обновить».');
if(!d||typeof d.revision!=='number'||!Array.isArray(d.rooms))return top+status+empty('Нейролаб недоступен','Сервер вернул пустое состояние. Нажми «Обновить».')+refreshBtn();
if(!d.started){
return top+status+`<section class="nl-cover"><img src="${nlPhoto('lobby')}" alt="Ночная стойка лаборатории: журнал, пейджер, объявление" fetchpriority="high"><div class="nl-cover-copy"><span class="micro" style="color:var(--nla)">22:03 · поступил сигнал тревоги</span><h2>Кто запер<br>изолятор?</h2><p>Сотрудница исчезла. Дверь закрыта изнутри. Ищи следы прямо в комнатах.</p><button class="button" data-nl-action="start" id="nl-start" type="button">Войти в лабораторию →</button></div></section><p class="nl-legend">Нажимай на предметы, находи улики, принимай решения.<br>Сюжет бесплатный. Награда — репутация и значок.</p>`;
}
+10 -5
View File
@@ -1485,7 +1485,7 @@ def _tg_check_hash(data):
check = "\n".join("{}={}".format(k, pairs[k]) for k in sorted(pairs))
secret = hashlib.sha256(_tg_bot_token().encode()).digest()
digest = hmac.new(secret, check.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(digest, received)
return hmac.compare_digest(digest.encode(), received.encode("utf-8", "replace"))
async def _newapi_call(session, method, path, bearer=None, json_body=None):
@@ -1720,13 +1720,13 @@ async def tg_callback(req):
if _tg_id and _tg_id.isdigit():
_row = await asyncio.to_thread(_tg_link_by_tgid, int(_tg_id))
if _row:
resp.set_cookie("tg_linked", "1", max_age=31536000,
resp.set_cookie("tg_linked", "1", max_age=31536000, secure=True,
httponly=False, samesite="Lax")
resp.set_cookie("tg_token", _row[1] or "", max_age=31536000,
resp.set_cookie("tg_token", _row[1] or "", max_age=31536000, secure=True,
httponly=True, samesite="Lax")
resp.set_cookie("tg_points", str(_row[2] or 0), max_age=31536000,
resp.set_cookie("tg_points", str(_row[2] or 0), max_age=31536000, secure=True,
httponly=False, samesite="Lax")
resp.set_cookie("tg_vip", str(_row[3] or 0), max_age=31536000,
resp.set_cookie("tg_vip", str(_row[3] or 0), max_age=31536000, secure=True,
httponly=False, samesite="Lax")
return resp
@@ -1764,6 +1764,11 @@ def _tg_normalize(data):
async def tg_login(req):
# Login CSRF: a cross-site form must not plant the attacker's signed session.
if req.headers.get("Origin") not in (
"https://reformboss.com", "https://api.reformboss.com", "https://" + req.host):
return web.json_response({"success": False, "error": "bad_origin"},
status=403, headers={"Cache-Control": "no-store"})
raw_body = await req.text()
try:
data = json.loads(raw_body)
+46
View File
@@ -0,0 +1,46 @@
"""Spinner middleware must answer the callback when the handler fails fast."""
import ast
import asyncio
from pathlib import Path
import pytest
SRC = Path(__file__).resolve().parents[1] / "bot" / "grok_bot.py"
def _load_mw():
tree = ast.parse(SRC.read_text(encoding="utf-8"))
fn = next(n for n in tree.body if isinstance(n, ast.AsyncFunctionDef) and n.name == "_cb_spinner_mw")
fn.decorator_list = []
ns = {"asyncio": asyncio}
exec(compile(ast.Module(body=[fn], type_ignores=[]), str(SRC), "exec"), ns)
return ns["_cb_spinner_mw"]
class _Ev:
def __init__(self):
self.answered = 0
async def answer(self):
self.answered += 1
def test_fast_failure_answers_and_reraises():
mw, ev = _load_mw(), _Ev()
async def handler(e, d):
raise ValueError("boom")
with pytest.raises(ValueError):
asyncio.run(mw(handler, ev, {}))
assert ev.answered == 1
def test_success_does_not_double_answer():
mw, ev = _load_mw(), _Ev()
async def handler(e, d):
return "ok"
assert asyncio.run(mw(handler, ev, {})) == "ok"
assert ev.answered == 0
+39
View File
@@ -0,0 +1,39 @@
"""Skin Telegram login: non-ASCII hash is a mismatch (not a 500), cross-site Origin is refused."""
import ast
import asyncio
import hashlib
import hmac
import json
import time
from pathlib import Path
from aiohttp import web
from aiohttp.test_utils import make_mocked_request
SRC = Path(__file__).resolve().parents[1] / "gateway" / "grok-web-skin.py"
def _load(*names, **extra):
tree = ast.parse(SRC.read_text(encoding="utf-8"))
nodes = [n for n in tree.body
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in names]
assert {n.name for n in nodes} == set(names)
ns = {"time": time, "hashlib": hashlib, "hmac": hmac, "json": json, "web": web,
"TG_AUTH_MAX_AGE": 86400, "_tg_bot_token": lambda: "123:abc", **extra}
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(SRC), "exec"), ns)
return ns
def test_non_ascii_hash_is_rejected_not_500():
ns = _load("_tg_check_hash")
data = {"id": "1", "auth_date": str(int(time.time())), "hash": "ф" * 64}
assert ns["_tg_check_hash"](data) is False
def test_tg_login_refuses_cross_site_origin():
ns = _load("tg_login")
req = make_mocked_request("POST", "/api/tg_widget_login",
headers={"Origin": "https://evil.example"})
resp = asyncio.run(ns["tg_login"](req))
assert resp.status == 403
assert json.loads(resp.body)["error"] == "bad_origin"