IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,268 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
log = logging.getLogger("entry_autoban")
|
||||
|
||||
BOT_DB = os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db")
|
||||
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
|
||||
SKIN_DB = os.environ.get("IISHKO_SKIN_DB", "/opt/grok-web-skin-tg.db")
|
||||
|
||||
PROTECT = tuple(int(v) for v in os.environ.get("IISHKO_PROTECTED_UIDS", "").replace(";", ",").split(",")
|
||||
if v.strip().isdigit())
|
||||
|
||||
|
||||
def enabled():
|
||||
return os.environ.get("IISHKO_ENTRY_AUTOBAN", "1").strip().lower() not in ("0", "off", "no", "false")
|
||||
|
||||
|
||||
def _connect(path):
|
||||
con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=rw", uri=True, timeout=10)
|
||||
try:
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA synchronous=FULL")
|
||||
return con
|
||||
except BaseException:
|
||||
con.close()
|
||||
raise
|
||||
|
||||
|
||||
def _main_name(name, uid):
|
||||
"""Accept the exact stored main name, never another account's reserved name."""
|
||||
if not name:
|
||||
return None
|
||||
if name.startswith(("tg", "pm", "sol")):
|
||||
match = re.fullmatch(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?", name)
|
||||
if not match or int(match[1]) != uid:
|
||||
return None
|
||||
return name
|
||||
|
||||
|
||||
def _snapshot(con, uid, reason, tokens):
|
||||
"""Stage an append-only preimage; caller MUST commit before updating tokens."""
|
||||
con.execute("CREATE TABLE IF NOT EXISTS entry_autobans("
|
||||
"ts INTEGER NOT NULL, uid INTEGER NOT NULL, reason TEXT NOT NULL, "
|
||||
"tokens TEXT NOT NULL DEFAULT '', applied INTEGER NOT NULL DEFAULT 1)")
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(entry_autobans)")}
|
||||
if "tokens" not in cols:
|
||||
con.execute("ALTER TABLE entry_autobans ADD COLUMN tokens TEXT NOT NULL DEFAULT ''")
|
||||
if "applied" not in cols:
|
||||
con.execute("ALTER TABLE entry_autobans ADD COLUMN applied INTEGER NOT NULL DEFAULT 1")
|
||||
payload = json.dumps(tokens, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
||||
# A failed apply can retry only the identical preimage. Never overwrite history.
|
||||
previous = con.execute("SELECT rowid,tokens,applied FROM entry_autobans "
|
||||
"WHERE uid=? ORDER BY rowid DESC LIMIT 1", (uid,)).fetchone()
|
||||
if previous and not previous["applied"] and previous["tokens"] == payload:
|
||||
return previous["rowid"], payload
|
||||
cur = con.execute("INSERT INTO entry_autobans(ts,uid,reason,tokens,applied) "
|
||||
"VALUES(strftime('%s','now'),?,?,?,0)", (uid, str(reason)[:120], payload))
|
||||
return cur.lastrowid, payload
|
||||
|
||||
|
||||
def _processed(g, con, uid, was_banned):
|
||||
g.execute("CREATE TABLE IF NOT EXISTS entry_autoban_applied("
|
||||
"uid INTEGER PRIMARY KEY,tokens TEXT NOT NULL)")
|
||||
row = g.execute("SELECT tokens FROM entry_autoban_applied WHERE uid=?", (uid,)).fetchone()
|
||||
if not was_banned:
|
||||
return set()
|
||||
legacy = False
|
||||
if row is None and con.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='entry_autobans'").fetchone():
|
||||
cols = {r[1] for r in con.execute("PRAGMA table_info(entry_autobans)")}
|
||||
if "tokens" in cols:
|
||||
# Older cluster bans recorded the original preimage after applying.
|
||||
# Do not burn those same credentials again while migrating receipts.
|
||||
applied = " AND applied=1" if "applied" in cols else ""
|
||||
row = con.execute("SELECT tokens FROM entry_autobans WHERE uid=?" + applied
|
||||
+ " ORDER BY rowid DESC LIMIT 1", (uid,)).fetchone()
|
||||
legacy = True
|
||||
if row is None or (legacy and not row["tokens"]):
|
||||
return set()
|
||||
data = json.loads(row["tokens"])
|
||||
if legacy:
|
||||
if not isinstance(data, list) or any(not isinstance(item, dict) for item in data):
|
||||
raise ValueError("invalid autoban recovery record")
|
||||
data = [[item.get("id"), item.get("name")] for item in data]
|
||||
if not isinstance(data, list) or any(
|
||||
not isinstance(item, list) or len(item) != 2 or type(item[0]) is not int
|
||||
or not isinstance(item[1], str) for item in data):
|
||||
raise ValueError("invalid autoban apply receipt")
|
||||
return {tuple(item) for item in data}
|
||||
|
||||
|
||||
def ban_user(uid, reason="entry_ip_collision", taken=None):
|
||||
uid = int(uid)
|
||||
if uid in PROTECT:
|
||||
return False
|
||||
g = _connect(GW_DB)
|
||||
saved = None
|
||||
try:
|
||||
# Same acquisition order as econ_guard/account_admin: gateway, then bot.
|
||||
# Keep the gateway write reservation through the separate durable audit
|
||||
g.execute("BEGIN IMMEDIATE")
|
||||
con = _connect(BOT_DB)
|
||||
try:
|
||||
con.execute("BEGIN IMMEDIATE")
|
||||
if (con.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='ban_wl'").fetchone()
|
||||
and con.execute("SELECT 1 FROM ban_wl WHERE uid=?", (uid,)).fetchone()):
|
||||
return False
|
||||
account = con.execute("SELECT token_name,admin,banned FROM users WHERE tg_id=?",
|
||||
(uid,)).fetchone()
|
||||
if account is not None and account["admin"]:
|
||||
return False
|
||||
tname = _main_name(account["token_name"], uid) if account is not None else None
|
||||
was_banned = bool(account["banned"]) if account is not None else False
|
||||
if tname and con.execute("SELECT 1 FROM users WHERE token_name=? AND tg_id!=? LIMIT 1",
|
||||
(tname, uid)).fetchone():
|
||||
raise ValueError("ambiguous autoban main ownership")
|
||||
names = list(dict.fromkeys(n for n in (tname, "pm%d" % uid, "sol%d" % uid) if n))
|
||||
tokens = []
|
||||
for name in names:
|
||||
tokens.extend(g.execute(
|
||||
"SELECT id,name,status,remain_quota,unlimited_quota FROM tokens "
|
||||
"WHERE name=? AND deleted_at IS NULL ORDER BY id", (name,)).fetchall())
|
||||
finite = [row for row in tokens if not row["unlimited_quota"]]
|
||||
if any(type(row["remain_quota"]) is not int for row in finite):
|
||||
raise ValueError("invalid autoban quota")
|
||||
processed = _processed(g, con, uid, was_banned)
|
||||
pending = [row for row in finite if (row["id"], row["name"]) not in processed]
|
||||
if any(row["remain_quota"] > 0 for row in pending):
|
||||
saved = _snapshot(con, uid, reason, [
|
||||
{"id": row["id"], "name": row["name"], "status": row["status"],
|
||||
"quota": row["remain_quota"], "unlimited_quota": row["unlimited_quota"]}
|
||||
for row in pending])
|
||||
con.commit() # FULL synchronous audit, before any token UPDATE.
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
# Financial preimage is already durable. Attach only now, otherwise
|
||||
# BEGIN IMMEDIATE would lock bot.db against the independent audit commit.
|
||||
g.execute("ATTACH DATABASE ? AS bot", (Path(BOT_DB).resolve().as_uri() + "?mode=rw",))
|
||||
current = g.execute("SELECT token_name,admin,banned FROM bot.users WHERE tg_id=?",
|
||||
(uid,)).fetchone()
|
||||
if (tuple(current) if current is not None else None) != (
|
||||
tuple(account) if account is not None else None):
|
||||
raise ValueError("autoban account changed; retry")
|
||||
if account is None:
|
||||
if g.execute("INSERT INTO bot.users(tg_id,username,banned) VALUES(?,'',1)", (uid,)).rowcount != 1:
|
||||
raise RuntimeError("autoban account insert failed")
|
||||
elif g.execute("UPDATE bot.users SET banned=1 WHERE tg_id=?", (uid,)).rowcount != 1:
|
||||
raise RuntimeError("autoban account update failed")
|
||||
if tname and g.execute("SELECT 1 FROM bot.users WHERE token_name=? AND tg_id!=? LIMIT 1",
|
||||
(tname, uid)).fetchone():
|
||||
raise ValueError("ambiguous autoban main ownership")
|
||||
if saved and g.execute(
|
||||
"UPDATE bot.entry_autobans SET applied=1 "
|
||||
"WHERE rowid=? AND uid=? AND tokens=? AND applied=0",
|
||||
(saved[0], uid, saved[1])).rowcount != 1:
|
||||
raise RuntimeError("autoban recovery record changed")
|
||||
for row in finite:
|
||||
identity = (row["id"], row["name"])
|
||||
quota = row["remain_quota"] if identity in processed else min(row["remain_quota"], 0)
|
||||
status = 2 if row["status"] == 1 else row["status"]
|
||||
if quota != row["remain_quota"] or status != row["status"]:
|
||||
cur = g.execute(
|
||||
"UPDATE tokens SET status=?,remain_quota=? WHERE id=? AND name=? "
|
||||
"AND deleted_at IS NULL AND remain_quota=? AND status IS ? "
|
||||
"AND NOT COALESCE(unlimited_quota,0)",
|
||||
(status, quota, row["id"], row["name"], row["remain_quota"], row["status"]))
|
||||
if cur.rowcount != 1:
|
||||
raise RuntimeError("autoban token update failed")
|
||||
processed.add(identity)
|
||||
g.execute("UPDATE users SET status=2 WHERE username=? AND status=1", ("tg%d" % uid,))
|
||||
if g.execute("INSERT OR REPLACE INTO entry_autoban_applied(uid,tokens) VALUES(?,?)",
|
||||
(uid, json.dumps(sorted(processed), ensure_ascii=False, separators=(",", ":")))).rowcount != 1:
|
||||
raise RuntimeError("autoban apply receipt failed")
|
||||
# roll back bot flags; WAL cannot promise cross-file crash atomicity.
|
||||
g.commit()
|
||||
except BaseException:
|
||||
g.rollback()
|
||||
raise
|
||||
finally:
|
||||
g.close()
|
||||
if tname:
|
||||
con = _connect(SKIN_DB)
|
||||
try:
|
||||
con.execute("DELETE FROM ip_claims WHERE token_name=?", (tname,))
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
if taken is not None and saved:
|
||||
taken[uid] = saved[1]
|
||||
log.warning("[ENTRY-AUTOBAN] enforced uid=%s", uid)
|
||||
return not was_banned
|
||||
|
||||
|
||||
def ban_cluster(uids, reason="entry_ip_collision"):
|
||||
uids = [int(u) for u in uids]
|
||||
if not enabled():
|
||||
log.warning("[ENTRY-AUTOBAN] disabled")
|
||||
return []
|
||||
out = []
|
||||
for uid in dict.fromkeys(uids):
|
||||
try:
|
||||
if ban_user(uid, reason):
|
||||
out.append(uid)
|
||||
except Exception as exc:
|
||||
log.error("entry_autoban failed uid=%s error=%s", uid, type(exc).__name__)
|
||||
return out
|
||||
|
||||
|
||||
def _gw_exec(sql, params=()):
|
||||
con = sqlite3.connect(GW_DB, timeout=10)
|
||||
try:
|
||||
con.execute(sql, params)
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _last_snapshot(uid):
|
||||
"""Pre-ban token state written by _snapshot(), newest first."""
|
||||
try:
|
||||
con = sqlite3.connect(BOT_DB, timeout=10)
|
||||
try:
|
||||
con.execute("CREATE TABLE IF NOT EXISTS entry_autobans("
|
||||
"ts INTEGER NOT NULL, uid INTEGER NOT NULL, reason TEXT NOT NULL, "
|
||||
"tokens TEXT NOT NULL DEFAULT '')")
|
||||
row = con.execute("SELECT tokens FROM entry_autobans WHERE uid=? "
|
||||
"ORDER BY ts DESC, rowid DESC LIMIT 1",
|
||||
(int(uid),)).fetchone()
|
||||
finally:
|
||||
con.close()
|
||||
except Exception:
|
||||
log.exception("entry_unban snapshot read uid=%s", uid)
|
||||
return []
|
||||
if not row or not row[0]:
|
||||
return []
|
||||
try:
|
||||
data = json.loads(row[0])
|
||||
except ValueError:
|
||||
return []
|
||||
seen, clean = set(), []
|
||||
for item in data if isinstance(data, list) else []:
|
||||
if not isinstance(item, dict) or "id" not in item or item["id"] in seen:
|
||||
continue
|
||||
seen.add(item["id"])
|
||||
clean.append(item)
|
||||
return clean
|
||||
|
||||
|
||||
def unban_user(uid, *, restore_tokens=True, reason="admin_button",
|
||||
actor_uid=None, admin_ids=()):
|
||||
import account_admin
|
||||
account_admin.unban_account(BOT_DB, GW_DB, uid, actor_uid=actor_uid,
|
||||
admin_ids=admin_ids)
|
||||
return True
|
||||
|
||||
|
||||
def unban_cluster(uids, reason="admin_button", *, actor_uid=None, admin_ids=()):
|
||||
"""Compatibility entry point; each target uses the same authorized unban."""
|
||||
out = []
|
||||
for uid in dict.fromkeys(uids):
|
||||
if unban_user(uid, reason=reason, actor_uid=actor_uid, admin_ids=admin_ids):
|
||||
out.append(uid)
|
||||
return out
|
||||
Reference in New Issue
Block a user