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.
This commit is contained in:
+13
-9
@@ -3,15 +3,13 @@
|
|||||||
# cp .env.example .env
|
# cp .env.example .env
|
||||||
|
|
||||||
# === Layout ===
|
# === Layout ===
|
||||||
# Root of the runtime tree that bot/gateway modules are resolved from.
|
# Bot module directory; scripts/run.py resolves relative paths from the repo root.
|
||||||
# Use an ABSOLUTE path: commerce/key-daemon code resolves modules from it.
|
IISHKO_APP_ROOT=./bot
|
||||||
IISHKO_APP_ROOT=/absolute/path/to/this/repo/bot
|
|
||||||
# Optional override of the bot source file. Default: $IISHKO_APP_ROOT/grok_bot.py
|
# Optional override of the bot source file. Default: $IISHKO_APP_ROOT/grok_bot.py
|
||||||
IISHKO_BOT_SOURCE=
|
IISHKO_BOT_SOURCE=
|
||||||
# Module search path for a local run (production flattens both dirs together):
|
# scripts/run.py sets the cross-platform module path; no manual PYTHONPATH needed.
|
||||||
# POSIX: export PYTHONPATH=bot:gateway
|
# Direct starts from the repo root: POSIX PYTHONPATH="$PWD/bot:$PWD/gateway:$PWD/bot/webapp"
|
||||||
# Windows: set PYTHONPATH=bot;gateway
|
# PowerShell: $env:PYTHONPATH="$PWD/bot;$PWD/gateway;$PWD/bot/webapp"
|
||||||
PYTHONPATH=bot:gateway
|
|
||||||
|
|
||||||
# === Bot identity ===
|
# === Bot identity ===
|
||||||
GROK_BOT_TOKEN=REPLACE_ME_TELEGRAM_BOT_TOKEN
|
GROK_BOT_TOKEN=REPLACE_ME_TELEGRAM_BOT_TOKEN
|
||||||
@@ -22,9 +20,12 @@ GROK_BOT_ALLOW_LOCAL=1 # 1 only for a local single-instanc
|
|||||||
IISHKO_BOT_DB=./bot.db # bot SQLite: users, keys, economy
|
IISHKO_BOT_DB=./bot.db # bot SQLite: users, keys, economy
|
||||||
GROK_BOT_DB=./bot.db # legacy alias of IISHKO_BOT_DB
|
GROK_BOT_DB=./bot.db # legacy alias of IISHKO_BOT_DB
|
||||||
GATE_BOT_DB=./bot.db # gateway-side alias of the same file
|
GATE_BOT_DB=./bot.db # gateway-side alias of the same file
|
||||||
IISHKO_GW_DB=./one-api.db # external New API SQLite (read-only use)
|
IISHKO_GW_DB=./one-api.db # external New API SQLite; economy/key operations WRITE here
|
||||||
IISHKO_SKIN_DB=./skin.db # skin/site accounts
|
IISHKO_SKIN_DB=./skin.db # skin/site accounts
|
||||||
|
# GATE_TG_DB is the legacy alias; IISHKO_SKIN_DB takes precedence.
|
||||||
|
TG_SID_SECRET_FILE=./.local/tg-sid-secret # private login/session secret, never commit
|
||||||
GATE_NEWAPI_DB=./one-api.db # legacy alias of IISHKO_GW_DB
|
GATE_NEWAPI_DB=./one-api.db # legacy alias of IISHKO_GW_DB
|
||||||
|
IISHKO_ECON_STATE=./econ_cap_state.json # shared economy pause/cap state
|
||||||
|
|
||||||
# === Upstream (external New API / one-api, AGPL-3.0, not bundled) ===
|
# === Upstream (external New API / one-api, AGPL-3.0, not bundled) ===
|
||||||
IISHKO_UPSTREAM=http://127.0.0.1:48000 # canonical upstream base URL
|
IISHKO_UPSTREAM=http://127.0.0.1:48000 # canonical upstream base URL
|
||||||
@@ -68,10 +69,13 @@ IISHKO_SRV_EXCLUDED_IPS=
|
|||||||
# reading an existing wallet and grants keeps working.
|
# reading an existing wallet and grants keeps working.
|
||||||
|
|
||||||
# === Other optional features, off by default ===
|
# === Other optional features, off by default ===
|
||||||
IISHKO_ENTRY_AUTOBAN=0 # IP-collision autoban touches balances/keys
|
IISHKO_ENTRY_AUTOBAN=0 # legacy API compatibility; no automatic IP enforcement
|
||||||
IISHKO_BC_PREMIUM_AUTOFILL=0 # cosmetic broadcast emoji autofill
|
IISHKO_BC_PREMIUM_AUTOFILL=0 # cosmetic broadcast emoji autofill
|
||||||
IISHKO_SANDBOX_ENABLED=0 # external command/file execution surface
|
IISHKO_SANDBOX_ENABLED=0 # external command/file execution surface
|
||||||
IISHKO_NOTIFICATIONS_ENABLED=0 # outbound Telegram notifications
|
IISHKO_NOTIFICATIONS_ENABLED=0 # outbound Telegram notifications
|
||||||
|
# Optional delivery kill switches; only meaningful after NOTIFICATIONS_ENABLED=1:
|
||||||
|
# IISHKO_SUPPORT_DELIVERY_ENABLED=0 # suppress support and entry alerts
|
||||||
|
# IISHKO_ENTRY_DELIVERY_ENABLED=0 # suppress entry alerts only
|
||||||
IISHKO_MEMORY_OFF=1 # 1 = no persistent chat context in RAM
|
IISHKO_MEMORY_OFF=1 # 1 = no persistent chat context in RAM
|
||||||
|
|
||||||
# === Media / payments providers (disabled while empty) ===
|
# === Media / payments providers (disabled while empty) ===
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ jobs:
|
|||||||
# Purchases are config-gated (empty commerce_offers + empty payment token),
|
# Purchases are config-gated (empty commerce_offers + empty payment token),
|
||||||
# not flag-gated: there is no IISHKO_WALLET_ENABLED / PAID_OFFERS switch.
|
# not flag-gated: there is no IISHKO_WALLET_ENABLED / PAID_OFFERS switch.
|
||||||
IISHKO_ADMIN_IDS: ""
|
IISHKO_ADMIN_IDS: ""
|
||||||
IISHKO_NOTIFICATIONS_ENABLED: "0"
|
|
||||||
IISHKO_SANDBOX_ENABLED: "0"
|
IISHKO_SANDBOX_ENABLED: "0"
|
||||||
|
|
||||||
moderation:
|
moderation:
|
||||||
|
|||||||
@@ -6,15 +6,18 @@
|
|||||||
*.sqlite3
|
*.sqlite3
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
|
runtime.env
|
||||||
!.env.example
|
!.env.example
|
||||||
config.json
|
config.json
|
||||||
bot/config.json
|
bot/config.json
|
||||||
|
providers.json
|
||||||
*.key
|
*.key
|
||||||
*.pem
|
*.pem
|
||||||
*.p12
|
*.p12
|
||||||
*.pfx
|
*.pfx
|
||||||
secrets/
|
secrets/
|
||||||
sessions/
|
sessions/
|
||||||
|
.local/
|
||||||
logs/
|
logs/
|
||||||
*.log
|
*.log
|
||||||
# geo dataset is downloaded by the operator (see bot/geo/provenance.json)
|
# geo dataset is downloaded by the operator (see bot/geo/provenance.json)
|
||||||
|
|||||||
+19
-41
@@ -1,7 +1,7 @@
|
|||||||
# Архитектура
|
# Архитектура
|
||||||
|
|
||||||
Документ описывает фактическое состояние кода на момент публикации. Проект в бете,
|
Документ описывает публичное дерево исходников, а не состояние рабочего сервера.
|
||||||
часть решений — временные; раздел «Известные проблемы» честно перечисляет, что сломано.
|
Внешний New API, настройки провайдеров и runtime-данные сюда не входят.
|
||||||
|
|
||||||
## Общая схема
|
## Общая схема
|
||||||
|
|
||||||
@@ -32,16 +32,16 @@ Telegram-клиент
|
|||||||
| Daemon операций с ключами | `bot/webapp/mk_daemon.py` | — (subprocess) | — | `one-api.db` (RW), `bot.db` |
|
| Daemon операций с ключами | `bot/webapp/mk_daemon.py` | — (subprocess) | — | `one-api.db` (RW), `bot.db` |
|
||||||
| Скин шлюза | `gateway/grok-web-skin.py` | 48001 | `grok-web-skin.service` | `one-api.db` |
|
| Скин шлюза | `gateway/grok-web-skin.py` | 48001 | `grok-web-skin.service` | `one-api.db` |
|
||||||
| Классификатор ошибок | `gateway/gateway_errors.py` | — (импортируется) | — | — |
|
| Классификатор ошибок | `gateway/gateway_errors.py` | — (импортируется) | — | — |
|
||||||
| grok2api | `gateway/g2a/` (конфиг) | 8000 | `g2a.service` | свой стейт |
|
| grok2api | `gateway/g2a/` (пример конфига) | внешний сервис | не поставляется | свой стейт |
|
||||||
| TS-переписывание | `iishko-ts/src/index.ts` | — | `iishko-ts.service` | `node:sqlite` |
|
| TS-версия (эксперимент) | `iishko-ts/src/index.ts` | — | не поставляется | `node:sqlite` |
|
||||||
|
|
||||||
Мониторинг, TTS и firewall — вне репозитория.
|
В `deploy/` остаются только шаблоны сервисов с исходниками в этом репозитории.
|
||||||
|
|
||||||
## Переменные окружения
|
## Переменные окружения
|
||||||
|
|
||||||
| Компонент | Переменные | Дефолт |
|
| Компонент | Переменные | Дефолт |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| grok-web-skin | `GATE_BOT_CONFIG`, `GATE_BOT_DB`, `GATE_NEWAPI_DB`, `GATE_TG_DB`, `IP_LOCK_ENFORCE`, `TG_SID_SECRET_FILE` | — |
|
| bot / Mini App / skin | `GROK_BOT_CFG` (алиасы `GROK_BOT_CONFIG`, `GATE_BOT_CONFIG`), `IISHKO_BOT_DB`, `IISHKO_GW_DB`, `IISHKO_SKIN_DB` (алиас `GATE_TG_DB`) | через `scripts/run.py`, см. `.env.example` |
|
||||||
|
|
||||||
|
|
||||||
## Хранилища
|
## Хранилища
|
||||||
@@ -117,39 +117,17 @@ Telegram-клиент
|
|||||||
- Источники начислений помимо выплаты: дуэли, квесты, джекпот, переводы между ключами.
|
- Источники начислений помимо выплаты: дуэли, квесты, джекпот, переводы между ключами.
|
||||||
- Казна (`econ`) считается как `supply − сумма_балансов_пользователей`.
|
- Казна (`econ`) считается как `supply − сумма_балансов_пользователей`.
|
||||||
|
|
||||||
## Известные проблемы
|
## Ограничения
|
||||||
|
|
||||||
Список честный и приоритизирован — хорошие первые PR.
|
- `bot/grok_bot.py` — монолитная реализация; `bot/iishko_bot.py` — обычный
|
||||||
|
совместимый лаунчер, не симлинк. Разделение модулей не завершено.
|
||||||
1. **Казна не сходится.** `loyalty_awarder` начисляет `MAX(...)` — то есть создаёт
|
- Python и TS — не взаимозаменяемые реализации. `iishko-ts/` экспериментален,
|
||||||
деньги, а `supply` закэширован как `user_sum_at_init + $500K`. При росте балансов
|
общего обещания функционального паритета нет.
|
||||||
казна уходит в минус. Выбранное решение: динамический supply
|
- Баланс, ранги и операции с ключами зависят от схемы внешнего New API. Несколько
|
||||||
(`SUPPLY = user_sum + $500K` на каждое чтение) — не задеплоено.
|
SQLite-файлов не образуют общую транзакцию автоматически: сверяйте квоты с
|
||||||
2. **429 апстрима показывается как вина пользователя.** Текст «Слишком много
|
журналом операций и делайте резервные копии перед миграциями.
|
||||||
запросов» приходит, когда троттлит канал провайдера. Правильно — нейтральный
|
- Каталог/справочные характеристики моделей не подтверждают live-маршрутизацию.
|
||||||
503/`upstream_throttled` с ретраем на другой канал.
|
Доступность, лимиты и ответы провайдеров проверяются отдельно.
|
||||||
3. **Обрезка ответов.** Дефолт `max_tokens=2000` резал длинные ответы
|
- Совпадение IP сохраняется для ручной проверки, но не является основанием
|
||||||
(«модели отвечают обрывочно»). На проде поднят до 8000; в коде дефолт стоит проверить.
|
автоматического бана или обнуления квот. Уведомления по умолчанию выключены.
|
||||||
4. **Ранговый гейтинг противоречит справке.** Доступ к моделям tier-gated, а текст
|
- Изменение кода здесь не означает его выкладку на рабочий сервер.
|
||||||
`/help` всё ещё утверждает, что ранг влияет только на лимиты и недельный кредит.
|
|
||||||
5. **Mini App требует слэш в конце.** Ссылка должна вести на `/webapp/`;
|
|
||||||
вариант без слэша у части клиентов отдаёт пустой 200 вместо 301 и показывает
|
|
||||||
«не удалось загрузить мини-апп».
|
|
||||||
6. **Render-blocking шрифты.** Подключение Google Fonts в `<head>` у пользователей
|
|
||||||
из РФ может блокировать отрисовку Mini App при живом сервере.
|
|
||||||
7. **Симлинк `grok_bot.py`.** Сервис запускает `iishko_bot.py`, а модули импортируют
|
|
||||||
`grok_bot`. При деплое копирование файла поверх симлинка оставляет сервис на старой версии.
|
|
||||||
8. **`status=4` при положительном балансе.** Авто-исчерпанные ключи с
|
|
||||||
`remain_quota>0` — видимый пользователю рассинхрон; требует явной политики.
|
|
||||||
9. **Баланс Mini App vs бот.** Исторически часть функций резолвила ключ как
|
|
||||||
`tg<uid>`, игнорируя `users.token_name`, из-за чего профиль показывал 0,
|
|
||||||
а вкладка «Эконом» — реальную сумму. Канонический резолв: `users.token_name` → fallback `tg<uid>`.
|
|
||||||
10. **Медиа-модели и `completion_tokens=0`.** Для генерации изображений/видео ноль
|
|
||||||
выходных токенов — норма; нельзя трактовать это как ошибку и делать возврат.
|
|
||||||
|
|
||||||
## Что планируется
|
|
||||||
|
|
||||||
- Переписать шлюз маршрутизации с нуля вместо форка `new-api`
|
|
||||||
(текущая кодовая база не поддаётся ни чтению, ни очистке).
|
|
||||||
- Перевести бота на TypeScript: `iishko-ts/` (grammy, `node:sqlite`, модули
|
|
||||||
`chat`, `economy`, `keys`, `start`) — модульная и типизированная замена монолиту.
|
|
||||||
|
|||||||
+42
-21
@@ -3,7 +3,7 @@
|
|||||||
Спасибо, что зашли. Проект в бете, мейнтейнер один, времени мало — поэтому правила
|
Спасибо, что зашли. Проект в бете, мейнтейнер один, времени мало — поэтому правила
|
||||||
простые и направлены на то, чтобы ваш PR можно было проверить быстро.
|
простые и направлены на то, чтобы ваш PR можно было проверить быстро.
|
||||||
|
|
||||||
**Все PR ревьюит владелец проекта.** Мержится только то, что прошло ревью.
|
Мержится только то, что прошло ревью мейнтейнера проекта.
|
||||||
|
|
||||||
## С чего начать
|
## С чего начать
|
||||||
|
|
||||||
@@ -13,9 +13,10 @@
|
|||||||
|
|
||||||
Также полезно:
|
Также полезно:
|
||||||
|
|
||||||
- тесты (их почти нет — это главная техническая дыра проекта);
|
- тесты в `tests/` (`unittest`/`pytest`) — покрытие неровное, регрессии по
|
||||||
|
экономике, доступу к моделям и стабильности запросов всегда нужны;
|
||||||
- TypeScript-переписывание в `iishko-ts/` — бот переезжает туда;
|
- TypeScript-переписывание в `iishko-ts/` — бот переезжает туда;
|
||||||
- разбор и чистка монолита `bot/iishko_bot.py` (~800 КБ) на модули.
|
- разбор и чистка монолита `bot/grok_bot.py` (~14.8 тыс. строк, 847 КБ) на модули.
|
||||||
|
|
||||||
## Правила PR
|
## Правила PR
|
||||||
|
|
||||||
@@ -25,9 +26,13 @@
|
|||||||
4. **Пруф.** Для баг-фиксов: тест или вывод до/после. «Работает у меня» — не пруф.
|
4. **Пруф.** Для баг-фиксов: тест или вывод до/после. «Работает у меня» — не пруф.
|
||||||
5. **Никаких секретов в диффе.** Ключи, токены, куки, IP боевых серверов,
|
5. **Никаких секретов в диффе.** Ключи, токены, куки, IP боевых серверов,
|
||||||
Telegram ID реальных пользователей, дампы БД — всё это отклоняется без обсуждения.
|
Telegram ID реальных пользователей, дампы БД — всё это отклоняется без обсуждения.
|
||||||
6. **Не коммитьте** `config.json`, `*.db*`, `*_state.json`,
|
6. **Не коммитьте** `config.json`, `runtime.env`, `*.db*`, `*_state.json`,
|
||||||
медиа и логи. Смотрите `.gitignore`.
|
медиа и логи. Смотрите `.gitignore`.
|
||||||
7. **Не ломайте симлинк** `bot/grok_bot.py → iishko_bot.py` (см. README).
|
7. **Не переименовывайте и не удаляйте** лончер `bot/iishko_bot.py` и модуль
|
||||||
|
`bot/grok_bot.py`, и **не копируйте один поверх другого.** Это два разных файла:
|
||||||
|
`bot/iishko_bot.py` — 13-строчный вход, который через `runpy.run_module` выполняет
|
||||||
|
`bot/grok_bot.py` с реальной реализацией. Оба нужны: первый — стабильная точка
|
||||||
|
входа, второй — код.
|
||||||
8. **Новые зависимости — только по нужде.** Сначала стандартная библиотека,
|
8. **Новые зависимости — только по нужде.** Сначала стандартная библиотека,
|
||||||
потом уже пакеты. Каждая зависимость обосновывается в описании PR.
|
потом уже пакеты. Каждая зависимость обосновывается в описании PR.
|
||||||
9. **Форматтер не навязываем.** Стиль существующего кода строгий не везде —
|
9. **Форматтер не навязываем.** Стиль существующего кода строгий не везде —
|
||||||
@@ -37,7 +42,7 @@
|
|||||||
## Чего скорее всего не примут
|
## Чего скорее всего не примут
|
||||||
|
|
||||||
- «Переписал всё и стало красиво» без описания поведения и пруфов.
|
- «Переписал всё и стало красиво» без описания поведения и пруфов.
|
||||||
- Изменения экономики (начисления, квоты, казна, ранги) без обсуждения с владельцем:
|
- Изменения экономики (начисления, квоты, казна, ранги) без обсуждения с мейнтейнером:
|
||||||
там каждая правка двигает живые деньги пользователей.
|
там каждая правка двигает живые деньги пользователей.
|
||||||
- Отключение проверок, капчи, лимитов и гейтинга «чтобы удобнее тестировать».
|
- Отключение проверок, капчи, лимитов и гейтинга «чтобы удобнее тестировать».
|
||||||
- Хардкод ключей и эндпоинтов вместо конфига.
|
- Хардкод ключей и эндпоинтов вместо конфига.
|
||||||
@@ -45,17 +50,26 @@
|
|||||||
|
|
||||||
## Локальный запуск
|
## Локальный запуск
|
||||||
|
|
||||||
```bash
|
Нужен Python 3.11+ и внешний шлюз (`new-api`/`one-api`) — его в репозитории нет,
|
||||||
python -m venv .venv && source .venv/bin/activate
|
см. [deploy/README.md](deploy/README.md).
|
||||||
pip install -r requirements.txt
|
|
||||||
|
|
||||||
cp bot/config.example.json bot/config.json # заполнить REPLACE_ME
|
```bash
|
||||||
python bot/iishko_bot.py # бот
|
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||||
python bot/webapp/server.py # Mini App на :8850
|
pip install -r requirements.txt -r requirements-dev.txt
|
||||||
|
|
||||||
|
python scripts/run.py bot # Telegram-бот
|
||||||
|
python scripts/run.py miniapp # Mini App на 127.0.0.1:8850
|
||||||
|
python scripts/run.py gateway # скин/прокси шлюза на 127.0.0.1:48001
|
||||||
```
|
```
|
||||||
|
|
||||||
Для Mini App нужен шлюз (upstream `new-api`/`one-api`) и доступ к его SQLite —
|
`scripts/run.py` читает `.env` из корня репозитория (реальные переменные окружения
|
||||||
см. README, раздел «Шлюз».
|
имеют приоритет), нормализует исторические alias‑имена конфига и выставляет
|
||||||
|
`sys.path`. Явный файл конфигурации: `--env-file PATH`. Офлайн‑проверка без сети и
|
||||||
|
без запуска приложения: `python scripts/run.py bot --check`.
|
||||||
|
|
||||||
|
Экспорт руками (`PYTHONPATH`, `GROK_BOT_CFG`, `IISHKO_ADMIN_IDS`) остаётся
|
||||||
|
совместимым — прямое `python bot/iishko_bot.py` тоже работает, но тогда
|
||||||
|
переменные окружения вы задаёте сами.
|
||||||
|
|
||||||
TypeScript-часть:
|
TypeScript-часть:
|
||||||
|
|
||||||
@@ -66,17 +80,24 @@ npm install
|
|||||||
npm run dev # tsx src/index.ts
|
npm run dev # tsx src/index.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Проверки перед PR
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest -q # весь набор из tests/
|
||||||
|
python scripts/selfcheck.py --source-only # офлайн, без импортов и сети
|
||||||
|
```
|
||||||
|
|
||||||
|
Оба прогона должны быть зелёными; падение, которое вы «не трогали», всё равно ваша
|
||||||
|
ответственность — иначе ревью не начнётся.
|
||||||
|
|
||||||
|
Деплой и раскладка файлов на сервере — [deploy/README.md](deploy/README.md).
|
||||||
|
|
||||||
## Язык
|
## Язык
|
||||||
|
|
||||||
Issues и PR можно писать по-русски или по-английски. Комментарии в коде — по-английски.
|
Issues и PR можно писать по-русски или по-английски. Комментарии в коде — по-английски.
|
||||||
|
|
||||||
## Вопросы
|
## Вопросы
|
||||||
|
|
||||||
Общие вопросы и идеи — в чат проекта. Личные — владельцу репозитория (`reform`) на git.reformboss.com.
|
Общие вопросы и идеи — в чат проекта. Личные — мейнтейнеру проекта в Telegram
|
||||||
|
(контакт указан в профиле владельца репозитория).
|
||||||
Уязвимости — только приватно, см. [SECURITY.md](SECURITY.md).
|
Уязвимости — только приватно, см. [SECURITY.md](SECURITY.md).
|
||||||
|
|
||||||
## Windows checkout note
|
|
||||||
|
|
||||||
`bot/grok_bot.py` — единственная реализация, обычный файл; `bot/iishko_bot.py` — тонкий
|
|
||||||
лаунчер для совместимости (см. README). Никаких symlink и копирований не нужно —
|
|
||||||
**не копируйте** `iishko_bot.py` поверх `grok_bot.py`: это затрёт реализацию.
|
|
||||||
|
|||||||
@@ -11,9 +11,8 @@
|
|||||||
|
|
||||||
| Путь | Статус | Комментарий |
|
| Путь | Статус | Комментарий |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `bot/`, `bot/webapp/`, `gateway/`, `site/`, `deploy/` | **legacy runtime, production-compatible** | Код, который реально работал на боевом сервере. Интерфейсы и схема БД совместимы с боевыми, но публичным сервисом этот репозиторий не запускается. |
|
| `bot/`, `bot/webapp/`, `gateway/`, `deploy/` | **legacy runtime** | Публичный снимок Python-компонентов. Это исходники, а не готовый публичный сервис и не подтверждение текущего состояния production. |
|
||||||
| `iishko-ts/` | **experimental** | Ранний TypeScript-перепись бота (grammy). Не feature-parity с Python-версией; параллельно с основным ботом не запускать. |
|
| `iishko-ts/` | **experimental** | Ранний TypeScript-перепись бота (grammy). Не feature-parity с Python-версией; параллельно с основным ботом не запускать. |
|
||||||
| `site/assets/*` | снимок | Собранный бандл лендинга как есть, без шага сборки. |
|
|
||||||
|
|
||||||
Честно о проверках: в этом репозитории **нет Docker-прогона и нет заявлений о «smoke-tested
|
Честно о проверках: в этом репозитории **нет Docker-прогона и нет заявлений о «smoke-tested
|
||||||
production»**. Локальный сценарий ниже — про то, что приложение стартует и отдаёт loopback-порты;
|
production»**. Локальный сценарий ниже — про то, что приложение стартует и отдаёт loopback-порты;
|
||||||
@@ -55,18 +54,29 @@ python scripts/selfcheck.py --source-only # синтаксис/замыкани
|
|||||||
Запуск компонентов (все слушают loopback, наружу — только через ваш reverse proxy):
|
Запуск компонентов (все слушают loopback, наружу — только через ваш reverse proxy):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Код сам .env не читает — загрузите его в окружение (в systemd: EnvironmentFile=)
|
# Каждая команда сама читает .env; shell-команды source/set не нужны.
|
||||||
set -a; . ./.env; set +a # POSIX
|
python scripts/run.py bot --check # только офлайн preflight конфига, не запуск
|
||||||
# PowerShell: Get-Content .env | ? { $_ -match '^[A-Z_]+=' } | % { $k,$v = $_ -split '=',2; Set-Item "env:$k" $v }
|
python scripts/run.py bot # Telegram-бот (long polling)
|
||||||
export PYTHONPATH=bot:gateway # PowerShell: $env:PYTHONPATH = "bot;gateway"
|
python scripts/run.py miniapp # Mini App backend, 127.0.0.1:8850
|
||||||
|
python scripts/run.py gateway # скин шлюза, 127.0.0.1:48001
|
||||||
python bot/grok_bot.py # Telegram-бот (long polling)
|
|
||||||
python bot/webapp/server.py # Mini App backend, 127.0.0.1:8850
|
|
||||||
python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`bot/iishko_bot.py` — совместимый лаунчер (systemd-юниты и часть модулей исторически
|
`scripts/run.py` явно читает только `.env` в корне (или `--env-file ПУТЬ`), не
|
||||||
делают `import grok_bot`). Реальная реализация одна — `bot/grok_bot.py`.
|
исполняет его как shell и не ищет файлы выше проекта. Реальное окружение процесса
|
||||||
|
имеет приоритет, в том числе legacy-алиасы; относительные пути считаются от корня.
|
||||||
|
Лаунчер задаёт module path для Windows/POSIX и согласует `GROK_BOT_CFG` с прежними
|
||||||
|
`GROK_BOT_CONFIG` / `GATE_BOT_CONFIG`. Прямой запуск скриптов сохранён для старых
|
||||||
|
unit-файлов, но сам `.env` не загружает; окружение и абсолютные пути к данным в этом
|
||||||
|
режиме задаёт оператор. Не запускайте два polling-процесса с одним токеном;
|
||||||
|
для локального запуска используйте отдельного бота.
|
||||||
|
|
||||||
|
Для работы нужны заполненный `bot/config.json` и существующий SQLite вашего New API
|
||||||
|
(`IISHKO_GW_DB`): конфиг-пример и пустой файл не заменяют upstream. `--check` проверяет
|
||||||
|
наличие конфигурации, но не подключается к Telegram, не проверяет схему New API и
|
||||||
|
не доказывает доступность моделей.
|
||||||
|
|
||||||
|
`bot/iishko_bot.py` — совместимый лаунчер для прежних запусков и импортов.
|
||||||
|
`scripts/run.py bot` запускает реализацию `bot/grok_bot.py` напрямую.
|
||||||
|
|
||||||
`bot.db` создаётся при первом запуске; собственный `one-api.db` предоставляет New API.
|
`bot.db` создаётся при первом запуске; собственный `one-api.db` предоставляет New API.
|
||||||
В репозитории нет ни баз, ни пользовательских данных.
|
В репозитории нет ни баз, ни пользовательских данных.
|
||||||
@@ -138,11 +148,10 @@ python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001
|
|||||||
|
|
||||||
## Конфигурация
|
## Конфигурация
|
||||||
|
|
||||||
* `.env.example` — переменные окружения: layout (`IISHKO_APP_ROOT` — абсолютный путь,
|
* `.env.example` — переменные окружения: layout (`IISHKO_APP_ROOT` — каталог модулей
|
||||||
опционально `IISHKO_BOT_SOURCE`), идентичность бота,
|
бота, через лаунчер допустим относительный путь; опционально `IISHKO_BOT_SOURCE`),
|
||||||
пути к БД (`IISHKO_BOT_DB`, алиасы `GROK_BOT_DB` / `GATE_BOT_DB` / `GATE_NEWAPI_DB`;
|
пути к БД (`IISHKO_BOT_DB`, алиасы `GROK_BOT_DB` / `GATE_BOT_DB`; шлюз —
|
||||||
БД Telegram-входа шлюза — `IISHKO_SKIN_DB`, алиас `GATE_TG_DB`; бот, автобан и скин
|
`IISHKO_GW_DB` / `GATE_NEWAPI_DB`; общая skin-БД — `IISHKO_SKIN_DB` / `GATE_TG_DB`),
|
||||||
пишут в неё, поэтому путь должен совпадать у всех сервисов),
|
|
||||||
апстрим (`IISHKO_UPSTREAM`, алиас `NEWAPI_URL`), шлюз
|
апстрим (`IISHKO_UPSTREAM`, алиас `NEWAPI_URL`), шлюз
|
||||||
(`IISHKO_GATEWAY_HOST` / `IISHKO_GATEWAY_PORT`, `IISHKO_PROVIDERS_FILE`), админы,
|
(`IISHKO_GATEWAY_HOST` / `IISHKO_GATEWAY_PORT`, `IISHKO_PROVIDERS_FILE`), админы,
|
||||||
commerce-флаги. Все дефолты — loopback.
|
commerce-флаги. Все дефолты — loopback.
|
||||||
@@ -151,14 +160,21 @@ python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001
|
|||||||
* `gateway/providers.example.json` — форма реестра провайдеров для pinning
|
* `gateway/providers.example.json` — форма реестра провайдеров для pinning
|
||||||
(только плейсхолдеры; нужен New API admin/owner). См. `docs/native-gateway.md`.
|
(только плейсхолдеры; нужен New API admin/owner). См. `docs/native-gateway.md`.
|
||||||
* `bot/config.example.json` — конфиг бота (`GROK_BOT_CFG`). Секреты — заглушки `REPLACE_ME_*`.
|
* `bot/config.example.json` — конфиг бота (`GROK_BOT_CFG`). Секреты — заглушки `REPLACE_ME_*`.
|
||||||
|
Без env-переопределений значения upstream и DB из JSON сохраняются. Лаунчер не
|
||||||
|
меняет `TG_SID_SECRET_FILE`, если он не задан: существующий путь секрета сохраняется.
|
||||||
|
`IISHKO_ECON_STATE` задаёт общий файл пауз/лимитов экономики.
|
||||||
* Шлюз и провайдеры настраиваются в вашем инстансе New API, не здесь.
|
* Шлюз и провайдеры настраиваются в вашем инстансе New API, не здесь.
|
||||||
|
|
||||||
|
Утилита `bot/abilities_guard.py` без `--apply` только читает маршруты. Запись требует
|
||||||
|
явных `--apply --db /absolute/one-api.db --source /absolute/grok_bot.py`; утилита
|
||||||
|
включает только подходящие `abilities`, не меняет токены, квоты или историю банов.
|
||||||
|
|
||||||
### Выключено по умолчанию
|
### Выключено по умолчанию
|
||||||
|
|
||||||
| Возможность | Переменная | По умолчанию |
|
| Возможность | Переменная | По умолчанию |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Автобан по совпадению IP в Mini App (без него общий IP — только алерт владельцу; включение: `1`) | `IISHKO_ENTRY_AUTOBAN` | `0` (выкл.) |
|
| Legacy-совместимость API автобана | `IISHKO_ENTRY_AUTOBAN` | `0`; автоматического IP-применения нет, общий IP не банит и при `1` |
|
||||||
| Уведомления владельцам в Telegram (саппорт/алерты); выключение: `0` | `IISHKO_NOTIFICATIONS_ENABLED` | `1` (вкл., только `IISHKO_ADMIN_IDS`) |
|
| Уведомления в Telegram (саппорт/алерты) | `IISHKO_NOTIFICATIONS_ENABLED` | `0` (выкл.) |
|
||||||
| Внешняя песочница исполнения команд/файлов | `IISHKO_SANDBOX_ENABLED` | `0` (выкл.) |
|
| Внешняя песочница исполнения команд/файлов | `IISHKO_SANDBOX_ENABLED` | `0` (выкл.) |
|
||||||
| Персистентный контекст чата | `IISHKO_MEMORY_OFF` | `1` (без памяти) |
|
| Персистентный контекст чата | `IISHKO_MEMORY_OFF` | `1` (без памяти) |
|
||||||
| Геолокация по IP (DB-IP) | файл `bot/geo/*.mmdb` | нет файла → функция выключена |
|
| Геолокация по IP (DB-IP) | файл `bot/geo/*.mmdb` | нет файла → функция выключена |
|
||||||
@@ -167,6 +183,17 @@ python gateway/grok-web-skin.py # скин шлюза, 127.0.0.1:48001
|
|||||||
| Чтение кошелька и grants | — (переключателя нет) | работает и при пустых офферах |
|
| Чтение кошелька и grants | — (переключателя нет) | работает и при пустых офферах |
|
||||||
| Премиум-эмодзи в рассылках | `IISHKO_BC_PREMIUM_AUTOFILL` | `0` (выкл.) |
|
| Премиум-эмодзи в рассылках | `IISHKO_BC_PREMIUM_AUTOFILL` | `0` (выкл.) |
|
||||||
|
|
||||||
|
Сетевые совпадения Mini App сохраняются только как сигнал для проверки администратором:
|
||||||
|
NAT/Wi-Fi/VPN не доказывают мультиаккаунт. Уведомления саппорта/сетевых алертов требуют
|
||||||
|
`IISHKO_NOTIFICATIONS_ENABLED=1`; дополнительные `IISHKO_SUPPORT_DELIVERY_ENABLED=0`
|
||||||
|
и `IISHKO_ENTRY_DELIVERY_ENABLED=0` — kill switches. Явная админская модерация не
|
||||||
|
включает автоматический IP-бан.
|
||||||
|
|
||||||
|
`IISHKO_SKIN_DB` — общий путь сайта и очистки IP-привязок, с legacy-алиасом `GATE_TG_DB`.
|
||||||
|
БД New API **не read-only** для приложения: выдача ключей, экономика и модерация
|
||||||
|
обновляют квоты/статусы. Для локальных проверок используйте отдельные тестовые БД,
|
||||||
|
не production-пути.
|
||||||
|
|
||||||
Платежи и «денежные» операции не включаются без вашего явного конфига; ни один
|
Платежи и «денежные» операции не включаются без вашего явного конфига; ни один
|
||||||
сценарий быстрого старта не выполняет боевых мутаций баланса.
|
сценарий быстрого старта не выполняет боевых мутаций баланса.
|
||||||
|
|
||||||
@@ -185,7 +212,6 @@ bot/ # канонический бот: grok_bot.py + модул
|
|||||||
vendor_entry_geo/ # MaxMind DB Reader (Apache-2.0), provenance.json
|
vendor_entry_geo/ # MaxMind DB Reader (Apache-2.0), provenance.json
|
||||||
geo/ # только лицензия и provenance датасета DB-IP (сам .mmdb не включён)
|
geo/ # только лицензия и provenance датасета DB-IP (сам .mmdb не включён)
|
||||||
gateway/ # скин шлюза, классификатор ошибок, transparent_api, model_identity, public_site
|
gateway/ # скин шлюза, классификатор ошибок, transparent_api, model_identity, public_site
|
||||||
site/ # лендинг/доки/прайс (собранный бандл)
|
|
||||||
deploy/ # примеры systemd/caddy под ваши пути и домены
|
deploy/ # примеры systemd/caddy под ваши пути и домены
|
||||||
iishko-ts/ # experimental TypeScript-перепись
|
iishko-ts/ # experimental TypeScript-перепись
|
||||||
scripts/selfcheck.py# офлайн self-check: синтаксис, замыкание импортов, конфиг
|
scripts/selfcheck.py# офлайн self-check: синтаксис, замыкание импортов, конфиг
|
||||||
|
|||||||
+7
-4
@@ -2,9 +2,12 @@
|
|||||||
|
|
||||||
## Как сообщить об уязвимости
|
## Как сообщить об уязвимости
|
||||||
|
|
||||||
**Не создавайте публичный issue и не пишите в общий чат.**
|
**Не создавайте публичный issue с деталями и не пишите в общий чат.**
|
||||||
|
|
||||||
Пишите лично владельцу репозитория `reform` на git.reformboss.com (не в публичные issues)
|
Приватный канал согласуется так: контакт для связи указан в профиле владельца
|
||||||
|
репозитория (GitHub/Gitea). Напишите туда лично и приложите отчёт. Если контакта в
|
||||||
|
профиле нет — откройте issue **без деталей** (только «есть уязвимость, нужен приватный
|
||||||
|
канал») и дождитесь ответа; подробности в публичный issue не переносите.
|
||||||
|
|
||||||
В сообщении укажите:
|
В сообщении укажите:
|
||||||
|
|
||||||
@@ -13,8 +16,8 @@
|
|||||||
3. Что злоумышленник получает в результате.
|
3. Что злоумышленник получает в результате.
|
||||||
4. Затронуты ли реальные пользовательские данные.
|
4. Затронуты ли реальные пользовательские данные.
|
||||||
|
|
||||||
Подтверждение получения — в течение ~72 часов. Сроки фикса честные: проект в бете,
|
Фиксированных сроков ответа нет: проект в бете, мейнтейнер один. Критичное чинится
|
||||||
мейнтейнер один, критичное чинится вне очереди, остальное — в порядке очереди.
|
вне очереди, остальное — как получится.
|
||||||
|
|
||||||
После выпуска фикса раскрытие деталей согласуется с вами; авторство в релизе — по желанию.
|
После выпуска фикса раскрытие деталей согласуется с вами; авторство в релизе — по желанию.
|
||||||
|
|
||||||
|
|||||||
+37
-23
@@ -1,13 +1,18 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
|
import argparse
|
||||||
|
from contextlib import closing
|
||||||
|
from pathlib import Path
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
|
||||||
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
|
from runtime_config import gateway_db_path
|
||||||
BOT_SRC = "/opt/grok-bot/iishko_bot.py" # [BOTFIX 2310] живой активный сервис
|
|
||||||
BOT_SRC_FALLBACK = "/opt/grok-bot/grok_bot.py" # старое имя (legacy)
|
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")
|
TIER_GROUPS = ("t1", "t2", "t3", "t4")
|
||||||
|
|
||||||
LIVE_SQL = ("SELECT COUNT(*) FROM abilities a JOIN channels c ON c.id=a.channel_id "
|
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):
|
def catalog_tiers(path=None):
|
||||||
"""Список тиров из исходника бота (без импорта бота).
|
"""Read tier declarations without importing or starting the bot."""
|
||||||
path=None: сначала живой iishko_bot.py (BOT_SRC), затем legacy grok_bot.py."""
|
|
||||||
paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK)
|
paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK)
|
||||||
for p in paths:
|
for p in paths:
|
||||||
tiers = _parse_tiers(_read_src(p))
|
tiers = _parse_tiers(_read_src(p))
|
||||||
@@ -84,29 +88,39 @@ def repair_abilities(con, tiers):
|
|||||||
return con.execute(sql, params).rowcount
|
return con.execute(sql, params).rowcount
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main(argv=None):
|
||||||
tiers = catalog_tiers()
|
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:
|
if not tiers:
|
||||||
print(time.strftime("%F %T"), "no catalog tiers parsed - refusing to touch abilities",
|
print("No catalog tiers parsed; no database changes made.", flush=True)
|
||||||
flush=True)
|
|
||||||
return 1
|
return 1
|
||||||
models = catalog_models(tiers)
|
models = catalog_models(tiers)
|
||||||
con = sqlite3.connect(GW_DB, timeout=60)
|
mode = "rw" if args.apply else "ro"
|
||||||
try:
|
try:
|
||||||
con.execute("PRAGMA busy_timeout=60000")
|
with closing(sqlite3.connect(db.resolve().as_uri() + "?mode=" + mode,
|
||||||
fixed = repair_abilities(con, tiers)
|
uri=True, timeout=10)) as con:
|
||||||
con.commit()
|
fixed = 0
|
||||||
dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]]
|
with con:
|
||||||
con.close()
|
if args.apply:
|
||||||
except Exception as e:
|
fixed = repair_abilities(con, tiers)
|
||||||
print(time.strftime("%F %T"), "ERROR", str(e)[:200], flush=True)
|
dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]]
|
||||||
try:
|
except sqlite3.Error as exc:
|
||||||
con.rollback()
|
print("Database check failed: " + type(exc).__name__, file=sys.stderr)
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return 2
|
return 2
|
||||||
print(time.strftime("%F %T"), "catalog=%d re-enabled=%d dark=%s"
|
print("mode=%s catalog=%d re-enabled=%d dark=%s"
|
||||||
% (len(models), fixed, ",".join(dark) if dark else "none"), flush=True)
|
% ("apply" if args.apply else "dry-run", len(models), fixed,
|
||||||
|
",".join(dark) if dark else "none"), flush=True)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ import sqlite3
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
from account_limits import account_uid, _name_scope
|
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.
|
# Account-level locks that are not owned by a ban; unban must never clear them.
|
||||||
INDEPENDENT_FLAGS = ("api_blocked", "key_locked", "chat_key_locked")
|
INDEPENDENT_FLAGS = ("api_blocked", "key_locked", "chat_key_locked")
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,8 @@
|
|||||||
"newapi_url": "http://127.0.0.1:48000",
|
"newapi_url": "http://127.0.0.1:48000",
|
||||||
"newapi_user": "REPLACE_ME_NEWAPI_ADMIN_LOGIN",
|
"newapi_user": "REPLACE_ME_NEWAPI_ADMIN_LOGIN",
|
||||||
"newapi_pass": "REPLACE_ME_NEWAPI_ADMIN_PASSWORD",
|
"newapi_pass": "REPLACE_ME_NEWAPI_ADMIN_PASSWORD",
|
||||||
"newapi_db": "/opt/grok-gateway/new-api/data/one-api.db",
|
"newapi_db": "./one-api.db",
|
||||||
"bot_db": "/opt/grok-bot/bot.db",
|
"bot_db": "./bot.db",
|
||||||
"public_base": "http://127.0.0.1:8850",
|
"public_base": "http://127.0.0.1:8850",
|
||||||
"user_quota": 500000000,
|
"user_quota": 500000000,
|
||||||
"unlimited": false,
|
"unlimited": false,
|
||||||
|
|||||||
+4
-3
@@ -8,10 +8,11 @@ from pathlib import Path
|
|||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
|
|
||||||
from account_limits import account_uid
|
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'
|
BOT_DB = bot_db_path()
|
||||||
NA_DB = '/opt/grok-gateway/new-api/one-api.db'
|
NA_DB = gateway_db_path()
|
||||||
STATE = '/opt/grok-bot/econ_cap_state.json'
|
STATE = econ_state_path()
|
||||||
# Keep this literal compatible with the Mini App's read-only policy parser.
|
# 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}
|
DAILY_USD_CAP = {0: 100, 1: 100, 2: 200, 3: 500, 4: 1000}
|
||||||
QUOTA_PER_USD = 500000
|
QUOTA_PER_USD = 500000
|
||||||
|
|||||||
+3
-2
@@ -1,10 +1,11 @@
|
|||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
import os
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
import time
|
||||||
import unicodedata
|
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
|
WINDOW = 86400
|
||||||
TAG_MAX = 48
|
TAG_MAX = 48
|
||||||
TAG_LIMIT = 12
|
TAG_LIMIT = 12
|
||||||
|
|||||||
+16
-7
@@ -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 json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import re
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
from runtime_config import bot_db_path, env_enabled, gateway_db_path, skin_db_path
|
||||||
|
|
||||||
log = logging.getLogger("entry_autoban")
|
log = logging.getLogger("entry_autoban")
|
||||||
|
|
||||||
BOT_DB = os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db")
|
BOT_DB = bot_db_path()
|
||||||
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
|
GW_DB = gateway_db_path()
|
||||||
SKIN_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db")
|
SKIN_DB = skin_db_path()
|
||||||
|
|
||||||
PROTECT = tuple(int(v) for v in os.environ.get("IISHKO_PROTECTED_UIDS", "").replace(";", ",").split(",")
|
PROTECT = tuple(int(v) for v in os.environ.get("IISHKO_PROTECTED_UIDS", "").replace(";", ",").split(",")
|
||||||
if v.strip().isdigit())
|
if v.strip().isdigit())
|
||||||
|
|
||||||
|
|
||||||
def enabled():
|
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):
|
def _connect(path):
|
||||||
@@ -97,6 +95,11 @@ def _processed(g, con, uid, was_banned):
|
|||||||
|
|
||||||
|
|
||||||
def ban_user(uid, reason="entry_ip_collision", taken=None):
|
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)
|
uid = int(uid)
|
||||||
if uid in PROTECT:
|
if uid in PROTECT:
|
||||||
return False
|
return False
|
||||||
@@ -200,7 +203,13 @@ def ban_user(uid, reason="entry_ip_collision", taken=None):
|
|||||||
|
|
||||||
|
|
||||||
def ban_cluster(uids, reason="entry_ip_collision"):
|
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]
|
uids = [int(u) for u in uids]
|
||||||
|
if reason != "admin_button" and not enabled():
|
||||||
|
log.warning("[ENTRY-AUTOBAN] disabled")
|
||||||
|
return []
|
||||||
out = []
|
out = []
|
||||||
for uid in dict.fromkeys(uids):
|
for uid in dict.fromkeys(uids):
|
||||||
try:
|
try:
|
||||||
|
|||||||
+3
-14
@@ -7,7 +7,6 @@ import hmac
|
|||||||
import ipaddress
|
import ipaddress
|
||||||
import json
|
import json
|
||||||
import math
|
import math
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import re
|
import re
|
||||||
import secrets
|
import secrets
|
||||||
@@ -20,6 +19,7 @@ import logging
|
|||||||
log = logging.getLogger("entry_telemetry")
|
log = logging.getLogger("entry_telemetry")
|
||||||
|
|
||||||
from support_store import NotificationError
|
from support_store import NotificationError
|
||||||
|
from runtime_config import notifications_enabled
|
||||||
|
|
||||||
WINDOW = 86400
|
WINDOW = 86400
|
||||||
# Known shared reverse-proxy/WARP networks; operators may add their own NAT/relay ranges.
|
# 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():
|
def delivery_enabled():
|
||||||
# The existing support switch is also a hard entry-delivery kill switch for old fixtures.
|
return notifications_enabled("entry")
|
||||||
return all(os.environ.get(name, "1") != "0" for name in (
|
|
||||||
"IISHKO_NOTIFICATIONS_ENABLED", "IISHKO_SUPPORT_DELIVERY_ENABLED", "IISHKO_ENTRY_DELIVERY_ENABLED"))
|
|
||||||
|
|
||||||
|
|
||||||
def _label(value, length):
|
def _label(value, length):
|
||||||
@@ -209,7 +207,6 @@ class EntryTelemetry:
|
|||||||
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
|
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
|
||||||
raise EntryError(403, "entry_forbidden", "Не удалось подтвердить аккаунт.")
|
raise EntryError(403, "entry_forbidden", "Не удалось подтвердить аккаунт.")
|
||||||
now = int(self.clock())
|
now = int(self.clock())
|
||||||
ban_uids = []
|
|
||||||
with closing(self.connect()) as con:
|
with closing(self.connect()) as con:
|
||||||
self._eligible(con, uid)
|
self._eligible(con, uid)
|
||||||
ip = public_ip(ip)
|
ip = public_ip(ip)
|
||||||
@@ -245,15 +242,7 @@ class EntryTelemetry:
|
|||||||
"VALUES(?,?,?,?,?,?)", (tag, now, payload, geo["country"], geo["city"], geo["source"]))
|
"VALUES(?,?,?,?,?,?)", (tag, now, payload, geo["country"], geo["city"], geo["source"]))
|
||||||
con.executemany("INSERT INTO wa_entry_outbox(alert_id,owner_id) VALUES(?,?)",
|
con.executemany("INSERT INTO wa_entry_outbox(alert_id,owner_id) VALUES(?,?)",
|
||||||
[(alert.lastrowid, owner) for owner in self.owners])
|
[(alert.lastrowid, owner) for owner in self.owners])
|
||||||
ban_uids = [row["uid"] for row in accounts]
|
|
||||||
con.commit()
|
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):
|
def claim(self):
|
||||||
now = self.clock()
|
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"]))
|
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"
|
text = ("Mini App: совпадение сети за 24 часа\nНаблюдение: %s\n%s\nПримерный регион: %s\nИсточник: %s\n"
|
||||||
"Сеть #%s. Совпадение IP не доказывает общего владельца: возможны Wi-Fi, NAT, VPN или relay. "
|
"Сеть #%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]
|
(observed, users, place, source, claim["ip_hmac"][:12]))[:3000]
|
||||||
# Operator tags always survive truncation: they are the fastest way to recognise a network.
|
# 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)
|
marks = " · ".join(str(tag) for tag in list(tags or ())[:12] if tag)
|
||||||
|
|||||||
+211
-51
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
import io
|
import io
|
||||||
import re
|
import re
|
||||||
import zipfile
|
import zipfile
|
||||||
|
import zlib
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from html import unescape
|
from html import unescape
|
||||||
|
|
||||||
@@ -11,9 +12,19 @@ MAX_FILE_BYTES = 8 * 1024 * 1024
|
|||||||
TEXT_BUDGET = 24000
|
TEXT_BUDGET = 24000
|
||||||
_MAX_PDF_PAGES = 60
|
_MAX_PDF_PAGES = 60
|
||||||
_MAX_XLSX_ROWS = 400
|
_MAX_XLSX_ROWS = 400
|
||||||
|
_MAX_XLSX_CELLS = 2000
|
||||||
_MAX_ZIP_ENTRIES = 200
|
_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 = {
|
TEXT_EXTS = {
|
||||||
".txt", ".md", ".markdown", ".rst", ".log", ".csv", ".tsv", ".json", ".jsonl",
|
".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
|
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 = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||||
clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
|
clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
|
||||||
truncated = len(clean) > TEXT_BUDGET
|
notes = list(warnings or [])
|
||||||
if truncated:
|
truncated = bool(cut) or len(clean) > TEXT_BUDGET
|
||||||
|
if len(clean) > TEXT_BUDGET:
|
||||||
clean = clean[:TEXT_BUDGET]
|
clean = clean[:TEXT_BUDGET]
|
||||||
warnings = list(warnings or [])
|
notes.append(f"показаны первые {TEXT_BUDGET} символов")
|
||||||
warnings.append(f"показаны первые {TEXT_BUDGET} символов")
|
|
||||||
if not clean:
|
if not clean:
|
||||||
return ExtractResult(ok=False, kind=kind, reason="в файле нет извлекаемого текста")
|
return ExtractResult(
|
||||||
|
ok=False, kind=kind, reason="в файле нет извлекаемого текста",
|
||||||
|
truncated=truncated, warnings=notes,
|
||||||
|
)
|
||||||
return ExtractResult(
|
return ExtractResult(
|
||||||
ok=True, kind=kind, text=clean, chars=len(clean),
|
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:
|
class _OfficeBudget:
|
||||||
info = zf.getinfo(name)
|
"""Read Office archive entries under one shared decompression budget.
|
||||||
if info.file_size > 32 * 1024 * 1024:
|
|
||||||
raise RuntimeError(f"entry {name} распаковывается в {info.file_size // 1048576} МБ — слишком много")
|
Only bytes actually read are charged (never the declared `file_size`), the
|
||||||
return zf.read(name).decode("utf-8", "replace")
|
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:
|
def _from_docx(reader: _OfficeBudget) -> str:
|
||||||
xml = _read_entry(zf, "word/document.xml")
|
xml, _ = reader.read_prefix("word/document.xml")
|
||||||
xml = xml.replace("</w:p>", "\n").replace("<w:tab/>", "\t").replace("<w:br/>", "\n")
|
xml = xml.replace("</w:p>", "\n").replace("<w:tab/>", "\t").replace("<w:br/>", "\n")
|
||||||
return unescape(_TAG_RE.sub("", xml))
|
return unescape(_TAG_RE.sub("", xml))
|
||||||
|
|
||||||
|
|
||||||
def _from_pptx(zf: zipfile.ZipFile) -> str:
|
def _from_pptx(reader: _OfficeBudget) -> str:
|
||||||
slides = sorted(
|
slides = sorted(
|
||||||
(n for n in zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
|
(n for n in reader.zf.namelist() if re.fullmatch(r"ppt/slides/slide\d+\.xml", n)),
|
||||||
key=lambda n: _num(n),
|
key=_num,
|
||||||
)
|
)
|
||||||
out, chars, unpacked = [], 0, 0
|
total = len(slides)
|
||||||
for n in slides[:_MAX_PPTX_SLIDES]:
|
if total > _OFFICE_MAX_SLIDES:
|
||||||
unpacked += zf.getinfo(n).file_size
|
slides = slides[:_OFFICE_MAX_SLIDES]
|
||||||
if unpacked > _MAX_UNPACKED_BYTES:
|
reader.note(f"в файле {total} слайдов — прочитаны первые {_OFFICE_MAX_SLIDES}")
|
||||||
raise RuntimeError(f"слайды распаковываются больше чем в {_MAX_UNPACKED_BYTES // 1048576} МБ")
|
out: list[str] = []
|
||||||
if chars > TEXT_BUDGET:
|
produced = 0
|
||||||
break # _finish() truncates anyway; don't decompress the rest
|
for n in slides:
|
||||||
xml = _read_entry(zf, n)
|
if reader.at_entry_limit:
|
||||||
xml = xml.replace("</a:p>", "\n")
|
reader.note(f"показаны не все слайды: {len(out)} из {total}")
|
||||||
out.append(f"--- {n.rsplit('/', 1)[-1]} ---\n" + unescape(_TAG_RE.sub("", xml)))
|
break
|
||||||
chars += len(out[-1])
|
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)
|
return "\n".join(out)
|
||||||
|
|
||||||
|
|
||||||
def _from_xlsx(zf: zipfile.ZipFile) -> str:
|
def _from_xlsx(reader: _OfficeBudget) -> str:
|
||||||
shared: list[str] = []
|
shared: list[str] = []
|
||||||
if "xl/sharedStrings.xml" in zf.namelist():
|
shared_clipped = False
|
||||||
ss = _read_entry(zf, "xl/sharedStrings.xml")
|
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)]
|
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]))
|
sheets.sort(key=lambda n: _num(n.rsplit("/", 1)[-1]))
|
||||||
|
if len(sheets) > 3:
|
||||||
|
reader.note(f"листов в книге {len(sheets)} — прочитаны первые 3")
|
||||||
out: list[str] = []
|
out: list[str] = []
|
||||||
|
produced = 0
|
||||||
for sheet in sheets[:3]:
|
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 = []
|
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 = []
|
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 ""
|
attrs, body = m.group(1) or "", m.group(2) or ""
|
||||||
val = ""
|
val = ""
|
||||||
vm = re.search(r"<v>(.*?)</v>", body, re.S)
|
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)
|
im = re.search(r"<t[^>]*>(.*?)</t>", body, re.S)
|
||||||
if im:
|
if im:
|
||||||
val = unescape(im.group(1))
|
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):
|
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:
|
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)
|
return "\n".join(out)
|
||||||
|
|
||||||
|
|
||||||
def _from_odt(zf: zipfile.ZipFile) -> str:
|
def _from_odt(reader: _OfficeBudget) -> str:
|
||||||
xml = _read_entry(zf, "content.xml")
|
xml, _ = reader.read_prefix("content.xml")
|
||||||
xml = re.sub(r"</text:(p|h|list-item)>", "\n", xml)
|
xml = re.sub(r"</text:(p|h|list-item)>", "\n", xml)
|
||||||
return unescape(_TAG_RE.sub("", 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:
|
def _from_office(data: bytes, ext: str) -> ExtractResult:
|
||||||
try:
|
try:
|
||||||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
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:
|
if ext == ".docx" and "word/document.xml" in names:
|
||||||
return _finish(_from_docx(zf), "docx")
|
text, kind = _from_docx(reader), "docx"
|
||||||
if ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
|
elif ext == ".pptx" and any(n.startswith("ppt/slides/slide") for n in names):
|
||||||
return _finish(_from_pptx(zf), "pptx")
|
text, kind = _from_pptx(reader), "pptx"
|
||||||
if ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
|
elif ext in (".xlsx", ".xlsm") and any(n.startswith("xl/worksheets/") for n in names):
|
||||||
return _finish(_from_xlsx(zf), "xlsx")
|
text, kind = _from_xlsx(reader), "xlsx"
|
||||||
if ext == ".odt" and "content.xml" in names:
|
elif ext == ".odt" and "content.xml" in names:
|
||||||
return _finish(_from_odt(zf), "odt")
|
text, kind = _from_odt(reader), "odt"
|
||||||
except (zipfile.BadZipFile, KeyError, ValueError, IndexError, RuntimeError) as exc:
|
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} повреждён или слишком большой внутри: {type(exc).__name__}")
|
||||||
return ExtractResult(ok=False, reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)")
|
return ExtractResult(ok=False, reason=f"{ext} без ожидаемой структуры — возможно, старый формат (.doc/.xls/.ppt)")
|
||||||
|
|
||||||
|
|||||||
+10
-8
@@ -4,6 +4,7 @@ import urllib.parse
|
|||||||
import contextvars # [EFFORT 2110]
|
import contextvars # [EFFORT 2110]
|
||||||
from contextlib import asynccontextmanager, closing
|
from contextlib import asynccontextmanager, closing
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from runtime_config import bot_config_path, effective_bot_config, skin_db_path
|
||||||
import reminders as reminder_store
|
import reminders as reminder_store
|
||||||
import key_notifications
|
import key_notifications
|
||||||
import community_economy
|
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.types import WebAppInfo # [WEBAPP 18.10]
|
||||||
from aiogram.enums import ParseMode
|
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).
|
# Секреты НЕ хардкодятся: только env-фоллбэк, реальные значения — в config.json (не в git).
|
||||||
DEFAULT_CFG = {
|
DEFAULT_CFG = {
|
||||||
"bot_token": os.environ.get("GROK_BOT_TOKEN", ""),
|
"bot_token": os.environ.get("GROK_BOT_TOKEN", ""),
|
||||||
"channel_username": "@alstack", "channel_link": "https://t.me/alstack", "channel_title": "@alstack",
|
"channel_username": "@alstack", "channel_link": "https://t.me/alstack", "channel_title": "@alstack",
|
||||||
"support": "@your-handle",
|
"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_user": "root", "newapi_pass": os.environ.get("NEWAPI_PASS", ""),
|
||||||
"newapi_db": "/opt/grok-gateway/new-api/one-api.db",
|
"newapi_db": "/opt/grok-gateway/new-api/one-api.db",
|
||||||
"public_base": "https://api.your-domain.com",
|
"public_base": "https://api.your-domain.com",
|
||||||
@@ -52,10 +53,11 @@ def load_cfg():
|
|||||||
if not os.path.exists(CFG_PATH):
|
if not os.path.exists(CFG_PATH):
|
||||||
print(f"[FATAL] config.json missing at {CFG_PATH}"); sys.exit(1)
|
print(f"[FATAL] config.json missing at {CFG_PATH}"); sys.exit(1)
|
||||||
try:
|
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))
|
cfg.update(json.load(_cfh))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[FATAL] config.json broken: {e}"); sys.exit(1)
|
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"):
|
for k in ("bot_token", "main_key", "channel_username", "newapi_pass"):
|
||||||
if not cfg.get(k):
|
if not cfg.get(k):
|
||||||
print(f"[FATAL] config.json missing required key: {k}"); sys.exit(1)
|
print(f"[FATAL] config.json missing required key: {k}"); sys.exit(1)
|
||||||
@@ -70,8 +72,7 @@ def load_cfg():
|
|||||||
return cfg
|
return cfg
|
||||||
CFG = load_cfg()
|
CFG = load_cfg()
|
||||||
KEY_WAIT_SEC = int(CFG.get("key_wait_hours", 24)) * 3600
|
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")
|
BOT_DB = CFG["bot_db"]
|
||||||
SKIN_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db")
|
|
||||||
def tge(em="🩸", _old=None):
|
def tge(em="🩸", _old=None):
|
||||||
return em # plain unicode: текст уходит с parse_mode=HTML, tg-emoji там запрещён
|
return em # plain unicode: текст уходит с parse_mode=HTML, tg-emoji там запрещён
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
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()) # первый запуск: историю НЕ трогаем (кольца забанены вручную)
|
_wm = int(time.time()) # первый запуск: историю НЕ трогаем (кольца забанены вручную)
|
||||||
_nb = 0
|
_nb = 0
|
||||||
try:
|
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
|
_excl = _iplock_excluded_ips() # [IPLOCK-SRVEXCL 2010] loopback + IISHKO_SRV_EXCLUDED_IPS
|
||||||
iprows = sk.execute(
|
iprows = sk.execute(
|
||||||
"SELECT ip, GROUP_CONCAT(DISTINCT token_name) FROM ip_lock_events "
|
"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 "Мимо")
|
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
|
QUOTA_PER_USD = 500000
|
||||||
|
|
||||||
def _cas_wallet(uid, paused_ok=True):
|
def _cas_wallet(uid, paused_ok=True):
|
||||||
@@ -3666,7 +3667,7 @@ def _full_ban(uid, tname, reason):
|
|||||||
# освобождаем ip-клейм: забаненный токен не должен держать IP на 24ч (ложные локи соседей)
|
# освобождаем ip-клейм: забаненный токен не должен держать IP на 24ч (ложные локи соседей)
|
||||||
if tname:
|
if tname:
|
||||||
try:
|
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.execute("DELETE FROM ip_claims WHERE token_name=?", (tname,))
|
||||||
_sk.commit()
|
_sk.commit()
|
||||||
_sk.close()
|
_sk.close()
|
||||||
@@ -14655,6 +14656,7 @@ async def cmd_unknown(m: Message):
|
|||||||
|
|
||||||
|
|
||||||
import entry_admin as _entry_admin
|
import entry_admin as _entry_admin
|
||||||
|
_entry_admin.BOT_DB = BOT_DB
|
||||||
try:
|
try:
|
||||||
_entry_admin.init_db()
|
_entry_admin.init_db()
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import secrets
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
import time
|
import time
|
||||||
from urllib.parse import urlsplit, urlunsplit
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
from runtime_config import bot_config_path, effective_bot_config
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger("key-notifications")
|
log = logging.getLogger("key-notifications")
|
||||||
@@ -481,13 +482,14 @@ class KeyNotificationWorker:
|
|||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="Read-only first-key notification aggregates; this CLI never sends.")
|
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("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("--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()
|
args = parser.parse_args()
|
||||||
with open(args.config, encoding="utf-8") as config:
|
with open(args.config, encoding="utf-8-sig") as config:
|
||||||
wait_seconds = int(json.load(config).get("key_wait_hours", 24)) * 3600
|
cfg = effective_bot_config(json.load(config))
|
||||||
store = KeyNotificationStore(args.bot_db, args.ledger, wait_seconds=wait_seconds)
|
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))
|
print(json.dumps(store.dry_run() if args.action == "dry-run" else store.status(), ensure_ascii=False, sort_keys=True))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -17,14 +17,16 @@ sys.path[:0] = os.environ.get("IISHKO_RUNTIME_PATHS", os.environ.get("IISHKO_APP
|
|||||||
import key_issue_guard
|
import key_issue_guard
|
||||||
from account_limits import account_uid, account_token_names
|
from account_limits import account_uid, account_token_names
|
||||||
import account_balances
|
import account_balances
|
||||||
|
from runtime_config import bot_db_path, econ_state_path, gateway_db_path
|
||||||
_so = sys.stdout
|
_so = sys.stdout
|
||||||
sys.stdout = sys.stderr
|
sys.stdout = sys.stderr
|
||||||
try:
|
try:
|
||||||
import grok_bot as g
|
import grok_bot as g
|
||||||
finally:
|
finally:
|
||||||
sys.stdout = _so
|
sys.stdout = _so
|
||||||
BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db")
|
BOT_DB = bot_db_path(g.CFG["bot_db"])
|
||||||
GW_DB = g.CFG['newapi_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
|
Q = g.QUOTA_PER_UNIT
|
||||||
|
|
||||||
|
|
||||||
@@ -379,17 +381,21 @@ def cmd_reveal(uid, n):
|
|||||||
return {'ok': True, 'key': 'sk-' + r['key'], 'name': r['name']}
|
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-транзакции
|
# [FIX-2410] чтение JSON-состояния вынесено из BEGIN IMMEDIATE-транзакции
|
||||||
try:
|
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)
|
state = json.load(fh)
|
||||||
return state if isinstance(state, dict) else {}
|
return state if isinstance(state, dict) else {}
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
return {}
|
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'):
|
if int(row['status']) != 2 or user.get('key_locked'):
|
||||||
return {}
|
return {}
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import entry_admin
|
|||||||
import miniapp_guard
|
import miniapp_guard
|
||||||
import gateway_commerce
|
import gateway_commerce
|
||||||
import commerce_access
|
import commerce_access
|
||||||
|
from runtime_config import bot_config_path, effective_bot_config, notifications_enabled
|
||||||
import community_board
|
import community_board
|
||||||
import account_balances
|
import account_balances
|
||||||
from account_limits import account_uid
|
from account_limits import account_uid
|
||||||
@@ -70,12 +71,13 @@ def _model_metadata_rows(model_ids):
|
|||||||
return reference or None
|
return reference or None
|
||||||
|
|
||||||
log = logging.getLogger("iishko-webapp")
|
log = logging.getLogger("iishko-webapp")
|
||||||
with open(os.environ.get("GROK_BOT_CONFIG", "/opt/grok-bot/config.json"), encoding="utf-8") as config_file:
|
with open(bot_config_path(), encoding="utf-8-sig") as config_file:
|
||||||
CFG = json.load(config_file)
|
CFG = effective_bot_config(json.load(config_file))
|
||||||
BOT_TOKEN = CFG["bot_token"]
|
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"))
|
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
|
QUOTA_PER_USD = 500000
|
||||||
ADMIN_IDS = {int(value) for value in os.environ.get("IISHKO_ADMIN_IDS", "").split(",") if value.strip().isdigit()}
|
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)
|
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):
|
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)
|
raise NotificationError(retryable=False)
|
||||||
payload = {"chat_id": admin_id, "text": text, "disable_web_page_preview": True}
|
payload = {"chat_id": admin_id, "text": text, "disable_web_page_preview": True}
|
||||||
if reply_markup:
|
if reply_markup:
|
||||||
@@ -2324,8 +2326,7 @@ async def _support_lifecycle(app):
|
|||||||
worker = SupportOutbox(_SUPPORT, lambda: ADMIN_IDS, _support_notify)
|
worker = SupportOutbox(_SUPPORT, lambda: ADMIN_IDS, _support_notify)
|
||||||
app["support_worker"] = worker
|
app["support_worker"] = worker
|
||||||
task = None
|
task = None
|
||||||
if (os.environ.get("IISHKO_SUPPORT_DELIVERY_ENABLED", "1") != "0" and
|
if notifications_enabled("support"):
|
||||||
os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") != "0"):
|
|
||||||
task = asyncio.create_task(worker.run(), name="iishko-support-outbox")
|
task = asyncio.create_task(worker.run(), name="iishko-support-outbox")
|
||||||
app["support_task"] = task
|
app["support_task"] = task
|
||||||
try:
|
try:
|
||||||
|
|||||||
+78
-35
@@ -1,61 +1,104 @@
|
|||||||
# Деплой (примеры)
|
# Деплой (примеры)
|
||||||
|
|
||||||
Это **примеры**, а не готовый боевой деплой. Пути (`/opt/...`), домены (`your-domain.com`)
|
Примеры, а не готовый боевой деплой: домен (`your-domain.com`), владельца юнитов и
|
||||||
и порты замените на свои. Все приватные порты по умолчанию — loopback (`127.0.0.1`);
|
порты замените на свои. Приватные порты — loopback (`127.0.0.1`), наружу только через
|
||||||
наружу выставляйте только через reverse proxy с TLS.
|
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/grok-bot.service` | Telegram-бот (long polling), цель `bot` |
|
||||||
| `systemd/iishko-webapp.service` | Mini App backend, `bot/webapp/server.py`, `127.0.0.1:8850` |
|
| `systemd/iishko-webapp.service` | Mini App backend, цель `miniapp`, `127.0.0.1:8850` |
|
||||||
| `systemd/grok-web-skin.service` | скин шлюза, `gateway/grok-web-skin.py`, `127.0.0.1:48001` |
|
| `systemd/grok-web-skin.service` | скин/прокси шлюза, цель `gateway`, `127.0.0.1:48001` |
|
||||||
| `systemd/iishko-moderation.service` | сервис модерации (`moderation/`), `127.0.0.1:48003` |
|
| `systemd/iishko-moderation.service` | политика модерации (Go-бинарь, loopback `:48003`) |
|
||||||
| `caddy/Caddyfile.example` | маршрутизация `/webapp/*`, `/v1/*`, статика сайта |
|
| `runtime.env.example` | шаблон `/etc/iishko/runtime.env` (только плейсхолдеры) |
|
||||||
|
| `caddy/Caddyfile.example` | маршрутизация `/webapp/*` и прокси к скину шлюза |
|
||||||
|
|
||||||
Единицы сняты с боевого сервера и оставлены как пример структуры: перед использованием
|
Core-юниты содержат `WorkingDirectory=/opt/iishko` и
|
||||||
поправьте `WorkingDirectory`, `ExecStart`, пути к БД и файл `EnvironmentFile=`.
|
`ExecStart=/opt/iishko/.venv/bin/python /opt/iishko/scripts/run.py <цель> --env-file /etc/iishko/runtime.env`
|
||||||
Мониторинг, TTS и firewall — вне репозитория, используйте свои.
|
(кроме `iishko-moderation` — он читает `/etc/iishko/runtime.env` напрямую через
|
||||||
|
`EnvironmentFile=`). Без env-файла юнит падает сразу.
|
||||||
|
|
||||||
## Порядок
|
## Порядок
|
||||||
|
|
||||||
1. Внешний шлюз (New API / one-api) поднимается **отдельно** — в репозиторий не входит.
|
1. Внешний шлюз (New API / one-api) поднимается отдельно, в репозиторий не входит.
|
||||||
Заведите каналы, получите мастер-ключ.
|
2. Клон в `/opt/iishko`, `.venv` и зависимости (`requirements.txt`), сборка
|
||||||
2. Заполните `.env` (см. `.env.example`) и `bot/config.json` (из `bot/config.example.json`).
|
`iishko-moderation` из `moderation/`.
|
||||||
3. `python scripts/selfcheck.py` — офлайн-проверка перед стартом.
|
3. `/opt/iishko/var`, `/etc/iishko/bot/config.json` (из `bot/config.example.json`) и
|
||||||
4. Запустите бота, Mini App и скин; наружу — через Caddy.
|
`/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
|
```powershell
|
||||||
$env:PYTHONPATH = "bot;gateway"
|
python scripts/run.py bot # читает .env из корня репозитория
|
||||||
$env:GROK_BOT_CFG = "C:\iishko\bot\config.json"
|
python scripts/run.py gateway --check
|
||||||
$env:IISHKO_ADMIN_IDS = "123456789"
|
|
||||||
python bot\grok_bot.py
|
|
||||||
```
|
```
|
||||||
|
|
||||||
POSIX:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export PYTHONPATH=bot:gateway
|
python scripts/run.py miniapp --env-file .env
|
||||||
export GROK_BOT_CFG=$PWD/bot/config.json
|
|
||||||
export IISHKO_ADMIN_IDS=123456789
|
|
||||||
python bot/grok_bot.py
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Ручной экспорт (`PYTHONPATH`, `GROK_BOT_CFG`, `IISHKO_ADMIN_IDS`) совместим, но не
|
||||||
|
обязателен: `scripts/run.py` делает то же самое.
|
||||||
|
|
||||||
## Выключено по умолчанию
|
## Выключено по умолчанию
|
||||||
|
|
||||||
Автобан Mini App (`IISHKO_ENTRY_AUTOBAN=0`, включается только `=1`), песочница
|
Legacy-флаг `IISHKO_ENTRY_AUTOBAN=0` оставлен для совместимости API, автоматического
|
||||||
(`IISHKO_SANDBOX_ENABLED=0`), гео-база (файла нет), платежи (токены пустые).
|
IP-применения нет. Уведомления (`IISHKO_NOTIFICATIONS_ENABLED=0`), песочница
|
||||||
Включайте осознанно: автобан трогает балансы и ключи реальных аккаунтов, а общий IP
|
(`IISHKO_SANDBOX_ENABLED=0`), гео-база (файла нет) и платежи (токены пустые) выключены.
|
||||||
(NAT, мобильный оператор, семья) сам по себе не доказывает мультиаккаунт.
|
Совпадение IP вызывает только алерт для ручной проверки, даже при `IISHKO_ENTRY_AUTOBAN=1`.
|
||||||
Уведомления владельцам (`IISHKO_ADMIN_IDS`) включены по умолчанию; выключение —
|
Явный бан администратором — отдельная операция; legacy-санкции могут менять квоты и ключи.
|
||||||
`IISHKO_NOTIFICATIONS_ENABLED=0`.
|
|
||||||
|
|
||||||
## Чего здесь нет
|
## Что не входит в репозиторий
|
||||||
|
|
||||||
Баз данных, ключей, логов и юнитов посторонних сервисов.
|
Кода и юнитов для healthcheck/health-timer, алертера (`alert-watch`), media/TTS-адаптера,
|
||||||
|
firewall-скрипта и шлюза New API здесь нет: это сервисы оператора, их код, расписание и
|
||||||
|
права вы заводите сами. В `deploy/systemd/` — только четыре юнита, которые репозиторий
|
||||||
|
реально запускает. Заглушек и фальшивых проверок нет.
|
||||||
|
|
||||||
|
Базы, ключи и логи сюда не входят. Caddyfile не импортирует файлы вне `deploy/caddy/`.
|
||||||
Датасет DB-IP (~121 MB) скачивается отдельно: `bot/geo/provenance.json`.
|
Датасет DB-IP (~121 MB) скачивается отдельно: `bot/geo/provenance.json`.
|
||||||
@@ -38,16 +38,20 @@
|
|||||||
|
|
||||||
api.your-domain.com {
|
api.your-domain.com {
|
||||||
import api_common
|
import api_common
|
||||||
handle /v1/media/* {
|
# Media/TTS (/v1/media/*) is NOT routed here: this repo ships no media adapter.
|
||||||
reverse_proxy 127.0.0.1:8000 {
|
# The gateway skin proxies every /v1/* path to the upstream. If you run an
|
||||||
# media responses are large; stream instead of buffering whole bodies
|
# operator-run adapter on loopback,
|
||||||
flush_interval -1
|
# add your own route above the catch-all:
|
||||||
transport http {
|
#
|
||||||
read_timeout 300s
|
# handle /v1/media/* {
|
||||||
dial_timeout 10s
|
# 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
|
# [WEBAPP-WIRE 19.10] Mini App: /webapp -> 127.0.0.1:8850
|
||||||
handle /webapp {
|
handle /webapp {
|
||||||
redir /webapp/ 301
|
redir /webapp/ 301
|
||||||
@@ -88,4 +92,3 @@ your-domain.com {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -1,14 +1,23 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Grok Telegram Bot
|
Description=IISHKO Telegram bot (long polling)
|
||||||
After=network-online.target new-api.service
|
Documentation=file:/opt/iishko/deploy/README.md
|
||||||
|
After=network-online.target
|
||||||
Wants=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]
|
[Service]
|
||||||
EnvironmentFile=/opt/grok-bot/.env
|
Type=simple
|
||||||
WorkingDirectory=/opt/grok-bot
|
User=root
|
||||||
ExecStart=/opt/venv/bin/python /opt/grok-bot/iishko_bot.py
|
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
|
Restart=always
|
||||||
RestartSec=10
|
RestartSec=10
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -1,13 +1,22 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=IISHKO gateway web skin
|
Description=IISHKO gateway skin (loopback 127.0.0.1:48001)
|
||||||
After=network-online.target new-api.service
|
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]
|
[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
|
TimeoutStopSec=30
|
||||||
ExecStart=/opt/venv/bin/python /opt/grok-web-skin.py
|
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=3
|
RestartSec=3
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -1,13 +1,17 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=IISHKO moderation policy (loopback only, no Telegram poller)
|
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]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
User=root
|
User=root
|
||||||
WorkingDirectory=/opt/grok-bot
|
WorkingDirectory=/opt/iishko
|
||||||
EnvironmentFile=/etc/iishko/moderation.env
|
# Native EnvironmentFile: the Go binary is not started through scripts/run.py.
|
||||||
ExecStart=/opt/grok-bot/bin/iishko-moderation -addr 127.0.0.1:48003
|
# 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
|
Restart=on-failure
|
||||||
RestartSec=3
|
RestartSec=3
|
||||||
TimeoutStopSec=15
|
TimeoutStopSec=15
|
||||||
@@ -15,6 +19,8 @@ NoNewPrivileges=true
|
|||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
ProtectSystem=strict
|
ProtectSystem=strict
|
||||||
ProtectHome=true
|
ProtectHome=true
|
||||||
|
# Runtime state is written under /opt/iishko/var (DBs, logs).
|
||||||
|
ReadWritePaths=/opt/iishko/var
|
||||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||||
CapabilityBoundingSet=
|
CapabilityBoundingSet=
|
||||||
MemoryMax=128M
|
MemoryMax=128M
|
||||||
|
|||||||
@@ -1,13 +1,20 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=iishko webapp (Mini App backend)
|
Description=IISHKO Mini App backend (loopback 127.0.0.1:8850)
|
||||||
After=network.target
|
Documentation=file:/opt/iishko/deploy/README.md
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
EnvironmentFile=/opt/grok-bot/.env
|
Type=simple
|
||||||
ExecStart=/opt/venv/bin/python /opt/grok-bot/webapp/server.py
|
User=root
|
||||||
WorkingDirectory=/opt/grok-bot/webapp
|
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
|
Restart=always
|
||||||
RestartSec=3
|
RestartSec=3
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Status: **shipped runtime is Python**. `gateway/grok-web-skin.py` plus the
|
Status: **shipped runtime is Python**. `gateway/grok-web-skin.py` plus the
|
||||||
`gateway_*` modules below are the runtime that this tree ships and tests. A Go
|
`gateway_*` modules below are the runtime that this tree ships and tests. A Go
|
||||||
native gateway is **not included and is not the default** — nothing here requires
|
native gateway is **not included and is not the default**. The separate Go service
|
||||||
a Go toolchain, and no Go build is part of CI.
|
in `moderation/` is built and checked in CI; it is not the gateway.
|
||||||
|
|
||||||
This page documents operational behaviour, not internals. Authoritative behaviour
|
This page documents operational behaviour, not internals. Authoritative behaviour
|
||||||
is the code in `gateway/` and the root `tests/` suite.
|
is the code in `gateway/` and the root `tests/` suite.
|
||||||
@@ -18,9 +18,9 @@ is the code in `gateway/` and the root `tests/` suite.
|
|||||||
| `gateway/gateway_usage.py` | usage accounting shared by HTTP and key paths |
|
| `gateway/gateway_usage.py` | usage accounting shared by HTTP and key paths |
|
||||||
| `gateway/gateway_providers.py` | provider registry (pinning, ownership, rpm bounds) |
|
| `gateway/gateway_providers.py` | provider registry (pinning, ownership, rpm bounds) |
|
||||||
| `gateway/gateway_provider_relay.py` | relay of a request to a pinned provider |
|
| `gateway/gateway_provider_relay.py` | relay of a request to a pinned provider |
|
||||||
| `gateway/gateway_commerce.py` | money routes (wallet/paid offers), disabled by default |
|
| `bot/gateway_commerce.py` | money routes (wallet/paid offers), disabled by default |
|
||||||
| `gateway/commerce_access.py` | access rules for money/board routes |
|
| `bot/commerce_access.py` | access rules for money/board routes |
|
||||||
| `gateway/community_board.py` | community board: authenticated `/api/activities` (no kill-switch flag) |
|
| `bot/community_board.py` | community board: authenticated `/api/activities` (no kill-switch flag) |
|
||||||
| `bot/account_balances.py` | exact read-only balance aggregation shared by HTTP and the key daemon |
|
| `bot/account_balances.py` | exact read-only balance aggregation shared by HTTP and the key daemon |
|
||||||
|
|
||||||
## Adaptive RPM
|
## Adaptive RPM
|
||||||
@@ -42,7 +42,9 @@ output are unaffected.
|
|||||||
Pinning is opt-in and registry-driven:
|
Pinning is opt-in and registry-driven:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export IISHKO_PROVIDERS_FILE=gateway/providers.example.json
|
cp gateway/providers.example.json providers.json
|
||||||
|
# Edit the private copy for your own instance before enabling pinning.
|
||||||
|
export IISHKO_PROVIDERS_FILE="$PWD/providers.json"
|
||||||
```
|
```
|
||||||
|
|
||||||
* The registry file is operator-owned configuration; `gateway/providers.example.json`
|
* The registry file is operator-owned configuration; `gateway/providers.example.json`
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ from gateway_features import install as install_gateway_features
|
|||||||
from gateway_provider_relay import relay_selected
|
from gateway_provider_relay import relay_selected
|
||||||
from gateway_providers import ProviderError, ProviderRegistry
|
from gateway_providers import ProviderError, ProviderRegistry
|
||||||
from gateway_policy import denial_response
|
from gateway_policy import denial_response
|
||||||
|
from runtime_config import bot_config_path, bot_db_path, effective_bot_config, skin_db_path
|
||||||
# [MODELMETA 2026-10-28] vendor-reference limits: static JSON, read-only, no network.
|
# [MODELMETA 2026-10-28] vendor-reference limits: static JSON, read-only, no network.
|
||||||
# Optional import: the gateway must boot even if the reference file/module is absent.
|
# Optional import: the gateway must boot even if the reference file/module is absent.
|
||||||
try:
|
try:
|
||||||
@@ -99,7 +100,12 @@ async def _models_catalogue_response(req, upstream):
|
|||||||
|
|
||||||
PROVIDER_KEY = web.AppKey("iishko_providers", ProviderRegistry)
|
PROVIDER_KEY = web.AppKey("iishko_providers", ProviderRegistry)
|
||||||
|
|
||||||
UPSTREAM = os.environ.get("IISHKO_UPSTREAM", "http://127.0.0.1:48000")
|
try:
|
||||||
|
with open(bot_config_path(), encoding="utf-8-sig") as config_file:
|
||||||
|
_runtime_cfg = effective_bot_config(json.load(config_file))
|
||||||
|
except FileNotFoundError:
|
||||||
|
_runtime_cfg = effective_bot_config({})
|
||||||
|
UPSTREAM = _runtime_cfg["newapi_url"].rstrip("/")
|
||||||
TIMEOUT = aiohttp.ClientTimeout(total=None, connect=10, sock_connect=10, sock_read=860)
|
TIMEOUT = aiohttp.ClientTimeout(total=None, connect=10, sock_connect=10, sock_read=860)
|
||||||
# Preserve the existing 64 generation slots; reserve independent capacity for reads.
|
# Preserve the existing 64 generation slots; reserve independent capacity for reads.
|
||||||
GENERATION_CONNECTIONS = 256
|
GENERATION_CONNECTIONS = 256
|
||||||
@@ -109,10 +115,8 @@ MAX_BODY = 40 * 1024 * 1024
|
|||||||
MAX_SSE_FRAME = 65536
|
MAX_SSE_FRAME = 65536
|
||||||
LOG = logging.getLogger("gateway_proxy")
|
LOG = logging.getLogger("gateway_proxy")
|
||||||
|
|
||||||
# ---------- [GATE] daily checkin + chat subscription enforcement (owner 2026-10-08) ----------
|
GATE_NEWAPI_DB = _runtime_cfg["newapi_db"]
|
||||||
# Reads current bot-account policy; unavailable databases temporarily deny access.
|
GATE_BOT_DB = bot_db_path(_runtime_cfg["bot_db"])
|
||||||
GATE_BOT_DB = os.environ.get("GATE_BOT_DB", os.environ.get("IISHKO_BOT_DB", "/opt/grok-bot/bot.db"))
|
|
||||||
GATE_NEWAPI_DB = os.environ.get("GATE_NEWAPI_DB", os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db"))
|
|
||||||
GATE_TTL = 60
|
GATE_TTL = 60
|
||||||
_gate_cache = {}
|
_gate_cache = {}
|
||||||
_gate_err_ts = [0.0]
|
_gate_err_ts = [0.0]
|
||||||
@@ -1075,9 +1079,9 @@ async def brand_asset(req):
|
|||||||
# injected JS POSTs it to /api/tg_widget_login.
|
# injected JS POSTs it to /api/tg_widget_login.
|
||||||
# Provision: new-api user "tg<id>" via admin API, password kept in skin-local store (0600).
|
# Provision: new-api user "tg<id>" via admin API, password kept in skin-local store (0600).
|
||||||
# Login: server-side POST /api/user/login, Set-Cookie forwarded to the browser.
|
# Login: server-side POST /api/user/login, Set-Cookie forwarded to the browser.
|
||||||
TG_BOT_CONFIG = os.environ.get("GATE_BOT_CONFIG", "/opt/grok-bot/config.json")
|
TG_BOT_CONFIG = bot_config_path()
|
||||||
TG_ADMIN_TOKEN_FILE = "/root/.secrets/newapi_admin_token"
|
TG_ADMIN_TOKEN_FILE = "/root/.secrets/newapi_admin_token"
|
||||||
TG_PROVISION_DB = os.environ.get("IISHKO_SKIN_DB") or os.environ.get("GATE_TG_DB", "/opt/grok-web-skin-tg.db")
|
TG_PROVISION_DB = skin_db_path()
|
||||||
TG_AUTH_MAX_AGE = 900
|
TG_AUTH_MAX_AGE = 900
|
||||||
TG_SID_SECRET_FILE = os.environ.get("TG_SID_SECRET_FILE", "/root/.secrets/iishko_tg_sid_secret")
|
TG_SID_SECRET_FILE = os.environ.get("TG_SID_SECRET_FILE", "/root/.secrets/iishko_tg_sid_secret")
|
||||||
_TG_SID_SECRET = None
|
_TG_SID_SECRET = None
|
||||||
@@ -1464,8 +1468,8 @@ def _key_share_seize(user_id, attacker_name, owner_name, key):
|
|||||||
|
|
||||||
|
|
||||||
def _tg_bot_token():
|
def _tg_bot_token():
|
||||||
with open(TG_BOT_CONFIG, encoding="utf-8") as fh:
|
with open(TG_BOT_CONFIG, encoding="utf-8-sig") as fh:
|
||||||
return json.load(fh)["bot_token"]
|
return effective_bot_config(json.load(fh))["bot_token"]
|
||||||
|
|
||||||
|
|
||||||
def _tg_check_hash(data):
|
def _tg_check_hash(data):
|
||||||
|
|||||||
+11
-7
@@ -1,22 +1,26 @@
|
|||||||
# iishko-ts
|
# iishko-ts
|
||||||
|
|
||||||
TypeScript rewrite of the [iishko](https://github.com/aaronjaworski710/iishko) Telegram AI bot.
|
Experimental TypeScript/grammY rewrite of the Python bot in this repository.
|
||||||
|
The Python runtime already has a test suite; this prototype explores a different
|
||||||
Why rewrite:
|
structure and is not a drop-in replacement.
|
||||||
- Python monolith (13K lines, single file) accumulated hotfixes; no tests, sync sqlite inside asyncio
|
|
||||||
- TypeScript + grammY: typed end-to-end, native async, modular from day one, graceful shutdown
|
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
**Skeleton / staging.** Core loop works (start, balance, key issuance, streaming chat with quota spend). Not yet at feature parity with the Python bot — production keeps running the Python version until parity + tests are green.
|
**Skeleton / staging, not production-ready.** Implemented handlers cover start,
|
||||||
|
balance, existing-key lookup, and streaming chat with quota spend. Key creation,
|
||||||
|
feature parity, and end-to-end integration are not established. The `/key`
|
||||||
|
prototype can print an existing key into a private chat; do not use it with
|
||||||
|
production credentials. Never run it alongside another polling process using
|
||||||
|
the same bot token. No staging systemd unit is supplied.
|
||||||
|
|
||||||
## Parity roadmap
|
## Parity roadmap
|
||||||
|
|
||||||
- [x] Config (typed, env + config.json)
|
- [x] Config (typed, env + config.json)
|
||||||
- [x] SQLite (WAL, busy_timeout) — users/tokens/ledger
|
- [x] SQLite (WAL, busy_timeout) — users/tokens/ledger
|
||||||
- [x] Gateway client: OpenAI-compat, SSE streaming, native tools, fallback chain (content-policy 400 → next model)
|
- [x] Gateway client: OpenAI-compat, SSE streaming, native tools, fallback chain (content-policy 400 → next model)
|
||||||
- [x] /start (referral capture), /balance, /key (KEYWAIT gate)
|
- [x] /start (referral capture), /balance, existing-key lookup with KEYWAIT gate
|
||||||
- [x] Streaming chat with edit-throttle + quota spend
|
- [x] Streaming chat with edit-throttle + quota spend
|
||||||
|
- [ ] Key creation and a private reveal flow (not plaintext chat delivery)
|
||||||
- [ ] Rank/tier system (MODEL_ALIASES + tier gating via sync_rank_limits equivalent)
|
- [ ] Rank/tier system (MODEL_ALIASES + tier gating via sync_rank_limits equivalent)
|
||||||
- [ ] Games/casino/quiz modules
|
- [ ] Games/casino/quiz modules
|
||||||
- [ ] Webapp (aiohttp → Hono/Fastify) + pricing showcase
|
- [ ] Webapp (aiohttp → Hono/Fastify) + pricing showcase
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=iishko TS bot (staging)
|
|
||||||
After=network-online.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
WorkingDirectory=/opt/iishko-ts
|
|
||||||
Environment=IISHKO_TS_CONFIG=/opt/iishko-ts/config.json
|
|
||||||
ExecStart=/usr/bin/node dist/index.js
|
|
||||||
Restart=always
|
|
||||||
RestartSec=5
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -13,6 +13,8 @@ yarl>=1.9
|
|||||||
psutil>=5.9
|
psutil>=5.9
|
||||||
# password hashing for account bootstrap paths
|
# password hashing for account bootstrap paths
|
||||||
bcrypt>=4.0
|
bcrypt>=4.0
|
||||||
|
# Explicit .env loading by scripts/run.py (never executes shell statements)
|
||||||
|
python-dotenv>=1.0,<2
|
||||||
|
|
||||||
# --- optional features (install only if you use them) ---
|
# --- optional features (install only if you use them) ---
|
||||||
# Web search in chat replies. Upstream package was renamed
|
# Web search in chat replies. Upstream package was renamed
|
||||||
|
|||||||
+140
@@ -0,0 +1,140 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Explicit local/service launcher. --check validates config, not live integrations."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import runpy
|
||||||
|
import sys
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
COMPONENTS = {
|
||||||
|
"bot": "bot/grok_bot.py",
|
||||||
|
"miniapp": "bot/webapp/server.py",
|
||||||
|
"gateway": "gateway/grok-web-skin.py",
|
||||||
|
}
|
||||||
|
CONFIG_KEYS = ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG")
|
||||||
|
PATH_GROUPS = (
|
||||||
|
(("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"), "bot_db", "/opt/grok-bot/bot.db"),
|
||||||
|
(("IISHKO_GW_DB", "GATE_NEWAPI_DB"), "newapi_db", "/opt/grok-gateway/new-api/one-api.db"),
|
||||||
|
(("IISHKO_SKIN_DB", "GATE_TG_DB"), None, "/opt/grok-web-skin-tg.db"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _pick(keys, process, file_values, default):
|
||||||
|
# A service/environment alias beats a canonical value in the optional file.
|
||||||
|
for layer in (process, file_values):
|
||||||
|
for key in keys:
|
||||||
|
if layer.get(key):
|
||||||
|
return layer[key]
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def _path(root, value):
|
||||||
|
path = Path(value).expanduser()
|
||||||
|
return str((root / path).resolve())
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_environment(root=ROOT, env_file=None, process=None):
|
||||||
|
root = Path(root).resolve()
|
||||||
|
process = dict(os.environ if process is None else process)
|
||||||
|
explicit = env_file is not None
|
||||||
|
path = Path(env_file).expanduser() if explicit else root / ".env"
|
||||||
|
if not path.is_absolute():
|
||||||
|
path = root / path
|
||||||
|
file_values = {}
|
||||||
|
if path.exists():
|
||||||
|
from dotenv import dotenv_values
|
||||||
|
# No shell evaluation, parent-file discovery or secret interpolation.
|
||||||
|
file_values = {key: value for key, value in dotenv_values(
|
||||||
|
path, encoding="utf-8-sig", interpolate=False).items() if value is not None}
|
||||||
|
elif explicit:
|
||||||
|
raise ValueError("explicit environment file does not exist")
|
||||||
|
env = {**file_values, **process}
|
||||||
|
config_path = _path(root, _pick(CONFIG_KEYS, process, file_values, "bot/config.json"))
|
||||||
|
for key in CONFIG_KEYS:
|
||||||
|
env[key] = config_path
|
||||||
|
config = {}
|
||||||
|
try:
|
||||||
|
with open(config_path, encoding="utf-8-sig") as source:
|
||||||
|
loaded = json.load(source)
|
||||||
|
if isinstance(loaded, dict):
|
||||||
|
config = loaded
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass # check_configuration reports the config error without exposing values.
|
||||||
|
for keys, config_key, default in PATH_GROUPS:
|
||||||
|
fallback = config.get(config_key) or default
|
||||||
|
value = _path(root, _pick(keys, process, file_values, fallback))
|
||||||
|
for key in keys:
|
||||||
|
env[key] = value
|
||||||
|
env["IISHKO_APP_ROOT"] = _path(root, _pick(("IISHKO_APP_ROOT",), process, file_values, "bot"))
|
||||||
|
for name in ("TG_SID_SECRET_FILE", "IISHKO_BOT_SOURCE", "IISHKO_PROVIDERS_FILE", "IISHKO_ECON_STATE"):
|
||||||
|
if env.get(name):
|
||||||
|
env[name] = _path(root, env[name])
|
||||||
|
upstream = _pick(("IISHKO_UPSTREAM", "NEWAPI_URL"), process, file_values,
|
||||||
|
config.get("newapi_url"))
|
||||||
|
if upstream:
|
||||||
|
env["IISHKO_UPSTREAM"] = env["NEWAPI_URL"] = upstream
|
||||||
|
module_dirs = [env["IISHKO_APP_ROOT"], str(root / "gateway"), str(root / "bot/webapp")]
|
||||||
|
env["IISHKO_RUNTIME_PATHS"] = os.pathsep.join(module_dirs)
|
||||||
|
# Do not inherit a POSIX-only PYTHONPATH from the distributed .env template.
|
||||||
|
env["PYTHONPATH"] = os.pathsep.join(module_dirs)
|
||||||
|
return env
|
||||||
|
|
||||||
|
|
||||||
|
def check_configuration(env):
|
||||||
|
problems = []
|
||||||
|
try:
|
||||||
|
with open(env["GROK_BOT_CFG"], encoding="utf-8-sig") as source:
|
||||||
|
config = json.load(source)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return ["bot config is missing, unreadable or invalid JSON (GROK_BOT_CFG)"]
|
||||||
|
if not isinstance(config, dict):
|
||||||
|
return ["bot config must be a JSON object"]
|
||||||
|
for key, name in (("bot_token", "GROK_BOT_TOKEN"), ("newapi_pass", "NEWAPI_PASS")):
|
||||||
|
if env.get(name):
|
||||||
|
config[key] = env[name]
|
||||||
|
for key in ("bot_token", "main_key", "channel_username", "newapi_pass"):
|
||||||
|
value = config.get(key)
|
||||||
|
if not isinstance(value, str) or not value.strip() or "REPLACE_ME" in value or "your_" in value:
|
||||||
|
problems.append("bot config requires a real value for " + key)
|
||||||
|
if not Path(env["IISHKO_APP_ROOT"]).is_dir():
|
||||||
|
problems.append("IISHKO_APP_ROOT must be an existing bot module directory")
|
||||||
|
if not Path(env["IISHKO_GW_DB"]).is_file():
|
||||||
|
problems.append("IISHKO_GW_DB must point to your existing New API SQLite database")
|
||||||
|
for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"):
|
||||||
|
path = Path(env[key])
|
||||||
|
if (path.exists() and not path.is_file()) or not path.parent.is_dir():
|
||||||
|
problems.append(key + " must name a file in an existing data directory")
|
||||||
|
return problems
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("component", choices=COMPONENTS)
|
||||||
|
parser.add_argument("--env-file", help="explicit dotenv file; real environment takes priority")
|
||||||
|
parser.add_argument("--check", action="store_true", help="offline config preflight, not an app smoke test")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
try:
|
||||||
|
env = prepare_environment(env_file=args.env_file)
|
||||||
|
problems = check_configuration(env)
|
||||||
|
except (OSError, ValueError, ImportError):
|
||||||
|
problems = ["environment setup failed; check the env file and installed requirements"]
|
||||||
|
if problems:
|
||||||
|
for problem in problems:
|
||||||
|
print("ERROR: " + problem, file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
if args.check:
|
||||||
|
print("Configuration preflight passed; no app started or integrations checked.")
|
||||||
|
return 0
|
||||||
|
os.environ.update(env)
|
||||||
|
os.chdir(ROOT)
|
||||||
|
target = ROOT / COMPONENTS[args.component]
|
||||||
|
sys.path[:0] = [str(target.parent), *env["IISHKO_RUNTIME_PATHS"].split(os.pathsep)]
|
||||||
|
sys.argv = [str(target)]
|
||||||
|
runpy.run_path(str(target), run_name="__main__")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -149,13 +149,13 @@ def check_config_templates(problems, notes):
|
|||||||
notes.append("config template absent (optional): %s" % rel)
|
notes.append("config template absent (optional): %s" % rel)
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
json.load(open(path, encoding="utf-8"))
|
json.load(open(path, encoding="utf-8-sig"))
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
problems.append("invalid JSON template %s: %s" % (rel, exc))
|
problems.append("invalid JSON template %s: %s" % (rel, exc))
|
||||||
cfg = os.environ.get("GROK_BOT_CFG") or os.path.join(ROOT, "bot", "config.json")
|
cfg = os.environ.get("GROK_BOT_CFG") or os.path.join(ROOT, "bot", "config.json")
|
||||||
if os.path.isfile(cfg):
|
if os.path.isfile(cfg):
|
||||||
try:
|
try:
|
||||||
data = json.load(open(cfg, encoding="utf-8"))
|
data = json.load(open(cfg, encoding="utf-8-sig"))
|
||||||
placeholders = sorted(k for k, v in data.items()
|
placeholders = sorted(k for k, v in data.items()
|
||||||
if isinstance(v, str) and ("REPLACE_ME" in v or "your_" in v))
|
if isinstance(v, str) and ("REPLACE_ME" in v or "your_" in v))
|
||||||
if placeholders:
|
if placeholders:
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,132 @@
|
|||||||
|
"""Operator route checks are read-only unless an explicit apply is authorized."""
|
||||||
|
from contextlib import closing, redirect_stderr
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
SCRIPT = ROOT / "bot" / "abilities_guard.py"
|
||||||
|
sys.path.insert(0, str(ROOT / "bot"))
|
||||||
|
|
||||||
|
|
||||||
|
class AbilitiesGuardCliTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(tmp.cleanup)
|
||||||
|
self.root = Path(tmp.name)
|
||||||
|
self.db = self.root / "gateway.db"
|
||||||
|
self.source = self.root / "catalog.py"
|
||||||
|
self.source.write_text('TIER_MODELS = {\n 1: ["basic"],\n 4: ["advanced"],\n}\n',
|
||||||
|
encoding="utf-8")
|
||||||
|
with closing(sqlite3.connect(self.db)) as con:
|
||||||
|
con.executescript('''
|
||||||
|
CREATE TABLE channels(id INTEGER PRIMARY KEY, status INTEGER, models TEXT);
|
||||||
|
CREATE TABLE abilities(channel_id INTEGER, model TEXT, "group" TEXT, enabled INTEGER);
|
||||||
|
CREATE TABLE tokens(id INTEGER PRIMARY KEY, status INTEGER, remain_quota INTEGER);
|
||||||
|
CREATE TABLE entry_autobans(uid INTEGER PRIMARY KEY, reason TEXT);
|
||||||
|
INSERT INTO channels VALUES(1,1,'basic, advanced'),(2,2,'basic'),(3,1,'other');
|
||||||
|
INSERT INTO abilities VALUES
|
||||||
|
(1,'basic','t1',0),(1,'advanced','t1',0),(1,'advanced','t4',0),
|
||||||
|
(1,'basic','default',0),(2,'basic','t1',0),(3,'basic','t1',0);
|
||||||
|
INSERT INTO tokens VALUES(1,1,5000);
|
||||||
|
INSERT INTO entry_autobans VALUES(101,'existing-receipt');
|
||||||
|
''')
|
||||||
|
self.env = {key: value for key, value in os.environ.items()
|
||||||
|
if not key.startswith(("IISHKO_", "GROK_", "GATE_", "NEWAPI_", "PYTHONPATH"))}
|
||||||
|
self.env.update(IISHKO_GW_DB=str(self.db), IISHKO_BOT_SOURCE=str(self.source))
|
||||||
|
|
||||||
|
def run_cli(self, *args):
|
||||||
|
return subprocess.run([sys.executable, str(SCRIPT), *map(str, args)],
|
||||||
|
cwd=self.root, env=self.env, capture_output=True,
|
||||||
|
text=True, encoding="utf-8", timeout=15)
|
||||||
|
|
||||||
|
def rows(self, table):
|
||||||
|
with closing(sqlite3.connect(self.db)) as con:
|
||||||
|
return con.execute("SELECT * FROM " + table).fetchall()
|
||||||
|
|
||||||
|
def test_default_is_read_only_with_no_database_changes(self):
|
||||||
|
before = self.db.read_bytes()
|
||||||
|
result = self.run_cli()
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertIn("mode=dry-run", result.stdout)
|
||||||
|
self.assertIn("re-enabled=0", result.stdout)
|
||||||
|
self.assertIn("dark=advanced,basic", result.stdout)
|
||||||
|
self.assertEqual(self.db.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_apply_requires_both_explicit_paths_even_when_env_is_configured(self):
|
||||||
|
before = self.db.read_bytes()
|
||||||
|
for args in (("--apply",), ("--apply", "--db", self.db),
|
||||||
|
("--apply", "--source", self.source)):
|
||||||
|
with self.subTest(args=args):
|
||||||
|
result = self.run_cli(*args)
|
||||||
|
self.assertEqual(result.returncode, 2)
|
||||||
|
self.assertIn("--apply requires explicit --db and --source", result.stderr)
|
||||||
|
self.assertEqual(self.db.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_missing_and_relative_paths_are_rejected_without_database_creation(self):
|
||||||
|
missing = self.root / "absent.db"
|
||||||
|
for args in (("--db", missing), ("--db", "gateway.db"),
|
||||||
|
("--source", "catalog.py"), ("--source", self.root / "absent.py")):
|
||||||
|
with self.subTest(args=args):
|
||||||
|
result = self.run_cli(*args)
|
||||||
|
self.assertEqual(result.returncode, 2)
|
||||||
|
self.assertIn("absolute path to an existing file", result.stderr)
|
||||||
|
self.assertFalse(missing.exists())
|
||||||
|
|
||||||
|
def test_empty_catalogue_does_not_touch_database(self):
|
||||||
|
self.source.write_text("TIER_MODELS = {}\n", encoding="utf-8")
|
||||||
|
before = self.db.read_bytes()
|
||||||
|
result = self.run_cli("--apply", "--db", self.db, "--source", self.source)
|
||||||
|
self.assertEqual(result.returncode, 1)
|
||||||
|
self.assertIn("no database changes made", result.stdout)
|
||||||
|
self.assertEqual(self.db.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_apply_repairs_only_matching_live_tier_abilities(self):
|
||||||
|
tokens, receipts = self.rows("tokens"), self.rows("entry_autobans")
|
||||||
|
result = self.run_cli("--apply", "--db", self.db, "--source", self.source)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertIn("mode=apply", result.stdout)
|
||||||
|
self.assertIn("re-enabled=3", result.stdout)
|
||||||
|
self.assertEqual([row[3] for row in self.rows("abilities")], [1, 0, 1, 1, 0, 0])
|
||||||
|
self.assertEqual(self.rows("tokens"), tokens)
|
||||||
|
self.assertEqual(self.rows("entry_autobans"), receipts)
|
||||||
|
repeated = self.run_cli("--apply", "--db", self.db, "--source", self.source)
|
||||||
|
self.assertEqual(repeated.returncode, 0, repeated.stderr)
|
||||||
|
self.assertIn("re-enabled=0", repeated.stdout)
|
||||||
|
|
||||||
|
def test_schema_failure_returns_nonzero_without_writing(self):
|
||||||
|
with closing(sqlite3.connect(self.db)) as con:
|
||||||
|
con.execute("DROP TABLE abilities")
|
||||||
|
con.commit()
|
||||||
|
before = self.db.read_bytes()
|
||||||
|
result = self.run_cli()
|
||||||
|
self.assertEqual(result.returncode, 2)
|
||||||
|
self.assertIn("Database check failed: OperationalError", result.stderr)
|
||||||
|
self.assertEqual(self.db.read_bytes(), before)
|
||||||
|
|
||||||
|
def test_apply_rolls_back_when_repair_fails(self):
|
||||||
|
spec = importlib.util.spec_from_file_location("abilities_guard_cli_probe", SCRIPT)
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
guard = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(guard)
|
||||||
|
before = self.rows("abilities")
|
||||||
|
|
||||||
|
def fail_after_write(con, tiers):
|
||||||
|
con.execute("UPDATE abilities SET enabled=1")
|
||||||
|
raise sqlite3.OperationalError("offline-injected-error")
|
||||||
|
|
||||||
|
with patch.object(guard, "repair_abilities", side_effect=fail_after_write), redirect_stderr(io.StringIO()):
|
||||||
|
code = guard.main(["--apply", "--db", str(self.db), "--source", str(self.source)])
|
||||||
|
self.assertEqual(code, 2)
|
||||||
|
self.assertEqual(self.rows("abilities"), before)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -524,7 +524,7 @@ class AccountAdminUnbanTests(unittest.TestCase):
|
|||||||
self.assertEqual(self.token(1)["status"], 2)
|
self.assertEqual(self.token(1)["status"], 2)
|
||||||
self.assert_finance(finance)
|
self.assert_finance(finance)
|
||||||
# The same receipt is read by entry autoban in the bot database.
|
# The same receipt is read by entry autoban in the bot database.
|
||||||
self.assertFalse(entry_autoban.ban_user(101))
|
self.assertFalse(entry_autoban.ban_user(101, reason="admin_button"))
|
||||||
self.assert_finance(finance)
|
self.assert_finance(finance)
|
||||||
|
|
||||||
def test_manual_unban_receipt_is_bot_scoped_and_explicit_ban_revokes_it(self):
|
def test_manual_unban_receipt_is_bot_scoped_and_explicit_ban_revokes_it(self):
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ class AccountBalancesTests(unittest.TestCase):
|
|||||||
tree = ast.parse((ROOT/'bot/webapp/mk_daemon.py').read_text(encoding='utf-8'))
|
tree = ast.parse((ROOT/'bot/webapp/mk_daemon.py').read_text(encoding='utf-8'))
|
||||||
functions = [node for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))]
|
functions = [node for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))]
|
||||||
self.ns = dict(globals(), BOT_DB=self.bot, GW_DB=self.gw, Q=500000,
|
self.ns = dict(globals(), BOT_DB=self.bot, GW_DB=self.gw, Q=500000,
|
||||||
|
econ_state_path=lambda: str(Path(temp.name) / 'econ_state.json'),
|
||||||
g=SimpleNamespace(MK_CAP={1:4},badge_of=lambda uid:1,KEY_WAIT_SEC=86400))
|
g=SimpleNamespace(MK_CAP={1:4},badge_of=lambda uid:1,KEY_WAIT_SEC=86400))
|
||||||
exec(compile(ast.Module(body=functions,type_ignores=[]), 'isolated-key-daemon', 'exec'), self.ns)
|
exec(compile(ast.Module(body=functions,type_ignores=[]), 'isolated-key-daemon', 'exec'), self.ns)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,350 @@
|
|||||||
|
"""Deploy/docs contract: every documented unit path must resolve inside this repo.
|
||||||
|
|
||||||
|
The tests are static: they parse the files shipped under ``deploy/`` and the two
|
||||||
|
operator-facing docs. Nothing here starts a service, imports runtime code or
|
||||||
|
touches the network.
|
||||||
|
|
||||||
|
Mapping source of truth is the table in ``deploy/README.md``; the four core
|
||||||
|
units under ``deploy/systemd/`` are checked against it. Services this repository
|
||||||
|
does not implement (healthcheck, alert-watch, media adapter, firewall) ship
|
||||||
|
nothing at all: no units, no templates, no stubs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import shlex
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
DEPLOY = REPO_ROOT / "deploy"
|
||||||
|
SYSTEMD = DEPLOY / "systemd"
|
||||||
|
CADDY = DEPLOY / "caddy" / "Caddyfile.example"
|
||||||
|
DEPLOY_README = DEPLOY / "README.md"
|
||||||
|
RUNTIME_ENV = DEPLOY / "runtime.env.example"
|
||||||
|
CONTRIBUTING = REPO_ROOT / "CONTRIBUTING.md"
|
||||||
|
SECURITY = REPO_ROOT / "SECURITY.md"
|
||||||
|
|
||||||
|
# Units that must exist: the first-party services this repo can actually run.
|
||||||
|
CORE_UNITS = {
|
||||||
|
"grok-bot.service": "bot",
|
||||||
|
"iishko-webapp.service": "miniapp",
|
||||||
|
"grok-web-skin.service": "gateway",
|
||||||
|
"iishko-moderation.service": None, # native binary, not run through run.py
|
||||||
|
}
|
||||||
|
|
||||||
|
# Scripts that do not exist in this repository; they belong to the operator.
|
||||||
|
ABSENT_EXTERNAL_SCRIPTS = (
|
||||||
|
"grok-healthcheck.py",
|
||||||
|
"grok-alert-watch.py",
|
||||||
|
"media_tts.py",
|
||||||
|
"iishko-fw.sh",
|
||||||
|
"/usr/local/sbin/iishko-fw",
|
||||||
|
"zai_shim.caddy",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ``scripts/run.py`` is the shared bootstrap; it is part of the repo contract and
|
||||||
|
# is referenced by every core target unit. If it is missing from a checkout the
|
||||||
|
# units still point at a documented location, so the path check allows it only
|
||||||
|
# when deploy/README.md documents it as the launcher.
|
||||||
|
BOOTSTRAP_REL = "scripts/run.py"
|
||||||
|
|
||||||
|
# Host paths are absolute, so anchoring on "/" keeps the target table (also
|
||||||
|
# backticked) from being parsed as mapping rows across line breaks.
|
||||||
|
MAPPING_ROW = re.compile(r"^\|\s*`(?P<host>/[^`]+)`\s*\|\s*(?P<source>[^|]*)\|\s*(?P<kind>[^|]*)\|", re.M)
|
||||||
|
TARGET_ROW = re.compile(r"^\|\s*`(?P<target>[a-z]+)`\s*\|\s*`(?P<module>[^`]+)`", re.M)
|
||||||
|
|
||||||
|
|
||||||
|
def read(path: Path) -> str:
|
||||||
|
return path.read_text(encoding="utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
def mapping() -> dict[str, tuple[str, str]]:
|
||||||
|
"""host path -> (repo source description, kind)."""
|
||||||
|
rows = {}
|
||||||
|
for match in MAPPING_ROW.finditer(read(DEPLOY_README)):
|
||||||
|
rows[match.group("host").strip()] = (match.group("source").strip(), match.group("kind").strip())
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def targets() -> dict[str, str]:
|
||||||
|
"""run.py target -> repo module."""
|
||||||
|
return {m.group("target"): m.group("module").strip() for m in TARGET_ROW.finditer(read(DEPLOY_README))}
|
||||||
|
|
||||||
|
|
||||||
|
def unit_directives(path: Path) -> list[tuple[str, str]]:
|
||||||
|
out = []
|
||||||
|
for line in read(path).splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith(("#", ";", "[")):
|
||||||
|
continue
|
||||||
|
if "=" not in line:
|
||||||
|
continue
|
||||||
|
key, value = line.split("=", 1)
|
||||||
|
out.append((key.strip(), value.strip()))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def exec_paths(value: str) -> list[str]:
|
||||||
|
"""Absolute filesystem paths from an ExecStart line (argv[0] + path args)."""
|
||||||
|
try:
|
||||||
|
argv = shlex.split(value)
|
||||||
|
except ValueError:
|
||||||
|
argv = value.split()
|
||||||
|
paths = []
|
||||||
|
for arg in argv:
|
||||||
|
if arg.startswith(("-", "@", "+", "!", ":")):
|
||||||
|
arg = arg.lstrip('-@+!:')
|
||||||
|
if arg.startswith("/") and "$" not in arg:
|
||||||
|
paths.append(arg)
|
||||||
|
return paths
|
||||||
|
|
||||||
|
|
||||||
|
def map_to_repo(host_path: str, table: dict[str, tuple[str, str]]) -> str | None:
|
||||||
|
"""Translate a host path into a repo-relative path using the mapping table."""
|
||||||
|
for host, (_source, _kind) in sorted(table.items(), key=lambda kv: -len(kv[0])):
|
||||||
|
host = host.rstrip("/")
|
||||||
|
if host_path == host:
|
||||||
|
return "."
|
||||||
|
if host_path.startswith(host + "/"):
|
||||||
|
return host_path[len(host) + 1 :]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class DeployMappingTest(unittest.TestCase):
|
||||||
|
def test_mapping_table_is_documented(self):
|
||||||
|
table = mapping()
|
||||||
|
self.assertIn("/opt/iishko", table, "deploy/README.md must document the repo root mapping")
|
||||||
|
self.assertIn("/etc/iishko/runtime.env", table, "runtime env file must be documented")
|
||||||
|
kind = table["/opt/iishko"][1].lower()
|
||||||
|
self.assertTrue("дерево" in kind or "tree" in kind, "repo root mapping must be documented as a tree")
|
||||||
|
|
||||||
|
def test_core_unit_execstart_paths_resolve(self):
|
||||||
|
table = mapping()
|
||||||
|
self.assertTrue(table, "mapping table is unreadable")
|
||||||
|
deploy_doc = read(DEPLOY_README)
|
||||||
|
for unit in sorted(SYSTEMD.glob("*.service")):
|
||||||
|
for key, value in unit_directives(unit):
|
||||||
|
if key != "ExecStart":
|
||||||
|
continue
|
||||||
|
paths = exec_paths(value)
|
||||||
|
self.assertTrue(paths, f"{unit.name}: ExecStart has no absolute path: {value}")
|
||||||
|
for host_path in paths:
|
||||||
|
if host_path == "/etc/iishko/runtime.env":
|
||||||
|
# Server-side config: seeded from deploy/runtime.env.example.
|
||||||
|
self.assertIn("/etc/iishko/runtime.env", table)
|
||||||
|
continue
|
||||||
|
rel = map_to_repo(host_path, table)
|
||||||
|
self.assertIsNotNone(rel, f"{unit.name}: {host_path} is outside the documented mapping")
|
||||||
|
if rel.startswith(".venv/"):
|
||||||
|
# Generated on the host, documented as such.
|
||||||
|
self.assertIn(".venv", deploy_doc)
|
||||||
|
self.assertIn("venv", deploy_doc.lower())
|
||||||
|
continue
|
||||||
|
if rel == BOOTSTRAP_REL:
|
||||||
|
# Shared bootstrap: documented, may be provided separately.
|
||||||
|
self.assertIn(BOOTSTRAP_REL, deploy_doc)
|
||||||
|
self.assertTrue(
|
||||||
|
(REPO_ROOT / BOOTSTRAP_REL).is_file(),
|
||||||
|
"scripts/run.py is documented as the launcher but missing from this checkout",
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
if rel == "bin/iishko-moderation":
|
||||||
|
self.assertTrue(
|
||||||
|
(REPO_ROOT / "moderation").is_dir(),
|
||||||
|
"moderation/ must exist to build bin/iishko-moderation",
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
self.assertTrue(
|
||||||
|
(REPO_ROOT / rel).exists(),
|
||||||
|
f"{unit.name}: {host_path} maps to missing {rel}",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_core_units_use_bootstrap_and_required_env_file(self):
|
||||||
|
for name, target in CORE_UNITS.items():
|
||||||
|
path = SYSTEMD / name
|
||||||
|
self.assertTrue(path.is_file(), f"missing core unit {name}")
|
||||||
|
directives = dict(unit_directives(path))
|
||||||
|
self.assertEqual(directives.get("WorkingDirectory"), "/opt/iishko", f"{name}: wrong WorkingDirectory")
|
||||||
|
if target:
|
||||||
|
execstart = directives.get("ExecStart", "")
|
||||||
|
self.assertIn(f"/{BOOTSTRAP_REL} {target}", execstart, f"{name}: must start via scripts/run.py {target}")
|
||||||
|
self.assertIn("--env-file /etc/iishko/runtime.env", execstart, f"{name}: runtime env file not passed")
|
||||||
|
else:
|
||||||
|
self.assertIn("/opt/iishko/bin/iishko-moderation", directives.get("ExecStart", ""), f"{name}: binary path")
|
||||||
|
self.assertEqual(
|
||||||
|
directives.get("EnvironmentFile"),
|
||||||
|
"/etc/iishko/runtime.env",
|
||||||
|
f"{name}: EnvironmentFile must be present and not optional ('-' prefix)",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_run_targets_exist_in_repo(self):
|
||||||
|
table_targets = targets()
|
||||||
|
for target in ("bot", "miniapp", "gateway"):
|
||||||
|
self.assertIn(target, table_targets, f"deploy/README.md must document run.py target {target}")
|
||||||
|
module = table_targets[target]
|
||||||
|
self.assertTrue((REPO_ROOT / module).is_file(), f"target {target} points at missing {module}")
|
||||||
|
|
||||||
|
def test_docs_state_the_launcher_semantics(self):
|
||||||
|
text = read(DEPLOY_README)
|
||||||
|
self.assertIn(BOOTSTRAP_REL, text)
|
||||||
|
self.assertIn("bot/iishko_bot.py", text)
|
||||||
|
self.assertIn("bot/grok_bot.py", text)
|
||||||
|
self.assertIn("--check", text)
|
||||||
|
|
||||||
|
def test_canonical_resolver_matches_documented_order(self):
|
||||||
|
module = REPO_ROOT / "bot" / "runtime_config.py"
|
||||||
|
self.assertTrue(module.is_file(), "deploy/README.md points at bot/runtime_config.py, which is missing")
|
||||||
|
body = read(module)
|
||||||
|
for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG", "IISHKO_SKIN_DB", "GATE_TG_DB"):
|
||||||
|
self.assertIn(name, body, f"bot/runtime_config.py must resolve {name}")
|
||||||
|
# Documented precedence: canonical name wins over the legacy alias.
|
||||||
|
order = [body.index(name) for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG")]
|
||||||
|
self.assertEqual(
|
||||||
|
order, sorted(order), "bot config precedence in runtime_config.py differs from deploy/README.md"
|
||||||
|
)
|
||||||
|
self.assertLess(body.index("IISHKO_SKIN_DB"), body.index("GATE_TG_DB"))
|
||||||
|
|
||||||
|
|
||||||
|
class DeployScopeTest(unittest.TestCase):
|
||||||
|
def test_no_external_script_in_core_units(self):
|
||||||
|
for unit in SYSTEMD.glob("*"):
|
||||||
|
body = read(unit)
|
||||||
|
for absent in ABSENT_EXTERNAL_SCRIPTS:
|
||||||
|
self.assertNotIn(absent, body, f"{unit.name} references absent {absent}")
|
||||||
|
|
||||||
|
def test_core_dir_has_no_templates(self):
|
||||||
|
for item in SYSTEMD.iterdir():
|
||||||
|
self.assertFalse(item.name.endswith(".example"), f"{item.name} is a template, not a unit")
|
||||||
|
self.assertEqual(set(CORE_UNITS), {p.name for p in SYSTEMD.glob("*.service")})
|
||||||
|
|
||||||
|
def test_no_external_template_graveyard(self):
|
||||||
|
"""Dead templates were removed: no directory may hold units the repo cannot run."""
|
||||||
|
self.assertFalse((DEPLOY / "external").exists(), "deploy/external must stay removed")
|
||||||
|
self.assertEqual(
|
||||||
|
{"systemd", "caddy"}, {p.name for p in DEPLOY.iterdir() if p.is_dir()},
|
||||||
|
"deploy/ grew an undocumented subdirectory",
|
||||||
|
)
|
||||||
|
for path in DEPLOY.rglob("*.service*"):
|
||||||
|
self.assertIn(path.parent, (SYSTEMD,), f"{path} ships a unit outside systemd/")
|
||||||
|
self.assertIn(path.name, CORE_UNITS, f"{path.name} has no implementation in this repo")
|
||||||
|
|
||||||
|
def test_readme_states_services_are_out_of_scope(self):
|
||||||
|
text = read(DEPLOY_README).lower()
|
||||||
|
for absent in ("healthcheck", "alert", "media", "firewall"):
|
||||||
|
self.assertIn(absent, text, f"deploy/README.md must say {absent} is not included")
|
||||||
|
self.assertNotIn("external/", text, "deploy/README.md still points at the removed template dir")
|
||||||
|
self.assertNotIn("template only", text, "deploy/README.md still announces template files")
|
||||||
|
|
||||||
|
|
||||||
|
class CaddyTest(unittest.TestCase):
|
||||||
|
def test_imports_resolve_inside_repo(self):
|
||||||
|
body = read(CADDY)
|
||||||
|
defined = set(re.findall(r"\((\w+)\)\s*\{", body))
|
||||||
|
for name in re.findall(r"^\s*import\s+(\S+)", body, re.M):
|
||||||
|
if name.startswith(("http://", "https://")):
|
||||||
|
continue
|
||||||
|
if name in defined:
|
||||||
|
continue
|
||||||
|
candidates = [DEPLOY / "caddy" / name, DEPLOY / "caddy" / f"{name}.caddy"]
|
||||||
|
self.assertTrue(
|
||||||
|
any(candidate.is_file() for candidate in candidates),
|
||||||
|
f"Caddyfile imports {name}, which is neither an inline snippet nor a file in deploy/caddy/",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_no_absent_media_service_route(self):
|
||||||
|
body = read(CADDY)
|
||||||
|
active = "\n".join(line for line in body.splitlines() if not line.strip().startswith("#"))
|
||||||
|
self.assertNotIn("127.0.0.1:8000", active, "Caddyfile must not route to the absent media adapter")
|
||||||
|
self.assertNotIn("zai_shim", body)
|
||||||
|
self.assertIn("reverse_proxy 127.0.0.1:48001", active)
|
||||||
|
self.assertIn("reverse_proxy 127.0.0.1:8850", active)
|
||||||
|
|
||||||
|
|
||||||
|
class DocsTest(unittest.TestCase):
|
||||||
|
def test_contributing_has_no_symlink_lie(self):
|
||||||
|
text = read(CONTRIBUTING).lower()
|
||||||
|
for forbidden in ("symlink", "симлинк", "120000"):
|
||||||
|
self.assertNotIn(forbidden, text, f"CONTRIBUTING.md still claims a symlink ({forbidden})")
|
||||||
|
|
||||||
|
def test_contributing_does_not_instruct_copying_modules(self):
|
||||||
|
text = read(CONTRIBUTING)
|
||||||
|
for pattern in (r"cp\s+bot/iishko_bot\.py", r"cp\s+bot/grok_bot\.py", r"copying the real module"):
|
||||||
|
self.assertIsNone(re.search(pattern, text, re.I), f"CONTRIBUTING.md still recommends {pattern}")
|
||||||
|
|
||||||
|
def test_contributing_points_at_real_launcher_and_tests(self):
|
||||||
|
text = read(CONTRIBUTING)
|
||||||
|
self.assertIn(f"python {BOOTSTRAP_REL} bot", text)
|
||||||
|
self.assertIn("bot/grok_bot.py", text)
|
||||||
|
self.assertIn("bot/iishko_bot.py", text)
|
||||||
|
self.assertIn("pytest", text)
|
||||||
|
self.assertNotIn("их почти нет", text)
|
||||||
|
|
||||||
|
def test_no_placeholder_maintainer_handle(self):
|
||||||
|
for doc in (CONTRIBUTING, SECURITY):
|
||||||
|
text = read(doc)
|
||||||
|
self.assertNotIn("@your-handle", text, f"{doc.name} still has a placeholder handle")
|
||||||
|
self.assertIsNone(
|
||||||
|
re.search(r"(?<![\w./])@[A-Za-z][A-Za-z0-9_]{4,}", text),
|
||||||
|
f"{doc.name} invents a private contact handle",
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_security_promises_no_sla(self):
|
||||||
|
text = read(SECURITY).lower()
|
||||||
|
for claim in ("72", "48 час", "в течение суток", "sla", "гарантируем ответ"):
|
||||||
|
self.assertNotIn(claim, text, f"SECURITY.md promises an unsupported response time ({claim})")
|
||||||
|
|
||||||
|
def test_security_has_no_fake_disclosure_endpoint(self):
|
||||||
|
text = read(SECURITY)
|
||||||
|
self.assertIn("профил", text.lower())
|
||||||
|
self.assertNotIn("mailto:", text)
|
||||||
|
self.assertIsNone(re.search(r"https?://", text), "SECURITY.md must not point at an unverified disclosure URL")
|
||||||
|
|
||||||
|
|
||||||
|
class RuntimeEnvTest(unittest.TestCase):
|
||||||
|
def test_example_env_has_no_secrets(self):
|
||||||
|
self.assertTrue(RUNTIME_ENV.is_file())
|
||||||
|
text = read(RUNTIME_ENV)
|
||||||
|
for line in text.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
key, value = line.split("=", 1)
|
||||||
|
value = value.strip().strip('"').strip("'")
|
||||||
|
self.assertNotRegex(value, r"^sk-[A-Za-z0-9_-]{8,}", f"{key}: looks like a real API key")
|
||||||
|
self.assertNotRegex(value, r"^[0-9a-fA-F]{32,}$", f"{key}: looks like a real secret")
|
||||||
|
self.assertNotRegex(value, r"^\d{8,10}:[A-Za-z0-9_-]{30,}$", f"{key}: looks like a real bot token")
|
||||||
|
if "TOKEN" in key.upper():
|
||||||
|
self.assertIn("REPLACE_ME", value, f"{key}: token placeholder must stay a placeholder")
|
||||||
|
|
||||||
|
def test_runtime_env_is_not_committed(self):
|
||||||
|
self.assertFalse((REPO_ROOT / "runtime.env").exists(), "runtime.env must never be committed")
|
||||||
|
self.assertFalse((REPO_ROOT / ".env").exists(), ".env must never be committed")
|
||||||
|
gitignore = read(REPO_ROOT / ".gitignore")
|
||||||
|
self.assertIn("runtime.env", gitignore)
|
||||||
|
|
||||||
|
def test_sid_secret_file_stays_outside_repo(self):
|
||||||
|
text = read(RUNTIME_ENV)
|
||||||
|
self.assertIn("TG_SID_SECRET_FILE", text, "runtime.env.example must document the session secret file")
|
||||||
|
value = ""
|
||||||
|
for line in text.splitlines():
|
||||||
|
if line.strip().startswith("TG_SID_SECRET_FILE="):
|
||||||
|
value = line.split("=", 1)[1].strip()
|
||||||
|
self.assertTrue(value.startswith("/"), "secret file must be an absolute operator path, not repo-relative")
|
||||||
|
self.assertNotIn(".local/tg-sid-secret", read(REPO_ROOT / ".gitignore"))
|
||||||
|
self.assertIn("0600", text)
|
||||||
|
self.assertIn("gateway service user", text)
|
||||||
|
self.assertNotIn("> FILE", text, "shell redirection can create a 0644 session secret")
|
||||||
|
|
||||||
|
def test_documented_env_names_match_example(self):
|
||||||
|
text = read(RUNTIME_ENV)
|
||||||
|
for name in ("GROK_BOT_CFG", "IISHKO_SKIN_DB", "IISHKO_UPSTREAM", "IISHKO_MODERATION_TOKEN"):
|
||||||
|
self.assertIn(name, text, f"runtime.env.example must define {name}")
|
||||||
|
deploy_doc = read(DEPLOY_README)
|
||||||
|
for alias in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG"):
|
||||||
|
self.assertIn(alias, deploy_doc, f"deploy/README.md must document config alias {alias}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Shared IP is a signal, not a sanction: autoban is opt-in (IISHKO_ENTRY_AUTOBAN=1)."""
|
"""Shared IP remains an operator signal even when legacy enforcement is enabled."""
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -66,11 +66,12 @@ class NatUsersTest(unittest.TestCase):
|
|||||||
self.assertEqual(banned, [(0,), (0,)])
|
self.assertEqual(banned, [(0,), (0,)])
|
||||||
self.assertEqual(alerts, 1) # operator still gets the signal
|
self.assertEqual(alerts, 1) # operator still gets the signal
|
||||||
|
|
||||||
def test_opt_in_enforces(self):
|
def test_opt_in_still_keeps_shared_ip_access_and_quota(self):
|
||||||
with mock.patch.dict(os.environ, {"IISHKO_ENTRY_AUTOBAN": "1"}):
|
with mock.patch.dict(os.environ, {"IISHKO_ENTRY_AUTOBAN": "1"}):
|
||||||
tokens, banned, _ = self._visit_both()
|
tokens, banned, alerts = self._visit_both()
|
||||||
self.assertEqual(tokens, [(2, 0), (2, 0)])
|
self.assertEqual(tokens, [(1, 5000), (1, 5000)])
|
||||||
self.assertEqual(banned, [(1,), (1,)])
|
self.assertEqual(banned, [(0,), (0,)])
|
||||||
|
self.assertEqual(alerts, 1)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""Real SQLite regressions: shared networks cannot alter accounts or balances."""
|
||||||
|
import ast
|
||||||
|
from contextlib import closing
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "bot"))
|
||||||
|
import entry_autoban
|
||||||
|
from entry_telemetry import EntryTelemetry, delivery_enabled, notification_text
|
||||||
|
from runtime_config import skin_db_path
|
||||||
|
|
||||||
|
|
||||||
|
class EntrySafetyTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(tmp.cleanup)
|
||||||
|
root = Path(tmp.name)
|
||||||
|
self.bot, self.gateway, self.skin = (str(root / name) for name in ("bot.db", "gateway.db", "custom-skin.db"))
|
||||||
|
with closing(sqlite3.connect(self.bot)) as con, con:
|
||||||
|
con.executescript("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, username TEXT, banned INTEGER DEFAULT 0,"
|
||||||
|
"privacy_ok INTEGER DEFAULT 1, admin INTEGER DEFAULT 0, token_name TEXT, api_key TEXT,"
|
||||||
|
"key_locked INTEGER DEFAULT 0,chat_key_locked INTEGER DEFAULT 0);"
|
||||||
|
"INSERT INTO users(tg_id,username,token_name) VALUES(101,'one','tg101'),(202,'two','tg202');")
|
||||||
|
with closing(sqlite3.connect(self.gateway)) as con, con:
|
||||||
|
con.executescript("CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT,key TEXT,status INTEGER,"
|
||||||
|
"remain_quota INTEGER,unlimited_quota INTEGER,deleted_at INTEGER);"
|
||||||
|
"INSERT INTO tokens VALUES(1,'tg101','one',1,777,0,NULL),(2,'tg202','two',1,888,0,NULL);"
|
||||||
|
"CREATE TABLE users(username TEXT,status INTEGER);"
|
||||||
|
"INSERT INTO users VALUES('tg101',1),('tg202',1);")
|
||||||
|
with closing(sqlite3.connect(self.skin)) as con, con:
|
||||||
|
con.executescript("CREATE TABLE ip_claims(token_name TEXT);INSERT INTO ip_claims VALUES('tg101'),('tg202');")
|
||||||
|
self.env = patch.dict(os.environ, {"IISHKO_SKIN_DB": self.skin}, clear=True)
|
||||||
|
self.env.start()
|
||||||
|
self.addCleanup(self.env.stop)
|
||||||
|
for name, value in (("BOT_DB", self.bot), ("GW_DB", self.gateway), ("SKIN_DB", self.skin), ("PROTECT", ())):
|
||||||
|
item = patch.object(entry_autoban, name, value)
|
||||||
|
item.start()
|
||||||
|
self.addCleanup(item.stop)
|
||||||
|
|
||||||
|
def rows(self, path, sql):
|
||||||
|
with closing(sqlite3.connect(path)) as con:
|
||||||
|
return con.execute(sql).fetchall()
|
||||||
|
|
||||||
|
def test_empty_environment_disables_automatic_sanctions_and_delivery(self):
|
||||||
|
self.assertFalse(entry_autoban.enabled())
|
||||||
|
self.assertFalse(delivery_enabled())
|
||||||
|
self.assertEqual(entry_autoban.ban_cluster([101], reason="automatic_signal"), [])
|
||||||
|
self.assertEqual(self.rows(self.gateway, "SELECT status,remain_quota FROM tokens"), [(1, 777), (1, 888)])
|
||||||
|
|
||||||
|
def test_shared_public_ip_is_only_a_review_signal_even_if_legacy_flag_is_enabled(self):
|
||||||
|
os.environ["IISHKO_ENTRY_AUTOBAN"] = "1"
|
||||||
|
telemetry = EntryTelemetry(self.bot, b"offline-test-secret", [999], clock=lambda: 100000)
|
||||||
|
telemetry.init_db()
|
||||||
|
telemetry.record(101, "8.8.4.4")
|
||||||
|
telemetry.record(202, "8.8.4.4")
|
||||||
|
self.assertEqual(self.rows(self.bot, "SELECT banned FROM users ORDER BY tg_id"), [(0,), (0,)])
|
||||||
|
self.assertEqual(self.rows(self.gateway, "SELECT status,remain_quota FROM tokens ORDER BY id"), [(1, 777), (1, 888)])
|
||||||
|
self.assertEqual(self.rows(self.gateway, "SELECT status FROM users"), [(1,), (1,)])
|
||||||
|
self.assertEqual(self.rows(self.skin, "SELECT COUNT(*) FROM ip_claims"), [(2,)])
|
||||||
|
self.assertEqual(self.rows(self.bot, "SELECT COUNT(*) FROM wa_entry_alerts"), [(1,)])
|
||||||
|
claim = telemetry.claim()
|
||||||
|
self.assertIsNotNone(claim)
|
||||||
|
self.assertIn("не применяется", notification_text(claim))
|
||||||
|
self.assertFalse(entry_autoban.ban_user(101))
|
||||||
|
self.assertEqual(entry_autoban.ban_cluster([101, 202]), [])
|
||||||
|
|
||||||
|
def test_explicit_admin_moderation_is_not_disabled_by_safe_automatic_default(self):
|
||||||
|
with patch.object(entry_autoban, "ban_user", return_value=True) as ban:
|
||||||
|
self.assertEqual(entry_autoban.ban_cluster([101, 101], reason="admin_button"), [101])
|
||||||
|
ban.assert_called_once_with(101, "admin_button")
|
||||||
|
|
||||||
|
def test_unified_custom_skin_path_is_used_for_actual_ip_claim_cleanup(self):
|
||||||
|
tree = ast.parse((ROOT / "bot/grok_bot.py").read_text(encoding="utf-8"))
|
||||||
|
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_full_ban")
|
||||||
|
ns = {"sqlite3": sqlite3, "Path": Path, "skin_db_path": skin_db_path,
|
||||||
|
"BOT_DB": self.bot, "log": logging.getLogger("offline-cleanup"), "_newapi_exec": Mock()}
|
||||||
|
exec(compile(ast.Module(body=[function], type_ignores=[]), "real-full-ban", "exec"), ns)
|
||||||
|
ns["_full_ban"](101, "tg101", "admin_button")
|
||||||
|
self.assertEqual(self.rows(self.skin, "SELECT token_name FROM ip_claims"), [("tg202",)])
|
||||||
|
# The gateway uses the same resolver, not a second hardcoded fallback.
|
||||||
|
tree = ast.parse((ROOT / "gateway/grok-web-skin.py").read_text(encoding="utf-8"))
|
||||||
|
assignment = next(node for node in tree.body if isinstance(node, ast.Assign)
|
||||||
|
and any(isinstance(target, ast.Name) and target.id == "TG_PROVISION_DB" for target in node.targets))
|
||||||
|
ns = {"skin_db_path": skin_db_path}
|
||||||
|
exec(compile(ast.Module(body=[assignment], type_ignores=[]), "gateway-path", "exec"), ns)
|
||||||
|
self.assertEqual(ns["TG_PROVISION_DB"], self.skin)
|
||||||
|
|
||||||
|
def test_notification_opt_in_and_kill_switches(self):
|
||||||
|
for value in ("0", "", "false", "no", "off", "unexpected"):
|
||||||
|
with self.subTest(value=value), patch.dict(os.environ, {"IISHKO_NOTIFICATIONS_ENABLED": value}):
|
||||||
|
self.assertFalse(delivery_enabled())
|
||||||
|
os.environ["IISHKO_NOTIFICATIONS_ENABLED"] = "1"
|
||||||
|
self.assertTrue(delivery_enabled())
|
||||||
|
os.environ["IISHKO_ENTRY_DELIVERY_ENABLED"] = "0"
|
||||||
|
self.assertFalse(delivery_enabled())
|
||||||
|
os.environ["IISHKO_ENTRY_DELIVERY_ENABLED"] = "1"
|
||||||
|
os.environ["IISHKO_SUPPORT_DELIVERY_ENABLED"] = "0"
|
||||||
|
self.assertFalse(delivery_enabled())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
"""Office-извлечение: обычные файлы, битые архивы и пределы распаковки.
|
||||||
|
|
||||||
|
ZIP раздувает вход: 8 МБ .pptx распаковываются в сотни МБ. Тесты проверяют,
|
||||||
|
что читаются фактические байты, а не объявленный размер, что лимит общий на
|
||||||
|
архив, что чтение идёт кусками и что ранний выход срабатывает, когда текста уже
|
||||||
|
достаточно. Никаких гигантских файлов: лимиты подменяются на маленькие.
|
||||||
|
"""
|
||||||
|
import importlib
|
||||||
|
import io
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
import warnings
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
BOT = Path(__file__).resolve().parents[1] / "bot"
|
||||||
|
sys.path.insert(0, str(BOT))
|
||||||
|
file_intake = importlib.import_module("file_intake")
|
||||||
|
extract = file_intake.extract
|
||||||
|
_OfficeBudget = file_intake._OfficeBudget
|
||||||
|
|
||||||
|
|
||||||
|
def _zip_bytes(entries) -> bytes:
|
||||||
|
"""Собрать zip в памяти. `entries` — список пар (name, bytes); дубликаты разрешены."""
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("ignore", UserWarning) # duplicate names are part of the scenario
|
||||||
|
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for name, data in entries:
|
||||||
|
zf.writestr(name, data)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _docx_bytes(text: str = "Привет, мир") -> bytes:
|
||||||
|
return _zip_bytes([
|
||||||
|
("[Content_Types].xml", b"<Types/>"),
|
||||||
|
("word/document.xml",
|
||||||
|
f'<?xml version="1.0"?><w:document><w:body><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:body></w:document>'.encode()),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def _slide_body(text: str) -> bytes:
|
||||||
|
return (
|
||||||
|
'<?xml version="1.0"?><p:sld><p:cSld><p:spTree><p:sp><p:txBody>'
|
||||||
|
f'<a:p><a:r><a:t>{text}</a:t></a:r></a:p>'
|
||||||
|
'</p:txBody></p:sp></p:spTree></p:cSld></p:sld>'
|
||||||
|
).encode()
|
||||||
|
|
||||||
|
|
||||||
|
def _pptx_bytes(texts) -> bytes:
|
||||||
|
entries = [("[Content_Types].xml", b"<Types/>")]
|
||||||
|
for i, text in enumerate(texts, start=1):
|
||||||
|
entries.append((f"ppt/slides/slide{i}.xml", _slide_body(text)))
|
||||||
|
return _zip_bytes(entries)
|
||||||
|
|
||||||
|
|
||||||
|
def _xlsx_bytes(shared, rows) -> bytes:
|
||||||
|
items = "".join(f"<si><t>{s}</t></si>" for s in shared)
|
||||||
|
cells = "".join(
|
||||||
|
f'<c r="A{n}" t="s"><v>{idx}</v></c>' for n, idx in enumerate(rows, start=1)
|
||||||
|
)
|
||||||
|
sheet = (
|
||||||
|
'<?xml version="1.0"?><worksheet><sheetData>'
|
||||||
|
f'<row r="1">{cells}</row>'
|
||||||
|
'</sheetData></worksheet>'
|
||||||
|
).encode()
|
||||||
|
return _zip_bytes([
|
||||||
|
("[Content_Types].xml", b"<Types/>"),
|
||||||
|
("xl/sharedStrings.xml", f"<sst>{items}</sst>".encode()),
|
||||||
|
("xl/worksheets/sheet1.xml", sheet),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
def _odt_bytes(paras) -> bytes:
|
||||||
|
body = "".join(f"<text:p>{p}</text:p>" for p in paras)
|
||||||
|
return _zip_bytes([
|
||||||
|
("[Content_Types].xml", b"<Types/>"),
|
||||||
|
("content.xml", f'<?xml version="1.0"?><office:document><office:body>{body}</office:body></office:document>'.encode()),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
class _SpyZip:
|
||||||
|
"""Прокси над ZipFile: считает открытия записей и запрошенные размеры read()."""
|
||||||
|
|
||||||
|
def __init__(self, zf: zipfile.ZipFile) -> None:
|
||||||
|
self._zf = zf
|
||||||
|
self.opened: list[str] = []
|
||||||
|
self.read_sizes: list[int] = []
|
||||||
|
|
||||||
|
def namelist(self):
|
||||||
|
return self._zf.namelist()
|
||||||
|
|
||||||
|
def infolist(self):
|
||||||
|
return self._zf.infolist()
|
||||||
|
|
||||||
|
def getinfo(self, name):
|
||||||
|
return self._zf.getinfo(name)
|
||||||
|
|
||||||
|
def open(self, name, *args, **kwargs):
|
||||||
|
self.opened.append(name)
|
||||||
|
raw = self._zf.open(name, *args, **kwargs)
|
||||||
|
spy = self
|
||||||
|
|
||||||
|
class _File:
|
||||||
|
def read(self, n=-1):
|
||||||
|
spy.read_sizes.append(n)
|
||||||
|
return raw.read(n)
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc):
|
||||||
|
raw.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
return _File()
|
||||||
|
|
||||||
|
|
||||||
|
class _RecordingBudget(_OfficeBudget):
|
||||||
|
"""Запоминает созданные читатели, чтобы проверить фактический объём распаковки."""
|
||||||
|
|
||||||
|
created: list = []
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
_RecordingBudget.created.append(self)
|
||||||
|
|
||||||
|
|
||||||
|
class OfficeExtractionTest(unittest.TestCase):
|
||||||
|
def setUp(self) -> None:
|
||||||
|
_RecordingBudget.created = []
|
||||||
|
|
||||||
|
# --- normal extraction --------------------------------------------------
|
||||||
|
|
||||||
|
def test_docx_plain_text(self) -> None:
|
||||||
|
res = extract("заметка.docx", _docx_bytes())
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
self.assertEqual(res.kind, "docx")
|
||||||
|
self.assertIn("Привет, мир", res.text)
|
||||||
|
self.assertFalse(res.truncated)
|
||||||
|
self.assertEqual(res.chars, len(res.text))
|
||||||
|
|
||||||
|
def test_pptx_slides_order_and_labels(self) -> None:
|
||||||
|
res = extract("deck.pptx", _pptx_bytes(["первый", "второй", "третий"]))
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
self.assertEqual(res.kind, "pptx")
|
||||||
|
self.assertLess(res.text.index("первый"), res.text.index("второй"))
|
||||||
|
self.assertLess(res.text.index("второй"), res.text.index("третий"))
|
||||||
|
self.assertIn("slide1.xml", res.text)
|
||||||
|
|
||||||
|
def test_xlsx_shared_strings_resolved(self) -> None:
|
||||||
|
res = extract("таблица.xlsx", _xlsx_bytes(["альфа", "бета"], [1, 0]))
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
line = [ln for ln in res.text.splitlines() if "\t" in ln][0]
|
||||||
|
self.assertEqual(line.split("\t"), ["бета", "альфа"])
|
||||||
|
|
||||||
|
def test_odt_paragraphs(self) -> None:
|
||||||
|
res = extract("док.odt", _odt_bytes(["первый абзац", "второй абзац"]))
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
self.assertEqual(res.kind, "odt")
|
||||||
|
self.assertIn("первый абзац", res.text)
|
||||||
|
self.assertIn("второй абзац", res.text)
|
||||||
|
|
||||||
|
# --- refusals -----------------------------------------------------------
|
||||||
|
|
||||||
|
def test_corrupt_archive_is_reported(self) -> None:
|
||||||
|
res = extract("битый.pptx", b"PK\x03\x04 definitely not a real zip")
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertIn("повреждён", res.reason)
|
||||||
|
|
||||||
|
def test_broken_compressed_stream_is_reported(self) -> None:
|
||||||
|
data = _pptx_bytes(["text"])
|
||||||
|
errors = (EOFError("truncated compressed stream"),
|
||||||
|
file_intake.zlib.error("invalid compressed stream"))
|
||||||
|
for error in errors:
|
||||||
|
with self.subTest(error=type(error).__name__):
|
||||||
|
with mock.patch.object(zipfile.ZipFile, "open", side_effect=error):
|
||||||
|
result = extract("broken.pptx", data)
|
||||||
|
self.assertFalse(result.ok)
|
||||||
|
self.assertIn("повреждён", result.reason)
|
||||||
|
|
||||||
|
def test_zip_without_office_structure(self) -> None:
|
||||||
|
data = _zip_bytes([("readme.txt", b"just a zip")])
|
||||||
|
res = extract("файл.docx", data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertIn("без ожидаемой структуры", res.reason)
|
||||||
|
|
||||||
|
def test_upload_limit_unchanged(self) -> None:
|
||||||
|
res = extract("big.docx", b"\0" * (file_intake.MAX_FILE_BYTES + 1))
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertIn("предел", res.reason)
|
||||||
|
self.assertEqual(file_intake.MAX_FILE_BYTES, 8 * 1024 * 1024)
|
||||||
|
|
||||||
|
# --- decompression limits -----------------------------------------------
|
||||||
|
|
||||||
|
def test_entry_limit_bounds_actual_bytes(self) -> None:
|
||||||
|
payload = ("слово " * 4000).encode() # ~24 KB of text, compresses well
|
||||||
|
data = _zip_bytes([("word/document.xml", payload)])
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy, entry_limit=1000)
|
||||||
|
text, clipped = reader.read_prefix("word/document.xml")
|
||||||
|
self.assertTrue(clipped)
|
||||||
|
self.assertLessEqual(reader.consumed, 1000)
|
||||||
|
self.assertLessEqual(sum(spy.read_sizes), 1000) # bytes actually read
|
||||||
|
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||||||
|
self.assertNotIn(-1, spy.read_sizes)
|
||||||
|
self.assertLessEqual(len(text), 1000)
|
||||||
|
self.assertEqual(reader.entries_read, 1)
|
||||||
|
self.assertTrue(reader.cut)
|
||||||
|
self.assertTrue(reader.warnings)
|
||||||
|
|
||||||
|
def test_exact_cap_needs_no_lookahead(self) -> None:
|
||||||
|
"""Ровно лимит байт: без досмотра лишнего байта, но помечается как обрезанное."""
|
||||||
|
payload = b"a" * 1024
|
||||||
|
data = _zip_bytes([("word/document.xml", payload)])
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy, entry_limit=1024, chunk=4096)
|
||||||
|
text, clipped = reader.read_prefix("word/document.xml")
|
||||||
|
self.assertEqual(spy.read_sizes, [1024]) # a single read, exactly the cap
|
||||||
|
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||||||
|
self.assertLessEqual(sum(spy.read_sizes), 1024)
|
||||||
|
self.assertEqual(len(text), 1024)
|
||||||
|
self.assertTrue(clipped) # an entry exactly at the cap is conservatively reported as cut
|
||||||
|
self.assertTrue(reader.cut)
|
||||||
|
|
||||||
|
def test_entry_limit_does_not_trust_declared_size(self) -> None:
|
||||||
|
# small input, large decompressed size: only real reads are charged
|
||||||
|
payload = b"a" * 200_000
|
||||||
|
data = _zip_bytes([("word/document.xml", payload)])
|
||||||
|
self.assertLess(len(data), 5000)
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||||
|
reader = _OfficeBudget(zf, entry_limit=5000)
|
||||||
|
reader.read_prefix("word/document.xml")
|
||||||
|
self.assertLessEqual(reader.consumed, 5000)
|
||||||
|
|
||||||
|
def test_total_budget_shared_across_entries(self) -> None:
|
||||||
|
data = _zip_bytes([
|
||||||
|
("ppt/slides/slide1.xml", b"x" * 5000),
|
||||||
|
("ppt/slides/slide2.xml", b"x" * 5000),
|
||||||
|
("ppt/slides/slide3.xml", b"x" * 5000),
|
||||||
|
])
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy, entry_limit=5000, total_limit=12_000)
|
||||||
|
for name in ("ppt/slides/slide1.xml", "ppt/slides/slide2.xml", "ppt/slides/slide3.xml"):
|
||||||
|
reader.read_prefix(name)
|
||||||
|
self.assertLessEqual(reader.consumed, 12_000)
|
||||||
|
self.assertLessEqual(sum(spy.read_sizes), 12_000)
|
||||||
|
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||||||
|
self.assertTrue(reader.cut)
|
||||||
|
self.assertTrue(any("предел" in w for w in reader.warnings))
|
||||||
|
|
||||||
|
def test_entry_cap_bounds_actual_reads(self) -> None:
|
||||||
|
"""Жёсткий предел на число записей: дальше лимита записи не открываются."""
|
||||||
|
names = [f"part{i}.xml" for i in range(1, 21)]
|
||||||
|
data = _zip_bytes([(n, b"<x>tiny</x>") for n in names])
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy, max_entries=5)
|
||||||
|
for name in names[:8]:
|
||||||
|
reader.read_prefix(name)
|
||||||
|
self.assertEqual(reader.entries_read, 5)
|
||||||
|
self.assertEqual(len(spy.opened), 5) # nothing is opened past the entry cap
|
||||||
|
self.assertTrue(reader.cut)
|
||||||
|
self.assertTrue(any("не читаются" in w for w in reader.warnings))
|
||||||
|
|
||||||
|
def test_reads_are_chunked(self) -> None:
|
||||||
|
data = _zip_bytes([("word/document.xml", b"y" * 20_000)])
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy, entry_limit=20_000, chunk=1024)
|
||||||
|
reader.read_prefix("word/document.xml")
|
||||||
|
self.assertTrue(spy.read_sizes)
|
||||||
|
self.assertNotIn(-1, spy.read_sizes) # never read a whole entry at once
|
||||||
|
self.assertLessEqual(max(spy.read_sizes), 1024)
|
||||||
|
self.assertGreater(len(spy.read_sizes), 1)
|
||||||
|
|
||||||
|
def test_slide_count_capped(self) -> None:
|
||||||
|
texts = [f"слайд {i}" for i in range(1, 11)]
|
||||||
|
with mock.patch.object(file_intake, "_OFFICE_MAX_SLIDES", 3):
|
||||||
|
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy)
|
||||||
|
text = file_intake._from_pptx(reader)
|
||||||
|
self.assertEqual(len(spy.opened), 3)
|
||||||
|
self.assertIn("слайд 3", text)
|
||||||
|
self.assertNotIn("слайд 4", text)
|
||||||
|
self.assertTrue(any("прочитаны первые 3" in w for w in reader.warnings))
|
||||||
|
|
||||||
|
def test_slide_byte_limit(self) -> None:
|
||||||
|
texts = ["текст " * 2000, "хвост"]
|
||||||
|
with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 400):
|
||||||
|
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||||||
|
reader = _OfficeBudget(real)
|
||||||
|
file_intake._from_pptx(reader)
|
||||||
|
self.assertLessEqual(reader.consumed, 800) # per-slide cap
|
||||||
|
self.assertTrue(reader.cut)
|
||||||
|
|
||||||
|
def test_markup_heavy_slide_stays_bounded(self) -> None:
|
||||||
|
markup = ('<a:p><a:r><a:rPr lang="ru-RU" sz="1800" b="1"/><a:t>'
|
||||||
|
+ "i" * 50 + "</a:t></a:r></a:p>") * 200 # ~24 KB of markup, ~10 KB of text
|
||||||
|
data = _zip_bytes([("ppt/slides/slide1.xml", markup.encode())])
|
||||||
|
with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 2000):
|
||||||
|
res = extract("тяжёлый.pptx", data)
|
||||||
|
self.assertTrue(res.truncated)
|
||||||
|
self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET)
|
||||||
|
self.assertTrue(res.warnings)
|
||||||
|
|
||||||
|
def test_early_stop_when_enough_text(self) -> None:
|
||||||
|
texts = [f"слайд номер {i} " + "z" * 500 for i in range(1, 41)]
|
||||||
|
with mock.patch.object(file_intake, "TEXT_BUDGET", 300):
|
||||||
|
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||||||
|
spy = _SpyZip(real)
|
||||||
|
reader = _OfficeBudget(spy)
|
||||||
|
res = file_intake._finish(
|
||||||
|
file_intake._from_pptx(reader), "pptx", reader.warnings, cut=reader.cut,
|
||||||
|
)
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
self.assertTrue(res.truncated)
|
||||||
|
self.assertLess(len(spy.opened), len(texts)) # stops before the end
|
||||||
|
self.assertLessEqual(len(res.text), 300)
|
||||||
|
self.assertTrue(any("показаны не все слайды" in w for w in res.warnings))
|
||||||
|
|
||||||
|
def test_eight_compressible_slides_bounded(self) -> None:
|
||||||
|
"""Исходный сценарий: 8 «плотных» слайдов. Объём ограничен байтами, не памятью."""
|
||||||
|
texts = [("слайд " + "q" * 3000) for _ in range(8)]
|
||||||
|
data = _pptx_bytes(texts)
|
||||||
|
self.assertLess(len(data), 20_000) # small input
|
||||||
|
with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget):
|
||||||
|
res = extract("amplify.pptx", data)
|
||||||
|
self.assertTrue(_RecordingBudget.created)
|
||||||
|
reader = _RecordingBudget.created[-1]
|
||||||
|
self.assertLessEqual(reader.consumed, file_intake._OFFICE_TOTAL_MAX_BYTES)
|
||||||
|
self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET)
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
|
||||||
|
def test_truncation_is_announced(self) -> None:
|
||||||
|
data = _pptx_bytes(["а" * 5000, "б" * 5000, "в" * 5000, "г" * 5000, "д" * 5000, "е" * 5000])
|
||||||
|
res = extract("long.pptx", data)
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
self.assertTrue(res.truncated)
|
||||||
|
self.assertTrue(any("показаны первые" in w for w in res.warnings))
|
||||||
|
|
||||||
|
def test_duplicate_entry_read_once(self) -> None:
|
||||||
|
data = _zip_bytes([
|
||||||
|
("word/document.xml", "<w:document><w:p><w:t>старый</w:t></w:p></w:document>".encode()),
|
||||||
|
("word/document.xml", "<w:document><w:p><w:t>новый</w:t></w:p></w:document>".encode()),
|
||||||
|
])
|
||||||
|
with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget):
|
||||||
|
res = extract("dubl.docx", data)
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
reader = _RecordingBudget.created[-1]
|
||||||
|
self.assertEqual(reader.entries_read, 1)
|
||||||
|
self.assertIn("новый", res.text)
|
||||||
|
self.assertLessEqual(reader.consumed, len(data) * 8)
|
||||||
|
|
||||||
|
|
||||||
|
# --- XLSX: one row must not inflate the text ------------------
|
||||||
|
|
||||||
|
def test_xlsx_reused_string_cannot_inflate_output(self) -> None:
|
||||||
|
"""Одна короткая строка sharedStrings на 3000 ячеек не даёт длинный текст."""
|
||||||
|
data = _xlsx_bytes(["z" * 40], [0] * 3000)
|
||||||
|
self.assertLess(len(data), 20_000) # small input
|
||||||
|
with mock.patch.object(file_intake, "TEXT_BUDGET", 500):
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
reader = _OfficeBudget(real)
|
||||||
|
text = file_intake._from_xlsx(reader)
|
||||||
|
self.assertLessEqual(len(text), 600)
|
||||||
|
self.assertTrue(any("ячейк" in w for w in reader.warnings))
|
||||||
|
self.assertTrue(reader.cut)
|
||||||
|
|
||||||
|
def test_xlsx_amplification_marked_truncated(self) -> None:
|
||||||
|
data = _xlsx_bytes(["z" * 40], [0] * 3000)
|
||||||
|
self.assertLess(len(data), 20_000) # small input, thousands of cells
|
||||||
|
with mock.patch.object(file_intake, "TEXT_BUDGET", 500):
|
||||||
|
res = extract("широкая.xlsx", data)
|
||||||
|
self.assertEqual(file_intake.TEXT_BUDGET, 500)
|
||||||
|
self.assertTrue(res.ok, res.reason)
|
||||||
|
self.assertTrue(res.truncated)
|
||||||
|
self.assertLessEqual(len(res.text), 500)
|
||||||
|
self.assertGreater(len(res.text), 100) # useful prefix survives
|
||||||
|
self.assertTrue(res.warnings)
|
||||||
|
|
||||||
|
def test_xlsx_cell_count_capped(self) -> None:
|
||||||
|
data = _xlsx_bytes(["z"], [0] * 3000)
|
||||||
|
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||||
|
reader = _OfficeBudget(real)
|
||||||
|
text = file_intake._from_xlsx(reader)
|
||||||
|
self.assertTrue(any(f"ячеек в строке больше {file_intake._MAX_XLSX_CELLS}" in w
|
||||||
|
for w in reader.warnings))
|
||||||
|
self.assertEqual(text.splitlines()[-1].count("\t") + 1, file_intake._MAX_XLSX_CELLS)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""PPTX: many highly-compressible slides must not be decompressed past the budgets."""
|
"""PPTX extraction stops on text and actual decompression budgets."""
|
||||||
import io
|
import io
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sys
|
import sys
|
||||||
@@ -20,19 +20,36 @@ def _pptx(slides: int, text: str) -> bytes:
|
|||||||
|
|
||||||
|
|
||||||
class PptxBudgetTest(unittest.TestCase):
|
class PptxBudgetTest(unittest.TestCase):
|
||||||
def test_stops_reading_after_text_budget(self):
|
def _extract_with_budget(self, data, total_limit=None):
|
||||||
data = _pptx(200, "x" * 5000)
|
readers = []
|
||||||
with mock.patch.object(file_intake, "_read_entry", wraps=file_intake._read_entry) as rd:
|
original = file_intake._OfficeBudget
|
||||||
res = file_intake.extract("deck.pptx", data)
|
|
||||||
self.assertTrue(res.ok)
|
|
||||||
self.assertTrue(res.truncated)
|
|
||||||
self.assertLess(rd.call_count, 10)
|
|
||||||
|
|
||||||
def test_total_unpacked_budget_rejects(self):
|
def factory(zf):
|
||||||
data = _pptx(20, "<b/>" * 262144) # 20 MiB of markup, no text
|
kwargs = {} if total_limit is None else {"total_limit": total_limit}
|
||||||
with mock.patch.object(file_intake, "_MAX_UNPACKED_BYTES", 8 * 1024 * 1024):
|
reader = original(zf, **kwargs)
|
||||||
res = file_intake.extract("deck.pptx", data)
|
readers.append(reader)
|
||||||
self.assertFalse(res.ok)
|
return reader
|
||||||
|
|
||||||
|
with mock.patch.object(file_intake, "_OfficeBudget", side_effect=factory):
|
||||||
|
result = file_intake.extract("deck.pptx", data)
|
||||||
|
self.assertEqual(len(readers), 1)
|
||||||
|
return result, readers[0]
|
||||||
|
|
||||||
|
def test_stops_reading_after_text_budget(self):
|
||||||
|
result, reader = self._extract_with_budget(_pptx(200, "x" * 5000))
|
||||||
|
self.assertTrue(result.ok)
|
||||||
|
self.assertTrue(result.truncated)
|
||||||
|
self.assertLess(reader.entries_read, 10)
|
||||||
|
self.assertLessEqual(len(result.text), file_intake.TEXT_BUDGET)
|
||||||
|
|
||||||
|
def test_total_unpacked_budget_rejects_textless_archive(self):
|
||||||
|
limit = 8 * 1024 * 1024
|
||||||
|
result, reader = self._extract_with_budget(_pptx(20, "<b/>" * 262144), limit)
|
||||||
|
self.assertFalse(result.ok)
|
||||||
|
self.assertTrue(result.truncated)
|
||||||
|
self.assertEqual(reader.consumed, limit)
|
||||||
|
self.assertLess(reader.entries_read, 20)
|
||||||
|
self.assertTrue(result.warnings)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,191 @@
|
|||||||
|
"""Bootstrap tests use temporary config files, not operator or production settings."""
|
||||||
|
from contextlib import closing
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
spec = importlib.util.spec_from_file_location("runtime_launcher", ROOT / "scripts/run.py")
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
launcher = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(launcher)
|
||||||
|
sys.path.insert(0, str(ROOT / "bot"))
|
||||||
|
runtime_config = __import__("runtime_config")
|
||||||
|
|
||||||
|
|
||||||
|
class BootstrapTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(tmp.cleanup)
|
||||||
|
self.root = Path(tmp.name)
|
||||||
|
(self.root / "bot").mkdir()
|
||||||
|
(self.root / "gateway").mkdir()
|
||||||
|
(self.root / "bot/webapp").mkdir()
|
||||||
|
self.config = {"bot_token": "123456:offline-token", "main_key": "offline-main",
|
||||||
|
"newapi_pass": "offline-password", "channel_username": "offline_channel",
|
||||||
|
"bot_db": "./bot.db", "newapi_db": "./one-api.db",
|
||||||
|
"newapi_url": "http://127.0.0.1:49100"}
|
||||||
|
(self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8")
|
||||||
|
with closing(sqlite3.connect(self.root / "one-api.db")) as con:
|
||||||
|
con.execute("CREATE TABLE tokens(id INTEGER PRIMARY KEY)")
|
||||||
|
con.commit()
|
||||||
|
(self.root / ".env").write_text("IISHKO_SKIN_DB=./skin.db\n", encoding="utf-8")
|
||||||
|
|
||||||
|
def test_explicit_root_dotenv_loads_without_shell_or_interpolation(self):
|
||||||
|
(self.root / ".env").write_text(
|
||||||
|
'\ufeffGROK_BOT_CFG=./bot/config.json\nIISHKO_SKIN_DB="./skin with space.db"\n'
|
||||||
|
'IISHKO_ENTRY_AUTOBAN=0 # comment\nOPAQUE="${SHELL_SECRET} $(nothing-executed)"\n', encoding="utf-8")
|
||||||
|
env = launcher.prepare_environment(self.root, process={"SHELL_SECRET": "must-not-expand"})
|
||||||
|
self.assertEqual(env["GROK_BOT_CFG"], str(self.root / "bot/config.json"))
|
||||||
|
self.assertEqual(env["IISHKO_ENTRY_AUTOBAN"], "0")
|
||||||
|
self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "skin with space.db"))
|
||||||
|
self.assertEqual(env["GATE_TG_DB"], env["IISHKO_SKIN_DB"])
|
||||||
|
self.assertEqual(env["OPAQUE"], "${SHELL_SECRET} $(nothing-executed)")
|
||||||
|
self.assertEqual(launcher.check_configuration(env), [])
|
||||||
|
|
||||||
|
def test_real_environment_including_legacy_alias_beats_file(self):
|
||||||
|
(self.root / ".env").write_text("IISHKO_SKIN_DB=./file.db\nIISHKO_NOTIFICATIONS_ENABLED=1\n", encoding="utf-8")
|
||||||
|
env = launcher.prepare_environment(self.root, process={"GATE_TG_DB": "./service.db",
|
||||||
|
"IISHKO_NOTIFICATIONS_ENABLED": "0"})
|
||||||
|
self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "service.db"))
|
||||||
|
self.assertEqual(env["IISHKO_NOTIFICATIONS_ENABLED"], "0")
|
||||||
|
env = launcher.prepare_environment(self.root, process={"IISHKO_SKIN_DB": "./canonical.db", "GATE_TG_DB": "./old.db"})
|
||||||
|
self.assertEqual(env["GATE_TG_DB"], str(self.root / "canonical.db"))
|
||||||
|
|
||||||
|
def test_legacy_config_and_db_aliases_are_shared_across_components(self):
|
||||||
|
env = launcher.prepare_environment(self.root, process={"GROK_BOT_CONFIG": "./bot/config.json",
|
||||||
|
"GATE_NEWAPI_DB": "./one-api.db"})
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
self.assertEqual(runtime_config.bot_config_path(), env["GROK_BOT_CFG"])
|
||||||
|
self.assertEqual(runtime_config.gateway_db_path(), env["IISHKO_GW_DB"])
|
||||||
|
self.assertEqual(runtime_config.skin_db_path(), env["IISHKO_SKIN_DB"])
|
||||||
|
self.assertEqual(env["GATE_BOT_CONFIG"], env["GROK_BOT_CFG"])
|
||||||
|
self.assertEqual(env["GATE_NEWAPI_DB"], env["IISHKO_GW_DB"])
|
||||||
|
|
||||||
|
def test_no_parent_dotenv_discovery_and_explicit_missing_file_fails(self):
|
||||||
|
(self.root / ".env").write_text("PARENT_ONLY=not-loaded\n", encoding="utf-8")
|
||||||
|
child = self.root / "child"
|
||||||
|
child.mkdir()
|
||||||
|
self.assertNotIn("PARENT_ONLY", launcher.prepare_environment(child, process={}))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
launcher.prepare_environment(self.root, env_file="missing.env", process={})
|
||||||
|
|
||||||
|
def test_real_platform_module_separator_and_direct_legacy_fallback(self):
|
||||||
|
env = launcher.prepare_environment(self.root, process={})
|
||||||
|
self.assertIn(str(self.root / "bot"), env["PYTHONPATH"].split(os.pathsep))
|
||||||
|
self.assertIn(str(self.root / "gateway"), env["PYTHONPATH"].split(os.pathsep))
|
||||||
|
with patch.dict(os.environ, {}, clear=True):
|
||||||
|
self.assertEqual(runtime_config.skin_db_path(), "/opt/grok-web-skin-tg.db")
|
||||||
|
self.assertFalse(runtime_config.notifications_enabled())
|
||||||
|
with patch.dict(os.environ, {"GATE_TG_DB": "legacy.db"}, clear=True):
|
||||||
|
self.assertEqual(runtime_config.skin_db_path(), "legacy.db")
|
||||||
|
|
||||||
|
def test_check_is_offline_and_never_starts_application(self):
|
||||||
|
with patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=launcher.prepare_environment(self.root, process={})), patch.object(launcher.runpy, "run_path") as run, patch("sys.stdout", new_callable=io.StringIO) as out:
|
||||||
|
self.assertEqual(launcher.main(["bot", "--check"]), 0)
|
||||||
|
run.assert_not_called()
|
||||||
|
self.assertIn("no app started", out.getvalue())
|
||||||
|
|
||||||
|
def test_normal_launch_receives_dotenv_paths_and_selected_entrypoint(self):
|
||||||
|
env = launcher.prepare_environment(self.root, process={})
|
||||||
|
old_cwd, old_path, old_argv = Path.cwd(), list(sys.path), list(sys.argv)
|
||||||
|
try:
|
||||||
|
with patch.dict(os.environ, {}, clear=True), patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=env), patch.object(launcher.runpy, "run_path") as run:
|
||||||
|
self.assertEqual(launcher.main(["miniapp"]), 0)
|
||||||
|
run.assert_called_once_with(str(self.root / "bot/webapp/server.py"), run_name="__main__")
|
||||||
|
self.assertEqual(os.environ["GROK_BOT_CONFIG"], str(self.root / "bot/config.json"))
|
||||||
|
self.assertEqual(Path.cwd(), self.root)
|
||||||
|
self.assertIn(str(self.root / "bot"), sys.path)
|
||||||
|
finally:
|
||||||
|
os.chdir(old_cwd)
|
||||||
|
sys.path[:] = old_path
|
||||||
|
sys.argv[:] = old_argv
|
||||||
|
|
||||||
|
def test_missing_config_and_placeholders_fail_without_leaking_values(self):
|
||||||
|
config_path = self.root / "bot/config.json"
|
||||||
|
config_path.write_text('{"bot_token":"REPLACE_ME_PRIVATE_VALUE"}', encoding="utf-8")
|
||||||
|
errors = launcher.check_configuration(launcher.prepare_environment(self.root, process={}))
|
||||||
|
self.assertTrue(errors)
|
||||||
|
self.assertNotIn("PRIVATE_VALUE", str(errors))
|
||||||
|
config_path.unlink()
|
||||||
|
self.assertIn("missing", launcher.check_configuration(launcher.prepare_environment(self.root, process={}))[0])
|
||||||
|
|
||||||
|
def test_config_upstream_and_db_survive_without_explicit_env_overrides(self):
|
||||||
|
env = launcher.prepare_environment(self.root, process={})
|
||||||
|
self.assertEqual(env["IISHKO_UPSTREAM"], self.config["newapi_url"])
|
||||||
|
self.assertEqual(env["NEWAPI_URL"], self.config["newapi_url"])
|
||||||
|
self.assertEqual(env["IISHKO_GW_DB"], str(self.root / "one-api.db"))
|
||||||
|
self.assertNotIn("TG_SID_SECRET_FILE", env)
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
resolved = runtime_config.effective_bot_config(self.config)
|
||||||
|
self.assertEqual(resolved["newapi_url"], env["IISHKO_UPSTREAM"])
|
||||||
|
self.assertEqual(resolved["newapi_db"], env["IISHKO_GW_DB"])
|
||||||
|
|
||||||
|
def test_env_secrets_override_config_for_validation_and_all_consumers(self):
|
||||||
|
for key in ("bot_token", "newapi_pass"):
|
||||||
|
self.config[key] = "REPLACE_ME_PRIVATE_VALUE"
|
||||||
|
(self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8")
|
||||||
|
process = {"GROK_BOT_TOKEN": "123456:env-offline-token", "NEWAPI_PASS": "env-offline-password",
|
||||||
|
"NEWAPI_URL": "http://127.0.0.1:49101", "TG_SID_SECRET_FILE": "./existing-secret"}
|
||||||
|
env = launcher.prepare_environment(self.root, process=process)
|
||||||
|
self.assertEqual(launcher.check_configuration(env), [])
|
||||||
|
self.assertEqual(env["TG_SID_SECRET_FILE"], str(self.root / "existing-secret"))
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
resolved = runtime_config.effective_bot_config(self.config)
|
||||||
|
self.assertEqual(resolved["bot_token"], process["GROK_BOT_TOKEN"])
|
||||||
|
self.assertEqual(resolved["newapi_pass"], process["NEWAPI_PASS"])
|
||||||
|
self.assertEqual(resolved["newapi_url"], process["NEWAPI_URL"])
|
||||||
|
|
||||||
|
def test_preflight_rejects_invalid_data_directories_without_creating_db(self):
|
||||||
|
env = launcher.prepare_environment(self.root, process={})
|
||||||
|
for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"):
|
||||||
|
with self.subTest(key=key):
|
||||||
|
changed = {**env, key: str(self.root / "missing-directory/new.db")}
|
||||||
|
self.assertTrue(any(key in problem for problem in launcher.check_configuration(changed)))
|
||||||
|
self.assertFalse(Path(changed[key]).exists())
|
||||||
|
|
||||||
|
def test_real_cli_reads_explicit_env_outside_repository_cwd(self):
|
||||||
|
env_file = self.root / "runtime.env"
|
||||||
|
env_file.write_text("\n".join((
|
||||||
|
"GROK_BOT_CFG=" + (self.root / "bot/config.json").as_posix(),
|
||||||
|
"IISHKO_GW_DB=" + (self.root / "one-api.db").as_posix(),
|
||||||
|
"IISHKO_APP_ROOT=" + (self.root / "bot").as_posix(),
|
||||||
|
"IISHKO_BOT_DB=" + (self.root / "bot.db").as_posix(),
|
||||||
|
"IISHKO_SKIN_DB=" + (self.root / "skin.db").as_posix(),
|
||||||
|
)), encoding="utf-8")
|
||||||
|
process = {key: value for key, value in os.environ.items()
|
||||||
|
if not key.startswith(("IISHKO_", "GATE_", "GROK_", "NEWAPI_", "TG_SID_"))}
|
||||||
|
for component in launcher.COMPONENTS:
|
||||||
|
with self.subTest(component=component):
|
||||||
|
result = subprocess.run([sys.executable, str(ROOT / "scripts/run.py"), component,
|
||||||
|
"--env-file", str(env_file), "--check"], cwd=self.root,
|
||||||
|
env=process, capture_output=True, text=True, timeout=15)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertIn("preflight passed", result.stdout)
|
||||||
|
|
||||||
|
def test_selfcheck_accepts_the_same_utf8_bom_config_as_entrypoints(self):
|
||||||
|
sc_spec = importlib.util.spec_from_file_location("iishko_selfcheck", ROOT / "scripts/selfcheck.py")
|
||||||
|
assert sc_spec is not None and sc_spec.loader is not None
|
||||||
|
selfcheck = importlib.util.module_from_spec(sc_spec)
|
||||||
|
sc_spec.loader.exec_module(selfcheck)
|
||||||
|
config_path = self.root / "bot/config.json"
|
||||||
|
config_path.write_text(json.dumps(self.config), encoding="utf-8-sig")
|
||||||
|
self.assertEqual(config_path.read_bytes()[:3], b"\xef\xbb\xbf")
|
||||||
|
problems, notes = [], []
|
||||||
|
with patch.object(selfcheck, "ROOT", str(self.root)), \
|
||||||
|
patch.dict(os.environ, {"GROK_BOT_CFG": str(config_path)}):
|
||||||
|
selfcheck.check_config_templates(problems, notes)
|
||||||
|
self.assertEqual(problems, [])
|
||||||
|
self.assertFalse(any("bot config not found" in note for note in notes))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
"""Economy consumers must honour the shared runtime path helpers.
|
||||||
|
|
||||||
|
Regressions cover non-default paths and conflicting aliases without importing the
|
||||||
|
whole bot runtime: econ_cap/account_admin are loaded as isolated module instances,
|
||||||
|
and the Mini App daemon helpers are AST-extracted and executed alone.
|
||||||
|
"""
|
||||||
|
import ast
|
||||||
|
from contextlib import closing
|
||||||
|
import importlib.util
|
||||||
|
import itertools
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
BOT = ROOT / "bot"
|
||||||
|
sys.path.insert(0, str(BOT))
|
||||||
|
|
||||||
|
COUNTER = itertools.count()
|
||||||
|
|
||||||
|
DEFAULT_BOT_DB = "/opt/grok-bot/bot.db"
|
||||||
|
DEFAULT_GW_DB = "/opt/grok-gateway/new-api/one-api.db"
|
||||||
|
DEFAULT_STATE = "/opt/grok-bot/econ_cap_state.json"
|
||||||
|
|
||||||
|
|
||||||
|
def _load(relative_path):
|
||||||
|
"""Load a module file by path so each case sees its own environment."""
|
||||||
|
path = BOT / relative_path
|
||||||
|
name = "econ_paths_probe_%s_%d" % (path.stem, next(COUNTER))
|
||||||
|
spec = importlib.util.spec_from_file_location(name, path)
|
||||||
|
assert spec is not None and spec.loader is not None
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
def _daemon_functions(names, environ):
|
||||||
|
"""Execute only the requested functions from mk_daemon, never the module."""
|
||||||
|
source = (BOT / "webapp" / "mk_daemon.py").read_text(encoding="utf-8")
|
||||||
|
tree = ast.parse(source)
|
||||||
|
wanted = [node for node in tree.body
|
||||||
|
if isinstance(node, ast.FunctionDef) and node.name in names]
|
||||||
|
missing = set(names) - {node.name for node in wanted}
|
||||||
|
assert not missing, "mk_daemon.py no longer defines %s" % sorted(missing)
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def econ_state_path():
|
||||||
|
calls.append(True)
|
||||||
|
return environ["IISHKO_ECON_STATE"]
|
||||||
|
|
||||||
|
namespace = {"json": json, "sqlite3": sqlite3, "econ_state_path": econ_state_path,
|
||||||
|
"calls": calls}
|
||||||
|
exec(compile(ast.Module(body=wanted, type_ignores=[]), "<mk_daemon>", "exec"), namespace)
|
||||||
|
return namespace, calls
|
||||||
|
|
||||||
|
|
||||||
|
def _module_assignments(relative_path):
|
||||||
|
tree = ast.parse((BOT / relative_path).read_text(encoding="utf-8"))
|
||||||
|
found = {}
|
||||||
|
for node in tree.body:
|
||||||
|
if isinstance(node, ast.Assign):
|
||||||
|
for target in node.targets:
|
||||||
|
if isinstance(target, ast.Name):
|
||||||
|
found[target.id] = node.value
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _calls_name(node, name):
|
||||||
|
return (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
|
||||||
|
and node.func.id == name)
|
||||||
|
|
||||||
|
|
||||||
|
def _mentions(node, name):
|
||||||
|
return any(isinstance(item, ast.Attribute) and item.attr == name
|
||||||
|
or isinstance(item, ast.Name) and item.id == name
|
||||||
|
for item in ast.walk(node))
|
||||||
|
|
||||||
|
|
||||||
|
class ConsumerPathTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(tmp.cleanup)
|
||||||
|
root = Path(tmp.name)
|
||||||
|
self.bot_db = str(root / "custom" / "bot.db")
|
||||||
|
self.gw_db = str(root / "custom" / "gateway.db")
|
||||||
|
self.state = str(root / "custom" / "econ_state.json")
|
||||||
|
for path in (self.bot_db, self.gw_db, self.state):
|
||||||
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- econ_cap
|
||||||
|
def test_econ_cap_prefers_canonical_names(self):
|
||||||
|
env = {
|
||||||
|
"IISHKO_BOT_DB": self.bot_db,
|
||||||
|
"GROK_BOT_DB": "/legacy/bot.db",
|
||||||
|
"GATE_BOT_DB": "/legacy/gate.db",
|
||||||
|
"IISHKO_GW_DB": self.gw_db,
|
||||||
|
"GATE_NEWAPI_DB": "/legacy/gateway.db",
|
||||||
|
"IISHKO_ECON_STATE": self.state,
|
||||||
|
}
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
module = _load("econ_cap.py")
|
||||||
|
self.assertEqual(module.BOT_DB, self.bot_db)
|
||||||
|
self.assertEqual(module.NA_DB, self.gw_db)
|
||||||
|
self.assertEqual(module.STATE, self.state)
|
||||||
|
|
||||||
|
def test_econ_cap_keeps_legacy_aliases(self):
|
||||||
|
env = {"GROK_BOT_DB": self.bot_db, "GATE_NEWAPI_DB": self.gw_db}
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
module = _load("econ_cap.py")
|
||||||
|
self.assertEqual(module.BOT_DB, self.bot_db)
|
||||||
|
self.assertEqual(module.NA_DB, self.gw_db)
|
||||||
|
|
||||||
|
def test_econ_cap_ignores_empty_canonical_alias(self):
|
||||||
|
env = {"IISHKO_BOT_DB": "", "GROK_BOT_DB": self.bot_db,
|
||||||
|
"IISHKO_ECON_STATE": ""}
|
||||||
|
with patch.dict(os.environ, env, clear=True):
|
||||||
|
module = _load("econ_cap.py")
|
||||||
|
self.assertEqual(module.BOT_DB, self.bot_db)
|
||||||
|
self.assertEqual(module.STATE, DEFAULT_STATE)
|
||||||
|
|
||||||
|
def test_econ_cap_defaults_when_nothing_is_configured(self):
|
||||||
|
with patch.dict(os.environ, {}, clear=True):
|
||||||
|
module = _load("econ_cap.py")
|
||||||
|
self.assertEqual(module.BOT_DB, DEFAULT_BOT_DB)
|
||||||
|
self.assertEqual(module.NA_DB, DEFAULT_GW_DB)
|
||||||
|
self.assertEqual(module.STATE, DEFAULT_STATE)
|
||||||
|
|
||||||
|
def test_econ_cap_state_file_round_trip(self):
|
||||||
|
Path(self.state).write_text(json.dumps({"v": 2, "paused": {"tg101": {"tid": 7}}}),
|
||||||
|
encoding="utf-8")
|
||||||
|
with patch.dict(os.environ, {"IISHKO_ECON_STATE": self.state}, clear=True):
|
||||||
|
module = _load("econ_cap.py")
|
||||||
|
paused, migrated = module.load_state(archive=False)
|
||||||
|
self.assertEqual(paused, {"tg101": {"tid": 7}})
|
||||||
|
self.assertEqual(migrated, 0)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ account_admin
|
||||||
|
def test_account_admin_pause_path_uses_canonical_helper(self):
|
||||||
|
with patch.dict(os.environ, {"IISHKO_ECON_STATE": self.state}, clear=True):
|
||||||
|
module = _load("account_admin.py")
|
||||||
|
self.assertEqual(module.PAUSE_PATH, self.state)
|
||||||
|
for name in ("set_banned", "unban_account"):
|
||||||
|
default = module.__dict__[name].__kwdefaults__["pause_path"]
|
||||||
|
self.assertEqual(default, self.state, name)
|
||||||
|
|
||||||
|
def test_account_admin_pause_path_falls_back(self):
|
||||||
|
with patch.dict(os.environ, {}, clear=True):
|
||||||
|
module = _load("account_admin.py")
|
||||||
|
self.assertEqual(module.PAUSE_PATH, DEFAULT_STATE)
|
||||||
|
|
||||||
|
# --------------------------------------------------------------- mk_daemon
|
||||||
|
def test_mk_daemon_module_paths_come_from_helpers(self):
|
||||||
|
assigns = _module_assignments("webapp/mk_daemon.py")
|
||||||
|
self.assertTrue(_calls_name(assigns["BOT_DB"], "bot_db_path"),
|
||||||
|
"mk_daemon BOT_DB must use the shared bot_db_path helper")
|
||||||
|
self.assertTrue(_mentions(assigns["GW_DB"], "CFG"),
|
||||||
|
"mk_daemon GW_DB must follow the imported bot CFG")
|
||||||
|
self.assertNotIn("GROK_BOT_DB", ast.dump(assigns["BOT_DB"]),
|
||||||
|
"mk_daemon must not re-implement the bot DB alias list")
|
||||||
|
|
||||||
|
def test_mk_daemon_reads_pause_state_from_env_path(self):
|
||||||
|
Path(self.state).write_text(json.dumps({"v": 2, "paused": {}}), encoding="utf-8")
|
||||||
|
environ = {"IISHKO_ECON_STATE": self.state}
|
||||||
|
namespace, calls = _daemon_functions({"_state_path", "_read_pause_state"}, environ)
|
||||||
|
self.assertEqual(namespace["_read_pause_state"](), {"v": 2, "paused": {}})
|
||||||
|
self.assertTrue(calls, "_read_pause_state must resolve the helper by default")
|
||||||
|
|
||||||
|
def test_mk_daemon_explicit_state_override_wins(self):
|
||||||
|
other = str(Path(self.state).with_name("override.json"))
|
||||||
|
Path(other).write_text(json.dumps({"v": 2, "paused": {"tg101": {"tid": 1}}}),
|
||||||
|
encoding="utf-8")
|
||||||
|
environ = {"IISHKO_ECON_STATE": str(Path(self.state).with_name("missing.json"))}
|
||||||
|
namespace, _ = _daemon_functions({"_state_path", "_read_pause_state"}, environ)
|
||||||
|
self.assertEqual(namespace["_read_pause_state"](other),
|
||||||
|
{"v": 2, "paused": {"tg101": {"tid": 1}}})
|
||||||
|
|
||||||
|
def test_mk_daemon_daily_pause_info_lazy_read(self):
|
||||||
|
now = int(time.time())
|
||||||
|
Path(self.state).write_text(json.dumps(
|
||||||
|
{"v": 2, "paused": {"tg101": {"tid": 7, "ts": now, "prev_status": 1}}}),
|
||||||
|
encoding="utf-8")
|
||||||
|
environ = {"IISHKO_ECON_STATE": self.state}
|
||||||
|
namespace, calls = _daemon_functions({"_state_path", "_read_pause_state", "_daily_pause_info"},
|
||||||
|
environ)
|
||||||
|
with closing(sqlite3.connect(":memory:")) as con:
|
||||||
|
info = namespace["_daily_pause_info"](
|
||||||
|
con, {"status": 2, "id": 7, "name": "tg101"}, {})
|
||||||
|
self.assertTrue(info.get("daily_paused"))
|
||||||
|
self.assertGreater(info["retry_at"], now)
|
||||||
|
self.assertTrue(calls, "_daily_pause_info must read the configured state file")
|
||||||
|
|
||||||
|
def test_mk_daemon_no_hardcoded_economy_paths(self):
|
||||||
|
source = (BOT / "webapp" / "mk_daemon.py").read_text(encoding="utf-8")
|
||||||
|
self.assertNotIn("/opt/grok-bot", source)
|
||||||
|
|
||||||
|
def test_consumers_have_no_hardcoded_economy_paths(self):
|
||||||
|
for relative in ("econ_cap.py", "account_admin.py"):
|
||||||
|
source = (BOT / relative).read_text(encoding="utf-8")
|
||||||
|
self.assertNotIn(DEFAULT_STATE, source, relative)
|
||||||
|
self.assertNotIn(DEFAULT_BOT_DB, source, relative)
|
||||||
|
self.assertNotIn(DEFAULT_GW_DB, source, relative)
|
||||||
|
|
||||||
|
|
||||||
|
class EntryAndNotificationPathsTests(unittest.TestCase):
|
||||||
|
def test_entry_admin_initializes_only_the_selected_alias_database(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
for alias in ("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"):
|
||||||
|
with self.subTest(alias=alias):
|
||||||
|
db = root / (alias + ".db")
|
||||||
|
with patch.dict(os.environ, {alias: str(db)}, clear=True):
|
||||||
|
module = _load("entry_admin.py")
|
||||||
|
self.assertEqual(module.BOT_DB, str(db))
|
||||||
|
module.init_db()
|
||||||
|
with closing(sqlite3.connect(db)) as con:
|
||||||
|
self.assertIsNotNone(con.execute(
|
||||||
|
"SELECT name FROM sqlite_master WHERE name='wa_entry_tags'").fetchone())
|
||||||
|
|
||||||
|
def test_entry_admin_binding_follows_the_effective_application_database(self):
|
||||||
|
for relative, module_name in (("grok_bot.py", "_entry_admin"),
|
||||||
|
("webapp/server.py", "entry_admin")):
|
||||||
|
with self.subTest(source=relative):
|
||||||
|
tree = ast.parse((BOT / relative).read_text(encoding="utf-8"))
|
||||||
|
bindings = [node for node in tree.body if isinstance(node, ast.Assign)
|
||||||
|
and any(isinstance(target, ast.Attribute)
|
||||||
|
and isinstance(target.value, ast.Name)
|
||||||
|
and target.value.id == module_name and target.attr == "BOT_DB"
|
||||||
|
for target in node.targets)]
|
||||||
|
self.assertEqual(len(bindings), 1)
|
||||||
|
self.assertEqual(ast.dump(bindings[0].value), ast.dump(ast.Name(id="BOT_DB", ctx=ast.Load())))
|
||||||
|
bot_db = _module_assignments(relative)["BOT_DB"]
|
||||||
|
self.assertEqual(ast.dump(bot_db), ast.dump(ast.parse('CFG["bot_db"]', mode="eval").body))
|
||||||
|
self.assertTrue(any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
|
||||||
|
and node.func.id == "effective_bot_config" for node in ast.walk(tree)))
|
||||||
|
|
||||||
|
def test_notification_cli_honours_config_env_and_explicit_paths_without_writing(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
config_db, env_db, explicit_db = (root / name for name in ("config.db", "env.db", "explicit.db"))
|
||||||
|
for db in (config_db, env_db, explicit_db):
|
||||||
|
with closing(sqlite3.connect(db)) as con:
|
||||||
|
con.execute("CREATE TABLE users(tg_id INTEGER,created INTEGER,privacy_ok INTEGER,banned INTEGER,lang TEXT)")
|
||||||
|
con.commit()
|
||||||
|
config = root / "config.json"
|
||||||
|
config.write_text(json.dumps({"bot_db": str(config_db), "key_wait_hours": 2}), encoding="utf-8-sig")
|
||||||
|
before = {db: db.read_bytes() for db in (config_db, env_db, explicit_db)}
|
||||||
|
base_env = {key: value for key, value in os.environ.items()
|
||||||
|
if not key.startswith(("IISHKO_", "GROK_", "GATE_"))}
|
||||||
|
scenarios = [
|
||||||
|
({"GATE_BOT_CONFIG": str(config)}, []),
|
||||||
|
({"GROK_BOT_CONFIG": str(config), "IISHKO_BOT_DB": str(env_db)}, []),
|
||||||
|
({"GROK_BOT_CFG": str(config), "GATE_BOT_DB": str(env_db)}, []),
|
||||||
|
({"GROK_BOT_CFG": str(config), "IISHKO_BOT_DB": str(root / "absent.db")},
|
||||||
|
["--bot-db", str(explicit_db)]),
|
||||||
|
]
|
||||||
|
for variables, args in scenarios:
|
||||||
|
with self.subTest(variables=sorted(variables), explicit=bool(args)):
|
||||||
|
configured_db = root / "config-should-not-be-opened.db" if any(
|
||||||
|
key.endswith("BOT_DB") for key in variables) else config_db
|
||||||
|
config.write_text(json.dumps({"bot_db": str(configured_db), "key_wait_hours": 2}),
|
||||||
|
encoding="utf-8-sig")
|
||||||
|
result = subprocess.run([sys.executable, str(BOT / "key_notifications.py"), "dry-run", *args],
|
||||||
|
cwd=root, env={**base_env, **variables}, capture_output=True,
|
||||||
|
text=True, encoding="utf-8", timeout=20)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(json.loads(result.stdout)["wait_seconds"], 7200)
|
||||||
|
self.assertFalse((root / "absent.db").exists())
|
||||||
|
self.assertFalse((root / "config-should-not-be-opened.db").exists())
|
||||||
|
self.assertFalse((root / "key_notifications.sqlite3").exists())
|
||||||
|
self.assertEqual({db: db.read_bytes() for db in before}, before)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,470 @@
|
|||||||
|
"""Startup smoke tests: every entrypoint is launched through ``scripts/run.py``.
|
||||||
|
|
||||||
|
Each test starts a real child interpreter with a scratch ``--env-file``; the
|
||||||
|
child bootstrap (a temporary ``sitecustomize``) forbids non-loopback network
|
||||||
|
access, and the bot child replaces the Telegram transport at the boundary with
|
||||||
|
one that only answers the calls a healthy startup needs. The bot test proves
|
||||||
|
that the real dispatcher reaches polling and that background workers were
|
||||||
|
registered and cancelled; the web app and gateway tests prove their listener
|
||||||
|
answers a request that touches neither SQLite business tables nor upstreams.
|
||||||
|
|
||||||
|
Nothing here starts production services: all writable paths (databases, icons,
|
||||||
|
key files, secret file, economy state) come from the generated env file, and
|
||||||
|
all listening ports are loopback ports reserved and released by the test.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import textwrap
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
LAUNCHER = ROOT / "scripts" / "run.py"
|
||||||
|
|
||||||
|
APP_ENV_PREFIXES = ("IISHKO_", "GROK_", "GATE_", "NEWAPI_", "TELEGRAM_", "TG_")
|
||||||
|
STRIPPED_ENV = frozenset(
|
||||||
|
{"PYTHONHOME", "PYTHONSTARTUP", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"})
|
||||||
|
|
||||||
|
STARTUP_TIMEOUT = 120.0
|
||||||
|
HTTP_TIMEOUT = 2.0
|
||||||
|
HTTP_POLL_INTERVAL = 0.2
|
||||||
|
|
||||||
|
# Defaults in bot/grok_bot.py, bot/runtime_config.py and gateway/grok-web-skin.py.
|
||||||
|
# A test that writes any of these has leaked a production path.
|
||||||
|
HARDCODED_STARTUP_PATHS = (
|
||||||
|
Path("C:/opt/grok-bot/bot.db"),
|
||||||
|
Path("C:/opt/grok-bot/icons.json"),
|
||||||
|
Path("C:/opt/grok-bot/econ_cap_state.json"),
|
||||||
|
Path("C:/opt/grok-gateway/new-api/one-api.db"),
|
||||||
|
Path("C:/opt/grok-web-skin-tg.db"),
|
||||||
|
Path("C:/root/.secrets/newapi_admin_token"),
|
||||||
|
Path("C:/root/iishko_audit.jsonl"),
|
||||||
|
)
|
||||||
|
|
||||||
|
CHILD_BOOTSTRAP = r'''
|
||||||
|
"""Temporary bootstrap injected via PYTHONPATH into every smoke child."""
|
||||||
|
import atexit
|
||||||
|
import inspect
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
|
||||||
|
_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain", "ip6-localhost"})
|
||||||
|
_STATE = {"methods": [], "polling": 0, "routers": 0, "workers_at_polling": 0, "tasks": []}
|
||||||
|
|
||||||
|
|
||||||
|
def _blocked(host):
|
||||||
|
if host is None or host == "" or host is False:
|
||||||
|
return False # bind on all interfaces / local resolution without a host
|
||||||
|
if isinstance(host, bytes):
|
||||||
|
host = host.decode("ascii", "replace")
|
||||||
|
host = str(host)
|
||||||
|
if host in _LOOPBACK_NAMES:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return not ipaddress.ip_address(host).is_loopback
|
||||||
|
except ValueError:
|
||||||
|
return True # a real DNS name; startup must not need it
|
||||||
|
|
||||||
|
|
||||||
|
def _guard(address):
|
||||||
|
if isinstance(address, str):
|
||||||
|
return # AF_UNIX path
|
||||||
|
if not isinstance(address, tuple) or not address:
|
||||||
|
raise PermissionError("SMOKE_NETGUARD: unsupported socket address %r" % (address,))
|
||||||
|
if _blocked(address[0]):
|
||||||
|
raise PermissionError("SMOKE_NETGUARD: blocked network address %r" % (address,))
|
||||||
|
|
||||||
|
|
||||||
|
def _install_netguard():
|
||||||
|
real_connect = socket.socket.connect
|
||||||
|
real_connect_ex = socket.socket.connect_ex
|
||||||
|
real_sendto = socket.socket.sendto
|
||||||
|
real_create_connection = socket.create_connection
|
||||||
|
real_getaddrinfo = socket.getaddrinfo
|
||||||
|
real_gethostbyname = socket.gethostbyname
|
||||||
|
real_gethostbyname_ex = socket.gethostbyname_ex
|
||||||
|
real_getnameinfo = socket.getnameinfo
|
||||||
|
|
||||||
|
def connect(self, address):
|
||||||
|
_guard(address)
|
||||||
|
return real_connect(self, address)
|
||||||
|
|
||||||
|
def connect_ex(self, address):
|
||||||
|
_guard(address)
|
||||||
|
return real_connect_ex(self, address)
|
||||||
|
|
||||||
|
def sendto(self, data, *args):
|
||||||
|
if args:
|
||||||
|
_guard(args[-1])
|
||||||
|
return real_sendto(self, data, *args)
|
||||||
|
|
||||||
|
def create_connection(address, *args, **kwargs):
|
||||||
|
_guard(address)
|
||||||
|
return real_create_connection(address, *args, **kwargs)
|
||||||
|
|
||||||
|
def getaddrinfo(host, port, *args, **kwargs):
|
||||||
|
if _blocked(host):
|
||||||
|
raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,))
|
||||||
|
return real_getaddrinfo(host, port, *args, **kwargs)
|
||||||
|
|
||||||
|
def gethostbyname(host):
|
||||||
|
if _blocked(host):
|
||||||
|
raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,))
|
||||||
|
return real_gethostbyname(host)
|
||||||
|
|
||||||
|
def gethostbyname_ex(host):
|
||||||
|
if _blocked(host):
|
||||||
|
raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,))
|
||||||
|
return real_gethostbyname_ex(host)
|
||||||
|
|
||||||
|
def getnameinfo(sockaddr, flags):
|
||||||
|
if isinstance(sockaddr, tuple) and sockaddr:
|
||||||
|
_guard(sockaddr)
|
||||||
|
return real_getnameinfo(sockaddr, flags)
|
||||||
|
|
||||||
|
socket.socket.connect = connect
|
||||||
|
socket.socket.connect_ex = connect_ex
|
||||||
|
socket.socket.sendto = sendto
|
||||||
|
socket.create_connection = create_connection
|
||||||
|
socket.getaddrinfo = getaddrinfo
|
||||||
|
socket.gethostbyname = gethostbyname
|
||||||
|
socket.gethostbyname_ex = gethostbyname_ex
|
||||||
|
socket.getnameinfo = getnameinfo
|
||||||
|
|
||||||
|
|
||||||
|
def _install_bot_fake():
|
||||||
|
from aiogram import Dispatcher
|
||||||
|
from aiogram.client.session.aiohttp import AiohttpSession
|
||||||
|
|
||||||
|
async def make_request(self, bot, method, timeout=None, **kwargs):
|
||||||
|
from aiogram.types import ChatMemberMember, User
|
||||||
|
|
||||||
|
name = type(method).__name__
|
||||||
|
_STATE["methods"].append(name)
|
||||||
|
if name == "GetMe":
|
||||||
|
return User(id=424242424, is_bot=True, first_name="Smoke", username="smoke_bot")
|
||||||
|
if name in ("DeleteWebhook", "SetMyCommands"):
|
||||||
|
return True
|
||||||
|
if name == "GetChatMember":
|
||||||
|
return ChatMemberMember(user=User(id=424242425, is_bot=False, first_name="Smoke"))
|
||||||
|
raise AssertionError("SMOKE_BOT_FAKE: unexpected Telegram method " + name)
|
||||||
|
|
||||||
|
async def start_polling(self, *args, **kwargs):
|
||||||
|
_STATE["polling"] += 1
|
||||||
|
_STATE["routers"] = len(getattr(self, "sub_routers", ()))
|
||||||
|
caller = inspect.currentframe().f_back
|
||||||
|
workers = (caller.f_globals.get("_BG_WORKERS") or {}) if caller is not None else {}
|
||||||
|
_STATE["workers_at_polling"] = len(workers)
|
||||||
|
_STATE["tasks"] = [task for task in workers.values() if task is not None]
|
||||||
|
raise SystemExit(0)
|
||||||
|
|
||||||
|
AiohttpSession.make_request = make_request
|
||||||
|
Dispatcher.start_polling = start_polling
|
||||||
|
|
||||||
|
|
||||||
|
def _dump():
|
||||||
|
path = os.environ.get("SMOKE_RESULT_FILE")
|
||||||
|
if not path:
|
||||||
|
return
|
||||||
|
payload = {
|
||||||
|
"polling": _STATE["polling"],
|
||||||
|
"routers": _STATE["routers"],
|
||||||
|
"workers_at_polling": _STATE["workers_at_polling"],
|
||||||
|
"tasks_pending": sum(1 for task in _STATE["tasks"] if not task.done()),
|
||||||
|
"methods": list(_STATE["methods"]),
|
||||||
|
}
|
||||||
|
database = os.environ.get("IISHKO_BOT_DB")
|
||||||
|
if database and os.path.isfile(database):
|
||||||
|
try:
|
||||||
|
connection = sqlite3.connect(database)
|
||||||
|
try:
|
||||||
|
payload["tables"] = connection.execute(
|
||||||
|
"SELECT count(*) FROM sqlite_master WHERE type='table'").fetchone()[0]
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
except sqlite3.Error as error:
|
||||||
|
payload["tables_error"] = type(error).__name__
|
||||||
|
with open(path, "w", encoding="utf-8") as sink:
|
||||||
|
json.dump(payload, sink)
|
||||||
|
|
||||||
|
|
||||||
|
if os.environ.get("SMOKE_NETGUARD") == "1":
|
||||||
|
_install_netguard()
|
||||||
|
|
||||||
|
if os.environ.get("SMOKE_FAKE_BOT") == "1":
|
||||||
|
_install_bot_fake()
|
||||||
|
|
||||||
|
atexit.register(_dump)
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_secret(seed: str) -> str:
|
||||||
|
return hashlib.sha256(("iishko-smoke:" + seed).encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _free_port() -> int:
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||||
|
sock.bind(("127.0.0.1", 0))
|
||||||
|
return sock.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
|
def _free_ports(count: int) -> list[int]:
|
||||||
|
ports: list[int] = []
|
||||||
|
while len(ports) < count:
|
||||||
|
port = _free_port()
|
||||||
|
if port not in ports:
|
||||||
|
ports.append(port)
|
||||||
|
return ports
|
||||||
|
|
||||||
|
|
||||||
|
def _write_json(path: Path, payload: object) -> None:
|
||||||
|
# utf-8-sig mirrors what operators hand-write on Windows; every entrypoint must accept it.
|
||||||
|
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8-sig")
|
||||||
|
|
||||||
|
|
||||||
|
def _create_sqlite(path: Path, statements: tuple[str, ...]) -> None:
|
||||||
|
connection = sqlite3.connect(path)
|
||||||
|
try:
|
||||||
|
for statement in statements:
|
||||||
|
connection.execute(statement)
|
||||||
|
connection.commit()
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _runtime(tmp_path: Path, target: str) -> dict:
|
||||||
|
"""Write every writable path into an env file; return the launch description."""
|
||||||
|
workdir = tmp_path / "runtime"
|
||||||
|
workdir.mkdir()
|
||||||
|
bootstrap = tmp_path / "bootstrap"
|
||||||
|
bootstrap.mkdir()
|
||||||
|
(bootstrap / "sitecustomize.py").write_text(textwrap.dedent(CHILD_BOOTSTRAP), encoding="utf-8")
|
||||||
|
|
||||||
|
paths = {
|
||||||
|
"config": workdir / "config.json",
|
||||||
|
"icons": workdir / "icons.json",
|
||||||
|
"bot_db": workdir / "bot.db",
|
||||||
|
"newapi_db": workdir / "newapi.db",
|
||||||
|
"skin_db": workdir / "skin.db",
|
||||||
|
"econ_state": workdir / "econ_cap_state.json",
|
||||||
|
"uptime_db": workdir / "uptime.db",
|
||||||
|
"support_db": workdir / "support.db",
|
||||||
|
"bot_source": workdir / "fake_bot_source.py",
|
||||||
|
"tg_secret": workdir / "tg_sid_secret",
|
||||||
|
"afkeys": workdir / "afkeys.json",
|
||||||
|
"kie_pool": workdir / "kie_pool.json",
|
||||||
|
"kie_dead": workdir / "kie_dead.json",
|
||||||
|
"pikeys": workdir / "pikeys.json",
|
||||||
|
"stdout": workdir / "child.stdout",
|
||||||
|
"stderr": workdir / "child.stderr",
|
||||||
|
"result": workdir / "result.json",
|
||||||
|
"env": workdir / "runtime.env",
|
||||||
|
}
|
||||||
|
ports = dict(zip(("webapp", "gateway", "upstream"), _free_ports(3)))
|
||||||
|
|
||||||
|
_write_json(paths["config"], {
|
||||||
|
"bot_token": "424242424:" + _fake_secret("bot-token"),
|
||||||
|
"main_key": "sk-" + _fake_secret("main-key"),
|
||||||
|
"channel_username": "@smoke_channel",
|
||||||
|
"newapi_pass": "np-" + _fake_secret("newapi-pass")[:32],
|
||||||
|
"newapi_db": paths["newapi_db"].as_posix(),
|
||||||
|
"newapi_url": "http://127.0.0.1:%d" % ports["upstream"],
|
||||||
|
})
|
||||||
|
_write_json(paths["icons"], {})
|
||||||
|
paths["bot_source"].write_text(
|
||||||
|
"TIER_MODELS = {1: ['smoke-model'], 2: ['smoke-model'], 3: ['smoke-model']}\n"
|
||||||
|
"MODEL_DESCS = {'smoke-model': 'smoke'}\n"
|
||||||
|
"TIER_TITLES = {1: 'Smoke', 2: 'Smoke', 3: 'Smoke'}\n"
|
||||||
|
"MEDIA_MODELS = {}\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
paths["tg_secret"].write_bytes(bytes.fromhex(_fake_secret("tg-sid")))
|
||||||
|
|
||||||
|
_create_sqlite(paths["newapi_db"], (
|
||||||
|
"CREATE TABLE tokens (id INTEGER PRIMARY KEY, name TEXT, status INTEGER)",
|
||||||
|
))
|
||||||
|
if target == "gateway":
|
||||||
|
# gate_boot_selfcheck() counts rows over these columns.
|
||||||
|
_create_sqlite(paths["bot_db"], (
|
||||||
|
"CREATE TABLE users (tg_id INTEGER PRIMARY KEY, api_blocked INTEGER, "
|
||||||
|
"api_block_reason TEXT, banned INTEGER)",
|
||||||
|
))
|
||||||
|
|
||||||
|
values = {
|
||||||
|
"GROK_BOT_CFG": paths["config"].as_posix(),
|
||||||
|
"IISHKO_BOT_DB": paths["bot_db"].as_posix(),
|
||||||
|
"IISHKO_GW_DB": paths["newapi_db"].as_posix(),
|
||||||
|
"IISHKO_SKIN_DB": paths["skin_db"].as_posix(),
|
||||||
|
"IISHKO_ECON_STATE": paths["econ_state"].as_posix(),
|
||||||
|
"GROK_UPTIME_DB": paths["uptime_db"].as_posix(),
|
||||||
|
"GROK_SUPPORT_DB": paths["support_db"].as_posix(),
|
||||||
|
"IISHKO_BOT_SOURCE": paths["bot_source"].as_posix(),
|
||||||
|
"TG_SID_SECRET_FILE": paths["tg_secret"].as_posix(),
|
||||||
|
"GROK_ICONS": paths["icons"].as_posix(),
|
||||||
|
"AFKEYS": paths["afkeys"].as_posix(),
|
||||||
|
"KIE_POOL": paths["kie_pool"].as_posix(),
|
||||||
|
"KIE_DEAD": paths["kie_dead"].as_posix(),
|
||||||
|
"PIKEYS": paths["pikeys"].as_posix(),
|
||||||
|
"GW_NEWAPI_DB": paths["newapi_db"].as_posix(),
|
||||||
|
"IISHKO_UPSTREAM": "http://127.0.0.1:%d" % ports["upstream"],
|
||||||
|
"IISHKO_WEBAPP_HOST": "127.0.0.1",
|
||||||
|
"IISHKO_WEBAPP_PORT": str(ports["webapp"]),
|
||||||
|
"IISHKO_GATEWAY_HOST": "127.0.0.1",
|
||||||
|
"IISHKO_GATEWAY_PORT": str(ports["gateway"]),
|
||||||
|
"GROK_BOT_ALLOW_LOCAL": "1",
|
||||||
|
"IISHKO_NOTIFICATIONS_ENABLED": "0",
|
||||||
|
"IISHKO_SUPPORT_DELIVERY_ENABLED": "0",
|
||||||
|
"IISHKO_ENTRY_DELIVERY_ENABLED": "0",
|
||||||
|
}
|
||||||
|
paths["env"].write_text(
|
||||||
|
"".join("%s=%s\n" % item for item in values.items()), encoding="utf-8")
|
||||||
|
return {"target": target, "tmp": tmp_path, "bootstrap": bootstrap,
|
||||||
|
"paths": paths, "ports": ports}
|
||||||
|
|
||||||
|
|
||||||
|
def _child_env(runtime: dict, fake_bot: bool) -> dict[str, str]:
|
||||||
|
env = {
|
||||||
|
key: value for key, value in os.environ.items()
|
||||||
|
if not key.upper().startswith(APP_ENV_PREFIXES) and key.upper() not in STRIPPED_ENV
|
||||||
|
}
|
||||||
|
env.update({
|
||||||
|
"TMP": str(runtime["tmp"]),
|
||||||
|
"TEMP": str(runtime["tmp"]),
|
||||||
|
"PYTHONPATH": str(runtime["bootstrap"]),
|
||||||
|
"PYTHONDONTWRITEBYTECODE": "1",
|
||||||
|
"PYTHONIOENCODING": "utf-8",
|
||||||
|
"SMOKE_NETGUARD": "1",
|
||||||
|
"SMOKE_FAKE_BOT": "1" if fake_bot else "0",
|
||||||
|
"SMOKE_RESULT_FILE": str(runtime["paths"]["result"]),
|
||||||
|
})
|
||||||
|
return env
|
||||||
|
|
||||||
|
|
||||||
|
def _spawn(runtime: dict, fake_bot: bool = False) -> subprocess.Popen:
|
||||||
|
paths = runtime["paths"]
|
||||||
|
with open(paths["stdout"], "wb") as out, open(paths["stderr"], "wb") as err:
|
||||||
|
process = subprocess.Popen(
|
||||||
|
[sys.executable, str(LAUNCHER), runtime["target"],
|
||||||
|
"--env-file", str(paths["env"])],
|
||||||
|
cwd=str(ROOT), env=_child_env(runtime, fake_bot),
|
||||||
|
stdin=subprocess.DEVNULL, stdout=out, stderr=err,
|
||||||
|
)
|
||||||
|
return process
|
||||||
|
|
||||||
|
|
||||||
|
def _tail(path: Path) -> str:
|
||||||
|
try:
|
||||||
|
return path.read_text(encoding="utf-8", errors="replace")[-4000:]
|
||||||
|
except OSError:
|
||||||
|
return "<no output>"
|
||||||
|
|
||||||
|
|
||||||
|
def _failure(summary: str, process: subprocess.Popen, runtime: dict) -> str:
|
||||||
|
paths = runtime["paths"]
|
||||||
|
return "%s\nreturncode=%r\nstdout:\n%s\nstderr:\n%s" % (
|
||||||
|
summary, process.returncode, _tail(paths["stdout"]), _tail(paths["stderr"]))
|
||||||
|
|
||||||
|
|
||||||
|
def _terminate(process: subprocess.Popen) -> None:
|
||||||
|
if process.poll() is None:
|
||||||
|
process.terminate()
|
||||||
|
try:
|
||||||
|
process.wait(timeout=20)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
process.kill()
|
||||||
|
process.wait(timeout=20)
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_http(process: subprocess.Popen, url: str, runtime: dict) -> tuple[int, str]:
|
||||||
|
parts = urllib.parse.urlsplit(url)
|
||||||
|
if parts.scheme != "http" or parts.hostname not in ("127.0.0.1", "::1"):
|
||||||
|
raise AssertionError("smoke requests must stay on loopback: " + url)
|
||||||
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||||
|
deadline = time.monotonic() + STARTUP_TIMEOUT
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if process.poll() is not None:
|
||||||
|
raise AssertionError(_failure("process exited before serving " + url, process, runtime))
|
||||||
|
try:
|
||||||
|
with opener.open(url, timeout=HTTP_TIMEOUT) as response:
|
||||||
|
return response.status, response.read().decode("utf-8", "replace")
|
||||||
|
except (urllib.error.URLError, OSError):
|
||||||
|
time.sleep(HTTP_POLL_INTERVAL)
|
||||||
|
raise AssertionError(_failure("no HTTP response from " + url, process, runtime))
|
||||||
|
|
||||||
|
|
||||||
|
def _hardcoded_paths_seen() -> set[str]:
|
||||||
|
return {str(path) for path in HARDCODED_STARTUP_PATHS if path.exists()}
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_no_new_hardcoded_paths(before: set[str], runtime: dict) -> None:
|
||||||
|
created = _hardcoded_paths_seen() - before
|
||||||
|
assert not created, "startup wrote hardcoded operator paths: %s" % sorted(created)
|
||||||
|
|
||||||
|
|
||||||
|
def test_bot_reaches_polling_through_launcher(tmp_path):
|
||||||
|
runtime = _runtime(tmp_path, "bot")
|
||||||
|
before = _hardcoded_paths_seen()
|
||||||
|
process = _spawn(runtime, fake_bot=True)
|
||||||
|
try:
|
||||||
|
returncode = process.wait(timeout=STARTUP_TIMEOUT)
|
||||||
|
finally:
|
||||||
|
_terminate(process)
|
||||||
|
assert returncode == 0, _failure("bot child failed", process, runtime)
|
||||||
|
|
||||||
|
result = json.loads((runtime["paths"]["result"]).read_text(encoding="utf-8"))
|
||||||
|
assert result["polling"] == 1, result
|
||||||
|
assert result["routers"] >= 1, result
|
||||||
|
assert result["workers_at_polling"] >= 1, result
|
||||||
|
assert result["tasks_pending"] == 0, result
|
||||||
|
assert result.get("tables", 0) >= 5, result
|
||||||
|
|
||||||
|
methods = result["methods"]
|
||||||
|
assert "GetMe" in methods, methods
|
||||||
|
assert "GetUpdates" not in methods, methods
|
||||||
|
assert set(methods) <= {"GetMe", "DeleteWebhook", "SetMyCommands", "GetChatMember"}, methods
|
||||||
|
# The database exists only at the path handed over by --env-file.
|
||||||
|
assert runtime["paths"]["bot_db"].is_file()
|
||||||
|
_assert_no_new_hardcoded_paths(before, runtime)
|
||||||
|
|
||||||
|
|
||||||
|
def test_miniapp_serves_healthz_through_launcher(tmp_path):
|
||||||
|
runtime = _runtime(tmp_path, "miniapp")
|
||||||
|
before = _hardcoded_paths_seen()
|
||||||
|
process = _spawn(runtime)
|
||||||
|
try:
|
||||||
|
url = "http://127.0.0.1:%d/healthz" % runtime["ports"]["webapp"]
|
||||||
|
status, body = _wait_http(process, url, runtime)
|
||||||
|
assert status == 200 and "ok" in body, (status, body)
|
||||||
|
assert process.poll() is None, _failure("webapp exited after serving", process, runtime)
|
||||||
|
finally:
|
||||||
|
_terminate(process)
|
||||||
|
_assert_no_new_hardcoded_paths(before, runtime)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_serves_robots_through_launcher(tmp_path):
|
||||||
|
runtime = _runtime(tmp_path, "gateway")
|
||||||
|
before = _hardcoded_paths_seen()
|
||||||
|
process = _spawn(runtime)
|
||||||
|
try:
|
||||||
|
url = "http://127.0.0.1:%d/robots.txt" % runtime["ports"]["gateway"]
|
||||||
|
status, body = _wait_http(process, url, runtime)
|
||||||
|
assert status == 200, (status, body)
|
||||||
|
assert "User-agent: *" in body and "Sitemap:" in body, body
|
||||||
|
assert process.poll() is None, _failure("gateway exited after serving", process, runtime)
|
||||||
|
finally:
|
||||||
|
_terminate(process)
|
||||||
|
_assert_no_new_hardcoded_paths(before, runtime)
|
||||||
Reference in New Issue
Block a user