From a05a36aa7b8b97310a44dd76afe51d48865a80dd Mon Sep 17 00:00:00 2001 From: reform Date: Sat, 31 Oct 2026 02:16:16 +0300 Subject: [PATCH] Harden Telegram login, callback spinner and Mini App escaping - 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 --- bot/grok_bot.py | 29 +++++++++++++---- bot/webapp/static/index.html | 8 ++--- gateway/grok-web-skin.py | 15 ++++++--- tests/test_bot_callback_spinner.py | 46 +++++++++++++++++++++++++++ tests/test_skin_tg_login_hardening.py | 39 +++++++++++++++++++++++ 5 files changed, 122 insertions(+), 15 deletions(-) create mode 100644 tests/test_bot_callback_spinner.py create mode 100644 tests/test_skin_tg_login_hardening.py diff --git a/bot/grok_bot.py b/bot/grok_bot.py index 56e693cc..a6b3259a 100644 --- a/bot/grok_bot.py +++ b/bot/grok_bot.py @@ -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) # текст апстрима, может быть 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 diff --git a/bot/webapp/static/index.html b/bot/webapp/static/index.html index 4294324a..f000bb0f 100644 --- a/bot/webapp/static/index.html +++ b/bot/webapp/static/index.html @@ -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 ``} +function ceButton(action,id=0){return ``} 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 `

#${t.id} · ${esc(t.title)}

${esc(ceLabels[t.status]||t.status)}

${fmt(t.reward)} монет · заказчик ${t.creator}${t.worker?' · исполнитель '+t.worker:''}

Приёмка: ${esc(t.criteria)}

${t.proof?`

Результат: ${esc(t.proof)}

`:''}${t.dispute?`

Спор: ${esc(t.dispute)}

`:''}${t.resolution?`

Решение: ${esc(t.resolution)}

`:''}
${actions}
`; +return `

#${esc(t.id)} · ${esc(t.title)}

${esc(ceLabels[t.status]||t.status)}

${fmt(t.reward)} монет · заказчик ${esc(t.creator)}${t.worker?' · исполнитель '+esc(t.worker):''}

Приёмка: ${esc(t.criteria)}

${t.proof?`

Результат: ${esc(t.proof)}

`:''}${t.dispute?`

Спор: ${esc(t.dispute)}

`:''}${t.resolution?`

Решение: ${esc(t.resolution)}

`:''}
${actions}
`; }).join(''); const kinds={grant:'Из фонда',transfer:'Перевод',escrow:'Резерв задания',refund:'Возврат резерва',payout:'Принятая работа',resolution:'Решение спора'}; -const history=(data.history||[]).map(t=>`
${t.dst===uid?'+':'−'}${fmt(t.amount)} монет · ${esc(kinds[t.kind]||t.kind)}${t.task_id?' #'+t.task_id:''}

${esc(t.reason)}

`).join(''); +const history=(data.history||[]).map(t=>`
${t.dst===uid?'+':'−'}${fmt(t.amount)} монет · ${esc(kinds[t.kind]||t.kind)}${t.task_id?' #'+esc(t.task_id):''}

${esc(t.reason)}

`).join(''); return (showIntro?intro('Монеты и задания.','За полезный результат — награда. Чат, бот и Mini App используют один журнал.',true):'')+ `
Монеты сообщества · не деньги
${fmt(data.balance)}

Доступно · ещё ${fmt(data.reserved)} в резерве твоих заданий

${esc(data.rules)}

${ceButton('create')}${ceButton('transfer')}${data.is_admin?ceButton('grant'):''}
${cePending(uid)?'

Ответ на последнюю операцию не подтверждён. Проверка с тем же номером не спишет монеты дважды.

':''} @@ -3229,7 +3229,7 @@ return {text:d.chapter?.objective||'Продолжи расследование. function nlView(d){ const top='
Протокол «Тишина»НЕЙРОЛАБ / ДЕЛО 01
'; const status='

'; -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+`
Ночная стойка лаборатории: журнал, пейджер, объявление
22:03 · поступил сигнал тревоги

Кто запер
изолятор?

Сотрудница исчезла. Дверь закрыта изнутри. Ищи следы прямо в комнатах.

Нажимай на предметы, находи улики, принимай решения.
Сюжет бесплатный. Награда — репутация и значок.

`; } diff --git a/gateway/grok-web-skin.py b/gateway/grok-web-skin.py index 1a4e0afb..da2dd9ad 100644 --- a/gateway/grok-web-skin.py +++ b/gateway/grok-web-skin.py @@ -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) diff --git a/tests/test_bot_callback_spinner.py b/tests/test_bot_callback_spinner.py new file mode 100644 index 00000000..78bb38cc --- /dev/null +++ b/tests/test_bot_callback_spinner.py @@ -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 diff --git a/tests/test_skin_tg_login_hardening.py b/tests/test_skin_tg_login_hardening.py new file mode 100644 index 00000000..35f8840c --- /dev/null +++ b/tests/test_skin_tg_login_hardening.py @@ -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"