Бот для капчи в чатах
Roman Sergienko
8 hours ago 47fba49d1835442f096739b92a3dd3ed9476470b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import hashlib
import hmac
import json
import urllib.parse
 
from aiohttp import web
 
import db
import cfg
from cfg import OWNER_ID, WEB_ADMINS, WEB_BASE_URL, bot
from util import now_ts
from web.render import render
 
SESS_TTL = 7 * 86400
COOKIE = "amd_sess"
 
 
def base_url(request) -> str:
    if WEB_BASE_URL:
        return WEB_BASE_URL
    proto = request.headers.get("X-Forwarded-Proto", request.scheme)
    host = request.headers.get("X-Forwarded-Host", request.host)
    return f"{proto}://{host}"
 
 
def is_staff(user_id: int) -> bool:
    return user_id == OWNER_ID or user_id in WEB_ADMINS
 
 
def verify_login(data: dict) -> bool:
    # Проверка подписи Telegram Login Widget: HMAC-SHA256 на секрете из токена бота.
    check = data.get("hash")
    if not check:
        return False
    pairs = sorted(f"{k}={v}" for k, v in data.items() if k != "hash")
    secret = hashlib.sha256(bot.token.encode()).digest()
    calc = hmac.new(secret, "\n".join(pairs).encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(calc, check):
        return False
    try:
        auth_date = int(data.get("auth_date", "0"))
    except ValueError:
        return False
    return now_ts() - auth_date <= 86400
 
 
def verify_webapp_init_data(init_data: str) -> dict | None:
    """Проверяет подпись Telegram Mini App initData и возвращает разобранные поля."""
    try:
        pairs = dict(urllib.parse.parse_qsl(init_data, keep_blank_values=True))
        received_hash = pairs.pop("hash", "")
        auth_date = int(pairs.get("auth_date", "0"))
    except (TypeError, ValueError):
        return None
    if not received_hash or now_ts() - auth_date > 86400 or auth_date > now_ts() + 30:
        return None
 
    data_check_string = "\n".join(f"{key}={value}" for key, value in sorted(pairs.items()))
    secret = hmac.new(b"WebAppData", bot.token.encode(), hashlib.sha256).digest()
    calc = hmac.new(secret, data_check_string.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(calc, received_hash):
        return None
    return pairs
 
 
async def create_miniapp_session(init_data: str) -> str | None:
    """Проверяет Telegram initData и возвращает токен веб-сессии."""
    verified = verify_webapp_init_data(init_data)
    if not verified:
        return None
    try:
        tg_user = json.loads(verified["user"])
        user_id = int(tg_user["id"])
    except (KeyError, TypeError, ValueError, json.JSONDecodeError):
        return None
 
    ts = now_ts()
    await db.upsert_web_user(
        user_id,
        tg_user.get("first_name", ""),
        tg_user.get("last_name", ""),
        tg_user.get("username", ""),
        tg_user.get("photo_url", ""),
        ts,
    )
    return await db.create_sess(user_id, ts, SESS_TTL)
 
 
@web.middleware
async def session_mw(request, handler):
    request["user"] = None
    token = request.cookies.get(COOKIE)
    if token:
        sess = await db.get_sess(token, now_ts())
        if sess:
            request["user"] = await db.get_web_user(sess["user_id"]) or {"user_id": sess["user_id"], "first_name": ""}
    public = request.path in (
        "/login",
        "/auth/telegram",
        "/auth/miniapp",
        "/miniapp",
        "/miniapp/login",
    ) or request.path.startswith("/static")
    
    # Для API запросов возвращаем JSON вместо редиректа
    is_api = request.path.startswith("/api/")
    
    if request["user"] is None and not public:
        if is_api:
            return web.json_response({"ok": False, "msg": "Не авторизован."}, status=401)
        raise web.HTTPFound("/login")
    try:
        response = await handler(request)
    except web.HTTPException as response:
        if request.path.startswith("/miniapp") or request.path == "/auth/miniapp":
            response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
            response.headers["Pragma"] = "no-cache"
        raise
    if request.path.startswith("/miniapp") or request.path == "/auth/miniapp":
        response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
        response.headers["Pragma"] = "no-cache"
    if request.path.startswith("/static/"):
        response.headers["Cache-Control"] = "no-cache, must-revalidate, max-age=0"
    return response
 
 
async def login_page(request) -> web.Response:
    # Имя бота читаем динамически: оно заполняется на старте в load_bot_username().
    if not cfg.BOT_USERNAME:
        await cfg.load_bot_username()
    return render(
        request,
        "login.html",
        bot_username=cfg.BOT_USERNAME,
        auth_url=base_url(request) + "/auth/telegram",
    )
 
 
async def auth_telegram(request) -> web.Response:
    q = dict(request.query)
    if not verify_login(q):
        raise web.HTTPFound("/login?err=1")
    try:
        user_id = int(q["id"])
    except (KeyError, ValueError):
        raise web.HTTPFound("/login?err=1")
 
    ts = now_ts()
    await db.upsert_web_user(
        user_id,
        q.get("first_name", ""),
        q.get("last_name", ""),
        q.get("username", ""),
        q.get("photo_url", ""),
        ts,
    )
    token = await db.create_sess(user_id, ts, SESS_TTL)
    resp = web.HTTPFound("/")
    resp.set_cookie(
        COOKIE,
        token,
        max_age=SESS_TTL,
        httponly=True,
        samesite="Lax",
        secure=base_url(request).startswith("https"),
    )
    return resp
 
 
async def auth_miniapp(request) -> web.Response:
    try:
        data = await request.json()
    except (ValueError, web.HTTPException):
        return web.json_response({"ok": False, "msg": "Некорректный запрос."}, status=400)
    token = await create_miniapp_session(data.get("init_data", "") if isinstance(data, dict) else "")
    if not token:
        return web.json_response({"ok": False, "msg": "Данные Telegram недействительны или устарели."}, status=401)
    resp = web.json_response({"ok": True})
    resp.set_cookie(
        COOKIE,
        token,
        max_age=SESS_TTL,
        httponly=True,
        samesite="None",
        secure=True,
    )
    return resp
 
 
async def logout(request) -> web.Response:
    token = request.cookies.get(COOKIE)
    if token:
        await db.del_sess(token)
    resp = web.HTTPFound("/login")
    resp.del_cookie(COOKIE)
    return resp