Files
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

341 lines
17 KiB
Python

"""Bounded support receipts and an at-least-once, secret-safe notification outbox."""
import asyncio
from contextlib import closing
import hashlib
import html
import json
import re
import secrets
import sqlite3
import time
from urllib.parse import unquote, urlsplit, urlunsplit
from assistant_runtime import redact_secrets
IDENTIFIER = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}\Z')
CONTEXT_LIMITS = {'screen': 64, 'model': 128, 'error_code': 64,
'request_id': 96, 'operation_id': 96}
_SECRET_FIELD = r'(?:password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|client[_-]?secret|bot[_-]?token|access[_-]?token|refresh[_-]?token|session[_-]?id|signature)'
_QUOTED_SECRET = re.compile(r'(?i)(["\']?\b' + _SECRET_FIELD + r'\b["\']?\s*[:=]\s*)(["\'])(.*?)\2')
_PLAIN_SECRET = re.compile(r'(?i)(\b' + _SECRET_FIELD + r'\b\s*[:=]\s*)(?!\[redacted\])[^\s,;&}\]]+')
_AUTH = re.compile(r'(?im)(["\']?\b(?:authorization|proxy-authorization|cookie|set-cookie)\b["\']?\s*[:=]\s*)(?:"[^"\r\n]*"|\'[^\'\r\n]*\'|[^\r\n]*)')
_INIT = re.compile(r'(?im)(\b(?:init[_-]?data|tgWebAppData|X-Init-Data)\b["\']?\s*[:=]\s*)[^\r\n]*')
_TELEGRAM_DATA = re.compile(r'(?i)(?:auth_date|query_id|chat_instance|user)=[^\s]*&(?:[^\s]*&)?(?:hash|signature)=[^\s]+|hash=[^\s]*&[^\s]*auth_date=[^\s]+')
_BOT_TOKEN = re.compile(r'\b\d{5,16}:[A-Za-z0-9_-]{20,}\b')
_BARE_AUTH = re.compile(r'(?i)\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]+')
_URL = re.compile(r'https?://[^\s<>"\']+', re.I)
_KEY_TOKEN = re.compile(r'\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b')
class SupportError(Exception):
def __init__(self, status, code, message):
super().__init__(code)
self.status, self.code, self.message = status, code, message
class NotificationError(Exception):
def __init__(self, *, retryable=True, retry_after=0):
super().__init__('notification_failed')
self.retryable = retryable
self.retry_after = retry_after if isinstance(retry_after, (int, float)) else 0
def identifier(value):
return isinstance(value, str) and IDENTIFIER.fullmatch(value) is not None
def redact_text(value):
text = html.unescape(value)
for _ in range(2):
decoded = unquote(text)
if decoded == text:
break
text = decoded
text = ''.join(c for c in text if c in '\n\t' or (ord(c) >= 32 and ord(c) != 127))
text = _INIT.sub(lambda m: m.group(1) + '[redacted]', text)
text = _TELEGRAM_DATA.sub('[redacted Telegram auth]', text)
text = _AUTH.sub(lambda m: m.group(1) + '[redacted]', text)
text = _QUOTED_SECRET.sub(lambda m: m.group(1) + '"[redacted]"', text)
text = _PLAIN_SECRET.sub(lambda m: m.group(1) + '[redacted]', text)
text = _BARE_AUTH.sub('[redacted authorization]', text)
text = _BOT_TOKEN.sub('[redacted bot token]', text)
text = _KEY_TOKEN.sub('[redacted key]', text)
text = redact_secrets(text)
def safe_url(match):
try:
url = urlsplit(match.group(0))
host = url.netloc.rsplit('@', 1)[-1]
return urlunsplit((url.scheme, host, url.path, '[redacted]' if url.query else '', ''))
except ValueError:
return '[redacted URL]'
return _URL.sub(safe_url, text)
def safe_request_id(value):
if identifier(value) and redact_text(value) == value:
return value
return secrets.token_hex(16)
def clean_submission(message, context):
if (not isinstance(message, str) or not message.strip() or len(message) > 4000
or any(0xD800 <= ord(c) <= 0xDFFF for c in message)):
raise SupportError(400, 'invalid_support_message', 'Опиши проблему: от 1 до 4000 символов.')
if context is None:
context = {}
if not isinstance(context, dict):
raise SupportError(400, 'invalid_support_context', 'Контекст должен быть JSON-объектом.')
cleaned = {}
for field, limit in CONTEXT_LIMITS.items():
if field not in context:
continue
value = context[field]
if (not isinstance(value, str) or len(value) > limit
or any(0xD800 <= ord(c) <= 0xDFFF for c in value)):
raise SupportError(400, 'invalid_support_context', 'Некорректный диагностический контекст.')
if field in ('request_id', 'operation_id'):
if not value:
continue
if not identifier(value) or redact_text(value) != value:
raise SupportError(400, 'invalid_support_context', 'Некорректный идентификатор диагностики.')
cleaned[field] = value
continue
value = redact_text(value).strip()
if field == 'screen':
if '://' in value:
try:
value = urlsplit(value).path
except ValueError:
value = ''
value = value.split('?', 1)[0].split('#', 1)[0]
value = re.sub(r'[^A-Za-z0-9_./:-]', '', value)
if value:
cleaned[field] = value[:limit]
return redact_text(message.strip())[:4000], cleaned
class SupportStore:
def __init__(self, path, *, clock=time.time, retention=30 * 86400, pending_retention=7 * 86400,
max_tickets=2000, max_user_tickets=50, hourly_limit=5, daily_limit=20,
max_attempts=5, retry_base=15, retry_max=3600, lease_seconds=60):
self.path, self.clock = str(path), clock
self.retention, self.pending_retention = retention, pending_retention
self.max_tickets, self.max_user_tickets = max_tickets, max_user_tickets
self.hourly_limit, self.daily_limit = hourly_limit, daily_limit
self.max_attempts, self.retry_base, self.retry_max = max_attempts, retry_base, retry_max
self.lease_seconds = lease_seconds
def connect(self):
con = sqlite3.connect(self.path, timeout=2)
con.row_factory = sqlite3.Row
con.execute('PRAGMA foreign_keys=ON')
con.execute('PRAGMA secure_delete=ON')
return con
def init_db(self):
with closing(self.connect()) as con:
con.execute('PRAGMA journal_mode=WAL')
con.executescript('''
CREATE TABLE IF NOT EXISTS support_tickets (
id TEXT PRIMARY KEY, uid INTEGER NOT NULL, request_id TEXT NOT NULL,
message TEXT NOT NULL, context TEXT NOT NULL, created_at INTEGER NOT NULL,
notification_status TEXT NOT NULL DEFAULT 'pending', UNIQUE(uid, request_id)
);
CREATE INDEX IF NOT EXISTS support_user_created ON support_tickets(uid, created_at);
CREATE TABLE IF NOT EXISTS support_outbox (
ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,
admin_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0,
lease_until REAL NOT NULL DEFAULT 0, PRIMARY KEY(ticket_id, admin_id)
);
CREATE INDEX IF NOT EXISTS support_delivery_due ON support_outbox(status, next_attempt);
''')
con.commit()
@staticmethod
def receipt(row):
return {'id': row['id'], 'status': 'received', 'notification_status': row['notification_status'],
'created_at': row['created_at']}
def _prune(self, con, now):
con.execute('DELETE FROM support_tickets WHERE created_at<=?', (now - self.retention,))
con.execute("UPDATE support_outbox SET status='failed',lease_until=0 WHERE ticket_id IN "
"(SELECT id FROM support_tickets WHERE notification_status='pending' AND created_at<=?)",
(now - self.pending_retention,))
con.execute("UPDATE support_tickets SET notification_status='failed' "
"WHERE notification_status='pending' AND created_at<=?", (now - self.pending_retention,))
def prune(self):
with closing(self.connect()) as con:
con.execute('BEGIN IMMEDIATE')
self._prune(con, self.clock())
con.commit()
def submit(self, uid, request_id, message, context=None):
if not identifier(request_id):
raise SupportError(400, 'invalid_request_id', 'Обнови экран и отправь обращение заново.')
message, context = clean_submission(message, context)
# Only a digest of the caller's deduplication ID is retained; it may itself be a pasted secret.
request_key = hashlib.sha256(request_id.encode('utf-8')).hexdigest()
now = self.clock()
with closing(self.connect()) as con:
con.execute('BEGIN IMMEDIATE')
self._prune(con, now)
row = con.execute('SELECT * FROM support_tickets WHERE uid=? AND request_id=?',
(uid, request_key)).fetchone()
if row:
con.commit()
return self.receipt(row)
recent = con.execute('SELECT COUNT(*),COALESCE(SUM(created_at>?),0) FROM support_tickets '
'WHERE uid=? AND created_at>?', (now - 3600, uid, now - 86400)).fetchone()
if recent[0] >= self.daily_limit or recent[1] >= self.hourly_limit:
raise SupportError(429, 'support_rate_limited', 'Обращения сохранены. Попробуй отправить новое позже.')
user_count = con.execute('SELECT COUNT(*) FROM support_tickets WHERE uid=?', (uid,)).fetchone()[0]
if user_count >= self.max_user_tickets:
raise SupportError(429, 'support_intake_full', 'Лимит сохранённых обращений достигнут. Попробуй позже.')
count = con.execute('SELECT COUNT(*) FROM support_tickets').fetchone()[0]
if count >= self.max_tickets:
raise SupportError(503, 'support_intake_full', 'Поддержка временно занята. Попробуй позже.')
ticket_id = secrets.token_hex(12)
con.execute('INSERT INTO support_tickets(id,uid,request_id,message,context,created_at) VALUES(?,?,?,?,?,?)',
(ticket_id, uid, request_key, message, json.dumps(context, ensure_ascii=False), int(now)))
row = con.execute('SELECT * FROM support_tickets WHERE id=?', (ticket_id,)).fetchone()
con.commit()
return self.receipt(row)
def list_receipts(self, uid, limit=20):
limit = max(1, min(int(limit), 50))
with closing(self.connect()) as con:
con.execute('BEGIN IMMEDIATE')
self._prune(con, self.clock())
rows = con.execute('SELECT * FROM support_tickets WHERE uid=? ORDER BY created_at DESC,id DESC LIMIT ?',
(uid, limit)).fetchall()
con.commit()
return [self.receipt(row) for row in rows]
@staticmethod
def _refresh(con):
con.execute('''UPDATE support_tickets SET notification_status=CASE
WHEN EXISTS(SELECT 1 FROM support_outbox o WHERE o.ticket_id=support_tickets.id
AND o.status IN ('pending','sending')) THEN 'pending'
WHEN EXISTS(SELECT 1 FROM support_outbox o WHERE o.ticket_id=support_tickets.id
AND o.status='failed') THEN 'failed'
WHEN EXISTS(SELECT 1 FROM support_outbox o WHERE o.ticket_id=support_tickets.id) THEN 'sent'
ELSE 'pending' END WHERE notification_status='pending' ''')
def claim(self, admin_ids):
admins = sorted({uid for uid in admin_ids if isinstance(uid, int) and not isinstance(uid, bool) and uid > 0})
if len(admins) > 64:
raise ValueError('too_many_support_admins')
now = self.clock()
with closing(self.connect()) as con:
con.execute('BEGIN IMMEDIATE')
self._prune(con, now)
if not admins:
con.commit()
return None
slots = ','.join('?' for _ in admins)
con.execute("DELETE FROM support_outbox WHERE ticket_id IN "
"(SELECT id FROM support_tickets WHERE notification_status='pending') "
'AND admin_id NOT IN (' + slots + ')', admins)
for admin in admins:
con.execute('INSERT OR IGNORE INTO support_outbox(ticket_id,admin_id) '
"SELECT id,? FROM support_tickets WHERE notification_status='pending'", (admin,))
con.execute("UPDATE support_outbox SET status='failed',lease_until=0 "
"WHERE status IN ('pending','sending') AND attempts>=? AND lease_until<=?",
(self.max_attempts, now))
self._refresh(con)
row = con.execute('''SELECT o.*,t.uid,t.message,t.context,t.created_at FROM support_outbox o
JOIN support_tickets t ON t.id=o.ticket_id WHERE t.notification_status='pending'
AND o.admin_id IN (''' + slots + ''') AND o.attempts<? AND
((o.status='pending' AND o.next_attempt<=?) OR (o.status='sending' AND o.lease_until<=?))
ORDER BY o.next_attempt,t.created_at,o.ticket_id,o.admin_id LIMIT 1''',
(*admins, self.max_attempts, now, now)).fetchone()
if row is None:
con.commit()
return None
con.execute("UPDATE support_outbox SET status='sending',attempts=attempts+1,lease_until=? "
'WHERE ticket_id=? AND admin_id=?', (now + self.lease_seconds, row['ticket_id'], row['admin_id']))
con.commit()
claimed = dict(row)
claimed['attempts'] += 1
return claimed
def finish(self, claim, *, sent=False, retryable=True, retry_after=0):
attempts = claim['attempts']
if sent:
state, delay = 'sent', 0
elif not retryable or attempts >= self.max_attempts:
state, delay = 'failed', 0
else:
state = 'pending'
retry_after = retry_after if isinstance(retry_after, (int, float)) else 0
delay = min(self.retry_max, max(self.retry_base * 2 ** (attempts - 1), retry_after))
with closing(self.connect()) as con:
con.execute('BEGIN IMMEDIATE')
con.execute("UPDATE support_outbox SET status=?,next_attempt=?,lease_until=0 "
"WHERE ticket_id=? AND admin_id=? AND attempts=? AND status='sending'",
(state, self.clock() + delay, claim['ticket_id'], claim['admin_id'], attempts))
self._refresh(con)
con.commit()
def notification_text(claim):
context = json.loads(claim['context'])
details = '\n'.join('%s: %s' % (key, value) for key, value in context.items())
message = claim['message'][:3000]
if len(claim['message']) > len(message):
message += '\n[Текст сокращён в уведомлении]'
return ('Обращение #%s\nПользователь: %s\n%s\n%s' %
(claim['ticket_id'], claim['uid'], message, details))[:4000]
class SupportOutbox:
def __init__(self, store, admin_ids, sender, *, interval=5, batch=8):
self.store, self.admin_ids, self.sender = store, admin_ids, sender
self.interval, self.batch = interval, batch
self.wake = asyncio.Event()
self.stopping = False
def stop(self):
self.stopping = True
self.wake.set()
async def run_once(self):
for _ in range(self.batch):
if self.stopping:
break
claim = await asyncio.to_thread(self.store.claim, self.admin_ids())
if claim is None:
break
try:
await self.sender(claim['admin_id'], notification_text(claim))
except asyncio.CancelledError:
# A crashed/cancelled delivery remains leased and is recoverable after restart.
raise
except NotificationError as error:
await asyncio.to_thread(self.store.finish, claim, retryable=error.retryable,
retry_after=error.retry_after)
except Exception:
await asyncio.to_thread(self.store.finish, claim, retryable=True)
else:
await asyncio.to_thread(self.store.finish, claim, sent=True)
async def run(self):
while not self.stopping:
self.wake.clear()
try:
await self.run_once()
except (sqlite3.Error, OSError, ValueError):
# No exception text: HTTP exceptions may contain a token-bearing Telegram URL.
pass
if self.stopping:
break
try:
await asyncio.wait_for(self.wake.wait(), timeout=self.interval)
except asyncio.TimeoutError:
pass