Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1bddb08
Add conservative Telemt WEB manager and strict topology validation
xPROMSx Sep 30, 2026
09865c4
Add fixture safety tests and Ubuntu CI checks
xPROMSx Sep 30, 2026
dce3d0f
Harden runtime validation and exercise complete install orchestration
xPROMSx Sep 30, 2026
2470bbb
Document upstream findings, operator workflow and recovery boundaries
xPROMSx Sep 30, 2026
869a346
Verify real Nginx transport and preserve complete recovery snapshots
xPROMSx Sep 30, 2026
e5cc6cd
Enforce managed file permissions and test download trust boundaries
xPROMSx Sep 30, 2026
fb88afc
Reject conflicting reinstall requests and clarify test stub quoting
xPROMSx Sep 30, 2026
e90598f
Recognize reviewed 3x-ui-pro topology and test complete upstream configs
xPROMSx Sep 30, 2026
51fe8e9
Isolate inherited HTTP access logs in real Nginx topology tests
xPROMSx Sep 30, 2026
c58621f
Document verified 3x-ui-pro compatibility and strict topology boundaries
xPROMSx Sep 30, 2026
c0134a3
Harden runtime state and locking; add transactional Nginx webroot iss…
xPROMSx Sep 30, 2026
32d23eb
Make ACME staging scope and failure branches explicit
xPROMSx Sep 30, 2026
b7e3aff
Keep ACME staging private through a scoped transaction wrapper
xPROMSx Sep 30, 2026
1911095
Constrain stream upstreams and keep locking tests on sandbox paths
xPROMSx Sep 30, 2026
e253936
Reject port 80 runtime drift and verify signal rollback during ACME i…
xPROMSx Sep 30, 2026
e87dc1b
Exercise strict signal handling and additional archive/release refusa…
xPROMSx Sep 30, 2026
f33e119
Exercise ACME issuance through the complete 3x-ui-pro installation flow
xPROMSx Sep 30, 2026
011df48
Document audited runtime and ACME contracts in complete English and R…
xPROMSx Sep 30, 2026
093b37b
Harden managed WEB contracts and recover safely after partial ACME su…
xPROMSx Oct 1, 2026
b530fb1
Make English and Russian front pages installation focused
xPROMSx Oct 1, 2026
9345d7d
Run CI on main and verify Noble nf_tables diagnostics in an isolated …
xPROMSx Oct 1, 2026
9112def
Validate certificate renewal sockets, canonical deploy hook and sched…
xPROMSx Oct 1, 2026
1be047a
Document renewal health refusals and warning-only scheduler diagnostics
xPROMSx Oct 1, 2026
73b51ed
Parse MIME records as data and validate Telemt compatibility without …
xPROMSx Oct 1, 2026
f08d9c3
Document live MIME coverage gap and contract-based release evaluation
xPROMSx Oct 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
* text=auto eol=lf
*.sh text eol=lf
40 changes: 40 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: checks
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
safety:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install test tools
run: sudo apt-get update && sudo apt-get install -y shellcheck jq nginx libnginx-mod-stream iptables
- name: Bash syntax
run: for file in telemt-web-manager.sh tests/*.sh; do bash -n "$file"; done
- name: ShellCheck
run: shellcheck -x telemt-web-manager.sh tests/*.sh
- name: Unit and fixture tests (no root, no production access)
run: bash tests/run.sh && bash tests/fresh.sh && bash tests/download.sh
- name: Published Telemt configuration contract (SHA256 verified)
run: bash tests/upstream.sh
- name: Version-independent compatibility, downgrade and rollback regressions
run: bash tests/versions.sh && FIXTURE_VERSION=42.7.123 bash tests/fresh.sh && FIXTURE_VERSION=42.7.123 FIXTURE_INCOMPATIBLE=1 bash tests/fresh.sh
- name: Actual Ubuntu nf_tables missing-chain diagnostic (isolated namespace)
run: bash tests/conntrack.sh
- name: Writable state and systemd contract
run: bash tests/contracts.sh
- name: Shared check lock and exclusive mutation races
run: bash tests/locks.sh
- name: Certbot and Nginx webroot transactions
run: bash tests/acme.sh
- name: Renewal socket, deploy hook and scheduler contracts (temporary root-owned fixtures)
run: sudo bash tests/renewal.sh
- name: Real Nginx stream and TLS fixture
run: bash tests/nginx.sh
- name: Current reviewed 3x-ui-pro installer and patcher topologies
run: bash tests/three-x-ui.sh
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
__pycache__/
*.pyc
155 changes: 154 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,154 @@
# telemt-web-manager
# Telemt WEB Manager

English | [Русский](README.ru.md)

A conservative Bash manager for [Telemt WEB Proxy](https://github.com/telemt/telemt)
behind an existing Nginx SNI router. Install, update, check and repair deployments
with direct or optional SOCKS5 egress. For Ubuntu VPS hosts already sharing HTTPS
port 443 through Nginx `stream` / `ssl_preread`.

## Features

- Interactive menu and non-interactive commands.
- Recognized Nginx integration with existing routes preserved.
- Official release SHA256 verification and configuration validation.
- Health checks, bounded startup readiness and automatic transaction rollback.
- Hardened systemd service; existing TOML preserved during updates.

## Installation

Run in a **root shell**, initially on a disposable test VPS.
Prerequisites: Ubuntu 24.04/26.04, systemd, Bash 5+, Python 3.11+, an active
recognized Nginx router and SSL, HTTP/2, realip, stream/ssl_preread modules.
Install command dependencies without replacing your working Nginx:

```bash
apt-get update
apt-get install git shellcheck bash python3 curl ca-certificates tar openssl jq \
dnsutils util-linux iproute2 coreutils passwd certbot iptables nftables
```

Obtain and inspect the source, validate it and install both files:

```bash
git clone https://github.com/xPROMSx/telemt-web-manager.git
cd telemt-web-manager

bash -n telemt-web-manager.sh
shellcheck telemt-web-manager.sh

install -d -m 0755 /opt/telemt-web-manager/lib
install -m 0755 telemt-web-manager.sh /opt/telemt-web-manager/
install -m 0644 lib/safety.py /opt/telemt-web-manager/lib/
```

Keep `/opt/telemt-web-manager` root-owned and unwritable by others.
On a clean Nginx package, stream usually requires `libnginx-mod-stream`;
match modules to your installed Nginx and verify `nginx -t`.
The manager checks dependencies; it does not install packages or run `curl | bash`.

## First run

Start the interactive menu:

```bash
/opt/telemt-web-manager/telemt-web-manager.sh
```

Choose Install and supply your WEB domain, public IPv4 and optional SOCKS5 address.
DNS must contain exactly one matching A record, with no CNAME or AAAA.
Ports `127.0.0.1:7444` and `127.0.0.1:18080` must be free.
For a new certificate the menu asks for an ACME email and agreement consent.

The private Telegram link is saved in
`/var/lib/telemt-web-manager/web-link.txt` (0600). Telemt also logs links to journald.
Treat the link, config, journals and backups as secrets.

## Common examples

Replace the example domain and TEST-NET address with your own values.

Direct egress:

```bash
/opt/telemt-web-manager/telemt-web-manager.sh --install \
--domain proxy.example.com \
--public-ip 203.0.113.10
```

SOCKS5 egress:

```bash
/opt/telemt-web-manager/telemt-web-manager.sh --install \
--domain proxy.example.com \
--public-ip 203.0.113.10 \
--socks 127.0.0.1:1080
```

For new non-interactive certificate issuance, append
`--email operator@example.com --agree-tos` after reviewing the ACME subscriber
agreement. An unrelated existing certificate is not automatically adopted.

## Update, check and repair

```bash
/opt/telemt-web-manager/telemt-web-manager.sh --update
/opt/telemt-web-manager/telemt-web-manager.sh --check
/opt/telemt-web-manager/telemt-web-manager.sh --repair
```

`--update` updates the audited **Telemt binary**, with validation and rollback;
it does not update the manager or rewrite TOML.
`--check` validates managed files, configuration, renewal state and service health.
`--repair` restarts/reloads only verified managed services, without reconstructing
changed files. To update the manager, review a newer checkout and repeat the
validation/copy steps above.

## Intended environment

Ubuntu 24.04/26.04 on x86_64 or aarch64, with one recognized Nginx SNI map/router,
IPv4 `:443`, optional existing `[::]:443`, outgoing PROXY protocol and an HTTP
`conf.d/*.conf` include. The manager adds a loopback TLS frontend and an IPv4-only
Telemt WEB listener. Telegram egress is direct or unauthenticated SOCKS5.
Source-audited baseline: **3.5.9**; official 3.5.7/3.5.9 configuration tests are retained.
Stable releases are evaluated against explicit configuration/runtime health contracts;
incompatible candidates are refused or rolled back, without a version-number gate.

HTTP-01 uses standalone on free port 80, or a persistent managed webroot when
port 80 belongs to the recognized Nginx redirect topology. Nginx is never stopped.
Verify external port 80/443 reachability and certificate renewal yourself.
Standalone renewal requires port 80 to remain free; `--check` fails on a conflict
and verifies the manager's deploy hook. No known Certbot timer produces a warning
to verify cron/custom scheduling manually.

## Tested 3x-ui-pro compatibility

Telemt WEB Manager is tested against the Nginx `stream` / `ssl_preread` topology
generated by [mozaroc/3x-ui-pro](https://github.com/mozaroc/3x-ui-pro) at revision
`a2c430cd6dec7c86d873dcda3544a61e7ac41144`, using both installer and patcher fixtures.
This is not an official integration. Arbitrary custom or future configurations
are not automatically supported. Xray and 3x-ui configuration/database are not modified.

CI uses the verified official Telemt binary and real Nginx traffic tests.
Systemd and Certbot lifecycle operations use mocks. Live VPS acceptance is still required.

## Important limitations

- Unknown Nginx topology, changed managed contracts and unaudited versions fail closed.
- Unrelated existing Telemt installations and certificates require manual review.
- No firewall/UFW changes, automatic TOML migrations or automatic uninstall.
- WEB AAAA, authenticated/IPv6 SOCKS and custom HTTP-80 routing require manual review.
- A certificate can survive failed issuance post-validation. Retry refuses missing
managed renewal state; see the recovery guide. Never blindly delete Certbot assets.
- SIGINT/TERM/HUP trigger transactional rollback. Power loss, SIGKILL, disk failure
and concurrent root edits remain manual recovery boundaries.

## Technical documentation

- [Upstream audit and version/configuration contracts](docs/UPSTREAM.md).
- [Architecture, security, ACME recovery, tests and operations](docs/OPERATIONS.md).

## License and independence

[MIT License](LICENSE). Independent project, not affiliated with, endorsed by,
or part of Telemt, 3x-ui or 3x-ui-pro.
159 changes: 159 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# Telemt WEB Manager

[English](README.md) | Русский

Консервативный Bash-менеджер для [Telemt WEB Proxy](https://github.com/telemt/telemt)
за существующим SNI-маршрутизатором Nginx. Установка, обновление, проверка
и восстановление с прямым выходом или через SOCKS5. Для Ubuntu VPS, где HTTPS-порт
443 уже распределяется между сервисами через Nginx `stream` / `ssl_preread`.

## Возможности

- Интерактивное меню и команды для запуска без диалога.
- Интеграция в распознанную схему Nginx с сохранением существующих маршрутов.
- Проверка официального SHA256 релиза и проверка конфигурации.
- Контроль работоспособности, ограниченное ожидание запуска и автоматический откат.
- Защищённый systemd-сервис; сохранение существующего TOML при обновлении.

## Установка

Выполняй в **root-консоли**, сначала на отдельном тестовом VPS.
Требования: Ubuntu 24.04/26.04, systemd, Bash 5+, Python 3.11+, работающий
распознаваемый маршрутизатор Nginx и модули SSL, HTTP/2, realip, stream/ssl_preread.
Установи зависимости команд, сохранив свою рабочую сборку Nginx:

```bash
apt-get update
apt-get install git shellcheck bash python3 curl ca-certificates tar openssl jq \
dnsutils util-linux iproute2 coreutils passwd certbot iptables nftables
```

Загрузи и изучи исходники, выполни проверки и установи оба файла:

```bash
git clone https://github.com/xPROMSx/telemt-web-manager.git
cd telemt-web-manager

bash -n telemt-web-manager.sh
shellcheck telemt-web-manager.sh

install -d -m 0755 /opt/telemt-web-manager/lib
install -m 0755 telemt-web-manager.sh /opt/telemt-web-manager/
install -m 0644 lib/safety.py /opt/telemt-web-manager/lib/
```

Каталог `/opt/telemt-web-manager` должен принадлежать root и быть недоступным
для записи другим пользователям. В стандартной пакетной установке Nginx для stream
обычно нужен `libnginx-mod-stream`; согласуй модули со своей сборкой и проверь
`nginx -t`. Менеджер проверяет зависимости, сам пакеты не устанавливает.
Запуск через `curl | bash` не используется.

## Первый запуск

Открой интерактивное меню:

```bash
/opt/telemt-web-manager/telemt-web-manager.sh
```

Выбери Install, укажи WEB-домен, публичный IPv4 и при необходимости адрес SOCKS5.
В DNS нужна ровно одна совпадающая A-запись, без CNAME и AAAA.
Порты `127.0.0.1:7444` и `127.0.0.1:18080` должны быть свободны.
Для нового сертификата меню запросит email ACME и согласие с условиями.

Приватная ссылка Telegram сохраняется в
`/var/lib/telemt-web-manager/web-link.txt` с правами 0600. Telemt также пишет
ссылки в journald. Ссылка, конфиг, журналы и резервные копии содержат секреты.

## Примеры

Замени домен example.com и адрес TEST-NET своими значениями.

Прямой выход:

```bash
/opt/telemt-web-manager/telemt-web-manager.sh --install \
--domain proxy.example.com \
--public-ip 203.0.113.10
```

Выход через SOCKS5:

```bash
/opt/telemt-web-manager/telemt-web-manager.sh --install \
--domain proxy.example.com \
--public-ip 203.0.113.10 \
--socks 127.0.0.1:1080
```

Для выпуска нового сертификата без диалога добавь
`--email operator@example.com --agree-tos`, предварительно прочитав соглашение ACME.
Существующий посторонний сертификат автоматически не принимается под управление.

## Обновление, проверка и восстановление

```bash
/opt/telemt-web-manager/telemt-web-manager.sh --update
/opt/telemt-web-manager/telemt-web-manager.sh --check
/opt/telemt-web-manager/telemt-web-manager.sh --repair
```

`--update` обновляет исследованный **бинарник Telemt**, проверяя кандидата
и выполняя откат при ошибке. Сам менеджер и TOML эта команда не обновляет.
`--check` проверяет управляемые файлы, конфигурацию, состояние продления сертификата
и работоспособность сервисов.
`--repair` перезапускает только проверенный Telemt и перечитывает проверенный Nginx;
повреждённые файлы не воссоздаёт. Для обновления самого менеджера изучи новую
версию репозитория и повтори проверки и копирование файлов из раздела установки.

## Для какого окружения

Ubuntu 24.04/26.04, x86_64 или aarch64, один распознаваемый SNI map/router Nginx,
IPv4 `:443`, необязательный существующий `[::]:443`, исходящий PROXY protocol
и HTTP include `conf.d/*.conf`. Менеджер добавляет локальный TLS frontend
и IPv4 WEB listener Telemt. Выход к Telegram прямой или через SOCKS5 без авторизации.
Исходники проверены на базе Telemt **3.5.9**, CI сохраняет проверки 3.5.7/3.5.9.
Стабильные релизы проверяются по контрактам конфигурации и здоровья runtime,
без ограничения номера версии. Несовместимые кандидаты отклоняются или откатываются.

HTTP-01 использует standalone на свободном порту 80 либо постоянный webroot,
когда порт 80 обслуживает распознанная схема redirect-vhost Nginx.
Nginx не останавливается. Внешнюю доступность 80/443 и продление сертификата
нужно проверить самостоятельно.
Для standalone порт 80 должен оставаться свободным: `--check` завершается ошибкой
при конфликте и проверяет deploy hook менеджера. Если известный таймер Certbot
не найден, выводится предупреждение проверить cron/своё расписание вручную.

## Проверенная совместимость с 3x-ui-pro

Telemt WEB Manager проверяется на схеме Nginx `stream` / `ssl_preread`,
которую создаёт [mozaroc/3x-ui-pro](https://github.com/mozaroc/3x-ui-pro)
на ревизии `a2c430cd6dec7c86d873dcda3544a61e7ac41144`: используются конфигурации
установщика и патчера. Это не официальная интеграция. Произвольные, изменённые
и будущие конфигурации автоматически не поддерживаются.
Конфигурация Xray, настройки и база данных 3x-ui не изменяются.

CI использует проверенный официальный бинарник Telemt и настоящий Nginx.
Операции systemd и Certbot проверяются с имитацией. Проверка на тестовом VPS ещё требуется.

## Важные ограничения

- Неизвестная схема Nginx, изменённый управляемый контракт и неисследованная версия вызывают отказ.
- Посторонние установки Telemt и сертификаты требуют ручной проверки.
- Нет изменений firewall/UFW, автоматической миграции TOML и автоматического удаления.
- AAAA для WEB-домена, SOCKS с авторизацией/IPv6 и нестандартный HTTP на порту 80 требуют проверки.
- Сертификат может сохраниться после ошибки проверки выпуска. Повторный запуск
откажет при неполном состоянии продления. Не удаляй объекты Certbot вслепую.
- SIGINT/TERM/HUP запускают откат транзакции. Отключение питания, SIGKILL, сбой диска
и параллельное редактирование root требуют ручного восстановления.

## Техническая документация

- [Исследование upstream, версии и контракты конфигурации](docs/UPSTREAM.md).
- [Архитектура, безопасность, восстановление ACME, тесты и эксплуатация](docs/OPERATIONS.md)
(на английском).

## Лицензия и независимость

[Лицензия MIT](LICENSE). Независимый проект, не связанный официально с Telemt,
3x-ui или 3x-ui-pro и не одобренный их разработчиками.
Loading