Files
iishko-public/bot/key_issue_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

111 lines
5.2 KiB
Python

"""Issuance throttles, not account bans. Client installation IDs are resettable signals.
Device claims are resettable too: they cap issuance velocity per installation, never prove
a person and never stand in for hardware attestation.
"""
from contextlib import closing
import hashlib
import hmac
import ipaddress
import re
import sqlite3
import time
# Shared networks are allowed; an IP is never treated as a unique person. Only the
# account and the client installation ID throttle issuance — NAT is never a reason to reject.
LIMITS = (('uid', 8, 600), ('device', 12, 600))
DEVICE_UID_LIMIT = 3
DEVICE_UID_WINDOW = 14 * 86400
def client_ip(remote, headers):
try:
peer = ipaddress.ip_address(remote or '')
except ValueError:
return 'unknown'
# Caddy overwrites X-Real-IP. Public peers must never supply a trusted value.
if peer.is_loopback:
try:
return str(ipaddress.ip_address(headers.get('X-Real-IP', '')))
except ValueError:
pass
return str(peer)
def opaque(secret, purpose, value):
return hmac.new(secret.encode(), (purpose + ':' + str(value)).encode(), hashlib.sha256).hexdigest()
def context(secret, uid, device, remote, headers):
if not isinstance(device, str) or not re.fullmatch(r'[a-f0-9]{32}', device):
return None
return {'uid': opaque(secret, 'key-uid', uid),
'device': opaque(secret, 'key-device', device),
'ip': opaque(secret, 'key-ip', client_ip(remote, headers))}
def attempt(db_path, signals, now=None):
"""Atomically allow/count an attempt, returning seconds until a rejected attempt may retry."""
now = int(time.time() if now is None else now)
with closing(sqlite3.connect(db_path, timeout=15)) as con:
con.execute('PRAGMA busy_timeout=15000')
con.execute('CREATE TABLE IF NOT EXISTS wa_issue_attempts(kind TEXT NOT NULL, signal TEXT NOT NULL, ts INTEGER NOT NULL)')
con.execute('CREATE INDEX IF NOT EXISTS wa_issue_attempts_lookup ON wa_issue_attempts(kind,signal,ts)')
con.execute('BEGIN IMMEDIATE')
try:
con.execute('DELETE FROM wa_issue_attempts WHERE ts<=?', (now-86400,))
retry = 0
for kind, limit, window in LIMITS:
count, oldest = con.execute('SELECT COUNT(*),MIN(ts) FROM wa_issue_attempts WHERE kind=? AND signal=? AND ts>?', (kind, signals[kind], now-window)).fetchone()
if count >= limit:
retry = max(retry, int(oldest) + window - now + 1)
if not retry:
con.executemany('INSERT INTO wa_issue_attempts VALUES (?,?,?)', [(kind, signals[kind], now) for kind, _, _ in LIMITS])
con.commit()
return retry
except BaseException:
con.rollback()
raise
def bind_beneficiary(con, uid, device_hash, now):
"""Called inside the daemon issuance transaction, before a first welcome allocation."""
if not isinstance(device_hash, str) or not re.fullmatch(r'[a-f0-9]{64}', device_hash):
raise ValueError('Для выдачи ключа открой Mini App заново и разреши хранение данных')
con.execute('CREATE TABLE IF NOT EXISTS bot.wa_issue_beneficiaries(device TEXT PRIMARY KEY, uid INTEGER NOT NULL, created INTEGER NOT NULL)')
row = con.execute('SELECT uid FROM bot.wa_issue_beneficiaries WHERE device=?', (device_hash,)).fetchone()
if row and row[0] != uid:
raise ValueError('На этой установке Mini App стартовый ключ уже получал другой аккаунт. Поддержка: @your-handle')
con.execute('INSERT OR IGNORE INTO bot.wa_issue_beneficiaries VALUES (?,?,?)', (device_hash, uid, now))
def ensure_device_table(con):
con.execute('CREATE TABLE IF NOT EXISTS bot.wa_key_dev(name TEXT PRIMARY KEY, uid INTEGER, '
'device TEXT, created INTEGER)')
con.execute('CREATE INDEX IF NOT EXISTS bot.wa_key_dev_device ON wa_key_dev(device,created)')
def _device_hash(device_hash):
if not isinstance(device_hash, str) or not re.fullmatch(r'[a-f0-9]{64}', device_hash):
raise ValueError('Для выдачи ключа открой Mini App заново и разреши хранение данных')
return device_hash
def check_device(con, uid, device_hash, now):
device_hash = _device_hash(device_hash)
ensure_device_table(con)
others = con.execute('SELECT COUNT(DISTINCT uid) FROM bot.wa_key_dev '
'WHERE device=? AND uid<>? AND created>=?',
(device_hash, uid, int(now) - DEVICE_UID_WINDOW)).fetchone()[0]
if others >= DEVICE_UID_LIMIT:
raise ValueError('С этой установки Mini App уже выдавались ключи другим аккаунтам. Поддержка: @your-handle')
def record_device(con, uid, device_hash, name, now):
device_hash = _device_hash(device_hash)
if not isinstance(name, str) or not name:
raise ValueError('Не удалось подтвердить ключ операции')
ensure_device_table(con)
con.execute('INSERT OR REPLACE INTO bot.wa_key_dev(name,uid,device,created) VALUES (?,?,?,?)',
(name, uid, device_hash, int(now)))