Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
337 lines
16 KiB
Python
337 lines
16 KiB
Python
from contextlib import closing
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import time
|
|
|
|
from account_limits import account_uid, _name_scope
|
|
|
|
|
|
PAUSE_PATH = "/opt/grok-bot/econ_cap_state.json"
|
|
# Account-level locks that are not owned by a ban; unban must never clear them.
|
|
INDEPENDENT_FLAGS = ("api_blocked", "key_locked", "chat_key_locked")
|
|
|
|
|
|
class AdminError(Exception):
|
|
pass
|
|
|
|
|
|
def _uid(value):
|
|
if type(value) is not int or not 0 < value <= 9223372036854775807:
|
|
raise AdminError("Некорректный Telegram ID")
|
|
return value
|
|
|
|
|
|
def _connect(bot_db, gateway_db):
|
|
con = sqlite3.connect(Path(gateway_db).resolve().as_uri() + "?mode=rw",
|
|
uri=True, timeout=30, isolation_level=None)
|
|
con.row_factory = sqlite3.Row
|
|
try:
|
|
con.execute("PRAGMA busy_timeout=30000")
|
|
con.execute("ATTACH DATABASE ? AS bot", (Path(bot_db).resolve().as_uri() + "?mode=rw",))
|
|
return con
|
|
except BaseException:
|
|
con.close()
|
|
raise
|
|
|
|
|
|
def _authorize(con, actor_uid, admin_ids):
|
|
_uid(actor_uid)
|
|
if actor_uid in admin_ids:
|
|
return
|
|
columns = {r[1] for r in con.execute("PRAGMA bot.table_info(users)")}
|
|
row = con.execute("SELECT admin FROM bot.users WHERE tg_id=?", (actor_uid,)).fetchone() if "admin" in columns else None
|
|
if not row or row[0] != 1:
|
|
raise AdminError("Нет прав администратора")
|
|
|
|
|
|
def _schema(con):
|
|
con.execute("CREATE TABLE IF NOT EXISTS bot.wa_admin_bans ("
|
|
"uid INTEGER PRIMARY KEY,actor INTEGER NOT NULL,started INTEGER NOT NULL,"
|
|
"active INTEGER NOT NULL,site_status INTEGER)")
|
|
columns = {r[1] for r in con.execute("PRAGMA bot.table_info(wa_admin_bans)")}
|
|
if "site_status" not in columns:
|
|
con.execute("ALTER TABLE bot.wa_admin_bans ADD COLUMN site_status INTEGER")
|
|
con.execute("CREATE TABLE IF NOT EXISTS bot.wa_admin_ban_tokens ("
|
|
"uid INTEGER NOT NULL,tid INTEGER NOT NULL,name TEXT NOT NULL,"
|
|
"credential_hash TEXT NOT NULL,previous_status INTEGER NOT NULL,"
|
|
"PRIMARY KEY(uid,tid))")
|
|
con.execute("CREATE TABLE IF NOT EXISTS bot.ban_wl("
|
|
"uid INTEGER PRIMARY KEY,ts INTEGER NOT NULL,note TEXT NOT NULL DEFAULT '')")
|
|
|
|
|
|
def _fingerprint(value):
|
|
return hashlib.sha256(str(value).encode("utf-8")).hexdigest()
|
|
|
|
|
|
def _has_table(con, schema, name):
|
|
return bool(con.execute("SELECT 1 FROM " + schema + ".sqlite_master WHERE type='table' AND name=?", (name,)).fetchone())
|
|
|
|
|
|
def _pause_snapshot(path):
|
|
try:
|
|
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
if not isinstance(data, dict) or data.get("v", 2) != 2 or not isinstance(data.get("paused", {}), dict):
|
|
return None
|
|
return data.get("paused", {})
|
|
except FileNotFoundError:
|
|
return {}
|
|
except (OSError, ValueError, TypeError):
|
|
return None
|
|
|
|
|
|
def _hold_reason(con, row, user, pause_state, now):
|
|
if any(user.get(flag) for flag in ("api_blocked", "key_locked", "chat_key_locked")):
|
|
return "independent_account_lock"
|
|
if row["status"] != 2:
|
|
return "status_changed"
|
|
if row.get("expired_time", -1) not in (None, -1, 0) and int(row["expired_time"]) <= now:
|
|
return "expired"
|
|
for schema in ("main", "bot"):
|
|
if _has_table(con, schema, "wa_key_locks"):
|
|
if con.execute("SELECT 1 FROM " + schema + ".wa_key_locks WHERE tid=?", (row["id"],)).fetchone():
|
|
return "self_or_manual_lock"
|
|
if _has_table(con, schema, "wa_daily_cap_pauses"):
|
|
if con.execute("SELECT 1 FROM " + schema + ".wa_daily_cap_pauses WHERE tid=? AND name=?", (row["id"], row["name"])).fetchone():
|
|
return "limiter_pause"
|
|
if pause_state is None:
|
|
return "pause_state_unavailable"
|
|
if row["name"] in pause_state:
|
|
receipt = pause_state[row["name"]]
|
|
if not isinstance(receipt, dict) or receipt.get("flag_only") is not True:
|
|
return "limiter_pause"
|
|
return ""
|
|
|
|
|
|
def _site_account(con, uid):
|
|
"""Return (status, readable) for the site account named tg<uid>.
|
|
|
|
readable is False when the gateway users table is absent or shaped
|
|
differently, so callers report an honest hold reason instead of treating
|
|
unknown state as an enabled account.
|
|
"""
|
|
if not _has_table(con, "main", "users"):
|
|
return None, False
|
|
columns = {r[1] for r in con.execute("PRAGMA main.table_info(users)")}
|
|
if not {"username", "status"} <= columns:
|
|
return None, False
|
|
row = con.execute("SELECT status FROM main.users WHERE username=?", ("tg%d" % uid,)).fetchone()
|
|
if row is not None and type(row[0]) is not int:
|
|
return None, False
|
|
return (None if row is None else row[0]), True
|
|
|
|
|
|
def _site_ready(user):
|
|
"""Site access is restored only when no independent account lock remains."""
|
|
return not any(user.get(flag) for flag in INDEPENDENT_FLAGS + ("cap_paused",))
|
|
|
|
|
|
def _site_disable(con, uid, fresh):
|
|
"""Disable status 1 -> 2 for a new ban and return (preimage, hold reason).
|
|
|
|
The preimage is the raw pre-ban status. Only status 1 can be attributed to
|
|
the ban, so a later unban restores just that case. A repeated ban never
|
|
overwrites the original preimage; it only re-asserts a disable this ban
|
|
already owns.
|
|
"""
|
|
status, readable = _site_account(con, uid)
|
|
if not readable:
|
|
return None, "site_unavailable"
|
|
if status is None:
|
|
return None, "site_missing"
|
|
if not fresh:
|
|
record = con.execute("SELECT site_status FROM bot.wa_admin_bans WHERE uid=?", (uid,)).fetchone()
|
|
if record and record[0] == 1 and status == 1:
|
|
con.execute("UPDATE main.users SET status=2 WHERE username=? AND status=1", ("tg%d" % uid,))
|
|
return None, ""
|
|
if status != 1:
|
|
return status, "site_already_disabled"
|
|
changed = con.execute("UPDATE main.users SET status=2 WHERE username=? AND status=1",
|
|
("tg%d" % uid,)).rowcount
|
|
if changed != 1:
|
|
return None, "site_status_changed"
|
|
return status, ""
|
|
|
|
|
|
def _site_restore(con, uid, user, record, attributable):
|
|
"""Restore only a site status this ban disabled; report why otherwise."""
|
|
status, readable = _site_account(con, uid)
|
|
if not readable:
|
|
return False, "site_unavailable"
|
|
if status is None:
|
|
return False, "site_missing"
|
|
if status == 1:
|
|
return False, ""
|
|
if not attributable:
|
|
return False, "site_not_recorded"
|
|
receipt = record["site_status"]
|
|
if receipt is None:
|
|
return False, "site_not_recorded"
|
|
if receipt != 1:
|
|
return False, "site_already_disabled"
|
|
if status != 2:
|
|
return False, "site_status_changed"
|
|
if not _site_ready(user):
|
|
return False, "independent_account_lock"
|
|
changed = con.execute("UPDATE main.users SET status=1 WHERE username=? AND status=2",
|
|
("tg%d" % uid,)).rowcount
|
|
if changed != 1:
|
|
return False, "site_status_changed"
|
|
return True, ""
|
|
|
|
|
|
def _clear_autoban_receipt(con, uid):
|
|
for schema in ("main", "bot"):
|
|
if not _has_table(con, schema, "entry_autoban_applied"):
|
|
continue
|
|
columns = {r[1] for r in con.execute("PRAGMA " + schema + ".table_info(entry_autoban_applied)")}
|
|
if "uid" in columns:
|
|
con.execute("DELETE FROM " + schema + ".entry_autoban_applied WHERE uid=?", (uid,))
|
|
|
|
|
|
def _change(bot_db, gateway_db, target_uid, banned, *, actor_uid, admin_ids, pause_path, now):
|
|
_uid(target_uid)
|
|
if type(banned) is not bool:
|
|
raise AdminError("Некорректное действие")
|
|
now = int(time.time() if now is None else now)
|
|
pause_state = None if banned else _pause_snapshot(pause_path)
|
|
with closing(_connect(bot_db, gateway_db)) as con:
|
|
try:
|
|
con.execute("BEGIN IMMEDIATE")
|
|
_authorize(con, actor_uid, admin_ids)
|
|
required = {"tg_id", "banned", "api_blocked", "key_locked", "chat_key_locked", "cap_paused"}
|
|
if not required <= {r[1] for r in con.execute("PRAGMA bot.table_info(users)")}:
|
|
raise AdminError("Не удалось проверить независимые блокировки; изменений нет")
|
|
found = con.execute("SELECT * FROM bot.users WHERE tg_id=?", (target_uid,)).fetchone()
|
|
if not found:
|
|
raise AdminError("Пользователь не найден")
|
|
user = dict(found)
|
|
_schema(con)
|
|
record = con.execute("SELECT * FROM bot.wa_admin_bans WHERE uid=?", (target_uid,)).fetchone()
|
|
scope, args = _name_scope("name", target_uid)
|
|
tokens = [dict(r) for r in con.execute("SELECT * FROM tokens WHERE deleted_at IS NULL AND " + scope, args)
|
|
if account_uid(r["name"]) == target_uid]
|
|
report = {"uid": target_uid, "banned": banned, "restored": 0, "disabled": 0, "held": [],
|
|
"site_restored": False, "site_held": ""}
|
|
if banned:
|
|
# Repeated bans must not replace the original pre-ban status image.
|
|
fresh = not user["banned"] and not (record and record["active"])
|
|
site_status, report["site_held"] = _site_disable(con, target_uid, fresh)
|
|
if fresh:
|
|
con.execute("DELETE FROM bot.wa_admin_ban_tokens WHERE uid=?", (target_uid,))
|
|
con.execute("INSERT OR REPLACE INTO bot.wa_admin_bans VALUES(?,?,?,?,?)",
|
|
(target_uid, actor_uid, now, 1, site_status))
|
|
con.executemany("INSERT INTO bot.wa_admin_ban_tokens VALUES(?,?,?,?,?)", [
|
|
(target_uid, row["id"], row["name"], _fingerprint(row["key"]), row["status"]) for row in tokens])
|
|
con.execute("UPDATE bot.users SET banned=1 WHERE tg_id=?", (target_uid,))
|
|
if _has_table(con, "bot", "ban_wl"):
|
|
con.execute("DELETE FROM bot.ban_wl WHERE uid=?", (target_uid,))
|
|
for row in tokens:
|
|
if row["status"] == 1:
|
|
con.execute("UPDATE tokens SET status=2 WHERE id=? AND name=? AND status=1", (row["id"], row["name"]))
|
|
report["disabled"] += 1
|
|
else:
|
|
attributable = bool(user["banned"] and record and record["active"])
|
|
receipts = {r["tid"]: dict(r) for r in con.execute("SELECT * FROM bot.wa_admin_ban_tokens WHERE uid=?", (target_uid,))}
|
|
for row in tokens:
|
|
if row["status"] != 2:
|
|
continue
|
|
previous = receipts.get(row["id"])
|
|
reason = "legacy_or_manual_status"
|
|
if attributable and previous:
|
|
if previous["name"] != row["name"] or previous["credential_hash"] != _fingerprint(row["key"]):
|
|
reason = "credential_changed"
|
|
elif previous["previous_status"] != 1:
|
|
reason = "preexisting_disabled"
|
|
else:
|
|
reason = _hold_reason(con, row, user, pause_state, now)
|
|
if reason:
|
|
report["held"].append({"name": row["name"], "reason": reason})
|
|
else:
|
|
changed = con.execute("UPDATE tokens SET status=1 WHERE id=? AND name=? AND status=2",
|
|
(row["id"], row["name"])).rowcount
|
|
if changed != 1:
|
|
raise AdminError("Статус ключа изменился; разбан отменён")
|
|
report["restored"] += changed
|
|
report["site_restored"], report["site_held"] = _site_restore(
|
|
con, target_uid, user, record, attributable)
|
|
con.execute("UPDATE bot.users SET banned=0 WHERE tg_id=?", (target_uid,))
|
|
con.execute("UPDATE bot.wa_admin_bans SET active=0 WHERE uid=?", (target_uid,))
|
|
_clear_autoban_receipt(con, target_uid)
|
|
# Preserve the live anti-reban policy in the BOT schema.
|
|
if user["banned"]:
|
|
con.execute("INSERT OR REPLACE INTO bot.ban_wl(uid,ts,note) VALUES(?,?,?)",
|
|
(target_uid, now, "admin_unban"))
|
|
con.commit()
|
|
return report
|
|
except BaseException:
|
|
if con.in_transaction:
|
|
con.rollback()
|
|
raise
|
|
|
|
|
|
def set_banned(bot_db, gateway_db, target_uid, banned, *, actor_uid, admin_ids,
|
|
pause_path=PAUSE_PATH, now=None):
|
|
return _change(bot_db, gateway_db, target_uid, banned, actor_uid=actor_uid,
|
|
admin_ids=admin_ids, pause_path=pause_path, now=now)
|
|
|
|
|
|
def unban_account(bot_db, gateway_db, target_uid, *, actor_uid, admin_ids,
|
|
pause_path=PAUSE_PATH, now=None):
|
|
return _change(bot_db, gateway_db, target_uid, False, actor_uid=actor_uid,
|
|
admin_ids=admin_ids, pause_path=pause_path, now=now)
|
|
|
|
|
|
def list_banned(bot_db, *, actor_uid, admin_ids, offset=0, limit=8):
|
|
_uid(actor_uid)
|
|
if type(offset) is not int or not 0 <= offset <= 1_000_000:
|
|
raise AdminError("Некорректная страница")
|
|
with closing(sqlite3.connect(Path(bot_db).resolve().as_uri() + "?mode=ro", uri=True, timeout=30)) as con:
|
|
con.row_factory = sqlite3.Row
|
|
if actor_uid not in admin_ids:
|
|
cols = {r[1] for r in con.execute("PRAGMA table_info(users)")}
|
|
admin = con.execute("SELECT admin FROM users WHERE tg_id=?", (actor_uid,)).fetchone() if "admin" in cols else None
|
|
if not admin or admin[0] != 1:
|
|
raise AdminError("Нет прав администратора")
|
|
total = con.execute("SELECT COUNT(*) FROM users WHERE banned=1").fetchone()[0]
|
|
rows = con.execute("SELECT tg_id,username FROM users WHERE banned=1 ORDER BY tg_id LIMIT ? OFFSET ?", (min(8, max(1, limit)), offset)).fetchall()
|
|
return {"total": total, "users": [dict(r) for r in rows], "offset": offset}
|
|
|
|
|
|
def summary(result):
|
|
if result["banned"]:
|
|
return "Бан установлен; балансы сохранены. Отключено ключей: %d" % result["disabled"]
|
|
held = len(result["held"])
|
|
text = "Бан снят; балансы без изменений. Включено ключей: %d" % result["restored"]
|
|
if held:
|
|
labels = {
|
|
"legacy_or_manual_status": "нет подтверждения, что ключ отключён этим баном",
|
|
"credential_changed": "ключ был перевыпущен",
|
|
"preexisting_disabled": "ключ был отключён до бана",
|
|
"independent_account_lock": "независимая блокировка аккаунта",
|
|
"status_changed": "статус ключа изменён",
|
|
"expired": "срок ключа истёк",
|
|
"self_or_manual_lock": "самоблокировка или ручной лок",
|
|
"limiter_pause": "активная пауза лимитера",
|
|
"pause_state_unavailable": "состояние пауз недоступно",
|
|
}
|
|
text += ". Остались отключены: %d" % held
|
|
for item in result["held"][:5]:
|
|
text += "\n%s: %s" % (item["name"], labels.get(item["reason"], "неизвестная блокировка"))
|
|
if held > 5:
|
|
text += "\nИ ещё %d" % (held - 5)
|
|
if result.get("site_restored"):
|
|
text += "\nСайт: доступ восстановлен"
|
|
elif result.get("site_held"):
|
|
site_labels = {
|
|
"site_not_recorded": "нет подтверждения, что доступ отключён этим баном",
|
|
"site_already_disabled": "доступ был отключён до бана",
|
|
"site_status_changed": "статус сайта изменён",
|
|
"site_missing": "аккаунт сайта не найден",
|
|
"site_unavailable": "состояние сайта недоступно",
|
|
"independent_account_lock": "независимая блокировка аккаунта",
|
|
}
|
|
text += "\nСайт остался отключён: %s" % site_labels.get(result["site_held"], "неизвестное состояние")
|
|
return text
|