Harden entry safety, unify runtime config, bound document unpacking
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

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.
This commit is contained in:
Vlad Gothbreach
2026-10-31 00:39:35 +03:00
parent 52018ca568
commit af292ff15d
52 changed files with 2858 additions and 551 deletions
+10 -8
View File
@@ -4,6 +4,7 @@ import urllib.parse
import contextvars # [EFFORT 2110]
from contextlib import asynccontextmanager, closing
from pathlib import Path
from runtime_config import bot_config_path, effective_bot_config, skin_db_path
import reminders as reminder_store
import key_notifications
import community_economy
@@ -32,13 +33,13 @@ from aiogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKe
from aiogram.types import WebAppInfo # [WEBAPP 18.10]
from aiogram.enums import ParseMode
CFG_PATH = os.environ.get("GROK_BOT_CFG", "/opt/grok-bot/config.json")
CFG_PATH = bot_config_path()
# Секреты НЕ хардкодятся: только env-фоллбэк, реальные значения — в config.json (не в git).
DEFAULT_CFG = {
"bot_token": os.environ.get("GROK_BOT_TOKEN", ""),
"channel_username": "@alstack", "channel_link": "https://t.me/alstack", "channel_title": "@alstack",
"support": "@your-handle",
"newapi_url": "http://127.0.0.1:3000",
"newapi_url": "http://127.0.0.1:48000",
"newapi_user": "root", "newapi_pass": os.environ.get("NEWAPI_PASS", ""),
"newapi_db": "/opt/grok-gateway/new-api/one-api.db",
"public_base": "https://api.your-domain.com",
@@ -52,10 +53,11 @@ def load_cfg():
if not os.path.exists(CFG_PATH):
print(f"[FATAL] config.json missing at {CFG_PATH}"); sys.exit(1)
try:
with open(CFG_PATH, encoding="utf-8") as _cfh:
with open(CFG_PATH, encoding="utf-8-sig") as _cfh:
cfg.update(json.load(_cfh))
except Exception as e:
print(f"[FATAL] config.json broken: {e}"); sys.exit(1)
cfg = effective_bot_config(cfg)
for k in ("bot_token", "main_key", "channel_username", "newapi_pass"):
if not cfg.get(k):
print(f"[FATAL] config.json missing required key: {k}"); sys.exit(1)
@@ -70,8 +72,7 @@ def load_cfg():
return cfg
CFG = load_cfg()
KEY_WAIT_SEC = int(CFG.get("key_wait_hours", 24)) * 3600
BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")
SKIN_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db")
BOT_DB = CFG["bot_db"]
def tge(em="🩸", _old=None):
return em # plain unicode: текст уходит с parse_mode=HTML, tg-emoji там запрещён
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
@@ -461,7 +462,7 @@ async def abuse_watchdog(bot):
_wm = int(time.time()) # первый запуск: историю НЕ трогаем (кольца забанены вручную)
_nb = 0
try:
sk = sqlite3.connect(Path(SKIN_DB).resolve().as_uri() + "?mode=ro", uri=True)
sk = sqlite3.connect(Path(skin_db_path()).resolve().as_uri() + "?mode=ro", uri=True)
_excl = _iplock_excluded_ips() # [IPLOCK-SRVEXCL 2010] loopback + IISHKO_SRV_EXCLUDED_IPS
iprows = sk.execute(
"SELECT ip, GROUP_CONCAT(DISTINCT token_name) FROM ip_lock_events "
@@ -3060,7 +3061,7 @@ async def cb_pquiz(c: CallbackQuery):
await c.answer("Верно!" if ok else "Мимо")
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
GW_DB = CFG["newapi_db"]
QUOTA_PER_USD = 500000
def _cas_wallet(uid, paused_ok=True):
@@ -3666,7 +3667,7 @@ def _full_ban(uid, tname, reason):
# освобождаем ip-клейм: забаненный токен не должен держать IP на 24ч (ложные локи соседей)
if tname:
try:
_sk = sqlite3.connect(SKIN_DB, timeout=10)
_sk = sqlite3.connect(Path(skin_db_path()).resolve().as_uri() + "?mode=rw", uri=True, timeout=10)
_sk.execute("DELETE FROM ip_claims WHERE token_name=?", (tname,))
_sk.commit()
_sk.close()
@@ -14655,6 +14656,7 @@ async def cmd_unknown(m: Message):
import entry_admin as _entry_admin
_entry_admin.BOT_DB = BOT_DB
try:
_entry_admin.init_db()
except Exception: