19 Commits

Author SHA1 Message Date
DenPiligrim a28d7a6954 Merge pull request #58 from denpiligrim/dp-fix
fix: bd sync
2026-06-08 23:35:25 +03:00
Den Piligrim 009506f915 fix: bd sync 2026-06-08 23:31:17 +03:00
DenPiligrim e84d77f248 Merge pull request #57 from denpiligrim/dp-fix
fix: insecure hy2
2026-06-08 22:48:26 +03:00
Den Piligrim f52e035d8a fix: insecure hy2 2026-06-08 22:47:25 +03:00
DenPiligrim 927a04f24a Merge pull request #55 from denpiligrim/dp-fix
...
2026-06-03 00:08:55 +03:00
Den Piligrim 600b398a5a ...
Co-Authored-By: Codex <267193182+codex@users.noreply.github.com>
2026-06-03 00:08:08 +03:00
DenPiligrim 73c9adf42a Merge pull request #48 from denpiligrim/dp-new-release
v2.2.0
2026-05-22 00:01:06 +03:00
Den Piligrim 2c1d7f3ec6 tag 2026-05-21 23:55:39 +03:00
Den Piligrim 1077f11fc7 fix creds 2026-05-21 23:33:30 +03:00
Den Piligrim c7e2afa631 fix uninstall 2026-05-21 23:19:13 +03:00
Den Piligrim 66defd5b20 fix postgres 2026-05-21 23:06:53 +03:00
Den Piligrim 26f3bb2934 v2.2.0 2026-05-21 22:58:29 +03:00
Den Piligrim 962544820f client reafactor 2026-05-18 15:52:15 +03:00
Den Piligrim 5629b43cd0 add: nodes 2026-05-18 15:50:36 +03:00
Den Piligrim 9bf4d34317 fix: deployment 2026-05-17 11:14:04 +03:00
DenPiligrim 5e4b265415 Merge pull request #45 from denpiligrim/fix/postgres-volume-mapping-5564566905280484491
Update PostgreSQL volume mapping to /var/lib/postgresql
2026-04-23 10:12:08 +03:00
google-labs-jules[bot] 84a64c248e Change PostgreSQL volume mapping in install.sh and docker-compose.yml
Updated the pg_data volume mount point from /var/lib/postgresql/data to /var/lib/postgresql to match the user's request for both the installer script and the default docker-compose configuration.

Co-authored-by: denpiligrim <89912505+denpiligrim@users.noreply.github.com>
2026-04-23 07:11:24 +00:00
DenPiligrim bcd819546b Merge pull request #42 from denpiligrim/dp-fix
fix forwarding command
2026-04-14 15:46:00 +03:00
Den Piligrim 33275e6588 fix forwarding command 2026-04-14 15:45:25 +03:00
64 changed files with 4840 additions and 1746 deletions
+3
View File
@@ -3,6 +3,9 @@ name: Docker Build & Publish
on:
push:
branches: [ "main" ]
paths:
- 'client/**'
- 'server/**'
workflow_dispatch:
env:
+1
View File
@@ -1,3 +1,4 @@
checker/
client/.env
client/coverage/
backups/
+108 -27
View File
@@ -2,16 +2,16 @@
<p><img src="https://denpiligrim.ru/storage/images/3dp-manager.png" alt="3dp-manager preview"></p>
![Version](https://img.shields.io/badge/version-2.1.0-blue.svg) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
![Version](https://img.shields.io/badge/version-2.2.0-blue.svg) ![Downloads](https://img.shields.io/badge/downloads-5.6k-blue) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
# 3DP-MANAGER
Утилита для автогенерации инбаундов к панели [3x-ui](https://github.com/MHSanaei/3x-ui), формирования единой подписки и настройки перенаправления трафика с промежуточного сервера на основной. Утилита, начиная с версии 2.0.0 имеет графический интерфейс и простые пользовательские настройки.
Утилита для автогенерации инбаундов к панели [3x-ui](https://github.com/MHSanaei/3x-ui), формирования единых подписок, управления несколькими 3x-ui нодами и настройки relay-перенаправления трафика с промежуточных серверов на основные. Начиная с версии 2.0.0 проект имеет графический интерфейс и простые пользовательские настройки.
**Поддержать проект**
- Банковским переводом:
- :credit_card: Карта МИР: `2204320436318077`
- :credit_card: Карта МИР: [finance.ozon.ru](https://finance.ozon.ru/apps/sbp/ozonbankpay/019e46e5-c08d-734a-a056-6b340969760d)
- :credit_card: Карта MasterCard: `5395452209474530`
- На электронный кошелек:
- :moneybag: ЮМоney: `4100116897060652`
@@ -25,18 +25,19 @@
## Описание
Главная цель утилиты — сделать так, чтобы ваш трафик не выглядел одинаковым. Бот генерирует по заданному интервалу 10 подключений с разными параметрами:
Главная цель утилиты — сделать так, чтобы ваш трафик не выглядел одинаковым. 3DP-MANAGER генерирует по заданному интервалу набор подключений с разными параметрами:
- протоколы: `vless`, `vmess`, `shadowsocks`, `hysteria2`, `trojan`;
- порты: `443`, `8443` (фиксированные) и случайные из диапазона `10000-60000`;
- транспорт: `tcp`, `websocket`, `grpc`, `xhttp`;
- SNI берутся из белого списка доменов (whitelist); можно использовать свой список.
- SNI берутся из белого списка доменов (whitelist) или задаются вручную;
- нода, relay-сервер, порт и флаг могут настраиваться отдельно для каждого инбаунда.
Все подключения объединяются в одну подписку со статичным URL. Бот работает с панелью `3x-ui` и не вмешивается в её работу напрямую, используя открытое API панели.
Все подключения объединяются в одну подписку со статичным URL. 3DP-MANAGER работает с панелью `3x-ui` и не вмешивается в её работу напрямую, используя открытое API панели.
Вторичная цель — стабильность подключения: клиент получает 10 вариантов подключений и может выбрать любое из них.
Вторичная цель — стабильность подключения: клиент получает несколько вариантов подключений и может выбрать любой из них. В одну подписку можно добавлять инбаунды с разных нод, использовать relay-серверы и добавлять собственные внешние ссылки как кастомные подключения.
Дополнительно: бот можно использовать в каскадной схеме. Сервис перенаправления автоматически настроит переадресацию подписки и трафика к основному серверу.
Дополнительно: 3DP-MANAGER можно использовать в каскадной схеме. Сервис перенаправления автоматически настроит переадресацию подписки и трафика к выбранной ноде.
Рекомендации:
@@ -46,15 +47,25 @@
## Возможности
- Генерация 10 разнообразных подключений
- Генерация разнообразных подключений для одной или нескольких подписок
- Формирование единой подписки со статичным URL
- Управление несколькими нодами `3x-ui`
- Авторизация нод по логину/паролю или токену
- Автоопределение IP, страны и флага ноды по URL панели
- Выбор ноды, relay-сервера, флага, SNI и порта для каждого инбаунда
- Поддержка фиксированного порта или значения `random`
- Кастомные подключения: можно добавить готовую внешнюю ссылку в подписку
- Отдельные пути к `fullchain.pem` и `privkey.pem` для Hysteria2 UDP
- Поддержка кастомного `whitelist` доменов
- Автоматическая настройка перенаправления трафика (опционально)
- Автоматическая настройка relay-перенаправления трафика (опционально)
- Установка Web UI через HTTP или HTTPS: Let's Encrypt, self-signed или свои сертификаты
## Требования
- Ubuntu 20.04 (и выше), Debian 12.11 (и выше)
- Панель `3x-ui` v2.8.4 (и выше)
- Панель `3x-ui` v2.9.4 (и выше)
- Root-доступ на сервере
- Docker и Docker Compose; если их нет, установочный скрипт попробует установить их автоматически
- Домен + SSL сертификат (опционально)
---
@@ -62,13 +73,29 @@
## Установка
У вас должна быть установлена панель управления `3x-ui`, которую можно поставить командой: `bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
Установите проект на сервер командой:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/install.sh)
```
<sup>Краткое описание: запускает скрипт установки и разворачивает контейнеры и сервисы.</sup>
Во время установки скрипт:
- проверит ОС, root-доступ, Docker и Docker Compose;
- при нехватке RAM создаст swap-файл 2 GB, если swap отсутствует;
- предложит выбрать режим доступа к Web UI:
- HTTPS через Let's Encrypt;
- HTTPS с self-signed сертификатом;
- HTTPS со своими сертификатами;
- HTTP без шифрования;
- сгенерирует случайный порт Web UI;
- сгенерирует логин и пароль администратора;
- развернёт контейнеры `postgres`, `backend` и `frontend`.
После завершения установки в терминале будут показаны URL, логин и пароль. Сразу смените пароль в настройках 3DP-MANAGER.
<sup>Краткое описание: запускает интерактивный скрипт установки, подготавливает окружение и разворачивает контейнеры проекта.</sup>
## Обновление
@@ -78,7 +105,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/update.sh)
```
<sup>Краткое описание: подтягивает последние изменения и перезапускает контейнеры.</sup>
<sup>Краткое описание: подтягивает последние изменения, применяет совместимые исправления конфигурации, обновляет контейнеры и перезапускает сервис.</sup>
## Удаление
@@ -92,15 +119,79 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
---
## Первый вход и доступы
Логин и пароль администратора выводятся в конце установки. Если нужно посмотреть их повторно:
```bash
grep -E "ADMIN_LOGIN|ADMIN_PASSWORD" /opt/3dp-manager/docker-compose.yml | sed 's/^[ \t]*//; s/^- //'
```
Web UI доступен по адресу, который показал установщик, например:
- `https://example.com:PORT` для HTTPS;
- `http://SERVER_IP:PORT` для HTTP.
Если включён `ufw`, установщик открывает рабочие диапазоны портов для инбаундов: `443`, `8443` и `10000-60000` для TCP/UDP.
---
## Ноды
Раздел **Ноды** позволяет подключить одну или несколько панелей `3x-ui`.
Для каждой ноды указываются:
- название;
- URL панели `3x-ui`;
- IP ноды;
- флаг/страна;
- тип авторизации: `password` или `token`;
- признак основной ноды.
После ввода URL приложение пытается определить IP и страну ноды автоматически. Флаг используется в названиях подключений внутри подписки, чтобы в клиенте было проще отличать серверы.
> [!NOTE]
> Основная нода используется как значение по умолчанию для подписок, инбаундов и relay-серверов.
---
## Подписки
Раздел **Подписки** управляет статичными URL подписок и составом инбаундов.
Для каждого инбаунда можно настроить:
- тип подключения;
- ноду;
- relay-сервер;
- флаг;
- порт: конкретное число `1-65535` или `random`;
- SNI: конкретный домен или `random`;
- готовую внешнюю ссылку для типа `custom`.
Для `hysteria2-udp` можно указать отдельные пути к сертификату и ключу:
- `certificateFile`, например `/root/cert/example.com/fullchain.pem`;
- `keyFile`, например `/root/cert/example.com/privkey.pem`.
Если порт или SNI указаны как `random`, значение будет выбрано при ротации из доступного диапазона или whitelist доменов.
---
## Установка сервиса перенаправления (forwarding)
> [!WARNING]
> Сервис перенаправления работает на промежуточном сервере
Сервис перенаправления позволяет проксировать входящие порты с промежуточного сервера на основной.
Сервис перенаправления позволяет проксировать входящие порты с промежуточного сервера на выбранную ноду. В Web UI такие серверы настраиваются в разделе **Relay серверы** и могут быть привязаны к конкретной ноде.
Relay-сервер можно добавить по IP или домену. Если указан домен, backend попытается определить IP автоматически.
Для ручной установки forwarding на промежуточном сервере замените `IP_ADDRESS` на IP основной ноды:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)
sudo ORIGIN_IP="IP_ADDRESS" bash -c "$(curl -sSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)"
```
<sup>Краткое описание: добавляет правила перенаправления.</sup>
@@ -111,17 +202,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_delete.sh)
```
<sup>Краткое описание: удаляет правила перенаправления.</sup>
---
## Посмотреть логин и пароль в терминале
Команда позволяет посмотреть логин и пароль от личного кабинета 3DP-MANAGER.
```bash
grep -E "ADMIN_LOGIN|ADMIN_PASSWORD" /opt/3dp-manager/docker-compose.yml | sed 's/^[ \t]*//; s/^- //'
```
<sup>Краткое описание: удаляет правила перенаправления. После удаления, чтобы изменения вступили в силу, перезапустите фаервол `ufw reload` и перезапустите систему `reboot`</sup>
---
@@ -160,4 +241,4 @@ node get_domains.js
## Обсуждение
- Телеграм: [@denpiligrim_web](https://t.me/denpiligrim_web)
- Раздел Issues в данном репозитории
- Раздел Issues в данном репозитории
+145 -68
View File
@@ -2,69 +2,100 @@
<p><img src="https://denpiligrim.ru/storage/images/3dp-manager.png" alt="3dp-manager preview"></p>
![Version](https://img.shields.io/badge/version-2.1.0-blue.svg) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
![Version](https://img.shields.io/badge/version-2.2.0-blue.svg) ![Downloads](https://img.shields.io/badge/downloads-5.1k-blue) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
# 3DP-MANAGER
这是一个用于为 `3x-ui` 面板自动生成入站连接、生成统一订阅并将流量从中服务器转发到主服务器的实用工具
3DP-MANAGER 是一个用于为 [3x-ui](https://github.com/MHSanaei/3x-ui) 面板自动生成 inbound、创建统一订阅、管理多个 3x-ui 节点,并配置从中服务器到源服务器的 relay 转发的工具。从 2.0.0 版本开始,项目提供图形界面和简单的用户设置
**支持项目**
- 捐助/支付信息
- MIR 卡: `2204320436318077`
- MasterCard: `5395452209474530`
- PayPal: `vasiljevdenisx@gmail.com`
- USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- 比特币: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- Bybit ID: `165292278`
- 银行转账
- :credit_card: MIR 卡`2204320436318077`
- :credit_card: MasterCard`5395452209474530`
- 电子钱包:
- :moneybag: YooMoney`4100116897060652`
- :moneybag: PayPal`vasiljevdenisx@gmail.com`
- 加密货币:
- :coin: USDT | ETH (ERC20 | BEP20)`0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- :coin: USDT | TRX (TRC20)`TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- :coin: Bitcoin`bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- :coin: TON`UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- :coin: Bybit ID`165292278`
## 描述
该工具的主要目标是使您的流量看起来不那么一。机器人会在设定间隔生成 10 个具有不同参数的连接:
该工具的主要目标是您的流量看起来不那么一。3DP-MANAGER 会按设定间隔生成一组具有不同参数的连接:
- 协议:`vless``vmess``shadowsocks``trojan`
- 端口:`443``8443`(固定)以及 `10000-60000` 范围内的随机端口
- 传输:`tcp``websocket``grpc``xhttp`
- SNI 从域名白名单`whitelist`)中获取;也可以使用自定义列表
- 协议:`vless``vmess``shadowsocks``hysteria2``trojan`
- 端口:固定的 `443``8443`以及 `10000-60000` 范围内的随机端口
- 传输:`tcp``websocket``grpc``xhttp`
- SNI 从域名白名单中选择,也可以手动指定;
- 每个 inbound 都可以单独设置节点、relay 服务器、端口和旗帜。
所有连接会合并具有静态 URL 的单一订阅。该机器人通过 `3x-ui` 面板的公 API 工作,不会直接修改面板内部。
所有连接会合并到一个具有静态 URL 的订阅中。3DP-MANAGER 通过 `3x-ui` 面板的公 API 工作,不会直接干预面板内部。
次要目标是提高连接稳定性:客户端会收到 10 个可选连接,用户可以选择任意一个
次要目标是提高连接稳定性:客户端会收到多个连接选项,并可选择其中任意一个。一个订阅可以包含来自不同节点的 inbound、relay 服务器,以及作为自定义连接添加的外部链接
此外,机器人可用于级联部署。转发服务会自动配置将订阅和流量重定向到主服务器
此外,3DP-MANAGER 也可用于级联部署。转发服务会把订阅和流量转发配置到选定节点
建议:
- 订阅使用 HTTPS(域名 + SSL 证书)。
- 生成间隔设置为 10 分钟;为稳定性建议每天一次(1440 分钟)。
- 在客户端设置更频繁的自动更新例如每小时,以便与服务器同步。
- 订阅使用 HTTPS(域名 + SSL 证书)。
- 生成间隔设置为不少于 10 分钟;为稳定性建议每天一次(1440 分钟)。
- 在客户端设置更频繁的自动更新例如每小时一次,以便与服务器保持同步。
## 功能
- 生成 10 个多样化连接
- 形成具有静态 URL 的统一订阅
- 支持自定义 `whitelist` 域名
- 可选的自动流量转发配置
- 为一个或多个订阅生成多样化连接
- 创建具有静态 URL 的统一订阅
- 管理多个 `3x-ui` 节点
- 支持使用登录名/密码或 token 进行节点认证
- 根据面板 URL 自动检测节点 IP、国家和旗帜
- 可为每个 inbound 选择节点、relay 服务器、旗帜、SNI 和端口
- 支持固定端口或 `random`
- 支持自定义连接:可将现成的外部链接加入订阅
- 可为 Hysteria2 UDP 单独指定 `fullchain.pem``privkey.pem` 路径
- 支持自定义域名 `whitelist`
- 可选的自动 relay 转发配置
- Web UI 可通过 HTTP 或 HTTPS 安装:Let's Encrypt、自签名证书或自定义证书
## 要求
- Ubuntu 20.04 或更高
- `3x-ui` 面板
- Ubuntu 20.04 或更高版本,Debian 12.11 或更高版本
- `3x-ui` 面板 v2.8.4 或更高版本
- 服务器 root 权限
- Docker 和 Docker Compose;如果缺失,安装脚本会尝试自动安装
- 域名 + SSL 证书(可选)
---
## 安装
在服务器上运行以下命令安装项目:
必须先安装 `3x-ui` 控制面板。可使用以下命令安装:`bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
在服务器上安装项目:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/install.sh)
```
<sup>简要说明:运行安装脚本并部署容器和服务。</sup>
安装过程中,脚本会:
- 检查操作系统、root 权限、Docker 和 Docker Compose
- 如果内存较低且没有 swap,则创建 2 GB 的 swap 文件;
- 询问 Web UI 访问模式:
- 通过 Let's Encrypt 使用 HTTPS
- 使用自签名证书的 HTTPS
- 使用自有证书的 HTTPS
- 不加密的 HTTP
- 生成随机 Web UI 端口;
- 生成管理员登录名和密码;
- 部署 `postgres``backend``frontend` 容器。
安装完成后,终端会显示 URL、登录名和密码。请立即在 3DP-MANAGER 设置中修改密码。
<sup>简要说明:运行交互式安装脚本,准备环境并部署项目容器。</sup>
## 更新
@@ -74,7 +105,7 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/update.sh)
```
<sup>简要说明:拉取最新更改并重启容器。</sup>
<sup>简要说明:拉取最新更改,应用兼容的配置修复,更新容器并重启服务。</sup>
## 删除
@@ -84,19 +115,86 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/delete.sh)
```
<sup>简要说明:删除容器和配置文件,恢复到安装前状态。</sup>
<sup>简要说明:删除容器和配置文件,将系统恢复到安装前状态。</sup>
---
## 安装转发服务(forwarding
## 首次登录
转发服务允许将中继服务器的入站端口代理到主服务器。
管理员登录名和密码会在安装结束时输出。如需再次查看:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)
grep -E "ADMIN_LOGIN|ADMIN_PASSWORD" /opt/3dp-manager/docker-compose.yml | sed 's/^[ \t]*//; s/^- //'
```
<sup>简要说明:添加转发规则并创建用于更新订阅的服务。</sup>
Web UI 可通过安装脚本显示的地址访问,例如:
- HTTPS`https://example.com:PORT`
- HTTP`http://SERVER_IP:PORT`
如果启用了 `ufw`,安装脚本会开放 inbound 工作端口范围:TCP/UDP 的 `443``8443``10000-60000`
---
## 节点
**节点** 页面用于连接一个或多个 `3x-ui` 面板。
每个节点需要设置:
- 名称;
- `3x-ui` 面板 URL
- 节点 IP
- 旗帜/国家;
- 认证类型:`password``token`
- 是否为主节点。
输入 URL 后,应用会尝试自动检测节点 IP 和国家。旗帜会用于订阅中的连接名称,方便客户端区分服务器。
> [!NOTE]
> 主节点会作为订阅、inbound 和 relay 服务器的默认值。
---
## 订阅
**订阅** 页面用于管理静态订阅 URL 和 inbound 组成。
每个 inbound 可配置:
- 连接类型;
- 节点;
- relay 服务器;
- 旗帜;
- 端口:`1-65535` 的具体数字或 `random`
- SNI:具体域名或 `random`
- `custom` 类型的现成外部链接。
对于 `hysteria2-udp`,可以单独指定证书和密钥路径:
- `certificateFile`,例如 `/root/cert/example.com/fullchain.pem`
- `keyFile`,例如 `/root/cert/example.com/privkey.pem`
如果端口或 SNI 设置为 `random`,轮换时会从可用端口范围或域名白名单中选择值。
---
## 安装转发服务
> [!WARNING]
> 转发服务运行在中间服务器上
转发服务会把中间服务器的入站端口代理到选定节点。在 Web UI 中,这些服务器在 **Relay 服务器** 页面配置,并可绑定到具体节点。
Relay 服务器可以通过 IP 或域名添加。如果提供域名,backend 会尝试自动解析其 IP。
如需在中间服务器上手动安装 forwarding,请将 `IP_ADDRESS` 替换为源节点 IP
```bash
sudo ORIGIN_IP="IP_ADDRESS" bash -c "$(curl -sSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)"
```
<sup>简要说明:添加转发规则。</sup>
## 删除转发
@@ -104,64 +202,43 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_delete.sh)
```
<sup>简要说明:删除规则并禁用转发服务。</sup>
<sup>简要说明:删除转发规则。删除后,请执行 `ufw reload` 重新加载防火墙,并执行 `reboot` 重启系统以使更改生效。</sup>
---
## 显示订阅 URL
在容器环境中打印当前订阅 URL 的命令:
```bash
cd /opt/3dp-manager && docker compose exec node env | grep SUB_URL | cut -d'=' -f2
```
<sup>简要说明:打印可在客户端使用的静态订阅 URL,适用于主服务器和中继服务器。</sup>
## 从多订阅收集域名
该工具从订阅中提取域名并为生成器构建 `whitelist`
该工具从订阅中提取域名并为生成器构建 `whitelist`
```bash
node get_domains.js
```
<sup>简要说明:在脚本中添加多订阅链接并运行命令 — 输出为域名列表。运行脚本需要 `Node.js`。</sup>
## 使用自定义白名单
1. 准备一个与 `whitelist.txt` 相同格式的文件。
2. 将其重命名为 `my_whitelist.txt` 并复制到 `/opt/3dp-manager/app`
```bash
cd /opt/3dp-manager && docker cp ./app/my_whitelist.txt node:/app/my_whitelist.txt
```
<sup>简要说明:将您的域名文件添加到应用容器中。</sup>
<sup>简要说明:在脚本中添加多订阅链接并运行命令,输出将是域名列表。运行脚本需要 `Node.js`。</sup>
---
## 注意当前限制
## 注意事项和当前限制
- 共享域名列表可能并非对所有提供商都有效;建议准备并使用自定义 `whitelist`
- 共享域名列表并非适用于所有服务商,因此建议准备并使用自己的 whitelist。
---
## 贡献
欢迎贡献!简单的贡献流程:
欢迎任何贡献!简单的贡献流程:
1. 在 GitHub 上 fork 仓库。
2. 创建有意义的分支名,例如 `feature/add-README``fix/whitelist-load`
3. 提交更改并添加简短的提交信息
4. 在本地运行检查(如有)
5. 推送分支到您的 fork 并创建 Pull Request。
3. 修改代码,并在 commit 中添加简短说明
4. 如有本地检查,请运行它们
5. 将分支推送到你的 fork,并向主仓库创建 Pull Request。
<sup>建议:在 PR 中说明更改和测试步骤;较大更改请拆成小提交。</sup>
<sup>建议:在 PR 中说明更改、目标和测试步骤。如果更改较大,请拆分为较小的 commit。</sup>
---
## 讨论
- Telegram: [@denpiligrim_web](https://t.me/denpiligrim_web)
- Issues
- 本仓库的 Issues
+143 -66
View File
@@ -2,69 +2,100 @@
<p><img src="https://denpiligrim.ru/storage/images/3dp-manager.png" alt="3dp-manager preview"></p>
![Version](https://img.shields.io/badge/version-2.1.0-blue.svg) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
![Version](https://img.shields.io/badge/version-2.2.0-blue.svg) ![Downloads](https://img.shields.io/badge/downloads-5.1k-blue) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
# 3DP-MANAGER
A utility for auto-generating inbound connections for the [3x-ui](https://github.com/MHSanaei/3x-ui) panel, creating a single subscription URL, and configuring traffic forwarding from an intermediate server to the main server.
A utility for automatically generating inbounds for the [3x-ui](https://github.com/MHSanaei/3x-ui) panel, creating unified subscriptions, managing multiple 3x-ui nodes, and configuring relay forwarding from intermediate servers to origin servers. Since version 2.0.0, the project has a graphical interface and simple user-facing settings.
**Support the project**
- Donation / payment details:
- MIR card: `2204320436318077`
- MasterCard: `5395452209474530`
- PayPal: `vasiljevdenisx@gmail.com`
- USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- Bitcoin: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- Bybit ID: `165292278`
- Bank transfer:
- :credit_card: MIR card: `2204320436318077`
- :credit_card: MasterCard: `5395452209474530`
- E-wallet:
- :moneybag: YooMoney: `4100116897060652`
- :moneybag: PayPal: `vasiljevdenisx@gmail.com`
- Crypto:
- :coin: USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- :coin: USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- :coin: Bitcoin: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- :coin: TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- :coin: Bybit ID: `165292278`
## Description
The main goal of the utility is to make your traffic appear non-uniform. The bot generates 10 connection entries at a configured interval with varying parameters:
The main goal of the utility is to make your traffic look less uniform. 3DP-MANAGER generates a set of connections at a configured interval with different parameters:
- Protocols: `vless`, `vmess`, `shadowsocks`, `trojan`;
- Ports: `443`, `8443` (fixed) and random ports from the range `10000-60000`;
- Transport: `tcp`, `websocket`, `grpc`, `xhttp`;
- SNI values are taken from a whitelist of domains (`whitelist`); you can use your own list.
- protocols: `vless`, `vmess`, `shadowsocks`, `hysteria2`, `trojan`;
- ports: fixed `443`, `8443`, plus random ports from `10000-60000`;
- transport: `tcp`, `websocket`, `grpc`, `xhttp`;
- SNI values are taken from the domain whitelist or set manually;
- node, relay server, port, and flag can be configured separately for each inbound.
All generated connections are combined into a single subscription with a static URL. The bot works with the `3x-ui` panel using its public API and does not directly modify the panel internals.
All connections are combined into one subscription with a static URL. 3DP-MANAGER works with the `3x-ui` panel through its public API and does not directly interfere with the panel internals.
The secondary goal is connection stability: the client receives 10 alternate connection options and can choose any of them.
The secondary goal is connection stability: the client receives several connection options and can choose any of them. One subscription can contain inbounds from different nodes, relay servers, and your own external links as custom connections.
Additionally, the bot can be used in a cascading setup. The forwarding service will automatically configure the subscription and traffic redirection to the main server.
Additionally, 3DP-MANAGER can be used in a cascading setup. The forwarding service configures subscription and traffic forwarding to the selected node.
Recommendations:
- Use HTTPS for the subscription (domain + SSL certificate).
- Set the generation interval to 10 minutes; for stability, once per day (1440 minutes) is recommended.
- Configure the client to check for updates more frequently (for example, hourly) to stay synchronized with the server.
- Use HTTPS for subscriptions (domain + SSL certificate).
- Set the generation interval to at least 10 minutes; for stability, once per day (1440 minutes) is recommended.
- Configure the client to refresh more frequently, for example every hour, so it stays synchronized with the server.
## Features
- Generates 10 diverse connection entries
- Creates a single subscription with a static URL
- Supports custom `whitelist` domains
- Optional automatic configuration of traffic forwarding
- Generates diverse connections for one or more subscriptions
- Creates a unified subscription with a static URL
- Manages multiple `3x-ui` nodes
- Supports node authentication by login/password or token
- Automatically detects node IP, country, and flag from the panel URL
- Lets you choose node, relay server, flag, SNI, and port per inbound
- Supports a fixed port or `random`
- Supports custom connections: add a ready-made external link to a subscription
- Allows separate `fullchain.pem` and `privkey.pem` paths for Hysteria2 UDP
- Supports a custom domain `whitelist`
- Optional automatic relay forwarding setup
- Installs the Web UI over HTTP or HTTPS: Let's Encrypt, self-signed, or custom certificates
## Requirements
- Ubuntu 20.04 or newer
- `3x-ui` panel
- Ubuntu 20.04 or newer, Debian 12.11 or newer
- `3x-ui` panel v2.8.4 or newer
- Root access on the server
- Docker and Docker Compose; if missing, the installer will try to install them automatically
- Domain + SSL certificate (optional)
---
## Installation
Install the project on your server with:
The `3x-ui` control panel must already be installed. You can install it with: `bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
Install the project on the server:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/install.sh)
```
<sup>Short description: runs the installer script and deploys containers and services.</sup>
During installation, the script will:
- check the OS, root access, Docker, and Docker Compose;
- create a 2 GB swap file if RAM is low and swap is missing;
- ask which Web UI access mode to use:
- HTTPS via Let's Encrypt;
- HTTPS with a self-signed certificate;
- HTTPS with your own certificates;
- HTTP without encryption;
- generate a random Web UI port;
- generate the administrator login and password;
- deploy the `postgres`, `backend`, and `frontend` containers.
After installation, the terminal will show the URL, login, and password. Change the password immediately in the 3DP-MANAGER settings.
<sup>Short description: runs the interactive installer, prepares the environment, and deploys the project containers.</sup>
## Update
@@ -74,7 +105,7 @@ Update to the latest version:
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/update.sh)
```
<sup>Short description: pulls the latest changes and restarts containers.</sup>
<sup>Short description: pulls the latest changes, applies compatible configuration fixes, updates containers, and restarts the service.</sup>
## Removal
@@ -88,37 +119,94 @@ bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main
---
## Install forwarding service
## First Login
The forwarding service allows proxying incoming ports from the intermediate server to the main server.
The administrator login and password are printed at the end of installation. To view them again:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)
grep -E "ADMIN_LOGIN|ADMIN_PASSWORD" /opt/3dp-manager/docker-compose.yml | sed 's/^[ \t]*//; s/^- //'
```
<sup>Short description: adds forwarding rules and creates a service to update the subscription.</sup>
The Web UI is available at the address shown by the installer, for example:
## Remove forwarding
- `https://example.com:PORT` for HTTPS;
- `http://SERVER_IP:PORT` for HTTP.
If `ufw` is active, the installer opens the working inbound port ranges: `443`, `8443`, and `10000-60000` for TCP/UDP.
---
## Nodes
The **Nodes** section lets you connect one or more `3x-ui` panels.
For each node, you specify:
- name;
- `3x-ui` panel URL;
- node IP;
- flag/country;
- authentication type: `password` or `token`;
- whether this node is the main node.
After you enter the URL, the application tries to detect the node IP and country automatically. The flag is used in connection names inside the subscription so clients can distinguish servers more easily.
> [!NOTE]
> The main node is used as the default value for subscriptions, inbounds, and relay servers.
---
## Subscriptions
The **Subscriptions** section manages static subscription URLs and inbound composition.
For each inbound, you can configure:
- connection type;
- node;
- relay server;
- flag;
- port: a concrete number from `1-65535` or `random`;
- SNI: a concrete domain or `random`;
- a ready-made external link for the `custom` type.
For `hysteria2-udp`, you can specify separate certificate and key paths:
- `certificateFile`, for example `/root/cert/example.com/fullchain.pem`;
- `keyFile`, for example `/root/cert/example.com/privkey.pem`.
If port or SNI is set to `random`, the value will be selected during rotation from the available range or domain whitelist.
---
## Install Forwarding Service
> [!WARNING]
> The forwarding service runs on an intermediate server
The forwarding service proxies incoming ports from an intermediate server to the selected node. In the Web UI, these servers are configured in **Relay servers** and can be linked to a specific node.
A relay server can be added by IP or domain. If a domain is provided, the backend will try to resolve its IP automatically.
For manual forwarding installation on the intermediate server, replace `IP_ADDRESS` with the origin node IP:
```bash
sudo ORIGIN_IP="IP_ADDRESS" bash -c "$(curl -sSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)"
```
<sup>Short description: adds forwarding rules.</sup>
## Remove Forwarding
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_delete.sh)
```
<sup>Short description: removes rules and disables the forwarding service.</sup>
<sup>Short description: removes forwarding rules. After removal, reload the firewall with `ufw reload` and reboot the system with `reboot` for changes to take effect.</sup>
---
## Show subscription URL
Command to print the current subscription URL from the container environment:
```bash
cd /opt/3dp-manager && docker compose exec node env | grep SUB_URL | cut -d'=' -f2
```
<sup>Short description: prints the static subscription URL that can be used in clients. Works on both main and intermediate servers.</sup>
## Collect domains from multi-subscriptions
## Collect Domains From Multi-Subscriptions
The utility extracts domains from subscriptions and builds a `whitelist` for the generator.
@@ -126,24 +214,13 @@ The utility extracts domains from subscriptions and builds a `whitelist` for the
node get_domains.js
```
<sup>Short description: add a multi-subscription link to the script and run the command — the output will be a list of domains. `Node.js` is required to run the script.</sup>
## Use your own whitelist
1. Prepare a file in the format of `whitelist.txt`.
2. Rename it to `my_whitelist.txt` and copy it into `/opt/3dp-manager/app`.
```bash
cd /opt/3dp-manager && docker cp ./app/my_whitelist.txt node:/app/my_whitelist.txt
```
<sup>Short description: adds your domain file into the application container.</sup>
<sup>Short description: add a multi-subscription link to the script and run the command. The output will be a domain list. `Node.js` is required.</sup>
---
## Notes and current limitations
## Notes And Current Limitations
- The shared domain list may not work with all providers; it is recommended to prepare and use your own `whitelist`.
- The shared domain list may not work with all providers, so it is recommended to prepare and use your own whitelist.
---
@@ -152,16 +229,16 @@ cd /opt/3dp-manager && docker cp ./app/my_whitelist.txt node:/app/my_whitelist.t
Contributions are welcome! Simple contributor workflow:
1. Fork the repository on GitHub.
2. Create a branch with a meaningful name, e.g. `feature/add-README` or `fix/whitelist-load`.
3. Make changes and add a short commit message.
2. Create a branch with a meaningful name, for example `feature/add-README` or `fix/whitelist-load`.
3. Make changes and add a short description in the commit.
4. Run local checks if available.
5. Push the branch to your fork and create a Pull Request to the main repository.
<sup>Tips: describe changes and testing steps in the PR. For large changes, split into smaller commits.</sup>
<sup>Tips: describe your changes in the PR, include the goal and test steps. If the changes are large, split them into small commits.</sup>
---
## Discussion
- Telegram: [@denpiligrim_web](https://t.me/denpiligrim_web)
- Issues
- Issues section in this repository
+148 -71
View File
@@ -2,166 +2,243 @@
<p><img src="https://denpiligrim.ru/storage/images/3dp-manager.png" alt="3dp-manager preview"></p>
![Version](https://img.shields.io/badge/version-2.1.0-blue.svg) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
![Version](https://img.shields.io/badge/version-2.2.0-blue.svg) ![Downloads](https://img.shields.io/badge/downloads-5.1k-blue) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
# 3DP-MANAGER
ابزاری برای تولید خودکار اتصال‌های inbound برای پنل `3x-ui`، ساخت یک اشتراک یکپارچه و هدایت ترافیک از سرور واسط به سرور اصلی.
ابزاری برای تولید خودکار inbound برای پنل [3x-ui](https://github.com/MHSanaei/3x-ui)، ساخت اشتراک‌های یکپارچه، مدیریت چندین نود 3x-ui و پیکربندی relay forwarding از سرورهای واسط به سرورهای اصلی. از نسخه 2.0.0 به بعد، پروژه دارای رابط گرافیکی و تنظیمات ساده کاربری است.
**حمایت از پروژه**
- اطلاعات پرداخت/اهدا:
- کارت MIR: `2204320436318077`
- کارت MasterCard: `5395452209474530`
- PayPal: `vasiljevdenisx@gmail.com`
- USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- بیت‌کوین: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- Bybit ID: `165292278`
- انتقال بانکی:
- :credit_card: کارت MIR: `2204320436318077`
- :credit_card: کارت MasterCard: `5395452209474530`
- کیف پول الکترونیکی:
- :moneybag: YooMoney: `4100116897060652`
- :moneybag: PayPal: `vasiljevdenisx@gmail.com`
- رمزارز:
- :coin: USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- :coin: USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- :coin: Bitcoin: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- :coin: TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- :coin: Bybit ID: `165292278`
## توضیحات
هدف اصلی این ابزار این است که ترافیک شما یکسان به نظر نرسد. ربات در فواصل زمانی مشخص 10 اتصال با پارامترهای مختلف تولید می‌کند:
هدف اصلی ابزار این است که ترافیک شما یکسان به نظر نرسد. 3DP-MANAGER در بازه زمانی تعیین‌شده، مجموعه‌ای از اتصال‌ها با پارامترهای متفاوت تولید می‌کند:
- پروتکل‌ها: `vless`, `vmess`, `shadowsocks`, `trojan`
- پورت‌ها: `443`, `8443` (ثابت) و پورت‌های تصادفی در بازه `10000-60000`
- لایه انتقال: `tcp`, `websocket`, `grpc`, `xhttp`
- SNI از لیست سفید دامنه‌ها گرفته می‌شود (`whitelist`); می‌توانید از لیست خود استفاده کنید.
- پروتکل‌ها: `vless`, `vmess`, `shadowsocks`, `hysteria2`, `trojan`;
- پورت‌ها: `443` و `8443` به‌صورت ثابت، و پورت‌های تصادفی از بازه `10000-60000`;
- transport: `tcp`, `websocket`, `grpc`, `xhttp`;
- SNI از whitelist دامنه‌ها انتخاب می‌شود یا به‌صورت دستی تنظیم می‌گردد؛
- نود، relay server، پورت و پرچم را می‌توان برای هر inbound جداگانه تنظیم کرد.
تمام اتصالات در یک اشتراک با URL ثابت تجمیع می‌شوند. ربات با پنل `3x-ui` از طریق API باز کار می‌کند و به‌طور مستقیم در عملکرد داخلی پنل دخالت نمی‌کند.
همه اتصالها در یک اشتراک با URL ثابت ترکیب می‌شوند. 3DP-MANAGER با پنل `3x-ui` از طریق API عمومی آن کار می‌کند و مستقیماً در بخش داخلی پنل دخالت نمی‌کند.
هدف ثانویه افزایش پایداری اتصال است: مشتری 10 گزینه اتصال دریافت می‌کند و می‌تواند هر کدام را انتخاب کند.
هدف دوم پایداری اتصال است: کلاینت چند گزینه اتصال دریافت می‌کند و می‌تواند هرکدام را انتخاب کند. در یک اشتراک می‌توان inboundهای مربوط به نودهای مختلف، relay serverها و لینک‌های خارجی آماده را به‌عنوان اتصال custom قرار داد.
علاوه بر این، ربات می‌تواند در طرح‌های آبشاری استفاده شود. سرویس فورواردینگ به‌طور خودکار بازنشانی اشتراک و ترافیک به سرور اصلی را تنظیم می‌کند.
همچنین 3DP-MANAGER را می‌توان در سناریوی زنجیره‌ای استفاده کرد. سرویس forwarding، هدایت اشتراک و ترافیک را به نود انتخاب‌شده پیکربندی می‌کند.
توصیه‌ها:
- برای اشتراک از HTTPS استفاده کنید (دامنه + گواهی SSL).
- فاصله تولید را 10 دقیقه در نظر بگیرید؛ برای پایداری توصیه می‌شود یک‌بار در روز (1440 دقیقه) تنظیم شود.
- در کلاینت به‌روزرسانی خودکار را بیشتر تنظیم کنید (مثلاً هر ساعت) تا همگام‌سازی با سرور انجام شود.
- فاصله تولید را حداقل 10 دقیقه تنظیم کنید؛ برای پایداری، یک‌بار در روز (1440 دقیقه) توصیه می‌شود.
- در کلاینت، به‌روزرسانی خودکار را دفعات بیشتری تنظیم کنید، مثلاً هر ساعت، تا با سرور همگام بماند.
## قابلیت‌ها
- تولید 10 اتصال متنوع
- تشکیل یک اشتراک یکپارچه با URL ثابت
- پشتیبانی از دامنه‌های `whitelist` سفارشی
- پیکربندی خودکار فورواردینگ ترافیک (اختیاری)
- تولید اتصال‌های متنوع برای یک یا چند اشتراک
- ساخت اشتراک یکپارچه با URL ثابت
- مدیریت چندین نود `3x-ui`
- پشتیبانی از احراز هویت نود با login/password یا token
- تشخیص خودکار IP، کشور و پرچم نود از URL پنل
- انتخاب نود، relay server، پرچم، SNI و پورت برای هر inbound
- پشتیبانی از پورت ثابت یا مقدار `random`
- پشتیبانی از اتصال‌های custom: افزودن لینک خارجی آماده به اشتراک
- امکان تعیین مسیرهای جداگانه `fullchain.pem` و `privkey.pem` برای Hysteria2 UDP
- پشتیبانی از `whitelist` دامنه سفارشی
- تنظیم خودکار relay forwarding به‌صورت اختیاری
- نصب Web UI از طریق HTTP یا HTTPS: Let's Encrypt، self-signed یا گواهی‌های خودتان
## نیازمندی‌ها
- Ubuntu 20.04 یا بالاتر
- پنل `3x-ui`
- Ubuntu 20.04 یا جدیدتر، Debian 12.11 یا جدیدتر
- پنل `3x-ui` نسخه v2.8.4 یا جدیدتر
- دسترسی root روی سرور
- Docker و Docker Compose؛ اگر نصب نباشند، اسکریپت نصب تلاش می‌کند آن‌ها را خودکار نصب کند
- دامنه + گواهی SSL (اختیاری)
---
## نصب
برای نصب پروژه در سرور، دستور زیر را اجرا کنید:
پنل مدیریتی `3x-ui` باید از قبل نصب شده باشد. می‌توانید آن را با این دستور نصب کنید: `bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
پروژه را روی سرور نصب کنید:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/install.sh)
```
<sup>توضیح کوتاه: اسکریپت نصب را اجرا کرده و کانتینرها و سرویس‌ها را راه‌اندازی می‌کند.</sup>
در زمان نصب، اسکریپت:
- سیستم‌عامل، دسترسی root، Docker و Docker Compose را بررسی می‌کند؛
- اگر RAM کم باشد و swap وجود نداشته باشد، یک فایل swap با حجم 2 GB می‌سازد؛
- حالت دسترسی Web UI را می‌پرسد:
- HTTPS با Let's Encrypt؛
- HTTPS با گواهی self-signed؛
- HTTPS با گواهی‌های خودتان؛
- HTTP بدون رمزنگاری؛
- یک پورت تصادفی برای Web UI ایجاد می‌کند؛
- login و password مدیر را ایجاد می‌کند؛
- کانتینرهای `postgres`, `backend` و `frontend` را اجرا می‌کند.
پس از پایان نصب، URL، login و password در ترمینال نمایش داده می‌شود. بلافاصله password را در تنظیمات 3DP-MANAGER تغییر دهید.
<sup>توضیح کوتاه: اسکریپت نصب تعاملی را اجرا می‌کند، محیط را آماده می‌سازد و کانتینرهای پروژه را راه‌اندازی می‌کند.</sup>
## به‌روزرسانی
برای به‌روزرسانی به آخرین نسخه:
به‌روزرسانی به آخرین نسخه:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/update.sh)
```
<sup>توضیح کوتاه: تغییرات جدید را می‌کشد و کانتینرها را ری‌استارت می‌کند.</sup>
<sup>توضیح کوتاه: آخرین تغییرات را دریافت می‌کند، اصلاحات سازگار پیکربندی را اعمال می‌کند، کانتینرها را به‌روزرسانی کرده و سرویس را راه‌اندازی مجدد می‌کند.</sup>
## حذف
برای حذف کامل سرویس:
حذف کامل سرویس:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/delete.sh)
```
<sup>توضیح کوتاه: کانتینرها و فایل‌های پیکربندی را حذف می‌کند و سیستم را به وضعیت پیش از نصب برمی‌گرداند.</sup>
<sup>توضیح کوتاه: کانتینرها و فایل‌های پیکربندی را حذف می‌کند و سیستم را به وضعیت پیش از نصب بازمی‌گرداند.</sup>
---
## نصب سرویس فورواردینگ (forwarding)
## اولین ورود
سرویس فورواردینگ امکان پراکسی کردن پورت‌های ورودی از سرور واسط به سرور اصلی را فراهم می‌کند.
login و password مدیر در پایان نصب نمایش داده می‌شود. برای مشاهده دوباره:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)
grep -E "ADMIN_LOGIN|ADMIN_PASSWORD" /opt/3dp-manager/docker-compose.yml | sed 's/^[ \t]*//; s/^- //'
```
<sup>توضیح کوتاه: قوانین فورواردینگ را اضافه کرده و سرویسی برای به‌روزرسانی اشتراک ایجاد می‌کند.</sup>
Web UI در آدرسی که نصب‌کننده نمایش داده قابل دسترسی است، برای مثال:
## حذف فورواردینگ
- `https://example.com:PORT` برای HTTPS؛
- `http://SERVER_IP:PORT` برای HTTP.
اگر `ufw` فعال باشد، نصب‌کننده بازه‌های پورت کاری inbound را برای TCP/UDP باز می‌کند: `443`, `8443` و `10000-60000`.
---
## نودها
بخش **نودها** امکان اتصال یک یا چند پنل `3x-ui` را فراهم می‌کند.
برای هر نود مشخص می‌شود:
- نام؛
- URL پنل `3x-ui`؛
- IP نود؛
- پرچم/کشور؛
- نوع احراز هویت: `password` یا `token`؛
- اینکه نود اصلی است یا خیر.
پس از وارد کردن URL، برنامه تلاش می‌کند IP و کشور نود را خودکار تشخیص دهد. پرچم در نام اتصال‌ها داخل اشتراک استفاده می‌شود تا تشخیص سرورها در کلاینت ساده‌تر باشد.
> [!NOTE]
> نود اصلی به‌عنوان مقدار پیش‌فرض برای اشتراک‌ها، inboundها و relay serverها استفاده می‌شود.
---
## اشتراک‌ها
بخش **اشتراک‌ها** URLهای ثابت اشتراک و ترکیب inboundها را مدیریت می‌کند.
برای هر inbound می‌توانید تنظیم کنید:
- نوع اتصال؛
- نود؛
- relay server؛
- پرچم؛
- پورت: عدد مشخص از `1-65535` یا `random`؛
- SNI: دامنه مشخص یا `random`؛
- لینک خارجی آماده برای نوع `custom`.
برای `hysteria2-udp` می‌توانید مسیرهای جداگانه گواهی و کلید را مشخص کنید:
- `certificateFile`، برای مثال `/root/cert/example.com/fullchain.pem`;
- `keyFile`، برای مثال `/root/cert/example.com/privkey.pem`.
اگر پورت یا SNI برابر `random` باشد، مقدار هنگام روتیشن از بازه موجود یا whitelist دامنه‌ها انتخاب می‌شود.
---
## نصب سرویس forwarding
> [!WARNING]
> سرویس forwarding روی سرور واسط اجرا می‌شود
سرویس forwarding پورت‌های ورودی سرور واسط را به نود انتخاب‌شده proxy می‌کند. در Web UI این سرورها در بخش **Relay serverها** تنظیم می‌شوند و می‌توانند به یک نود مشخص متصل شوند.
Relay server را می‌توان با IP یا دامنه اضافه کرد. اگر دامنه وارد شود، backend تلاش می‌کند IP آن را خودکار resolve کند.
برای نصب دستی forwarding روی سرور واسط، `IP_ADDRESS` را با IP نود اصلی جایگزین کنید:
```bash
sudo ORIGIN_IP="IP_ADDRESS" bash -c "$(curl -sSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)"
```
<sup>توضیح کوتاه: قوانین forwarding را اضافه می‌کند.</sup>
## حذف forwarding
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_delete.sh)
```
<sup>توضیح کوتاه: قوانین را حذف کرده و سرویس فورواردینگ را غیرفعال می‌کند.</sup>
<sup>توضیح کوتاه: قوانین forwarding را حذف می‌کند. پس از حذف، برای اعمال تغییرات firewall را با `ufw reload` بارگذاری مجدد کنید و سیستم را با `reboot` ری‌استارت کنید.</sup>
---
## نمایش URL اشتراک
## جمع‌آوری دامنه‌ها از چند اشتراک
دستور برای نمایش URL اشتراک فعلی در محیط کانتینر:
```bash
cd /opt/3dp-manager && docker compose exec node env | grep SUB_URL | cut -d'=' -f2
```
<sup>توضیح کوتاه: URL ثابت اشتراک را نمایش می‌دهد که می‌توان در کلاینت‌ها استفاده کرد. هم در سرور اصلی و هم در سرور واسط کار می‌کند.</sup>
## جمع‌آوری دامنه‌ها از چندین اشتراک
ابزار دامنه‌ها را از اشتراک‌های دارای چندین پیکربندی استخراج کرده و `whitelist` تولید می‌کند.
این ابزار دامنه‌ها را از اشتراک‌ها استخراج می‌کند و برای generator یک `whitelist` می‌سازد.
```bash
node get_domains.js
```
<sup>توضیح کوتاه: لینک چندین اشتراک را در اسکریپت قرار داده و فرمان را اجرا کنید خروجی فهرست دامنه‌ها خواهد بود. نیازمند `Node.js` است.</sup>
## استفاده از whitelist شخصی
1. فایلی با ساختار مشابه `whitelist.txt` آماده کنید.
2. آن را به `my_whitelist.txt` تغییر نام دهید و در پوشه `/opt/3dp-manager/app` کپی کنید.
```bash
cd /opt/3dp-manager && docker cp ./app/my_whitelist.txt node:/app/my_whitelist.txt
```
<sup>توضیح کوتاه: فایل دامنه شما را به کانتینر برنامه اضافه می‌کند.</sup>
<sup>توضیح کوتاه: لینک چند اشتراک را در اسکریپت اضافه کنید و دستور را اجرا کنید. خروجی، فهرست دامنه‌ها خواهد بود. برای اجرای اسکریپت به `Node.js` نیاز است.</sup>
---
## نکات و محدودیت‌های فعلی
- لیست عمومی دامنه‌ها برای همه ارائه‌دهندگان کار نمی‌کند؛ پیشنهاد می‌شود `whitelist` خود را تهیه و استفاده کنید.
- فهرست عمومی دامنه‌ها با همه ارائه‌دهندگان کار نمی‌کند، بنابراین توصیه می‌شود whitelist خودتان را بسازید و استفاده کنید.
---
## مشارکت
از هرگونه مشارکت در توسعه پروژه خوشحال می‌شوم! روند ساده برای مشارکت‌کنندگان:
از هرگونه مشارکت در توسعه پروژه استقبال می‌شود! روند ساده برای مشارکت‌کنندگان:
1. مخزن را در GitHub fork کنید.
2. شاخه‌ای با نام معنادار ایجاد کنید مانند `feature/add-README` یا `fix/whitelist-load`.
3. تغییرات را اعمال کرده و یک پیام کوتاه در کامیت اضافه کنید.
2. شاخه‌ای با نام معنادار بسازید، مثل `feature/add-README` یا `fix/whitelist-load`.
3. تغییرات را اعمال کنید و توضیح کوتاهی در commit بنویسید.
4. در صورت وجود، بررسی‌های محلی را اجرا کنید.
5. شاخه را به fork خود پوش کرده و Pull Request ایجاد کنید.
5. شاخه را به fork خود push کنید و در مخزن اصلی Pull Request بسازید.
<sup>نکات: تغییرات را در PR شرح دهید و مراحل تست را بنویسید. در صورت تغییرات بزرگ، آنها را به کامیت‌های کوچک تقسیم کنید.</sup>
<sup>نکته: تغییرات، هدف و مراحل تست را در PR توضیح دهید. اگر تغییرات بزرگ هستند، آنها را به commitهای کوچک تقسیم کنید.</sup>
---
## بحث
## گفتگو
- تلگرام: [@denpiligrim_web](https://t.me/denpiligrim_web)
- Issues
- بخش Issues در همین مخزن
+160 -71
View File
@@ -2,154 +2,243 @@
<p><img src="https://denpiligrim.ru/storage/images/3dp-manager.png" alt="3dp-manager preview"></p>
![Version](https://img.shields.io/badge/version-2.1.0-blue.svg) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
![Version](https://img.shields.io/badge/version-2.2.0-blue.svg) ![Downloads](https://img.shields.io/badge/downloads-5.1k-blue) [![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0) [![Telegram](https://img.shields.io/badge/Telegram-26A5E4?style=flat&logo=telegram&logoColor=white)](https://t.me/denpiligrim_web) [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UCOv2tFFYDY4mXOM60PVz8zw)](https://www.youtube.com/@denpiligrim)
# 3DP-MANAGER
Bu gural `3x-ui` paneli üçin awtomatiki ýagdaýda inbound baglanyşlaryny döredýär, birleşdirilen abunany (subscription) döretmäge we aragatnaşyk serwerinden esasy servere trafigiň ugradylyşyny sazlamaga kömek edýär.
[3x-ui](https://github.com/MHSanaei/3x-ui) paneli üçin inbound-lary awtomatiki döretmäge, birleşdirilen abunalary düzmäge, birnäçe 3x-ui node-ny dolandyrmaga we aralyk serwerlerden esasy serwerlere relay forwarding sazlamaga niýetlenen gural. 2.0.0 wersiýadan bäri taslamada grafiki interfeýs we ýönekeý ulanyjy sazlamalary bar.
**Taslamany goldaň**
- Töleg / goşant maglumatlary:
- MIR kart: `2204320436318077`
- MasterCard: `5395452209474530`
- PayPal: `vasiljevdenisx@gmail.com`
- USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- Bitcoin: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- Bybit ID: `165292278`
- Bank geçirimi:
- :credit_card: MIR kart: `2204320436318077`
- :credit_card: MasterCard: `5395452209474530`
- Elektron gapjyk:
- :moneybag: YooMoney: `4100116897060652`
- :moneybag: PayPal: `vasiljevdenisx@gmail.com`
- Kriptowalýuta:
- :coin: USDT | ETH (ERC20 | BEP20): `0x6fe140040f6Cdc1E1Ff2136cd1d60C0165809463`
- :coin: USDT | TRX (TRC20): `TEWxXmJxvkAmhshp7E61XJGHB3VyM9hNAb`
- :coin: Bitcoin: `bc1qctntwncsv2yn02x2vgnkrqm00c4h04c0afkgpl`
- :coin: TON: `UQCZ3MiwyYHXftPItMMzJRYRiKHugr16jFMq2nfOQOOoemLy`
- :coin: Bybit ID: `165292278`
## Düşündiriş
Esasy maksady trafigiňizi birmeňzeş bolmaz ýaly etmekdir. Bot bellenen aralykda dürli parametrler bilen 10 sany baglanyşygy döredýär:
Guralyň esasy maksady trafigiňiziň birmeňzeş görünmezligini gazanmakdyr. 3DP-MANAGER bellenen aralykda dürli parametrli baglanyşyklar toplumyny döredýär:
- Protokollar: `vless`, `vmess`, `shadowsocks`, `trojan`;
- Portlar: `443`, `8443` (hemişelik) we `10000-60000` aralygyndan tötänleýin portlar;
- Transport: `tcp`, `websocket`, `grpc`, `xhttp`;
- SNI `whitelist` domen sanawyndan alynýar; öz sanawyňyzy hem ulanyp bilersiňiz.
- protokollar: `vless`, `vmess`, `shadowsocks`, `hysteria2`, `trojan`;
- portlar: hemişelik `443`, `8443` we `10000-60000` aralygyndaky tötänleýin portlar;
- transport: `tcp`, `websocket`, `grpc`, `xhttp`;
- SNI domen whitelist-den alynýar ýa-da el bilen berilýär;
- her inbound üçin node, relay serwer, port we baýdak aýratyn sazlanýar.
Ähli döredilen baglanyşyklary biri-birine birleşdirip, statik URL bilen bir abuna döredilýär. Bot `3x-ui` paneliniň açyk API-sini ulanýar we paneliň içki konfigurasiýasyna gönüden-göni aralaşmaýar.
Ähli baglanyşyklar statik URL-li bir abuna birleşdirilýär. 3DP-MANAGER `3x-ui` paneli bilen onuň açyk API-si arkaly işleýär we paneliň içki işine göni gatyşmaýar.
Ikinji maksady baglanyşygyň durnuklylygyny ýokarlandyrmakdyr: müşderi 10 dürli baglanyşyk opsiýasyny alýar we islese haýsyny islese saýlap biär.
Ikinji maksat baglanyşygyň durnuklylygydyr: müşderi birnäçe baglanyşyk wariantyny alýar we islänini saýlap bilýär. Bir abuna dürli node-lardan inbound-lary, relay serwerleri we custom baglanyşyk hökmünde taýýar daşarky linkleri goşup boar.
Göçürme (forwarding) hyzmaty bilen birleşdirilende, bot abonnament we trafik diňe esasy servere ugradylyşyny awtomatiki sazlar.
Mundan başga-da, 3DP-MANAGER kaskadly shemada ulanylyp bilner. Forwarding hyzmaty abunany we trafigi saýlanan node-a ugrukdyrmagy sazlaýar.
Maslahatchylyklar:
Maslahatlar:
- Abuna üçin HTTPS ulanyň (domain + SSL şahadatnamasy).
- Dörediş aralygyny 10 minut goýuň; durnuklylyk üçin her gün bir gezek (1440 minut) maslahat berilýär.
- Müşderide awtomatiki täzelenmäni ýygylaşdyryň (meselem, her sagat) — serwera sazlaşyklylyk üçin.
- Abuna üçin HTTPS ulanyň (domen + SSL şahadatnamasy).
- Döretmek aralygyny azyndan 10 minut goýuň; durnuklylyk üçin günde bir gezek (1440 minut) maslahat berilýär.
- Müşderide awtomatiki täzelenmäni ýygy goýuň, meselem her sagat, serwer bilen sazlaşyk saklansyn.
## Imkaylyklar
## mkiilikler
- 10 dürli baglanyşygy öndürýär
- Statik URL bilen bir abuna döredýär
- Öz `whitelist` domenleriňizi goldaýar
- Trafigiň awtomatik forwarding sazlamalary (islege bagly)
- Bir ýa-da birnäçe abuna üçin dürli baglanyşyklar döredýär
- Statik URL bilen birleşdirilen abuna döredýär
- Birnäçe `3x-ui` node-ny dolandyrýar
- Node autentifikasiýasyny login/password ýa-da token arkaly goldaýar
- Panel URL-den node IP-sini, ýurduny we baýdagyny awtomatiki kesgitleýär
- Her inbound üçin node, relay serwer, baýdak, SNI we port saýlamaga mümkinçilik berýär
- Hemişelik porty ýa-da `random` bahasyny goldaýar
- Custom baglanyşyklary goldaýar: taýýar daşarky linki abuna goşup bolýar
- Hysteria2 UDP üçin `fullchain.pem` we `privkey.pem` ýollaryny aýratyn görkezmäge mümkinçilik berýär
- Öz domen `whitelist` sanawyňyzy goldaýar
- Relay forwarding-i awtomatiki sazlamak mümkinçiligi bar
- Web UI HTTP ýa-da HTTPS arkaly gurnalýar: Let's Encrypt, self-signed ýa-da öz şahadatnamalaryňyz
## Talaplar
- Ubuntu 20.04 ýa-da täze
- `3x-ui` paneli
- Domain + SSL şahadatnamasy (islege bagly)
- Ubuntu 20.04 ýa-da täze, Debian 12.11 ýa-da täze
- `3x-ui` paneli v2.8.4 ýa-da täze
- Serwerde root elýeterliligi
- Docker we Docker Compose; ýok bolsa, gurnama skripti olary awtomatiki gurnamaga synanyşar
- Domen + SSL şahadatnamasy (islege bagly)
---
## Gurnama
Taslamany serwera gurnamak üçin şu komandany ýerine ýetiriň:
`3x-ui` dolandyryş paneli öňünden gurnalan bolmaly. Ony şu komanda bilen gurnap bilersiňiz: `bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
Taslamany serwere gurnaň:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/install.sh)
```
<sup>Gysgaça: gurnama skripti işledilýär we konteýnerler we hyzmatlar döredilýär.</sup>
Gurnama wagtynda skript:
## Täzelik
- OS, root elýeterliligi, Docker we Docker Compose-y barlaýar;
- RAM az we swap ýok bolsa, 2 GB swap faýl döredýär;
- Web UI elýeterlilik görnüşini saýladýar:
- Let's Encrypt arkaly HTTPS;
- self-signed şahadatnama bilen HTTPS;
- öz şahadatnamalaryňyz bilen HTTPS;
- şifrlemesiz HTTP;
- Web UI üçin tötänleýin port döredýär;
- administrator login we password döredýär;
- `postgres`, `backend` we `frontend` konteýnerlerini işe goýberýär.
Soňky wersiýa çenli täzeläň:
Gurnama tamamlanandan soň terminalda URL, login we password görkeziler. Password-y derrew 3DP-MANAGER sazlamalarynda üýtgediň.
<sup>Gysgaça: interaktiw gurnama skriptini işledýär, gurşawy taýýarlaýar we taslamanyň konteýnerlerini ýerleşdirýär.</sup>
## Täzelemek
Soňky wersiýa çenli täzelemek:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/update.sh)
```
<sup>Gysgaça: soňky üýtgeşmeleri çekýär we konteýnerleri gaýtadan işledýär.</sup>
<sup>Gysgaça: soňky üýtgeşmeleri alýar, laýyk konfigurasiýa düzedişlerini ulanýar, konteýnerleri täzeleýär we hyzmaty gaýtadan işledýär.</sup>
## Pozmak
Hyzmaty doly pozmak üçin:
Hyzmaty doly pozmak:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/delete.sh)
```
<sup>Gysgaça: konteýnerleri we konfigurasiýa faýllaryny pozup, systemany gurnamadan öňki ýagdaýyna getirer.</sup>
<sup>Gysgaça: konteýnerleri we konfigurasiýa faýllaryny pozýar, ulgamy gurnamadan öňki ýagdaýa getirýär.</sup>
---
## Forwarding hyzmatyny gurnamak
## Ilkinji Giriş
Forwarding hyzmaty aragatnaşyk serwerinden esasy servere gelýän portlary proxy arkaly geçirýär.
Administrator login we password gurnamanyň ahyrynda görkezilýär. Olary gaýtadan görmek üçin:
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)
grep -E "ADMIN_LOGIN|ADMIN_PASSWORD" /opt/3dp-manager/docker-compose.yml | sed 's/^[ \t]*//; s/^- //'
```
## Forwarding-i pozmak
Web UI gurnawçynyň görkezen salgysy boýunça elýeterlidir, mysal üçin:
- HTTPS üçin `https://example.com:PORT`;
- HTTP üçin `http://SERVER_IP:PORT`.
Eger `ufw` işjeň bolsa, gurnawçy inbound üçin iş portlaryny açýar: TCP/UDP üçin `443`, `8443` we `10000-60000`.
---
## Node-lar
**Node-lar** bölümi bir ýa-da birnäçe `3x-ui` panelini birikdirmäge mümkinçilik berýär.
Her node üçin görkezilýär:
- ady;
- `3x-ui` panel URL-i;
- node IP-si;
- baýdak/ýurt;
- autentifikasiýa görnüşi: `password` ýa-da `token`;
- esasy node bolup durýandygy.
URL girizilenden soň programma node IP-sini we ýurduny awtomatiki kesgitlemäge synanyşýar. Baýdak abunanyň içindäki baglanyşyk atlarynda ulanylýar, müşderide serwerleri tapawutlandyrmak aňsat bolýar.
> [!NOTE]
> Esasy node abunalar, inbound-lar we relay serwerler üçin deslapky baha hökmünde ulanylýar.
---
## Abunalar
**Abunalar** bölümi statik abuna URL-lerini we inbound düzümini dolandyrýar.
Her inbound üçin sazlap bolýar:
- baglanyşyk görnüşi;
- node;
- relay serwer;
- baýdak;
- port: `1-65535` aralygyndaky anyk san ýa-da `random`;
- SNI: anyk domen ýa-da `random`;
- `custom` görnüşi üçin taýýar daşarky link.
`hysteria2-udp` üçin şahadatnama we açar ýollaryny aýratyn görkezmek bolýar:
- `certificateFile`, mysal üçin `/root/cert/example.com/fullchain.pem`;
- `keyFile`, mysal üçin `/root/cert/example.com/privkey.pem`.
Port ýa-da SNI `random` bolsa, baha rotasiýa wagtynda elýeterli aralykdan ýa-da domen whitelist-den saýlanar.
---
## Forwarding Hyzmatyny Gurnamak
> [!WARNING]
> Forwarding hyzmaty aralyk serwerde işleýär
Forwarding hyzmaty aralyk serweriň gelýän portlaryny saýlanan node-a proxy edýär. Web UI-de şeýle serwerler **Relay serwerler** bölüminde sazlanýar we belli bir node bilen baglanyşdyrylyp bilýär.
Relay serwer IP ýa-da domen boýunça goşulyp bilner. Domen görkezilse, backend onuň IP-sini awtomatiki çözmäge synanyşar.
Aralyk serwerde forwarding-i el bilen gurnamak üçin `IP_ADDRESS` ýerine esasy node IP-sini goýuň:
```bash
sudo ORIGIN_IP="IP_ADDRESS" bash -c "$(curl -sSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_install.sh)"
```
<sup>Gysgaça: forwarding düzgünlerini goşýar.</sup>
## Forwarding-i Pozmak
```bash
bash <(curl -fsSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_delete.sh)
```
<sup>Gysgaça: forwarding düzgünlerini pozýar. Pozlandan soň üýtgeşmeler güýje girmegi üçin firewall-y `ufw reload` bilen täzeden ýükläň we ulgamy `reboot` bilen täzeden işlediň.</sup>
---
## Abuna URL-ni görkezmek
## Multi-Abunalardan Domenleri Toplamak
Konteýner gurşawynda häzirki abuna URL-ni görkezýän komanda:
```bash
cd /opt/3dp-manager && docker compose exec node env | grep SUB_URL | cut -d'=' -f2
```
## Multi-abunalardan domenleri toplamak
Gural birden köp konfigurasiýa içeren abunalardan domenleri çykaryp `whitelist` düzýär.
Gural abunalardan domenleri çykaryp, generator üçin `whitelist` düzýär.
```bash
node get_domains.js
```
## Öz `whitelist`-iňizi ulanmak
1. `whitelist.txt` bilen meňzeş struktura eýe faýl taýýarlaň.
2. Ony `my_whitelist.txt` diýip atlandyryp `/opt/3dp-manager/app` içine göçüriň.
```bash
cd /opt/3dp-manager && docker cp ./app/my_whitelist.txt node:/app/my_whitelist.txt
```
<sup>Gysgaça: skripte multi-abuna linkini goşuň we komandany işlediň. Netijede domenleriň sanawy çykýar. Skript üçin `Node.js` gerek.</sup>
---
## Bellikler we çäklendirmeler
## Bellikler We Häzirki Çäklendirmeler
- Umumy domen sanawy ähli üpjün edijilerde işlemeýär; öz `whitelist`-iňizi düzmegiňizi maslahat berýäris.
- Umumy domen sanawy ähli prowaýderlerde işlemeýär, şonuň üçin öz whitelist sanawyňyzy taýýarlamak we ulanmak maslahat berilýär.
---
## Goşanty
## Goşant
Proýekte goşant bermäge hoş geldiňiz! Goşant prosesi ýönekeý:
Taslama goşantlaryňyza hoşal bolarys! Goşantçylar üçin ýönekeý proses:
1. GitHub-da repo-ny fork ediň.
2. Meni manly at bilen şahamça (branch) dörediň, meselem `feature/add-README` ýa-da `fix/whitelist-load`.
3. Üýtgeşmeleri giriziň we gysga commit ýazmagy unutmaň.
4. Lokal barlaglary işlediň (bardy bolsa).
5. Şahamçany fork-a iteriň we Pull Request dörediň.
1. GitHub-da repozitoriýany fork ediň.
2. Manyly at bilen branch dörediň, mysal üçin `feature/add-README` ýa-da `fix/whitelist-load`.
3. Üýtgeşmeleri giriziň we commit-de gysga düşündiriş ýazyň.
4. Bar bolsa, lokal barlaglary işlediň.
5. Branch-i öz fork-uňyza push ediň we esasy repozitoriýa Pull Request dörediň.
<sup>Maslahat: PR-de üýtgeşmeleri, maksady we test ädimlerini ýazyň. Üýtgeşmeler uly bolsa, olary kiçi commit-lere bölüň.</sup>
---
## Çeperdeşlik
## Ara Alyp Maslahatlaşmak
- Telegram: [@denpiligrim_web](https://t.me/denpiligrim_web)
- Issues
- Şu repozitoriýanyň Issues bölümi
+1 -1
View File
@@ -10,7 +10,7 @@ COPY . .
ENV VITE_API_URL=/api
ENV VITE_LOG_LEVEL=debug
ENV VITE_SEND_LOGS_TO_BACKEND=true
ENV VITE_APP_VERSION=2.1.0
ENV VITE_APP_VERSION=2.2.0
RUN npm run build
+4 -1
View File
@@ -1,9 +1,12 @@
<!doctype html>
<html lang="en">
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link data-rh="true" rel="icon" href="/img/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
<title>3DP-MANAGER</title>
</head>
<body>
+3 -1
View File
@@ -11,6 +11,7 @@ import NotFoundPage from './pages/NotFoundPage';
import { AxiosInterceptor } from './auth/AxiosInterceptor';
import PublicRoute from './auth/PublicRoute';
import TunnelsPage from './pages/TunnelsPage';
import NodesPage from './pages/NodesPage';
function App() {
return (
@@ -31,6 +32,7 @@ function App() {
<Route index element={<SubscriptionsPage />} />
<Route path="settings" element={<SettingsPage />} />
<Route path="domains" element={<DomainsPage />} />
<Route path="nodes" element={<NodesPage />} />
<Route path="tunnels" element={<TunnelsPage />} />
</Route>
<Route path="*" element={<NotFoundPage />} />
@@ -41,4 +43,4 @@ function App() {
);
}
export default App;
export default App;
+29 -21
View File
@@ -1,9 +1,17 @@
import {
Toolbar, Drawer, List, ListItem,
ListItemButton, ListItemIcon, ListItemText, Box, useMediaQuery, useTheme
Box,
Drawer,
List,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
Toolbar,
useMediaQuery,
useTheme,
} from '@mui/material';
import { People, Settings, Dns, SwapHoriz } from '@mui/icons-material';
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
import { Dns, Hub, People, Settings, SwapHoriz } from '@mui/icons-material';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useState } from 'react';
import Header from './Header';
@@ -13,6 +21,14 @@ import { useSecureConnection } from '../utils/useSecureConnection';
const drawerWidth = 240;
const menuItems = [
{ text: 'Подписки', icon: <People />, path: '/' },
{ text: 'Ноды', icon: <Hub />, path: '/nodes' },
{ text: 'Relay серверы', icon: <SwapHoriz />, path: '/tunnels' },
{ text: 'Домены', icon: <Dns />, path: '/domains' },
{ text: 'Настройки', icon: <Settings />, path: '/settings' },
];
export default function Layout() {
const navigate = useNavigate();
const location = useLocation();
@@ -22,23 +38,16 @@ export default function Layout() {
const { isSecure } = useSecureConnection();
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
setMobileOpen((prev) => !prev);
};
const menuItems = [
{ text: 'Подписки', icon: <People />, path: '/' },
{ text: 'Домены', icon: <Dns />, path: '/domains' },
{ text: 'Перенаправление', icon: <SwapHoriz />, path: '/tunnels' },
{ text: 'Настройки', icon: <Settings />, path: '/settings' },
];
const drawerContent = (
<Box sx={{ overflow: 'auto' }}>
<Toolbar />
<List>
{menuItems.map((item) => (
<ListItem key={item.text} disablePadding>
<ListItemButton
<ListItemButton
selected={location.pathname === item.path}
onClick={() => {
navigate(item.path);
@@ -56,11 +65,10 @@ export default function Layout() {
return (
<Box sx={{ display: 'flex', minHeight: '100vh', width: '100%' }}>
{/* Передаем функцию открытия в Header */}
<Header onMenuClick={handleDrawerToggle} isMobile={isMobile} />
<Drawer
variant={isMobile ? "temporary" : "permanent"}
variant={isMobile ? 'temporary' : 'permanent'}
open={isMobile ? mobileOpen : true}
onClose={handleDrawerToggle}
sx={{
@@ -72,15 +80,15 @@ export default function Layout() {
{drawerContent}
</Drawer>
<Box
component="main"
sx={{
flexGrow: 1,
<Box
component="main"
sx={{
flexGrow: 1,
display: 'flex',
flexDirection: 'column',
minHeight: '100vh',
width: '100%',
overflowX: 'hidden'
overflowX: 'hidden',
}}
>
<Toolbar />
@@ -92,4 +100,4 @@ export default function Layout() {
</Box>
</Box>
);
}
}
+62
View File
@@ -0,0 +1,62 @@
import api from '../../api';
import type { NodePayload, NodeRecord } from '../../types/node';
export const nodesApi = {
async list() {
const { data } = await api.get<NodeRecord[]>('/nodes');
return data;
},
async create(payload: NodePayload) {
const { data } = await api.post<NodeRecord>('/nodes', payload);
return data;
},
async update(id: string, payload: Partial<NodePayload>) {
const { data } = await api.put<NodeRecord>(`/nodes/${id}`, payload);
return data;
},
async remove(id: string) {
const { data } = await api.delete<{ success: boolean }>(`/nodes/${id}`);
return data;
},
async setMain(id: string) {
const { data } = await api.post<NodeRecord>(`/nodes/${id}/main`);
return data;
},
async check(id: string) {
const { data } = await api.post<{ success: boolean; version?: string }>(
`/nodes/${id}/check`,
);
return data;
},
async checkPayload(payload: NodePayload) {
const { data } = await api.post<{ success: boolean; version?: string }>(
'/nodes/check',
payload,
);
return data;
},
async detectLocation(url: string) {
const { data } = await api.post<{
ip?: string;
host?: string;
flag?: string;
country?: string;
countryCode?: string;
}>('/nodes/detect-location', { url });
return data;
},
async syncFromMain() {
const { data } = await api.post<{ success: boolean; count: number }>(
'/nodes/sync/main',
);
return data;
},
};
+14 -1
View File
@@ -1,3 +1,16 @@
html {
font-family: "Inter", "Roboto", "Helvetica", "Arial", sans-serif;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
font-family: inherit;
}
.animated-container {
background: linear-gradient(-45deg, #111827, #15122c, #24243e, #0B0F19);
background-size: 400% 400%;
@@ -32,4 +45,4 @@
input:autofill {
background: transparent;
}
}
+1
View File
@@ -4,6 +4,7 @@ import './index.css'
import '@fontsource/inter/300.css';
import '@fontsource/inter/400.css';
import '@fontsource/inter/500.css';
import '@fontsource/inter/600.css';
import '@fontsource/inter/700.css';
import App from './App.tsx'
+8
View File
@@ -50,6 +50,7 @@ export default function DomainsPage() {
const [domains, setDomains] = useState<Domain[]>([]);
const [newDomain, setNewDomain] = useState('');
const fileInputRef = useRef<HTMLInputElement>(null);
const emptyDomainsNotified = useRef(false);
const [totalCount, setTotalCount] = useState(0);
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
@@ -203,6 +204,13 @@ export default function DomainsPage() {
setDomains(data.data);
setTotalCount(data.total);
if (data.total === 0 && !emptyDomainsNotified.current) {
emptyDomainsNotified.current = true;
setSnackbar({ open: true, type: 'error', message: 'Создайте хотя бы один домен!' });
}
if (data.total > 0) {
emptyDomainsNotified.current = false;
}
Logger.debug(`Loaded ${data.data.length} domains (total: ${data.total})`, 'Domains');
} catch (error) {
Logger.error('Failed to load', 'Domains', error);
+471
View File
@@ -0,0 +1,471 @@
import { useCallback, useEffect, useState } from 'react';
import {
Alert,
Box,
Button,
Chip,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
FormHelperText,
IconButton,
InputLabel,
MenuItem,
Paper,
Select,
Snackbar,
Stack,
Switch,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
Typography,
} from '@mui/material';
import {
Add,
CheckCircle,
Delete,
Edit,
Star,
StarBorder,
Sync,
} from '@mui/icons-material';
import api from '../api';
import { nodesApi } from '../features/nodes/api';
import type { NodeAuthType, NodePayload, NodeRecord } from '../types/node';
import { getApiErrorMessage } from '../utils/errorHandlers';
import { FlagIcon, FlagOptionLabel } from '../utils/flags';
const emptyForm: NodePayload = {
name: '',
url: '',
ip: '',
flag: '',
authType: 'token',
login: '',
password: '',
token: '',
isMain: false,
};
interface CountryOption {
name: string;
code: string;
emoji: string;
}
const isValidIp = (value?: string) =>
!!value &&
(/^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(value.trim()) ||
/^([0-9a-f]{1,4}:){2,7}[0-9a-f]{1,4}$/i.test(value.trim()));
export default function NodesPage() {
const [nodes, setNodes] = useState<NodeRecord[]>([]);
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState<NodeRecord | null>(null);
const [form, setForm] = useState<NodePayload>(emptyForm);
const [checkingId, setCheckingId] = useState<string | null>(null);
const [countries, setCountries] = useState<CountryOption[]>([]);
const [detectingLocation, setDetectingLocation] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<NodeRecord | null>(null);
const [formErrors, setFormErrors] = useState<Partial<Record<keyof NodePayload, string>>>({});
const [message, setMessage] = useState({
open: false,
type: 'success' as 'success' | 'error',
text: '',
});
const loadNodes = useCallback(async () => {
const data = await nodesApi.list();
setNodes(Array.isArray(data) ? data : []);
}, []);
useEffect(() => {
loadNodes();
api.get<CountryOption[]>('/settings/countries').then((res) => setCountries(Array.isArray(res.data) ? res.data : []));
}, [loadNodes]);
const openCreate = () => {
setEditing(null);
setForm(emptyForm);
setFormErrors({});
setOpen(true);
};
const openEdit = (node: NodeRecord) => {
setEditing(node);
setForm({
name: node.name,
url: node.url || '',
ip: node.ip || '',
flag: node.flag || '',
authType: node.authType,
login: node.login || '',
password: '',
token: '',
isMain: node.isMain,
version: node.version || '',
});
setFormErrors({});
setOpen(true);
};
const updateField = <K extends keyof NodePayload>(key: K, value: NodePayload[K]) => {
setForm((prev) => ({ ...prev, [key]: value }));
setFormErrors((prev) => ({ ...prev, [key]: undefined }));
};
const validateForm = (requireSecrets = !editing) => {
const errors: Partial<Record<keyof NodePayload, string>> = {};
if (!form.name.trim()) errors.name = 'Введите название ноды';
if (!form.url.trim()) errors.url = 'Введите URL панели 3x-ui';
if (!isValidIp(form.ip)) errors.ip = 'Введите корректный IP ноды';
if (!form.flag) errors.flag = 'Выберите флаг ноды';
if (form.authType === 'password') {
if (!form.login?.trim()) errors.login = 'Введите логин';
if (requireSecrets && !form.password?.trim()) errors.password = 'Введите пароль';
}
if (form.authType === 'token' && requireSecrets && !form.token?.trim()) {
errors.token = 'Введите токен';
}
setFormErrors(errors);
return Object.keys(errors).length === 0;
};
const detectNodeLocation = async () => {
const url = form.url.trim();
if (!url) return;
setDetectingLocation(true);
try {
const result = await nodesApi.detectLocation(url.replace(/\/+$/, ''));
setForm((prev) => ({
...prev,
ip: result.ip || prev.ip,
flag: result.flag || prev.flag,
}));
if (result.country || result.ip) {
setMessage({
open: true,
type: 'success',
text: `Определено: ${result.country || 'страна неизвестна'}${result.ip ? `, IP ${result.ip}` : ''}`,
});
}
} catch {
setMessage({ open: true, type: 'error', text: 'Не удалось определить страну ноды' });
} finally {
setDetectingLocation(false);
}
};
const saveNode = async () => {
if (!validateForm(!editing)) {
setMessage({ open: true, type: 'error', text: 'Заполните обязательные поля' });
return;
}
const payload: NodePayload = {
...form,
url: form.url.replace(/\/+$/, ''),
ip: form.ip || undefined,
flag: form.flag || undefined,
login: form.authType === 'password' ? form.login : undefined,
password: form.authType === 'password' && form.password ? form.password : undefined,
token: form.authType === 'token' && form.token ? form.token : undefined,
};
try {
if (editing) {
await nodesApi.update(editing.id, payload);
} else {
await nodesApi.create(payload);
}
setOpen(false);
setMessage({
open: true,
type: 'success',
text: editing ? 'Нода обновлена' : 'Нода добавлена',
});
loadNodes();
} catch (error: unknown) {
const text =
(error as { response?: { data?: { message?: string } } })?.response?.data?.message ||
'Не удалось сохранить ноду';
setMessage({ open: true, type: 'error', text });
}
};
const checkFormConnection = async () => {
if (!validateForm(true)) {
setMessage({ open: true, type: 'error', text: 'Заполните обязательные поля для проверки подключения' });
return;
}
const result = await nodesApi.checkPayload({
...form,
url: form.url.replace(/\/+$/, ''),
login: form.authType === 'password' ? form.login : undefined,
password: form.authType === 'password' ? form.password : undefined,
token: form.authType === 'token' ? form.token : undefined,
});
setMessage({
open: true,
type: result.success ? 'success' : 'error',
text: result.success ? 'Подключение успешно' : 'Не удалось подключиться',
});
};
const checkNode = async (node: NodeRecord) => {
setCheckingId(node.id);
try {
const result = await nodesApi.check(node.id);
setMessage({
open: true,
type: result.success ? 'success' : 'error',
text: result.success ? 'Подключение успешно' : 'Не удалось подключиться',
});
loadNodes();
} finally {
setCheckingId(null);
}
};
const syncNodes = async () => {
const result = await nodesApi.syncFromMain();
setMessage({
open: true,
type: 'success',
text: `Синхронизировано нод: ${result.count}`,
});
loadNodes();
};
const removeNode = async () => {
if (!deleteTarget) return;
try {
await nodesApi.remove(deleteTarget.id);
setDeleteTarget(null);
setMessage({ open: true, type: 'success', text: 'Нода удалена' });
loadNodes();
} catch (error) {
setMessage({
open: true,
type: 'error',
text: getApiErrorMessage(error, 'Ошибка удаления ноды'),
});
}
};
return (
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3, gap: 2 }}>
<Box>
<Typography variant="h4">Ноды</Typography>
</Box>
<Box>
<Stack direction="row" spacing={1}>
{/* <Button startIcon={<Sync />} variant="outlined" onClick={syncNodes}>
Синхронизировать
</Button> */}
<Button startIcon={<Add />} variant="contained" onClick={openCreate}>
Добавить
</Button>
</Stack>
</Box>
</Box>
<Paper sx={{ overflowX: 'auto' }}>
<Table>
<TableHead>
<TableRow>
<TableCell>Название</TableCell>
<TableCell>Флаг</TableCell>
<TableCell>IP</TableCell>
<TableCell>URL панели</TableCell>
<TableCell>Авторизация</TableCell>
<TableCell>Статус</TableCell>
<TableCell align="right">Действия</TableCell>
</TableRow>
</TableHead>
<TableBody>
{nodes.map((node) => (
<TableRow key={node.id}>
<TableCell>
<Stack direction="row" spacing={1} alignItems="center">
<IconButton size="small" onClick={() => nodesApi.setMain(node.id).then(loadNodes)} title={node.isMain ? '' : 'Сделать основной'}>
{node.isMain ? <Star color="warning" /> : <StarBorder />}
</IconButton>
<Typography fontWeight={700}>{node.name}</Typography>
</Stack>
</TableCell>
<TableCell>
<FlagIcon flag={node.flag} />
</TableCell>
<TableCell>{node.ip || '-'}</TableCell>
<TableCell>{node.url}</TableCell>
<TableCell>{node.authType}</TableCell>
<TableCell>
{node.isMain && <Chip icon={<CheckCircle />} label="Основная" color="success" size="small" />}
</TableCell>
<TableCell align="right">
{/* <IconButton disabled={checkingId === node.id} onClick={() => checkNode(node)}>
{checkingId === node.id ? <CircularProgress size={20} /> : <CheckCircle />}
</IconButton> */}
<IconButton onClick={() => openEdit(node)}>
<Edit />
</IconButton>
<IconButton color="error" onClick={() => setDeleteTarget(node)}>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
{nodes.length === 0 && (
<TableRow>
<TableCell colSpan={7} align="center" sx={{ color: 'text.secondary' }}>
Ноды не добавлены
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</Paper>
<Dialog open={open} onClose={() => setOpen(false)} maxWidth="sm" fullWidth>
<DialogTitle>{editing ? 'Редактировать ноду' : 'Новая нода'}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
<TextField
label="Название"
required
value={form.name}
onChange={(e) => updateField('name', e.target.value)}
error={!!formErrors.name}
helperText={formErrors.name}
/>
<TextField
label="URL панели 3x-ui"
required
helperText={formErrors.url || 'Например: https://85.198.84.27:35366/2vIsDA5HanQ3R7JyIH'}
value={form.url}
onChange={(e) => updateField('url', e.target.value)}
onBlur={detectNodeLocation}
error={!!formErrors.url}
InputProps={{ endAdornment: detectingLocation ? <CircularProgress size={18} /> : undefined }}
/>
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
<TextField
label="IP ноды"
required
fullWidth
value={form.ip || ''}
onChange={(e) => updateField('ip', e.target.value)}
error={!!formErrors.ip}
helperText={formErrors.ip}
/>
<FormControl fullWidth required error={!!formErrors.flag}>
<InputLabel>Флаг</InputLabel>
<Select
value={form.flag || ''}
label="Флаг"
onChange={(e) => updateField('flag', e.target.value)}
renderValue={(value) => (
<FlagOptionLabel flag={value} label={countries.find((country) => country.emoji === value)?.name || 'Флаг'} />
)}
>
<MenuItem value="">Без флага</MenuItem>
{countries.map((country) => (
<MenuItem key={country.code} value={country.emoji}>
<FlagOptionLabel flag={country.emoji} code={country.code} label={country.name} />
</MenuItem>
))}
</Select>
{formErrors.flag && <FormHelperText>{formErrors.flag}</FormHelperText>}
</FormControl>
</Stack>
<FormControl fullWidth required>
<InputLabel>Тип авторизации</InputLabel>
<Select
value={form.authType}
label="Тип авторизации"
onChange={(e) => updateField('authType', e.target.value as NodeAuthType)}
>
<MenuItem value="password">Логин и пароль</MenuItem>
<MenuItem value="token">Токен</MenuItem>
</Select>
</FormControl>
{form.authType === 'password' ? (
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
<TextField
label="Логин"
required
fullWidth
value={form.login || ''}
onChange={(e) => updateField('login', e.target.value)}
error={!!formErrors.login}
helperText={formErrors.login}
/>
<TextField
label={editing ? 'Новый пароль' : 'Пароль'}
type="password"
required={!editing}
fullWidth
value={form.password || ''}
onChange={(e) => updateField('password', e.target.value)}
error={!!formErrors.password}
helperText={formErrors.password || (editing ? 'Оставьте пустым, чтобы не менять пароль' : undefined)}
/>
</Stack>
) : (
<TextField
label={editing ? 'Новый токен' : 'Токен'}
type="password"
required={!editing}
value={form.token || ''}
onChange={(e) => updateField('token', e.target.value)}
error={!!formErrors.token}
helperText={formErrors.token || (editing ? 'Оставьте пустым, чтобы не менять токен' : undefined)}
/>
)}
<Stack direction="row" alignItems="center" spacing={1}>
<Switch checked={!!form.isMain} onChange={(e) => updateField('isMain', e.target.checked)} />
<Typography>Сделать основной нодой</Typography>
</Stack>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={checkFormConnection}>Проверить подключение</Button>
<Button onClick={() => setOpen(false)}>Отмена</Button>
<Button variant="contained" onClick={saveNode}>Сохранить</Button>
</DialogActions>
</Dialog>
<Dialog open={!!deleteTarget} onClose={() => setDeleteTarget(null)}>
<DialogTitle>Удалить ноду?</DialogTitle>
<DialogContent>
<Typography>Вы уверены, что хотите удалить ноду {deleteTarget?.name}?</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteTarget(null)}>Отмена</Button>
<Button color="error" variant="contained" onClick={removeNode}>Удалить</Button>
</DialogActions>
</Dialog>
<Snackbar open={message.open} autoHideDuration={5000} onClose={() => setMessage({ ...message, open: false })}>
<Alert severity={message.type}>{message.text}</Alert>
</Snackbar>
</Box>
);
}
+66 -576
View File
@@ -1,615 +1,105 @@
import React, { useEffect, useState, useCallback } from 'react';
import { Box, TextField, Button, Typography, Paper, Snackbar, Alert, Grid, Divider, InputAdornment, Stack, Chip, Tooltip, IconButton, useTheme, useMediaQuery, Dialog, DialogTitle, DialogContent, DialogActions, List, ListItem, FormControlLabel, Checkbox } from '@mui/material';
import { type ChangeEvent, useCallback, useEffect, useState } from 'react';
import {
Alert,
Box,
Button,
Divider,
Paper,
Snackbar,
Stack,
TextField,
Typography,
} from '@mui/material';
import api from '../api';
import { CheckCircle, PauseCircleFilled, PlayCircleFilled, Refresh } from '@mui/icons-material';
import { Logger } from '../utils/logger';
const ROTATION_PRESETS = [
{ label: 'Сутки', value: 1440 },
{ label: '3 дня', value: 4320 },
{ label: 'Неделя', value: 10080 },
];
interface Subscription {
id: string;
name: string;
uuid: string;
isAutoRotationEnabled?: boolean;
}
export default function SettingsPage() {
const [settings, setSettings] = useState({
xui_url: '',
xui_login: '',
xui_password: '',
rotation_interval: '30',
rotation_status: 'active',
last_rotation_timestamp: '',
});
const [adminProfile, setAdminProfile] = useState({
login: '',
password: '',
});
const [subs, setSubs] = useState<Subscription[]>([]);
const [msg, setMsg] = useState({ open: false, type: 'success' as 'success' | 'error', text: '' });
const [loadingRotate, setLoadingRotate] = useState<boolean>(false);
const [confirmDialog, setConfirmDialog] = useState({
open: false, title: '', onConfirm: () => {},
confirmText: 'Удалить', confirmColor: 'error' as 'error' | 'primary'
const [message, setMessage] = useState({
open: false,
type: 'success' as 'success' | 'error',
text: '',
});
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
const loadSettings = useCallback(async () => {
const loadProfile = useCallback(async () => {
try {
Logger.debug('Loading settings...', 'Settings');
const { data } = await api.get('/settings');
Logger.debug('Settings API response', 'Settings', data);
setSettings((prev) => ({ ...prev, ...data }));
Logger.debug('Settings after update', 'Settings', {
rotation_interval: data.rotation_interval,
prev_interval: prev => prev.rotation_interval
});
const { data } = await api.get<Record<string, string>>('/settings');
if (data.admin_login) {
setAdminProfile((prev) => ({ ...prev, login: data.admin_login }));
}
Logger.debug('Settings loaded successfully', 'Settings');
} catch (error) {
Logger.error('Failed to load', 'Settings', error);
}
}, []);
const loadSubscriptions = useCallback(async () => {
try {
Logger.debug('Loading subscriptions...', 'Settings');
const { data } = await api.get('/subscriptions');
setSubs(data);
Logger.debug(`Loaded ${data.length} subscriptions`, 'Settings');
} catch (error) {
Logger.error('Failed to load subscriptions', 'Settings', error);
Logger.error('Failed to load profile settings', 'Settings', error);
}
}, []);
useEffect(() => {
loadSettings();
loadSubscriptions();
}, [loadSettings, loadSubscriptions]);
loadProfile();
}, [loadProfile]);
const getIntervalError = () => {
const val = parseInt(settings.rotation_interval, 10);
if (isNaN(val) || val < 10) {
return 'Минимальный интервал — 10 минут';
}
return '';
};
const handleChange =
(field: 'login' | 'password') =>
(event: ChangeEvent<HTMLInputElement>) => {
setAdminProfile((prev) => ({ ...prev, [field]: event.target.value }));
};
const cleanData = () => {
const cleaned = { ...settings };
if (cleaned.xui_url) {
cleaned.xui_url = cleaned.xui_url.replace(/\/+$/, '');
}
if (cleaned.xui_login) cleaned.xui_login = cleaned.xui_login.trim();
if (cleaned.xui_password) cleaned.xui_password = cleaned.xui_password.trim();
setSettings(prev => ({ ...prev, ...cleaned }));
return cleaned;
};
const handleCheckConnection = async () => {
const data = cleanData();
try {
Logger.debug(`Checking connection to: ${data.xui_url}`, 'Settings');
setMsg({ open: true, type: 'success', text: 'Проверка...' });
const res = await api.post('/settings/check', {
xui_url: data.xui_url,
xui_login: data.xui_login,
xui_password: data.xui_password
});
if (res.data.success) {
Logger.debug('Connection check: SUCCESS', 'Settings');
setMsg({
open: true,
type: 'success',
text: 'Подключение успешно!'
});
} else {
Logger.warn('Connection check: FAILED', 'Settings', res.data);
setMsg({
open: true,
type: 'error',
text: 'Ошибка: Неверные данные или нет доступа'
});
}
} catch (error) {
Logger.error('Connection check error', 'Settings', error);
setMsg({ open: true, type: 'error', text: 'Ошибка сети при проверке' });
}
};
const handleSettingChange = useCallback((prop: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
setSettings(prev => ({ ...prev, [prop]: event.target.value }));
}, []);
const handlePresetClick = (minutes: number) => {
setSettings(prev => ({ ...prev, rotation_interval: minutes.toString() }));
};
const handleSaveSettings = async () => {
// Валидация полей подключения к 3x-ui
if (!settings.xui_url || !settings.xui_login || !settings.xui_password) {
setMsg({
open: true,
text: 'Заполните все поля подключения к 3x-ui (URL, логин, пароль)',
type: 'error'
});
return;
}
if (getIntervalError()) {
setMsg({ open: true, text: 'Исправьте ошибки перед сохранением', type: 'error' });
return;
}
const data = cleanData();
try {
Logger.debug('Saving settings', 'Settings', {
xui_url: data.xui_url ? '***' : 'empty',
xui_login: data.xui_login,
rotation_interval: data.rotation_interval
});
await api.post('/settings', data);
Logger.debug('Settings saved successfully', 'Settings');
setMsg({ open: true, type: 'success', text: 'Настройки сохранены!' });
} catch (error) {
Logger.error('Save error', 'Settings', error);
setMsg({ open: true, type: 'error', text: 'Ошибка сохранения' });
}
};
const handleSaveInterval = async () => {
if (getIntervalError()) {
setMsg({ open: true, text: 'Неверный интервал (минимум 10 минут)', type: 'error' });
const handleSave = async () => {
if (!adminProfile.login.trim()) {
setMessage({ open: true, type: 'error', text: 'Login is required' });
return;
}
try {
Logger.debug('Saving rotation interval', 'Settings', {
rotation_interval: settings.rotation_interval
});
await api.post('/settings', {
rotation_interval: settings.rotation_interval
});
Logger.debug('Rotation interval saved successfully', 'Settings');
setMsg({ open: true, type: 'success', text: 'Интервал генерации применён!' });
} catch (error) {
Logger.error('Save interval error', 'Settings', error);
setMsg({ open: true, type: 'error', text: 'Ошибка сохранения интервала' });
}
};
const handleAdminChange = useCallback((prop: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
setAdminProfile(prev => ({ ...prev, [prop]: event.target.value }));
}, []);
const handleSaveAdmin = async () => {
try {
Logger.debug('Updating admin profile', 'Settings', { login: adminProfile.login });
await api.post('/auth/update-profile', adminProfile);
Logger.debug('Admin profile updated', 'Settings');
setMsg({ open: true, type: 'success', text: 'Профиль администратора обновлен!' });
setAdminProfile(prev => ({ ...prev, password: '' }));
setAdminProfile((prev) => ({ ...prev, password: '' }));
setMessage({ open: true, type: 'success', text: 'Profile updated' });
} catch (error) {
Logger.error('Update admin profile error', 'Settings', error);
setMsg({ open: true, type: 'error', text: 'Ошибка обновления профиля' });
Logger.error('Update profile error', 'Settings', error);
setMessage({ open: true, type: 'error', text: 'Failed to update profile' });
}
};
const handleForceRotate = async () => {
setConfirmDialog({
open: true,
title: 'ВНИМАНИЕ: Это немедленно обновит конфиги в подписках.\n\nИнтервал автоматической ротации НЕ будет сброшен.\n\nПродолжить?',
confirmText: 'Сгенерировать',
confirmColor: 'primary',
onConfirm: async () => {
try {
Logger.debug('Starting forced rotation', 'Rotation');
setLoadingRotate(true);
const res = await api.post('/rotation/rotate-all');
setLoadingRotate(false);
if (res.data && res.data.success) {
Logger.debug('Rotation completed successfully', 'Rotation');
setMsg({ open: true, type: 'success', text: res.data.message || 'Ротация успешно выполнена!' });
} else {
Logger.warn('Rotation completed with issues', 'Rotation', res.data?.message);
setMsg({
open: true,
type: 'error',
text: res.data?.message || 'Ошибка выполнения ротации'
});
}
} catch (error) {
setLoadingRotate(false);
Logger.error('Rotation error', 'Rotation', error);
setMsg({ open: true, type: 'error', text: 'Ошибка сети или сервера' });
}
}
});
};
const handleToggleAutoRotation = async (subscriptionId: string, enabled: boolean) => {
try {
await api.put('/subscriptions/bulk-auto-rotation', {
subscriptionIds: [subscriptionId],
enabled
});
setSubs(prev => prev.map(s =>
s.id === subscriptionId ? { ...s, isAutoRotationEnabled: enabled } : s
));
setMsg({
open: true,
type: 'success',
text: enabled ? 'Авторотация включена' : 'Авторотация выключена'
});
} catch (error: unknown) {
const message = (error as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Ошибка обновления';
Logger.error(`Toggle auto-rotation error: ${message}`, 'Settings');
setMsg({ open: true, type: 'error', text: message });
loadSubscriptions();
}
};
const handleManualRotate = async (sub: Subscription) => {
setConfirmDialog({
open: true,
title: `Обновить подписку "${sub.name}" сейчас?`,
confirmText: 'Обновить',
confirmColor: 'primary',
onConfirm: async () => {
try {
Logger.debug(`Starting manual rotation for subscription: ${sub.id}`, 'Settings');
const res = await api.post(`/rotation/rotate-one/${sub.id}`);
Logger.debug('Manual rotation completed', 'Settings');
setMsg({ open: true, type: 'success', text: res.data.message || 'Ротация выполнена' });
loadSubscriptions();
} catch (error: unknown) {
const message = (error as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Ошибка ротации';
Logger.error(`Manual rotation error: ${message}`, 'Settings');
setMsg({ open: true, type: 'error', text: message });
}
}
});
};
const handleBulkUpdate = async (enabled: boolean) => {
try {
const { data } = await api.put('/subscriptions/bulk-auto-rotation', {
subscriptionIds: subs.map(s => s.id),
enabled
});
setMsg({ open: true, type: 'success', text: data.message || 'Настройки обновлены' });
loadSubscriptions();
} catch (error: unknown) {
const message = (error as { response?: { data?: { message?: string } } })?.response?.data?.message || 'Ошибка обновления';
Logger.error(`Bulk update error: ${message}`, 'Settings');
setMsg({ open: true, type: 'error', text: message });
}
};
const togglePause = async () => {
const newStatus = settings.rotation_status === 'active' ? 'stopped' : 'active';
const updatedSettings = { ...settings, rotation_status: newStatus };
Logger.debug(`Toggling rotation status: ${settings.rotation_status}${newStatus}`, 'Settings');
setSettings(updatedSettings);
try {
await api.post('/settings', updatedSettings);
Logger.debug('Rotation status updated', 'Settings');
} catch (error) {
Logger.error('Toggle pause error', 'Settings', error);
setSettings((prev) => ({ ...prev, rotation_status: prev.rotation_status }));
setMsg({ open: true, type: 'error', text: 'Не удалось изменить статус' });
}
};
const formatDate = (isoString: string) => {
if (!isoString) return 'Нет данных';
return new Date(+isoString).toLocaleString('ru-RU', {
day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit'
});
};
const getNextRotationDate = () => {
if (settings.rotation_status === 'stopped') return 'Пауза';
if (!settings.last_rotation_timestamp) return 'Ожидание...';
const last = new Date(+settings.last_rotation_timestamp);
const intervalMinutes = parseInt(settings.rotation_interval) || 60;
const next = new Date(last.getTime() + intervalMinutes * 60000);
return next.toLocaleString('ru-RU', {
day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit'
});
};
const isPaused = settings.rotation_status === 'stopped';
return (
<Box>
<Typography variant={isMobile ? 'h5' : 'h4'} gutterBottom>Настройки утилиты</Typography>
<Typography variant="h4" gutterBottom>
Настройки
</Typography>
<Grid container spacing={3}>
<Grid size={{ xs: 12 }}>
<Grid container spacing={1}>
<Grid size={{ xs: 12, md: 4 }}>
<Typography variant="subtitle2" color="textSecondary" gutterBottom>
Статус сервиса
</Typography>
{isPaused ?
<Chip icon={<PauseCircleFilled />} label="Остановлен" color="warning" size="small" variant="outlined" /> :
<Chip icon={<CheckCircle />} label="Активен" color="success" size="small" variant="outlined" />
}
<Tooltip title={isPaused ? "Возобновить ротацию" : "Поставить на паузу"}>
<IconButton
onClick={togglePause}
size="small"
sx={{
bgcolor: 'background.paper',
boxShadow: 2,
'&:hover': { bgcolor: 'background.paper' },
ml: 1
}}
>
{isPaused ? <PlayCircleFilled fontSize="large" /> : <PauseCircleFilled fontSize="large" />}
</IconButton>
</Tooltip>
</Grid>
{/* Последняя генерация */}
<Grid size={{ xs: 12, md: 4 }}>
<Stack direction="row" alignItems="center" spacing={1}>
<Box>
<Typography variant="subtitle2" color="textSecondary">
Последняя генерация
</Typography>
<Typography variant="body1" sx={{ fontWeight: 500, mt: 2 }}>
{formatDate(settings.last_rotation_timestamp)}
</Typography>
</Box>
</Stack>
</Grid>
{/* Следующая генерация */}
<Grid size={{ xs: 12, md: 4 }}>
<Stack direction="row" alignItems="center" spacing={1}>
<Box>
<Typography variant="subtitle2" color="textSecondary">
Следующая генерация
</Typography>
<Typography variant="body1" sx={{ fontWeight: 500, mt: 2 }}>
{getNextRotationDate()}
</Typography>
</Box>
</Stack>
</Grid>
</Grid>
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<Paper sx={{ p: 3, height: '100%' }}>
<Typography variant="h6" gutterBottom>Панель 3x-ui</Typography>
<Divider sx={{ mb: 2 }} />
<TextField
fullWidth margin="normal" label="URL панели"
value={settings.xui_url} onChange={handleSettingChange('xui_url')}
helperText="Например: https://my-vpn.com:2053/wfgpoVHaOF"
/>
<TextField
fullWidth margin="normal" label="Логин 3x-ui"
value={settings.xui_login} onChange={handleSettingChange('xui_login')}
/>
<TextField
fullWidth margin="normal" label="Пароль 3x-ui" type="password"
value={settings.xui_password} onChange={handleSettingChange('xui_password')}
/>
<Button variant="contained" sx={{ mt: 2 }} onClick={handleSaveSettings}>
Сохранить подключение
<Paper sx={{ p: 3, maxWidth: 680 }}>
<Typography variant="h6">Профиль панели 3dp-manager</Typography>
<Divider sx={{ my: 2 }} />
<Stack spacing={2}>
<TextField
label="Логин"
value={adminProfile.login}
onChange={handleChange('login')}
fullWidth
/>
<TextField
label="Новый пароль"
type="password"
value={adminProfile.password}
onChange={handleChange('password')}
helperText="Оставьте пустым, если не хотите менять пароль"
fullWidth
/>
<Box>
<Button variant="contained" onClick={handleSave}>
Сохранить
</Button>
{settings.xui_url && settings.xui_login && settings.xui_password && (
<Button
variant="outlined"
color="info"
sx={{ mt: 2, ml: isMobile ? 1 : 2 }}
onClick={handleCheckConnection}
>
Проверить
</Button>
)}
</Paper>
</Grid>
<Grid size={{ xs: 12, md: 6 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>Генерация инбаундов</Typography>
<Divider sx={{ mb: 2 }} />
<TextField
fullWidth margin="normal" label="Интервал генерации"
type="number"
value={settings.rotation_interval}
onChange={handleSettingChange('rotation_interval')}
slotProps={{
input: { endAdornment: <InputAdornment position="end">мин</InputAdornment> }
}}
helperText="Как часто менять инбаунды (минимум 10 мин)"
/>
<Stack direction="row" spacing={1} sx={{ mt: 1, mb: 2 }}>
{ROTATION_PRESETS.map((preset) => (
<Chip
key={preset.value}
label={preset.label}
onClick={() => handlePresetClick(preset.value)}
color={settings.rotation_interval === preset.value.toString() ? "primary" : "default"}
variant={settings.rotation_interval === preset.value.toString() ? "filled" : "outlined"}
clickable
/>
))}
</Stack>
<Button variant="contained" sx={{ mt: 2 }} onClick={handleSaveInterval}>
Применить интервал
</Button>
<Button
variant="outlined"
loading={loadingRotate}
color="warning"
onClick={handleForceRotate}
sx={{ mt: 2, ml: isMobile ? 0 : 2 }}
>
Сгенерировать сейчас
</Button>
<Divider sx={{ my: 3 }} />
<Typography variant="subtitle1" gutterBottom sx={{ fontWeight: 600 }}>
Управление авторотацией подписок
</Typography>
<Typography variant="body2" color="textSecondary" paragraph>
Выберите подписки для автоматической ротации:
</Typography>
{subs.length === 0 ? (
<Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
Нет активных подписок
</Typography>
) : (
<List sx={{ maxHeight: 400, overflow: 'auto', bgcolor: 'background.default', borderRadius: 1 }}>
{subs.map(sub => (
<ListItem
key={sub.id}
sx={{
py: 1,
borderBottom: '1px solid',
borderColor: 'divider',
'&:last-child': { borderBottom: 'none' }
}}
>
<FormControlLabel
control={
<Checkbox
checked={sub.isAutoRotationEnabled ?? true}
onChange={(e) => handleToggleAutoRotation(sub.id, e.target.checked)}
color="primary"
/>
}
label={
<Box>
<Typography variant="body2" sx={{ fontWeight: 500 }}>{sub.name}</Typography>
<Typography variant="caption" color="textSecondary">
{sub.uuid.substring(0, 8)}...
</Typography>
</Box>
}
sx={{ flexGrow: 1 }}
/>
<Tooltip title="Обновить подписку вручную">
<IconButton
size="small"
onClick={() => handleManualRotate(sub)}
color="primary"
>
<Refresh />
</IconButton>
</Tooltip>
</ListItem>
))}
</List>
)}
{subs.length > 0 && (
<Box sx={{ mt: 2, display: 'flex', gap: 1 }}>
<Button
variant="outlined"
size="small"
onClick={() => handleBulkUpdate(true)}
>
Включить для всех
</Button>
<Button
variant="outlined"
size="small"
onClick={() => handleBulkUpdate(false)}
>
Выключить для всех
</Button>
</Box>
)}
</Paper>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>Доступ к 3DP-MANAGER</Typography>
<Divider sx={{ mb: 2 }} />
<TextField
fullWidth margin="normal" label="Логин администратора"
value={adminProfile.login}
onChange={handleAdminChange('login')}
/>
<TextField
fullWidth margin="normal" label="Новый пароль" type="password"
value={adminProfile.password}
onChange={handleAdminChange('password')}
helperText="Оставьте пустым, если не хотите менять"
/>
<Button variant="contained" color="warning" sx={{ mt: 2 }} onClick={handleSaveAdmin}>
Обновить профиль
</Button>
</Paper>
</Box>
</Grid>
</Grid>
</Stack>
</Paper>
<Snackbar open={msg.open} autoHideDuration={5000} onClose={() => setMsg({ ...msg, open: false })}>
<Alert severity={msg.type}>{msg.text}</Alert>
<Snackbar
open={message.open}
autoHideDuration={5000}
onClose={() => setMessage({ ...message, open: false })}
>
<Alert severity={message.type}>{message.text}</Alert>
</Snackbar>
<Dialog open={confirmDialog.open} onClose={() => setConfirmDialog({ ...confirmDialog, open: false })}>
<DialogTitle>Подтверждение действия</DialogTitle>
<DialogContent>
<Typography>{confirmDialog.title}</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setConfirmDialog({ ...confirmDialog, open: false })}>
Отмена
</Button>
<Button
onClick={() => {
setConfirmDialog({ ...confirmDialog, open: false });
confirmDialog.onConfirm();
}}
variant="contained"
color={confirmDialog.confirmColor}
>
{confirmDialog.confirmText}
</Button>
</DialogActions>
</Dialog>
</Box>
);
}
}
File diff suppressed because it is too large Load Diff
+206 -225
View File
@@ -1,106 +1,150 @@
import React, { useEffect, useState, useCallback } from 'react';
import { type ChangeEvent, useCallback, useEffect, useMemo, useState } from 'react';
import {
Box, Button, Typography, Paper, Table, TableBody, TableCell,
TableHead, TableRow, IconButton, Dialog, DialogTitle,
DialogContent, TextField, DialogActions, Chip, CircularProgress,
useTheme,
useMediaQuery,
Alert,
Box,
Button,
Chip,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
RadioGroup,
FormControlLabel,
IconButton,
InputLabel,
MenuItem,
Paper,
Radio,
RadioGroup,
Select,
Snackbar,
Alert
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
Typography,
useMediaQuery,
useTheme,
} from '@mui/material';
import { Delete, Add, Terminal, CheckCircle, Error, Dns } from '@mui/icons-material';
import { Add, CheckCircle, Delete, Dns, Error, Terminal } from '@mui/icons-material';
import api from '../api';
import { getApiErrorMessage } from '../utils/errorHandlers';
import { Logger } from '../utils/logger';
import type { NodeRecord } from '../types/node';
interface Tunnel {
id: number;
name: string;
ip: string;
domain?: string;
sshPort: number;
username: string;
isInstalled: boolean;
nodeId?: string;
node?: NodeRecord;
}
const emptyForm = {
name: '',
nodeId: '',
ip: '',
sshPort: 22,
username: 'root',
password: '',
privateKey: '',
domain: '',
};
export default function TunnelsPage() {
const [tunnels, setTunnels] = useState<Tunnel[]>([]);
const [nodes, setNodes] = useState<NodeRecord[]>([]);
const [open, setOpen] = useState(false);
const [loadingId, setLoadingId] = useState<number | null>(null);
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
const [authMethod, setAuthMethod] = useState<'password' | 'key'>('password');
const [form, setForm] = useState({
name: '', ip: '', sshPort: 22, username: 'root', password: '', privateKey: '', domain: ''
const [form, setForm] = useState(emptyForm);
const [formErrors, setFormErrors] = useState<Record<string, string>>({});
const [snackbar, setSnackbar] = useState({
open: false,
type: 'success' as 'success' | 'error',
message: '',
});
const [confirmDialog, setConfirmDialog] = useState({
open: false,
title: '',
confirmText: 'Подтвердить',
confirmColor: 'primary' as 'primary' | 'error',
onConfirm: () => {},
});
// Snackbar state for notifications
const [snackbar, setSnackbar] = useState({ open: false, type: 'success' as 'success' | 'error', message: '' });
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
const mainNode = useMemo(() => nodes.find((node) => node.isMain), [nodes]);
// Confirmation dialog state
const [confirmDialog, setConfirmDialog] = useState({ open: false, title: '', onConfirm: () => {} });
const loadData = useCallback(async () => {
try {
const [tunnelsRes, nodesRes] = await Promise.all([
api.get<Tunnel[]>('/tunnels'),
api.get<NodeRecord[]>('/nodes'),
]);
setTunnels(Array.isArray(tunnelsRes.data) ? tunnelsRes.data : []);
setNodes(Array.isArray(nodesRes.data) ? nodesRes.data : []);
} catch (error) {
Logger.error('Failed to load forwarding data', 'Tunnels', error);
}
}, []);
// Form validation errors
const [formErrors, setFormErrors] = useState<Record<string, string>>({});
useEffect(() => {
loadData();
}, [loadData]);
const isValidIp = (value: string) =>
/^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(value.trim()) ||
/^([0-9a-f]{1,4}:){2,7}[0-9a-f]{1,4}$/i.test(value.trim());
const isValidDomain = (value: string) =>
/^(?=.{1,253}$)(?!-)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(value.trim());
const isValidAddress = (value: string) => isValidIp(value) || isValidDomain(value);
const selectedNode = nodes.find((node) => node.id === form.nodeId) || mainNode;
const validateForm = () => {
const errors: Record<string, string> = {};
if (!form.name.trim()) {
errors.name = 'Введите название сервера';
}
if (!form.ip.trim()) {
errors.ip = 'Введите IP адрес';
} else {
// IPv4 validation
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
// IPv6 basic validation
const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:){1,7}:$|^([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}$|^([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}$|^([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}$|^([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}$|^[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})$|^:((:[0-9a-fA-F]{1,4}){1,7}|:)$/;
if (!ipv4Regex.test(form.ip) && !ipv6Regex.test(form.ip)) {
errors.ip = 'Неверный формат IP адреса';
}
}
if (!form.name.trim()) errors.name = 'Введите название relay сервера';
if (!selectedNode) errors.nodeId = 'Добавьте или выберите ноду';
if (!isValidAddress(form.ip)) errors.ip = 'Введите корректный IP или домен relay сервера';
if (!form.sshPort || form.sshPort < 1 || form.sshPort > 65535) {
errors.sshPort = 'Порт должен быть от 1 до 65535';
}
if (!form.username.trim()) {
errors.username = 'Введите SSH пользователя';
}
if (authMethod === 'password' && !form.password) {
errors.password = 'Введите SSH пароль';
}
if (authMethod === 'key' && !form.privateKey.trim()) {
errors.privateKey = 'Введите SSH ключ';
} else if (authMethod === 'key' && !form.privateKey.includes('-----BEGIN')) {
errors.privateKey = 'Неверный формат SSH ключа';
}
if (!form.username.trim()) errors.username = 'Введите SSH пользователя';
if (authMethod === 'password' && !form.password) errors.password = 'Введите SSH пароль';
if (authMethod === 'key' && !form.privateKey.trim()) errors.privateKey = 'Введите SSH ключ';
setFormErrors(errors);
return Object.keys(errors).length === 0;
};
const loadTunnels = useCallback(async () => {
try {
Logger.debug('Loading tunnels...', 'Tunnels');
const { data } = await api.get('/tunnels');
setTunnels(data);
Logger.debug(`Loaded ${data.length} tunnels`, 'Tunnels');
} catch (error) {
Logger.error('Failed to load', 'Tunnels', error);
}
}, []);
const handleChange =
(prop: keyof typeof emptyForm) => (event: ChangeEvent<HTMLInputElement>) => {
setForm((prev) => ({ ...prev, [prop]: event.target.value }));
};
useEffect(() => { loadTunnels(); }, [loadTunnels]);
const resetForm = () => {
setForm({ ...emptyForm, nodeId: mainNode?.id || '' });
setAuthMethod('password');
setFormErrors({});
};
const openCreate = () => {
if (nodes.length === 0) {
setSnackbar({ open: true, type: 'error', message: 'Создайте хотя бы одну ноду!' });
return;
}
resetForm();
setOpen(true);
};
const handleCreate = async () => {
if (!validateForm()) {
@@ -110,67 +154,76 @@ export default function TunnelsPage() {
const payload = {
...form,
password: authMethod === 'password' ? form.password : null,
privateKey: authMethod === 'key' ? form.privateKey : null,
nodeId: form.nodeId || mainNode?.id,
password: authMethod === 'password' ? form.password : undefined,
privateKey: authMethod === 'key' ? form.privateKey : undefined,
};
Logger.debug(`Creating tunnel`, 'Tunnels', { name: form.name, ip: form.ip });
await api.post('/tunnels', payload);
Logger.debug('Tunnel created successfully', 'Tunnels');
setOpen(false);
setForm({ name: '', ip: '', sshPort: 22, username: 'root', password: '', privateKey: '', domain: '' });
setAuthMethod('password');
setFormErrors({});
loadTunnels();
setSnackbar({ open: true, type: 'success', message: 'Сервер добавлен' });
try {
await api.post('/tunnels', payload);
setOpen(false);
resetForm();
loadData();
setSnackbar({ open: true, type: 'success', message: 'Relay сервер добавлен' });
} catch (error) {
setSnackbar({ open: true, type: 'error', message: getApiErrorMessage(error, 'Не удалось добавить relay сервер') });
}
};
const handleDelete = async (id: number) => {
const handleInstall = (id: number) => {
setConfirmDialog({
open: true,
title: 'Удалить сервер из списка?',
title: 'Установить перенаправление на выбранный сервер?',
confirmText: 'Установить',
confirmColor: 'primary',
onConfirm: async () => {
Logger.debug(`Deleting tunnel ID: ${id}`, 'Tunnels');
await api.delete(`/tunnels/${id}`);
Logger.debug(`Deleted tunnel ID: ${id}`, 'Tunnels');
loadTunnels();
setSnackbar({ open: true, type: 'success', message: 'Сервер удалён' });
}
});
};
const handleInstall = async (id: number) => {
setConfirmDialog({
open: true,
title: 'Начать установку перенаправления на этот сервер?',
onConfirm: async () => {
Logger.debug(`Installing forwarding on tunnel ID: ${id}`, 'Tunnels');
setLoadingId(id);
try {
await api.post(`/tunnels/${id}/install`);
Logger.debug('Forwarding installed successfully', 'Tunnels');
setSnackbar({ open: true, type: 'success', message: 'Скрипт успешно установлен! Трафик перенаправляется.' });
loadTunnels();
} catch (e) {
const message = getApiErrorMessage(e, 'Неизвестная ошибка');
Logger.error(`Install error on ID ${id}: ${message}`, 'Tunnels');
setSnackbar({ open: true, type: 'error', message: 'Ошибка: ' + message });
setSnackbar({ open: true, type: 'success', message: 'Перенаправление установлено' });
loadData();
} catch (error) {
setSnackbar({ open: true, type: 'error', message: getApiErrorMessage(error, 'Ошибка установки') });
} finally {
setLoadingId(null);
}
}
},
});
};
const handleChange = useCallback((prop: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
setForm(prev => ({ ...prev, [prop]: e.target.value }));
}, []);
const handleDelete = (tunnel: Tunnel) => {
const deleteForwarding =
tunnel.isInstalled &&
window.confirm('Удалить перенаправление на сервере через forwarding_delete.sh (приведет сервер к первоначальному состоянию)? Нажмите Ок для подтверждения.');
setConfirmDialog({
open: true,
title: deleteForwarding
? 'Удалить relay и выполнить удаление перенаправления на сервере?'
: 'Удалить relay сервер только из списка?',
confirmText: 'Удалить',
confirmColor: 'error',
onConfirm: async () => {
setLoadingId(tunnel.id);
try {
await api.delete(`/tunnels/${tunnel.id}`, { params: { deleteForwarding } });
setSnackbar({ open: true, type: 'success', message: 'Relay сервер удалён' });
loadData();
} catch (error) {
setSnackbar({ open: true, type: 'error', message: getApiErrorMessage(error, 'Ошибка удаления') });
} finally {
setLoadingId(null);
}
},
});
};
return (
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
<Typography variant={isMobile ? 'h5' : 'h4'}>Relay серверы</Typography>
<Button variant="contained" startIcon={<Add />} onClick={() => setOpen(true)}>Добавить</Button>
<Box><Button variant="contained" startIcon={<Add />} onClick={openCreate}>Добавить</Button></Box>
</Box>
<Paper sx={{ overflowX: 'auto' }}>
@@ -178,104 +231,77 @@ export default function TunnelsPage() {
<TableHead>
<TableRow>
<TableCell>Название</TableCell>
<TableCell>Нода</TableCell>
<TableCell>Адрес</TableCell>
<TableCell>Статус</TableCell>
<TableCell align="right">Действия</TableCell>
</TableRow>
</TableHead>
<TableBody>
{tunnels.map((t) => (
<TableRow key={t.id}>
<TableCell>{t.name}</TableCell>
{tunnels.map((tunnel) => (
<TableRow key={tunnel.id}>
<TableCell>{tunnel.name}</TableCell>
<TableCell>{tunnel.node?.name || '-'}</TableCell>
<TableCell>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Dns fontSize="small" color="action" />
{t.ip}
{tunnel.domain || tunnel.ip}
</Box>
</TableCell>
<TableCell>
{!isMobile && (t.isInstalled ?
<Chip icon={<CheckCircle />} label={"Активен"} color="success" size="small" variant="outlined" /> :
<Chip icon={<Error />} label={"Не настроен"} color="warning" size="small" variant="outlined" />
)}
{isMobile && (t.isInstalled ?
<CheckCircle color='success' /> :
<Error color='warning' />
{tunnel.isInstalled ? (
<Chip icon={<CheckCircle />} label="Активен" color="success" size="small" variant="outlined" />
) : (
<Chip icon={<Error />} label="Не установлен" color="warning" size="small" variant="outlined" />
)}
</TableCell>
<TableCell align="right">
{!t.isInstalled && (
<>
{isMobile ? (
<IconButton disabled={loadingId !== null} color="primary" onClick={() => handleInstall(t.id)}>
{loadingId === t.id ? <CircularProgress size={20} /> : <Terminal />}
</IconButton>
) : (
<Button
startIcon={loadingId === t.id ? <CircularProgress size={20} /> : <Terminal />}
disabled={loadingId !== null}
onClick={() => handleInstall(t.id)}
sx={{ mr: 1 }}
variant="outlined"
size="small"
>
{isMobile ? '' : (loadingId === t.id ? 'Установка...' : 'Установить')}
</Button>
)}
</>
{!tunnel.isInstalled && (
<Button
startIcon={loadingId === tunnel.id ? <CircularProgress size={20} /> : <Terminal />}
disabled={loadingId !== null}
onClick={() => handleInstall(tunnel.id)}
sx={{ mr: 1 }}
variant="outlined"
size="small"
>
Установить
</Button>
)}
<IconButton color="inherit" onClick={() => handleDelete(t.id)}>
<IconButton color="error" disabled={loadingId !== null} onClick={() => handleDelete(tunnel)}>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
{tunnels.length === 0 && <TableRow><TableCell colSpan={4} align="center" sx={{ color: 'text.secondary' }}>Нет серверов</TableCell></TableRow>}
{tunnels.length === 0 && (
<TableRow>
<TableCell colSpan={5} align="center" sx={{ color: 'text.secondary' }}>
Relay серверы не добавлены
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</Paper>
<Dialog open={open} onClose={() => setOpen(false)}>
<DialogTitle>Новый редирект сервер</DialogTitle>
<Dialog open={open} onClose={() => setOpen(false)} maxWidth="sm" fullWidth>
<DialogTitle>Новый relay сервер</DialogTitle>
<DialogContent>
<TextField
margin="dense"
label="Название"
fullWidth
value={form.name}
onChange={handleChange('name')}
error={!!formErrors.name}
helperText={formErrors.name}
/>
<TextField
margin="dense"
label="IP адрес"
fullWidth
value={form.ip}
onChange={handleChange('ip')}
error={!!formErrors.ip}
helperText={formErrors.ip}
/>
<TextField margin="dense" label="Название" required fullWidth value={form.name} onChange={handleChange('name')} error={!!formErrors.name} helperText={formErrors.name} />
<FormControl fullWidth required margin="dense" error={!!formErrors.nodeId}>
<InputLabel>Нода</InputLabel>
<Select value={form.nodeId || mainNode?.id || ''} label="Нода" onChange={(event) => setForm((prev) => ({ ...prev, nodeId: event.target.value }))}>
{nodes.map((node) => (
<MenuItem key={node.id} value={node.id}>{node.name}{node.isMain ? ' (основная)' : ''}</MenuItem>
))}
</Select>
{formErrors.nodeId && <Typography variant="caption" color="error" sx={{ mt: 0.5, ml: 1.5 }}>{formErrors.nodeId}</Typography>}
</FormControl>
<TextField margin="dense" label="IP или домен relay сервера" required fullWidth value={form.ip} onChange={handleChange('ip')} error={!!formErrors.ip} helperText={formErrors.ip} />
<Box sx={{ display: 'flex', gap: 2 }}>
<TextField
margin="dense"
label="SSH Порт"
type="number"
fullWidth
value={form.sshPort}
onChange={handleChange('sshPort')}
error={!!formErrors.sshPort}
helperText={formErrors.sshPort}
/>
<TextField
margin="dense"
label="SSH User"
fullWidth
value={form.username}
onChange={handleChange('username')}
error={!!formErrors.username}
helperText={formErrors.username}
/>
<TextField margin="dense" label="SSH порт" required type="number" fullWidth value={form.sshPort} onChange={handleChange('sshPort')} error={!!formErrors.sshPort} helperText={formErrors.sshPort} />
<TextField margin="dense" label="SSH пользователь" required fullWidth value={form.username} onChange={handleChange('username')} error={!!formErrors.username} helperText={formErrors.username} />
</Box>
<FormControl component="fieldset" sx={{ mt: 2, mb: 1 }}>
<RadioGroup row value={authMethod} onChange={(e) => setAuthMethod(e.target.value as 'password' | 'key')}>
@@ -285,30 +311,9 @@ export default function TunnelsPage() {
</FormControl>
{authMethod === 'password' ? (
<TextField
margin="dense"
label="SSH Пароль"
type="password"
fullWidth
value={form.password}
onChange={handleChange('password')}
error={!!formErrors.password}
helperText={formErrors.password}
/>
<TextField margin="dense" label="SSH пароль" required type="password" fullWidth value={form.password} onChange={handleChange('password')} error={!!formErrors.password} helperText={formErrors.password} />
) : (
<TextField
margin="dense"
label="SSH Private Key (RSA / Ed25519)"
multiline
rows={4}
fullWidth
value={form.privateKey}
onChange={handleChange('privateKey')}
placeholder="-----BEGIN OPENSSH PRIVATE KEY-----&#10;...&#10;-----END OPENSSH PRIVATE KEY-----"
slotProps={{ input: { style: { fontFamily: 'monospace', fontSize: '0.875rem' } } }}
error={!!formErrors.privateKey}
helperText={formErrors.privateKey}
/>
<TextField margin="dense" label="SSH private key" required multiline rows={4} fullWidth value={form.privateKey} onChange={handleChange('privateKey')} placeholder="-----BEGIN OPENSSH PRIVATE KEY-----" slotProps={{ input: { style: { fontFamily: 'monospace', fontSize: '0.875rem' } } }} error={!!formErrors.privateKey} helperText={formErrors.privateKey} />
)}
</DialogContent>
<DialogActions>
@@ -317,42 +322,18 @@ export default function TunnelsPage() {
</DialogActions>
</Dialog>
{/* Confirmation Dialog */}
<Dialog open={confirmDialog.open} onClose={() => setConfirmDialog({ ...confirmDialog, open: false })}>
<DialogTitle>Подтверждение</DialogTitle>
<DialogContent>
<Typography>{confirmDialog.title}</Typography>
</DialogContent>
<DialogContent><Typography>{confirmDialog.title}</Typography></DialogContent>
<DialogActions>
<Button onClick={() => setConfirmDialog({ ...confirmDialog, open: false })}>Отмена</Button>
<Button
onClick={() => {
confirmDialog.onConfirm();
setConfirmDialog({ ...confirmDialog, open: false });
}}
variant="contained"
color="error"
>
Подтвердить
</Button>
<Button onClick={() => { setConfirmDialog({ ...confirmDialog, open: false }); confirmDialog.onConfirm(); }} variant="contained" color={confirmDialog.confirmColor}>{confirmDialog.confirmText}</Button>
</DialogActions>
</Dialog>
{/* Snackbar notifications */}
<Snackbar
open={snackbar.open}
autoHideDuration={6000}
onClose={() => setSnackbar({ ...snackbar, open: false })}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
>
<Alert
onClose={() => setSnackbar({ ...snackbar, open: false })}
severity={snackbar.type}
sx={{ width: '100%' }}
>
{snackbar.message}
</Alert>
<Snackbar open={snackbar.open} autoHideDuration={6000} onClose={() => setSnackbar({ ...snackbar, open: false })} anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}>
<Alert onClose={() => setSnackbar({ ...snackbar, open: false })} severity={snackbar.type} sx={{ width: '100%' }}>{snackbar.message}</Alert>
</Snackbar>
</Box>
);
}
}
+34
View File
@@ -0,0 +1,34 @@
export type NodeAuthType = 'password' | 'token';
export type NodeProtocol = 'http' | 'https';
export interface NodeRecord {
id: string;
name: string;
url: string;
host?: string;
domain?: string;
ip?: string;
flag?: string;
port?: number;
protocol?: NodeProtocol;
authType: NodeAuthType;
login?: string;
isMain: boolean;
version?: string;
createdAt: string;
updatedAt: string;
}
export interface NodePayload {
name: string;
url: string;
domain?: string;
ip?: string;
flag?: string;
authType: NodeAuthType;
login?: string;
password?: string;
token?: string;
isMain?: boolean;
version?: string;
}
+99
View File
@@ -0,0 +1,99 @@
import { Box, Stack, Typography } from '@mui/material';
const SPECIAL_CODES: Record<string, string> = {
ENGLAND: 'gb-eng',
SCOTLAND: 'gb-sct',
WALES: 'gb-wls',
};
export const decodeFlag = (flag?: string) => {
if (!flag) return '';
try {
return decodeURIComponent(flag);
} catch {
return flag;
}
};
export const countryCodeFromFlag = (flag?: string) => {
const decoded = decodeFlag(flag);
const points = Array.from(decoded).map((char) => char.codePointAt(0) || 0);
if (points.length < 2) return undefined;
if (points[0] < 0x1f1e6 || points[0] > 0x1f1ff) return undefined;
if (points[1] < 0x1f1e6 || points[1] > 0x1f1ff) return undefined;
return String.fromCharCode(points[0] - 0x1f1e6 + 65, points[1] - 0x1f1e6 + 65);
};
const normalizeCode = (code?: string) => {
if (!code) return undefined;
return SPECIAL_CODES[code.toUpperCase()] || code.toLowerCase();
};
export function FlagIcon({
flag,
code,
size = 22,
}: {
flag?: string;
code?: string;
size?: number;
}) {
const normalizedCode = normalizeCode(code || countryCodeFromFlag(flag));
if (!normalizedCode) {
return (
<Box
component="span"
sx={{
width: size,
height: Math.round(size * 0.72),
borderRadius: 0.5,
border: 1,
borderColor: 'divider',
display: 'inline-block',
bgcolor: 'action.hover',
flexShrink: 0,
}}
/>
);
}
return (
<Box
component="img"
src={`https://flagcdn.com/w40/${normalizedCode}.png`}
srcSet={`https://flagcdn.com/w80/${normalizedCode}.png 2x`}
alt=""
loading="lazy"
sx={{
width: size,
height: Math.round(size * 0.72),
borderRadius: 0.5,
objectFit: 'cover',
boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.12)',
flexShrink: 0,
}}
/>
);
}
export function FlagOptionLabel({
flag,
code,
label,
}: {
flag?: string;
code?: string;
label: string;
}) {
return (
<Stack component="span" direction="row" spacing={1} alignItems="center">
<FlagIcon flag={flag} code={code} size={22} />
<Typography component="span" variant="body2">
{label}
</Typography>
</Stack>
);
}
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = '2.1.0';
export const APP_VERSION = '2.2.0';
+9 -40
View File
@@ -175,13 +175,13 @@ describe('SubscriptionsPage', () => {
await waitFor(() => {
expect(mockGet).toHaveBeenCalledWith('/tunnels')
expect(mockGet).toHaveBeenCalledTimes(3)
expect(mockGet).toHaveBeenCalled()
})
})
})
describe('Селектор сервера', () => {
it('должен отображать селектор сервера при наличии туннелей', async () => {
describe('Список подписок без выбора сервера', () => {
it('не должен отображать верхний селектор сервера при наличии туннелей', async () => {
const mockTunnels = [
{ id: 1, name: 'Tunnel 1', ip: '1.1.1.1', domain: '', isInstalled: true }
]
@@ -189,38 +189,7 @@ describe('SubscriptionsPage', () => {
renderSubscriptionsPage()
await waitFor(() => {
const select = screen.getByRole('combobox')
expect(select).toBeInTheDocument()
})
})
it('должен отображать иконку Dns для основного сервера', async () => {
const mockTunnels = [
{ id: 1, name: 'Tunnel 1', ip: '1.1.1.1', domain: '', isInstalled: true }
]
setupMockGet({ tunnels: mockTunnels, subscriptions: [] })
renderSubscriptionsPage()
await waitFor(() => {
expect(screen.getByText('Основной сервер')).toBeInTheDocument()
})
})
it('должен переключать выбранный сервер', async () => {
const mockTunnels = [
{ id: 1, name: 'Tunnel 1', ip: '1.1.1.1', domain: '', isInstalled: true }
]
setupMockGet({ tunnels: mockTunnels, subscriptions: [] })
renderSubscriptionsPage()
const select = await screen.findByRole('combobox')
fireEvent.mouseDown(select)
const tunnelOption = await screen.findByText('Tunnel 1')
fireEvent.click(tunnelOption)
await waitFor(() => {
expect(screen.getByText('Tunnel 1')).toBeInTheDocument()
expect(screen.queryByText('Основной сервер')).not.toBeInTheDocument()
})
})
})
@@ -273,7 +242,7 @@ describe('SubscriptionsPage', () => {
fireEvent.click(createButton)
await waitFor(() => {
expect(screen.getByText('Инбаунды (10/20)')).toBeInTheDocument()
expect(screen.getByText('Инбаунды (9/20)')).toBeInTheDocument()
})
})
@@ -317,7 +286,7 @@ describe('SubscriptionsPage', () => {
fireEvent.click(createButton)
await waitFor(() => {
expect(screen.getByText('Инбаунды (10/20)')).toBeInTheDocument()
expect(screen.getByText('Инбаунды (9/20)')).toBeInTheDocument()
})
})
@@ -345,7 +314,7 @@ describe('SubscriptionsPage', () => {
fireEvent.click(addButton)
await waitFor(() => {
expect(screen.getByText('Инбаунды (11/20)')).toBeInTheDocument()
expect(screen.getByText('Инбаунды (10/20)')).toBeInTheDocument()
})
})
@@ -371,7 +340,7 @@ describe('SubscriptionsPage', () => {
const createButton = await screen.findByText('Создать')
fireEvent.click(createButton)
for (let i = 0; i < 10; i++) {
for (let i = 0; i < 11; i++) {
const addButton = screen.getByText('Добавить инбаунд')
fireEvent.click(addButton)
}
@@ -380,7 +349,7 @@ describe('SubscriptionsPage', () => {
const addButton = screen.getByText('Добавить инбаунд')
expect(addButton).toBeDisabled()
})
})
}, 15000)
})
describe('Сохранение подписки', () => {
+44 -18
View File
@@ -17,6 +17,20 @@ need_root() {
[[ $EUID -eq 0 ]] || die "Запускать только от root"
}
resolve_compose_cmd() {
if docker compose version >/dev/null 2>&1; then
COMPOSE_CMD=("docker" "compose")
return 0
fi
if command -v docker-compose >/dev/null 2>&1; then
COMPOSE_CMD=("docker-compose")
return 0
fi
return 1
}
echo "Перед удалением самостоятельно удалите подписки в 3DP-MANAGER, чтобы инбунды удалились в панели 3x-ui"
read -r -p "Вы уверены, что хотите удалить? (y/n): " answer
@@ -39,44 +53,56 @@ PROJECT_DIR="/opt/3dp-manager"
log "Начинаем удаление 3dp-manager"
if [[ ! -d "$PROJECT_DIR" ]]; then
warn "Директория $PROJECT_DIR не найдена — удалять нечего"
exit 0
if [[ -d "$PROJECT_DIR" ]]; then
cd "$PROJECT_DIR"
else
warn "Директория $PROJECT_DIR не найдена — проверяем Docker-ресурсы по известным именам"
fi
cd "$PROJECT_DIR"
#################################
# DOCKER COMPOSE DOWN
#################################
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
if [[ -f docker-compose.yml ]]; then
if command -v docker >/dev/null 2>&1; then
if [[ -d "$PROJECT_DIR" && -f docker-compose.yml ]] && resolve_compose_cmd; then
log "Останавливаем контейнеры 3dp-manager"
docker compose down --volumes --remove-orphans || warn "Ошибка при docker compose down"
"${COMPOSE_CMD[@]}" down --volumes --remove-orphans || warn "Ошибка при docker compose down"
else
warn "docker-compose.yml не найден"
warn "docker-compose.yml или Docker Compose не найден — удаляем контейнеры и volumes по известным именам"
fi
docker rm -f 3dp-postgres 3dp-backend 3dp-frontend >/dev/null 2>&1 || true
for volume in 3dp-manager_pg_data 3dpmanager_pg_data; do
if docker volume inspect "$volume" >/dev/null 2>&1; then
log "Удаляем volume $volume"
docker volume rm "$volume" >/dev/null 2>&1 || warn "Не удалось удалить volume $volume"
fi
done
else
warn "Docker или docker compose не установлен — пропуск"
warn "Docker не установлен — пропуск удаления Docker-ресурсов"
fi
#################################
# CLEAN IMAGES
#################################
log "Удаляем образы 3dp-manager (если есть)"
if command -v docker >/dev/null 2>&1; then
log "Удаляем образы 3dp-manager (если есть)"
docker images --format '{{.Repository}} {{.ID}}' \
| grep 3dp-manager \
| awk '{print $2}' \
| xargs -r docker rmi -f || true
docker images --format '{{.Repository}} {{.ID}}' \
| grep 3dp-manager \
| awk '{print $2}' \
| xargs -r docker rmi -f || true
fi
#################################
# REMOVE DIRECTORY
#################################
log "Удаляем $PROJECT_DIR"
rm -rf "$PROJECT_DIR"
if [[ -d "$PROJECT_DIR" ]]; then
log "Удаляем $PROJECT_DIR"
rm -rf "$PROJECT_DIR"
fi
#################################
# DONE
#################################
log "✔ 3dp-manager полностью удалён"
log "✔ 3dp-manager полностью удалён"
+5 -1
View File
@@ -1,3 +1,5 @@
name: 3dp-manager
services:
postgres:
image: postgres:18-alpine
@@ -24,6 +26,8 @@ services:
DB_USERNAME: ${POSTGRES_USER}
DB_PASSWORD: ${POSTGRES_PASSWORD}
DB_NAME: ${POSTGRES_DB}
DB_SYNCHRONIZE: "true"
DB_MIGRATIONS_RUN: "false"
JWT_SECRET: ${JWT_SECRET}
ADMIN_LOGIN: ${ADMIN_LOGIN}
ADMIN_PASSWORD: ${ADMIN_PASSWORD}
@@ -49,4 +53,4 @@ volumes:
networks:
app-network:
driver: bridge
driver: bridge
+45 -69
View File
@@ -96,6 +96,26 @@ get_random_port() {
done
}
cleanup_previous_install_data() {
log "Checking for previous 3dp-manager installation data..."
if [[ -f docker-compose.yml ]]; then
warn "Existing docker-compose.yml found. Stopping previous installation and removing its volumes so newly generated credentials are used."
"${COMPOSE_CMD[@]}" down --volumes --remove-orphans || true
else
warn "docker-compose.yml not found. Removing known 3dp-manager containers if they still exist."
fi
docker rm -f 3dp-postgres 3dp-backend 3dp-frontend >/dev/null 2>&1 || true
for volume in 3dp-manager_pg_data 3dpmanager_pg_data; do
if docker volume inspect "$volume" >/dev/null 2>&1; then
warn "Removing stale Postgres volume: $volume"
docker volume rm "$volume" >/dev/null 2>&1 || true
fi
done
}
#################################
# ASCII-баннер
#################################
@@ -189,6 +209,7 @@ mkdir -p "$PROJECT_DIR/server"
mkdir -p "$PROJECT_DIR/client"
cd "$PROJECT_DIR"
cleanup_previous_install_data
#################################
# СБОР ДАННЫХ: SSL / HTTPS
@@ -303,13 +324,19 @@ case "$ssl_choice" in
;;
3)
read -rp "Введите домен для панели (например panel.example.com; Enter — использовать IP): " INPUT_HOST
read -rp "Путь к fullchain.pem: " user_cert
read -rp "Путь к privkey.pem: " user_key
if [[ -f "$user_cert" && -f "$user_key" ]]; then
USE_SSL=true
CERT_PATH="$user_cert"
KEY_PATH="$user_key"
UI_HOST=$(hostname -I | awk '{print $1}')
if [ -n "$INPUT_HOST" ]; then
UI_HOST="$INPUT_HOST"
else
UI_HOST=$(hostname -I | awk '{print $1}')
warn "Домен не указан. В итоговом URL будет использован IP: $UI_HOST"
fi
else
warn "Файлы не найдены. Переключение на HTTP."
fi
@@ -339,74 +366,16 @@ ADMIN_USER=$(openssl rand -base64 8)
ADMIN_PASS=$(openssl rand -base64 12)
# Определяем ALLOWED_ORIGINS из домена или IP
if [[ -n "${UI_HOST:-}" ]]; then
if [[ "$UI_HOST" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
ALLOWED_ORIGINS="http://${UI_HOST}"
else
ALLOWED_ORIGINS="https://${UI_HOST}"
URL_SCHEME="http"
if [[ "$USE_SSL" == "true" ]]; then
URL_SCHEME="https"
fi
ALLOWED_ORIGINS="${URL_SCHEME}://${UI_HOST}"
else
ALLOWED_ORIGINS=""
fi
log "Сгенерированы секретные ключи для БД и JWT."
#################################
# Hysteria 2
#################################
# Проверка установки Hysteria 2 через наличие systemd сервиса
if ! systemctl cat hysteria-server.service &> /dev/null; then
echo "Сервис Hysteria 2 не найден. Начинаем установку..."
# Установка Hysteria 2 согласно документации
bash <(curl -fsSL https://get.hy2.sh/) < /dev/null || true
RANDOM_FREE_PORT=$(get_random_port 10000 20000)
# Генерация надежных паролей
GENERATED_PASSWORD=$(openssl rand -base64 16 | tr -dc 'A-Za-z0-9' | cut -c1-16)
GENERATED_OBFS_PASSWORD=$(openssl rand -base64 16 | tr -dc 'A-Za-z0-9' | cut -c1-16)
# Запрос данных у пользователя
echo "=== Настройка Hysteria 2 ==="
read -e -p "Введите email для уведомлений Let's Encrypt: " HYSTERIA_EMAIL
HYSTERIA_EMAIL=$(echo "$HYSTERIA_EMAIL" | tr -cd 'a-zA-Z0-9.@_-')
# Создание конфигурационного файла
cat > /etc/hysteria/config.yaml <<EOF
listen: :$RANDOM_FREE_PORT
acme:
domains:
- $UI_HOST
email: $HYSTERIA_EMAIL
auth:
type: password
password: $GENERATED_PASSWORD
obfs:
type: salamander
salamander:
password: $GENERATED_OBFS_PASSWORD
masquerade:
type: proxy
proxy:
url: https://ya.ru/
rewriteHost: true
EOF
# Перезапуск демона и включение сервиса для автозапуска
systemctl daemon-reload
systemctl enable --now hysteria-server.service
systemctl restart hysteria-server.service
echo "Hysteria 2 успешно установлена и запущена на порту $RANDOM_FREE_PORT"
systemctl status hysteria-server.service --no-pager
else
echo "Hysteria 2 уже установлена, пропускаем установку."
fi
#################################
# ГЕНЕРАЦИЯ ФАЙЛОВ DOCKER
@@ -466,6 +435,8 @@ EOF
# 2. Docker Compose
cat > docker-compose.yml <<EOF
name: 3dp-manager
services:
postgres:
image: postgres:18-alpine
@@ -476,7 +447,7 @@ services:
POSTGRES_PASSWORD: ${DB_PASS}
POSTGRES_DB: 3dp_manager
volumes:
- pg_data:/var/lib/postgresql/data
- pg_data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin -d 3dp_manager"]
interval: 5s
@@ -498,12 +469,12 @@ services:
DB_USERNAME: admin
DB_PASSWORD: ${DB_PASS}
DB_NAME: 3dp_manager
DB_SYNCHRONIZE: "true"
DB_MIGRATIONS_RUN: "false"
JWT_SECRET: ${JWT_SECRET}
ADMIN_LOGIN: ${ADMIN_USER}
ADMIN_PASSWORD: ${ADMIN_PASS}
PORT: 3100
volumes:
- /etc/hysteria/config.yaml:/etc/hysteria/config.yaml:ro
networks:
- app-network
@@ -577,6 +548,8 @@ EOF
# 2. Docker Compose
cat > docker-compose.yml <<EOF
name: 3dp-manager
services:
postgres:
image: postgres:18-alpine
@@ -587,7 +560,7 @@ services:
POSTGRES_PASSWORD: ${DB_PASS}
POSTGRES_DB: 3dp_manager
volumes:
- pg_data:/var/lib/postgresql/data
- pg_data:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U admin -d 3dp_manager"]
interval: 5s
@@ -609,12 +582,12 @@ services:
DB_USERNAME: admin
DB_PASSWORD: ${DB_PASS}
DB_NAME: 3dp_manager
DB_SYNCHRONIZE: "true"
DB_MIGRATIONS_RUN: "false"
JWT_SECRET: ${JWT_SECRET}
ADMIN_LOGIN: ${ADMIN_USER}
ADMIN_PASSWORD: ${ADMIN_PASS}
PORT: 3100
volumes:
- /etc/hysteria/config.yaml:/etc/hysteria/config.yaml:ro
networks:
- app-network
@@ -647,6 +620,9 @@ log "Сборка и запуск контейнеров..."
# Останавливаем старые, если были
"${COMPOSE_CMD[@]}" down || true
# Подтягиваем свежие образы, потому что тег релиза переиспользуется.
"${COMPOSE_CMD[@]}" pull || warn "Не удалось обновить образы перед запуском. Будет использован локальный кэш, если он есть."
# Запускаем сборку и старт
"${COMPOSE_CMD[@]}" up --build -d --remove-orphans
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "3dp-manager",
"version": "2.1.0",
"version": "2.2.0",
"description": "Inbound generator for 3x-ui",
"private": false,
"repository": {
+1 -1
View File
@@ -54,4 +54,4 @@ ENV PORT=3100
EXPOSE 3100
CMD ["node", "dist/main"]
CMD ["node", "dist/src/main"]
+1 -1
View File
@@ -11,7 +11,7 @@
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"start:prod": "node dist/src/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
+142
View File
@@ -0,0 +1,142 @@
import { NestFactory } from '@nestjs/core';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import { AppModule } from '../src/app.module';
import { InboundBuilderService } from '../src/inbounds/inbound-builder.service';
import { XuiInboundRaw } from '../src/inbounds/xui-inbound.types';
import { Node } from '../src/nodes/entities/node.entity';
import { XuiService } from '../src/xui/xui.service';
const SNI = process.env.SMOKE_SNI || 'www.cloudflare.com';
type SmokeResult = {
type: string;
port: number;
success: boolean;
xuiId?: number | null;
deleted?: boolean;
error?: string;
};
const randomPort = () => Math.floor(Math.random() * (60000 - 20000 + 1)) + 20000;
async function main() {
console.log('Starting inbound smoke test...');
const app = await NestFactory.createApplicationContext(AppModule, {
logger: ['error', 'warn', 'log'],
});
console.log('Application context is ready.');
const nodeRepo = app.get<Repository<Node>>(getRepositoryToken(Node));
const xuiService = app.get(XuiService);
const builder = app.get(InboundBuilderService);
const node = await nodeRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.isMain = :isMain', { isMain: true })
.getOne();
if (!node) {
throw new Error('Main node not found');
}
console.log(`Main node loaded: ${node.name}`);
const keys = await xuiService.getNewX25519Cert(node);
if (!keys) {
throw new Error('Could not get Reality keys from the main node');
}
console.log('Reality keys received.');
const buildCases: Array<{
type: string;
build: (port: number, uuid: string) => XuiInboundRaw;
}> = [
{
type: 'vless-tcp-reality',
build: (port, uuid) => builder.buildVlessRealityTcp({ port, uuid, sni: SNI, ...keys }),
},
{
type: 'vless-xhttp-reality',
build: (port, uuid) => builder.buildVlessRealityXhttp({ port, uuid, sni: SNI, ...keys }),
},
{
type: 'vless-grpc-reality',
build: (port, uuid) => builder.buildVlessRealityGrpc({ port, uuid, sni: SNI, ...keys }),
},
{
type: 'vless-ws',
build: (port, uuid) => builder.buildVlessWs({ port, uuid, sni: SNI }),
},
{
type: 'vmess-tcp',
build: (port, uuid) => builder.buildVmessTcp({ port, uuid }),
},
{
type: 'shadowsocks-tcp',
build: (port, uuid) => builder.buildShadowsocksTcp({ port, uuid }),
},
{
type: 'trojan-tcp-reality',
build: (port, uuid) => builder.buildTrojanRealityTcp({ port, uuid, sni: SNI, ...keys }),
},
{
type: 'hysteria2-udp',
build: (port, uuid) => builder.buildHysteria2Inbound({ port, uuid, sni: SNI }),
},
];
const results: SmokeResult[] = [];
for (const testCase of buildCases) {
const port = randomPort();
const uuid = uuidv4();
let xuiId: number | null = null;
try {
console.log(`Testing ${testCase.type} on port ${port}...`);
const config = testCase.build(port, uuid);
config.remark = `smoke-${testCase.type}-${Date.now()}`;
xuiId = await xuiService.addInbound(config, node);
if (xuiId) {
console.log(`${testCase.type}: created with xuiId=${xuiId}; deleting...`);
await xuiService.deleteInbound(xuiId, node);
}
results.push({
type: testCase.type,
port,
success: Boolean(xuiId),
xuiId,
deleted: Boolean(xuiId),
});
console.log(`${testCase.type}: ${xuiId ? 'ok' : 'failed'}`);
} catch (error) {
if (xuiId) {
await xuiService.deleteInbound(xuiId, node);
}
results.push({
type: testCase.type,
port,
success: false,
xuiId,
deleted: Boolean(xuiId),
error: error instanceof Error ? error.message : 'Unknown error',
});
}
}
console.table(results);
await app.close();
const failed = results.filter((result) => !result.success);
process.exitCode = failed.length > 0 ? 1 : 0;
}
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exitCode = 1;
});
+14 -2
View File
@@ -22,6 +22,11 @@ import { ClientModule } from './client/client.module';
import { TunnelsModule } from './tunnels/tunnels.module';
import { Tunnel } from './tunnels/entities/tunnel.entity';
import { SessionModule } from './session/session.module';
import { Node } from './nodes/entities/node.entity';
import { NodesModule } from './nodes/nodes.module';
import { AddNodesAndNodeRelations1765960000000 } from './migrations/1765960000000-add-nodes-and-node-relations';
import { AddNodeIpFlagAndInboundLabels1770000000000 } from './migrations/1770000000000-add-node-ip-flag-and-inbound-labels';
import { AddNodeDomain1770000000001 } from './migrations/1770000000001-add-node-domain';
@Module({
imports: [
@@ -41,8 +46,14 @@ import { SessionModule } from './session/session.module';
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
entities: [Setting, Domain, Subscription, Inbound, Tunnel],
synchronize: true,
entities: [Setting, Domain, Subscription, Inbound, Tunnel, Node],
migrations: [
AddNodesAndNodeRelations1765960000000,
AddNodeIpFlagAndInboundLabels1770000000000,
AddNodeDomain1770000000001,
],
synchronize: process.env.DB_SYNCHRONIZE !== 'false',
migrationsRun: process.env.DB_MIGRATIONS_RUN === 'true',
}),
SessionModule,
XuiModule,
@@ -54,6 +65,7 @@ import { SessionModule } from './session/session.module';
AuthModule,
ClientModule,
TunnelsModule,
NodesModule,
],
controllers: [AppController],
providers: [
@@ -1,5 +1,7 @@
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { Subscription } from '../../subscriptions/entities/subscription.entity';
import { Node } from '../../nodes/entities/node.entity';
import { Tunnel } from '../../tunnels/entities/tunnel.entity';
@Entity()
export class Inbound {
@@ -23,4 +25,19 @@ export class Inbound {
@ManyToOne(() => Subscription, (sub) => sub.inbounds, { onDelete: 'CASCADE' })
subscription: Subscription;
@Column({ nullable: true })
nodeId?: string;
@ManyToOne(() => Node, (node) => node.inbounds, {
nullable: true,
onDelete: 'SET NULL',
})
node?: Node;
@Column({ nullable: true })
relayServerId?: number;
@ManyToOne(() => Tunnel, { nullable: true, onDelete: 'SET NULL' })
relayServer?: Tunnel;
}
+151 -1
View File
@@ -422,6 +422,93 @@ export class InboundBuilderService {
};
}
buildHysteria2Inbound(params: {
port: number;
uuid: string;
sni: string;
certificateFile?: string;
keyFile?: string;
}) {
const { port, uuid, sni } = params;
const certificateFile =
params.certificateFile || `/root/cert/${sni}/fullchain.pem`;
const keyFile =
params.keyFile || `/root/cert/${sni}/privkey.pem`;
const obfsPassword = crypto.randomBytes(8).toString('hex');
return {
enable: true,
port,
protocol: 'hysteria',
remark: 'hysteria2-udp',
settings: JSON.stringify({
clients: [
{
auth: uuid,
email: uuid,
enable: true,
},
],
version: 2,
}),
streamSettings: JSON.stringify({
network: 'hysteria',
security: 'tls',
finalmask: {
udp: [
{
settings: {
password: obfsPassword,
},
type: 'salamander',
},
],
},
hysteriaSettings: {
auth: uuid,
masquerade: {
content: '',
dir: '',
headers: {},
rewriteHost: false,
statusCode: 0,
type: 'proxy',
url: 'https://google.com',
},
udpIdleTimeout: 60,
version: 2,
},
tlsSettings: {
serverName: sni,
alpn: ['h3'],
certificates: [
{
buildChain: false,
certificateFile,
keyFile,
oneTimeLoading: false,
usage: 'encipherment',
},
],
cipherSuites: '',
disableSystemRoot: false,
echForceQuery: 'none',
echServerKeys: '',
enableSessionResumption: false,
maxVersion: '1.3',
minVersion: '1.2',
rejectUnknownSni: false,
},
}),
sniffing: JSON.stringify({
enabled: false,
destOverride: ['http', 'tls', 'quic', 'fakedns'],
metadataOnly: false,
routeOnly: false,
}),
};
}
generateUuid() {
return uuidv4();
}
@@ -448,6 +535,10 @@ export class InboundBuilderService {
case 'trojan':
link = this.buildTrojanLink(inbound, sni, idOrPass);
break;
case 'hysteria':
case 'hysteria2':
link = this.buildHysteria2PanelLink(inbound, sni, idOrPass, flagEmoji);
break;
}
return link;
@@ -595,6 +686,49 @@ export class InboundBuilderService {
);
}
private buildHysteria2PanelLink(
inbound: XuiInboundRaw,
serverAddress: string,
password: string,
flagEmoji: string,
) {
const stream = JSON.parse(inbound.streamSettings) as {
tlsSettings?: { serverName?: string };
finalmask?: { udp?: Array<{ type?: string; settings?: { password?: string } }> };
};
const settings = JSON.parse(inbound.settings) as {
clients?: Array<{ auth?: string; password?: string }>;
};
const auth = settings.clients?.[0]?.auth || settings.clients?.[0]?.password || password;
const finalmask = stream.finalmask?.udp?.[0];
const params = new URLSearchParams();
params.set('security', 'tls');
params.set('fp', 'chrome');
params.set('alpn', 'h3');
const fmConfig = {
udp: [
{
type: finalmask.type,
settings: {
password: finalmask.settings.password,
},
},
],
};
params.set('fm', JSON.stringify(fmConfig));
params.set('sni', stream.tlsSettings?.serverName || serverAddress);
if (finalmask?.type) params.set('obfs', finalmask.type);
if (finalmask?.settings?.password) {
params.set('obfs-password', finalmask.settings.password);
}
return (
`hy2://${auth}@${serverAddress}:${inbound.port}/?${params.toString()}` +
`#${flagEmoji}%20${encodeURIComponent(inbound.remark || '')}`
);
}
buildHysteria2Link(
serverAddress: string,
sni: string,
@@ -633,11 +767,27 @@ export class InboundBuilderService {
}
const params = new URLSearchParams();
params.set('insecure', '0');
params.set('security', 'tls');
params.set('fp', 'chrome');
params.set('alpn', 'h3');
params.set('sni', serverAddress);
params.set('obfs', obfs);
params.set('obfs-password', obfsPass);
const fmConfig = {
udp: [
{
type: obfs,
settings: {
password: obfsPass,
},
},
],
};
params.set('fm', JSON.stringify(fmConfig));
return `hy2://${auth}@${serverAddress}:${port}/?${params.toString()}#${remark}`;
}
}
@@ -0,0 +1,126 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddNodesAndNodeRelations1765960000000
implements MigrationInterface
{
name = 'AddNodesAndNodeRelations1765960000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'node_protocol_enum') THEN
CREATE TYPE "node_protocol_enum" AS ENUM ('http', 'https');
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'node_authtype_enum') THEN
CREATE TYPE "node_authtype_enum" AS ENUM ('password', 'token');
END IF;
END
$$;
`);
await queryRunner.query(`
CREATE TABLE IF NOT EXISTS "node" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"name" character varying NOT NULL,
"url" character varying,
"host" character varying,
"port" integer,
"protocol" "node_protocol_enum" DEFAULT 'https',
"authType" "node_authtype_enum" NOT NULL DEFAULT 'password',
"login" character varying,
"password" character varying,
"token" character varying,
"isMain" boolean NOT NULL DEFAULT false,
"version" character varying,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT "PK_node_id" PRIMARY KEY ("id")
)
`);
await queryRunner.query(`
ALTER TABLE "node"
ADD COLUMN IF NOT EXISTS "url" character varying
`);
await queryRunner.query(`
ALTER TABLE "node"
ALTER COLUMN "host" DROP NOT NULL,
ALTER COLUMN "port" DROP NOT NULL,
ALTER COLUMN "protocol" DROP NOT NULL
`).catch(() => undefined);
await queryRunner.query(`
CREATE UNIQUE INDEX IF NOT EXISTS "IDX_node_single_main"
ON "node" ("isMain")
WHERE "isMain" = true
`);
await queryRunner.query(`
ALTER TABLE "subscription"
ADD COLUMN IF NOT EXISTS "nodeId" uuid,
ADD COLUMN IF NOT EXISTS "relayServerId" integer
`);
await queryRunner.query(`
ALTER TABLE "inbound"
ADD COLUMN IF NOT EXISTS "nodeId" uuid,
ADD COLUMN IF NOT EXISTS "relayServerId" integer
`);
await queryRunner.query(`
ALTER TABLE "tunnel"
ADD COLUMN IF NOT EXISTS "nodeId" uuid,
ADD COLUMN IF NOT EXISTS "ports" text
`);
await queryRunner.query(`
ALTER TABLE "subscription"
ADD CONSTRAINT "FK_subscription_node"
FOREIGN KEY ("nodeId") REFERENCES "node"("id") ON DELETE SET NULL
`).catch(() => undefined);
await queryRunner.query(`
ALTER TABLE "subscription"
ADD CONSTRAINT "FK_subscription_relay"
FOREIGN KEY ("relayServerId") REFERENCES "tunnel"("id") ON DELETE SET NULL
`).catch(() => undefined);
await queryRunner.query(`
ALTER TABLE "inbound"
ADD CONSTRAINT "FK_inbound_node"
FOREIGN KEY ("nodeId") REFERENCES "node"("id") ON DELETE SET NULL
`).catch(() => undefined);
await queryRunner.query(`
ALTER TABLE "inbound"
ADD CONSTRAINT "FK_inbound_relay"
FOREIGN KEY ("relayServerId") REFERENCES "tunnel"("id") ON DELETE SET NULL
`).catch(() => undefined);
await queryRunner.query(`
ALTER TABLE "tunnel"
ADD CONSTRAINT "FK_tunnel_node"
FOREIGN KEY ("nodeId") REFERENCES "node"("id") ON DELETE SET NULL
`).catch(() => undefined);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "tunnel" DROP CONSTRAINT IF EXISTS "FK_tunnel_node"`);
await queryRunner.query(`ALTER TABLE "inbound" DROP CONSTRAINT IF EXISTS "FK_inbound_relay"`);
await queryRunner.query(`ALTER TABLE "inbound" DROP CONSTRAINT IF EXISTS "FK_inbound_node"`);
await queryRunner.query(`ALTER TABLE "subscription" DROP CONSTRAINT IF EXISTS "FK_subscription_relay"`);
await queryRunner.query(`ALTER TABLE "subscription" DROP CONSTRAINT IF EXISTS "FK_subscription_node"`);
await queryRunner.query(`ALTER TABLE "tunnel" DROP COLUMN IF EXISTS "ports"`);
await queryRunner.query(`ALTER TABLE "tunnel" DROP COLUMN IF EXISTS "nodeId"`);
await queryRunner.query(`ALTER TABLE "inbound" DROP COLUMN IF EXISTS "relayServerId"`);
await queryRunner.query(`ALTER TABLE "inbound" DROP COLUMN IF EXISTS "nodeId"`);
await queryRunner.query(`ALTER TABLE "subscription" DROP COLUMN IF EXISTS "relayServerId"`);
await queryRunner.query(`ALTER TABLE "subscription" DROP COLUMN IF EXISTS "nodeId"`);
await queryRunner.query(`DROP INDEX IF EXISTS "IDX_node_single_main"`);
await queryRunner.query(`DROP TABLE IF EXISTS "node"`);
await queryRunner.query(`DROP TYPE IF EXISTS "node_authtype_enum"`);
await queryRunner.query(`DROP TYPE IF EXISTS "node_protocol_enum"`);
}
}
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddNodeIpFlagAndInboundLabels1770000000000
implements MigrationInterface
{
name = 'AddNodeIpFlagAndInboundLabels1770000000000';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "node"
ADD COLUMN IF NOT EXISTS "ip" character varying,
ADD COLUMN IF NOT EXISTS "flag" character varying
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "node" DROP COLUMN IF EXISTS "flag"`);
await queryRunner.query(`ALTER TABLE "node" DROP COLUMN IF EXISTS "ip"`);
}
}
@@ -0,0 +1,18 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class AddNodeDomain1770000000001 implements MigrationInterface {
name = 'AddNodeDomain1770000000001';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
ALTER TABLE "node"
ADD COLUMN IF NOT EXISTS "domain" character varying
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "node" DROP COLUMN IF EXISTS "domain"`,
);
}
}
+62
View File
@@ -0,0 +1,62 @@
import {
IsBoolean,
IsEnum,
IsIP,
IsOptional,
IsString,
MinLength,
ValidateIf,
} from 'class-validator';
import { PartialType } from '@nestjs/mapped-types';
import { NodeAuthType } from '../entities/node.entity';
export class CreateNodeDto {
@IsString()
@MinLength(2)
name: string;
@IsString()
url: string;
@IsIP()
@IsOptional()
ip?: string;
@IsString()
@IsOptional()
domain?: string;
@IsString()
@IsOptional()
flag?: string;
@IsEnum(NodeAuthType)
authType: NodeAuthType;
@ValidateIf((dto: CreateNodeDto) => dto.authType === NodeAuthType.Password)
@IsString()
login?: string;
@ValidateIf((dto: CreateNodeDto) => dto.authType === NodeAuthType.Password)
@IsString()
password?: string;
@ValidateIf((dto: CreateNodeDto) => dto.authType === NodeAuthType.Token)
@IsString()
token?: string;
@IsBoolean()
@IsOptional()
isMain?: boolean;
@IsString()
@IsOptional()
version?: string;
}
export class UpdateNodeDto extends PartialType(CreateNodeDto) {}
export class NodeConnectionDto {
@IsString()
id: string;
}
+89
View File
@@ -0,0 +1,89 @@
import {
Column,
CreateDateColumn,
Entity,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { Inbound } from '../../inbounds/entities/inbound.entity';
import { Subscription } from '../../subscriptions/entities/subscription.entity';
import { Tunnel } from '../../tunnels/entities/tunnel.entity';
export enum NodeAuthType {
Password = 'password',
Token = 'token',
}
export enum NodeProtocol {
Http = 'http',
Https = 'https',
}
@Entity()
export class Node {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
name: string;
@Column({ nullable: true })
url?: string;
@Column({ nullable: true })
host?: string;
@Column({ nullable: true })
domain?: string;
@Column({ nullable: true })
ip?: string;
@Column({ nullable: true })
flag?: string;
@Column({ type: 'int', nullable: true })
port?: number;
@Column({
type: 'enum',
enum: NodeProtocol,
default: NodeProtocol.Https,
nullable: true,
})
protocol?: NodeProtocol;
@Column({ type: 'enum', enum: NodeAuthType, default: NodeAuthType.Password })
authType: NodeAuthType;
@Column({ nullable: true })
login?: string;
@Column({ select: false, nullable: true })
password?: string;
@Column({ select: false, nullable: true })
token?: string;
@Column({ default: false })
isMain: boolean;
@Column({ nullable: true })
version?: string;
@OneToMany(() => Subscription, (subscription) => subscription.node)
subscriptions: Subscription[];
@OneToMany(() => Inbound, (inbound) => inbound.node)
inbounds: Inbound[];
@OneToMany(() => Tunnel, (tunnel) => tunnel.node)
tunnels: Tunnel[];
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
+53
View File
@@ -0,0 +1,53 @@
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { CreateNodeDto, UpdateNodeDto } from './dto/node.dto';
import { NodesService } from './nodes.service';
@Controller('nodes')
export class NodesController {
constructor(private readonly nodesService: NodesService) {}
@Get()
findAll() {
return this.nodesService.findAll();
}
@Post()
create(@Body() dto: CreateNodeDto) {
return this.nodesService.create(dto);
}
@Post('check')
checkPayload(@Body() dto: CreateNodeDto) {
return this.nodesService.checkPayload(dto);
}
@Post('detect-location')
detectLocation(@Body() body: { url: string }) {
return this.nodesService.detectLocation(body.url);
}
@Put(':id')
update(@Param('id') id: string, @Body() dto: UpdateNodeDto) {
return this.nodesService.update(id, dto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.nodesService.remove(id);
}
@Post(':id/main')
setMain(@Param('id') id: string) {
return this.nodesService.setMain(id);
}
@Post(':id/check')
check(@Param('id') id: string) {
return this.nodesService.checkConnection(id);
}
@Post('sync/main')
syncFromMain() {
return this.nodesService.syncFromMain();
}
}
+20
View File
@@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Node } from './entities/node.entity';
import { NodesController } from './nodes.controller';
import { NodesService } from './nodes.service';
import { XuiModule } from '../xui/xui.module';
import { Subscription } from '../subscriptions/entities/subscription.entity';
import { Tunnel } from '../tunnels/entities/tunnel.entity';
import { Inbound } from '../inbounds/entities/inbound.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Node, Subscription, Tunnel, Inbound]),
XuiModule,
],
controllers: [NodesController],
providers: [NodesService],
exports: [NodesService, TypeOrmModule],
})
export class NodesModule {}
+435
View File
@@ -0,0 +1,435 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateNodeDto, UpdateNodeDto } from './dto/node.dto';
import { Node, NodeAuthType, NodeProtocol } from './entities/node.entity';
import { XuiService } from '../xui/xui.service';
import { Subscription } from '../subscriptions/entities/subscription.entity';
import { Tunnel } from '../tunnels/entities/tunnel.entity';
import { Inbound } from '../inbounds/entities/inbound.entity';
import * as dns from 'dns/promises';
import * as net from 'net';
import { COUNTRIES } from '../settings/countries';
type GeoResult = {
ip: string;
country?: string;
countryCode?: string;
flag?: string;
};
const getDomainFromHost = (host?: string) =>
host && net.isIP(host) === 0 ? host : undefined;
@Injectable()
export class NodesService {
constructor(
@InjectRepository(Node)
private readonly nodesRepo: Repository<Node>,
@InjectRepository(Subscription)
private readonly subscriptionsRepo: Repository<Subscription>,
@InjectRepository(Tunnel)
private readonly tunnelsRepo: Repository<Tunnel>,
@InjectRepository(Inbound)
private readonly inboundsRepo: Repository<Inbound>,
private readonly xuiService: XuiService,
) {}
findAll() {
return this.nodesRepo.find({ order: { isMain: 'DESC', createdAt: 'DESC' } });
}
async findOneWithSecrets(id: string) {
const node = await this.nodesRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.id = :id', { id })
.getOne();
if (!node) {
throw new NotFoundException('Node not found');
}
return node;
}
async getDefaultNode() {
return this.nodesRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.isMain = :isMain', { isMain: true })
.getOne();
}
async create(dto: CreateNodeDto) {
this.assertCredentials(dto);
const resolved = await this.resolveNodeLocation(dto.url, dto.flag, dto.ip);
const node = this.nodesRepo.create({
...dto,
url: this.normalizeUrl(dto.url),
host: resolved.host,
domain: dto.domain || resolved.domain,
port: resolved.port,
protocol: resolved.protocol,
ip: resolved.ip,
flag: resolved.flag,
isMain: dto.isMain ?? false,
});
if ((await this.nodesRepo.count()) === 0) {
node.isMain = true;
}
if (node.isMain) {
await this.clearMainNode();
}
return this.nodesRepo.save(node);
}
async update(id: string, dto: UpdateNodeDto) {
const node = await this.findOneWithSecrets(id);
const nextAuthType = dto.authType ?? node.authType;
if (nextAuthType === NodeAuthType.Password) {
const login = dto.login ?? node.login;
const password = dto.password ?? node.password;
if (!login || !password) {
throw new BadRequestException('Login and password are required');
}
}
if (nextAuthType === NodeAuthType.Token) {
const token = dto.token ?? node.token;
if (!token) {
throw new BadRequestException('Token is required');
}
}
Object.assign(node, dto);
if (dto.url) {
node.url = this.normalizeUrl(dto.url);
const resolved = await this.resolveNodeLocation(
dto.url,
dto.flag ?? node.flag,
dto.ip,
);
node.host = resolved.host;
node.domain = dto.domain || resolved.domain;
node.port = resolved.port;
node.protocol = resolved.protocol;
node.ip = resolved.ip;
node.flag = resolved.flag;
} else {
if (dto.domain !== undefined) node.domain = dto.domain;
if (dto.ip) node.ip = dto.ip;
if (dto.flag) node.flag = dto.flag;
}
if (dto.isMain) {
await this.clearMainNode(id);
node.isMain = true;
}
return this.nodesRepo.save(node);
}
async remove(id: string) {
const node = await this.findOneWithSecrets(id);
const nodeCount = await this.nodesRepo.count();
await this.cleanupNodeDependencies(node, nodeCount === 1);
await this.nodesRepo.remove(node);
const main = await this.getDefaultNode();
if (!main) {
const fallback = await this.nodesRepo.findOne({
where: {},
order: { createdAt: 'DESC' },
});
if (fallback) {
fallback.isMain = true;
await this.nodesRepo.save(fallback);
}
}
return { success: true };
}
private async cleanupNodeDependencies(node: Node, isLastNode: boolean) {
await this.deleteNodeInbounds(node);
const id = node.id;
if (isLastNode) {
await this.subscriptionsRepo.createQueryBuilder().delete().execute();
await this.tunnelsRepo.createQueryBuilder().delete().execute();
return;
}
await this.tunnelsRepo.delete({ nodeId: id });
await this.inboundsRepo.delete({ nodeId: id });
const subscriptions = await this.subscriptionsRepo.find({
where: [{ nodeId: id }],
});
for (const sub of subscriptions) {
sub.nodeId = undefined;
sub.node = undefined;
await this.subscriptionsRepo.save(sub);
}
const configuredSubscriptions = await this.subscriptionsRepo.find();
for (const sub of configuredSubscriptions) {
const config = sub.inboundsConfig || [];
const nextConfig = config.map((item) => {
if (item.nodeId !== id) return item;
const { nodeId: _nodeId, relayServerId: _relayServerId, ...rest } = item;
return rest;
});
if (JSON.stringify(nextConfig) !== JSON.stringify(config)) {
sub.inboundsConfig = nextConfig;
await this.subscriptionsRepo.save(sub);
}
}
}
private async deleteNodeInbounds(node: Node) {
const inbounds = await this.inboundsRepo.find({
where: { nodeId: node.id },
});
for (const inbound of inbounds) {
if (inbound.xuiId && inbound.xuiId > 0) {
const isDeleted = await this.xuiService.deleteInbound(
inbound.xuiId,
node,
);
if (!isDeleted) {
throw new BadRequestException(
`Failed to delete inbound ${inbound.xuiId} from 3x-ui`,
);
}
}
}
}
async setMain(id: string) {
const node = await this.findOneWithSecrets(id);
await this.clearMainNode(id);
node.isMain = true;
return this.nodesRepo.save(node);
}
async checkConnection(id: string) {
const node = await this.findOneWithSecrets(id);
const status = await this.xuiService.checkNodeConnection(node);
return { success: status.success, version: status.version };
}
async syncFromMain() {
const main = await this.getDefaultNode();
if (!main) {
throw new BadRequestException('Main node is not configured');
}
const discovered = await this.xuiService.getNodes(main);
const synced: Node[] = [];
for (const item of discovered) {
if (!item.host || !item.port) {
continue;
}
const url = `${item.protocol}://${item.host}:${item.port}`.replace(
/\/+$/,
'',
);
const existing = await this.nodesRepo.findOne({
where: { url },
});
if (existing) {
existing.name = item.name || existing.name;
existing.version = item.version || existing.version;
synced.push(await this.nodesRepo.save(existing));
continue;
}
synced.push(
await this.nodesRepo.save(
this.nodesRepo.create({
name: item.name || item.host,
url,
host: item.host,
domain: getDomainFromHost(item.host),
port: item.port,
ip: await this.resolveIp(item.host),
flag: (
await this.lookupGeo(await this.resolveIp(item.host))
)?.flag,
protocol:
item.protocol === NodeProtocol.Http
? NodeProtocol.Http
: NodeProtocol.Https,
authType: main.authType,
login: main.login,
password: main.password,
token: main.token,
version: item.version,
isMain: false,
}),
),
);
}
return { success: true, count: synced.length, nodes: synced };
}
private assertCredentials(dto: CreateNodeDto) {
if (dto.authType === NodeAuthType.Password && (!dto.login || !dto.password)) {
throw new BadRequestException('Login and password are required');
}
if (dto.authType === NodeAuthType.Token && !dto.token) {
throw new BadRequestException('Token is required');
}
}
private async clearMainNode(exceptId?: string) {
const qb = this.nodesRepo
.createQueryBuilder()
.update(Node)
.set({ isMain: false })
.where('isMain = :isMain', { isMain: true });
if (exceptId) {
qb.andWhere('id != :exceptId', { exceptId });
}
await qb.execute();
}
async checkPayload(dto: CreateNodeDto) {
this.assertCredentials(dto);
const node = this.nodesRepo.create({
...dto,
url: this.normalizeUrl(dto.url),
});
const status = await this.xuiService.checkNodeConnection(node);
return { success: status.success, version: status.version };
}
async detectLocation(url: string) {
const resolved = await this.resolveNodeLocation(url);
return {
ip: resolved.ip,
host: resolved.host,
domain: resolved.domain,
port: resolved.port,
protocol: resolved.protocol,
flag: resolved.flag,
country: resolved.country,
countryCode: resolved.countryCode,
};
}
private async resolveNodeLocation(
url: string,
preferredFlag?: string,
preferredIp?: string,
) {
const normalized = this.normalizeUrl(url);
const parsed = this.parseUrl(normalized);
const ip = preferredIp || (await this.resolveIp(parsed.host));
const geo = ip ? await this.lookupGeo(ip) : undefined;
return {
...parsed,
domain: getDomainFromHost(parsed.host),
ip,
country: geo?.country,
countryCode: geo?.countryCode,
flag: preferredFlag || geo?.flag,
};
}
private parseUrl(url: string) {
try {
const parsed = new URL(url);
return {
host: parsed.hostname,
port: parsed.port ? Number(parsed.port) : undefined,
protocol:
parsed.protocol.replace(':', '') === NodeProtocol.Http
? NodeProtocol.Http
: NodeProtocol.Https,
};
} catch {
return { host: url, port: undefined, protocol: NodeProtocol.Https };
}
}
private async resolveIp(host?: string) {
if (!host || host === 'localhost') return undefined;
if (net.isIP(host) !== 0) return host;
try {
const result = await dns.lookup(host);
return result.address;
} catch {
return undefined;
}
}
private async lookupGeo(ip?: string): Promise<GeoResult | undefined> {
if (!ip || ip === '127.0.0.1') return undefined;
const fromCode = (countryCode?: string, country?: string) => {
const countryInfo = COUNTRIES.find((c) => c.code === countryCode);
return countryInfo
? { ip, country: countryInfo.name, countryCode, flag: countryInfo.emoji }
: { ip, country, countryCode };
};
try {
const res = await fetch(`https://ipwho.is/${ip}`);
const data = (await res.json()) as {
success?: boolean;
country?: string;
country_code?: string;
};
if (data.success !== false) {
return fromCode(data.country_code, data.country);
}
} catch {
// Fallback below.
}
try {
const res = await fetch(`http://ip-api.com/json/${ip}`);
const data = (await res.json()) as {
status?: string;
country?: string;
countryCode?: string;
};
if (data.status === 'success') {
return fromCode(data.countryCode, data.country);
}
} catch {
return undefined;
}
}
private normalizeUrl(url: string) {
return url.trim().replace(/\/+$/, '');
}
}
+3 -1
View File
@@ -11,10 +11,12 @@ import { Inbound } from '../inbounds/entities/inbound.entity';
import { Domain } from '../domains/entities/domain.entity';
import { Setting } from '../settings/entities/setting.entity';
import { RotationController } from './rotation.controller';
import { Node } from '../nodes/entities/node.entity';
import { Tunnel } from '../tunnels/entities/tunnel.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Subscription, Inbound, Domain, Setting]),
TypeOrmModule.forFeature([Subscription, Inbound, Domain, Setting, Node, Tunnel]),
ScheduleModule.forRoot(),
XuiModule,
InboundsModule,
+182 -21
View File
@@ -7,6 +7,8 @@ import { Subscription } from '../subscriptions/entities/subscription.entity';
import { Inbound } from '../inbounds/entities/inbound.entity';
import { Domain } from '../domains/entities/domain.entity';
import { Setting } from '../settings/entities/setting.entity';
import { Node } from '../nodes/entities/node.entity';
import { Tunnel } from '../tunnels/entities/tunnel.entity';
import { XuiService } from '../xui/xui.service';
import { InboundBuilderService } from '../inbounds/inbound-builder.service';
@@ -22,6 +24,8 @@ export class RotationService implements OnModuleInit {
@InjectRepository(Inbound) private inboundRepo: Repository<Inbound>,
@InjectRepository(Domain) private domainRepo: Repository<Domain>,
@InjectRepository(Setting) private settingRepo: Repository<Setting>,
@InjectRepository(Node) private nodeRepo: Repository<Node>,
@InjectRepository(Tunnel) private tunnelRepo: Repository<Tunnel>,
private xuiService: XuiService,
private inboundBuilder: InboundBuilderService,
) {}
@@ -127,7 +131,8 @@ export class RotationService implements OnModuleInit {
async performRotation() {
this.logger.debug('Запуск плановой ротации...');
const isLoginSuccess = await this.xuiService.login();
const defaultNode = await this.getDefaultNode();
const isLoginSuccess = defaultNode ? true : await this.xuiService.login();
if (!isLoginSuccess) {
this.logger.error('Отмена ротации: Не удалось войти в панель 3x-ui');
return { success: false, message: 'Не удалось войти в панель 3x-ui' };
@@ -138,7 +143,7 @@ export class RotationService implements OnModuleInit {
isEnabled: true,
isAutoRotationEnabled: true,
},
relations: ['inbounds'],
relations: ['inbounds', 'inbounds.node', 'node', 'relayServer'],
});
if (subscriptions.length === 0) {
return { success: false, message: 'Нет активных подписок для ротации' };
@@ -151,41 +156,62 @@ export class RotationService implements OnModuleInit {
}
for (const sub of subscriptions) {
await this.rotateSubscription(sub, domains);
const rotated = await this.rotateSubscription(sub, domains, defaultNode);
if (!rotated) {
return {
success: false,
message: 'Failed to delete old inbounds',
};
}
}
this.logger.debug('Ротация завершена.');
return { success: true, message: 'Ротация успешно выполнена' };
}
private async rotateSubscription(sub: Subscription, domains: Domain[]) {
private async rotateSubscription(
sub: Subscription,
domains: Domain[],
defaultNode: Node | null,
) {
this.logger.debug(`Ротация для подписки: ${sub.name} (${sub.uuid})`);
// Удаляем старые инбаунды
if (sub.inbounds && sub.inbounds.length > 0) {
for (const inbound of sub.inbounds) {
if (inbound.xuiId && inbound.xuiId > 0) {
await this.xuiService.deleteInbound(inbound.xuiId);
const isDeleted = await this.xuiService.deleteInbound(
inbound.xuiId,
await this.resolveInboundNode(inbound),
);
if (!isDeleted) {
this.logger.error(
`Failed to delete old inbound ${inbound.xuiId}; rotation for subscription ${sub.id} is aborted`,
);
return false;
}
}
await this.inboundRepo.delete(inbound.id);
}
}
const keys = await this.xuiService.getNewX25519Cert();
const baseNode = sub.node ?? defaultNode ?? undefined;
const keys = await this.xuiService.getNewX25519Cert(baseNode);
if (!keys) {
this.logger.error(
'Не удалось получить Reality ключи, пропускаем подписку',
);
return;
return false;
}
const usedPorts = new Set<number>();
const host = await this.settingRepo.findOne({ where: { key: 'xui_host' } });
const serverAddress = host?.value || 'localhost';
const serverAddress =
this.getNodeAddress(baseNode) || host?.value || 'localhost';
const flag = await this.settingRepo.findOne({
where: { key: 'xui_geo_flag' },
});
const flagEmoji = flag?.value ?? '%F0%9F%92%AF';
const defaultFlagEmoji = flag?.value ?? '%F0%9F%92%AF';
// Получаем конфиг или пустой массив
const inboundsConfig = sub.inboundsConfig || [];
@@ -193,6 +219,25 @@ export class RotationService implements OnModuleInit {
for (const config of inboundsConfig) {
const type = config.type;
const uuid = uuidv4();
const targetNode = await this.resolveNode(
config.nodeId,
sub.node,
defaultNode,
);
const resolvedRelay = await this.resolveRelay(
config.relayServerId,
sub.relayServer,
);
const relayServer =
resolvedRelay && this.isRelayAvailableForNode(resolvedRelay, targetNode)
? resolvedRelay
: undefined;
const targetAddress =
relayServer?.domain ||
relayServer?.ip ||
this.getNodeAddress(targetNode) ||
serverAddress;
const flagEmoji = config.flag || targetNode?.flag || defaultFlagEmoji;
let sni = '';
@@ -214,18 +259,54 @@ export class RotationService implements OnModuleInit {
// === 2. Обработка Hysteria2 ===
if (type === 'hysteria2-udp') {
const link = this.inboundBuilder.buildHysteria2Link(
serverAddress,
sni,
flagEmoji + '%20hysteria2-udp',
let port = 0;
if (config.port === 'random' || !config.port) {
port = await this.getFreePort(0, usedPorts);
} else {
port =
typeof config.port === 'string'
? parseInt(config.port, 10)
: config.port;
}
usedPorts.add(port);
const hysteriaSni = this.getNodeAddress(targetNode) || serverAddress;
const hysteriaConfig = this.inboundBuilder.buildHysteria2Inbound({
port,
uuid,
sni: hysteriaSni,
certificateFile: config.certificateFile,
keyFile: config.keyFile,
});
if (config.name?.trim()) {
hysteriaConfig.remark = config.name.trim();
}
const xuiId = await this.xuiService.addInbound(
hysteriaConfig,
targetNode,
);
if (!xuiId) {
this.logger.warn(
'Hysteria2 inbound was not created by 3x-ui; skipping subscription link for this inbound',
);
continue;
}
const link = this.inboundBuilder.buildInboundLink(
hysteriaConfig,
targetAddress,
uuid,
flagEmoji,
);
const newInbound = this.inboundRepo.create({
xuiId: 0,
port: 0, // Обычно Hysteria висит на 443, фактический порт вытаскивается в билдере
xuiId,
port,
protocol: 'hysteria2',
remark: 'hysteria2-udp',
remark: hysteriaConfig.remark,
link: link,
subscription: sub,
node: targetNode,
relayServer,
});
await this.inboundRepo.save(newInbound);
continue;
@@ -295,7 +376,11 @@ export class RotationService implements OnModuleInit {
continue;
}
const xuiId = await this.xuiService.addInbound(xuiConfig);
if (config.name?.trim()) {
xuiConfig.remark = config.name.trim();
}
const xuiId = await this.xuiService.addInbound(xuiConfig, targetNode);
if (xuiId && xuiConfig) {
const settings = JSON.parse(xuiConfig.settings) as {
@@ -306,7 +391,7 @@ export class RotationService implements OnModuleInit {
const fullLink = this.inboundBuilder.buildInboundLink(
xuiConfig,
serverAddress,
targetAddress,
idOrPass,
flagEmoji,
);
@@ -318,10 +403,14 @@ export class RotationService implements OnModuleInit {
remark: xuiConfig.remark,
link: fullLink,
subscription: sub,
node: targetNode,
relayServer,
});
await this.inboundRepo.save(newInbound);
}
}
return true;
}
private pickDomain(list: Domain[]): string {
@@ -356,7 +445,7 @@ export class RotationService implements OnModuleInit {
const sub = await this.subRepo.findOne({
where: { id: subscriptionId },
relations: ['inbounds'],
relations: ['inbounds', 'inbounds.node', 'node', 'relayServer'],
});
if (!sub) {
@@ -367,7 +456,8 @@ export class RotationService implements OnModuleInit {
};
}
const isLoginSuccess = await this.xuiService.login();
const defaultNode = await this.getDefaultNode();
const isLoginSuccess = defaultNode ? true : await this.xuiService.login();
if (!isLoginSuccess) {
this.logger.error('Отмена ротации: Не удалось войти в панель 3x-ui');
return { success: false, message: 'Не удалось войти в панель 3x-ui' };
@@ -379,9 +469,80 @@ export class RotationService implements OnModuleInit {
return { success: false, message: 'Список доменов пуст!' };
}
await this.rotateSubscription(sub, domains);
const rotated = await this.rotateSubscription(sub, domains, defaultNode);
if (!rotated) {
return {
success: false,
message: 'Failed to delete old inbounds',
};
}
this.logger.debug(`Ручная ротация подписки ${subscriptionId} завершена.`);
return { success: true, message: 'Ротация успешно выполнена' };
}
private async getDefaultNode() {
return this.nodeRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.isMain = :isMain', { isMain: true })
.getOne();
}
private async resolveNode(
nodeId?: string,
subscriptionNode?: Node,
defaultNode?: Node | null,
) {
if (!nodeId) return subscriptionNode ?? defaultNode ?? undefined;
return (
(await this.nodeRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.id = :nodeId', { nodeId })
.getOne()) ??
subscriptionNode ??
defaultNode ??
undefined
);
}
private async resolveInboundNode(inbound: Inbound) {
if (!inbound.nodeId) return inbound.node;
return (
(await this.nodeRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.id = :nodeId', { nodeId: inbound.nodeId })
.getOne()) ?? inbound.node
);
}
private async resolveRelay(relayServerId?: number, subscriptionRelay?: Tunnel) {
if (!relayServerId) return subscriptionRelay ?? undefined;
return (await this.tunnelRepo.findOne({ where: { id: relayServerId } })) ?? undefined;
}
private isRelayAvailableForNode(relay: Tunnel, node?: Node) {
if (!relay.nodeId) return true;
return Boolean(node?.id && relay.nodeId === node.id);
}
private getNodeAddress(node?: Node) {
if (!node) return undefined;
if (node.domain) return node.domain;
if (node.ip) return node.ip;
if (node.host) return node.host;
try {
return node.url ? new URL(node.url).hostname : undefined;
} catch {
return node.url;
}
}
}
@@ -26,6 +26,11 @@ export class SettingsController {
);
}
@Get('countries')
countries() {
return COUNTRIES;
}
@Post('check')
async checkConnection(
@Body() body: { xui_url: string; xui_login: string; xui_password: string },
@@ -4,16 +4,50 @@ import {
ValidateNested,
IsOptional,
IsBoolean,
IsUUID,
IsInt,
ValidateIf,
ArrayMinSize,
ArrayMaxSize,
ValidateBy,
ValidationOptions,
} from 'class-validator';
import { Type } from 'class-transformer';
const PORT_OR_RANDOM = 'portOrRandom';
function IsPortOrRandom(validationOptions?: ValidationOptions) {
return ValidateBy(
{
name: PORT_OR_RANDOM,
validator: {
validate: (value: unknown) => {
if (value === undefined || value === null || value === '') {
return true;
}
if (value === 'random') return true;
const port =
typeof value === 'number'
? value
: typeof value === 'string' && /^\d+$/.test(value)
? Number(value)
: NaN;
return Number.isInteger(port) && port >= 1 && port <= 65535;
},
defaultMessage: () =>
'port must be "random" or an integer from 1 to 65535',
},
},
validationOptions,
);
}
export class InboundConfigDto {
@IsString()
type: string;
@IsOptional()
@IsPortOrRandom()
port?: number | string;
@IsString()
@@ -23,6 +57,31 @@ export class InboundConfigDto {
@IsString()
@IsOptional()
link?: string;
@IsUUID()
@IsOptional()
nodeId?: string;
@ValidateIf((dto: InboundConfigDto) => dto.relayServerId !== undefined)
@Type(() => Number)
@IsInt()
relayServerId?: number;
@IsString()
@IsOptional()
flag?: string;
@IsString()
@IsOptional()
name?: string;
@IsString()
@IsOptional()
certificateFile?: string;
@IsString()
@IsOptional()
keyFile?: string;
}
export class CreateSubscriptionDto {
@@ -40,4 +99,13 @@ export class CreateSubscriptionDto {
@IsBoolean()
@IsOptional()
isAutoRotationEnabled?: boolean;
@IsUUID()
@IsOptional()
nodeId?: string;
@ValidateIf((dto: CreateSubscriptionDto) => dto.relayServerId !== undefined)
@Type(() => Number)
@IsInt()
relayServerId?: number;
}
@@ -5,8 +5,11 @@ import {
CreateDateColumn,
UpdateDateColumn,
OneToMany,
ManyToOne,
} from 'typeorm';
import { Inbound } from '../../inbounds/entities/inbound.entity';
import { Node } from '../../nodes/entities/node.entity';
import { Tunnel } from '../../tunnels/entities/tunnel.entity';
@Entity()
export class Subscription {
@@ -31,8 +34,29 @@ export class Subscription {
port?: number | string;
sni?: string;
link?: string;
nodeId?: string;
relayServerId?: number;
flag?: string;
name?: string;
certificateFile?: string;
keyFile?: string;
}>;
@Column({ nullable: true })
nodeId?: string;
@ManyToOne(() => Node, (node) => node.subscriptions, {
nullable: true,
onDelete: 'SET NULL',
})
node?: Node;
@Column({ nullable: true })
relayServerId?: number;
@ManyToOne(() => Tunnel, { nullable: true, onDelete: 'SET NULL' })
relayServer?: Tunnel;
@OneToMany(() => Inbound, (inbound) => inbound.subscription)
inbounds: Inbound[];
@@ -5,9 +5,14 @@ import { SubscriptionsController } from './subscriptions.controller';
import { Subscription } from './entities/subscription.entity';
import { Inbound } from '../inbounds/entities/inbound.entity';
import { XuiModule } from '../xui/xui.module';
import { Node } from '../nodes/entities/node.entity';
import { Tunnel } from '../tunnels/entities/tunnel.entity';
@Module({
imports: [TypeOrmModule.forFeature([Subscription, Inbound]), XuiModule],
imports: [
TypeOrmModule.forFeature([Subscription, Inbound, Node, Tunnel]),
XuiModule,
],
controllers: [SubscriptionsController],
providers: [SubscriptionsService],
exports: [SubscriptionsService],
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Subscription } from './entities/subscription.entity';
@@ -6,28 +6,38 @@ import { XuiService } from '../xui/xui.service';
import { CreateSubscriptionDto } from './dto/create-subscription.dto';
import { UpdateSubscriptionDto } from './dto/update-subscription.dto';
import { v4 as uuidv4 } from 'uuid';
import { Node } from '../nodes/entities/node.entity';
import { Tunnel } from '../tunnels/entities/tunnel.entity';
import { Inbound } from '../inbounds/entities/inbound.entity';
@Injectable()
export class SubscriptionsService {
constructor(
@InjectRepository(Subscription)
private subRepo: Repository<Subscription>,
@InjectRepository(Node)
private nodeRepo: Repository<Node>,
@InjectRepository(Tunnel)
private tunnelRepo: Repository<Tunnel>,
private xuiService: XuiService,
) {}
findAll() {
return this.subRepo.find({
relations: ['inbounds'],
relations: ['inbounds', 'node', 'relayServer'],
order: { createdAt: 'DESC' },
});
}
async create(dto: CreateSubscriptionDto) {
await this.validateInboundsConfig(dto.inboundsConfig);
const sub = this.subRepo.create({
name: dto.name,
uuid: uuidv4(),
inboundsConfig: dto.inboundsConfig || [],
isAutoRotationEnabled: dto.isAutoRotationEnabled ?? true,
node: await this.resolveNode(dto.nodeId),
relayServer: await this.resolveRelay(dto.relayServerId),
});
return this.subRepo.save(sub);
@@ -36,7 +46,7 @@ export class SubscriptionsService {
async update(id: string, dto: UpdateSubscriptionDto) {
const sub = await this.subRepo.findOne({
where: { id },
relations: ['inbounds'],
relations: ['inbounds', 'node', 'relayServer'],
});
if (!sub) {
@@ -49,6 +59,7 @@ export class SubscriptionsService {
}
if (dto.inboundsConfig) {
await this.validateInboundsConfig(dto.inboundsConfig);
sub.inboundsConfig = dto.inboundsConfig;
}
@@ -56,22 +67,139 @@ export class SubscriptionsService {
sub.isAutoRotationEnabled = dto.isAutoRotationEnabled;
}
if ('nodeId' in dto) {
sub.node = await this.resolveNode(dto.nodeId);
sub.nodeId = dto.nodeId;
}
if ('relayServerId' in dto) {
sub.relayServer = await this.resolveRelay(dto.relayServerId);
sub.relayServerId = dto.relayServerId;
}
return this.subRepo.save(sub);
}
async remove(id: string) {
const sub = await this.subRepo.findOne({
where: { id },
relations: ['inbounds'],
relations: ['inbounds', 'inbounds.node'],
});
if (!sub) return;
if (sub.inbounds && sub.inbounds.length > 0) {
for (const inbound of sub.inbounds) {
await this.xuiService.deleteInbound(inbound.xuiId);
if (!inbound.xuiId || inbound.xuiId <= 0) continue;
const isDeleted = await this.xuiService.deleteInbound(
inbound.xuiId,
await this.resolveInboundNode(inbound),
);
if (!isDeleted) {
throw new BadRequestException(
`Failed to delete inbound ${inbound.xuiId} from 3x-ui`,
);
}
}
}
return this.subRepo.remove(sub);
}
private async resolveNode(nodeId?: string | null) {
if (!nodeId) return null;
const node = await this.nodeRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.id = :nodeId', { nodeId })
.getOne();
if (!node) {
throw new BadRequestException('Node not found');
}
return node;
}
private async resolveInboundNode(inbound: Inbound) {
if (!inbound.nodeId) return undefined;
return (
(await this.nodeRepo
.createQueryBuilder('node')
.addSelect('node.password')
.addSelect('node.token')
.where('node.id = :nodeId', { nodeId: inbound.nodeId })
.getOne()) ?? inbound.node
);
}
private async resolveRelay(relayServerId?: number | null) {
if (!relayServerId) return null;
const relay = await this.tunnelRepo.findOne({
where: { id: relayServerId },
});
if (!relay) {
throw new BadRequestException('Relay server not found');
}
return relay;
}
private async validateInboundsConfig(
inboundsConfig?: CreateSubscriptionDto['inboundsConfig'],
) {
for (const config of inboundsConfig || []) {
if (config.type === 'custom') continue;
if (config.nodeId) {
const node = await this.nodeRepo.findOne({
where: { id: config.nodeId },
});
if (!node) {
throw new BadRequestException('Node not found');
}
}
if (config.relayServerId) {
const relay = await this.tunnelRepo.findOne({
where: { id: config.relayServerId },
});
if (!relay) {
throw new BadRequestException('Relay server not found');
}
if (config.nodeId && relay.nodeId && relay.nodeId !== config.nodeId) {
throw new BadRequestException(
'Relay server belongs to another node',
);
}
}
if (
config.port === undefined ||
config.port === null ||
config.port === '' ||
config.port === 'random'
) {
continue;
}
const port =
typeof config.port === 'number'
? config.port
: /^\d+$/.test(config.port)
? Number(config.port)
: NaN;
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new BadRequestException(
'Port must be "random" or an integer from 1 to 65535',
);
}
}
}
}
@@ -0,0 +1,47 @@
import {
IsInt,
IsOptional,
IsString,
IsUUID,
Max,
Min,
MinLength,
ValidateIf,
} from 'class-validator';
import { Type } from 'class-transformer';
export class CreateTunnelDto {
@IsString()
@MinLength(2)
name: string;
@IsUUID()
@IsOptional()
nodeId?: string;
@IsString()
@MinLength(1)
ip: string;
@Type(() => Number)
@IsInt()
@Min(1)
@Max(65535)
sshPort: number;
@IsString()
@MinLength(1)
username: string;
@ValidateIf((dto: CreateTunnelDto) => !dto.privateKey)
@IsString()
password?: string;
@ValidateIf((dto: CreateTunnelDto) => !dto.password)
@IsString()
privateKey?: string;
@IsString()
@IsOptional()
domain?: string;
}
+14 -1
View File
@@ -1,4 +1,5 @@
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { Node } from '../../nodes/entities/node.entity';
@Entity()
export class Tunnel {
@@ -26,6 +27,18 @@ export class Tunnel {
@Column({ nullable: true })
domain: string;
@Column({ nullable: true })
nodeId?: string;
@ManyToOne(() => Node, (node) => node.tunnels, {
nullable: true,
onDelete: 'SET NULL',
})
node?: Node;
@Column({ type: 'simple-array', nullable: true })
ports?: number[];
@Column({ default: false })
isInstalled: boolean;
}
+19 -5
View File
@@ -14,18 +14,30 @@ export class SshService {
privateKey?: string;
},
command: string,
timeoutMs = 120000,
): Promise<string> {
return new Promise((resolve, reject) => {
const conn = new Client();
let timer: NodeJS.Timeout | undefined;
const finish = (callback: () => void) => {
if (timer) clearTimeout(timer);
conn.end();
callback();
};
conn
.on('ready', () => {
this.logger.debug(`SSH Connection established to ${config.host}`);
this.logger.debug(`Executing SSH command: ${command}`);
timer = setTimeout(() => {
finish(() => reject(new Error(`SSH command timeout after ${timeoutMs}ms`)));
}, timeoutMs);
conn.exec(command, (err, stream) => {
if (err) {
conn.end();
return reject(err);
return finish(() => reject(err));
}
let output = '';
@@ -33,9 +45,10 @@ export class SshService {
stream
.on('close', (code, _signal) => {
this.logger.debug(`SSH Command finished with code ${code}`);
conn.end();
if (code === 0) resolve(output);
else reject(new Error(`Exit code ${code}. Output: ${output}`));
finish(() => {
if (code === 0) resolve(output);
else reject(new Error(`Exit code ${code}. Output: ${output}`));
});
})
.on('data', (data: Buffer) => {
output += data.toString();
@@ -47,6 +60,7 @@ export class SshService {
})
.on('error', (err) => {
this.logger.error(`SSH Error: ${err.message}`);
if (timer) clearTimeout(timer);
reject(err);
})
.connect({
+13 -5
View File
@@ -1,13 +1,13 @@
import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
import { Controller, Get, Post, Body, Param, Delete, Query } from '@nestjs/common';
import { TunnelsService } from './tunnels.service';
import { Tunnel } from './entities/tunnel.entity';
import { CreateTunnelDto } from './dto/create-tunnel.dto';
@Controller('tunnels')
export class TunnelsController {
constructor(private readonly tunnelsService: TunnelsService) {}
@Post()
create(@Body() createTunnelDto: Tunnel) {
create(@Body() createTunnelDto: CreateTunnelDto) {
return this.tunnelsService.create(createTunnelDto);
}
@@ -21,8 +21,16 @@ export class TunnelsController {
return this.tunnelsService.installScript(+id);
}
@Post(':id/uninstall')
uninstall(@Param('id') id: string) {
return this.tunnelsService.uninstallScript(+id);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.tunnelsService.remove(+id);
remove(
@Param('id') id: string,
@Query('deleteForwarding') deleteForwarding?: string,
) {
return this.tunnelsService.remove(+id, deleteForwarding === 'true');
}
}
+3 -1
View File
@@ -5,9 +5,11 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { Tunnel } from './entities/tunnel.entity';
import { Setting } from '../settings/entities/setting.entity';
import { SshService } from './ssh.service';
import { Node } from '../nodes/entities/node.entity';
import { Subscription } from '../subscriptions/entities/subscription.entity';
@Module({
imports: [TypeOrmModule.forFeature([Tunnel, Setting])],
imports: [TypeOrmModule.forFeature([Tunnel, Setting, Node, Subscription])],
controllers: [TunnelsController],
providers: [TunnelsService, SshService],
})
+167 -10
View File
@@ -1,9 +1,14 @@
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DeepPartial } from 'typeorm';
import { Repository } from 'typeorm';
import { Tunnel } from './entities/tunnel.entity';
import { SshService } from './ssh.service';
import { Setting } from '../settings/entities/setting.entity';
import { Node } from '../nodes/entities/node.entity';
import { Subscription } from '../subscriptions/entities/subscription.entity';
import { CreateTunnelDto } from './dto/create-tunnel.dto';
import * as net from 'net';
import * as dns from 'dns/promises';
@Injectable()
export class TunnelsService {
@@ -12,22 +17,79 @@ export class TunnelsService {
constructor(
@InjectRepository(Tunnel) private tunnelRepo: Repository<Tunnel>,
@InjectRepository(Setting) private settingRepo: Repository<Setting>,
@InjectRepository(Node) private nodeRepo: Repository<Node>,
@InjectRepository(Subscription)
private subscriptionRepo: Repository<Subscription>,
private sshService: SshService,
) {}
async create(createTunnelDto: DeepPartial<Tunnel>) {
const tunnel = this.tunnelRepo.create(createTunnelDto);
async create(createTunnelDto: CreateTunnelDto) {
const address = await this.resolveRelayAddress(createTunnelDto.ip);
const node = createTunnelDto.nodeId
? await this.nodeRepo.findOne({ where: { id: createTunnelDto.nodeId } })
: await this.nodeRepo.findOne({ where: { isMain: true } });
if (!node) {
throw new HttpException('Node not found', HttpStatus.BAD_REQUEST);
}
const tunnelPayload = {
...createTunnelDto,
ip: address.ip,
node,
nodeId: node.id,
};
const domain = createTunnelDto.domain || address.domain;
if (domain) {
Object.assign(tunnelPayload, { domain });
}
const tunnel = this.tunnelRepo.create(tunnelPayload);
return this.tunnelRepo.save(tunnel);
}
async findAll() {
return this.tunnelRepo.find();
return this.tunnelRepo.find({ relations: ['node'] });
}
async remove(id: number) {
async remove(id: number, deleteForwarding = false) {
if (deleteForwarding) {
await this.uninstallScript(id);
}
await this.cleanupRelayDependencies(id);
return this.tunnelRepo.delete(id);
}
private async cleanupRelayDependencies(id: number) {
const subscriptions = await this.subscriptionRepo.find({
where: [{ relayServerId: id }],
});
for (const sub of subscriptions) {
sub.relayServerId = undefined;
sub.relayServer = undefined;
await this.subscriptionRepo.save(sub);
}
const configuredSubscriptions = await this.subscriptionRepo.find();
for (const sub of configuredSubscriptions) {
const config = sub.inboundsConfig || [];
const nextConfig = config.map((item) => {
if (item.relayServerId !== id) return item;
const { relayServerId: _relayServerId, ...rest } = item;
return rest;
});
if (JSON.stringify(nextConfig) !== JSON.stringify(config)) {
sub.inboundsConfig = nextConfig;
await this.subscriptionRepo.save(sub);
}
}
}
async installScript(id: number) {
const tunnel = await this.tunnelRepo
.createQueryBuilder('tunnel')
@@ -39,17 +101,22 @@ export class TunnelsService {
if (!tunnel)
throw new HttpException('Tunnel not found', HttpStatus.NOT_FOUND);
const hostSetting = await this.settingRepo.findOne({
where: { key: 'xui_ip' },
});
const targetNode = tunnel.nodeId
? await this.nodeRepo.findOne({ where: { id: tunnel.nodeId } })
: await this.nodeRepo.findOne({ where: { isMain: true } });
const hostSetting = await this.settingRepo.findOne({ where: { key: 'xui_ip' } });
if (!hostSetting || !hostSetting.value) {
if (!targetNode && (!hostSetting || !hostSetting.value)) {
throw new HttpException(
'В настройках (Settings) не сохранен Host/IP основного сервера (xui_host). Сохраните настройки подключения к 3x-ui заново.',
HttpStatus.BAD_REQUEST,
);
}
const mainServerIp = hostSetting.value;
const mainServerIp =
targetNode?.ip ||
targetNode?.host ||
this.getNodeAddress(targetNode) ||
hostSetting?.value;
this.logger.debug(
`Начинаем установку редиректа на ${tunnel.ip} -> ${mainServerIp}`,
@@ -67,6 +134,7 @@ export class TunnelsService {
privateKey: tunnel.privateKey,
},
command,
180000,
);
this.logger.debug(`Скрипт выполнен успешно:\n${output}`);
@@ -84,4 +152,93 @@ export class TunnelsService {
);
}
}
async uninstallScript(id: number) {
const tunnel = await this.tunnelRepo
.createQueryBuilder('tunnel')
.addSelect('tunnel.password')
.addSelect('tunnel.privateKey')
.where('tunnel.id = :id', { id })
.getOne();
if (!tunnel) {
throw new HttpException('Tunnel not found', HttpStatus.NOT_FOUND);
}
const command =
'sudo bash -c "$(curl -sSL https://raw.githubusercontent.com/denpiligrim/3dp-manager/main/forwarding_delete.sh)"';
try {
const output = await this.sshService.executeCommand(
{
host: tunnel.ip,
port: tunnel.sshPort,
username: tunnel.username,
password: tunnel.password,
privateKey: tunnel.privateKey,
},
command,
180000,
);
tunnel.isInstalled = false;
await this.tunnelRepo.save(tunnel);
return { success: true, output };
} catch (e) {
const error = e as Error;
this.logger.error(`Forwarding delete error: ${error.message}`);
throw new HttpException(
`Forwarding delete failed: ${error.message}`,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
private getNodeAddress(node?: Node | null) {
if (!node?.url) return undefined;
try {
return new URL(node.url).hostname;
} catch {
return node.url;
}
}
private async resolveRelayAddress(value: string) {
const address = value.trim();
if (!address) {
throw new HttpException(
'Relay server address is required',
HttpStatus.BAD_REQUEST,
);
}
if (net.isIP(address) !== 0) {
return { ip: address, domain: undefined };
}
if (!this.isValidHostname(address)) {
throw new HttpException(
'Relay server address is invalid',
HttpStatus.BAD_REQUEST,
);
}
try {
const result = await dns.lookup(address);
return { ip: result.address, domain: address };
} catch {
throw new HttpException(
'Relay server domain cannot be resolved',
HttpStatus.BAD_REQUEST,
);
}
}
private isValidHostname(value: string) {
if (value.length > 253) return false;
return /^(?=.{1,253}$)(?!-)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i.test(
value,
);
}
}
+159 -10
View File
@@ -3,9 +3,16 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import axios, { AxiosInstance, AxiosError } from 'axios';
import * as https from 'https';
import * as http from 'http';
import { Setting } from '../settings/entities/setting.entity';
import { XuiResponse, XuiCertResult, XuiInboundRaw } from './xui.types';
import {
XuiResponse,
XuiCertResult,
XuiInboundRaw,
XuiDiscoveredNode,
} from './xui.types';
import { SessionService } from '../session/session.service';
import { Node, NodeAuthType } from '../nodes/entities/node.entity';
interface LoginResponse {
success: boolean;
@@ -23,7 +30,7 @@ export class XuiService {
) {
this.api = axios.create({
timeout: 15000,
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
proxy: false,
withCredentials: true,
});
@@ -36,6 +43,14 @@ export class XuiService {
});
}
private getNodeBaseUrl(node: Node): string {
if (node.url) {
return node.url.replace(/\/+$/, '');
}
return `${node.protocol}://${node.host}:${node.port}`.replace(/\/+$/, '');
}
private async getSettings() {
const settings = await this.settingsRepo.find();
const config: Record<string, string> = {};
@@ -43,6 +58,65 @@ export class XuiService {
return config;
}
private createApi(baseURL?: string): AxiosInstance {
return axios.create({
baseURL,
timeout: 15000,
proxy: false,
...this.getAgentConfig(baseURL),
withCredentials: true,
});
}
private getAgentConfig(baseURL?: string) {
if (!baseURL || baseURL.startsWith('https://')) {
return { httpsAgent: new https.Agent({ rejectUnauthorized: false }) };
}
return { httpAgent: new http.Agent() };
}
private async createAuthenticatedApi(node?: Node): Promise<AxiosInstance | null> {
if (!node) {
const success = await this.login();
return success ? this.api : null;
}
const api = this.createApi(this.getNodeBaseUrl(node));
if (node.authType === NodeAuthType.Token) {
if (!node.token) return null;
api.defaults.headers.common.Authorization = `Bearer ${node.token}`;
return api;
}
if (!node.login || !node.password) return null;
const res = await api.post<LoginResponse>('/login', {
username: node.login,
password: node.password,
});
if (!res.data?.success || !res.headers['set-cookie']) {
return null;
}
api.defaults.headers.common.Cookie = res.headers['set-cookie'].join('; ');
return api;
}
private parseVersion(headers: Record<string, unknown>, data: unknown): string | undefined {
const headerVersion = headers['x-ui-version'] || headers['x-3x-ui-version'];
if (typeof headerVersion === 'string') return headerVersion;
if (data && typeof data === 'object' && 'version' in data) {
const version = (data as { version?: unknown }).version;
return typeof version === 'string' ? version : undefined;
}
return undefined;
}
async login() {
try {
const config = await this.getSettings();
@@ -57,6 +131,9 @@ export class XuiService {
this.logger.log(`Attempting login to 3x-ui: ${config['xui_url']}`);
this.api.defaults.baseURL = config['xui_url'];
const agentConfig = this.getAgentConfig(config['xui_url']);
this.api.defaults.httpAgent = agentConfig.httpAgent;
this.api.defaults.httpsAgent = agentConfig.httpsAgent;
const res = await this.api.post<LoginResponse>('/login', {
username: config['xui_login'],
@@ -79,6 +156,7 @@ export class XuiService {
async addInbound(
inboundConfig: { port: number; [key: string]: unknown } | XuiInboundRaw,
node?: Node,
): Promise<number | null> {
let attempts = 0;
const maxAttempts = 3;
@@ -89,7 +167,13 @@ export class XuiService {
attempts++;
try {
const res = await this.api.post<XuiResponse<{ id: number }>>(
const api = await this.createAuthenticatedApi(node);
if (!api) {
this.logger.error('3x-ui authentication failed before addInbound');
return null;
}
const res = await api.post<XuiResponse<{ id: number }>>(
'/panel/api/inbounds/add',
inboundConfig,
);
@@ -122,7 +206,7 @@ export class XuiService {
const error = e as AxiosError;
if (error.response?.status === 401) {
this.logger.log('Сессия истекла, пробуем релогин...');
if (await this.login()) {
if (!node && (await this.login())) {
return this.addInbound(inboundConfig);
}
}
@@ -140,14 +224,35 @@ export class XuiService {
return null;
}
async deleteInbound(id: number) {
async deleteInbound(id: number, node?: Node): Promise<boolean> {
if (!id || id <= 0) {
this.logger.debug(`Skipping 3x-ui inbound deletion for non-remote id: ${id}`);
return true;
}
try {
await this.api.post(`/panel/api/inbounds/del/${id}`);
this.logger.debug(`Инбаунд ${id} удален`);
const api = await this.createAuthenticatedApi(node);
if (!api) {
this.logger.error(`3x-ui authentication failed before deleting inbound ${id}`);
return false;
}
const res = await api.post<XuiResponse<unknown>>(
`/panel/api/inbounds/del/${id}`,
);
if (!res.data?.success) {
this.logger.error(
`3x-ui rejected inbound deletion ${id}: ${res.data?.msg || 'unknown error'}`,
);
return false;
}
this.logger.debug(`Inbound ${id} deleted`);
return true;
} catch (e) {
const error = e as AxiosError;
this.logger.error(`Ошибка удаления инбаунда ${id}: ${error.message}`);
}
return false;
}
async checkConnection(
@@ -161,7 +266,8 @@ export class XuiService {
const tempApi = axios.create({
baseURL: url,
timeout: 5000,
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
proxy: false,
...this.getAgentConfig(url),
withCredentials: true,
});
@@ -187,9 +293,32 @@ export class XuiService {
return false;
}
async getNewX25519Cert(): Promise<XuiCertResult | null> {
async checkNodeConnection(
node: Node,
): Promise<{ success: boolean; version?: string }> {
try {
const res = await this.api.get<XuiResponse<XuiCertResult>>(
const api = await this.createAuthenticatedApi(node);
if (!api) return { success: false };
const res = await api.get('/panel/api/inbounds/list');
return {
success: true,
version: this.parseVersion(res.headers as Record<string, unknown>, res.data),
};
} catch (error) {
const axiosError = error as AxiosError;
this.logger.error(
`Node connection error: ${axiosError.message} (${node.name})`,
);
return { success: false };
}
}
async getNewX25519Cert(node?: Node): Promise<XuiCertResult | null> {
try {
const api = await this.createAuthenticatedApi(node);
if (!api) return null;
const res = await api.get<XuiResponse<XuiCertResult>>(
'/panel/api/server/getNewX25519Cert',
);
if (res.data?.success && res.data.obj) return res.data.obj;
@@ -198,4 +327,24 @@ export class XuiService {
}
return null;
}
async getNodes(node: Node): Promise<XuiDiscoveredNode[]> {
try {
const api = await this.createAuthenticatedApi(node);
if (!api) return [];
const res = await api.get<XuiResponse<XuiDiscoveredNode[]>>(
'/panel/api/nodes/list',
);
if (res.data?.success && Array.isArray(res.data.obj)) {
return res.data.obj;
}
} catch (error) {
const axiosError = error as AxiosError;
this.logger.warn(`Node sync is not available: ${axiosError.message}`);
}
return [];
}
}
+8
View File
@@ -63,3 +63,11 @@ export interface XuiCertResult {
privateKey: string;
publicKey: string;
}
export interface XuiDiscoveredNode {
name?: string;
host: string;
port: number;
protocol: 'http' | 'https';
version?: string;
}
@@ -270,6 +270,50 @@ describe('InboundBuilderService', () => {
});
});
describe('buildHysteria2Inbound', () => {
it('creates 3x-ui hysteria v2 inbound with certificate paths', () => {
const result = service.buildHysteria2Inbound({
port: 34443,
uuid: 'test-auth',
sni: 'oil.3dp-manager.com',
});
expect(result).toMatchObject({
enable: true,
listen: '0.0.0.0',
port: 34443,
protocol: 'hysteria',
tag: 'inbound-34443',
});
const settings = JSON.parse(result.settings);
const streamSettings = JSON.parse(result.streamSettings);
expect(settings.clients[0].auth).toBe('test-auth');
expect(settings.version).toBe(2);
expect(streamSettings.network).toBe('hysteria');
expect(streamSettings.hysteriaSettings.version).toBe(2);
expect(streamSettings.finalmask.udp[0].type).toBe('salamander');
expect(streamSettings.tlsSettings.certificates[0].certificateFile).toBe(
'/etc/letsencrypt/live/oil.3dp-manager.com/fullchain.pem',
);
expect(streamSettings.tlsSettings.certificates[0].keyFile).toBe(
'/etc/letsencrypt/live/oil.3dp-manager.com/privkey.pem',
);
const link = service.buildInboundLink(
result as any,
'relay.example.com',
'fallback-auth',
'%F0%9F%92%AF',
);
expect(link).toContain('hy2://test-auth@relay.example.com:34443/');
expect(link).toContain('sni=oil.3dp-manager.com');
expect(link).toContain('obfs=salamander');
expect(link).toContain('obfs-password=abcd1234');
});
});
describe('buildInboundLink', () => {
const baseInbound = {
protocol: 'vless',
+102
View File
@@ -0,0 +1,102 @@
import { Repository } from 'typeorm';
import { NodesService } from 'src/nodes/nodes.service';
import { Node } from 'src/nodes/entities/node.entity';
import { Subscription } from 'src/subscriptions/entities/subscription.entity';
import { Tunnel } from 'src/tunnels/entities/tunnel.entity';
import { Inbound } from 'src/inbounds/entities/inbound.entity';
import { XuiService } from 'src/xui/xui.service';
describe('NodesService', () => {
const createNodeRepo = (getOne: jest.Mock) => ({
createQueryBuilder: jest.fn(() => ({
addSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getOne,
})),
count: jest.fn(),
remove: jest.fn(),
findOne: jest.fn(),
save: jest.fn(),
});
const createService = (nodeRepo: ReturnType<typeof createNodeRepo>) => {
const subscriptionsRepo = {
createQueryBuilder: jest.fn(() => ({
delete: jest.fn().mockReturnThis(),
execute: jest.fn().mockResolvedValue({}),
})),
find: jest.fn().mockResolvedValue([]),
save: jest.fn(),
};
const tunnelsRepo = {
createQueryBuilder: jest.fn(() => ({
delete: jest.fn().mockReturnThis(),
execute: jest.fn().mockResolvedValue({}),
})),
delete: jest.fn(),
};
const inboundsRepo = {
find: jest.fn().mockResolvedValue([]),
delete: jest.fn(),
};
const xuiService = {
deleteInbound: jest.fn().mockResolvedValue(true),
};
return {
service: new NodesService(
nodeRepo as unknown as Repository<Node>,
subscriptionsRepo as unknown as Repository<Subscription>,
tunnelsRepo as unknown as Repository<Tunnel>,
inboundsRepo as unknown as Repository<Inbound>,
xuiService as unknown as XuiService,
),
subscriptionsRepo,
tunnelsRepo,
inboundsRepo,
xuiService,
};
};
it('deletes the main node and makes the next node main', async () => {
const mainNode = { id: 'main', isMain: true } as Node;
const nextNode = { id: 'next', isMain: false } as Node;
const getOne = jest
.fn()
.mockResolvedValueOnce(mainNode)
.mockResolvedValueOnce(null);
const nodeRepo = createNodeRepo(getOne);
nodeRepo.count.mockResolvedValue(2);
nodeRepo.findOne.mockResolvedValue(nextNode);
nodeRepo.save.mockResolvedValue(nextNode);
const { service } = createService(nodeRepo);
const result = await service.remove('main');
expect(result).toEqual({ success: true });
expect(nodeRepo.remove).toHaveBeenCalledWith(mainNode);
expect(nodeRepo.findOne).toHaveBeenCalledWith({
where: {},
order: { createdAt: 'DESC' },
});
expect(nextNode.isMain).toBe(true);
expect(nodeRepo.save).toHaveBeenCalledWith(nextNode);
});
it('uses node credentials when deleting node inbounds', async () => {
const mainNode = { id: 'main', isMain: true } as Node;
const getOne = jest
.fn()
.mockResolvedValueOnce(mainNode)
.mockResolvedValueOnce(null);
const nodeRepo = createNodeRepo(getOne);
nodeRepo.count.mockResolvedValue(1);
nodeRepo.findOne.mockResolvedValue(null);
const { service, inboundsRepo, xuiService } = createService(nodeRepo);
inboundsRepo.find.mockResolvedValue([{ id: 1, xuiId: 101, nodeId: 'main' }]);
await service.remove('main');
expect(xuiService.deleteInbound).toHaveBeenCalledWith(101, mainNode);
});
});
+77 -4
View File
@@ -14,6 +14,8 @@ import { Domain } from 'src/domains/entities/domain.entity';
import { Setting } from 'src/settings/entities/setting.entity';
import { XuiService } from 'src/xui/xui.service';
import { InboundBuilderService } from 'src/inbounds/inbound-builder.service';
import { Node } from 'src/nodes/entities/node.entity';
import { Tunnel } from 'src/tunnels/entities/tunnel.entity';
// Mock @nestjs/schedule для тестирования Cron
jest.mock('@nestjs/schedule', () => ({
@@ -64,6 +66,19 @@ describe('RotationService', () => {
save: jest.fn(),
};
const mockNodeRepo = {
findOne: jest.fn(),
createQueryBuilder: jest.fn(() => ({
addSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getOne: jest.fn(),
})),
};
const mockTunnelRepo = {
findOne: jest.fn(),
};
const mockXuiService = {
login: jest.fn(),
deleteInbound: jest.fn(),
@@ -79,6 +94,7 @@ describe('RotationService', () => {
buildVmessTcp: jest.fn(),
buildShadowsocksTcp: jest.fn(),
buildTrojanRealityTcp: jest.fn(),
buildHysteria2Inbound: jest.fn(),
buildHysteria2Link: jest.fn(),
buildInboundLink: jest.fn(),
};
@@ -103,6 +119,14 @@ describe('RotationService', () => {
provide: getRepositoryToken(Setting),
useValue: mockSettingRepo,
},
{
provide: getRepositoryToken(Node),
useValue: mockNodeRepo,
},
{
provide: getRepositoryToken(Tunnel),
useValue: mockTunnelRepo,
},
{
provide: XuiService,
useValue: mockXuiService,
@@ -129,6 +153,10 @@ describe('RotationService', () => {
jest.clearAllMocks();
});
beforeEach(() => {
mockXuiService.deleteInbound.mockResolvedValue(true);
});
describe('onModuleInit', () => {
it('должен инициализировать настройки по умолчанию', async () => {
mockSettingRepo.findOne.mockResolvedValue(null);
@@ -437,7 +465,7 @@ describe('RotationService', () => {
{ id: 1, name: 'ya.ru', isEnabled: true },
]);
expect(xuiService.deleteInbound).toHaveBeenCalledWith(101);
expect(xuiService.deleteInbound).toHaveBeenCalledWith(101, undefined);
expect(inboundRepo.delete).toHaveBeenCalled();
});
@@ -468,6 +496,7 @@ describe('RotationService', () => {
id: '1',
uuid: 'uuid-1',
isEnabled: true,
node: { id: 'node-1', domain: 'node.example.com' },
inbounds: [],
inboundsConfig: [{ type: 'hysteria2-udp', sni: 'ya.ru' }],
};
@@ -475,15 +504,59 @@ describe('RotationService', () => {
mockDomainRepo.find.mockResolvedValue([
{ id: 1, name: 'ya.ru', isEnabled: true },
]);
mockInboundBuilder.buildHysteria2Link.mockReturnValue('hy2://link');
mockXuiService.getNewX25519Cert.mockResolvedValue({
privateKey: 'key',
publicKey: 'pub',
});
mockInboundBuilder.buildHysteria2Inbound.mockReturnValue({
protocol: 'hysteria2',
remark: 'hysteria2-udp',
settings: '{"clients":[{"password":"uuid"}]}',
streamSettings: '{"tlsSettings":{"serverName":"ya.ru"}}',
sniffing: '{}',
});
mockXuiService.addInbound.mockResolvedValue(101);
mockInboundBuilder.buildInboundLink.mockReturnValue('hy2://link');
mockInboundRepo.save.mockResolvedValue({});
await (service as any).rotateSubscription(mockSub, [
{ id: 1, name: 'ya.ru', isEnabled: true },
]);
expect(xuiService.addInbound).not.toHaveBeenCalled();
expect(inboundBuilder.buildHysteria2Link).toHaveBeenCalled();
expect(xuiService.addInbound).toHaveBeenCalled();
expect(inboundBuilder.buildHysteria2Inbound).toHaveBeenCalledWith(
expect.objectContaining({ sni: 'node.example.com' }),
);
expect(inboundBuilder.buildInboundLink).toHaveBeenCalled();
});
it('does not save hysteria2 when 3x-ui does not create an inbound', async () => {
const mockSub = {
id: '1',
uuid: 'uuid-1',
isEnabled: true,
inbounds: [],
inboundsConfig: [{ type: 'hysteria2-udp', sni: 'ya.ru' }],
};
mockXuiService.getNewX25519Cert.mockResolvedValue({
privateKey: 'key',
publicKey: 'pub',
});
mockInboundBuilder.buildHysteria2Inbound.mockReturnValue({
protocol: 'hysteria2',
remark: 'hysteria2-udp',
settings: '{"clients":[{"password":"uuid"}]}',
streamSettings: '{"tlsSettings":{"serverName":"ya.ru"}}',
sniffing: '{}',
});
mockXuiService.addInbound.mockResolvedValue(null);
await (service as any).rotateSubscription(mockSub, [
{ id: 1, name: 'ya.ru', isEnabled: true },
]);
expect(inboundRepo.save).not.toHaveBeenCalled();
});
it('должен использовать случайный порт, если указано random', async () => {
@@ -8,6 +8,8 @@ import { SubscriptionsService } from 'src/subscriptions/subscriptions.service';
import { Subscription } from 'src/subscriptions/entities/subscription.entity';
import { XuiService } from 'src/xui/xui.service';
import { CreateSubscriptionDto } from 'src/subscriptions/dto/create-subscription.dto';
import { Node } from 'src/nodes/entities/node.entity';
import { Tunnel } from 'src/tunnels/entities/tunnel.entity';
describe('SubscriptionsService', () => {
let service: SubscriptionsService;
@@ -23,6 +25,19 @@ describe('SubscriptionsService', () => {
remove: jest.fn(),
};
const mockNodeRepo = {
findOne: jest.fn(),
createQueryBuilder: jest.fn(() => ({
addSelect: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
getOne: jest.fn(),
})),
};
const mockTunnelRepo = {
findOne: jest.fn(),
};
const mockXuiService = {
deleteInbound: jest.fn(),
};
@@ -35,6 +50,14 @@ describe('SubscriptionsService', () => {
provide: getRepositoryToken(Subscription),
useValue: mockSubRepo,
},
{
provide: getRepositoryToken(Node),
useValue: mockNodeRepo,
},
{
provide: getRepositoryToken(Tunnel),
useValue: mockTunnelRepo,
},
{
provide: XuiService,
useValue: mockXuiService,
@@ -47,6 +70,7 @@ describe('SubscriptionsService', () => {
getRepositoryToken(Subscription),
);
xuiService = module.get<XuiService>(XuiService);
mockXuiService.deleteInbound.mockResolvedValue(true);
});
afterEach(() => {
@@ -86,7 +110,7 @@ describe('SubscriptionsService', () => {
expect(result).toEqual(mockSubs);
expect(subRepo.find).toHaveBeenCalledWith({
relations: ['inbounds'],
relations: ['inbounds', 'node', 'relayServer'],
order: { createdAt: 'DESC' },
});
});
@@ -128,6 +152,8 @@ describe('SubscriptionsService', () => {
uuid: expect.any(String),
inboundsConfig: createDto.inboundsConfig,
isAutoRotationEnabled: true,
node: null,
relayServer: null,
});
expect(subRepo.save).toHaveBeenCalledWith(mockSubscription);
expect(result).toEqual(mockSubscription);
@@ -197,7 +223,7 @@ describe('SubscriptionsService', () => {
expect(subRepo.findOne).toHaveBeenCalledWith({
where: { id: 'test-id' },
relations: ['inbounds'],
relations: ['inbounds', 'node', 'relayServer'],
});
expect(subRepo.save).toHaveBeenCalledWith(
expect.objectContaining({ name: 'New Name' }),
@@ -329,8 +355,8 @@ describe('SubscriptionsService', () => {
await service.remove('test-id');
expect(xuiService.deleteInbound).toHaveBeenCalledWith(101);
expect(xuiService.deleteInbound).toHaveBeenCalledWith(102);
expect(xuiService.deleteInbound).toHaveBeenCalledWith(101, undefined);
expect(xuiService.deleteInbound).toHaveBeenCalledWith(102, undefined);
expect(subRepo.remove).toHaveBeenCalledWith(subWithInbounds);
});
@@ -82,7 +82,7 @@ describe('TunnelsController', () => {
await controller.remove('1');
expect(tunnelsService.remove).toHaveBeenCalledWith(1);
expect(tunnelsService.remove).toHaveBeenCalledWith(1, false);
});
});
});
+30 -4
View File
@@ -8,6 +8,8 @@ import { TunnelsService } from 'src/tunnels/tunnels.service';
import { Tunnel } from 'src/tunnels/entities/tunnel.entity';
import { SshService } from 'src/tunnels/ssh.service';
import { Setting } from 'src/settings/entities/setting.entity';
import { Node } from 'src/nodes/entities/node.entity';
import { Subscription } from 'src/subscriptions/entities/subscription.entity';
describe('TunnelsService', () => {
let service: TunnelsService;
@@ -34,6 +36,15 @@ describe('TunnelsService', () => {
save: jest.fn(),
};
const mockNodeRepo = {
findOne: jest.fn(),
};
const mockSubscriptionRepo = {
find: jest.fn(),
save: jest.fn(),
};
const mockSshService = {
executeCommand: jest.fn(),
};
@@ -50,6 +61,14 @@ describe('TunnelsService', () => {
provide: getRepositoryToken(Setting),
useValue: mockSettingRepo,
},
{
provide: getRepositoryToken(Node),
useValue: mockNodeRepo,
},
{
provide: getRepositoryToken(Subscription),
useValue: mockSubscriptionRepo,
},
{
provide: SshService,
useValue: mockSshService,
@@ -64,21 +83,27 @@ describe('TunnelsService', () => {
});
afterEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
describe('create', () => {
it('должен создать туннель', async () => {
const dto = { ip: '192.168.1.1', sshPort: 22, username: 'root' };
const mockTunnel = { id: 1, ...dto };
const node = { id: 'node-1', isMain: true };
const mockTunnel = { id: 1, ...dto, node, nodeId: node.id };
mockNodeRepo.findOne.mockResolvedValue(node);
mockTunnelRepo.create.mockReturnValue(mockTunnel);
mockTunnelRepo.save.mockResolvedValue(mockTunnel);
const result = await service.create(dto);
expect(result).toEqual(mockTunnel);
expect(tunnelRepo.create).toHaveBeenCalledWith(dto);
expect(tunnelRepo.create).toHaveBeenCalledWith({
...dto,
node,
nodeId: node.id,
});
});
});
@@ -94,12 +119,13 @@ describe('TunnelsService', () => {
const result = await service.findAll();
expect(result).toEqual(mockTunnels);
expect(tunnelRepo.find).toHaveBeenCalledTimes(1);
expect(tunnelRepo.find).toHaveBeenCalledWith({ relations: ['node'] });
});
});
describe('remove', () => {
it('должен удалить туннель по ID', async () => {
mockSubscriptionRepo.find.mockResolvedValue([]);
mockTunnelRepo.delete.mockResolvedValue({ affected: 1 });
await service.remove(1);
+32 -4
View File
@@ -56,7 +56,7 @@ describe('XuiService', () => {
});
afterEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
describe('login', () => {
@@ -149,7 +149,16 @@ describe('XuiService', () => {
describe('deleteInbound', () => {
it('должен удалить инбаунд', async () => {
mockAxiosInstance.post.mockResolvedValue({ data: { success: true } });
mockSettingsRepo.find.mockResolvedValue([
{ key: 'xui_url', value: 'http://localhost:3100' },
{ key: 'xui_login', value: 'admin' },
{ key: 'xui_password', value: 'password' },
]);
mockAxiosInstance.post
.mockResolvedValueOnce({
headers: { 'set-cookie': ['session=abc123'] },
})
.mockResolvedValueOnce({ data: { success: true } });
await service.deleteInbound(101);
@@ -159,16 +168,35 @@ describe('XuiService', () => {
});
it('должен обработать ошибку удаления', async () => {
mockAxiosInstance.post.mockRejectedValue(new Error('Not found'));
mockSettingsRepo.find.mockResolvedValue([
{ key: 'xui_url', value: 'http://localhost:3100' },
{ key: 'xui_login', value: 'admin' },
{ key: 'xui_password', value: 'password' },
]);
mockAxiosInstance.post
.mockResolvedValueOnce({
headers: { 'set-cookie': ['session=abc123'] },
})
.mockRejectedValueOnce(new Error('Not found'));
await service.deleteInbound(999);
expect(mockAxiosInstance.post).toHaveBeenCalled();
expect(mockAxiosInstance.post).toHaveBeenCalledWith(
'/panel/api/inbounds/del/999',
);
});
});
describe('getNewX25519Cert', () => {
it('должен получить Reality ключи', async () => {
mockSettingsRepo.find.mockResolvedValue([
{ key: 'xui_url', value: 'http://localhost:3100' },
{ key: 'xui_login', value: 'admin' },
{ key: 'xui_password', value: 'password' },
]);
mockAxiosInstance.post.mockResolvedValueOnce({
headers: { 'set-cookie': ['session=abc123'] },
});
mockAxiosInstance.get.mockResolvedValue({
data: {
success: true,
+106 -5
View File
@@ -38,9 +38,8 @@ check_containers_running() {
# Формат: NAME\tSTATUS (например: "3dp-postgres\tUp 2 days" или "3dp-postgres\tError")
while IFS=$'\t' read -r container_name status; do
if [ -n "$container_name" ] && [ -n "$status" ]; then
# Проверяем, что статус содержит Up/running/healthy/restarting
# Up, Up 2 days, Up Less than a second, (healthy), running, restarting
if ! echo "$status" | grep -qiE "^up|running|healthy|restarting"; then
# Restarting означает, что контейнер не смог стабильно запуститься.
if ! echo "$status" | grep -qiE "^up|running|healthy"; then
failed=1
warn "Контейнер $container_name в статусе: $status"
fi
@@ -250,6 +249,86 @@ ensure_bus_location() {
mv "$tmp_file" "$nginx_conf"
}
remove_hysteria_mount() {
local compose_file="$1"
[[ -f "$compose_file" ]] || return 0
local tmp_file
tmp_file="$(mktemp)"
awk '
/^[[:space:]]*volumes:[[:space:]]*$/ {
pending_volumes = $0
next
}
/\/etc\/hysteria\/config\.yaml:\/etc\/hysteria\/config\.yaml:ro/ {
pending_volumes = ""
next
}
{
if (pending_volumes != "") {
print pending_volumes
pending_volumes = ""
}
print $0
}
END {
if (pending_volumes != "") print pending_volumes
}
' "$compose_file" > "$tmp_file"
mv "$tmp_file" "$compose_file"
}
ensure_safe_database_mode() {
local compose_file="$1"
[[ -f "$compose_file" ]] || return 0
local tmp_file
tmp_file="$(mktemp)"
awk '
/^[[:space:]]+DB_SYNCHRONIZE:/ { next }
/^[[:space:]]+DB_MIGRATIONS_RUN:/ { next }
{
print $0
if ($0 ~ /^[[:space:]]+DB_NAME:/) {
match($0, /^[[:space:]]+/)
indent = substr($0, RSTART, RLENGTH)
print indent "DB_SYNCHRONIZE: \"false\""
print indent "DB_MIGRATIONS_RUN: \"true\""
}
}
' "$compose_file" > "$tmp_file"
mv "$tmp_file" "$compose_file"
}
get_node_count() {
docker exec 3dp-postgres sh -c '
psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atqc "
SELECT CASE
WHEN to_regclass('\''public.node'\'') IS NULL THEN 0
ELSE (SELECT count(*) FROM node)
END
"
' 2>/dev/null | tr -d '[:space:]'
}
backup_database() {
local backup_dir="$PROJECT_DIR/backups"
BACKUP_FILE="$backup_dir/pre-update-$(date +%Y%m%d-%H%M%S).sql.gz"
mkdir -p "$backup_dir"
log "Создание резервной копии базы данных: $BACKUP_FILE"
docker exec 3dp-postgres sh -c \
'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB"' | gzip > "$BACKUP_FILE"
chmod 600 "$BACKUP_FILE"
}
need_root() {
[[ $EUID -eq 0 ]] || die "Запускать только от root"
}
@@ -280,13 +359,28 @@ log "Compose команда: ${COMPOSE_CMD[*]}"
#################################
# CHECK AND FIX CREDENTIALS
#################################
check_and_fix_credentials || true
# Обновление не должно менять пароль уже инициализированной PostgreSQL:
# изменение только .env делает существующую базу недоступной.
if [[ ! -f ".env" ]]; then
die "Файл .env не найден. Обновление остановлено, чтобы не потерять доступ к существующей базе данных"
fi
#################################
# FIX NGINX CONFIG
#################################
ensure_nginx_api_timeouts "$PROJECT_DIR/client/nginx-client.conf"
ensure_bus_location "$PROJECT_DIR/client/nginx-client.conf"
remove_hysteria_mount "$PROJECT_DIR/docker-compose.yml"
ensure_safe_database_mode "$PROJECT_DIR/docker-compose.yml"
#################################
# BACKUP DATABASE
#################################
node_count_before="$(get_node_count)"
[[ "$node_count_before" =~ ^[0-9]+$ ]] || die "Не удалось проверить количество нод перед обновлением"
backup_database
backup_file="$BACKUP_FILE"
[[ -s "$backup_file" ]] || die "Не удалось создать резервную копию базы данных"
#################################
# REBUILD BACKEND
@@ -306,11 +400,18 @@ log "Пересоздание контейнеров..."
# Проверка: все ли контейнеры запустились
if ! check_containers_running 60; then
error "Не удалось запустить контейнеры. Логи:"
warn "Не удалось запустить контейнеры. Логи:"
"${COMPOSE_CMD[@]}" logs --tail=50
die "Обновление прервано из-за ошибки запуска контейнеров"
fi
node_count_after="$(get_node_count)"
[[ "$node_count_after" =~ ^[0-9]+$ ]] || die "Не удалось проверить количество нод после обновления. Резервная копия: $backup_file"
if (( node_count_after < node_count_before )); then
"${COMPOSE_CMD[@]}" stop backend || true
die "Количество нод уменьшилось с $node_count_before до $node_count_after. Обновление остановлено, резервная копия: $backup_file"
fi
log "Очистка старых Docker-образов (освобождение места)..."
docker image prune -f