Files
iishko-public/bot/miniapp_guard.py
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

126 lines
5.7 KiB
Python

"""In-process UID throttles. Device IDs, forwarding headers and query strings are not identities."""
from collections import OrderedDict
import hashlib
import hmac
import math
import time
from aiohttp import web
POLICIES = {"read": (180, 60), "write": (30, 60), "chat": (12, 60),
"files": (3, 60), "support": (12, 60), "captcha": (6, 60),
"control": (120, 60)}
CONTROL = {"/api/agent_cancel", "/api/agent_history", "/api/agent_history/clear", "/api/reminders/cancel"}
CHAT = {"/api/agent_chat", "/api/neurolab/talk"}
def families(method, path):
# aiohttp Request.path is decoded and excludes the query; also protect direct callers.
path = path.split("?", 1)[0]
if path in CONTROL:
return ("control",)
if method in ("GET", "HEAD"):
return ("captcha",) if path == "/api/captcha" else ("read",)
if path in CHAT:
return ("chat",)
if path == "/api/support":
return ("write", "support")
return ("write",)
def rate_response(retry_after, *, operation_id=None):
retry = max(1, min(86400, int(math.ceil(retry_after))))
message = "Слишком много запросов. Подожди немного и повтори вручную."
body = {"error": "miniapp_rate", "msg": message, "message": message,
"retry_after": retry, "operation_rejected": True}
# No state/uncertain claim: this request did not enter the handler, but an earlier
# request with the same unknown operation ID might still be running/completed.
if operation_id is not None:
body["operation_id"] = operation_id
return web.json_response(body, status=429, headers={"Retry-After": str(retry)})
class MiniappGuard:
def __init__(self, secret, *, policies=None, clock=time.monotonic,
max_users=10000, max_peers=2048, idle_ttl=900, auth_limit=30):
self.clock = clock
self.policies = dict(POLICIES if policies is None else policies)
if not self.policies or any(type(limit) is not int or limit <= 0 or
not isinstance(window, (int, float)) or not math.isfinite(window) or window <= 0
for limit, window in self.policies.values()):
raise ValueError("miniapp_rate_policy_invalid")
self.max_users, self.max_peers = max(1, max_users), max(1, max_peers)
self.idle_ttl = max(idle_ttl, max(window for _, window in self.policies.values()), 60)
self.auth_limit = max(1, auth_limit)
self.users, self.peers = OrderedDict(), OrderedDict()
self.secret = str(secret).encode("utf-8")
self.global_auth = (float(self.auth_limit * 20), self.clock())
def _prune(self, records, now):
while records:
key, record = next(iter(records.items()))
if now - record["last"] < self.idle_ttl:
break
records.pop(key)
@staticmethod
def _available(bucket, limit, window, now):
tokens, updated = bucket if bucket is not None else (float(limit), now)
available = min(float(limit), tokens + max(0, now - updated) * limit / window)
return available, max(0, int(math.ceil((1 - available) * window / limit)))
def take(self, uid, *requested):
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
return 60
now = self.clock()
self._prune(self.users, now)
record = self.users.get(uid)
if record is None:
if len(self.users) >= self.max_users:
oldest = next(iter(self.users.values()))
return max(1, int(math.ceil(oldest["last"] + self.idle_ttl - now)))
record = {"last": now, "buckets": {}}
self.users[uid] = record
record["last"] = now
self.users.move_to_end(uid)
pending, retry = {}, 0
for family in set(requested):
limit, window = self.policies[family]
available, wait = self._available(record["buckets"].get(family), limit, window, now)
pending[family] = available
retry = max(retry, wait)
if not retry:
for family, available in pending.items():
record["buckets"][family] = (available - 1, now)
return retry
def check(self, uid, method, path):
return self.take(uid, *families(method, path))
def reject_auth(self, remote):
"""Only invalid signatures spend this inexpensive bounded budget; valid users are not IP-throttled."""
now = self.clock()
self._prune(self.peers, now)
remote = remote if isinstance(remote, str) and len(remote) <= 64 else "unknown"
peer = hmac.new(self.secret, ("auth-peer:" + remote).encode("utf-8"), hashlib.sha256).hexdigest()
record = self.peers.get(peer)
if record is None:
if len(self.peers) >= self.max_peers:
oldest = next(iter(self.peers.values()))
return max(1, int(math.ceil(oldest["last"] + self.idle_ttl - now)))
record = {"last": now, "bucket": None}
self.peers[peer] = record
record["last"] = now
self.peers.move_to_end(peer)
tokens, wait = self._available(record["bucket"], self.auth_limit, 60, now)
global_tokens, global_wait = self._available(self.global_auth, self.auth_limit * 20, 60, now)
retry = max(wait, global_wait)
if not retry:
record["bucket"] = (tokens - 1, now)
self.global_auth = (global_tokens - 1, now)
return retry
@staticmethod
def response(retry_after, *, operation_id=None):
return rate_response(retry_after, operation_id=operation_id)