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
+37 -23
View File
@@ -1,13 +1,18 @@
#!/usr/bin/env python3
import argparse
from contextlib import closing
from pathlib import Path
import os
import re
import sqlite3
import sys
import time
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
BOT_SRC = "/opt/grok-bot/iishko_bot.py" # [BOTFIX 2310] живой активный сервис
BOT_SRC_FALLBACK = "/opt/grok-bot/grok_bot.py" # старое имя (legacy)
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 "
@@ -38,8 +43,7 @@ def _parse_tiers(src):
def catalog_tiers(path=None):
"""Список тиров из исходника бота (без импорта бота).
path=None: сначала живой iishko_bot.py (BOT_SRC), затем legacy grok_bot.py."""
"""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))
@@ -84,29 +88,39 @@ def repair_abilities(con, tiers):
return con.execute(sql, params).rowcount
def main():
tiers = catalog_tiers()
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(time.strftime("%F %T"), "no catalog tiers parsed - refusing to touch abilities",
flush=True)
print("No catalog tiers parsed; no database changes made.", flush=True)
return 1
models = catalog_models(tiers)
con = sqlite3.connect(GW_DB, timeout=60)
mode = "rw" if args.apply else "ro"
try:
con.execute("PRAGMA busy_timeout=60000")
fixed = repair_abilities(con, tiers)
con.commit()
dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]]
con.close()
except Exception as e:
print(time.strftime("%F %T"), "ERROR", str(e)[:200], flush=True)
try:
con.rollback()
except Exception:
pass
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(time.strftime("%F %T"), "catalog=%d re-enabled=%d dark=%s"
% (len(models), fixed, ",".join(dark) if dark else "none"), flush=True)
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
+2 -1
View File
@@ -6,9 +6,10 @@ import sqlite3
import time
from account_limits import account_uid, _name_scope
from runtime_config import econ_state_path
PAUSE_PATH = "/opt/grok-bot/econ_cap_state.json"
PAUSE_PATH = econ_state_path()
# Account-level locks that are not owned by a ban; unban must never clear them.
INDEPENDENT_FLAGS = ("api_blocked", "key_locked", "chat_key_locked")
+2 -2
View File
@@ -7,8 +7,8 @@
"newapi_url": "http://127.0.0.1:48000",
"newapi_user": "REPLACE_ME_NEWAPI_ADMIN_LOGIN",
"newapi_pass": "REPLACE_ME_NEWAPI_ADMIN_PASSWORD",
"newapi_db": "/opt/grok-gateway/new-api/data/one-api.db",
"bot_db": "/opt/grok-bot/bot.db",
"newapi_db": "./one-api.db",
"bot_db": "./bot.db",
"public_base": "http://127.0.0.1:8850",
"user_quota": 500000000,
"unlimited": false,
+4 -3
View File
@@ -8,10 +8,11 @@ from pathlib import Path
from contextlib import closing
from account_limits import account_uid
from runtime_config import bot_db_path, econ_state_path, gateway_db_path
BOT_DB = '/opt/grok-bot/bot.db'
NA_DB = '/opt/grok-gateway/new-api/one-api.db'
STATE = '/opt/grok-bot/econ_cap_state.json'
BOT_DB = bot_db_path()
NA_DB = gateway_db_path()
STATE = econ_state_path()
# Keep this literal compatible with the Mini App's read-only policy parser.
DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000}
QUOTA_PER_USD = 500000
+3 -2
View File
@@ -1,10 +1,11 @@
from contextlib import closing
import os
import sqlite3
import time
import unicodedata
BOT_DB = os.environ.get("IISHKO_BOT_DB", os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db"))
from runtime_config import bot_db_path
BOT_DB = bot_db_path()
WINDOW = 86400
TAG_MAX = 48
TAG_LIMIT = 12
+16 -7
View File
@@ -1,25 +1,23 @@
"""Opt-in: automatic IP-collision bans run only with IISHKO_ENTRY_AUTOBAN=1.
A shared IP (NAT, mobile CGNAT, family Wi-Fi) is otherwise only an operator alert.
Manual operator bans (ban_cluster) are not gated by this flag."""
import json
import logging
import os
from pathlib import Path
import re
import sqlite3
from runtime_config import bot_db_path, env_enabled, gateway_db_path, skin_db_path
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") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db")
BOT_DB = bot_db_path()
GW_DB = gateway_db_path()
SKIN_DB = skin_db_path()
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", "0").strip().lower() in ("1", "on", "yes", "true")
return env_enabled("IISHKO_ENTRY_AUTOBAN")
def _connect(path):
@@ -97,6 +95,11 @@ def _processed(g, con, uid, was_banned):
def ban_user(uid, reason="entry_ip_collision", taken=None):
"""Legacy enforcement; an omitted reason or a shared IP never authorizes sanctions."""
# An IP match is evidence for review, not account ownership or fraud.
if reason == "entry_ip_collision":
log.info("[ENTRY-AUTOBAN] shared-IP ban skipped uid=%s", uid)
return False
uid = int(uid)
if uid in PROTECT:
return False
@@ -200,7 +203,13 @@ def ban_user(uid, reason="entry_ip_collision", taken=None):
def ban_cluster(uids, reason="entry_ip_collision"):
if reason == "entry_ip_collision":
log.info("[ENTRY-AUTOBAN] shared network recorded without sanctions")
return []
uids = [int(u) for u in uids]
if reason != "admin_button" and not enabled():
log.warning("[ENTRY-AUTOBAN] disabled")
return []
out = []
for uid in dict.fromkeys(uids):
try:
+3 -14
View File
@@ -7,7 +7,6 @@ import hmac
import ipaddress
import json
import math
import os
from pathlib import Path
import re
import secrets
@@ -20,6 +19,7 @@ import logging
log = logging.getLogger("entry_telemetry")
from support_store import NotificationError
from runtime_config import notifications_enabled
WINDOW = 86400
# Known shared reverse-proxy/WARP networks; operators may add their own NAT/relay ranges.
@@ -75,9 +75,7 @@ def public_ip(value):
def delivery_enabled():
# The existing support switch is also a hard entry-delivery kill switch for old fixtures.
return all(os.environ.get(name, "1") != "0" for name in (
"IISHKO_NOTIFICATIONS_ENABLED", "IISHKO_SUPPORT_DELIVERY_ENABLED", "IISHKO_ENTRY_DELIVERY_ENABLED"))
return notifications_enabled("entry")
def _label(value, length):
@@ -209,7 +207,6 @@ class EntryTelemetry:
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
raise EntryError(403, "entry_forbidden", "Не удалось подтвердить аккаунт.")
now = int(self.clock())
ban_uids = []
with closing(self.connect()) as con:
self._eligible(con, uid)
ip = public_ip(ip)
@@ -245,15 +242,7 @@ class EntryTelemetry:
"VALUES(?,?,?,?,?,?)", (tag, now, payload, geo["country"], geo["city"], geo["source"]))
con.executemany("INSERT INTO wa_entry_outbox(alert_id,owner_id) VALUES(?,?)",
[(alert.lastrowid, owner) for owner in self.owners])
ban_uids = [row["uid"] for row in accounts]
con.commit()
if ban_uids:
try:
import entry_autoban
if entry_autoban.enabled(): # opt-in; otherwise the alert above is the only effect
entry_autoban.ban_cluster(ban_uids, reason="entry_ip_collision")
except Exception:
log.exception("entry autoban failed")
def claim(self):
now = self.clock()
@@ -303,7 +292,7 @@ def notification_text(claim, tags=()):
observed = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(claim["created_at"]))
text = ("Mini App: совпадение сети за 24 часа\nНаблюдение: %s\n%s\nПримерный регион: %s\nИсточник: %s\n"
"Сеть #%s. Совпадение IP не доказывает общего владельца: возможны Wi-Fi, NAT, VPN или relay. "
"Автобан применён автоматически (все аккаунты сети, кроме админов).\nГеоданные: IP Geolocation by DB-IP, CC BY 4.0 — https://db-ip.com" %
"Автобан не применяется; требуется проверка администратором.\nГеоданные: IP Geolocation by DB-IP, CC BY 4.0 — https://db-ip.com" %
(observed, users, place, source, claim["ip_hmac"][:12]))[:3000]
# Operator tags always survive truncation: they are the fastest way to recognise a network.
marks = " · ".join(str(tag) for tag in list(tags or ())[:12] if tag)
+211 -51
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import io
import re
import zipfile
import zlib
from dataclasses import dataclass, field
from html import unescape
@@ -11,9 +12,19 @@ MAX_FILE_BYTES = 8 * 1024 * 1024
TEXT_BUDGET = 24000
_MAX_PDF_PAGES = 60
_MAX_XLSX_ROWS = 400
_MAX_XLSX_CELLS = 2000
_MAX_ZIP_ENTRIES = 200
_MAX_PPTX_SLIDES = 300
_MAX_UNPACKED_BYTES = 64 * 1024 * 1024
# A ZIP amplifies its input: an 8 MB .pptx inflates into hundreds of MB. The old
# code read every entry in full, so a per-entry limit bounded nothing in memory.
# Here both the entry and the whole archive are bounded, and reads are chunked.
_OFFICE_ENTRY_MAX_BYTES = 8 * 1024 * 1024
_OFFICE_TOTAL_MAX_BYTES = 24 * 1024 * 1024
_OFFICE_SLIDE_MAX_BYTES = 4 * 1024 * 1024
_OFFICE_MAX_SLIDES = 200
_OFFICE_MAX_ENTRIES = 400
_OFFICE_READ_CHUNK = 128 * 1024
_OFFICE_MAX_WARNINGS = 6
TEXT_EXTS = {
".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv", ".json", ".jsonl",
@@ -85,68 +96,190 @@ def _looks_binary(text: str) -> bool:
return len(_CTRL_RE.findall(sample)) / len(sample) > 0.02
def _finish(text: str, kind: str, warnings: list | None = None) -> ExtractResult:
def _finish(text: str, kind: str, warnings: list | None = None, cut: bool = False) -> ExtractResult:
"""Build the result. `cut` means the content is knowingly incomplete."""
clean = text.replace("\r\n", "\n").replace("\r", "\n")
clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
truncated = len(clean) > TEXT_BUDGET
if truncated:
notes = list(warnings or [])
truncated = bool(cut) or len(clean) > TEXT_BUDGET
if len(clean) > TEXT_BUDGET:
clean = clean[:TEXT_BUDGET]
warnings = list(warnings or [])
warnings.append(f"показаны первые {TEXT_BUDGET} символов")
notes.append(f"показаны первые {TEXT_BUDGET} символов")
if not clean:
return ExtractResult(ok=False, kind=kind, reason="в файле нет извлекаемого текста")
return ExtractResult(
ok=False, kind=kind, reason="в файле нет извлекаемого текста",
truncated=truncated, warnings=notes,
)
return ExtractResult(
ok=True, kind=kind, text=clean, chars=len(clean),
truncated=truncated, warnings=list(warnings or []),
truncated=truncated, warnings=notes,
)
def _read_entry(zf: zipfile.ZipFile, name: str) -> str:
info = zf.getinfo(name)
if info.file_size > 32 * 1024 * 1024:
raise RuntimeError(f"entry {name} распаковывается в {info.file_size // 1048576} МБ — слишком много")
return zf.read(name).decode("utf-8", "replace")
class _OfficeBudget:
"""Read Office archive entries under one shared decompression budget.
Only bytes actually read are charged (never the declared `file_size`), the
budget is shared by the whole archive, and reads go in `chunk` blocks. Every
entry we refuse or clip is recorded in `warnings`, and `cut` tells the caller
that the extracted text is incomplete.
"""
def __init__(
self,
zf: zipfile.ZipFile,
entry_limit: int = _OFFICE_ENTRY_MAX_BYTES,
total_limit: int = _OFFICE_TOTAL_MAX_BYTES,
chunk: int = _OFFICE_READ_CHUNK,
max_entries: int = _OFFICE_MAX_ENTRIES,
) -> None:
self.zf = zf
self.entry_limit = entry_limit
self.total_limit = total_limit
self.chunk = chunk
self.max_entries = max_entries
self.consumed = 0 # bytes actually decompressed
self.entries_read = 0
self.cut = False
self.warnings: list[str] = []
def note(self, msg: str, cut: bool = True) -> None:
"""Record a warning; `cut=True` marks the extracted text as incomplete."""
if cut:
self.cut = True
if msg not in self.warnings and len(self.warnings) < _OFFICE_MAX_WARNINGS:
self.warnings.append(msg)
@property
def remaining(self) -> int:
return max(0, self.total_limit - self.consumed)
@property
def at_entry_limit(self) -> bool:
return self.entries_read >= self.max_entries
def exhausted(self) -> bool:
return self.remaining <= 0
def has(self, name: str) -> bool:
try:
self.zf.getinfo(name)
except KeyError:
return False
return True
def read_prefix(self, name: str, limit: int | None = None) -> tuple[str, bool]:
"""Read the head of one entry within the budget. Returns (text, clipped).
No lookahead byte is read: reaching the cap is reported as clipped, which
is conservative (an entry of exactly cap bytes is treated as cut).
"""
if self.at_entry_limit:
self.note(f"файлов в архиве больше {self.max_entries} — остальные не читаются")
return "", True
cap = self.entry_limit if limit is None else min(limit, self.entry_limit)
cap = min(cap, self.remaining)
if cap <= 0:
self.note("предел распаковки Office-архива исчерпан — часть документа не прочитана")
return "", True
self.entries_read += 1
parts: list[bytes] = []
got = 0
with self.zf.open(name) as fh:
while got < cap:
block = fh.read(min(self.chunk, cap - got))
if not block:
break
parts.append(block)
got += len(block)
self.consumed += got
text = b"".join(parts).decode("utf-8", "replace")
clipped = got >= cap
if clipped:
# Cut in the middle of the XML: drop the trailing partial tag.
text = re.sub(r"<[^>]*$", "", text)
self.note("часть документа не прочитана: превышен предел распаковки")
return text, clipped
def _from_docx(zf: zipfile.ZipFile) -> str:
xml = _read_entry(zf, "word/document.xml")
def _from_docx(reader: _OfficeBudget) -> str:
xml, _ = reader.read_prefix("word/document.xml")
xml = xml.replace("</w:p>", "\n").replace("<w:tab/>", "\t").replace("<w:br/>", "\n")
return unescape(_TAG_RE.sub("", xml))
def _from_pptx(zf: zipfile.ZipFile) -> str:
def _from_pptx(reader: _OfficeBudget) -> str:
slides = sorted(
(n for n in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
key=lambda n: _num(n),
(n for n in reader.zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
key=_num,
)
out, chars, unpacked = [], 0, 0
for n in slides[:_MAX_PPTX_SLIDES]:
unpacked += zf.getinfo(n).file_size
if unpacked > _MAX_UNPACKED_BYTES:
raise RuntimeError(f"слайды распаковываются больше чем в {_MAX_UNPACKED_BYTES // 1048576} МБ")
if chars > TEXT_BUDGET:
break # _finish() truncates anyway; don't decompress the rest
xml = _read_entry(zf, n)
xml = xml.replace("</a:p>", "\n")
out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + unescape(_TAG_RE.sub("", xml)))
chars += len(out[-1])
total = len(slides)
if total > _OFFICE_MAX_SLIDES:
slides = slides[:_OFFICE_MAX_SLIDES]
reader.note(f"в файле {total} слайдов — прочитаны первые {_OFFICE_MAX_SLIDES}")
out: list[str] = []
produced = 0
for n in slides:
if reader.at_entry_limit:
reader.note(f"показаны не все слайды: {len(out)} из {total}")
break
if produced >= TEXT_BUDGET or reader.exhausted():
reader.note(f"показаны не все слайды: {len(out)} из {total}")
break
xml, _ = reader.read_prefix(n, limit=_OFFICE_SLIDE_MAX_BYTES)
text = unescape(_TAG_RE.sub("", xml.replace("</a:p>", "\n")))
if text.strip():
out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + text)
produced += len(text)
return "\n".join(out)
def _from_xlsx(zf: zipfile.ZipFile) -> str:
def _from_xlsx(reader: _OfficeBudget) -> str:
shared: list[str] = []
if "xl/sharedStrings.xml" in zf.namelist():
ss = _read_entry(zf, "xl/sharedStrings.xml")
shared_clipped = False
if reader.has("xl/sharedStrings.xml"):
# Half the budget: otherwise the string table eats the limit and sheets stay empty.
ss, shared_clipped = reader.read_prefix(
"xl/sharedStrings.xml", limit=min(_OFFICE_ENTRY_MAX_BYTES, reader.total_limit // 2),
)
shared = [unescape(_TAG_RE.sub("", m)) for m in re.findall(r"<si>(.*?)</si>", ss, re.S)]
sheets = [n for n in zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)]
if shared_clipped:
reader.note("таблица текстов прочитана частично — часть ячеек показана номером, а не значением")
sheets = [n for n in reader.zf.namelist() if re.fullmatch(r"xl/worksheets/sheet\d+\.xml", n)]
sheets.sort(key=lambda n: _num(n.rsplit("/", 1)[-1]))
if len(sheets) > 3:
reader.note(f"листов в книге {len(sheets)} — прочитаны первые 3")
out: list[str] = []
produced = 0
for sheet in sheets[:3]:
xml = _read_entry(zf, sheet)
if reader.at_entry_limit:
reader.note(f"показаны не все листы: {len(out)} из {len(sheets)}")
break
if produced >= TEXT_BUDGET or reader.exhausted():
reader.note("предел распаковки Office-архива исчерпан — часть листов не прочитана")
break
label = sheet.rsplit('/', 1)[-1]
xml, _ = reader.read_prefix(sheet)
rows = []
for row in re.findall(r"<row[^>]*>(.*?)</row>", xml, re.S)[:_MAX_XLSX_ROWS]:
all_rows = re.findall(r"<row[^>]*>(.*?)</row>", xml, re.S)
if len(all_rows) > _MAX_XLSX_ROWS:
reader.note(f"строк в листе больше {_MAX_XLSX_ROWS} — показаны первые")
for row in all_rows[:_MAX_XLSX_ROWS]:
if produced >= TEXT_BUDGET:
reader.note(f"показаны не все строки листа {label}")
break
cells = []
for m in re.finditer(r"<c([^>]*)(?:/>|>(.*?)</c>)", row, re.S):
row_chars = 0
for count, m in enumerate(re.finditer(r"<c([^>]*)(?:/>|>(.*?)</c>)", row, re.S), start=1):
if count > _MAX_XLSX_CELLS:
reader.note(f"ячеек в строке больше {_MAX_XLSX_CELLS} — показаны первые")
break
left = TEXT_BUDGET - produced - row_chars
if left <= 0:
# A tiny shared string reused by many cells must not inflate
# the output: stop expanding as soon as the budget is spent.
reader.note(f"показаны не все ячейки листа {label}")
break
attrs, body = m.group(1) or "", m.group(2) or ""
val = ""
vm = re.search(r"<v>(.*?)</v>", body, re.S)
@@ -158,16 +291,20 @@ def _from_xlsx(zf: zipfile.ZipFile) -> str:
im = re.search(r"<t[^>]*>(.*?)</t>", body, re.S)
if im:
val = unescape(im.group(1))
cells.append(val.replace("\t", " ").replace("\n", " "))
val = val.replace("\t", " ").replace("\n", " ")[:left]
row_chars += len(val)
cells.append(val)
if any(c.strip() for c in cells):
rows.append("\t".join(cells))
line = "\t".join(cells)
rows.append(line)
produced += len(line)
if rows:
out.append(f"--- {sheet.rsplit('/', 1)[-1]} ---\n" + "\n".join(rows))
out.append(f"--- {label} ---\n" + "\n".join(rows))
return "\n".join(out)
def _from_odt(zf: zipfile.ZipFile) -> str:
xml = _read_entry(zf, "content.xml")
def _from_odt(reader: _OfficeBudget) -> str:
xml, _ = reader.read_prefix("content.xml")
xml = re.sub(r"</text:(p|h|list-item)>", "\n", xml)
return unescape(_TAG_RE.sub("", xml))
@@ -175,16 +312,39 @@ def _from_odt(zf: zipfile.ZipFile) -> str:
def _from_office(data: bytes, ext: str) -> ExtractResult:
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
names = set(zf.namelist())
reader = _OfficeBudget(zf)
count = len(zf.infolist())
if count > _OFFICE_MAX_ENTRIES:
# Informational only: the hard bound is enforced on actual reads.
reader.note(
f"в архиве {count} файлов — читаются не более {_OFFICE_MAX_ENTRIES}",
cut=False,
)
names = zf.namelist() # central directory listing only, nothing decompressed
text: str | None = None
kind = ext.lstrip(".")
if ext == ".docx" and "word/document.xml" in names:
return _finish(_from_docx(zf), "docx")
if ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
return _finish(_from_pptx(zf), "pptx")
if ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
return _finish(_from_xlsx(zf), "xlsx")
if ext == ".odt" and "content.xml" in names:
return _finish(_from_odt(zf), "odt")
except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError) as exc:
text, kind = _from_docx(reader), "docx"
elif ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
text, kind = _from_pptx(reader), "pptx"
elif ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
text, kind = _from_xlsx(reader), "xlsx"
elif ext == ".odt" and "content.xml" in names:
text, kind = _from_odt(reader), "odt"
if text is None:
return ExtractResult(
ok=False,
reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)",
)
res = _finish(text, kind, reader.warnings, cut=reader.cut)
if not res.ok and reader.cut:
return ExtractResult(
ok=False, kind=kind, truncated=True,
reason="текста нет: сработал предел распаковки Office-файла (архив слишком «плотный»)",
warnings=list(reader.warnings),
)
return res
except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError, EOFError, zlib.error) as exc:
return ExtractResult(ok=False, reason=f"{ext} повреждён или слишком большой внутри: {type(exc).__name__}")
return ExtractResult(ok=False, reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)")
+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:
+7 -5
View File
@@ -11,6 +11,7 @@ import secrets
import sqlite3
import time
from urllib.parse import urlsplit, urlunsplit
from runtime_config import bot_config_path, effective_bot_config
log = logging.getLogger("key-notifications")
@@ -481,13 +482,14 @@ class KeyNotificationWorker:
def main():
parser = argparse.ArgumentParser(description="Read-only first-key notification aggregates; this CLI never sends.")
parser.add_argument("action", choices=("dry-run", "status"))
parser.add_argument("--bot-db", default=os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db"))
parser.add_argument("--bot-db")
parser.add_argument("--ledger")
parser.add_argument("--config", default=os.environ.get("GROK_BOT_CFG", "/opt/grok-bot/config.json"))
parser.add_argument("--config", default=bot_config_path())
args = parser.parse_args()
with open(args.config, encoding="utf-8") as config:
wait_seconds = int(json.load(config).get("key_wait_hours", 24)) * 3600
store = KeyNotificationStore(args.bot_db, args.ledger, wait_seconds=wait_seconds)
with open(args.config, encoding="utf-8-sig") as config:
cfg = effective_bot_config(json.load(config))
wait_seconds = int(cfg.get("key_wait_hours", 24)) * 3600
store = KeyNotificationStore(args.bot_db or cfg["bot_db"], args.ledger, wait_seconds=wait_seconds)
print(json.dumps(store.dry_run() if args.action == "dry-run" else store.status(), ensure_ascii=False, sort_keys=True))
+61
View File
@@ -0,0 +1,61 @@
"""Small shared configuration helpers; importing this module has no side effects."""
import os
_TRUE = frozenset({"1", "true", "yes", "on"})
def env_enabled(name, default=False):
value = os.environ.get(name)
return default if value is None else value.strip().lower() in _TRUE
def notifications_enabled(channel=None):
if not env_enabled("IISHKO_NOTIFICATIONS_ENABLED"):
return False
if channel in ("support", "entry") and not env_enabled("IISHKO_SUPPORT_DELIVERY_ENABLED", True):
return False
return channel != "entry" or env_enabled("IISHKO_ENTRY_DELIVERY_ENABLED", True)
def skin_db_path():
"""Canonical name wins; keep the old gateway-only name for existing units."""
return (os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB")
or "/opt/grok-web-skin-tg.db")
def bot_config_path():
return (os.environ.get("GROK_BOT_CFG") or os.environ.get("GROK_BOT_CONFIG")
or os.environ.get("GATE_BOT_CONFIG") or "/opt/grok-bot/config.json")
def gateway_db_path(fallback="/opt/grok-gateway/new-api/one-api.db"):
return os.environ.get("IISHKO_GW_DB") or os.environ.get("GATE_NEWAPI_DB") or fallback
def bot_db_path(fallback="/opt/grok-bot/bot.db"):
return (os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB")
or os.environ.get("GATE_BOT_DB") or fallback)
def econ_state_path(fallback="/opt/grok-bot/econ_cap_state.json"):
return os.environ.get("IISHKO_ECON_STATE") or fallback
def upstream_url(fallback="http://127.0.0.1:48000"):
return (os.environ.get("IISHKO_UPSTREAM") or os.environ.get("NEWAPI_URL")
or fallback)
def effective_bot_config(config):
"""Apply one environment contract to bot, Mini App and Telegram login."""
config = dict(config)
for key, name in (("bot_token", "GROK_BOT_TOKEN"), ("newapi_pass", "NEWAPI_PASS")):
if os.environ.get(name):
config[key] = os.environ[name]
config["bot_db"] = bot_db_path(config.get("bot_db") or "/opt/grok-bot/bot.db")
config["newapi_db"] = gateway_db_path(
config.get("newapi_db") or "/opt/grok-gateway/new-api/one-api.db")
config["newapi_url"] = upstream_url(
config.get("newapi_url") or "http://127.0.0.1:48000")
return config
+11 -5
View File
@@ -17,14 +17,16 @@ sys.path[:0] = os.environ.get("IISHKO_RUNTIME_PATHS", os.environ.get("IISHKO_APP
import key_issue_guard
from account_limits import account_uid, account_token_names
import account_balances
from runtime_config import bot_db_path, econ_state_path, gateway_db_path
_so = sys.stdout
sys.stdout = sys.stderr
try:
import grok_bot as g
finally:
sys.stdout = _so
BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")
GW_DB = g.CFG['newapi_db']
BOT_DB = bot_db_path(g.CFG["bot_db"])
# Same value the imported bot resolved, so both sides share one gateway database.
GW_DB = g.CFG.get('newapi_db') or gateway_db_path()
Q = g.QUOTA_PER_UNIT
@@ -379,17 +381,21 @@ def cmd_reveal(uid, n):
return {'ok': True, 'key': 'sk-' + r['key'], 'name': r['name']}
def _read_pause_state(state_path='/opt/grok-bot/econ_cap_state.json'):
def _state_path(state_path=None):
return state_path or econ_state_path()
def _read_pause_state(state_path=None):
# [FIX-2410] чтение JSON-состояния вынесено из BEGIN IMMEDIATE-транзакции
try:
with open(state_path, encoding='utf-8') as fh:
with open(_state_path(state_path), encoding='utf-8') as fh:
state = json.load(fh)
return state if isinstance(state, dict) else {}
except (OSError, ValueError):
return {}
def _daily_pause_info(con, row, user, state=None, state_path='/opt/grok-bot/econ_cap_state.json'):
def _daily_pause_info(con, row, user, state=None, state_path=None):
if int(row['status']) != 2 or user.get('key_locked'):
return {}
try:
+8 -7
View File
@@ -41,6 +41,7 @@ import entry_admin
import miniapp_guard
import gateway_commerce
import commerce_access
from runtime_config import bot_config_path, effective_bot_config, notifications_enabled
import community_board
import account_balances
from account_limits import account_uid
@@ -70,12 +71,13 @@ def _model_metadata_rows(model_ids):
return reference or None
log = logging.getLogger("iishko-webapp")
with open(os.environ.get("GROK_BOT_CONFIG", "/opt/grok-bot/config.json"), encoding="utf-8") as config_file:
CFG = json.load(config_file)
with open(bot_config_path(), encoding="utf-8-sig") as config_file:
CFG = effective_bot_config(json.load(config_file))
BOT_TOKEN = CFG["bot_token"]
BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")
BOT_DB = CFG["bot_db"]
entry_admin.BOT_DB = BOT_DB
UPTIME_DB = os.environ.get("GROK_UPTIME_DB", os.path.join(os.path.dirname(BOT_DB), "model_uptime.db"))
NEWAPI_DB = CFG.get("newapi_db", "/opt/grok-gateway/new-api/one-api.db")
NEWAPI_DB = CFG["newapi_db"]
QUOTA_PER_USD = 500000
ADMIN_IDS = {int(value) for value in os.environ.get("IISHKO_ADMIN_IDS", "").split(",") if value.strip().isdigit()}
ADMIN_IDS.update(value for value in CFG.get("admin_ids", []) if type(value) is int and value > 0)
@@ -2261,7 +2263,7 @@ async def api_support_get(req):
async def _support_notify(admin_id, text, reply_markup=None):
if os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") == "0":
if not notifications_enabled():
raise NotificationError(retryable=False)
payload = {"chat_id": admin_id, "text": text, "disable_web_page_preview": True}
if reply_markup:
@@ -2324,8 +2326,7 @@ async def _support_lifecycle(app):
worker = SupportOutbox(_SUPPORT, lambda: ADMIN_IDS, _support_notify)
app["support_worker"] = worker
task = None
if (os.environ.get("IISHKO_SUPPORT_DELIVERY_ENABLED", "1") != "0" and
os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") != "0"):
if notifications_enabled("support"):
task = asyncio.create_task(worker.run(), name="iishko-support-outbox")
app["support_task"] = task
try: