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.
129 lines
4.8 KiB
Python
129 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
import argparse
|
|
from contextlib import closing
|
|
from pathlib import Path
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
|
|
from runtime_config import gateway_db_path
|
|
|
|
GW_DB = gateway_db_path()
|
|
BOT_SRC = os.environ.get("IISHKO_BOT_SOURCE") or str(Path(__file__).with_name("grok_bot.py"))
|
|
BOT_SRC_FALLBACK = BOT_SRC
|
|
TIER_GROUPS = ("t1", "t2", "t3", "t4")
|
|
|
|
LIVE_SQL = ("SELECT COUNT(*) FROM abilities a JOIN channels c ON c.id=a.channel_id "
|
|
"WHERE a.model=? AND a.enabled=1 AND c.status=1 "
|
|
"AND instr(',' || replace(c.models,' ','') || ',', ',' || a.model || ',')>0") # [FIX-2410] containment как в repair
|
|
|
|
|
|
def _read_src(path):
|
|
try:
|
|
with open(path, encoding="utf-8") as f:
|
|
return f.read()
|
|
except OSError as e:
|
|
print(time.strftime("%F %T"), "cannot read", path, str(e)[:120], flush=True)
|
|
return ""
|
|
|
|
|
|
def _parse_tiers(src):
|
|
m = re.search(r"^TIER_MODELS\s*=\s*\{(.*?)^\s*\}", src, re.S | re.M)
|
|
if not m:
|
|
return {}
|
|
body = re.sub(r"#[^\n]*", "", m.group(1))
|
|
tiers = {}
|
|
for tm in re.finditer(r"(\d+)\s*:\s*\[(.*?)\]", body, re.S):
|
|
names = re.findall(r"""["']([A-Za-z0-9._/\-]+)["']""", tm.group(2))
|
|
if names:
|
|
tiers[int(tm.group(1))] = sorted(set(names))
|
|
return tiers
|
|
|
|
|
|
def catalog_tiers(path=None):
|
|
"""Read tier declarations without importing or starting the bot."""
|
|
paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK)
|
|
for p in paths:
|
|
tiers = _parse_tiers(_read_src(p))
|
|
if tiers:
|
|
return tiers
|
|
return {}
|
|
|
|
|
|
def catalog_models(tiers):
|
|
"""Union моделей каталога (для отчёта dark)."""
|
|
return sorted({m for ms in tiers.values() for m in ms})
|
|
|
|
|
|
def repair_abilities(con, tiers):
|
|
if not tiers:
|
|
return 0
|
|
models = catalog_models(tiers)
|
|
order = [n for n in sorted(tiers) if 1 <= n <= 4]
|
|
if not models or not order:
|
|
return 0
|
|
|
|
def ph(n):
|
|
return ",".join(["?"] * n)
|
|
|
|
params = list(models) + list(TIER_GROUPS)
|
|
gate_parts = ['abilities."group" NOT IN (' + ph(len(TIER_GROUPS)) + ')']
|
|
for n in order:
|
|
cum = [m for i in order if i <= n for m in tiers[i]]
|
|
if not cum:
|
|
continue
|
|
gate_parts.append('(abilities."group"=? AND abilities.model IN ('
|
|
+ ph(len(cum)) + '))')
|
|
params.append("t" + str(n))
|
|
params.extend(cum)
|
|
# [FIX-2410] Нормализация containment: c.models может быть «m1, m2» с пробелами —
|
|
sql = ("UPDATE abilities SET enabled=1 WHERE enabled=0 AND model IN ("
|
|
+ ph(len(models)) + ") "
|
|
+ "AND EXISTS (SELECT 1 FROM channels c WHERE c.id=abilities.channel_id "
|
|
"AND c.status=1 AND instr(',' || replace(c.models,' ','') || ',', "
|
|
"',' || abilities.model || ',')>0) "
|
|
+ "AND (" + " OR ".join(gate_parts) + ")")
|
|
return con.execute(sql, params).rowcount
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(
|
|
description="Check route availability; read-only unless --apply is explicit.")
|
|
parser.add_argument("--db", help="absolute path to an existing New API SQLite database")
|
|
parser.add_argument("--source", help="absolute path to bot source containing TIER_MODELS")
|
|
parser.add_argument("--apply", action="store_true", help="explicitly re-enable matching abilities")
|
|
args = parser.parse_args(argv)
|
|
if args.apply and (not args.db or not args.source):
|
|
parser.error("--apply requires explicit --db and --source")
|
|
db, source = Path(args.db or GW_DB), Path(args.source or BOT_SRC)
|
|
for label, path in (("database", db), ("source", source)):
|
|
if not path.is_absolute() or not path.is_file():
|
|
parser.error(label + " must be an absolute path to an existing file")
|
|
tiers = catalog_tiers(str(source))
|
|
if not tiers:
|
|
print("No catalog tiers parsed; no database changes made.", flush=True)
|
|
return 1
|
|
models = catalog_models(tiers)
|
|
mode = "rw" if args.apply else "ro"
|
|
try:
|
|
with closing(sqlite3.connect(db.resolve().as_uri() + "?mode=" + mode,
|
|
uri=True, timeout=10)) as con:
|
|
fixed = 0
|
|
with con:
|
|
if args.apply:
|
|
fixed = repair_abilities(con, tiers)
|
|
dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]]
|
|
except sqlite3.Error as exc:
|
|
print("Database check failed: " + type(exc).__name__, file=sys.stderr)
|
|
return 2
|
|
print("mode=%s catalog=%d re-enabled=%d dark=%s"
|
|
% ("apply" if args.apply else "dry-run", len(models), fixed,
|
|
",".join(dark) if dark else "none"), flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|