Files
iishko-public/bot/file_intake.py
T
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

429 lines
18 KiB
Python

from __future__ import annotations
import io
import re
import zipfile
import zlib
from dataclasses import dataclass, field
from html import unescape
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
# 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",
".ndjson", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env", ".sh",
".bash", ".zsh", ".ps1", ".bat", ".py", ".pyi", ".js", ".mjs", ".cjs", ".ts",
".tsx", ".jsx", ".java", ".kt", ".kts", ".c", ".h", ".cpp", ".hpp", ".cc",
".cs", ".go", ".rs", ".rb", ".php", ".swift", ".m", ".mm", ".sql", ".html",
".htm", ".xml", ".css", ".scss", ".less", ".vue", ".svelte", ".gitignore",
".dockerfile", ".makefile", ".patch", ".diff", ".srt", ".vtt", ".tex",
}
_OFFICE_EXTS = {".docx", ".xlsx", ".xlsm", ".pptx", ".odt"}
_TAG_RE = re.compile(r"<[^>]+>")
_CTRL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
@dataclass
class ExtractResult:
ok: bool
kind: str = ""
text: str = ""
reason: str = ""
chars: int = 0
truncated: bool = False
warnings: list = field(default_factory=list)
def _num(name: str) -> int:
"""Порядковый номер из имени вида sheet3.xml / slide12.xml; 0 если цифр нет."""
m = re.search(r"(\d+)", name)
return int(m.group(1)) if m else 0
def _too_big(size: int) -> ExtractResult | None:
if size > MAX_FILE_BYTES:
return ExtractResult(
ok=False,
reason=f"файл {size / 1048576:.1f} МБ — предел {MAX_FILE_BYTES // 1048576} МБ",
)
if size == 0:
return ExtractResult(ok=False, reason="файл пустой")
return None
def _decode(data: bytes) -> str | None:
"""Текстовая декодировка: BOM-кодировки, затем utf-8, cp1251, koi8-r, latin-1.
utf-16 пробуется ТОЛЬКО при наличии BOM: вслепую он успешно «декодирует»
cp1251-байты чётной длины в CJK-мусор, и русский файл приезжал иероглифами.
"""
if data[:2] in (b"\xff\xfe", b"\xfe\xff") or data[:3] == b"\xef\xbb\xbf":
for enc in ("utf-8-sig", "utf-16"):
try:
return data.decode(enc)
except (UnicodeDecodeError, UnicodeError):
continue
for enc in ("utf-8", "cp1251", "koi8-r", "latin-1"):
try:
return data.decode(enc)
except (UnicodeDecodeError, UnicodeError):
continue
return None
def _looks_binary(text: str) -> bool:
sample = text[:8192]
if not sample:
return True
return len(_CTRL_RE.findall(sample)) / len(sample) > 0.02
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()
notes = list(warnings or [])
truncated = bool(cut) or len(clean) > TEXT_BUDGET
if len(clean) > TEXT_BUDGET:
clean = clean[:TEXT_BUDGET]
notes.append(f"показаны первые {TEXT_BUDGET} символов")
if not clean:
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=notes,
)
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(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(reader: _OfficeBudget) -> str:
slides = sorted(
(n for n in reader.zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
key=_num,
)
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(reader: _OfficeBudget) -> str:
shared: list[str] = []
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)]
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]:
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 = []
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 = []
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)
if vm:
val = unescape(vm.group(1))
if 't="s"' in attrs and val.isdigit() and int(val) < len(shared):
val = shared[int(val)]
else:
im = re.search(r"<t[^>]*>(.*?)</t>", body, re.S)
if im:
val = unescape(im.group(1))
val = val.replace("\t", " ").replace("\n", " ")[:left]
row_chars += len(val)
cells.append(val)
if any(c.strip() for c in cells):
line = "\t".join(cells)
rows.append(line)
produced += len(line)
if rows:
out.append(f"--- {label} ---\n" + "\n".join(rows))
return "\n".join(out)
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))
def _from_office(data: bytes, ext: str) -> ExtractResult:
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
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:
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)")
def _from_pdf(data: bytes) -> ExtractResult:
try:
from pypdf import PdfReader # type: ignore[import-not-found]
except ImportError:
return ExtractResult(ok=False, reason="PDF-ридер не установлен на сервере (pypdf)")
try:
reader = PdfReader(io.BytesIO(data))
pages = reader.pages[:_MAX_PDF_PAGES]
parts = []
for i, page in enumerate(pages, 1):
try:
parts.append((page.extract_text() or "").strip())
except Exception as exc: # битая страница не должна ронять весь файл
parts.append(f"[страница {i} не читается: {type(exc).__name__}]")
text = "\n".join(p for p in parts if p)
warns = []
if len(reader.pages) > _MAX_PDF_PAGES:
warns.append(f"прочитаны первые {_MAX_PDF_PAGES} из {len(reader.pages)} страниц")
if not text.strip():
return ExtractResult(
ok=False,
reason="PDF без текстового слоя (скан) — нужно распознавание, его на сервере нет",
)
return _finish(text, "pdf", warns)
except Exception as exc:
return ExtractResult(ok=False, reason=f"PDF не читается: {type(exc).__name__}")
def _from_zip_listing(zf: zipfile.ZipFile) -> ExtractResult:
infos = zf.infolist()[:_MAX_ZIP_ENTRIES]
lines = [f"{i.file_size:>10} {i.filename}" for i in infos if not i.is_dir()]
body = "\n".join(lines) or "(архив пуст)"
more = f"\n…и ещё {len(zf.infolist()) - len(infos)}" if len(zf.infolist()) > len(infos) else ""
return _finish(f"Содержимое архива:\n{body}{more}", "zip-listing")
def extract(name: str, data: bytes) -> ExtractResult:
name = str(name or "").strip()
guard = _too_big(len(data or b""))
if guard:
return guard
ext = ("." + name.rsplit(".", 1)[-1].lower()) if "." in name else ""
if ext in _OFFICE_EXTS:
return _from_office(data, ext)
if ext == ".pdf":
return _from_pdf(data)
if ext in (".zip", ".apk", ".whl", ".jar", ".epub"):
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
return _from_zip_listing(zf)
except zipfile.BadZipFile:
return ExtractResult(ok=False, reason="архив повреждён")
if ext in (".doc", ".xls", ".ppt", ".rtf"):
return ExtractResult(
ok=False,
reason=f"{ext} — старый бинарный формат, конвертера на сервере нет. Пересохрани как "
f"{'docx' if ext == '.doc' else 'xlsx' if ext == '.xls' else 'pdf'} или .txt",
)
if ext in {".png", ".jpg", ".jpeg", ".webp", ".gif", ".mp3", ".ogg", ".mp4", ".wav", ".webm"}:
return ExtractResult(ok=False, reason="это медиа, а не документ — пришли фото отдельно, оно уходит в vision-модель")
text = _decode(data)
if text is None or _looks_binary(text):
return ExtractResult(
ok=False,
reason=f"бинарный файл{f' {ext}' if ext else ''} — текстового содержимого нет",
)
kind = ext.lstrip(".") or "text"
return _finish(text, kind if kind in TEXT_EXTS or ext else "text")
def describe(name: str, res: ExtractResult) -> str:
"""Короткое честное описание результата для сообщения юзеру (без HTML-разметки)."""
if res.ok:
extra = f", {res.warnings[0]}" if res.warnings else ""
return f"{name}: {res.kind}, {res.chars} символов{extra}"
return f"{name}: не прочитан — {res.reason}"