Files
Vlad Gothbreach af292ff15d
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
Harden entry safety, unify runtime config, bound document unpacking
Shared-IP safety: entry autoban and entry notifications default off, and a
shared IP is treated as review evidence only. ban_user/ban_cluster refuse
reason=entry_ip_collision (also with the legacy flag set to 1), so token status
and quota are never touched; explicit admin moderation still works.

Reproducible startup: new bot/runtime_config.py and scripts/run.py load the
repository .env (or --env-file) without shell interpolation, normalize
config/DB/upstream aliases, and make the bot, Mini App, gateway, econ cap,
account admin, mk_daemon, entry admin and key notifications resolve the same
paths. "run.py <target> --check" is an offline preflight that starts nothing
and reports placeholders, missing upstream DB and invalid data directories.

Resource limits: aggregate Office decompression, a 400 read-entry cap and a
per-row XLSX cell budget stop early; truncated or corrupt archives are
reported instead of raising.

Deploy and docs: only source-backed systemd units remain, and
deploy/runtime.env.example documents the environment contract including the
0600 session-secret file rules. Removed the destructive
"cp bot/iishko_bot.py bot/grok_bot.py" instruction, the unused generated site/
snapshot and the unsupported iishko-ts staging unit; corrected .env.example,
README, ARCHITECTURE, SECURITY, docs/native-gateway.md and iishko-ts/README.md.

Tests: entry safety, runtime bootstrap, economy paths, file intake, deploy
contract, abilities_guard CLI, and a startup smoke that launches all three
components through scripts/run.py with non-loopback network blocked. Every
config reader, selfcheck included, accepts a UTF-8 BOM.

Verified on this tree: pytest 716 passed + 322 subtests, node --test 73/73,
go test and go vet clean, selfcheck --source-only ok, gitleaks worktree and
history 0 findings. No production or live-split changes are included.
2026-10-31 00:39:35 +03:00

188 lines
6.5 KiB
Python

from contextlib import closing
import sqlite3
import time
import unicodedata
from runtime_config import bot_db_path
BOT_DB = bot_db_path()
WINDOW = 86400
TAG_MAX = 48
TAG_LIMIT = 12
def _connect():
con = sqlite3.connect(BOT_DB, timeout=10)
con.row_factory = sqlite3.Row
con.execute("PRAGMA busy_timeout=8000")
return con
def init_db():
with closing(_connect()) as con:
con.executescript("""
CREATE TABLE IF NOT EXISTS wa_entry_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip_hmac TEXT NOT NULL,
tag TEXT NOT NULL,
created_at INTEGER NOT NULL,
by_uid INTEGER NOT NULL DEFAULT 0,
UNIQUE(ip_hmac, tag)
);
CREATE INDEX IF NOT EXISTS wa_entry_tag_net ON wa_entry_tags(ip_hmac);
CREATE TABLE IF NOT EXISTS wa_entry_tag_prompts (
message_id INTEGER PRIMARY KEY,
chat_id INTEGER NOT NULL,
alert_id INTEGER NOT NULL,
ip_hmac TEXT NOT NULL,
alert_message_id INTEGER NOT NULL DEFAULT 0,
admin_id INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
""")
con.commit()
return True
def clean_tag(value):
if not isinstance(value, str):
return ""
text = "".join(ch for ch in value[:TAG_MAX * 4]
if not unicodedata.category(ch).startswith("C"))
return " ".join(text.split())[:TAG_MAX]
def alert(alert_id):
try:
alert_id = int(alert_id)
except (TypeError, ValueError):
return None
with closing(_connect()) as con:
row = con.execute("SELECT id,ip_hmac,created_at,accounts,country,city,geo_source "
"FROM wa_entry_alerts WHERE id=?", (alert_id,)).fetchone()
if row is None:
return None
data = dict(row)
try:
import json
data["accounts"] = json.loads(data.get("accounts") or "[]")
except ValueError:
data["accounts"] = []
data["uids"] = [int(item["uid"]) for item in data["accounts"]
if isinstance(item, dict) and isinstance(item.get("uid"), int)]
return data
def recent_alerts(limit=5):
limit = max(1, min(int(limit or 5), 20))
with closing(_connect()) as con:
rows = con.execute("SELECT id,ip_hmac,created_at,accounts,country,city "
"FROM wa_entry_alerts ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
out = []
for row in rows:
item = dict(row)
try:
import json
item["accounts"] = json.loads(item.get("accounts") or "[]")
except ValueError:
item["accounts"] = []
out.append(item)
return out
def net_accounts(ip_hmac, window=WINDOW, limit=40):
"""Every account that entered through this network inside the window."""
now = int(time.time())
with closing(_connect()) as con:
rows = con.execute(
"SELECT v.uid, u.username, COALESCE(u.banned,0) AS banned, COALESCE(u.admin,0) AS admin, "
"v.last_visit, v.country, v.city FROM wa_entry_visits v "
"LEFT JOIN users u ON u.tg_id=v.uid WHERE v.ip_hmac=? AND v.last_visit>? "
"ORDER BY v.last_visit DESC LIMIT ?", (str(ip_hmac), now - int(window), limit)).fetchall()
return [dict(row) for row in rows]
def tags(ip_hmac):
if not ip_hmac:
return []
with closing(_connect()) as con:
rows = con.execute("SELECT tag FROM wa_entry_tags WHERE ip_hmac=? "
"ORDER BY id LIMIT ?", (str(ip_hmac), TAG_LIMIT)).fetchall()
return [row["tag"] for row in rows]
def add_tag(ip_hmac, tag, by_uid=0):
tag = clean_tag(tag)
if not tag or not ip_hmac:
return False
with closing(_connect()) as con:
count = con.execute("SELECT COUNT(*) FROM wa_entry_tags WHERE ip_hmac=?", (str(ip_hmac),)).fetchone()[0]
exists = con.execute("SELECT 1 FROM wa_entry_tags WHERE ip_hmac=? AND tag=?",
(str(ip_hmac), tag)).fetchone()
if exists is None and count >= TAG_LIMIT:
return False
con.execute("INSERT OR IGNORE INTO wa_entry_tags(ip_hmac,tag,created_at,by_uid) VALUES(?,?,?,?)",
(str(ip_hmac), tag, int(time.time()), int(by_uid or 0)))
con.commit()
return True
def del_tag(ip_hmac, tag):
tag = clean_tag(tag)
if not tag or not ip_hmac:
return False
with closing(_connect()) as con:
cur = con.execute("DELETE FROM wa_entry_tags WHERE ip_hmac=? AND tag=?",
(str(ip_hmac), tag))
con.commit()
return cur.rowcount > 0
def apply_tags(ip_hmac, raw, by_uid=0):
"""Accepts 'a, b, c' or '-a' to drop a tag. Returns (added, removed, all_tags)."""
added, removed = [], []
for chunk in str(raw or "").replace(";", ",").split(",")[:8]:
chunk = chunk.strip()
if not chunk:
continue
if chunk.startswith("-"):
if del_tag(ip_hmac, chunk[1:]):
removed.append(clean_tag(chunk[1:]))
elif add_tag(ip_hmac, chunk, by_uid):
added.append(clean_tag(chunk))
return added, removed, tags(ip_hmac)
def save_prompt(message_id, chat_id, alert_id, ip_hmac, alert_message_id, admin_id):
with closing(_connect()) as con:
con.execute("DELETE FROM wa_entry_tag_prompts WHERE created_at<?",
(int(time.time()) - 3 * WINDOW,))
con.execute("INSERT OR REPLACE INTO wa_entry_tag_prompts"
"(message_id,chat_id,alert_id,ip_hmac,alert_message_id,admin_id,created_at) "
"VALUES(?,?,?,?,?,?,?)",
(int(message_id), int(chat_id), int(alert_id), str(ip_hmac),
int(alert_message_id or 0), int(admin_id), int(time.time())))
con.commit()
return True
def has_prompt(message_id, admin_id):
with closing(_connect()) as con:
row = con.execute("SELECT 1 FROM wa_entry_tag_prompts WHERE message_id=? AND admin_id=?",
(int(message_id), int(admin_id))).fetchone()
return row is not None
def take_prompt(message_id):
with closing(_connect()) as con:
row = con.execute("SELECT * FROM wa_entry_tag_prompts WHERE message_id=?",
(int(message_id),)).fetchone()
if row is None:
return None
con.execute("DELETE FROM wa_entry_tag_prompts WHERE message_id=?", (int(message_id),))
con.commit()
return dict(row)
if __name__ == "__main__":
print("init_db:", init_db())