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
+79 -36
View File
@@ -1,61 +1,104 @@
# Деплой (примеры)
Это **примеры**, а не готовый боевой деплой. Пути (`/opt/...`), домены (`your-domain.com`)
и порты замените на свои. Все приватные порты по умолчанию — loopback (`127.0.0.1`);
наружу выставляйте только через reverse proxy с TLS.
Примеры, а не готовый боевой деплой: домен (`your-domain.com`), владельца юнитов и
порты замените на свои. Приватные порты — loopback (`127.0.0.1`), наружу только через
reverse proxy с TLS. Репозиторий копируется целиком (git clone / rsync), «плоской»
сборки нет: `bot/`, `gateway/`, `scripts/`, `tests/` остаются на месте.
## Раскладка на сервере
| Расположение | Источник | Тип |
|---|---|---|
| `/opt/iishko` | корень репозитория | дерево |
| `/etc/iishko/runtime.env` | `deploy/runtime.env.example` (права `0640 root:root`) | конфиг сервера |
| `/etc/iishko/bot/config.json` | `bot/config.example.json` (права `0600`) | конфиг сервера |
| `/opt/iishko/var/` | каталог для SQLite/логов, создаётся вами | состояние |
Модерация собирается из корня репозитория:
```bash
mkdir -p bin
(cd moderation && go build -o ../bin/iishko-moderation .)
```
Запуск — только через `scripts/run.py`:
| Цель | Точка входа |
|---|---|
| `bot` | `bot/grok_bot.py` (`bot/iishko_bot.py` оставлен для прежних запусков) |
| `miniapp` | `bot/webapp/server.py` |
| `gateway` | `gateway/grok-web-skin.py` |
`scripts/run.py` читает `--env-file`, при этом реальная переменная окружения важнее
файла; нормализует исторические имена конфига (`GROK_BOT_CFG` / `GROK_BOT_CONFIG` /
`GATE_BOT_CONFIG`) и стартует цель. Своих загрузчиков env в юнитах нет. `--check`
проверяет конфигурацию офлайн, без сети и без запуска приложения.
Канонические имена выбирает `bot/runtime_config.py`: конфиг бота —
`GROK_BOT_CFG` > `GROK_BOT_CONFIG` > `GATE_BOT_CONFIG`, база скина — `IISHKO_SKIN_DB` >
`GATE_TG_DB`. База New API (`IISHKO_GW_DB`) должна существовать до старта: `run.py` и
`--check` её не создают и завершаются ошибкой, если файла нет. Остальные SQLite
открывают сами приложения.
## Состав
| Файл | Назначение |
|---|---|
| `systemd/grok-bot.service` | Telegram-бот (long polling), `bot/grok_bot.py` |
| `systemd/iishko-webapp.service` | Mini App backend, `bot/webapp/server.py`, `127.0.0.1:8850` |
| `systemd/grok-web-skin.service` | скин шлюза, `gateway/grok-web-skin.py`, `127.0.0.1:48001` |
| `systemd/iishko-moderation.service` | сервис модерации (`moderation/`), `127.0.0.1:48003` |
| `caddy/Caddyfile.example` | маршрутизация `/webapp/*`, `/v1/*`, статика сайта |
| `systemd/grok-bot.service` | Telegram-бот (long polling), цель `bot` |
| `systemd/iishko-webapp.service` | Mini App backend, цель `miniapp`, `127.0.0.1:8850` |
| `systemd/grok-web-skin.service` | скин/прокси шлюза, цель `gateway`, `127.0.0.1:48001` |
| `systemd/iishko-moderation.service` | политика модерации (Go-бинарь, loopback `:48003`) |
| `runtime.env.example` | шаблон `/etc/iishko/runtime.env` (только плейсхолдеры) |
| `caddy/Caddyfile.example` | маршрутизация `/webapp/*` и прокси к скину шлюза |
Единицы сняты с боевого сервера и оставлены как пример структуры: перед использованием
поправьте `WorkingDirectory`, `ExecStart`, пути к БД и файл `EnvironmentFile=`.
Мониторинг, TTS и firewall — вне репозитория, используйте свои.
Core-юниты содержат `WorkingDirectory=/opt/iishko` и
`ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py <цель> --env-file /etc/iishko/runtime.env`
(кроме `iishko-moderation` — он читает `/etc/iishko/runtime.env` напрямую через
`EnvironmentFile=`). Без env-файла юнит падает сразу.
## Порядок
1. Внешний шлюз (New API / one-api) поднимается **отдельно** — в репозиторий не входит.
Заведите каналы, получите мастер-ключ.
2. Заполните `.env` (см. `.env.example`) и `bot/config.json` (из `bot/config.example.json`).
3. `python scripts/selfcheck.py` — офлайн-проверка перед стартом.
4. Запустите бота, Mini App и скин; наружу — через Caddy.
1. Внешний шлюз (New API / one-api) поднимается отдельно, в репозиторий не входит.
2. Клон в `/opt/iishko`, `.venv` и зависимости (`requirements.txt`), сборка
`iishko-moderation` из `moderation/`.
3. `/opt/iishko/var`, `/etc/iishko/bot/config.json` (из `bot/config.example.json`) и
`/etc/iishko/runtime.env` (из `deploy/runtime.env.example`) — со своими значениями.
4. Офлайн-проверка: `.venv/bin/python scripts/run.py bot --env-file /etc/iishko/runtime.env --check`
(так же для `miniapp`, `gateway`).
5. Юниты из `deploy/systemd/`, `systemctl daemon-reload`, `enable --now`.
6. Наружу — только через Caddy по `deploy/caddy/Caddyfile.example`.
## Переменные окружения
PowerShell:
Канонический источник — `/etc/iishko/runtime.env` (см. `runtime.env.example`, там же
приоритеты). Для локальной разработки достаточно `.env` в корне репозитория:
```powershell
$env:PYTHONPATH = "bot;gateway"
$env:GROK_BOT_CFG = "C:\iishko\bot\config.json"
$env:IISHKO_ADMIN_IDS = "123456789"
python bot\grok_bot.py
python scripts/run.py bot # читает .env из корня репозитория
python scripts/run.py gateway --check
```
POSIX:
```bash
export PYTHONPATH=bot:gateway
export GROK_BOT_CFG=$PWD/bot/config.json
export IISHKO_ADMIN_IDS=123456789
python bot/grok_bot.py
python scripts/run.py miniapp --env-file .env
```
Ручной экспорт (`PYTHONPATH`, `GROK_BOT_CFG`, `IISHKO_ADMIN_IDS`) совместим, но не
обязателен: `scripts/run.py` делает то же самое.
## Выключено по умолчанию
Автобан Mini App (`IISHKO_ENTRY_AUTOBAN=0`, включается только `=1`), песочница
(`IISHKO_SANDBOX_ENABLED=0`), гео-база (файла нет), платежи (токены пустые).
Включайте осознанно: автобан трогает балансы и ключи реальных аккаунтов, а общий IP
(NAT, мобильный оператор, семья) сам по себе не доказывает мультиаккаунт.
Уведомления владельцам (`IISHKO_ADMIN_IDS`) включены по умолчанию; выключение —
`IISHKO_NOTIFICATIONS_ENABLED=0`.
Legacy-флаг `IISHKO_ENTRY_AUTOBAN=0` оставлен для совместимости API, автоматического
IP-применения нет. Уведомления (`IISHKO_NOTIFICATIONS_ENABLED=0`), песочница
(`IISHKO_SANDBOX_ENABLED=0`), гео-база (файла нет) и платежи (токены пустые) выключены.
Совпадение IP вызывает только алерт для ручной проверки, даже при `IISHKO_ENTRY_AUTOBAN=1`.
Явный бан администратором — отдельная операция; legacy-санкции могут менять квоты и ключи.
## Чего здесь нет
## Что не входит в репозиторий
Баз данных, ключей, логов и юнитов посторонних сервисов.
Датасет DB-IP (~121 MB) скачивается отдельно: `bot/geo/provenance.json`.
Кода и юнитов для healthcheck/health-timer, алертера (`alert-watch`), media/TTS-адаптера,
firewall-скрипта и шлюза New API здесь нет: это сервисы оператора, их код, расписание и
права вы заводите сами. В `deploy/systemd/` — только четыре юнита, которые репозиторий
реально запускает. Заглушек и фальшивых проверок нет.
Базы, ключи и логи сюда не входят. Caddyfile не импортирует файлы вне `deploy/caddy/`.
Датасет DB-IP (~121 MB) скачивается отдельно: `bot/geo/provenance.json`.
+14 -11
View File
@@ -38,16 +38,20 @@
api.your-domain.com {
import api_common
handle /v1/media/* {
reverse_proxy 127.0.0.1:8000 {
# media responses are large; stream instead of buffering whole bodies
flush_interval -1
transport http {
read_timeout 300s
dial_timeout 10s
}
}
}
# Media/TTS (/v1/media/*) is NOT routed here: this repo ships no media adapter.
# The gateway skin proxies every /v1/* path to the upstream. If you run an
# operator-run adapter on loopback,
# add your own route above the catch-all:
#
# handle /v1/media/* {
# reverse_proxy 127.0.0.1:<your-adapter-port> {
# flush_interval -1
# transport http {
# read_timeout 300s
# dial_timeout 10s
# }
# }
# }
# [WEBAPP-WIRE 19.10] Mini App: /webapp -> 127.0.0.1:8850
handle /webapp {
redir /webapp/ 301
@@ -88,4 +92,3 @@ your-domain.com {
}
}
}
+60
View File
@@ -0,0 +1,60 @@
# IISHKO runtime environment for systemd units.
#
# Install (never commit the real file):
# sudo install -d -m 0750 /etc/iishko
# sudo install -m 0640 -o root -g root \
# /opt/iishko/deploy/runtime.env.example /etc/iishko/runtime.env
# sudoedit /etc/iishko/runtime.env # replace every REPLACE_ME
#
# Consumers:
# deploy/systemd/grok-bot.service -> scripts/run.py bot --env-file /etc/iishko/runtime.env
# deploy/systemd/iishko-webapp.service -> scripts/run.py miniapp --env-file /etc/iishko/runtime.env
# deploy/systemd/grok-web-skin.service -> scripts/run.py gateway --env-file /etc/iishko/runtime.env
# deploy/systemd/iishko-moderation.service -> EnvironmentFile=/etc/iishko/runtime.env (Go binary)
#
# Priority: a variable already present in the process environment wins over the
# value in this file. scripts/run.py loads the file, normalises the legacy config
# aliases (GROK_BOT_CFG / GROK_BOT_CONFIG / GATE_BOT_CONFIG) and only then starts
# the target process; it does not override real environment variables.
#
# This file holds configuration only. Secrets live in bot/config.json (0600) and
# in this file — both stay outside the repository.
# --- bot config (canonical name; aliases are set by scripts/run.py) -----------
GROK_BOT_CFG=/etc/iishko/bot/config.json
# --- SQLite files (absolute; create the directory first) ---------------------
IISHKO_BOT_DB=/opt/iishko/var/bot.db
IISHKO_GW_DB=/opt/iishko/var/newapi.db
# Canonical skin DB name; GATE_TG_DB is the legacy alias for the same file.
IISHKO_SKIN_DB=/opt/iishko/var/grok-web-skin-tg.db
IISHKO_ECON_STATE=/opt/iishko/var/econ_cap_state.json
# --- loopback listeners (never expose these directly) -----------------------
IISHKO_WEBAPP_HOST=127.0.0.1
IISHKO_WEBAPP_PORT=8850
IISHKO_GATEWAY_HOST=127.0.0.1
IISHKO_GATEWAY_PORT=48001
# --- upstream gateway (New API / one-api, external service) ------------------
IISHKO_UPSTREAM=http://127.0.0.1:48000
# --- provider registry (operator-owned file, see gateway/providers.example.json)
IISHKO_PROVIDERS_FILE=/etc/iishko/providers.json
# --- moderation token (required by iishko-moderation, >=32 chars) ------------
IISHKO_MODERATION_TOKEN=REPLACE_ME_MODERATION_TOKEN
# --- admin Telegram IDs, comma separated ------------------------------------
IISHKO_ADMIN_IDS=
# --- Telegram website session-signing secret (never commit or overwrite) ----
# Leave the path absent on first start: gateway creates it atomically with mode 0600.
# Keep it outside the repo and preserve it across upgrades. An existing file must
# have mode 0600 and belong to the gateway service user; its contents are not printed.
TG_SID_SECRET_FILE=/etc/iishko/tg-sid-secret
# --- optional features, off by default (see deploy/README.md) ---------------
IISHKO_ENTRY_AUTOBAN=0
IISHKO_NOTIFICATIONS_ENABLED=0
IISHKO_SANDBOX_ENABLED=0
+15 -6
View File
@@ -1,14 +1,23 @@
[Unit]
Description=Grok Telegram Bot
After=network-online.target new-api.service
Description=IISHKO Telegram bot (long polling)
Documentation=file:/opt/iishko/deploy/README.md
After=network-online.target
Wants=network-online.target
# The upstream gateway (New API / one-api) is an external service and has no unit
# in this repo. If it runs on this host, add its unit name to After= below.
[Service]
EnvironmentFile=/opt/grok-bot/.env
WorkingDirectory=/opt/grok-bot
ExecStart=/opt/venv/bin/python /opt/grok-bot/iishko_bot.py
Type=simple
User=root
WorkingDirectory=/opt/iishko
# scripts/run.py loads /etc/iishko/runtime.env (real environment wins), adds the
# repo directories to sys.path and starts bot/grok_bot.py.
# The file is required: without it the unit fails fast instead of starting half-configured.
ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py bot --env-file /etc/iishko/runtime.env
Restart=always
RestartSec=10
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
WantedBy=multi-user.target
+14 -5
View File
@@ -1,13 +1,22 @@
[Unit]
Description=IISHKO gateway web skin
After=network-online.target new-api.service
Description=IISHKO gateway skin (loopback 127.0.0.1:48001)
Documentation=file:/opt/iishko/deploy/README.md
After=network-online.target
Wants=network-online.target
# Upstream gateway is external, see the note in grok-bot.service.
[Service]
EnvironmentFile=/opt/grok-bot/.env
Type=simple
User=root
WorkingDirectory=/opt/iishko
# gateway target runs gateway/grok-web-skin.py; sys.path needs gateway/ and bot/
# (the skin imports bot modules), which scripts/run.py sets up.
ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py gateway --env-file /etc/iishko/runtime.env
TimeoutStopSec=30
ExecStart=/opt/venv/bin/python /opt/grok-web-skin.py
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
WantedBy=multi-user.target
+11 -5
View File
@@ -1,13 +1,17 @@
[Unit]
Description=IISHKO moderation policy (loopback only, no Telegram poller)
After=network.target
Documentation=file:/opt/iishko/deploy/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/grok-bot
EnvironmentFile=/etc/iishko/moderation.env
ExecStart=/opt/grok-bot/bin/iishko-moderation -addr 127.0.0.1:48003
WorkingDirectory=/opt/iishko
# Native EnvironmentFile: the Go binary is not started through scripts/run.py.
# IISHKO_MODERATION_TOKEN is required (see deploy/runtime.env.example).
EnvironmentFile=/etc/iishko/runtime.env
ExecStart=/opt/iishko/bin/iishko-moderation -addr 127.0.0.1:48003
Restart=on-failure
RestartSec=3
TimeoutStopSec=15
@@ -15,6 +19,8 @@ NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
# Runtime state is written under /opt/iishko/var (DBs, logs).
ReadWritePaths=/opt/iishko/var
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
CapabilityBoundingSet=
MemoryMax=128M
@@ -22,4 +28,4 @@ TasksMax=32
UMask=0077
[Install]
WantedBy=multi-user.target
WantedBy=multi-user.target
+13 -6
View File
@@ -1,13 +1,20 @@
[Unit]
Description=iishko webapp (Mini App backend)
After=network.target
Description=IISHKO Mini App backend (loopback 127.0.0.1:8850)
Documentation=file:/opt/iishko/deploy/README.md
After=network-online.target
Wants=network-online.target
[Service]
EnvironmentFile=/opt/grok-bot/.env
ExecStart=/opt/venv/bin/python /opt/grok-bot/webapp/server.py
WorkingDirectory=/opt/grok-bot/webapp
Type=simple
User=root
WorkingDirectory=/opt/iishko
# miniapp target runs bot/webapp/server.py; listen address comes from runtime.env
# (IISHKO_WEBAPP_HOST / IISHKO_WEBAPP_PORT).
ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py miniapp --env-file /etc/iishko/runtime.env
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
WantedBy=multi-user.target