diff --git a/.dockerignore b/.dockerignore index 1a16a95..8ef72ea 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,5 @@ node_modules .vpn-proxy -_archive .git .gitea .github diff --git a/.env.example b/.env.example index 7beed9e..e5c012a 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,7 @@ PORT=3456 APP_MODE=gateway CLIENT_UI_PORT=3456 -CLIENT_PROXY_PORT_START=8082 -CLIENT_PROXY_PORT_END=8082 +CLIENT_PROXY_PORT=8082 BASE_IMAGE=debian:bookworm-slim SINGBOX_VERSION=1.12.13 INSTALL_RUNTIME_DEPS=true @@ -13,5 +12,4 @@ TPROXY_PORT=7895 TPROXY_MARK=1 TPROXY_TABLE=100 TPROXY_CHAIN=VPN_PROXY_TPROXY -ROUTING_RU_DIRECT=true LOG_LEVEL=info diff --git a/.gitignore b/.gitignore index 2c0691f..372f91d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,8 @@ -# Local archive with the previous implementation and runtime secrets -_archive/ - # Runtime state .env *.env.local data/ .vpn-proxy/ -.superpowers/ .worktrees/ # Node/Vite diff --git a/.interface-design/system.md b/.interface-design/system.md deleted file mode 100644 index f1ebcbe..0000000 --- a/.interface-design/system.md +++ /dev/null @@ -1,142 +0,0 @@ -# Windows Client Interface System - -Дата: 2026-07-08 - -## Направление - -Это максимально простая Windows-утилита управления службами и их состояниями. Она не должна ощущаться как VPN-dashboard, SaaS-панель или маркетинговый клиент. Главные глаголы интерфейса: - -- проверить состояние; -- установить компонент; -- удалить компонент; -- запустить службу; -- остановить службу; -- обновить/перепроверить состояние; -- добавить приложение/путь; -- применить конфигурацию только когда prerequisites готовы. - -Интерфейс должен быть плотным, спокойным, системным и предсказуемым. Пользователь открывает его не для анализа статистики, а чтобы быстро понять "что сейчас установлено, что запущено, что сломано и какую одну кнопку нажать дальше". - -## Домен - -Ключевые понятия: Windows service, installed/running/stopped/missing, install/uninstall, helper/elevation, ProxiFyre, Local sing-box, selected apps, endpoint, generated config, logs, diagnostics, readiness blockers. - -Цветовой мир: темная Windows-оболочка, service console, terminal black, muted slate panels, driver/service green, warning amber, blocked red, focus/navigation blue. - -Сигнатура продукта: `Service Control Row` - компактная строка компонента, где слева состояние службы, в центре человекочитаемый статус и путь/деталь, справа ровно одно главное действие плюс меню дополнительных действий. Эта строка должна быть повторяемым паттерном для ProxiFyre, Local sing-box и будущих компонентов. - -## Визуальная модель - -- Основной layout: fixed header, fixed tabs, scrollable work area, adaptive log/status area. -- Основная композиция: не больше одного главного действия на компонент или экран. -- Summary должен отвечать "готово / не готово / что сделать дальше", а не показывать длинный dashboard. -- Route chain полезен, но он вторичен к service-control модели. Он должен объяснять эффект состояний служб, а не превращать приложение в карту сети. - -## Depth And Surfaces - -Стратегия глубины: borders-only + subtle surface shifts. Без тяжелых shadows. - -- `canvas`: `#101216` - фон приложения. -- `surface`: `#131720` - обычные панели. -- `surface-raised`: `#151923` - service rows и важные панели. -- `surface-control`: `#242a35` - neutral buttons. -- `surface-inset`: `#0d1016` - inputs и read-only inset fields. -- `border`: `#2b3342`. -- `border-strong`: `#343b49`. -- `focus`: `#3b82f6`. - -Радиусы: 4px для buttons, inputs, rows, panels; 999px только для pills/dots. Карточки и панели не должны становиться мягкими/крупно-скругленными. - -Spacing base: 4px. Основные значения: 6, 8, 10, 12, 14, 18. Для плотной утилиты 20+ использовать редко, только между большими группами. - -## Typography - -Шрифт: Inter/system stack как сейчас. - -Плотная шкала: - -- caption: 12px / 500-700 / muted; -- body: 14px / 400-500 / secondary; -- control: 14px / 700 / primary; -- section title: 16px / 700; -- screen title: 18px / 650-750; -- status title: 22px / 700 only for primary readiness state. - -Иерархия должна строиться весом и цветом больше, чем размером. Letter spacing держать `0`. - -## Компонентная база - -### Button - -Все кнопки должны идти через общий компонент и общие variants: - -- `primary`: главное безопасное действие текущего блока. Зеленый использовать только когда действие реально применимо и готово к выполнению. -- `neutral`: refresh, open, cancel, secondary action. -- `add`: добавление процесса, EXE, папки, target. Иконка + tooltip; текстовая кнопка только когда без текста смысл неясен. -- `danger`: stop/uninstall/delete. Не смешивать с neutral. -- `icon`: квадрат 40-44px, только иконка, обязательны `aria-label`, `title` или tooltip. - -Button states обязательны: default, hover, active, focus-visible, disabled, loading. - -Loading state не должен выглядеть как зависание: показывать spinner/progress label, менять текст на действие в процессе ("Проверяю", "Устанавливаю", "Останавливаю"), блокировать повторный запуск. - -### Service Control Row - -Повторяемый компонент для служб: - -- left: status dot/icon (`checking`, `missing`, `installed`, `running`, `stopped`, `error`); -- center: title + short status + optional path/details; -- right: primary action (`Установить`, `Запустить`, `Остановить`, `Обновить`) + overflow menu; -- expanded area: setup checklist, diagnostics, paths, generated config. - -В строке не должно быть двух конкурирующих primary actions. - -### Tabs - -Tabs должны быть единым компонентом: - -- role tablist/tab/tabpanel; -- arrow-key navigation; -- active indicator 3px blue; -- height 46px desktop, не меньше 40px narrow; -- transition 180-240ms только `opacity` + `transform`; -- no layout shift при переключении. - -### Status And Logs - -Status surface должен показывать человеческий текст первым, raw details вторым уровнем. - -- Preview/native command errors: friendly summary in dock, raw error in details. -- `aria-live` объявляет только короткий статус. -- Narrow width: dock collapses into compact toast/details control. - -### Forms And Inputs - -Inputs are inset: - -- background `surface-inset`; -- border `border-strong`; -- focus ring 1px `focus`; -- validation appears directly below or beside the field; -- invalid state disables dependent action and explains exact accepted format. - -### Motion - -Motion должна показывать, что интерфейс живой, но не тормозить повторяющиеся операции. - -- Button press: 100-140ms, `transform: scale(0.98)`. -- Tab switch: 180-240ms, `opacity` + `translateX` 12-24px. -- Popover/menu: 150-180ms, `opacity` + `scale(0.97 -> 1)`. -- Service checking/installing: subtle spinner or border trace, but not decorative glow everywhere. -- Respect `prefers-reduced-motion`. - -Не использовать `transition: all`. - -## Implementation Priorities - -1. Создать shared UI layer: `Button`, `IconButton`, `Tabs`, `ServiceControlRow`, `StatusPill`, `LogDock`, `Field`, `ActionMenu`. -2. Перевести текущие кнопки на variants, чтобы "обновить", "добавить", "установить", "удалить", "применить" выглядели и вели себя стабильно. -3. Ввести readiness blockers для apply actions. -4. Свести все анимации к общим duration/easing tokens. -5. Проверить keyboard flow и responsive snapshots после каждого крупного UI изменения. - diff --git a/PRODUCT.md b/PRODUCT.md index 1c594f2..6d2c06d 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -6,11 +6,11 @@ product ## Users -macOS users without networking or Docker expertise. They open the client only to add a VPN subscription, choose a server, and turn the connection on or off. +People running either a local macOS proxy client or a small Linux VPN gateway. They open the client only to add a subscription, choose a server, turn the VPN on or off, and copy the connection address. ## Product Purpose -Provide a small, dependable control surface for the Docker-based macOS VPN client. Success means the current connection state is obvious and the full everyday workflow fits on one screen. +Provide one small, dependable control surface for the macOS client and the system gateway. Success means the connection state is obvious, while the gateway address and proxy URLs are ready to copy from the same screen. ## Brand Personality @@ -18,7 +18,7 @@ Soft, calm, precise. Familiar to macOS users, with sharper geometry and a quiet ## Anti-references -Not an admin dashboard, network console, settings maze, or enclosing card. Avoid sidebars, technical route diagrams, framed content areas, decorative effects, and controls for gateway or server administration. +Not an admin dashboard, network console, settings maze, or enclosing card. Avoid sidebars, technical route diagrams, framed content areas, decorative effects, and routing-rule administration. ## Design Principles diff --git a/README.md b/README.md index 9d9e42f..9e84162 100644 --- a/README.md +++ b/README.md @@ -1,481 +1,43 @@ # VPN Proxy -Локальный Docker-клиент для Mac и прозрачный VPN-шлюз на базе [sing-box](https://sing-box.sagernet.org/). +Один компактный VPN-клиент в двух режимах: -## macOS: локальный Docker-клиент +- `gateway` — отдельная Linux-машина принимает трафик устройств как системный Gateway или HTTP/SOCKS5 Proxy; +- `client` — локальный proxy-клиент для macOS. -Самый простой режим: контейнер работает как обычный локальный HTTP/SOCKS proxy без TProxy, iptables, `network_mode: host` и прав `NET_ADMIN`. +В обоих режимах пользователь добавляет подписку, выбирает сервер и включает VPN на одном экране. + +## Gateway ```bash -curl -fsSL https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/scripts/install-macos-client.sh | bash +cp .env.example .env +docker compose -f docker-compose.gateway.yml up -d --build ``` -После запуска по умолчанию: +Интерфейс: `http://:3456`. -- UI: `http://127.0.0.1:3456` -- HTTP/SOCKS proxy: `127.0.0.1:8082` по умолчанию; установщик интерактивно спросит proxy-порт и опубликует только его +После подключения экран показывает: -Установщик интерактивно спросит proxy-порт. Если стандартный UI-порт `3456` занят другим контейнером, установщик попросит выбрать свободный UI-порт. Для неинтерактивного запуска можно задать порты заранее; тогда вопросы не появятся: +- `Gateway` — адрес, который можно назначить устройству как основной шлюз; +- `Proxy` — один адрес на порту `8080`, доступный как `HTTP` и `SOCKS5`. + +Весь перехваченный публичный TCP/UDP и весь proxy-трафик идут через выбранный VPN. Приватные и локальные сети не перехватываются, чтобы сохранить доступ к Gateway и LAN. + +Proxy по умолчанию разрешён только из приватных сетей. Диапазоны задаются через `PROXY_ALLOWED_CIDRS`. + +## macOS client ```bash -curl -fsSL https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/scripts/install-macos-client.sh | VPN_PROXY_CLIENT_PORT=18080 bash +./scripts/install-macos-client.sh ``` -Если старый gateway/client уже занимает `3456` или выбранный proxy-порт, можно не трогать старый контейнер и поставить новый клиент на другие порты: +По умолчанию интерфейс доступен на `http://127.0.0.1:3456`, локальный HTTP/SOCKS5 proxy — на `127.0.0.1:8082`. + +## Проверка ```bash -curl -fsSL https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/scripts/install-macos-client.sh | VPN_PROXY_CLIENT_UI_PORT=3457 VPN_PROXY_CLIENT_PORT=18080 bash +npm test +npm run build +docker compose -f docker-compose.gateway.yml config +docker compose -f docker-compose.client.yml config ``` - -После запуска скрипт проверяет, что UI реально ответил на `/api/state`. Если контейнер сразу упал или порт занят, он покажет `docker compose ps` и последние логи вместо ложного сообщения о готовности. - -В Mac UI есть **Домашний режим**. Когда он включён, приложения по-прежнему используют выбранный локальный proxy-порт, но весь proxy-трафик идёт напрямую без VPN. - -Также Mac-клиент можно связать с серверным gateway. На gateway доступна ручка: - -```bash -GET http://:3456/api/shared-proxy -``` - -Если gateway запущен и его mixed proxy работает, ручка вернёт `available: true` и SOCKS5 endpoint общего proxy. В Mac UI укажите адрес gateway UI, например `http://192.168.50.111:3456`. Клиент проверит ручку и переключит локальный `127.0.0.1:` в режим upstream: весь proxy-трафик пойдёт через общий gateway, локальная VPN-подписка на Mac для этого режима не нужна. - -Ручной запуск из checkout: - -```bash -docker compose -f docker-compose.client.yml up -d --build -``` - -Перезапуск и логи: - -```bash -cd ~/.vpn-proxy-client -docker compose -f docker-compose.client.yml logs -f -docker compose -f docker-compose.client.yml restart -``` - -## Windows Desktop Client - -The Windows desktop client has been split out of this repository. Continue -Windows-specific work in the sibling repository: - -```powershell -cd D:\repos\ProxyWarden -``` - -This repository keeps the gateway and Docker client runtime; it no longer owns -the Tauri Windows app, ProxiFyre adapter, or Local sing-box installer flow. - -Windows source configuration is owned by JSON under -`C:\ProgramData\VpnProxy\config`. Generated ProxiFyre and sing-box files under -`C:\ProgramData\VpnProxy\generated` are derived artifacts. - ---- - -# VPN Proxy Gateway - -Самохостируемый прозрачный VPN-шлюз на базе [sing-box](https://sing-box.sagernet.org/). -Разворачивается в Docker (LXC, VPS), перехватывает трафик всей локальной сети через iptables TProxy — без клиентов на устройствах. - -Веб-интерфейс на React даёт полное управление: подписки, выбор сервера, кастомные правила маршрутизации, просмотр трафика в реальном времени. - ---- - -## Архитектура - -``` -Клиент (ПК/телефон) - │ TCP/UDP трафик - ▼ -[Роутер] → маршрут по умолчанию → LXC/VPS (gateway) - │ - ▼ -iptables mangle PREROUTING → цепочка VPN_PROXY_TPROXY - │ - ├─ source bypass chain → ACCEPT ← устройства мимо sing-box - │ └─ FORWARD + MASQUERADE → обычный internet path - ├─ ipset vpn_direct_bypass (dst IP) → RETURN ← опциональный bypass-кэш - ├─ приватные CIDR (RFC1918, ...) → RETURN - └─ TCP/UDP → TPROXY :7895 - │ - ▼ - sing-box (tproxy inbound :7895) - │ - роутинг по правилам - │ - ┌──────────┼──────────┐ - ▼ ▼ ▼ - direct VPN out block -``` - -ПК-приложения, которым нужен VPN явно: - -``` -Windows app → ProxiFyre/Proxifier → gateway:8080 → sing-box mixed-in → global rules → default VPN -``` - -**Node.js API-сервер** (`src/server/index.js`) работает внутри того же контейнера: -управляет процессом sing-box, парсит его логи, экспортирует REST API и SSE-стримы для веб-интерфейса. - ---- - -## Стек - -| Слой | Технология | -| ---------------- | ------------------------------------------------------------- | -| Контейнер | Docker, `network_mode: host`, `CAP_NET_ADMIN` + `CAP_NET_RAW` | -| Перехват трафика | iptables TProxy + iproute2 policy routing | -| Bypass-кэш | опциональный ipset `hash:ip` с TTL | -| VPN-ядро | sing-box (VLESS/VLESS-Reality/VMess/Trojan/Hysteria2/SS) | -| API-сервер | Node.js 18, plain `http` (без фреймворков) | -| Веб-интерфейс | React 18 + Vite 7, SPA | - ---- - -## Как работает прозрачное проксирование - -### 1. TProxy и policy routing - -При старте контейнера `entrypoint.sh` настраивает ядро: - -```bash -# Policy routing: пакеты с меткой TPROXY_MARK уходят через loopback -ip rule add fwmark 1 table 100 -ip route replace local 0.0.0.0/0 dev lo table 100 - -# Цепочка iptables (порядок правил — критичен) -iptables -t mangle -N VPN_PROXY_TPROXY -iptables -t mangle -N VPN_PROXY_SRC_BYPASS -iptables -N VPN_PROXY_FWD_BYPASS -iptables -t nat -N VPN_PROXY_NAT_BYPASS - -m addrtype --dst-type LOCAL → RETURN # ответы самого sing-box - -m mark --mark 1 → RETURN # уже помеченные пакеты - -j VPN_PROXY_SRC_BYPASS → ACCEPT # source bypass до sing-box - -m set --match-set vpn_direct_bypass → RETURN # только если DIRECT_BYPASS_CACHE=true - -d 10.0.0.0/8, 192.168.0.0/16, ... → RETURN # приватные адреса - -p tcp → TPROXY :7895 mark 1 - -p udp → TPROXY :7895 mark 1 -iptables -t mangle -A PREROUTING -j VPN_PROXY_TPROXY -``` - -При остановке контейнера (`SIGTERM`) все правила iptables удаляются идемпотентно. -ipset-кэш намеренно **не** очищается — записи истекают по TTL. - -Устройства можно исключить из transparent-перехвата в интерфейсе: **Routing → Устройства → Mode → bypass TProxy**. -Такой source IP обходит `tproxy-in` и не попадает в `sing-box`; для него gateway включает обычный kernel forwarding + `MASQUERADE`. -Ручной HTTP/SOCKS proxy на `gateway:8080` остаётся доступен для выбранных программ. - -### 2. Маршрутизация внутри sing-box - -Каждый пакет проходит правила в порядке приоритета — **первое совпадение побеждает**: - -| Приоритет | Условие | Действие | -| --------- | ------------------------------------------- | ---------------------------------------- | -| 1 | `ip_is_private: true` | `direct` (защита LAN) | -| 2 | Global custom rules | `direct` / VPN / `block` для всех inbound | -| 3 | `rule_set: [geoip-ru, geosite-category-ru]` | `direct` | -| 4 | Device defaults для `tproxy-in` | `direct` / VPN / `block` | -| 5 | Proxy default для `mixed-in` | по умолчанию VPN | -| 6 | Transparent default для unknown devices | по умолчанию VPN | -| 7 | Всё остальное (`final`) | `direct` | - -Конфиг генерируется динамически через `buildGatewayConfig()` из подписки + сохранённых правил. Перед применением выполняется `sing-box check`. - -### 3. Bypass Mode (весь трафик напрямую) - -Кнопка "Весь трафик напрямую" в дашборде. При активации `buildGatewayConfig()` вызывается с `{ bypassAll: true }` — в конфиге убираются все rule_set, `final: "direct"`. Удобно для диагностики или когда VPN не нужен. - ---- - -## Direct Bypass Cache (ipset) - -Оптимизация выключена по умолчанию: `DIRECT_BYPASS_CACHE=false`. Причина — dst-IP cache обходит sing-box до проверки global rules, а значит может нарушить требования вида `AI → VPN` или `blocked → block`. - -Если явно включить `DIRECT_BYPASS_CACHE=true`, IP-адреса, которые sing-box уже отправил напрямую, кэшируются в ядре и больше не проходят через userspace. - -**Цепочка событий:** - -1. sing-box маршрутизирует соединение как `direct`, пишет в лог: - `[TCP] 192.168.1.5:54321 --> 203.0.113.10:443 outbound/direct[direct]` - -2. Node.js парсит строку (regex `-->` + `outbound/`). Если `category === "direct"` и назначение — IPv4-адрес: - - ```bash - ipset add vpn_direct_bypass 203.0.113.10 timeout 3600 -exist - ``` - -3. Следующий пакет к `203.0.113.10` обрабатывается iptables **до** передачи в sing-box: - - ``` - -m set --match-set vpn_direct_bypass dst → RETURN - ``` - - Пакет уходит напрямую на уровне ядра — нулевые накладные расходы userspace sing-box. - -4. Запись истекает через TTL (по умолчанию 1 час). - -``` -DIRECT_BYPASS_CACHE=false # безопасное значение по умолчанию -DIRECT_BYPASS_SET=vpn_direct_bypass # имя ipset -DIRECT_BYPASS_TTL=3600 # TTL в секундах -``` - -## Профили устройств - -Управляются из UI на вкладке **Маршрутизация** и сохраняются в `devices.json`: - -```json -{ - "defaultTransparentMode": "vpn", - "proxyDefaultMode": "vpn", - "devices": [ - { - "id": "gaming-pc", - "name": "Gaming PC", - "ip": "192.168.1.50", - "mac": "", - "mode": "direct", - "enabled": true - }, - { - "id": "phone", - "name": "Phone", - "ip": "192.168.1.60", - "mode": "vpn", - "enabled": true - } - ] -} -``` - -| Mode | Что делает | -| -------- | ----------------------------------------------------------------- | -| `direct` | fallback устройства после global rules → `direct` | -| `vpn` | fallback устройства после global rules → выбранный VPN | -| `block` | fallback устройства после global rules → `block` | -| `rules` | не задаёт fallback устройства; используется transparent default | - -`mixed-in` не зависит от режима устройства: если приложение явно пошло на `gateway:8080`, сначала применяются global rules, затем `proxyDefaultMode` (по умолчанию VPN). - ---- - -## Кастомные правила маршрутизации - -Управляются из вкладки **Маршрутизация**. Сохраняются в `custom-rules.json`. -Правила применяются в порядке отображения в UI — **first match wins**. Custom rules являются global rules: они применяются для `tproxy-in`, `mixed-in`, ПК, телефона и unknown devices до любых fallback-режимов. - -| Поле | Тип | Описание | -| ---------------- | ---------------------------- | ------------------------------------------- | -| `name` | string | Название правила | -| `enabled` | bool | Вкл/выкл | -| `outbound` | `direct` \| `vpn` \| `block` | Куда отправить трафик | -| `domains` | string[] | Точные домены (`example.com`) | -| `domainSuffixes` | string[] | Суффикс домена (`.example.com` + поддомены) | -| `domainKeywords` | string[] | Keyword в имени хоста | -| `ipCidrs` | string[] | IP-диапазоны CIDR | -| `ports` | string[] | Порты или диапазоны (`443`, `8000-9000`) | -| `networks` | `tcp` \| `udp` | Протокол | -| `ruleSets` | string[] | Ссылки на remote rule-set | - -UI автоматически детектирует конфликты — когда правило полностью перекрывается предыдущим. - -### Remote Rule Sets - -В **Настройках** можно добавить произвольные rule-set: - -```json -{ "tag": "gaming-servers", "url": "https://...", "format": "binary" } -``` - -sing-box скачивает их при старте, кэширует в `cache.db`. Ключ кэша — SHA-1 от URL. - ---- - -## Подписки - -Поддерживаемые форматы: - -- **JSON-конфиг sing-box** — объект с полем `outbounds[]` -- **Base64-список VLESS-ссылок** — декодируется, каждая ссылка парсится -- **Прямые VLESS URI** (`vless://uuid@host:port?...#tag`) - -После загрузки пользователь выбирает сервер → генерируется конфиг → `sing-box check` → перезапуск. - -Подписка кэшируется в `subscription-cache.json` — при рестарте контейнера конфиг автоматически пересоздаётся из кэша без повторного скачивания. - ---- - -## Просмотр трафика - -Вкладка **Трафик** в разделе Логи. Данные приходят через SSE (`/api/traffic/stream`). - -### Парсинг логов sing-box - -Node.js читает stderr sing-box и извлекает трафик двумя шагами: - -``` -[router] match[2][my-rule] => outbound/direct[direct] ← имя правила -[TCP] 192.168.1.5:PORT --> example.com:443 outbound/vpn[tag] ← соединение -``` - -1. `[router]`-строка → имя правила сохраняется с TTL 500 мс -2. Следующая строка с `-->` подхватывает имя в поле `matchedRule` -3. Тип трафика: `direct` / `vpn` / `block` по outbound -4. Direct + IPv4 → добавление в ipset bypass-кэш, только если `DIRECT_BYPASS_CACHE=true` - -### Группировка и сортировка - -`(category, host, port, matchedRule)` объединяются в группу с счётчиком: - -- **По частоте** — самые частые наверху (по умолчанию) -- **По времени** — последние наверху - ---- - -## Проверка маршрута - -Вкладка **Проверка** позволяет узнать, по какому правилу пойдёт трафик к хосту/IP/порту — без реального подключения. Node.js (`routeMatcher.js`) симулирует ту же логику, что и sing-box: - -1. private IP → direct -2. global custom rules -3. geoip-ru / geosite-category-ru → direct -4. `tproxy-in` + device default -5. `mixed-in` + proxy default -6. final → direct - ---- - -## Быстрый старт - -```bash -# Сборка фронтенда -npm install && npm run build - -# Запуск контейнера -docker compose -f docker-compose.gateway.yml up -d -``` - -Если Docker Hub отвечает таймаутом на `debian:bookworm-slim`, можно собрать через read-through mirror: - -```bash -BASE_IMAGE=mirror.gcr.io/library/debian:bookworm-slim \ -docker compose -f docker-compose.gateway.yml build - -docker compose -f docker-compose.gateway.yml up -d -``` - -Если сборку нужно выполнять на контейнере/хосте, который уже ходит через рабочий gateway, а запускать image на другом: - -```bash -BUILD_HOST=107 DEPLOY_HOST=111 ./scripts/build-on-107-deploy-111.sh -``` - -Скрипт собирает image на `BUILD_HOST`, переносит его на `DEPLOY_HOST` через `docker save | docker load` и запускает без `docker pull`. Если `107`/`111` не являются SSH-алиасами, укажите реальные адреса, например `BUILD_HOST=root@192.168.1.107 DEPLOY_HOST=root@192.168.1.111`. - -Чтобы не получать циклическую зависимость "собрать gateway можно только через уже работающий gateway", подготовьте runtime base на `107` один раз: - -```bash -./scripts/build-runtime-base.sh -``` - -После этого CI и `build-on-107-deploy-111.sh` используют локальный `vpn-proxy-runtime-base:bookworm-slim`: основная сборка gateway больше не делает `apt-get`, не качает sing-box и не обращается к Docker Hub за base image. - -UI доступен на `http://:3456`. - -На роутере указать шлюз по умолчанию (или нужные подсети) на IP контейнера. - ---- - -## Переменные окружения - -| Переменная | По умолчанию | Описание | -| ------------------- | -------------------- | -------------------------------------- | -| `APP_MODE` | `gateway` | `gateway` или `client`; compose клиента задаёт `client` автоматически | -| `CLIENT_UI_PORT` | `3456` | Host-порт UI для `docker-compose.client.yml` | -| `VPN_PROXY_CLIENT_UI_PORT` | unset | UI-порт для macOS installer; записывается в `CLIENT_UI_PORT` | -| `VPN_PROXY_CLIENT_PORT` | unset | Proxy-порт для macOS installer; записывает `CLIENT_PROXY_PORT` и single-port `CLIENT_PROXY_PORT_START/END` | -| `CLIENT_PROXY_PORT` | `8082` | Единственный host/container proxy-порт для `docker-compose.client.yml` | -| `CLIENT_PROXY_PORT_START` | `8082` | Совместимость со старым env; в client compose считается тем же одиночным proxy-портом | -| `CLIENT_PROXY_PORT_END` | same as start | Совместимость со старым env; по умолчанию не расширяет Docker-публикацию в диапазон | -| `SHARED_PROXY_HOST` | unset | Явный host/IP, который gateway отдаёт в `/api/shared-proxy`; если не задан, берётся Host заголовок запроса | -| `PORT` | `3456` | Порт веб-интерфейса | -| `BASE_IMAGE` | `debian:bookworm-slim` | Базовый Docker image для сборки; можно заменить на mirror | -| `SINGBOX_VERSION` | `1.12.13` | Версия sing-box для Docker build | -| `INSTALL_RUNTIME_DEPS` | `true` | Устанавливать runtime-пакеты в Docker build; `false` для подготовленного runtime base | -| `INSTALL_SINGBOX` | `true` | Скачивать sing-box в Docker build; `false` для подготовленного runtime base | -| `PROXY_PORT` | `8080` | HTTP/SOCKS mixed inbound | -| `TPROXY_PORT` | `7895` | TProxy inbound sing-box | -| `TPROXY_BYPASS_SOURCE_CIDRS` | unset | Source CIDR устройств, которые должны идти напрямую мимо TProxy/sing-box, например `192.168.50.25/32` | -| `TPROXY_SOURCE_BYPASS_CHAIN` | `VPN_PROXY_SRC_BYPASS` | Управляемая iptables-цепочка для UI source-bypass | -| `TPROXY_SOURCE_FORWARD_CHAIN` | `VPN_PROXY_FWD_BYPASS` | Управляемая filter/FORWARD цепочка для UI source-bypass | -| `TPROXY_SOURCE_NAT_CHAIN` | `VPN_PROXY_NAT_BYPASS` | Управляемая nat/POSTROUTING цепочка для UI source-bypass | -| `DATA_DIR` | `/var/lib/vpn-proxy` | Директория данных (volume) | -| `ROUTING_RU_DIRECT` | `true` | geoip-ru/geosite-ru → direct | -| `LOG_LEVEL` | `info` | Уровень логов sing-box | -| `DIRECT_BYPASS_CACHE` | `false` | Включить dst-IP bypass cache; по умолчанию выключен | -| `DIRECT_BYPASS_SET` | `vpn_direct_bypass` | Имя ipset bypass-кэша | -| `DIRECT_BYPASS_TTL` | `3600` | TTL записей (секунды) | -| `RULE_SET_DOWNLOAD_DETOUR` | `vpn` | Через какой outbound sing-box скачивает remote rule-set; `vpn` = выбранный сервер | -| `PROXY_BIND_IP` | `0.0.0.0` | Bind для HTTP/SOCKS в LAN; можно сузить до IP gateway | -| `PROXY_FIREWALL` | `true` | Закрыть `PROXY_PORT` не из allowed CIDR | -| `PROXY_ALLOWED_CIDRS` | `10.0.0.0/8 172.16.0.0/12 192.168.0.0/16` | Кто может подключаться к mixed proxy | - ---- - -## REST API - -| Метод | Путь | Описание | -| --------- | ---------------------- | ------------------------------------ | -| `GET` | `/api/state` | Полное состояние системы | -| `GET` | `/api/shared-proxy` | Проверка и параметры общего gateway proxy | -| `POST` | `/api/subscription` | Загрузить подписку по URL | -| `POST` | `/api/apply` | Применить сервер (`{ selectedTag }`) | -| `GET` | `/api/servers` | Список серверов из кэша | -| `GET/PUT` | `/api/rules` | Кастомные правила | -| `GET/PUT` | `/api/devices` | Профили устройств и default fallback | -| `GET/PUT` | `/api/rule-sets` | Кастомные remote rule-set | -| `POST` | `/api/singbox/start` | Запустить sing-box | -| `POST` | `/api/singbox/stop` | Остановить sing-box | -| `POST` | `/api/singbox/restart` | Перезапустить sing-box | -| `POST` | `/api/bypass` | `{ enabled }` — bypass mode | -| `GET` | `/api/direct-cache` | Состояние ipset bypass-кэша | -| `DELETE` | `/api/direct-cache` | Сбросить bypass-кэш | -| `POST` | `/api/route/check` | Симулировать маршрут | -| `POST` | `/api/servers/ping` | TCP-пинг до хоста | -| `GET` | `/api/logs/stream` | SSE системных логов | -| `GET` | `/api/traffic/stream` | SSE трафика | - ---- - -## Структура проекта - -``` -├── Dockerfile # debian + sing-box + ipset + node -├── entrypoint.sh # iptables/ipset setup → запуск node -├── docker-compose.gateway.yml -├── src/ -│ ├── server/ -│ │ ├── index.js # HTTP-сервер, управление sing-box, SSE -│ │ ├── singbox.js # генерация конфига sing-box -│ │ ├── subscription.js # парсинг подписок (JSON/VLESS/base64) -│ │ ├── routeMatcher.js # симулятор маршрутизации -│ │ ├── ping.js # TCP-пинг и DNS-resolve -│ │ └── config.js # настройки из env -│ └── web/ -│ ├── App.jsx # корневой компонент, глобальный state -│ ├── api.js # обёртка fetch для API -│ └── components/ -│ ├── OverviewPage.jsx # дашборд, bypass-toggle -│ ├── LogsPage.jsx # трафик + системные логи -│ ├── RoutingPage.jsx # кастомные правила -│ ├── ServersPage.jsx # подписка и выбор сервера -│ ├── SettingsPage.jsx # rule-sets и настройки -│ └── RouteChecker.jsx # проверка маршрута -└── docs/ - └── roadmap.md -``` - -## Ограничения - -- TProxy только IPv4. IPv6 — в roadmap. -- DNS-перехват не включён; выдавайте клиентам DNS через DHCP роутера. -- Gateway не видит имя процесса на клиентском ПК — правила для игр задаются через домены, CIDR и порты. diff --git a/docker-compose.client.yml b/docker-compose.client.yml index 6aceb20..d8e8b88 100644 --- a/docker-compose.client.yml +++ b/docker-compose.client.yml @@ -9,15 +9,11 @@ services: environment: APP_MODE: client PORT: ${PORT:-3456} - PROXY_PORT: ${CLIENT_PROXY_PORT:-${CLIENT_PROXY_PORT_START:-8082}} - CLIENT_PROXY_PORT_START: ${CLIENT_PROXY_PORT:-${CLIENT_PROXY_PORT_START:-8082}} - CLIENT_PROXY_PORT_END: ${CLIENT_PROXY_PORT:-${CLIENT_PROXY_PORT_START:-8082}} + PROXY_PORT: ${CLIENT_PROXY_PORT:-8082} PROXY_BIND_IP: 0.0.0.0 DATA_DIR: /var/lib/vpn-proxy SING_BOX_CONFIG: /etc/sing-box/config.json SING_BOX_CACHE: /var/lib/sing-box/cache.db - ROUTING_RU_DIRECT: ${ROUTING_RU_DIRECT:-true} - RULE_SET_DOWNLOAD_DETOUR: ${RULE_SET_DOWNLOAD_DETOUR:-vpn} LOG_LEVEL: ${LOG_LEVEL:-info} HTTP_PROXY: "" HTTPS_PROXY: "" @@ -29,7 +25,7 @@ services: no_proxy: "localhost,127.0.0.1,host.docker.internal" ports: - "127.0.0.1:${CLIENT_UI_PORT:-3456}:${PORT:-3456}" - - "127.0.0.1:${CLIENT_PROXY_PORT:-${CLIENT_PROXY_PORT_START:-8082}}:${CLIENT_PROXY_PORT:-${CLIENT_PROXY_PORT_START:-8082}}" + - "127.0.0.1:${CLIENT_PROXY_PORT:-8082}:${CLIENT_PROXY_PORT:-8082}" volumes: - vpn-proxy-client-data:/var/lib/vpn-proxy - sing-box-client-cache:/var/lib/sing-box diff --git a/docker-compose.gateway.yml b/docker-compose.gateway.yml index 2e76e01..53b4209 100644 --- a/docker-compose.gateway.yml +++ b/docker-compose.gateway.yml @@ -14,7 +14,8 @@ services: - NET_ADMIN - NET_RAW env_file: - - .env + - path: .env + required: false environment: DATA_DIR: /var/lib/vpn-proxy SING_BOX_CACHE: /var/lib/sing-box/cache.db diff --git a/docs/design/open-design/vpn-proxy-full-mock-prototype.html b/docs/design/open-design/vpn-proxy-full-mock-prototype.html deleted file mode 100644 index 8962ccb..0000000 --- a/docs/design/open-design/vpn-proxy-full-mock-prototype.html +++ /dev/null @@ -1,1752 +0,0 @@ - - - - - - VPN Proxy Gateway Mock Prototype - - - -
-
-
-
- -
-

VPN Gateway Control

- Server gateway for LAN transparent and explicit proxy traffic -
-
-
- gateway running - 192.168.50.111, tproxy :7895, proxy :8080 -
-
- - - -
-
- -
- -
- -
-
-
- -
- - - - - - - - diff --git a/docs/design/open-design/vpn-proxy-route-console-redesign.html b/docs/design/open-design/vpn-proxy-route-console-redesign.html deleted file mode 100644 index 8e8a365..0000000 --- a/docs/design/open-design/vpn-proxy-route-console-redesign.html +++ /dev/null @@ -1,774 +0,0 @@ - - - - - - VPN Proxy Route Console Redesign - - - -
-
-
-
- -
-

VPN Proxy Client

- Local control panel, macOS Docker mode -
-
-
- sing-box running - - -
-
- -
- - -
-
-
-

Текущий маршрут: приложения Mac идут через локальный VPN

-

- Главный экран показывает не настройки как список, а фактический путь трафика: - от приложения до интернета, с портом, выбранным режимом и состоянием сервиса. -

-
-
- 42 ms - последняя проверка маршрута -
-
- -
-
- Источник - Mac apps - браузер, Discord, Telegram -
-
- Локальный proxy - 127.0.0.1:8082 - HTTP и SOCKS5 -
-
- Режим - Local VPN - Finland 02 -
-
- Выход - Internet - проверка 11:04 -
-
- -
- Mac apps>127.0.0.1:8082>sing-box>Finland 02>Internet -
- -
-
-
-

Настройка выбранного режима

- -
-
-
- - -
-
-
- -
-
-

Сводка

-
-
-
-
Servicerunning since 10:52
-
Configapplied 2 minutes ago
-
FallbackVPN by default
-
Quota18 GB left
-
-
-
-
-
- - -
-
-
- - diff --git a/docs/roadmap.md b/docs/roadmap.md deleted file mode 100644 index 0340f34..0000000 --- a/docs/roadmap.md +++ /dev/null @@ -1,99 +0,0 @@ -# Roadmap: VPN Proxy rebuild - -## Целевая модель - -Проект должен стать multi-mode системой вокруг `sing-box`: - -| Режим | Назначение | Runtime | Статус | -| --- | --- | --- | --- | -| `gateway` | LXC/VPS как gateway для роутера и всей сети | Docker `network_mode: host` + TProxy | делаем первым | -| `desktop-proxy` | Mac/Linux локальный HTTP/SOCKS proxy с fallback | Docker bridged ports | позже переносим из старой реализации | -| `windows-gaming` | Windows для игр/Discord/Vesktop | standalone Tauri 2 app + ProxiFyre adapter + optional native `sing-box.exe` | вынесено в `D:\repos\ProxyWarden` | - -## Gateway mode - -Цель: контейнер, который становится прозрачным gateway для сети. - -Требования: - -- `sing-box` внутри контейнера. -- `network_mode: host`. -- `CAP_NET_ADMIN` и `CAP_NET_RAW`. -- TProxy inbound на `7895`. -- Mixed HTTP/SOCKS inbound на `8080`. -- Web UI на `3456`. -- Subscription URL вводится в UI, парсится, пользователь выбирает сервер. -- Пользовательские routing lists управляются из UI. -- Генерируется `/etc/sing-box/config.json`. -- `sing-box check` перед применением. -- Restart `sing-box` после применения. -- Idempotent iptables setup. -- Cleanup iptables/ip rule/ip route при остановке контейнера. - -Маршрутизация v1: - -- private IP ranges -> `direct`. -- пользовательские списки -> `direct`, `vpn` или `block`. -- `geoip-ru` -> `direct`. -- `geosite-category-ru` -> `direct`. -- все остальное -> выбранный VPN outbound. - -Порядок правил: - -1. safety private-direct, чтобы не ломать LAN. -2. custom routing lists из UI. -3. RU direct rules. -4. default VPN outbound. - -Формат пользовательского списка: - -- `name`. -- `enabled`. -- `outbound`: `direct`, `vpn`, `block`. -- `domains`: exact domains. -- `domainSuffixes`: доменные suffix, удобно для игр/сервисов. -- `domainKeywords`: keyword matching. -- `ipCidrs`: CIDR ranges. -- `ports`: TCP/UDP ports. -- `networks`: `tcp`, `udp`. -- UI должен автосохранять списки с debounce, чтобы polling state не затирал незавершенное редактирование. - -Важно: gateway не видит process name на клиентском ПК. Для сценария вроде "League of Legends всегда direct" нужны домены, CIDR и порты Riot, а не имя процесса. - -Отдельно решить позже: - -- DNS strategy: DHCP DNS, DNS redirect или local DNS inbound. -- IPv6 TProxy. -- nftables backend. -- health checks и smoke diagnostics. -- secret storage через Infisical/Vault/env. - -## Desktop proxy mode - -Цель: сохранить удобный Docker-сценарий для Mac/Linux без TProxy. - -Требования: - -- UI на `3456`. -- Mixed inbound на `8080`. -- Subscription parser. -- Выбор сервера. -- Fallback proxy через `urltest`. -- Direct mode toggle. -- Не требует `NET_ADMIN`. - -## Windows gaming mode - -Цель: отдельное Windows desktop-приложение для Discord/Vesktop/игр, где Control App, Proxyfier Layer и Local sing-box являются независимыми компонентами. - -Статус: вынесено в соседний репозиторий `D:\repos\ProxyWarden`. Этот репозиторий больше не содержит Tauri Windows app, Windows-specific планы/evidence или installer scripts. - -## Рабочий порядок - -1. Сделать новый gateway root. -2. Реализовать Docker image + entrypoint TProxy lifecycle. -3. Реализовать маленький control-server. -4. Реализовать Vite + React UI для subscription -> server select -> apply. -5. Добавить gateway docs/install script. -6. Потом переносить desktop-proxy. -7. Windows desktop client развивать в `D:\repos\ProxyWarden`. diff --git a/docs/superpowers/plans/2026-05-19-macos-client.md b/docs/superpowers/plans/2026-05-19-macos-client.md deleted file mode 100644 index 7e3f5e8..0000000 --- a/docs/superpowers/plans/2026-05-19-macos-client.md +++ /dev/null @@ -1,74 +0,0 @@ -# macOS Docker Client Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Build a macOS Docker client mode that exposes a local HTTP/SOCKS proxy on `127.0.0.1:8080` with a friendlier UI and a curl installer. - -**Architecture:** Reuse the current Node API, React UI, subscription parser, sing-box process manager, and routing rule generator. Add `APP_MODE=client` so the same backend emits a proxy-only sing-box config without TProxy, and use a dedicated Dockerfile/compose path for Mac installation. - -**Tech Stack:** Node.js ESM, React/Vite, sing-box, Docker Compose, POSIX shell, `node:test`. - ---- - -### Task 1: Client Mode Config Contract - -**Files:** -- Create: `test/server/singbox-client-mode.test.js` -- Modify: `package.json` -- Modify: `src/server/config.js` -- Modify: `src/server/singbox.js` -- Modify: `src/server/index.js` - -- [ ] Add `node:test` coverage that proves `APP_MODE=client` config has `mixed-in`, no `tproxy-in`, no transparent fallback, and a VPN proxy fallback. -- [ ] Add `npm test` script. -- [ ] Add `settings.appMode`. -- [ ] Make `buildGatewayConfig()` conditionally emit client-only inbounds and route rules. -- [ ] Expose `mode` and hide irrelevant tproxy fields in public state. - -### Task 2: macOS Client Docker Runtime - -**Files:** -- Create: `entrypoint.client.sh` -- Create: `Dockerfile.client` -- Create: `docker-compose.client.yml` - -- [ ] Add an entrypoint that starts only the Node control server. -- [ ] Add a Dockerfile that builds the Vite frontend inside Docker and installs only client runtime dependencies plus sing-box. -- [ ] Add compose with loopback-only port publishing for UI and proxy. - -### Task 3: User-Friendly Client UI - -**Files:** -- Create: `src/web/components/ClientOverviewPage.jsx` -- Modify: `src/web/App.jsx` -- Modify: `src/web/components/Sidebar.jsx` -- Modify: `src/web/components/Topbar.jsx` -- Modify: `src/web/components/StatusPane.jsx` -- Modify: `src/web/components/RouteChecker.jsx` -- Modify: `src/web/styles.css` - -- [ ] Add a client overview with status, active server, copyable proxy URLs, and macOS setup commands. -- [ ] Hide gateway-only navigation and side status pane in client mode. -- [ ] Rename topbar brand to match current mode. -- [ ] Keep servers, logs, and settings reachable in client mode. - -### Task 4: curl Installer and Docs - -**Files:** -- Create: `scripts/install-macos-client.sh` -- Modify: `README.md` -- Modify: `.env.example` - -- [ ] Add curl-friendly installer with Docker/Git checks and update-or-clone behavior. -- [ ] Document one-line install command and manual compose command. -- [ ] Add client mode environment examples. - -### Task 5: Verification - -**Commands:** -- `npm test` -- `npm run build` -- `docker compose -f docker-compose.client.yml config` - -- [ ] Run all commands and fix any failures. -- [ ] Inspect the diff to confirm existing CI/runtime-base edits remain untouched. diff --git a/docs/superpowers/plans/2026-05-24-vpn-proxy-client-route-console-redesign.md b/docs/superpowers/plans/2026-05-24-vpn-proxy-client-route-console-redesign.md deleted file mode 100644 index b07fbe3..0000000 --- a/docs/superpowers/plans/2026-05-24-vpn-proxy-client-route-console-redesign.md +++ /dev/null @@ -1,470 +0,0 @@ -# VPN Proxy Client Route Console Redesign Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Replace the current macOS client overview with a route-first console that makes the active traffic path, local proxy address, selected mode, and next action obvious at a glance. - -**Architecture:** Keep `resolveClientRoute()` as the single source of truth and keep `ClientOverviewPage` as the orchestrator. Split the screen into small presentational components inside `src/web/components/ClientOverviewPage.jsx`, then replace only the client-mode CSS block in `src/web/styles.css` so gateway and Windows work stay untouched. - -**Tech Stack:** React 19, Vite, Node.js `node:test`, existing CSS variables, Open Design static HTML artifact. - -**Design Artifact:** `docs/design/open-design/vpn-proxy-route-console-redesign.html` - ---- - -## Current Findings - -- `src/web/components/ClientOverviewPage.jsx` already has the right model: one overview screen, mutually exclusive `Gateway`, `VPN`, and `Direct` modes, and route state from `resolveClientRoute()`. -- `src/web/styles.css` makes the client screen visually separate, but it uses a dark blue-green palette that reads as a monitoring dashboard rather than a macOS setup tool. -- The current status panel, route line, mode grid, and proxy panel have similar visual weight. The user must scan several boxes to answer the primary question: where does my traffic go right now? -- Copyable proxy addresses sit in the side panel. They are useful, but they are visually separated from the route story. -- The three mode buttons look like cards. They work, but they do not communicate that mode selection changes the middle segment of the route. - -## Target Design - -Use a light, restrained operational UI for a normal macOS desktop context: a user has Docker running, a browser open, and is checking why an app uses a certain proxy path. The interface should feel closer to a compact network control console than a server dashboard. - -The first viewport should show: - -- top status: service running, restart, apply route; -- left mode rail: Gateway, Local VPN, Direct; -- main route strip: `Mac apps > local proxy > selected route > Internet`; -- right utility panel: copy proxy addresses, proxy port, recent activity; -- settings below route: only the form for the selected mode. - -## File Structure - -- Modify `src/web/components/ClientOverviewPage.jsx`: reorganize render structure into route console subcomponents while preserving props and handlers. -- Modify `src/web/styles.css`: replace `.client-*` layout styles from `.client-mode .app-main` through the final client media query. -- Test `test/web/client-route.test.js`: extend route state coverage so UI changes do not hide incorrect mode/status combinations. -- Keep `docs/design/open-design/vpn-proxy-route-console-redesign.html`: reference artifact for visual decisions. - ---- - -### Task 1: Lock Route Contract Before UI Changes - -**Files:** -- Modify: `test/web/client-route.test.js` - -- [ ] **Step 1: Add tests for all user-visible route statuses** - -Add these cases to `test/web/client-route.test.js`: - -```js -test('resolves running local VPN route', () => { - const route = resolveClientRoute({ - state: { - singboxRunning: true, - configExists: true, - proxyPort: 8082, - selectedTag: 'finland-02', - clientSettings: { homeBypassEnabled: false, sharedProxyEnabled: false }, - }, - activeServer: { tag: 'finland-02' }, - }); - - assert.equal(route.mode, 'vpn'); - assert.equal(route.status, 'connected'); - assert.equal(route.localProxy, '127.0.0.1:8082'); - assert.deepEqual(route.path, ['Mac apps', '127.0.0.1:8082', 'VPN finland-02', 'Internet']); -}); - -test('resolves gateway route when shared proxy is enabled', () => { - const route = resolveClientRoute({ - state: { - singboxRunning: true, - configExists: true, - proxyPort: 8082, - clientSettings: { - sharedProxyEnabled: true, - sharedProxy: { host: '192.168.50.111', port: 8080 }, - }, - }, - }); - - assert.equal(route.mode, 'gateway'); - assert.equal(route.status, 'connected'); - assert.equal(route.target, '192.168.50.111:8080'); - assert.deepEqual(route.path, ['Mac apps', '127.0.0.1:8082', 'Gateway 192.168.50.111:8080', 'Internet']); -}); - -test('resolves direct route when home bypass is enabled', () => { - const route = resolveClientRoute({ - state: { - singboxRunning: true, - configExists: true, - clientSettings: { homeBypassEnabled: true, sharedProxyEnabled: false, proxyPort: 8084 }, - }, - }); - - assert.equal(route.mode, 'direct'); - assert.equal(route.status, 'connected'); - assert.equal(route.localProxy, '127.0.0.1:8084'); - assert.deepEqual(route.path, ['Mac apps', '127.0.0.1:8084', 'Direct', 'Internet']); -}); -``` - -- [ ] **Step 2: Run the route tests** - -Run: - -```bash -npm test -- test/web/client-route.test.js -``` - -Expected: all existing and new route tests pass. - -- [ ] **Step 3: Commit** - -```bash -git add test/web/client-route.test.js -git commit -m "test: lock client route display contract" -``` - ---- - -### Task 2: Restructure Client Overview Markup - -**Files:** -- Modify: `src/web/components/ClientOverviewPage.jsx` - -- [ ] **Step 1: Replace the route line with route nodes** - -Replace `RouteLine` with: - -```jsx -function RouteStrip({ route }) { - const nodes = [ - { label: 'Источник', value: route.path[0], detail: 'приложения Mac' }, - { label: 'Локальный proxy', value: route.localProxy, detail: 'HTTP и SOCKS5' }, - { label: 'Режим', value: route.target, detail: route.targetDetail, active: route.status === 'connected' }, - { label: 'Выход', value: 'Internet', detail: route.status === 'connected' ? 'маршрут активен' : 'ожидает запуска' }, - ]; - - return ( -
- {nodes.map((node) => ( -
- {node.label} - {node.value} - {node.detail} -
- ))} -
- ); -} - -function RoutePath({ route }) { - return ( -
- {route.path.map((item, index) => ( - - {item} - {index < route.path.length - 1 && {'>'}} - - ))} -
- ); -} -``` - -- [ ] **Step 2: Add a mode rail component** - -Add: - -```jsx -function ModeRail({ route, setupMode, clientSettings, state, busy, onGateway, onVpn, onDirect }) { - const modes = [ - { - id: 'gateway', - title: 'Общий gateway', - subtitle: clientSettings?.sharedProxy - ? `${clientSettings.sharedProxy.host}:${clientSettings.sharedProxy.port}` - : 'серверная proxy', - onClick: onGateway, - }, - { - id: 'vpn', - title: 'Локальный VPN', - subtitle: state?.selectedTag || 'выбрать сервер', - onClick: onVpn, - }, - { - id: 'direct', - title: 'Напрямую', - subtitle: 'без VPN', - onClick: onDirect, - }, - ]; - - return ( - - ); -} -``` - -- [ ] **Step 3: Replace the top-level JSX** - -Use this layout in `ClientOverviewPage`: - -```jsx -return ( -
- { - setSetupMode('direct'); - enableDirect(); - }} - /> - -
- - - - -
- {setupMode === 'gateway' && ( - - )} - {setupMode === 'vpn' && ( - - )} - {setupMode === 'direct' && } -
-
- - -
-); -``` - -- [ ] **Step 4: Run build** - -Run: - -```bash -npm run build -``` - -Expected: Vite build succeeds. - -- [ ] **Step 5: Commit** - -```bash -git add src/web/components/ClientOverviewPage.jsx -git commit -m "refactor: reshape client overview around route console" -``` - ---- - -### Task 3: Replace Client Visual System - -**Files:** -- Modify: `src/web/styles.css` - -- [ ] **Step 1: Replace only the client CSS block** - -Replace the CSS from `.client-mode .app-main` through the client media query with the style direction from `docs/design/open-design/vpn-proxy-route-console-redesign.html`. Keep selectors scoped to `.client-*` so gateway screens keep the existing palette. - -Use these token values for the client block: - -```css -.app-body.client-mode { - grid-template-columns: 1fr; - background: oklch(0.965 0.008 232); -} - -.client-mode .topbar { - background: oklch(0.978 0.007 232); - border-bottom-color: oklch(0.835 0.018 232); -} - -.client-mode .app-main { - max-width: 1320px; - width: 100%; - margin: 0 auto; - padding: 18px; - color: oklch(0.238 0.028 238); -} - -.client-console { - min-height: calc(100vh - var(--topbar-h) - 36px); - display: grid; - grid-template-columns: 264px minmax(0, 1fr) 312px; - overflow: hidden; - background: oklch(0.986 0.006 232); - border: 1px solid oklch(0.835 0.018 232); - border-radius: 8px; - box-shadow: 0 18px 42px oklch(0.36 0.035 238 / 0.13); -} -``` - -- [ ] **Step 2: Add responsive behavior** - -Add: - -```css -@media (max-width: 1080px) { - .client-console { - grid-template-columns: 220px minmax(0, 1fr); - } - - .client-side-panel { - grid-column: 1 / -1; - border-left: 0; - border-top: 1px solid oklch(0.835 0.018 232); - } - - .client-route-strip { - grid-template-columns: 1fr 1fr; - } -} - -@media (max-width: 760px) { - .client-console, - .client-route-strip, - .client-inline-form, - .client-port-row { - grid-template-columns: 1fr; - } - - .client-mode-rail { - border-right: 0; - border-bottom: 1px solid oklch(0.835 0.018 232); - } -} -``` - -- [ ] **Step 3: Verify no banned patterns were introduced** - -Run: - -```bash -rg -n "background-clip:\\s*text|border-left:\\s*[2-9]|border-right:\\s*[2-9]|backdrop-filter|letter-spacing:\\s*-" src/web/styles.css -``` - -Expected: no matches. - -- [ ] **Step 4: Run build** - -Run: - -```bash -npm run build -``` - -Expected: Vite build succeeds. - -- [ ] **Step 5: Commit** - -```bash -git add src/web/styles.css -git commit -m "style: apply light route console client theme" -``` - ---- - -### Task 4: Browser Verification - -**Files:** -- No file changes expected. - -- [ ] **Step 1: Start the dev server** - -Run: - -```bash -npm run dev -- --host 127.0.0.1 --port 4567 -``` - -Expected: Vite listens on `http://127.0.0.1:4567`. - -- [ ] **Step 2: Open client mode with representative state** - -Use the browser to open: - -```text -http://127.0.0.1:4567 -``` - -Expected: the first viewport shows the mode rail, route strip, route path, selected-mode form, and copyable proxy addresses without overlap at desktop width. - -- [ ] **Step 3: Check mobile width** - -Resize to 390px wide. - -Expected: rail, route workspace, and proxy panel stack vertically; long proxy URLs truncate inside their containers; action buttons remain readable. - -- [ ] **Step 4: Run final verification** - -Run: - -```bash -npm test -npm run build -git diff --check -``` - -Expected: all commands pass. - -- [ ] **Step 5: Commit** - -```bash -git add src/web/components/ClientOverviewPage.jsx src/web/styles.css test/web/client-route.test.js -git commit -m "feat: redesign client overview as route console" -``` - ---- - -## Self-Review - -Spec coverage: - -- Current UX assessment is captured in `Current Findings`. -- New design direction is captured in `Target Design`. -- Open Design artifact is referenced explicitly. -- Implementation tasks cover route contract, markup, scoped CSS, and browser verification. - -Placeholder scan: - -- No `TBD`, `TODO`, or unspecified validation steps remain. - -Type consistency: - -- Route fields match `resolveClientRoute()`: `mode`, `status`, `localProxy`, `target`, `targetDetail`, `path`. diff --git a/docs/superpowers/specs/2026-05-19-macos-client-design.md b/docs/superpowers/specs/2026-05-19-macos-client-design.md deleted file mode 100644 index b25b041..0000000 --- a/docs/superpowers/specs/2026-05-19-macos-client-design.md +++ /dev/null @@ -1,48 +0,0 @@ -# macOS Docker Client Design - -## Goal - -Add a simple macOS-friendly Docker client that behaves like the previous local proxy product: the user runs one container, opens a web UI, loads a subscription, chooses a server, and points macOS apps at `127.0.0.1:8080`. - -## Product Shape - -The client is not a transparent gateway. It must not require router changes, host networking, `NET_ADMIN`, iptables, ipset, or TProxy. The first-screen UI should explain the current proxy state, active server, and exact local proxy addresses. Gateway-only controls remain available only when the app runs in gateway mode. - -## Runtime Architecture - -`APP_MODE=client` switches the config generator to proxy-only sing-box config: - -- one `mixed` inbound on `PROXY_PORT`; -- no `tproxy` inbound; -- custom routing rules still apply before fallback; -- `proxyDefaultMode` controls the mixed proxy fallback and defaults to VPN; -- generated configs still pass `sing-box check` before restart. - -The client Docker image builds the React frontend inside Docker so macOS installation does not require local Node.js. Docker publishes only loopback ports: - -- `127.0.0.1:3456` for the UI; -- `127.0.0.1:8080` for HTTP/SOCKS proxy. - -## Installer - -The macOS installer is a curl-friendly shell script. It checks macOS, Docker, Docker Compose, and Git, clones or updates the repository under `~/.vpn-proxy-client`, then runs the client compose file with `--build`. It prints the UI URL, proxy URLs, and optional `networksetup` commands, but does not change system proxy settings automatically. - -## UI - -Client mode gets a user-facing overview based on the old workflow: - -- status: ready, stopped, not configured, applying, error; -- active server and traffic quota; -- copyable HTTP and SOCKS5 proxy URLs; -- short macOS setup commands; -- primary actions: load subscription, choose server, restart, stop. - -Gateway terminology such as TProxy, devices, router, transparent fallback, and direct bypass cache is hidden in client mode. - -## Verification - -Use `node:test` for server config behavior, then run: - -- `npm test`; -- `npm run build`; -- `docker compose -f docker-compose.client.yml config`. diff --git a/entrypoint.sh b/entrypoint.sh old mode 100644 new mode 100755 index ad40747..30ade8c --- a/entrypoint.sh +++ b/entrypoint.sh @@ -5,22 +5,12 @@ TPROXY_PORT="${TPROXY_PORT:-7895}" TPROXY_MARK="${TPROXY_MARK:-1}" TPROXY_TABLE="${TPROXY_TABLE:-100}" TPROXY_CHAIN="${TPROXY_CHAIN:-VPN_PROXY_TPROXY}" -TPROXY_SOURCE_BYPASS_CHAIN="${TPROXY_SOURCE_BYPASS_CHAIN:-VPN_PROXY_SRC_BYPASS}" -TPROXY_SOURCE_FORWARD_CHAIN="${TPROXY_SOURCE_FORWARD_CHAIN:-VPN_PROXY_FWD_BYPASS}" -TPROXY_SOURCE_NAT_CHAIN="${TPROXY_SOURCE_NAT_CHAIN:-VPN_PROXY_NAT_BYPASS}" PROXY_PORT="${PROXY_PORT:-8080}" PROXY_BIND_IP="${PROXY_BIND_IP:-0.0.0.0}" PROXY_INPUT_CHAIN="${PROXY_INPUT_CHAIN:-VPN_PROXY_INPUT}" PROXY_FIREWALL="${PROXY_FIREWALL:-true}" PROXY_ALLOWED_CIDRS="${PROXY_ALLOWED_CIDRS:-10.0.0.0/8 172.16.0.0/12 192.168.0.0/16}" -TPROXY_BYPASS_SOURCE_CIDRS="${TPROXY_BYPASS_SOURCE_CIDRS:-}" BYPASS_CIDRS="${BYPASS_CIDRS:-0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4}" -# Имя ipset для IP-адресов, которые sing-box отправил напрямую (direct bypass cache) -DIRECT_BYPASS_SET="${DIRECT_BYPASS_SET:-vpn_direct_bypass}" -# TTL записи в ipset (секунды). По умолчанию 1 час. -DIRECT_BYPASS_TTL="${DIRECT_BYPASS_TTL:-3600}" -# Direct bypass cache выключен по умолчанию, потому что он обходит global rules. -DIRECT_BYPASS_CACHE="${DIRECT_BYPASS_CACHE:-false}" log() { printf '[gateway-entrypoint] %s\n' "$*" @@ -38,55 +28,27 @@ cleanup_proxy_firewall() { } cleanup_tproxy() { - log "cleanup tproxy rules" ipt -t mangle -D PREROUTING -j "$TPROXY_CHAIN" 2>/dev/null || true - ipt -D FORWARD -j "$TPROXY_SOURCE_FORWARD_CHAIN" 2>/dev/null || true - ipt -t nat -D POSTROUTING -j "$TPROXY_SOURCE_NAT_CHAIN" 2>/dev/null || true ipt -t mangle -F "$TPROXY_CHAIN" 2>/dev/null || true ipt -t mangle -X "$TPROXY_CHAIN" 2>/dev/null || true - ipt -t mangle -F "$TPROXY_SOURCE_BYPASS_CHAIN" 2>/dev/null || true - ipt -t mangle -X "$TPROXY_SOURCE_BYPASS_CHAIN" 2>/dev/null || true - ipt -F "$TPROXY_SOURCE_FORWARD_CHAIN" 2>/dev/null || true - ipt -X "$TPROXY_SOURCE_FORWARD_CHAIN" 2>/dev/null || true - ipt -t nat -F "$TPROXY_SOURCE_NAT_CHAIN" 2>/dev/null || true - ipt -t nat -X "$TPROXY_SOURCE_NAT_CHAIN" 2>/dev/null || true ip rule del fwmark "$TPROXY_MARK" table "$TPROXY_TABLE" 2>/dev/null || true ip route flush table "$TPROXY_TABLE" 2>/dev/null || true - # ipset не чистим при завершении — TTL сам истечёт } enable_ip_forwarding() { - log "enable IPv4 forwarding for source bypass" if [[ -w /proc/sys/net/ipv4/ip_forward ]]; then printf '1' > /proc/sys/net/ipv4/ip_forward || true - return - fi - if command -v sysctl >/dev/null 2>&1; then + elif command -v sysctl >/dev/null 2>&1; then sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true fi } -setup_direct_bypass_set() { - if [[ "$DIRECT_BYPASS_CACHE" != "true" ]]; then - export DIRECT_BYPASS_CACHE - return - fi - - log "setup ipset ${DIRECT_BYPASS_SET} (timeout=${DIRECT_BYPASS_TTL}s)" - # Создаём с timeout; если уже существует — не трогаем (сохраняем накопленные записи) - ipset create "$DIRECT_BYPASS_SET" hash:ip timeout "$DIRECT_BYPASS_TTL" 2>/dev/null || true - # Экспортируем имя для использования в Node.js через env - export DIRECT_BYPASS_SET DIRECT_BYPASS_TTL DIRECT_BYPASS_CACHE -} - setup_proxy_firewall() { if [[ "$PROXY_FIREWALL" != "true" || "$PROXY_BIND_IP" == "127.0.0.1" || "$PROXY_BIND_IP" == "::1" ]]; then return fi - log "setup proxy firewall for :${PROXY_PORT} (${PROXY_ALLOWED_CIDRS})" cleanup_proxy_firewall - ipt -N "$PROXY_INPUT_CHAIN" for cidr in $PROXY_ALLOWED_CIDRS; do ipt -A "$PROXY_INPUT_CHAIN" -s "$cidr" -j RETURN @@ -97,41 +59,17 @@ setup_proxy_firewall() { } setup_tproxy() { - log "setup tproxy on port ${TPROXY_PORT}, mark ${TPROXY_MARK}, table ${TPROXY_TABLE}" + log "setup tproxy on port ${TPROXY_PORT}" cleanup_tproxy enable_ip_forwarding ip rule add fwmark "$TPROXY_MARK" table "$TPROXY_TABLE" 2>/dev/null || true ip route replace local 0.0.0.0/0 dev lo table "$TPROXY_TABLE" - ipt -t mangle -N "$TPROXY_CHAIN" - ipt -t mangle -N "$TPROXY_SOURCE_BYPASS_CHAIN" - ipt -N "$TPROXY_SOURCE_FORWARD_CHAIN" - ipt -t nat -N "$TPROXY_SOURCE_NAT_CHAIN" - # Пропускаем пакеты, адресованные самому хосту (ответы на исходящие соединения sing-box) ipt -t mangle -A "$TPROXY_CHAIN" -m addrtype --dst-type LOCAL -j RETURN ipt -t mangle -A "$TPROXY_CHAIN" -m mark --mark "$TPROXY_MARK" -j RETURN - ipt -t mangle -A "$TPROXY_CHAIN" -j "$TPROXY_SOURCE_BYPASS_CHAIN" - ipt -I FORWARD 1 -j "$TPROXY_SOURCE_FORWARD_CHAIN" - ipt -t nat -I POSTROUTING 1 -j "$TPROXY_SOURCE_NAT_CHAIN" - - for cidr in $BYPASS_CIDRS; do - ipt -t nat -A "$TPROXY_SOURCE_NAT_CHAIN" -d "$cidr" -j RETURN - done - - for cidr in $TPROXY_BYPASS_SOURCE_CIDRS; do - ipt -t mangle -A "$TPROXY_SOURCE_BYPASS_CHAIN" -s "$cidr" -j ACCEPT - ipt -A "$TPROXY_SOURCE_FORWARD_CHAIN" -s "$cidr" -j ACCEPT - ipt -A "$TPROXY_SOURCE_FORWARD_CHAIN" -d "$cidr" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT - ipt -t nat -A "$TPROXY_SOURCE_NAT_CHAIN" -s "$cidr" -j MASQUERADE - done - - if [[ "$DIRECT_BYPASS_CACHE" == "true" ]]; then - # Direct bypass cache: IP-адреса из ipset идут напрямую, минуя sing-box. - # Включайте только если готовы к тому, что global rules для этих dst IP не будут проверяться. - ipt -t mangle -A "$TPROXY_CHAIN" -m set --match-set "$DIRECT_BYPASS_SET" dst -j RETURN - fi + # Private/local destinations stay reachable; every intercepted public packet goes to VPN. for cidr in $BYPASS_CIDRS; do ipt -t mangle -A "$TPROXY_CHAIN" -d "$cidr" -j RETURN done @@ -141,7 +79,6 @@ setup_tproxy() { ipt -t mangle -A PREROUTING -j "$TPROXY_CHAIN" } -setup_direct_bypass_set setup_tproxy setup_proxy_firewall @@ -149,7 +86,6 @@ node /app/src/server/index.js & APP_PID=$! shutdown() { - log "shutdown requested" kill "$APP_PID" 2>/dev/null || true wait "$APP_PID" 2>/dev/null || true cleanup_proxy_firewall @@ -157,7 +93,6 @@ shutdown() { } trap 'shutdown; exit 0' SIGTERM SIGINT - wait "$APP_PID" STATUS=$? cleanup_proxy_firewall diff --git a/package-lock.json b/package-lock.json index cba40ae..709dc72 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,15 +8,11 @@ "name": "vpn-proxy-gateway", "version": "0.1.0", "dependencies": { - "@dnd-kit/core": "^6.3.1", - "@dnd-kit/sortable": "^10.0.0", - "@dnd-kit/utilities": "^3.2.2", "@vitejs/plugin-react": "^5.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", "vite": "^7.0.0" - }, - "devDependencies": {} + } }, "node_modules/@babel/code-frame": { "version": "7.29.0", @@ -281,59 +277,6 @@ "node": ">=6.9.0" } }, - "node_modules/@dnd-kit/accessibility": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", - "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", - "license": "MIT", - "dependencies": { - "tslib": "^2.0.0" - }, - "peerDependencies": { - "react": ">=16.8.0" - } - }, - "node_modules/@dnd-kit/core": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", - "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", - "license": "MIT", - "dependencies": { - "@dnd-kit/accessibility": "^3.1.1", - "@dnd-kit/utilities": "^3.2.2", - "tslib": "^2.0.0" - }, - "peerDependencies": { - "react": ">=16.8.0", - "react-dom": ">=16.8.0" - } - }, - "node_modules/@dnd-kit/sortable": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz", - "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==", - "license": "MIT", - "dependencies": { - "@dnd-kit/utilities": "^3.2.2", - "tslib": "^2.0.0" - }, - "peerDependencies": { - "@dnd-kit/core": "^6.3.0", - "react": ">=16.8.0" - } - }, - "node_modules/@dnd-kit/utilities": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", - "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", - "license": "MIT", - "dependencies": { - "tslib": "^2.0.0" - }, - "peerDependencies": { - "react": ">=16.8.0" - } - }, "node_modules/@esbuild/aix-ppc64": { "version": "0.27.7", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", @@ -1606,12 +1549,6 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, "node_modules/update-browserslist-db": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", diff --git a/package.json b/package.json index 7e3fec2..a2d1008 100644 --- a/package.json +++ b/package.json @@ -11,9 +11,6 @@ "start": "node src/server/index.js" }, "dependencies": { - "@dnd-kit/core": "^6.3.1", - "@dnd-kit/sortable": "^10.0.0", - "@dnd-kit/utilities": "^3.2.2", "@vitejs/plugin-react": "^5.0.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/scripts/install-macos-client.sh b/scripts/install-macos-client.sh index fd42fdf..5577be6 100755 --- a/scripts/install-macos-client.sh +++ b/scripts/install-macos-client.sh @@ -234,7 +234,6 @@ fi PROXY_PORT="$(ask_proxy_port)" assert_proxy_port_available "$PROXY_PORT" -PROXY_PORT_END="$PROXY_PORT" UI_PORT="${REQUESTED_UI_PORT:-$(get_env_value CLIENT_UI_PORT)}" UI_PORT="${UI_PORT:-3456}" UI_PORT="$(choose_ui_port "$UI_PORT")" @@ -243,8 +242,6 @@ assert_ui_outside_proxy_range set_env_value APP_MODE client set_env_value CLIENT_UI_PORT "$UI_PORT" set_env_value CLIENT_PROXY_PORT "$PROXY_PORT" -set_env_value CLIENT_PROXY_PORT_START "$PROXY_PORT" -set_env_value CLIENT_PROXY_PORT_END "$PROXY_PORT_END" set_env_value PROXY_PORT "$PROXY_PORT" log "UI port: http://127.0.0.1:${UI_PORT}" diff --git a/src/server/clientSettings.js b/src/server/clientSettings.js deleted file mode 100644 index eb248c4..0000000 --- a/src/server/clientSettings.js +++ /dev/null @@ -1,101 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { settings } from "./config.js"; - -const DEFAULT_CLIENT_SETTINGS = { - homeBypassEnabled: false, - sharedProxyEnabled: false, - sharedProxyControlUrl: "", - sharedProxy: null, -}; - -function normalizeProxyPort(value, fallback = settings.proxyPort) { - const parsed = Number.parseInt(value, 10); - const min = Number.isInteger(settings.clientProxyPortStart) - ? settings.clientProxyPortStart - : settings.proxyPort; - const max = Number.isInteger(settings.clientProxyPortEnd) - ? settings.clientProxyPortEnd - : min; - const fallbackPort = - Number.isInteger(fallback) && fallback >= min && fallback <= max - ? fallback - : min; - if (!Number.isInteger(parsed) || parsed < min || parsed > max) { - return fallbackPort; - } - return parsed; -} - -function readJson(filePath, fallback) { - try { - if (!fs.existsSync(filePath)) return fallback; - return JSON.parse(fs.readFileSync(filePath, "utf8")); - } catch { - return fallback; - } -} - -function writeJson(filePath, value) { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, JSON.stringify(value, null, 2), "utf8"); -} - -function normalizeUrl(value) { - const raw = String(value || "").trim(); - if (!raw) return ""; - try { - const url = new URL(raw); - if (!["http:", "https:"].includes(url.protocol)) return ""; - url.hash = ""; - url.search = ""; - return url.toString().replace(/\/$/, ""); - } catch { - return ""; - } -} - -function normalizeSharedProxy(value) { - if (!value || typeof value !== "object") return null; - const host = String(value.host || "").trim(); - const port = Number.parseInt(value.port, 10); - const protocol = value.protocol === "http" ? "http" : "socks5"; - if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) { - return null; - } - return { - host, - port, - protocol, - checkedAt: value.checkedAt || null, - }; -} - -export function normalizeClientSettings(input = {}) { - const sharedProxy = normalizeSharedProxy(input.sharedProxy); - const sharedProxyEnabled = Boolean(input.sharedProxyEnabled && sharedProxy); - return { - homeBypassEnabled: Boolean(input.homeBypassEnabled), - proxyPort: normalizeProxyPort(input.proxyPort), - sharedProxyEnabled, - sharedProxyControlUrl: normalizeUrl(input.sharedProxyControlUrl), - sharedProxy, - }; -} - -export function readClientSettings() { - return normalizeClientSettings({ - ...DEFAULT_CLIENT_SETTINGS, - proxyPort: settings.proxyPort, - ...readJson(settings.clientSettingsPath, {}), - }); -} - -export function writeClientSettings(input) { - const normalized = normalizeClientSettings({ - ...readClientSettings(), - ...(input && typeof input === "object" ? input : {}), - }); - writeJson(settings.clientSettingsPath, normalized); - return normalized; -} diff --git a/src/server/config.js b/src/server/config.js index b4cb88b..e648d3c 100644 --- a/src/server/config.js +++ b/src/server/config.js @@ -9,29 +9,12 @@ const proxyPort = parsePort( process.env.PROXY_PORT, process.env.APP_MODE === "client" ? 8082 : 8080, ); -const clientProxyPortStart = parsePort( - process.env.CLIENT_PROXY_PORT_START, - proxyPort, -); -const clientProxyPortEnd = parsePort( - process.env.CLIENT_PROXY_PORT_END, - clientProxyPortStart, -); export const settings = { appMode: process.env.APP_MODE === "client" ? "client" : "gateway", port: parsePort(process.env.PORT, 3456), proxyPort, - clientProxyPortStart, - clientProxyPortEnd, tproxyPort: parsePort(process.env.TPROXY_PORT, 7895), - tproxyChain: process.env.TPROXY_CHAIN || "VPN_PROXY_TPROXY", - tproxySourceBypassChain: - process.env.TPROXY_SOURCE_BYPASS_CHAIN || "VPN_PROXY_SRC_BYPASS", - tproxySourceForwardChain: - process.env.TPROXY_SOURCE_FORWARD_CHAIN || "VPN_PROXY_FWD_BYPASS", - tproxySourceNatChain: - process.env.TPROXY_SOURCE_NAT_CHAIN || "VPN_PROXY_NAT_BYPASS", bindIp: process.env.PROXY_BIND_IP || "0.0.0.0", dataDir, distDir: process.env.DIST_DIR || "/app/dist", @@ -39,16 +22,9 @@ export const settings = { process.env.SING_BOX_CONFIG || path.join(dataDir, "sing-box-config.json"), cachePath: process.env.SING_BOX_CACHE || "/var/lib/sing-box/cache.db", statePath: path.join(dataDir, "state.json"), - customRulesPath: path.join(dataDir, "custom-rules.json"), - customRuleSetsPath: path.join(dataDir, "custom-rule-sets.json"), - clientSettingsPath: path.join(dataDir, "client-settings.json"), - devicesPath: path.join(dataDir, "devices.json"), - deviceRulesPath: path.join(dataDir, "device-rules.json"), subscriptionCachePath: path.join(dataDir, "subscription-cache.json"), sharedProxyHost: process.env.SHARED_PROXY_HOST || "", hwidPath: path.join(dataDir, "hwid"), - routingRuDirect: String(process.env.ROUTING_RU_DIRECT || "true") !== "false", - ruleSetDownloadDetour: process.env.RULE_SET_DOWNLOAD_DETOUR || "vpn", logLevel: process.env.LOG_LEVEL || "info", appName: "VPN Proxy Gateway", }; diff --git a/src/server/devices.js b/src/server/devices.js deleted file mode 100644 index 790b6fe..0000000 --- a/src/server/devices.js +++ /dev/null @@ -1,152 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { settings } from "./config.js"; - -export const DEVICE_MODES = new Set(["direct", "vpn", "rules", "block", "bypass"]); -export const DEFAULT_DEVICE_MODES = new Set(["direct", "vpn", "block"]); -export const DEFAULT_DEVICE_MODE = "vpn"; -export const DEFAULT_PROXY_MODE = "vpn"; -export const TPROXY_INBOUND = "tproxy-in"; -export const MIXED_INBOUND = "mixed-in"; - -const IPISH_RE = /^[\.\d:/]+$/; - -function readJson(filePath, fallback) { - try { - if (!fs.existsSync(filePath)) return fallback; - return JSON.parse(fs.readFileSync(filePath, "utf8")); - } catch { - return fallback; - } -} - -function writeJson(filePath, value) { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, JSON.stringify(value, null, 2), "utf8"); -} - -function normalizeDeviceMode(mode, fallback = "rules") { - const value = String(mode || "").trim().toLowerCase(); - return DEVICE_MODES.has(value) ? value : fallback; -} - -function normalizeDefaultMode(mode) { - const value = String(mode || "").trim().toLowerCase(); - return DEFAULT_DEVICE_MODES.has(value) ? value : DEFAULT_DEVICE_MODE; -} - -function normalizeProxyMode(mode) { - const value = String(mode || "").trim().toLowerCase(); - return DEFAULT_DEVICE_MODES.has(value) ? value : DEFAULT_PROXY_MODE; -} - -function normalizeIp(ip) { - const value = String(ip || "").trim(); - return value && IPISH_RE.test(value) ? value : ""; -} - -function normalizeMac(mac) { - return String(mac || "").trim(); -} - -function fromLegacyDeviceRules(input) { - const rules = Array.isArray(input) ? input : []; - const devices = []; - - for (const rule of rules) { - const sourceIps = Array.isArray(rule?.sourceIps) ? rule.sourceIps : []; - const mode = normalizeDeviceMode(rule?.outbound, "direct"); - sourceIps.forEach((sourceIp, ipIndex) => { - const ip = normalizeIp(sourceIp); - if (!ip) return; - devices.push({ - id: String(rule.id || `dev-${devices.length}`) + `-${ipIndex}`, - name: String(rule.name || `Устройство ${devices.length + 1}`).trim(), - enabled: rule.enabled !== false, - ip, - mac: "", - mode, - lastSeen: null, - }); - }); - } - - return { - defaultTransparentMode: DEFAULT_DEVICE_MODE, - proxyDefaultMode: DEFAULT_PROXY_MODE, - devices, - }; -} - -export function normalizeDeviceProfiles(input) { - const raw = - input && typeof input === "object" && !Array.isArray(input) - ? input - : { devices: input }; - const rawDevices = Array.isArray(raw.devices) ? raw.devices : []; - - return { - defaultTransparentMode: normalizeDefaultMode( - raw.defaultTransparentMode || raw.defaultMode, - ), - proxyDefaultMode: normalizeProxyMode(raw.proxyDefaultMode), - devices: rawDevices.map((device, index) => ({ - id: String(device.id || `dev-${Date.now()}-${index}`), - name: String(device.name || `Устройство ${index + 1}`).trim(), - enabled: device.enabled !== false, - ip: normalizeIp(device.ip || device.sourceIp), - mac: normalizeMac(device.mac), - mode: normalizeDeviceMode(device.mode || device.outbound, "rules"), - lastSeen: device.lastSeen || null, - })), - }; -} - -export function readDeviceProfiles() { - if (fs.existsSync(settings.devicesPath)) { - return normalizeDeviceProfiles(readJson(settings.devicesPath, null)); - } - - if (fs.existsSync(settings.deviceRulesPath)) { - return normalizeDeviceProfiles( - fromLegacyDeviceRules(readJson(settings.deviceRulesPath, [])), - ); - } - - return { - defaultTransparentMode: DEFAULT_DEVICE_MODE, - proxyDefaultMode: DEFAULT_PROXY_MODE, - devices: [], - }; -} - -export function writeDeviceProfiles(value) { - const normalized = normalizeDeviceProfiles(value); - writeJson(settings.devicesPath, normalized); - return normalized; -} - -export function normalizeCidr(ip) { - const value = normalizeIp(ip); - if (!value) return ""; - return value.includes("/") ? value : `${value}/32`; -} - -export function deviceCidrs(devices, modes) { - const allowedModes = new Set(Array.isArray(modes) ? modes : [modes]); - return (Array.isArray(devices) ? devices : []) - .filter((device) => device.enabled !== false && allowedModes.has(device.mode)) - .map((device) => normalizeCidr(device.ip)) - .filter(Boolean); -} - -export function legacyDeviceRulesFromProfiles(profiles) { - const { devices } = normalizeDeviceProfiles(profiles); - return devices.map((device) => ({ - id: device.id, - name: device.name, - enabled: device.enabled, - sourceIps: device.ip ? [device.ip] : [], - outbound: device.mode === "rules" ? "direct" : device.mode, - })); -} diff --git a/src/server/index.js b/src/server/index.js index 3a2665d..1d1dcc7 100644 --- a/src/server/index.js +++ b/src/server/index.js @@ -1,417 +1,29 @@ -import http from "node:http"; -import fs from "node:fs"; -import path from "node:path"; -import crypto from "node:crypto"; -import { spawn, spawnSync } from "node:child_process"; -import { settings } from "./config.js"; -import { fetchSubscription, fetchSubscriptionInfo } from "./subscription.js"; -import os from "node:os"; +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import { spawn, spawnSync } from 'node:child_process'; +import { settings } from './config.js'; +import { tcpPing } from './ping.js'; +import { buildSharedProxyInfo } from './sharedProxy.js'; import { buildGatewayConfig, - writeSingboxConfig, - readSingboxConfig, removeSingboxConfig, -} from "./singbox.js"; -import { - legacyDeviceRulesFromProfiles, - readDeviceProfiles, - writeDeviceProfiles, -} from "./devices.js"; -import { - readClientSettings, - writeClientSettings, -} from "./clientSettings.js"; -import { - buildSharedProxyInfo, - checkSharedProxyGateway, -} from "./sharedProxy.js"; -import { - sourceBypassCidrs, - syncTproxySourceBypass, -} from "./tproxySourceBypass.js"; -import { matchRoute, detectRuleConflicts } from "./routeMatcher.js"; -import { tcpPing, resolveHost } from "./ping.js"; + writeSingboxConfig, +} from './singbox.js'; +import { fetchSubscription, fetchSubscriptionInfo } from './subscription.js'; -const APPLY_HISTORY_LIMIT = 10; -const RULE_SET_TAG_RE = /^[a-z0-9][a-z0-9_.@!-]*$/i; -const FALLBACK_RULE_SET_CATALOG = { - geosite: [ - "geosite-category-ru", - "geosite-category-ai-!cn", - "geosite-geolocation-!cn", - "geosite-google", - "geosite-youtube", - "geosite-telegram", - "geosite-openai", - "geosite-apple", - "geosite-github", - "geosite-steam", - "geosite-discord", - "geosite-netflix", - "geosite-cloudflare", - "geosite-category-ads-all", - ], - geoip: [ - "geoip-ru", - "geoip-cloudflare", - "geoip-telegram", - "geoip-google", - "geoip-netflix", - "geoip-private", - ], -}; +const MAX_BODY_BYTES = 1_000_000; fs.mkdirSync(settings.dataDir, { recursive: true }); -const SINGBOX_PID_FILE = path.join(settings.dataDir, "singbox.pid"); - -// ─── Direct bypass cache (ipset) ──────────────────────────────────────────── -const DIRECT_BYPASS_SET = process.env.DIRECT_BYPASS_SET || "vpn_direct_bypass"; -const DIRECT_BYPASS_TTL = process.env.DIRECT_BYPASS_TTL || "3600"; -const DIRECT_BYPASS_CACHE = process.env.DIRECT_BYPASS_CACHE === "true"; -const IPSET_AVAILABLE = (() => { - try { - const result = spawnSync("ipset", ["version"], { timeout: 1000 }); - return !result.error && result.status === 0; - } catch { - return false; - } -})(); -const IP_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/; - -// Локальный счётчик добавленных IP (RAM-only, сбрасывается при перезапуске) -let directBypassCount = 0; - -function addToDirectBypass(ip) { - if (!DIRECT_BYPASS_CACHE || !IPSET_AVAILABLE || !IP_RE.test(ip)) return; - try { - spawnSync( - "ipset", - ["add", DIRECT_BYPASS_SET, ip, "timeout", DIRECT_BYPASS_TTL, "-exist"], - { - timeout: 500, - }, - ); - directBypassCount++; - } catch {} -} - -function flushDirectBypass() { - directBypassCount = 0; - if (!IPSET_AVAILABLE) return; - try { - spawnSync("ipset", ["flush", DIRECT_BYPASS_SET], { timeout: 1000 }); - } catch {} -} - -function listDirectBypass() { - if (!DIRECT_BYPASS_CACHE || !IPSET_AVAILABLE) return []; - try { - const result = spawnSync( - "ipset", - ["list", DIRECT_BYPASS_SET, "-output", "plain"], - { - encoding: "utf8", - timeout: 2000, - }, - ); - const lines = (result.stdout || "").split("\n"); - // После строки "Members:" идут IP-адреса - const membersIdx = lines.findIndex((l) => l.trim() === "Members:"); - if (membersIdx === -1) return []; - return lines - .slice(membersIdx + 1) - .map((l) => l.trim().split(" ")[0]) - .filter((l) => IP_RE.test(l)); - } catch { - return []; - } -} - let singboxProcess = null; let singboxStartedAt = null; -const LOG_BUFFER_SIZE = 500; -const logBuffer = []; -const logSubscribers = new Set(); - -const TRAFFIC_BUFFER_SIZE = 500; -const trafficBuffer = []; -const trafficSubscribers = new Set(); - -// Паттерны для парсинга трафика из логов sing-box. -// Форматы логов sing-box: -// [TCP] 192.168.1.1:PORT --> example.com:443 outbound/direct[direct] -// [UDP] 192.168.1.1:PORT --> 8.8.8.8:53 outbound/direct[direct] -// [router] match[N][rule-name] => outbound/direct[tag] -// outbound/direct[tag]: dial tcp connection to host:port - -// Назначение после --> (старый формат sing-box) -const DEST_ARROW_RE = /-->\s*([\w.\-]+):(\d{1,5})/; -// Назначение в словесном стиле -const DEST_WORD_RE = - /(?:connection\s+to|dial(?:ing)?|connect(?:ing)?\s+to)\s+([\w.\-]+):(\d{1,5})/i; -// Тип аутбаунда: outbound/TYPE[tag] или outbound/TYPE -const OUTBOUND_RE = /outbound\/([a-z0-9_\-]+)/i; -// Строка роутера: [router] match[N][rule-name] => outbound/TYPE[tag] -const ROUTER_MATCH_LINE_RE = - /\[router\].*\bmatch\[\d+\]\[([^\]]+)\].*outbound\/([a-z0-9_\-]+)/i; -// ID соединения: [CONN_ID Nms] -const CONN_ID_RE = /\[(\d{5,12})\s+\d+ms\]/; -// Входящее соединение от устройства: inbound [packet] connection from IP:PORT -const INBOUND_FROM_RE = - /inbound(?:\s+packet)?\s+connection\s+from\s+([\d.]+):\d+/i; -// Source IP из --> формата: IP:PORT --> -const SOURCE_ARROW_RE = /\b([\d.]+):\d+\s+-->/; -// Карта source IP по ID соединения -const CONN_TTL_MS = 10_000; -const connSourceMap = new Map(); -setInterval(() => { - const now = Date.now(); - for (const [id, v] of connSourceMap) { - if (now - v.at > CONN_TTL_MS) connSourceMap.delete(id); - } -}, 30_000); - -// Хранит имя последнего правила из [router] строки (для следующей строки с dest) -let _pendingRuleName = null; -let _pendingRuleAt = 0; -const RULE_CONTEXT_TTL_MS = 500; - -function parseTrafficLine(line) { - // Расширенная очистка ANSI (включая многопараметрические: \x1b[38;5;Nm) - const clean = line.replace(/\x1b\[[0-9;]*m/g, "").trim(); - - // Детектируем строку роутера — содержит правило, но не dest - const routerM = clean.match(ROUTER_MATCH_LINE_RE); - if (routerM) { - _pendingRuleName = routerM[1]; - _pendingRuleAt = Date.now(); - return null; - } - - // Извлекаем ID соединения для корреляции - const connM = clean.match(CONN_ID_RE); - const connId = connM ? connM[1] : null; - - // Строка "inbound connection from IP:PORT" — сохраняем source IP и выходим - const inboundFromM = clean.match(INBOUND_FROM_RE); - if (inboundFromM) { - if (connId) - connSourceMap.set(connId, { sourceIp: inboundFromM[1], at: Date.now() }); - return null; - } - - // Берём накопленное имя правила, если свежее - let inheritedRule = null; - if (_pendingRuleName && Date.now() - _pendingRuleAt < RULE_CONTEXT_TTL_MS) { - inheritedRule = _pendingRuleName; - } - _pendingRuleName = null; - _pendingRuleAt = 0; - - // Ищем outbound - const obM = clean.match(OUTBOUND_RE); - if (!obM) return null; - const outboundRaw = obM[1].toLowerCase(); - - // Пропускаем DNS-аутбаунды - if (outboundRaw === "dns-out" || outboundRaw === "dns") return null; - - let category; - if (outboundRaw === "direct" || outboundRaw.startsWith("direct-")) - category = "direct"; - else if (outboundRaw === "block" || outboundRaw === "reject") - category = "block"; - else category = "vpn"; - - // Ищем назначение: --> (старый формат), потом словесный (inbound/outbound connection to) - const destM = clean.match(DEST_ARROW_RE) || clean.match(DEST_WORD_RE); - if (!destM) return null; - - const host = destM[1]; - const port = parseInt(destM[2], 10); - - // Source IP: из корреляционной карты (новый формат) или из --> (старый формат) - let sourceIp = null; - if (connId) { - const stored = connSourceMap.get(connId); - if (stored && Date.now() - stored.at < CONN_TTL_MS) - sourceIp = stored.sourceIp; - } - if (!sourceIp) { - const srcM = clean.match(SOURCE_ARROW_RE); - if (srcM) sourceIp = srcM[1]; - } - - return { - ts: new Date().toISOString(), - outbound: outboundRaw, - category, - host, - port, - sourceIp, - matchedRule: inheritedRule, - }; -} - -function pushTrafficEntry(entry) { - trafficBuffer.push(entry); - if (trafficBuffer.length > TRAFFIC_BUFFER_SIZE) trafficBuffer.shift(); - for (const sub of trafficSubscribers) { - try { - sub(entry); - } catch {} - } -} - -function pushLog(level, line) { - const entry = { ts: new Date().toISOString(), level, line }; - logBuffer.push(entry); - if (logBuffer.length > LOG_BUFFER_SIZE) logBuffer.shift(); - for (const subscriber of logSubscribers) { - try { - subscriber(entry); - } catch {} - } - // Парсим трафик из info/debug строк - if (level === "info" || level === "debug") { - const traffic = parseTrafficLine(line); - if (traffic) { - pushTrafficEntry(traffic); - // Если direct и назначение — IP, добавляем в bypass-кэш - if (traffic.category === "direct" && IP_RE.test(traffic.host)) { - addToDirectBypass(traffic.host); - } - } else if ( - (level === "info" || level === "debug") && - _debugUnparsed < 30 && - /\bTCP\b|\bUDP\b|\boutbound\b/i.test(line.replace(/\x1b\[\d+m/g, "")) - ) { - _debugUnparsed++; - process.stdout.write( - `[traffic:unmatched] ${line.replace(/\x1b\[\d+m/g, "").trim()}\n`, - ); - } - } -} - -let _debugUnparsed = 0; - -// Sing-box пишет все логи в stderr, поэтому парсим уровень из содержимого строки. -// Формат: ESC[m LEVEL ESC[0m, где ESC = \x1b -const SINGBOX_LEVEL_RE = - /\x1b\[\d+m(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\x1b\[0m/i; -function parseSingboxLevel(line, fallback) { - const m = line.match(SINGBOX_LEVEL_RE); - if (!m) return fallback; - const l = m[1].toLowerCase(); - if (l === "warn") return "warning"; - if (l === "fatal") return "error"; - return l; // trace, debug, info, error -} - -// ─── PID helpers ──────────────────────────────────────────────────────────── - -function saveSingboxPid(pid) { - try { - fs.writeFileSync(SINGBOX_PID_FILE, String(pid), "utf8"); - } catch {} -} - -function readSingboxPid() { - try { - const pid = parseInt(fs.readFileSync(SINGBOX_PID_FILE, "utf8").trim(), 10); - return Number.isFinite(pid) && pid > 0 ? pid : null; - } catch { - return null; - } -} - -function removeSingboxPid() { - try { - fs.unlinkSync(SINGBOX_PID_FILE); - } catch {} -} - -function isPidAlive(pid) { - if (!pid) return false; - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -/** - * Подхватывает уже запущенный sing-box по PID — без перезапуска. - * Логи недоступны (процесс запущен раньше), но kill/stop работает. - */ -function attachExistingSingbox(pid) { - const stateData = readJson(settings.statePath, {}); - singboxStartedAt = stateData.appliedAt || new Date().toISOString(); - - let exitCb = null; - singboxProcess = { - pid, - kill: (sig = "SIGTERM") => { - try { - process.kill(pid, sig); - } catch {} - }, - once: (event, cb) => { - if (event === "exit") exitCb = cb; - }, - }; - - // Периодически проверяем, что процесс ещё жив - const watcher = setInterval(() => { - if (!isPidAlive(pid)) { - clearInterval(watcher); - if (singboxProcess?.pid === pid) { - singboxProcess = null; - singboxStartedAt = null; - removeSingboxPid(); - pushLog("warning", `sing-box (pid=${pid}) завершился`); - } - if (exitCb) { - exitCb(null, null); - exitCb = null; - } - } - }, 2000); - - pushLog("info", `sing-box подхвачен при старте (pid=${pid})`); -} - -function captureStream(stream, fallbackLevel) { - let remainder = ""; - stream.setEncoding("utf8"); - stream.on("data", (chunk) => { - const data = remainder + chunk; - const lines = data.split(/\r?\n/); - remainder = lines.pop() || ""; - for (const line of lines) { - if (!line) continue; - const level = parseSingboxLevel(line, fallbackLevel); - process.stdout.write(`[sing-box:${level}] ${line}\n`); - pushLog(level, line); - } - }); - stream.on("end", () => { - if (remainder) { - const level = parseSingboxLevel(remainder, fallbackLevel); - process.stdout.write(`[sing-box:${level}] ${remainder}\n`); - pushLog(level, remainder); - } - remainder = ""; - }); -} function readJson(filePath, fallback) { try { - if (!fs.existsSync(filePath)) return fallback; - return JSON.parse(fs.readFileSync(filePath, "utf8")); + return fs.existsSync(filePath) + ? JSON.parse(fs.readFileSync(filePath, 'utf8')) + : fallback; } catch { return fallback; } @@ -419,135 +31,60 @@ function readJson(filePath, fallback) { function writeJson(filePath, value) { fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, JSON.stringify(value, null, 2), "utf8"); -} - -function maskSubscriptionUrl(url) { - if (!url) return ""; - try { - const parsed = new URL(url); - return `${parsed.hostname}/...`; - } catch { - return url.length > 32 ? `${url.slice(0, 32)}...` : url; - } + fs.writeFileSync(filePath, JSON.stringify(value, null, 2), 'utf8'); } function sendJson(res, statusCode, payload) { - const body = JSON.stringify(payload, null, 2); - res.writeHead(statusCode, { - "content-type": "application/json; charset=utf-8", - "content-length": Buffer.byteLength(body), - }); - res.end(body); -} - -function normalizeRuleSetUrl(url) { - const value = String(url || "").trim(); - if (!value) return []; - - const urls = [value]; - - const jsdelivrMatch = value.match( - /^https:\/\/cdn\.jsdelivr\.net\/gh\/([^/]+)\/([^@/]+)@([^/]+)\/(.+)$/i, - ); - if (jsdelivrMatch) { - const [, owner, repo, ref, filePath] = jsdelivrMatch; - urls.push( - `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${filePath}`, - ); - } - - const rawMatch = value.match( - /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.+)$/i, - ); - if (rawMatch) { - const [, owner, repo, ref, filePath] = rawMatch; - urls.push(`https://cdn.jsdelivr.net/gh/${owner}/${repo}@${ref}/${filePath}`); - } - - return Array.from(new Set(urls)); -} - -function downloadFile(urlOrUrls, outputPath) { - return new Promise((resolve, reject) => { - const candidates = Array.isArray(urlOrUrls) - ? Array.from(new Set(urlOrUrls.flatMap((url) => normalizeRuleSetUrl(url)))) - : normalizeRuleSetUrl(urlOrUrls); - let index = 0; - let lastError = ""; - - function tryNext() { - const url = candidates[index]; - if (!url) { - reject(new Error(lastError || "Не удалось скачать файл")); - return; - } - - let stderr = ""; - const dl = spawn("curl", [ - "-fsSL", - "--retry", - "2", - "--retry-delay", - "1", - "--connect-timeout", - "10", - "--max-time", - "45", - "-A", - "vpn-proxy-app", - url, - "-o", - outputPath, - ]); - dl.stderr.on("data", (d) => { - stderr += d; - }); - dl.on("error", (err) => { - lastError = err.message; - index += 1; - tryNext(); - }); - dl.on("close", (code) => { - if (code === 0) { - resolve(url); - return; - } - lastError = `curl ${url} завершился с кодом ${code}: ${stderr}`; - index += 1; - tryNext(); - }); - } - - tryNext(); - }); + res.writeHead(statusCode, { 'content-type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify(payload)); } function readBody(req) { return new Promise((resolve, reject) => { const chunks = []; - req.on("data", (chunk) => chunks.push(chunk)); - req.on("end", () => { + let size = 0; + let tooLarge = false; + req.on('data', (chunk) => { + if (tooLarge) return; + size += chunk.length; + if (size > MAX_BODY_BYTES) { + tooLarge = true; + const error = new Error('Тело запроса слишком большое'); + error.statusCode = 413; + reject(error); + return; + } + chunks.push(chunk); + }); + req.on('end', () => { + if (tooLarge) return; if (!chunks.length) return resolve({}); try { - resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); + resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { - reject(new Error("Невалидный JSON в теле запроса")); + const error = new Error('Невалидный JSON в теле запроса'); + error.statusCode = 400; + reject(error); } }); - req.on("error", reject); + req.on('error', reject); }); } -function checkSingboxConfig() { - const result = spawnSync("sing-box", ["check", "-c", settings.configPath], { - encoding: "utf8", - }); +function subscriptionHost(url) { + try { + return `${new URL(url).host}/…`; + } catch { + return ''; + } +} +function checkSingboxConfig() { + const result = spawnSync('sing-box', ['check', '-c', settings.configPath], { + encoding: 'utf8', + }); if (result.status !== 0) { - throw new Error( - (result.stderr || result.stdout || "sing-box check failed").trim(), - ); + throw new Error((result.stderr || result.stdout || 'sing-box check failed').trim()); } } @@ -561,1064 +98,219 @@ function stopSingbox() { const current = singboxProcess; singboxProcess = null; singboxStartedAt = null; - const timeout = setTimeout(() => { - current.kill("SIGKILL"); + current.kill('SIGKILL'); resolve(); }, 4000); - current.once("exit", () => { + current.once('exit', () => { clearTimeout(timeout); resolve(); }); - - current.kill("SIGTERM"); + current.kill('SIGTERM'); }); } async function startSingbox() { if (!fs.existsSync(settings.configPath)) return false; - checkSingboxConfig(); await stopSingbox(); - singboxProcess = spawn("sing-box", ["run", "-c", settings.configPath], { - stdio: ["ignore", "pipe", "pipe"], + const child = spawn('sing-box', ['run', '-c', settings.configPath], { + stdio: ['ignore', 'inherit', 'inherit'], }); + singboxProcess = child; singboxStartedAt = new Date().toISOString(); - saveSingboxPid(singboxProcess.pid); - pushLog("info", `sing-box запущен (pid=${singboxProcess.pid})`); - - captureStream(singboxProcess.stdout, "info"); - captureStream(singboxProcess.stderr, "error"); - - singboxProcess.once("exit", (code, signal) => { - pushLog("info", `sing-box завершён: code=${code} signal=${signal}`); - singboxProcess = null; - singboxStartedAt = null; - removeSingboxPid(); + child.once('exit', () => { + if (singboxProcess === child) { + singboxProcess = null; + singboxStartedAt = null; + } }); - return true; } function publicState() { const state = readJson(settings.statePath, {}); - const customRules = readJson(settings.customRulesPath, []); - const deviceProfiles = readDeviceProfiles(); - const clientSettings = readClientSettings(); - const { subscriptionUrl, servers = [], ...rest } = state; return { mode: settings.appMode, port: settings.port, - proxyPort: - settings.appMode === "client" ? clientSettings.proxyPort : settings.proxyPort, - clientProxyPortRange: { - start: settings.clientProxyPortStart, - end: settings.clientProxyPortEnd, - }, - proxyBindIp: settings.bindIp, - tproxyPort: settings.appMode === "gateway" ? settings.tproxyPort : null, - routingRuDirect: settings.routingRuDirect, - clientSettings, + proxyPort: settings.proxyPort, configExists: fs.existsSync(settings.configPath), singboxRunning: Boolean(singboxProcess), singboxStartedAt, - subscriptionHost: maskSubscriptionUrl(subscriptionUrl), - hasSubscription: Boolean(subscriptionUrl), - customRules, - devicesConfig: deviceProfiles, - devices: deviceProfiles.devices, - deviceRules: legacyDeviceRulesFromProfiles(deviceProfiles), - appliedHistory: state.appliedHistory || [], - rulesUpdatedAt: state.rulesUpdatedAt || null, - devicesUpdatedAt: state.devicesUpdatedAt || null, - rulesAppliedAt: state.rulesAppliedAt || null, - bypassMode: Boolean(state.bypassMode), - directBypassCount, - directBypassEnabled: DIRECT_BYPASS_CACHE, - directBypassAvailable: IPSET_AVAILABLE, - sourceBypassCidrs: sourceBypassCidrs(deviceProfiles), - ...rest, - servers: servers.map((server) => ({ + subscriptionHost: subscriptionHost(state.subscriptionUrl), + hasSubscription: Boolean(state.subscriptionUrl), + selectedTag: state.selectedTag || '', + userInfo: state.userInfo || {}, + fetchedAt: state.fetchedAt || null, + servers: (state.servers || []).map((server) => ({ ...server, tag: String(server.tag || '').trim(), })), }; } -function normalizeList(value) { - if (Array.isArray(value)) { - return value.map((item) => String(item || "").trim()).filter(Boolean); - } - return String(value || "") - .split(/\r?\n|,/) - .map((item) => item.trim()) - .filter(Boolean); -} - -function normalizeCustomRules(input) { - const rules = Array.isArray(input) ? input : []; - return rules.map((rule, index) => ({ - id: String(rule.id || `rule-${Date.now()}-${index}`), - name: String(rule.name || `Правило ${index + 1}`).trim(), - enabled: rule.enabled !== false, - outbound: ["direct", "vpn", "block"].includes(rule.outbound) - ? rule.outbound - : "direct", - domains: normalizeList(rule.domains), - domainSuffixes: normalizeList(rule.domainSuffixes), - domainKeywords: normalizeList(rule.domainKeywords), - ipCidrs: normalizeList(rule.ipCidrs), - ports: normalizeList(rule.ports), - networks: normalizeList(rule.networks).filter((network) => - ["tcp", "udp"].includes(network), - ), - ruleSets: normalizeList(rule.ruleSets).filter((tag) => - RULE_SET_TAG_RE.test(tag), - ), - })); -} - -function normalizeDeviceRules(input) { - const rules = Array.isArray(input) ? input : []; - return rules.map((r, index) => ({ - id: String(r.id || `dev-${Date.now()}-${index}`), - name: String(r.name || `Устройство ${index + 1}`).trim(), - enabled: r.enabled !== false, - sourceIps: normalizeList(r.sourceIps).filter((ip) => - /^[\.\d:/]+$/.test(ip), - ), - outbound: ["direct", "vpn", "block"].includes(r.outbound) - ? r.outbound - : "direct", - })); -} - async function applySelectedServer(selectedTag) { const cached = readJson(settings.subscriptionCachePath, null); - if (!cached?.config) { - throw new Error("Сначала загрузите подписку"); + if (!cached?.config) throw new Error('Сначала загрузите подписку'); + + const previousConfig = fs.existsSync(settings.configPath) + ? fs.readFileSync(settings.configPath, 'utf8') + : null; + writeSingboxConfig(buildGatewayConfig(cached.config, selectedTag)); + try { + await startSingbox(); + } catch (error) { + if (previousConfig === null) removeSingboxConfig(); + else fs.writeFileSync(settings.configPath, previousConfig, 'utf8'); + throw error; } - - const customRules = readJson(settings.customRulesPath, []); - const stateForBypass = readJson(settings.statePath, {}); - const generated = buildGatewayConfig( - { ...cached.config, customRules }, - selectedTag, - { bypassAll: Boolean(stateForBypass.bypassMode) }, - ); - writeSingboxConfig(generated); - await startSingbox(); - - const prevState = readJson(settings.statePath, {}); - const now = new Date().toISOString(); - const previousTag = - prevState.selectedTag && prevState.selectedTag !== selectedTag - ? prevState.selectedTag - : prevState.previousTag || null; - const history = Array.isArray(prevState.appliedHistory) - ? prevState.appliedHistory - : []; - const nextHistory = [ - { tag: selectedTag, at: now }, - ...history.filter((h) => h.tag !== selectedTag), - ].slice(0, APPLY_HISTORY_LIMIT); - writeJson(settings.statePath, { - ...prevState, + ...readJson(settings.statePath, {}), selectedTag, - previousTag, - appliedAt: now, - rulesAppliedAt: now, - appliedHistory: nextHistory, - }); -} - -async function applyClientSharedProxy() { - const clientSettings = readClientSettings(); - if (!clientSettings.sharedProxyEnabled || !clientSettings.sharedProxy) { - return false; - } - - const generated = buildGatewayConfig( - { outbounds: [], customRules: [] }, - "", - ); - writeSingboxConfig(generated); - await startSingbox(); - pushLog( - "info", - `Mac client uses shared gateway proxy ${clientSettings.sharedProxy.host}:${clientSettings.sharedProxy.port}`, - ); - return true; -} - -async function applyClientDirectProxy() { - const generated = buildGatewayConfig( - { outbounds: [], customRules: [] }, - "", - ); - writeSingboxConfig(generated); - await startSingbox(); - pushLog("info", "Mac client routes local proxy directly"); - return true; -} - -function handleLogsStream(req, res) { - res.writeHead(200, { - "content-type": "text/event-stream; charset=utf-8", - "cache-control": "no-cache, no-transform", - connection: "keep-alive", - "x-accel-buffering": "no", - }); - - for (const entry of logBuffer.slice(-200)) { - res.write(`data: ${JSON.stringify(entry)}\n\n`); - } - - const subscriber = (entry) => { - res.write(`data: ${JSON.stringify(entry)}\n\n`); - }; - logSubscribers.add(subscriber); - - const keepalive = setInterval(() => { - try { - res.write(": ping\n\n"); - } catch {} - }, 15000); - - req.on("close", () => { - clearInterval(keepalive); - logSubscribers.delete(subscriber); + appliedAt: new Date().toISOString(), }); } async function handleApi(req, res) { - if (req.method === "GET" && req.url === "/api/state") { + if (req.method === 'GET' && req.url === '/api/state') { return sendJson(res, 200, publicState()); } - if (req.method === "GET" && req.url === "/api/shared-proxy") { - return sendJson( - res, - 200, - buildSharedProxyInfo({ - appMode: settings.appMode, - proxyPort: settings.proxyPort, - running: Boolean(singboxProcess), - hostHeader: req.headers.host, - sharedProxyHost: settings.sharedProxyHost, - }), - ); + if (req.method === 'GET' && req.url === '/api/shared-proxy') { + return sendJson(res, 200, buildSharedProxyInfo({ + appMode: settings.appMode, + proxyPort: settings.proxyPort, + running: Boolean(singboxProcess), + hostHeader: req.headers.host, + sharedProxyHost: settings.sharedProxyHost, + })); } - if (req.method === "GET" && req.url === "/api/config") { - const config = readSingboxConfig(); - return sendJson(res, 200, { success: true, config }); - } - - if (req.method === "GET" && req.url === "/api/logs") { - return sendJson(res, 200, { success: true, logs: logBuffer.slice(-200) }); - } - - if (req.method === "GET" && req.url === "/api/logs/stream") { - return handleLogsStream(req, res); - } - - if (req.method === "GET" && req.url === "/api/traffic/stream") { - res.writeHead(200, { - "content-type": "text/event-stream; charset=utf-8", - "cache-control": "no-cache, no-transform", - connection: "keep-alive", - "x-accel-buffering": "no", - }); - for (const entry of trafficBuffer.slice(-200)) { - res.write(`data: ${JSON.stringify(entry)}\n\n`); - } - const sub = (entry) => res.write(`data: ${JSON.stringify(entry)}\n\n`); - trafficSubscribers.add(sub); - const keepalive = setInterval(() => { - try { - res.write(": ping\n\n"); - } catch {} - }, 15000); - req.on("close", () => { - clearInterval(keepalive); - trafficSubscribers.delete(sub); - }); - return; - } - - if (req.method === "DELETE" && req.url === "/api/traffic") { - trafficBuffer.splice(0); - return sendJson(res, 200, { success: true }); - } - - if (req.method === "GET" && req.url === "/api/direct-cache") { - const members = listDirectBypass(); - return sendJson(res, 200, { - success: true, - count: members.length, - available: IPSET_AVAILABLE, - members, - }); - } - - if (req.method === "DELETE" && req.url === "/api/direct-cache") { - flushDirectBypass(); - return sendJson(res, 200, { success: true }); - } - - if (req.method === "POST" && req.url === "/api/bypass") { - const body = await readBody(req); - const enabled = Boolean(body.enabled); - const prevState = readJson(settings.statePath, {}); - writeJson(settings.statePath, { ...prevState, bypassMode: enabled }); - - // Перегенерируем и применяем конфиг, если sing-box запущен - if (singboxProcess && prevState.selectedTag) { - const cached = readJson(settings.subscriptionCachePath, null); - if (cached?.config) { - const customRules = readJson(settings.customRulesPath, []); - const generated = buildGatewayConfig( - { ...cached.config, customRules }, - prevState.selectedTag, - { bypassAll: enabled }, - ); - writeSingboxConfig(generated); - await startSingbox(); - pushLog( - "info", - enabled - ? "Режим обхода включён — весь трафик идёт напрямую" - : "Режим обхода отключён — правила маршрутизации восстановлены", - ); - } - } - return sendJson(res, 200, { success: true, bypassMode: enabled }); - } - - if (req.method === "GET" && req.url === "/api/rules") { - return sendJson(res, 200, { - success: true, - rules: readJson(settings.customRulesPath, []), - }); - } - - if (req.method === "PUT" && req.url === "/api/rules") { - const body = await readBody(req); - const rules = normalizeCustomRules(body.rules); - writeJson(settings.customRulesPath, rules); - const prevState = readJson(settings.statePath, {}); - writeJson(settings.statePath, { - ...prevState, - rulesUpdatedAt: new Date().toISOString(), - }); - return sendJson(res, 200, { success: true, rules }); - } - - if (req.method === "GET" && req.url === "/api/rules/conflicts") { - const rules = readJson(settings.customRulesPath, []); - return sendJson(res, 200, { - success: true, - conflicts: detectRuleConflicts(rules), - }); - } - - if (req.method === "GET" && req.url === "/api/device-rules") { - const deviceProfiles = readDeviceProfiles(); - return sendJson(res, 200, { - success: true, - deviceRules: legacyDeviceRulesFromProfiles(deviceProfiles), - }); - } - - if (req.method === "PUT" && req.url === "/api/device-rules") { - const body = await readBody(req); - const rules = normalizeDeviceRules(body.deviceRules); - const devices = []; - for (const rule of rules) { - rule.sourceIps.forEach((ip, index) => { - devices.push({ - id: `${rule.id}-${index}`, - name: rule.name, - enabled: rule.enabled, - ip, - mode: rule.outbound, - }); - }); - } - const profiles = writeDeviceProfiles({ - defaultTransparentMode: "vpn", - proxyDefaultMode: "vpn", - devices, - }); - const prevState = readJson(settings.statePath, {}); - writeJson(settings.statePath, { - ...prevState, - devicesUpdatedAt: new Date().toISOString(), - }); - return sendJson(res, 200, { - success: true, - ...profiles, - deviceRules: legacyDeviceRulesFromProfiles(profiles), - }); - } - - if (req.method === "GET" && req.url === "/api/devices") { - const profiles = readDeviceProfiles(); - return sendJson(res, 200, { success: true, ...profiles }); - } - - if (req.method === "PUT" && req.url === "/api/devices") { - const body = await readBody(req); - const input = body.devicesConfig || { - defaultTransparentMode: body.defaultTransparentMode || body.defaultMode, - proxyDefaultMode: body.proxyDefaultMode, - devices: body.devices, - }; - const profiles = writeDeviceProfiles(input); - const sourceBypassResult = syncTproxySourceBypass(profiles); - if (!sourceBypassResult.success) { - pushLog( - "warning", - `Не удалось применить bypass устройств в iptables: ${sourceBypassResult.error}`, - ); - } - const prevState = readJson(settings.statePath, {}); - const devicesUpdatedAt = new Date().toISOString(); - writeJson(settings.statePath, { - ...prevState, - devicesUpdatedAt, - }); - return sendJson(res, 200, { - success: true, - ...profiles, - sourceBypassCidrs: sourceBypassCidrs(profiles), - sourceBypassResult, - devicesUpdatedAt, - }); - } - - if (req.method === "GET" && req.url === "/api/client-settings") { - return sendJson(res, 200, { - success: true, - clientSettings: readClientSettings(), - }); - } - - if (req.method === "PUT" && req.url === "/api/client-settings") { - const body = await readBody(req); - const clientSettings = writeClientSettings(body.clientSettings || body); - const prevState = readJson(settings.statePath, {}); - - if (settings.appMode === "client") { - if (clientSettings.sharedProxyEnabled) { - await applyClientSharedProxy(); - } else if (clientSettings.homeBypassEnabled) { - await applyClientDirectProxy(); - } else if ( - prevState.selectedTag && - readJson(settings.subscriptionCachePath, null)?.config - ) { - await applySelectedServer(prevState.selectedTag); - } else { - await stopSingbox(); - removeSingboxConfig(); - } - } - - return sendJson(res, 200, { - success: true, - clientSettings, - singboxRunning: Boolean(singboxProcess), - }); - } - - if (req.method === "POST" && req.url === "/api/client-settings/shared-proxy/check") { - const body = await readBody(req); - const url = String(body.url || "").trim(); - if (!url) { - return sendJson(res, 400, { - success: false, - error: "Укажите адрес gateway", - }); - } - - const patch = await checkSharedProxyGateway(url); - const clientSettings = writeClientSettings({ - ...readClientSettings(), - ...patch, - homeBypassEnabled: false, - }); - - if (settings.appMode === "client") { - await applyClientSharedProxy(); - } - - return sendJson(res, 200, { - success: true, - clientSettings, - singboxRunning: Boolean(singboxProcess), - }); - } - - if (req.method === "GET" && req.url === "/api/rule-sets") { - return sendJson(res, 200, { - success: true, - ruleSets: readJson(settings.customRuleSetsPath, []), - }); - } - - if (req.method === "PUT" && req.url === "/api/rule-sets") { - const body = await readBody(req); - const rawSets = Array.isArray(body.ruleSets) ? body.ruleSets : []; - const normalized = rawSets - .filter((rs) => rs && rs.tag && rs.url) - .map((rs) => ({ - tag: String(rs.tag).trim(), - url: String(rs.url).trim(), - format: rs.format === "source" ? "source" : "binary", - })) - .filter((rs) => RULE_SET_TAG_RE.test(rs.tag)); - writeJson(settings.customRuleSetsPath, normalized); - return sendJson(res, 200, { success: true, ruleSets: normalized }); - } - - if (req.method === "POST" && req.url === "/api/rule-sets/lookup") { - const body = await readBody(req); - const url = String(body.url || "").trim(); - const tag = String(body.tag || "").trim(); - if (!url) - return sendJson(res, 400, { success: false, error: "Укажите url" }); - - // Кеш — файл рядом с custom-rule-sets.json - // Используем crypto hash чтобы избежать коллизий при одинаковом префиксе URL - const cacheKey = crypto.createHash("sha1").update(url).digest("hex"); - const cacheFile = path.join( - settings.dataDir, - `ruleset-cache-${cacheKey}.json`, - ); - const CACHE_TTL_MS = 3 * 60 * 60 * 1000; // 3 часа - - if (fs.existsSync(cacheFile)) { - try { - const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8")); - if (Date.now() - new Date(cached.cachedAt).getTime() < CACHE_TTL_MS) { - return sendJson(res, 200, { success: true, ...cached }); - } - } catch {} - } - - // Скачать .srs во временный файл - const tmpSrs = path.join(os.tmpdir(), `singbox-rs-${Date.now()}.srs`); - const tmpJson = tmpSrs.replace(".srs", ".json"); - try { - const downloadedFrom = await downloadFile(url, tmpSrs); - - // Декомпилировать через sing-box rule-set decompile - const dec = spawnSync( - "sing-box", - ["rule-set", "decompile", "--output", tmpJson, tmpSrs], - { - timeout: 15000, - encoding: "utf8", - }, - ); - - if (dec.error) { - return sendJson(res, 200, { - success: false, - error: `sing-box не найден или не запустился: ${dec.error.message}`, - }); - } - - if (dec.status !== 0) { - return sendJson(res, 200, { - success: false, - error: `sing-box decompile завершился с ошибкой: ${dec.stderr || "неизвестная ошибка"}`, - }); - } - - const raw = JSON.parse(fs.readFileSync(tmpJson, "utf8")); - // Плоский список записей из всех rules - const rules = Array.isArray(raw.rules) ? raw.rules : []; - const entries = []; - for (const rule of rules) { - if (Array.isArray(rule.domain)) - entries.push( - ...rule.domain.map((v) => ({ type: "domain", value: v })), - ); - if (Array.isArray(rule.domain_suffix)) - entries.push( - ...rule.domain_suffix.map((v) => ({ type: "suffix", value: v })), - ); - if (Array.isArray(rule.domain_keyword)) - entries.push( - ...rule.domain_keyword.map((v) => ({ type: "keyword", value: v })), - ); - if (Array.isArray(rule.ip_cidr)) - entries.push( - ...rule.ip_cidr.map((v) => ({ type: "cidr", value: v })), - ); - if (Array.isArray(rule.domain_regex)) - entries.push( - ...rule.domain_regex.map((v) => ({ type: "regex", value: v })), - ); - } - - const stats = { - domain: entries.filter((e) => e.type === "domain").length, - suffix: entries.filter((e) => e.type === "suffix").length, - keyword: entries.filter((e) => e.type === "keyword").length, - cidr: entries.filter((e) => e.type === "cidr").length, - regex: entries.filter((e) => e.type === "regex").length, - total: entries.length, - }; - - const result = { - tag, - url, - downloadedFrom, - entries, - stats, - cachedAt: new Date().toISOString(), - }; - writeJson(cacheFile, result); - return sendJson(res, 200, { success: true, ...result }); - } catch (err) { - return sendJson(res, 200, { success: false, error: err.message }); - } finally { - for (const f of [tmpSrs, tmpJson]) { - try { - fs.unlinkSync(f); - } catch {} - } - } - } - - if (req.method === "GET" && req.url === "/api/rule-sets/sagernet-catalog") { - const cacheFile = path.join( - settings.dataDir, - "sagernet-catalog-cache.json", - ); - const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 часа - - if (fs.existsSync(cacheFile)) { - try { - const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8")); - if (Date.now() - new Date(cached.cachedAt).getTime() < CACHE_TTL_MS) { - return sendJson(res, 200, { success: true, ...cached }); - } - } catch {} - } - - try { - const headers = { "User-Agent": "vpn-proxy-app" }; - const [gsRes, giRes] = await Promise.all([ - fetch( - "https://api.github.com/repos/SagerNet/sing-geosite/git/trees/rule-set?recursive=1", - { headers }, - ), - fetch( - "https://api.github.com/repos/SagerNet/sing-geoip/git/trees/rule-set?recursive=1", - { headers }, - ), - ]); - if (!gsRes.ok || !giRes.ok) { - throw new Error( - `GitHub API недоступен: geosite=${gsRes.status}, geoip=${giRes.status}`, - ); - } - const gsData = await gsRes.json(); - const giData = await giRes.json(); - - const geosite = (gsData.tree || []) - .filter((f) => f.path.endsWith(".srs")) - .map((f) => f.path.replace(".srs", "")) - .sort(); - const geoip = (giData.tree || []) - .filter((f) => f.path.endsWith(".srs")) - .map((f) => f.path.replace(".srs", "")) - .sort(); - - if (!geosite.length && !geoip.length) { - throw new Error("GitHub API вернул пустой каталог rule-set"); - } - - const result = { geosite, geoip, cachedAt: new Date().toISOString() }; - writeJson(cacheFile, result); - return sendJson(res, 200, { success: true, ...result }); - } catch (err) { - const result = { - ...FALLBACK_RULE_SET_CATALOG, - cachedAt: new Date().toISOString(), - fallback: true, - warning: `GitHub каталог не загрузился, показан встроенный список: ${err.message}`, - }; - return sendJson(res, 200, { success: true, ...result }); - } - } - - if (req.method === "POST" && req.url === "/api/route/check") { - const body = await readBody(req); - const host = String(body.host || "").trim(); - let ip = String(body.ip || "").trim(); - const port = - body.port !== undefined && body.port !== "" - ? Number(body.port) - : undefined; - const network = String(body.network || "").trim() || undefined; - const sourceIp = String(body.sourceIp || "").trim() || undefined; - const inbound = String(body.inbound || "").trim() || undefined; - - if (!host && !ip) { - return sendJson(res, 400, { - success: false, - error: "Укажите домен или IP", - }); - } - - let resolvedFrom = null; - if (!ip && host) { - const resolved = await resolveHost(host); - if (resolved) { - ip = resolved; - resolvedFrom = host; - } - } - - const rules = readJson(settings.customRulesPath, []); + if (req.method === 'POST' && req.url === '/api/servers/ping-all') { const state = readJson(settings.statePath, {}); - const vpnTag = state.selectedTag || "vpn-out"; - const result = matchRoute({ host, ip, port, network, sourceIp, inbound }, rules, { - routingRuDirect: settings.routingRuDirect, - vpnTag, - deviceProfiles: readDeviceProfiles(), - }); - - return sendJson(res, 200, { - success: true, - result, - resolvedIp: ip || null, - resolvedFrom, - }); - } - - if (req.method === "POST" && req.url === "/api/servers/ping") { - const body = await readBody(req); - const host = String(body.host || "").trim(); - const port = Number(body.port); - if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) { - return sendJson(res, 400, { - success: false, - error: "Требуются host и port", - }); - } - const result = await tcpPing(host, port, Number(body.timeout) || 3000); - return sendJson(res, 200, { success: true, ...result }); - } - - if (req.method === "POST" && req.url === "/api/servers/ping-all") { - const cached = readJson(settings.subscriptionCachePath, null); - const state = readJson(settings.statePath, {}); - const servers = state.servers || cached?.servers || []; - const results = await Promise.all( - servers.map(async (server) => { - const ping = await tcpPing(server.server, server.server_port, 3000); - return { - tag: String(server.tag || '').trim(), - ...ping, - checkedAt: new Date().toISOString(), - }; - }), - ); + const results = await Promise.all((state.servers || []).map(async (server) => ({ + tag: String(server.tag || '').trim(), + ...await tcpPing(server.server, server.server_port), + checkedAt: new Date().toISOString(), + }))); return sendJson(res, 200, { success: true, results }); } - if (req.method === "POST" && req.url === "/api/config/validate") { - const cached = readJson(settings.subscriptionCachePath, null); - const customRules = readJson(settings.customRulesPath, []); - const stateData = readJson(settings.statePath, {}); - const tag = stateData.selectedTag; - - if (!cached?.config) { - return sendJson(res, 200, { - success: true, - valid: false, - error: "Подписка не загружена", - }); - } - if (!tag) { - return sendJson(res, 200, { - success: true, - valid: false, - error: "Сервер не выбран", - }); - } - - try { - buildGatewayConfig({ ...cached.config, customRules }, tag); - } catch (err) { - return sendJson(res, 200, { - success: true, - valid: false, - error: err.message, - }); - } - - if (fs.existsSync(settings.configPath)) { - try { - checkSingboxConfig(); - return sendJson(res, 200, { success: true, valid: true }); - } catch (err) { - return sendJson(res, 200, { - success: true, - valid: false, - error: err.message, - }); - } - } - return sendJson(res, 200, { - success: true, - valid: true, - note: "Конфиг собирается без ошибок (sing-box check не выполнен — нет файла)", - }); - } - - if (req.method === "POST" && req.url === "/api/apply/rollback") { - const stateData = readJson(settings.statePath, {}); - const target = stateData.previousTag; - if (!target) { - return sendJson(res, 400, { - success: false, - error: "Нет предыдущего сервера для отката", - }); - } - await applySelectedServer(target); - return sendJson(res, 200, { success: true, selectedTag: target }); - } - - if (req.method === "POST" && req.url === "/api/subscription/fetch") { - const body = await readBody(req); - const url = String(body.url || "").trim(); - if (!url) - return sendJson(res, 400, { - success: false, - error: "Укажите subscription URL", - }); - - const parsed = await fetchSubscription(url); - writeJson(settings.subscriptionCachePath, { url, ...parsed }); - - const prevState = readJson(settings.statePath, {}); + if (req.method === 'POST' && req.url === '/api/subscription/fetch') { + const { url = '' } = await readBody(req); + const normalizedUrl = String(url).trim(); + const parsed = await fetchSubscription(normalizedUrl); + writeJson(settings.subscriptionCachePath, { url: normalizedUrl, ...parsed }); writeJson(settings.statePath, { - ...prevState, - subscriptionUrl: url, + subscriptionUrl: normalizedUrl, servers: parsed.servers, userInfo: parsed.userInfo, fetchedAt: parsed.fetchedAt, }); - + await stopSingbox(); + removeSingboxConfig(); return sendJson(res, 200, { success: true, ...parsed }); } - if (req.method === "POST" && req.url === "/api/subscription/refresh-info") { - const prevState = readJson(settings.statePath, {}); - if (!prevState.subscriptionUrl) { - return sendJson(res, 400, { success: false, error: "Подписка не настроена" }); + if (req.method === 'POST' && req.url === '/api/subscription/refresh-info') { + const state = readJson(settings.statePath, {}); + if (!state.subscriptionUrl) { + return sendJson(res, 400, { success: false, error: 'Подписка не настроена' }); } - - const info = await fetchSubscriptionInfo(prevState.subscriptionUrl); - writeJson(settings.statePath, { ...prevState, ...info }); + const info = await fetchSubscriptionInfo(state.subscriptionUrl); + writeJson(settings.statePath, { ...state, ...info }); const cached = readJson(settings.subscriptionCachePath, null); if (cached) writeJson(settings.subscriptionCachePath, { ...cached, ...info }); return sendJson(res, 200, { success: true, ...info }); } - if (req.method === "DELETE" && req.url === "/api/subscription") { - if (fs.existsSync(settings.subscriptionCachePath)) - fs.rmSync(settings.subscriptionCachePath); - const prevState = readJson(settings.statePath, {}); - delete prevState.subscriptionUrl; - delete prevState.servers; - delete prevState.userInfo; - delete prevState.fetchedAt; - delete prevState.selectedTag; - delete prevState.appliedAt; - writeJson(settings.statePath, prevState); + if (req.method === 'DELETE' && req.url === '/api/subscription') { await stopSingbox(); removeSingboxConfig(); - pushLog("info", "Подписка удалена, sing-box остановлен"); + fs.rmSync(settings.subscriptionCachePath, { force: true }); + writeJson(settings.statePath, {}); return sendJson(res, 200, { success: true }); } - if (req.method === "POST" && req.url === "/api/apply") { - const body = await readBody(req); - const selectedTag = String(body.selectedTag || "").trim(); - if (!selectedTag) - return sendJson(res, 400, { - success: false, - error: "selectedTag обязателен", - }); - - if (settings.appMode === "client") { - writeClientSettings({ - ...readClientSettings(), - homeBypassEnabled: false, - sharedProxyEnabled: false, - }); - } - - await applySelectedServer(selectedTag); - return sendJson(res, 200, { - success: true, - selectedTag, - configPath: settings.configPath, - singboxRunning: Boolean(singboxProcess), - }); + if (req.method === 'POST' && req.url === '/api/apply') { + const { selectedTag = '' } = await readBody(req); + const tag = String(selectedTag).trim(); + if (!tag) return sendJson(res, 400, { success: false, error: 'Выберите сервер' }); + await applySelectedServer(tag); + return sendJson(res, 200, { success: true, selectedTag: tag }); } - if (req.method === "POST" && req.url === "/api/singbox/stop") { + if (req.method === 'POST' && req.url === '/api/singbox/stop') { await stopSingbox(); - pushLog("info", "sing-box остановлен пользователем"); return sendJson(res, 200, { success: true, singboxRunning: false }); } - if (req.method === "POST" && req.url === "/api/singbox/restart") { + if (req.method === 'POST' && req.url === '/api/singbox/restart') { if (!fs.existsSync(settings.configPath)) { - return sendJson(res, 400, { - success: false, - error: "Конфиг отсутствует — сначала примените сервер", - }); + return sendJson(res, 400, { success: false, error: 'Сначала выберите сервер' }); } await startSingbox(); - pushLog("info", "sing-box перезапущен пользователем"); - return sendJson(res, 200, { - success: true, - singboxRunning: Boolean(singboxProcess), - }); + return sendJson(res, 200, { success: true, singboxRunning: true }); } - if (req.method === "POST" && req.url === "/api/singbox/clear") { - await stopSingbox(); - removeSingboxConfig(); - const prevState = readJson(settings.statePath, {}); - delete prevState.selectedTag; - delete prevState.appliedAt; - writeJson(settings.statePath, prevState); - pushLog("info", "Конфиг sing-box удалён, процесс остановлен"); - return sendJson(res, 200, { success: true, singboxRunning: false }); - } - - return sendJson(res, 404, { success: false, error: "Не найдено" }); + return sendJson(res, 404, { success: false, error: 'Не найдено' }); } const mime = { - ".html": "text/html; charset=utf-8", - ".js": "text/javascript; charset=utf-8", - ".css": "text/css; charset=utf-8", - ".svg": "image/svg+xml", - ".json": "application/json; charset=utf-8", + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.svg': 'image/svg+xml', + '.json': 'application/json; charset=utf-8', }; function serveStatic(req, res) { - const requestPath = new URL(req.url, `http://localhost:${settings.port}`) - .pathname; - const cleanPath = requestPath === "/" ? "/index.html" : requestPath; - const filePath = path.resolve(settings.distDir, `.${cleanPath}`); - const distRoot = path.resolve(settings.distDir); - - if (!filePath.startsWith(distRoot)) { + const pathname = new URL(req.url, `http://localhost:${settings.port}`).pathname; + const requested = pathname === '/' ? 'index.html' : pathname.slice(1); + const filePath = path.resolve(settings.distDir, requested); + const relative = path.relative(path.resolve(settings.distDir), filePath); + if (relative.startsWith('..') || path.isAbsolute(relative)) { res.writeHead(403); - return res.end("Forbidden"); + return res.end('Forbidden'); } - - const finalPath = - fs.existsSync(filePath) && fs.statSync(filePath).isFile() - ? filePath - : path.join(settings.distDir, "index.html"); - - const ext = path.extname(finalPath); - res.writeHead(200, { - "content-type": mime[ext] || "application/octet-stream", - }); + const finalPath = fs.existsSync(filePath) && fs.statSync(filePath).isFile() + ? filePath + : path.join(settings.distDir, 'index.html'); + res.writeHead(200, { 'content-type': mime[path.extname(finalPath)] || 'application/octet-stream' }); fs.createReadStream(finalPath).pipe(res); } const server = http.createServer(async (req, res) => { try { - if (req.url?.startsWith("/api/")) { - return await handleApi(req, res); - } - return serveStatic(req, res); + return req.url?.startsWith('/api/') + ? await handleApi(req, res) + : serveStatic(req, res); } catch (error) { - console.error("[control] request failed", error); - return sendJson(res, 500, { + console.error('[control] request failed', error); + return sendJson(res, error.statusCode || 500, { success: false, error: error.message || String(error), }); } }); -process.on("SIGTERM", async () => { +async function shutdown() { await stopSingbox(); process.exit(0); -}); - -process.on("SIGINT", async () => { - await stopSingbox(); - process.exit(0); -}); - -const sourceBypassStartup = syncTproxySourceBypass(readDeviceProfiles()); -if (!sourceBypassStartup.success) { - pushLog( - "warning", - `Не удалось применить bypass устройств в iptables: ${sourceBypassStartup.error}`, - ); } -// При старте пробуем подхватить уже запущенный sing-box -const existingPid = readSingboxPid(); -if (existingPid && isPidAlive(existingPid)) { - attachExistingSingbox(existingPid); -} else { - removeSingboxPid(); +process.on('SIGTERM', shutdown); +process.on('SIGINT', shutdown); - // Если конфиг отсутствует (например после передплоя), пробуем пересобрать из кэша - if (!fs.existsSync(settings.configPath)) { - const stateData = readJson(settings.statePath, {}); - const cached = readJson(settings.subscriptionCachePath, null); - if (stateData.selectedTag && cached?.config) { - try { - const customRules = readJson(settings.customRulesPath, []); - const generated = buildGatewayConfig( - { ...cached.config, customRules }, - stateData.selectedTag, - { bypassAll: Boolean(stateData.bypassMode) }, - ); - writeSingboxConfig(generated); - pushLog( - "info", - `Конфиг sing-box восстановлен из кэша (сервер: ${stateData.selectedTag})`, - ); - } catch (err) { - pushLog( - "error", - `Не удалось восстановить конфиг sing-box: ${err.message}`, - ); - } - } - } - - await startSingbox().catch((error) => { - console.warn(`[control] sing-box не запущен: ${error.message}`); - pushLog("error", `sing-box не запущен при старте: ${error.message}`); - }); +const state = readJson(settings.statePath, {}); +const cached = readJson(settings.subscriptionCachePath, null); +if (!fs.existsSync(settings.configPath) && state.selectedTag && cached?.config) { + writeSingboxConfig(buildGatewayConfig(cached.config, state.selectedTag)); } +await startSingbox().catch((error) => console.warn(`[control] sing-box не запущен: ${error.message}`)); -server.listen(settings.port, "0.0.0.0", () => { - console.log(`[control] gateway UI слушает :${settings.port}`); +server.listen(settings.port, '0.0.0.0', () => { + console.log(`[control] ${settings.appMode} UI слушает :${settings.port}`); }); diff --git a/src/server/routeMatcher.js b/src/server/routeMatcher.js deleted file mode 100644 index a528984..0000000 --- a/src/server/routeMatcher.js +++ /dev/null @@ -1,340 +0,0 @@ -// Простой симулятор роутинга sing-box. -// Берём список customRules + safety/RU-direct и определяем, какое правило сработает. -// Для geoip-ru / geosite-category-ru возвращаем "может сработать" — без скачанного ruleset -// мы не можем точно сказать, попадает ли IP/домен в RU. - -import net from "node:net"; -import { TPROXY_INBOUND, MIXED_INBOUND } from "./devices.js"; - -function ipv4ToInt(ip) { - const parts = ip.split(".").map((x) => Number.parseInt(x, 10)); - if ( - parts.length !== 4 || - parts.some((n) => Number.isNaN(n) || n < 0 || n > 255) - ) - return null; - return ( - ((parts[0] << 24) >>> 0) + (parts[1] << 16) + (parts[2] << 8) + parts[3] - ); -} - -function ipInCidr(ip, cidr) { - if (!net.isIP(ip)) return false; - const [addr, maskStr] = String(cidr).split("/"); - if (!addr) return false; - - if (net.isIPv4(ip) && net.isIPv4(addr)) { - const mask = maskStr === undefined ? 32 : Number.parseInt(maskStr, 10); - if (!Number.isInteger(mask) || mask < 0 || mask > 32) return false; - const ipInt = ipv4ToInt(ip); - const cidrInt = ipv4ToInt(addr); - if (ipInt === null || cidrInt === null) return false; - if (mask === 0) return true; - const m = (~0 << (32 - mask)) >>> 0; - return (ipInt & m) === (cidrInt & m); - } - // IPv6 — упрощённо: точное сравнение строк (без полноценной обработки) - return false; -} - -const PRIVATE_CIDRS = [ - "10.0.0.0/8", - "172.16.0.0/12", - "192.168.0.0/16", - "127.0.0.0/8", - "169.254.0.0/16", -]; - -function isPrivateIp(ip) { - if (!ip) return false; - return PRIVATE_CIDRS.some((cidr) => ipInCidr(ip, cidr)); -} - -function normalizeCidr(ip) { - const value = String(ip || "").trim(); - if (!value) return ""; - return value.includes("/") ? value : `${value}/32`; -} - -function deviceMatchesSourceIp(device, sourceIp) { - if (!device?.ip || !sourceIp) return false; - return ipInCidr(sourceIp, normalizeCidr(device.ip)); -} - -function modeOutbound(mode, vpnTag) { - if (mode === "vpn") return `${vpnTag} (VPN)`; - if (mode === "direct" || mode === "block") return mode; - return null; -} - -function likelyRuHost(host) { - const value = String(host || "").toLowerCase(); - return value === "ru" || value.endsWith(".ru"); -} - -function hostMatchesDomain(host, domain) { - if (!host || !domain) return false; - return host.toLowerCase() === domain.toLowerCase(); -} - -function hostMatchesSuffix(host, suffix) { - if (!host || !suffix) return false; - const h = host.toLowerCase(); - const s = suffix.toLowerCase(); - return h === s || h.endsWith("." + s) || h.endsWith(s); -} - -function hostMatchesKeyword(host, keyword) { - if (!host || !keyword) return false; - return host.toLowerCase().includes(keyword.toLowerCase()); -} - -function ruleMatches(rule, target) { - const { host = "", ip = "", port, network } = target; - - if (!rule?.enabled) return false; - - const checks = []; - - if (rule.domains?.length) { - checks.push(rule.domains.some((d) => hostMatchesDomain(host, d))); - } - if (rule.domainSuffixes?.length) { - checks.push(rule.domainSuffixes.some((d) => hostMatchesSuffix(host, d))); - } - if (rule.domainKeywords?.length) { - checks.push(rule.domainKeywords.some((d) => hostMatchesKeyword(host, d))); - } - if (rule.ipCidrs?.length) { - if (!ip) return false; - checks.push(rule.ipCidrs.some((cidr) => ipInCidr(ip, cidr))); - } - if (rule.ports?.length) { - if (port === undefined || port === null || port === "") return false; - const p = Number(port); - checks.push( - rule.ports.some((portStr) => { - const s = String(portStr).trim(); - if (s.includes("-")) { - const [from, to] = s.split("-").map((x) => Number(x)); - return p >= from && p <= to; - } - return p === Number(s); - }), - ); - } - if (rule.networks?.length) { - if (!network) return false; - checks.push(rule.networks.includes(network)); - } - - if (!checks.length) return false; - return checks.every(Boolean); -} - -/** - * Симулирует роутинг и возвращает результат. - * @param {object} target { host, ip, port, network } - * @param {Array} customRules - * @param {object} options { routingRuDirect, vpnTag } - */ -export function matchRoute(target, customRules, options = {}) { - const { - routingRuDirect = true, - vpnTag = "vpn-out", - deviceProfiles = { - defaultTransparentMode: "vpn", - proxyDefaultMode: "vpn", - devices: [], - }, - } = options; - const rules = Array.isArray(customRules) ? customRules : []; - const inbound = target.inbound || TPROXY_INBOUND; - const sourceIp = target.sourceIp || ""; - const devices = Array.isArray(deviceProfiles.devices) - ? deviceProfiles.devices - : []; - const matchedDevice = devices.find( - (device) => - device.enabled !== false && deviceMatchesSourceIp(device, sourceIp), - ); - - if ( - inbound === TPROXY_INBOUND && - matchedDevice && - matchedDevice.mode === "bypass" - ) { - return { - matched: "kernel-bypass", - ruleIndex: -1, - ruleId: matchedDevice.id, - ruleName: `${matchedDevice.name} -> bypass TProxy`, - outbound: "direct", - reason: "Source IP исключён на уровне iptables до попадания в sing-box", - }; - } - - // 1. private IP → direct - if (target.ip && isPrivateIp(target.ip)) { - return { - matched: "system", - ruleIndex: -1, - ruleName: "private IP → direct", - outbound: "direct", - reason: `IP ${target.ip} приватный`, - }; - } - - // 2. global custom rules apply to every inbound before fallbacks. - for (let i = 0; i < rules.length; i += 1) { - const rule = rules[i]; - if (ruleMatches(rule, target)) { - const outbound = - rule.outbound === "vpn" ? `${vpnTag} (VPN)` : rule.outbound; - return { - matched: "custom", - ruleIndex: i, - ruleId: rule.id, - ruleName: rule.name, - outbound, - reason: "Совпадение по global custom rule", - }; - } - } - - // 3. RU direct is global. Without a local rule-set DB we only detect obvious .ru hosts. - if (routingRuDirect && likelyRuHost(target.host)) { - return { - matched: "geo", - ruleIndex: -2, - ruleName: "geosite-category-ru → direct", - outbound: "direct", - reason: "Домен выглядит как RU; точное попадание в rule-set проверит sing-box", - }; - } - - // 4. transparent device defaults. - if (inbound === TPROXY_INBOUND && matchedDevice) { - const outbound = modeOutbound(matchedDevice.mode, vpnTag); - if (outbound) { - return { - matched: "device-default", - ruleIndex: -1, - ruleId: matchedDevice.id, - ruleName: `${matchedDevice.name} → ${matchedDevice.mode}`, - outbound, - reason: "Fallback устройства после global rules", - }; - } - } - - // 5. explicit proxy default. - if (inbound === MIXED_INBOUND) { - const mode = deviceProfiles.proxyDefaultMode || "vpn"; - return { - matched: "proxy-default", - ruleIndex: -1, - ruleName: `mixed-in default → ${mode}`, - outbound: modeOutbound(mode, vpnTag) || `${vpnTag} (VPN)`, - reason: "Fallback explicit HTTP/SOCKS proxy после global rules", - }; - } - - // 6. unknown transparent device default. - if (inbound === TPROXY_INBOUND) { - const mode = deviceProfiles.defaultTransparentMode || "vpn"; - return { - matched: "transparent-default", - ruleIndex: -1, - ruleName: `transparent default → ${mode}`, - outbound: modeOutbound(mode, vpnTag) || "direct", - reason: "Fallback unknown transparent device после global rules", - }; - } - - // 7. final → direct - return { - matched: "final", - ruleIndex: -3, - ruleName: "final", - outbound: "direct", - reason: "Не сработало ни одно правило — итоговый final отправляет напрямую", - }; -} - -/** - * Детектор конфликтов: ищет правила, перекрытые предыдущими. - * Простая эвристика: если правило-кандидат полностью перекрывается ранее идущим - * по доменам/суффиксам/CIDR — отмечаем конфликт. - */ -export function detectRuleConflicts(rules) { - const list = Array.isArray(rules) ? rules : []; - const conflicts = []; - - for (let i = 1; i < list.length; i += 1) { - const cur = list[i]; - if (!cur?.enabled) continue; - - for (let j = 0; j < i; j += 1) { - const prev = list[j]; - if (!prev?.enabled) continue; - - // Если outbound одинаковый — это не "конфликт", это дубликат - const sameOutbound = prev.outbound === cur.outbound; - - // Проверка перекрытия доменов - const overlaps = []; - - // Точные домены покрываются prev.suffix - for (const d of cur.domains || []) { - if ((prev.domainSuffixes || []).some((s) => hostMatchesSuffix(d, s))) { - overlaps.push({ - kind: "domain", - value: d, - by: `суффикс ${(prev.domainSuffixes || []).find((s) => hostMatchesSuffix(d, s))}`, - }); - } - if ((prev.domains || []).includes(d)) { - overlaps.push({ kind: "domain", value: d, by: "точный домен" }); - } - } - - // Суффиксы покрываются более общим суффиксом prev - for (const s of cur.domainSuffixes || []) { - if ( - (prev.domainSuffixes || []).some( - (ps) => hostMatchesSuffix(s, ps) && ps !== s, - ) - ) { - overlaps.push({ - kind: "suffix", - value: s, - by: "более общий суффикс", - }); - } - } - - // CIDR - for (const c of cur.ipCidrs || []) { - if ((prev.ipCidrs || []).includes(c)) { - overlaps.push({ kind: "cidr", value: c, by: "тот же CIDR" }); - } - } - - if (overlaps.length) { - conflicts.push({ - ruleId: cur.id, - ruleIndex: i, - ruleName: cur.name, - conflictWithId: prev.id, - conflictWithIndex: j, - conflictWithName: prev.name, - severity: sameOutbound ? "info" : "warning", - overlaps, - }); - } - } - } - - return conflicts; -} diff --git a/src/server/singbox.js b/src/server/singbox.js index d59448d..324d666 100644 --- a/src/server/singbox.js +++ b/src/server/singbox.js @@ -1,352 +1,71 @@ -import fs from "node:fs"; -import path from "node:path"; -import { settings } from "./config.js"; -import { - MIXED_INBOUND, - TPROXY_INBOUND, - normalizeCidr, - readDeviceProfiles, -} from "./devices.js"; -import { readClientSettings } from "./clientSettings.js"; +import fs from 'node:fs'; +import path from 'node:path'; +import { settings } from './config.js'; -const PROXY_TYPES = new Set([ - "vless", - "vmess", - "trojan", - "shadowsocks", - "hysteria2", -]); -const CUSTOM_OUTBOUNDS = new Set(["direct", "vpn", "block"]); - -function clone(value) { - return JSON.parse(JSON.stringify(value)); -} +const PROXY_TYPES = new Set(['vless', 'vmess', 'trojan', 'shadowsocks', 'hysteria2']); +const MIXED_INBOUND = 'mixed-in'; +const TPROXY_INBOUND = 'tproxy-in'; function findOutbound(subscriptionConfig, selectedTag) { const outbounds = Array.isArray(subscriptionConfig?.outbounds) ? subscriptionConfig.outbounds : []; - const exact = outbounds.find( - (outbound) => - outbound.tag === selectedTag && PROXY_TYPES.has(outbound.type), - ); - if (exact) return exact; - - const trimmedTag = String(selectedTag || "").trim(); - return outbounds.find( - (outbound) => - String(outbound.tag || "").trim() === trimmedTag && - PROXY_TYPES.has(outbound.type), - ); + const tag = String(selectedTag || '').trim(); + return outbounds.find((outbound) => ( + String(outbound.tag || '').trim() === tag && PROXY_TYPES.has(outbound.type) + )); } -function readCustomRuleSets() { - try { - if (!fs.existsSync(settings.customRuleSetsPath)) return []; - const data = JSON.parse( - fs.readFileSync(settings.customRuleSetsPath, "utf8"), - ); - return Array.isArray(data) ? data : []; - } catch { - return []; - } -} - -function ruleSetDownloadDetour(vpnTag) { - const detour = String(settings.ruleSetDownloadDetour || "vpn").trim(); - if (!detour || detour === "vpn") return vpnTag; - return detour; -} - -function ruleSets(customRuleSets = [], vpnTag = "direct") { - const downloadDetour = ruleSetDownloadDetour(vpnTag); - const builtIn = settings.routingRuDirect - ? [ - { - type: "remote", - tag: "geoip-ru", - format: "binary", - url: "https://cdn.jsdelivr.net/gh/SagerNet/sing-geoip@rule-set/geoip-ru.srs", - download_detour: downloadDetour, - }, - { - type: "remote", - tag: "geosite-category-ru", - format: "binary", - url: "https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-category-ru.srs", - download_detour: downloadDetour, - }, - ] - : []; - - const custom = (Array.isArray(customRuleSets) ? customRuleSets : []) - .filter((rs) => rs.tag && rs.url) - .map((rs) => ({ - type: "remote", - tag: String(rs.tag).trim(), - format: rs.format || "binary", - url: String(rs.url).trim(), - download_detour: downloadDetour, - })); - - // Пользовательские rule-sets не должны дублировать встроенные - const builtInTags = new Set(builtIn.map((rs) => rs.tag)); - const merged = [ - ...builtIn, - ...custom.filter((rs) => !builtInTags.has(rs.tag)), - ]; - return merged; -} - -function uniqueClean(values) { - return Array.from( - new Set( - (Array.isArray(values) ? values : []) - .map((value) => String(value || "").trim()) - .filter(Boolean), - ), - ); -} - -function parsePorts(values) { - return uniqueClean(values) - .map((value) => Number.parseInt(value, 10)) - .filter((value) => Number.isInteger(value) && value > 0 && value <= 65535); -} - -function toSingboxRule(customRule, vpnTag, baseRule = {}) { - if (!customRule?.enabled) return null; - if (!CUSTOM_OUTBOUNDS.has(customRule.outbound)) return null; - - const rule = { ...baseRule }; - const domains = uniqueClean(customRule.domains); - const domainSuffixes = uniqueClean(customRule.domainSuffixes); - const domainKeywords = uniqueClean(customRule.domainKeywords); - const ipCidrs = uniqueClean(customRule.ipCidrs); - const ports = parsePorts(customRule.ports); - const networks = uniqueClean(customRule.networks).filter((network) => - ["tcp", "udp"].includes(network), - ); - - if (domains.length) rule.domain = domains; - if (domainSuffixes.length) rule.domain_suffix = domainSuffixes; - if (domainKeywords.length) rule.domain_keyword = domainKeywords; - if (ipCidrs.length) rule.ip_cidr = ipCidrs; - if (ports.length) rule.port = ports; - if (networks.length) rule.network = networks; - - const ruleSetsRef = uniqueClean(customRule.ruleSets); - if (ruleSetsRef.length) rule.rule_set = ruleSetsRef; - - if ( - !rule.domain && - !rule.domain_suffix && - !rule.domain_keyword && - !rule.ip_cidr && - !rule.port && - !rule.network && - !rule.rule_set - ) { - return null; +export function buildGatewayConfig(subscriptionConfig, selectedTag) { + const clientMode = settings.appMode === 'client'; + const vpnOutbound = structuredClone(findOutbound(subscriptionConfig, selectedTag)); + if (!vpnOutbound) throw new Error(`Outbound не найден: ${selectedTag}`); + if (!vpnOutbound.tag) vpnOutbound.tag = 'vpn-out'; + if (vpnOutbound.type === 'vless' && !vpnOutbound.packet_encoding) { + vpnOutbound.packet_encoding = 'xudp'; } - rule.outbound = customRule.outbound === "vpn" ? vpnTag : customRule.outbound; - return rule; -} - -function customRouteRules(customRules, vpnTag, baseRule = {}) { - return (Array.isArray(customRules) ? customRules : []) - .map((rule) => toSingboxRule(rule, vpnTag, baseRule)) - .filter(Boolean); -} - -// ─── Device rules (маршрутизация по source IP) ────────────────────────────── - -function modeOutbound(mode, vpnTag) { - if (mode === "vpn") return vpnTag; - if (mode === "direct" || mode === "block") return mode; - return null; -} - -function deviceDefaultRouteRule(device, vpnTag) { - if (!device?.enabled) return null; - const outbound = modeOutbound(device.mode, vpnTag); - if (!outbound) return null; - - const cidr = normalizeCidr(device.ip); - if (!cidr) return null; - - return { - inbound: [TPROXY_INBOUND], - source_ip_cidr: [cidr], - outbound, - }; -} - -function deviceDefaultRouteRules(devices, vpnTag) { - return (Array.isArray(devices) ? devices : []) - .map((device) => deviceDefaultRouteRule(device, vpnTag)) - .filter(Boolean); -} - -function inboundDefaultRule(inbound, mode, vpnTag) { - const outbound = modeOutbound(mode, vpnTag); - if (!outbound) return null; - return { inbound: [inbound], outbound }; -} - -function ruDirectRule() { - if (!settings.routingRuDirect) return null; - return { - rule_set: ["geoip-ru", "geosite-category-ru"], - outbound: "direct", - }; -} - -function routeRules(customRules, vpnTag, { includeTransparent = true } = {}) { - const deviceProfiles = readDeviceProfiles(); - const rules = [ - { - ip_is_private: true, - outbound: "direct", - }, - ]; - - // Global rules apply to every inbound before contextual fallbacks. - rules.push(...customRouteRules(customRules, vpnTag)); - - const ruRule = ruDirectRule(); - if (ruRule) rules.push(ruRule); - - if (includeTransparent) { - // Device defaults are only transparent-gateway fallbacks after global rules. - rules.push(...deviceDefaultRouteRules(deviceProfiles.devices, vpnTag)); - } - - const proxyFallback = inboundDefaultRule( - MIXED_INBOUND, - deviceProfiles.proxyDefaultMode, - vpnTag, - ); - if (proxyFallback) rules.push(proxyFallback); - - if (includeTransparent) { - const transparentFallback = inboundDefaultRule( - TPROXY_INBOUND, - deviceProfiles.defaultTransparentMode, - vpnTag, - ); - if (transparentFallback) rules.push(transparentFallback); - } - - return rules; -} - -function sharedProxyOutbound(sharedProxy) { - if (!sharedProxy?.host || !sharedProxy?.port) return null; - if (sharedProxy.protocol === "http") { - return { - type: "http", - tag: "shared-proxy", - server: sharedProxy.host, - server_port: sharedProxy.port, - }; - } - return { - type: "socks", - tag: "shared-proxy", - server: sharedProxy.host, - server_port: sharedProxy.port, - version: "5", - }; -} - -export function buildGatewayConfig( - subscriptionConfig, - selectedTag, - { bypassAll = false } = {}, -) { - const customRuleSets = readCustomRuleSets(); - const clientMode = settings.appMode === "client"; - const clientSettings = clientMode ? readClientSettings() : null; - const sharedOutbound = - clientMode && clientSettings?.sharedProxyEnabled - ? sharedProxyOutbound(clientSettings.sharedProxy) - : null; - const directOnlyClient = clientMode && clientSettings?.homeBypassEnabled; - const selectedOutbound = sharedOutbound - ? null - : findOutbound(subscriptionConfig, selectedTag); - if (!sharedOutbound && !directOnlyClient && !selectedOutbound) { - throw new Error(`Outbound не найден: ${selectedTag}`); - } - - const vpnOutbound = selectedOutbound ? clone(selectedOutbound) : null; - if (vpnOutbound && !vpnOutbound.tag) vpnOutbound.tag = "vpn-out"; - if (vpnOutbound?.type === "vless" && !vpnOutbound.packet_encoding) { - vpnOutbound.packet_encoding = "xudp"; - } - - const clientOutbound = sharedOutbound - ? sharedOutbound.tag - : clientSettings?.homeBypassEnabled - ? "direct" - : vpnOutbound.tag; - const mixedProxyPort = clientSettings?.proxyPort || settings.proxyPort; - const proxyOnlyRules = [{ inbound: [MIXED_INBOUND], outbound: clientOutbound }]; const inbounds = [ - ...(clientMode - ? [] - : [ - { - type: "tproxy", - tag: "tproxy-in", - listen: "::", - listen_port: settings.tproxyPort, - sniff: true, - sniff_override_destination: true, - }, - ]), + ...(!clientMode ? [{ + type: 'tproxy', + tag: TPROXY_INBOUND, + listen: '::', + listen_port: settings.tproxyPort, + sniff: true, + sniff_override_destination: true, + }] : []), { - type: "mixed", - tag: "mixed-in", + type: 'mixed', + tag: MIXED_INBOUND, listen: settings.bindIp, - listen_port: mixedProxyPort, + listen_port: settings.proxyPort, sniff: true, set_system_proxy: false, }, ]; + const rules = clientMode + ? [{ inbound: [MIXED_INBOUND], outbound: vpnOutbound.tag }] + : [ + { inbound: [TPROXY_INBOUND], outbound: vpnOutbound.tag }, + { inbound: [MIXED_INBOUND], outbound: vpnOutbound.tag }, + ]; return { - log: { - level: settings.logLevel, - timestamp: true, - }, + log: { level: settings.logLevel, timestamp: true }, experimental: { - cache_file: { - enabled: true, - path: settings.cachePath, - }, - }, - dns: { - independent_cache: true, + cache_file: { enabled: true, path: settings.cachePath }, }, + dns: { independent_cache: true }, inbounds, outbounds: [ - ...(sharedOutbound ? [sharedOutbound] : vpnOutbound ? [vpnOutbound] : []), - { type: "direct", tag: "direct" }, - { type: "block", tag: "block" }, + vpnOutbound, + { type: 'direct', tag: 'direct' }, + { type: 'block', tag: 'block' }, ], route: { - rule_set: bypassAll || clientMode ? [] : ruleSets(customRuleSets, vpnOutbound.tag), - rules: bypassAll - ? [{ ip_is_private: true, outbound: "direct" }] - : clientMode - ? proxyOnlyRules - : routeRules(subscriptionConfig.customRules, vpnOutbound.tag, { - includeTransparent: !clientMode, - }), - final: "direct", + rule_set: [], + rules, + final: vpnOutbound.tag, ...(clientMode ? {} : { auto_detect_interface: true }), }, }; @@ -354,24 +73,9 @@ export function buildGatewayConfig( export function writeSingboxConfig(config) { fs.mkdirSync(path.dirname(settings.configPath), { recursive: true }); - fs.writeFileSync( - settings.configPath, - JSON.stringify(config, null, 2), - "utf8", - ); -} - -export function readSingboxConfig() { - if (!fs.existsSync(settings.configPath)) return null; - try { - return JSON.parse(fs.readFileSync(settings.configPath, "utf8")); - } catch { - return null; - } + fs.writeFileSync(settings.configPath, JSON.stringify(config, null, 2), 'utf8'); } export function removeSingboxConfig() { - if (fs.existsSync(settings.configPath)) { - fs.rmSync(settings.configPath); - } + fs.rmSync(settings.configPath, { force: true }); } diff --git a/src/server/tproxySourceBypass.js b/src/server/tproxySourceBypass.js deleted file mode 100644 index 0825402..0000000 --- a/src/server/tproxySourceBypass.js +++ /dev/null @@ -1,124 +0,0 @@ -import { spawnSync } from "node:child_process"; -import { settings } from "./config.js"; -import { deviceCidrs, normalizeCidr } from "./devices.js"; - -const DEFAULT_NAT_BYPASS_CIDRS = - "0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 224.0.0.0/4 240.0.0.0/4"; - -function splitCidrs(value) { - return String(value || "") - .split(/[\s,]+/) - .map((item) => normalizeCidr(item)) - .filter(Boolean); -} - -function unique(list) { - return [...new Set(list)]; -} - -export function sourceBypassCidrs( - profiles, - envCidrs = process.env.TPROXY_BYPASS_SOURCE_CIDRS || "", -) { - return unique([ - ...splitCidrs(envCidrs), - ...deviceCidrs(profiles?.devices || [], "bypass"), - ]); -} - -export function buildSourceBypassIptablesCommands( - cidrs, - { - chain = settings.tproxySourceBypassChain, - forwardChain = settings.tproxySourceForwardChain, - natChain = settings.tproxySourceNatChain, - natBypassCidrs = splitCidrs( - process.env.BYPASS_CIDRS || DEFAULT_NAT_BYPASS_CIDRS, - ), - } = {}, -) { - return [ - ["-w", "-t", "mangle", "-F", chain], - ["-w", "-F", forwardChain], - ["-w", "-t", "nat", "-F", natChain], - ...cidrs.map((cidr) => [ - "-w", - "-t", - "mangle", - "-A", - chain, - "-s", - cidr, - "-j", - "ACCEPT", - ]), - ...cidrs.flatMap((cidr) => [ - ["-w", "-A", forwardChain, "-s", cidr, "-j", "ACCEPT"], - [ - "-w", - "-A", - forwardChain, - "-d", - cidr, - "-m", - "conntrack", - "--ctstate", - "RELATED,ESTABLISHED", - "-j", - "ACCEPT", - ], - ]), - ...natBypassCidrs.map((cidr) => [ - "-w", - "-t", - "nat", - "-A", - natChain, - "-d", - cidr, - "-j", - "RETURN", - ]), - ...cidrs.map((cidr) => [ - "-w", - "-t", - "nat", - "-A", - natChain, - "-s", - cidr, - "-j", - "MASQUERADE", - ]), - ]; -} - -export function syncTproxySourceBypass(profiles, options = {}) { - if (settings.appMode !== "gateway") { - return { success: true, skipped: true, cidrs: [] }; - } - - const cidrs = sourceBypassCidrs( - profiles, - options.envCidrs ?? process.env.TPROXY_BYPASS_SOURCE_CIDRS, - ); - const commands = buildSourceBypassIptablesCommands(cidrs, options); - - for (const args of commands) { - const result = spawnSync("iptables", args, { - encoding: "utf8", - timeout: 1000, - }); - if (result.error || result.status !== 0) { - return { - success: false, - cidrs, - error: - result.error?.message || - (result.stderr || result.stdout || "iptables command failed").trim(), - }; - } - } - - return { success: true, cidrs }; -} diff --git a/src/web/App.jsx b/src/web/App.jsx index a8d2ee3..133df13 100644 --- a/src/web/App.jsx +++ b/src/web/App.jsx @@ -1,85 +1,22 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { createRoot } from 'react-dom/client'; import './styles.css'; import { api } from './api.js'; -import { Topbar } from './components/Topbar.jsx'; -import { Sidebar } from './components/Sidebar.jsx'; -import { StatusPane } from './components/StatusPane.jsx'; -import { OverviewPage } from './components/OverviewPage.jsx'; import { ClientOverviewPage } from './components/ClientOverviewPage.jsx'; -import { ServersPage } from './components/ServersPage.jsx'; -import { RoutingPage } from './components/RoutingPage.jsx'; -import { LogsPage } from './components/LogsPage.jsx'; -import { SettingsPage } from './components/SettingsPage.jsx'; -import { ConfigViewer } from './components/ConfigViewer.jsx'; -import { Toasts } from './components/Toasts.jsx'; - -const ROLLBACK_WINDOW_MS = 12_000; - -function getInitialPage() { - const hash = window.location.hash.replace('#/', '').replace('#', ''); - const valid = ['overview', 'servers', 'routing', 'logs', 'settings']; - return valid.includes(hash) ? hash : 'overview'; -} function App() { - const [page, setPage] = useState(getInitialPage()); const [state, setState] = useState(null); const [subscriptionUrl, setSubscriptionUrl] = useState(''); const [servers, setServers] = useState([]); - const [customRules, setCustomRules] = useState([]); - const [devicesConfig, setDevicesConfig] = useState({ - defaultTransparentMode: 'vpn', - proxyDefaultMode: 'vpn', - devices: [], - }); - const [selectedTag, setSelectedTag] = useState(''); const [pendingTag, setPendingTag] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); - const [rulesSaveStatus, setRulesSaveStatus] = useState('saved'); - const [configOpen, setConfigOpen] = useState(false); - const [pings, setPings] = useState({}); - const [toasts, setToasts] = useState([]); - const [applyStatus, setApplyStatus] = useState('idle'); // idle | applying | error - const [rollbackOffer, setRollbackOffer] = useState(null); - - const rulesDirtyRef = useRef(false); - const rulesSaveTimerRef = useRef(null); - const rulesRevisionRef = useRef(0); - const rollbackTimerRef = useRef(null); - - function pushToast(toast) { - const id = `t-${Date.now()}-${Math.random()}`; - setToasts((prev) => [...prev, { id, ...toast }]); - } - function dismissToast(id) { - setToasts((prev) => prev.filter((t) => t.id !== id)); - } - - function navigate(p) { - setPage(p); - window.location.hash = `#/${p}`; - } - - useEffect(() => { - function onHash() { setPage(getInitialPage()); } - window.addEventListener('hashchange', onHash); - return () => window.removeEventListener('hashchange', onHash); - }, []); async function loadState() { const data = await api.state(); setState(data); setServers(data.servers || []); - if (!rulesDirtyRef.current) setCustomRules(data.customRules || []); - setDevicesConfig(data.devicesConfig || { - defaultTransparentMode: 'vpn', - proxyDefaultMode: 'vpn', - devices: data.devices || [], - }); - setSelectedTag((prev) => prev || data.selectedTag || ''); - setPendingTag((prev) => prev || data.selectedTag || ''); + setPendingTag((current) => current || data.selectedTag || ''); } useEffect(() => { @@ -88,496 +25,72 @@ function App() { return () => clearInterval(timer); }, []); - useEffect(() => { - if (state?.mode === 'client' && page !== 'overview') { - navigate('overview'); - } - }, [state?.mode, page]); - - useEffect(() => () => { - if (rulesSaveTimerRef.current) clearTimeout(rulesSaveTimerRef.current); - if (rollbackTimerRef.current) clearTimeout(rollbackTimerRef.current); - }, []); - - async function withBusy(label, fn, { quiet = false } = {}) { + async function run(action) { setBusy(true); setError(''); try { - const result = await fn(); - if (!quiet && label && state?.mode !== 'client') { - pushToast({ kind: 'success', title: label }); - } - return result; + await action(); + await loadState(); } catch (err) { setError(err.message); - pushToast({ kind: 'danger', title: 'Ошибка', message: err.message, duration: 6000 }); throw err; } finally { setBusy(false); } } - // === Subscription === async function fetchSubscription() { - return withBusy('Подписка обновлена', async () => { - const data = await api.subscription.fetch(subscriptionUrl || state?.subscriptionHost || ''); + return run(async () => { + const data = await api.subscription.fetch(subscriptionUrl); setServers(data.servers || []); - if (data.servers?.length) { - if (state?.mode === 'client') { - setSelectedTag(''); - setPendingTag(''); - } else { - const nextTag = data.servers.some((server) => server.tag === selectedTag) - ? selectedTag - : data.servers[0].tag; - setSelectedTag(nextTag); - setPendingTag(nextTag); - } - } - await loadState(); + setPendingTag(''); }); } async function refreshSubscriptionInfo() { const data = await api.subscription.refreshInfo(); - setState((prev) => prev ? { ...prev, userInfo: data.userInfo, fetchedAt: data.fetchedAt } : prev); + setState((current) => current ? { + ...current, + userInfo: data.userInfo, + fetchedAt: data.fetchedAt, + } : current); return data; } async function forgetSubscription() { - if (!confirm('Удалить подписку и остановить sing-box?')) return; - return withBusy('Подписка удалена', async () => { + if (!confirm('Удалить подписку и остановить VPN?')) return; + return run(async () => { await api.subscription.forget(); setSubscriptionUrl(''); setServers([]); - setSelectedTag(''); setPendingTag(''); - await loadState(); }); } - // === Apply with rollback offer === - async function applyServer(tag) { - const target = tag || selectedTag; - if (!target) return; - const previous = state?.selectedTag; - setApplyStatus('applying'); - try { - await withBusy('Сервер применён', async () => { - await api.apply(target); - await loadState(); - }); - setApplyStatus('idle'); - - if (state?.mode !== 'client' && previous && previous !== target) { - setRollbackOffer({ from: target, to: previous, expiresAt: Date.now() + ROLLBACK_WINDOW_MS }); - if (rollbackTimerRef.current) clearTimeout(rollbackTimerRef.current); - rollbackTimerRef.current = setTimeout(() => setRollbackOffer(null), ROLLBACK_WINDOW_MS); - } - } catch { - setApplyStatus('error'); - } - } - - async function rollback() { - if (rollbackTimerRef.current) clearTimeout(rollbackTimerRef.current); - setRollbackOffer(null); - return withBusy('Откат выполнен', async () => { - const data = await api.rollback(); - setSelectedTag(data.selectedTag); - setPendingTag(data.selectedTag); - await loadState(); - }); - } - - // === sing-box control === - async function stopSingbox(confirmFirst = true) { - if (confirmFirst && !confirm('Остановить sing-box? Трафик через шлюз перестанет ходить.')) return; - return withBusy('Остановлено', async () => { await api.singbox.stop(); await loadState(); }); - } - async function restartSingbox() { - return withBusy('Перезапущено', async () => { await api.singbox.restart(); await loadState(); }); - } - async function clearConfig() { - if (!confirm('Сбросить config sing-box и остановить процесс?')) return; - return withBusy('Config сброшен', async () => { - await api.singbox.clear(); - setSelectedTag(''); - setPendingTag(''); - await loadState(); - }); - } - - async function toggleBypass() { - const next = !state?.bypassMode; - return withBusy( - next ? 'Обход правил включён — весь трафик напрямую' : 'Обход правил отключён', - async () => { - await api.bypass(next); - await loadState(); - }, - ); - } - - async function flushDirectCache() { - return withBusy('Bypass-кэш сброшен', async () => { - await api.directCache.flush(); - await loadState(); - }); - } - - // === Devices === - async function saveDevicesConfig(nextConfig) { - try { - const data = await api.devices.save(nextConfig); - setDevicesConfig({ - defaultTransparentMode: data.defaultTransparentMode || data.defaultMode || 'vpn', - proxyDefaultMode: data.proxyDefaultMode || 'vpn', - devices: data.devices || [], - }); - setState((prev) => prev ? { - ...prev, - devicesUpdatedAt: data.devicesUpdatedAt, - sourceBypassCidrs: data.sourceBypassCidrs, - } : prev); - if (data.sourceBypassResult && data.sourceBypassResult.success === false) { - pushToast({ - kind: 'warning', - title: 'Bypass сохранён, но не применён', - message: data.sourceBypassResult.error, - duration: 7000, - }); - } - } catch (err) { - pushToast({ kind: 'danger', title: 'Не удалось сохранить устройства', message: err.message }); - } - } - - function addDevice() { - const nextConfig = { - ...devicesConfig, - devices: [ - ...devicesConfig.devices, - { id: `dev-${Date.now()}`, name: 'Новое устройство', enabled: true, ip: '', mac: '', mode: 'direct', lastSeen: null }, - ], - }; - setDevicesConfig(nextConfig); - saveDevicesConfig(nextConfig); - } - - function updateDevice(id, patch) { - const nextConfig = { - ...devicesConfig, - devices: devicesConfig.devices.map((d) => (d.id === id ? { ...d, ...patch } : d)), - }; - setDevicesConfig(nextConfig); - saveDevicesConfig(nextConfig); - } - - function removeDevice(id) { - const nextConfig = { - ...devicesConfig, - devices: devicesConfig.devices.filter((d) => d.id !== id), - }; - setDevicesConfig(nextConfig); - saveDevicesConfig(nextConfig); - } - - function updateDeviceDefaults(patch) { - const nextConfig = { ...devicesConfig, ...patch }; - setDevicesConfig(nextConfig); - saveDevicesConfig(nextConfig); - } - - // === Rules CRUD === - function emptyRule() { - return { - id: `rule-${Date.now()}`, - name: 'Новое правило', - enabled: true, - outbound: 'direct', - domains: [], domainSuffixes: [], domainKeywords: [], - ipCidrs: [], ports: [], networks: [], - }; - } - - function queueRulesSave(nextRules) { - rulesDirtyRef.current = true; - const revision = rulesRevisionRef.current + 1; - rulesRevisionRef.current = revision; - setRulesSaveStatus('pending'); - - if (rulesSaveTimerRef.current) clearTimeout(rulesSaveTimerRef.current); - rulesSaveTimerRef.current = setTimeout(() => saveRules(nextRules, { silent: true, revision }), 700); - } - - async function saveRules(nextRules = customRules, options = {}) { - const { silent = false, revision = rulesRevisionRef.current + 1 } = options; - setError(''); - setRulesSaveStatus('saving'); - try { - const data = await api.rules.save(nextRules); - if (rulesRevisionRef.current === revision) { - rulesDirtyRef.current = false; - setCustomRules(data.rules || []); - setRulesSaveStatus('saved'); - await loadState(); - if (!silent) pushToast({ kind: 'success', title: 'Правила сохранены' }); - } else { - setRulesSaveStatus('pending'); - } - } catch (err) { - setError(err.message); - setRulesSaveStatus('error'); - pushToast({ kind: 'danger', title: 'Не удалось сохранить', message: err.message }); - } - } - - function saveRulesNow() { - if (rulesSaveTimerRef.current) clearTimeout(rulesSaveTimerRef.current); - rulesDirtyRef.current = true; - const revision = rulesRevisionRef.current + 1; - rulesRevisionRef.current = revision; - saveRules(customRules, { silent: false, revision }); - } - - function updateRule(id, patch) { - setCustomRules((rules) => { - const next = rules.map((r) => (r.id === id ? { ...r, ...patch } : r)); - queueRulesSave(next); - return next; - }); - } - function addRule() { - setCustomRules((rules) => { - const next = [emptyRule(), ...rules]; - queueRulesSave(next); - return next; - }); - } - function addRuleFromTemplate(tpl) { - setCustomRules((rules) => { - const next = [tpl, ...rules]; - queueRulesSave(next); - return next; - }); - } - function removeRule(id) { - setCustomRules((rules) => { - const next = rules.filter((r) => r.id !== id); - queueRulesSave(next); - return next; - }); - } - function reorderRules(next) { - setCustomRules(next); - queueRulesSave(next); - } - - // === Computed === - const status = useMemo(() => { - if (applyStatus === 'applying') return 'applying'; - if (applyStatus === 'error') return 'error'; - if (state?.singboxRunning) return 'running'; - if (state?.configExists) return 'stopped'; - return 'no_config'; - }, [state, applyStatus]); - - const activeServer = useMemo( - () => servers.find((s) => s.tag === state?.selectedTag) || null, - [servers, state?.selectedTag], - ); - const isClientMode = state?.mode === 'client'; - - const dirtyRules = rulesSaveStatus === 'pending' || rulesSaveStatus === 'saving'; - const dirtyDevices = Boolean( - state?.devicesUpdatedAt && - (!state?.rulesAppliedAt || state.devicesUpdatedAt > state.rulesAppliedAt), - ); - const dirtyServer = pendingTag && pendingTag !== state?.selectedTag; - const dirtyRouting = dirtyRules || dirtyDevices; - const dirty = dirtyRouting || dirtyServer; - - const sidebarBadges = { - routing: dirtyRouting ? { kind: 'warn', text: '●' } : null, - servers: dirtyServer ? { kind: 'warn', text: '●' } : null, - settings: !state?.hasSubscription ? { kind: 'danger', text: '!' } : null, - }; - - // === Render === if (!state) return
VPN
; return ( -
- {!isClientMode && ( - - )} - -
- {!isClientMode && } - +
+
- {(page === 'overview' || isClientMode) && ( - isClientMode ? ( - stopSingbox(false)} - /> - ) : ( - setConfigOpen(true)} - onNav={navigate} - onBypassToggle={toggleBypass} - onFlushDirectCache={flushDirectCache} - /> - ) - )} - {page === 'servers' && !isClientMode && ( - - )} - {page === 'routing' && !isClientMode && ( - - )} - {page === 'logs' && !isClientMode && } - {page === 'settings' && !isClientMode && ( - setConfigOpen(true)} - onClearConfig={clearConfig} - pushToast={pushToast} - /> - )} - - {/* Sticky bar — для routing/servers */} - {(page === 'routing' && dirtyRouting) && ( -
-
- - - {rulesSaveStatus === 'saving' && 'Сохраняем…'} - {rulesSaveStatus === 'pending' && 'Есть несохранённые изменения'} - {rulesSaveStatus === 'saved' && dirtyDevices && 'Изменения устройств сохранены'} - {rulesSaveStatus === 'error' && 'Ошибка сохранения'} - - Конфиг sing-box нужно пересобрать и применить. -
-
- {rulesSaveStatus !== 'saved' && ( - - )} - {state?.selectedTag && ( - - )} -
-
- )} - - {(page === 'servers' && dirtyServer) && ( -
-
- - Сервер не применён - Выбран: {pendingTag} -
-
- - -
-
- )} -
- - {!isClientMode && ( - setConfigOpen(true)} + error={error} + subscriptionUrl={subscriptionUrl} + setSubscriptionUrl={setSubscriptionUrl} + servers={servers} + pendingTag={pendingTag} + setPendingTag={setPendingTag} + onFetchSubscription={fetchSubscription} + onRefreshSubscriptionInfo={refreshSubscriptionInfo} + onForgetSubscription={forgetSubscription} + onApply={(tag) => run(() => api.apply(tag))} + onRestart={() => run(api.singbox.restart)} + onStop={() => run(api.singbox.stop)} /> - )} +
- - setConfigOpen(false)} /> - - - {rollbackOffer && ( -
-
- -
- Сервер применён - Можно откатиться к «{rollbackOffer.to}» - -
- -
-
- )}
); } diff --git a/src/web/api.js b/src/web/api.js index 24cdd9e..bc6071e 100644 --- a/src/web/api.js +++ b/src/web/api.js @@ -2,113 +2,36 @@ async function request(url, options = {}) { const response = await fetch(url, { ...options, headers: { - "content-type": "application/json", + 'content-type': 'application/json', ...(options.headers || {}), }, }); const data = await response.json().catch(() => ({})); - if (!response.ok || (data && data.success === false)) { - throw new Error( - data?.error || `Запрос ${url} завершился ошибкой ${response.status}`, - ); + if (!response.ok || data?.success === false) { + throw new Error(data?.error || `Запрос ${url} завершился ошибкой ${response.status}`); } return data; } export const api = { - state: () => request("/api/state"), - config: () => request("/api/config"), - - rules: { - get: () => request("/api/rules"), - save: (rules) => - request("/api/rules", { method: "PUT", body: JSON.stringify({ rules }) }), - conflicts: () => request("/api/rules/conflicts"), - }, - - deviceRules: { - get: () => request("/api/device-rules"), - save: (deviceRules) => - request("/api/device-rules", { - method: "PUT", - body: JSON.stringify({ deviceRules }), - }), - }, - - devices: { - get: () => request("/api/devices"), - save: (devicesConfig) => - request("/api/devices", { - method: "PUT", - body: JSON.stringify(devicesConfig), - }), - }, - - ruleSets: { - get: () => request("/api/rule-sets"), - save: (ruleSets) => - request("/api/rule-sets", { - method: "PUT", - body: JSON.stringify({ ruleSets }), - }), - lookup: (tag, url) => - request("/api/rule-sets/lookup", { - method: "POST", - body: JSON.stringify({ tag, url }), - }), - sagernetCatalog: () => request("/api/rule-sets/sagernet-catalog"), - }, - + state: () => request('/api/state'), subscription: { - fetch: (url) => - request("/api/subscription/fetch", { - method: "POST", - body: JSON.stringify({ url }), - }), - refreshInfo: () => request("/api/subscription/refresh-info", { method: "POST" }), - forget: () => request("/api/subscription", { method: "DELETE" }), - }, - - apply: (selectedTag) => - request("/api/apply", { - method: "POST", - body: JSON.stringify({ selectedTag }), + fetch: (url) => request('/api/subscription/fetch', { + method: 'POST', + body: JSON.stringify({ url }), }), - rollback: () => request("/api/apply/rollback", { method: "POST" }), - + refreshInfo: () => request('/api/subscription/refresh-info', { method: 'POST' }), + forget: () => request('/api/subscription', { method: 'DELETE' }), + }, + apply: (selectedTag) => request('/api/apply', { + method: 'POST', + body: JSON.stringify({ selectedTag }), + }), singbox: { - stop: () => request("/api/singbox/stop", { method: "POST" }), - restart: () => request("/api/singbox/restart", { method: "POST" }), - clear: () => request("/api/singbox/clear", { method: "POST" }), + stop: () => request('/api/singbox/stop', { method: 'POST' }), + restart: () => request('/api/singbox/restart', { method: 'POST' }), }, - servers: { - ping: (host, port) => - request("/api/servers/ping", { - method: "POST", - body: JSON.stringify({ host, port }), - }), - pingAll: () => request("/api/servers/ping-all", { method: "POST" }), + pingAll: () => request('/api/servers/ping-all', { method: 'POST' }), }, - - bypass: (enabled) => - request("/api/bypass", { - method: "POST", - body: JSON.stringify({ enabled }), - }), - - directCache: { - get: () => request("/api/direct-cache"), - flush: () => request("/api/direct-cache", { method: "DELETE" }), - }, - - route: { - check: ({ host, ip, port, network, sourceIp, inbound }) => - request("/api/route/check", { - method: "POST", - body: JSON.stringify({ host, ip, port, network, sourceIp, inbound }), - }), - }, - - configValidate: () => request("/api/config/validate", { method: "POST" }), }; diff --git a/src/web/components/ChipsInput.jsx b/src/web/components/ChipsInput.jsx deleted file mode 100644 index ebad5aa..0000000 --- a/src/web/components/ChipsInput.jsx +++ /dev/null @@ -1,61 +0,0 @@ -import React, { useState } from 'react'; - -/** - * Chip input. Items separated by Enter, comma, или space (для CIDR/портов). - * Невалидные элементы помечаются красным. - */ -export function ChipsInput({ value = [], onChange, placeholder = '', validate, splitter = /[\s,]/ }) { - const [draft, setDraft] = useState(''); - - function commit(text) { - const parts = String(text).split(splitter).map((p) => p.trim()).filter(Boolean); - if (!parts.length) return; - const next = Array.from(new Set([...value, ...parts])); - onChange(next); - setDraft(''); - } - - function remove(item) { - onChange(value.filter((v) => v !== item)); - } - - function onKeyDown(e) { - if (e.key === 'Enter' || e.key === ',') { - e.preventDefault(); - if (draft.trim()) commit(draft); - } else if (e.key === 'Backspace' && !draft && value.length) { - onChange(value.slice(0, -1)); - } - } - - function onPaste(e) { - const text = e.clipboardData.getData('text'); - if (text && splitter.test(text)) { - e.preventDefault(); - commit(text); - } - } - - return ( -
e.currentTarget.querySelector('input')?.focus()}> - {value.map((item) => { - const invalid = validate ? !validate(item) : false; - return ( - - {item} - - - ); - })} - setDraft(e.target.value)} - onKeyDown={onKeyDown} - onPaste={onPaste} - onBlur={() => draft.trim() && commit(draft)} - placeholder={value.length ? '' : placeholder} - /> -
- ); -} diff --git a/src/web/components/ClientOverviewPage.jsx b/src/web/components/ClientOverviewPage.jsx index 4e9ba93..5c1a4bf 100644 --- a/src/web/components/ClientOverviewPage.jsx +++ b/src/web/components/ClientOverviewPage.jsx @@ -13,6 +13,7 @@ import { formatBytes } from '../utils/format.js'; export function ClientOverviewPage({ state, busy, + error, subscriptionUrl, setSubscriptionUrl, servers, @@ -25,6 +26,7 @@ export function ClientOverviewPage({ onRestart, onStop, }) { + const isGateway = state?.mode === 'gateway'; const connected = Boolean(state?.singboxRunning); const hasSubscription = Boolean(state?.hasSubscription); const selectedTag = pendingTag || state?.selectedTag || ''; @@ -41,7 +43,8 @@ export function ClientOverviewPage({ const subscriptionInputRef = useRef(null); const subscriptionRef = useRef(null); const serverKey = servers.map((server) => `${server.tag}:${server.server}:${server.server_port}`).join('|'); - const proxyUrls = localProxyUrls(state?.proxyPort); + const gatewayAddress = isGateway ? window.location.hostname : '127.0.0.1'; + const proxyUrls = localProxyUrls(state?.proxyPort, gatewayAddress); const usage = subscriptionUsage(state?.userInfo); const [displayedUsed, setDisplayedUsed] = useState(usage.used); const hasUsage = Boolean( @@ -152,7 +155,7 @@ export function ClientOverviewPage({ async function copyProxy(kind) { try { - await navigator.clipboard.writeText(proxyUrls[kind]); + await navigator.clipboard.writeText(kind === 'gateway' ? gatewayAddress : proxyUrls[kind]); setCopiedProxy(kind); setTimeout(() => setCopiedProxy(''), 800); } catch { @@ -191,7 +194,7 @@ export function ClientOverviewPage({ type="button" role="switch" aria-checked={connected} - aria-label={connected ? 'Выключить VPN' : 'Включить VPN'} + aria-label={connected ? `Выключить ${isGateway ? 'Gateway' : 'VPN'}` : `Включить ${isGateway ? 'Gateway' : 'VPN'}`} disabled={busy || (!connected && !canStart)} onClick={toggleConnection} > @@ -201,7 +204,9 @@ export function ClientOverviewPage({

- {connected ? 'VPN включён' : 'VPN выключен'} + {isGateway + ? connected ? 'Gateway включён' : 'Gateway выключен' + : connected ? 'VPN включён' : 'VPN выключен'}

{connected ? ( @@ -216,12 +221,28 @@ export function ClientOverviewPage({
-
- Адрес - - {proxyUrls.http.replace(/^https?:\/\//, '')} - -
+
+ {isGateway && ( +
+ Gateway + {gatewayAddress} + +
+ )} +
+ {isGateway ? 'Proxy' : 'Адрес'} + + {proxyUrls.http.replace(/^https?:\/\//, '')} + +
{[ ['socks5', 'SOCKS5'], ['http', 'HTTP'], @@ -237,11 +258,14 @@ export function ClientOverviewPage({ {copiedProxy === kind && Copied} ))} +
)} + {error &&

{error}

} +
{ - if (!open) return; - let cancelled = false; - setConfig(null); - setError(''); - api.config() - .then((data) => { if (!cancelled) setConfig(data.config); }) - .catch((err) => { if (!cancelled) setError(err.message); }); - return () => { cancelled = true; }; - }, [open]); - - const text = useMemo(() => (config ? JSON.stringify(config, null, 2) : ''), [config]); - - const highlighted = useMemo(() => { - if (!search || !text) return text; - try { - const re = new RegExp(search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi'); - return text.split(re); - } catch { - return text; - } - }, [text, search]); - - if (!open) return null; - - function copy() { navigator.clipboard?.writeText(text).catch(() => {}); } - function download() { - const blob = new Blob([text], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = 'sing-box-config.json'; - a.click(); - URL.revokeObjectURL(url); - } - - return ( -
-
e.stopPropagation()}> -
-
-

sing-box config

- Автогенерируемый, перезаписывается при apply -
-
- setSearch(e.target.value)} - style={{ width: 160 }} - /> - - - -
-
-
- {error &&
{error}
} - {!error && !config &&

Конфиг ещё не сгенерирован.

} - {config && ( -
-              {Array.isArray(highlighted)
-                ? highlighted.map((part, i) => (
-                    
-                      {part}
-                      {i < highlighted.length - 1 && {search}}
-                    
-                  ))
-                : text}
-            
- )} -
-
-
- ); -} diff --git a/src/web/components/LogsPage.jsx b/src/web/components/LogsPage.jsx deleted file mode 100644 index f0fa3bb..0000000 --- a/src/web/components/LogsPage.jsx +++ /dev/null @@ -1,337 +0,0 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; -import { formatTime } from '../utils/format.js'; - -const MAX_ENTRIES = 800; -const MAX_TRAFFIC = 500; -const GROUP_WINDOW_MS = 30_000; - -function normalizeLine(line) { - return String(line || '').replace(/\x1b\[\d+m/g, '').trim(); -} - -function groupEntries(entries) { - const out = []; - for (const e of entries) { - const key = `${e.level}|${normalizeLine(e.line)}`; - const last = out[out.length - 1]; - const ts = new Date(e.ts).getTime(); - if (last && last._key === key && ts - last._lastTs < GROUP_WINDOW_MS) { - last.count += 1; - last._lastTs = ts; - last.lastTs = e.ts; - } else { - out.push({ ...e, _key: key, _lastTs: ts, count: 1, lastTs: e.ts }); - } - } - return out; -} - -const CATEGORY_BADGE = { - direct: { cls: 'success', label: 'direct' }, - vpn: { cls: 'info', label: 'VPN' }, - block: { cls: 'danger', label: 'block' }, - other: { cls: '', label: 'other' }, -}; - -function getDeviceName(sourceIp, devices) { - if (!sourceIp || !devices?.length) return null; - for (const d of devices) { - if (d.enabled === false) continue; - const ip = d.ip || d.sourceIp || (d.sourceIps || [])[0]; - const plain = ip?.endsWith('/32') ? ip.slice(0, -3) : ip; - if (plain === sourceIp) return d.name; - } - return null; -} - -function groupTraffic(list, sortBy = 'time') { - const map = new Map(); - for (const e of list) { - const key = `${e.sourceIp || ''}|${e.category}|${e.host}|${e.port}|${e.matchedRule || ''}`; - const ts = new Date(e.ts).getTime(); - if (map.has(key)) { - const g = map.get(key); - g.count++; - g._lastTs = ts; - g.lastTs = e.ts; - } else { - map.set(key, { ...e, _key: key, _lastTs: ts, count: 1, lastTs: e.ts }); - } - } - const arr = Array.from(map.values()); - if (sortBy === 'count') return arr.sort((a, b) => b.count - a.count || b._lastTs - a._lastTs); - return arr.sort((a, b) => b._lastTs - a._lastTs); -} - -function TrafficTab({ devices = [] }) { - const [traffic, setTraffic] = useState([]); - const [paused, setPaused] = useState(false); - const [filter, setFilter] = useState('all'); // all | direct | vpn | block - const [search, setSearch] = useState(''); - const [grouped, setGrouped] = useState(true); - const [sortBy, setSortBy] = useState('count'); // time | count - const [autoscroll, setAutoscroll] = useState(true); - const containerRef = useRef(null); - const pausedRef = useRef(false); - - useEffect(() => { pausedRef.current = paused; }, [paused]); - - useEffect(() => { - const source = new EventSource('/api/traffic/stream'); - source.onmessage = (ev) => { - if (pausedRef.current) return; - try { - const entry = JSON.parse(ev.data); - setTraffic((prev) => { - const next = [...prev, entry]; - if (next.length > MAX_TRAFFIC) next.splice(0, next.length - MAX_TRAFFIC); - return next; - }); - } catch {} - }; - return () => source.close(); - }, []); - - const filtered = useMemo(() => { - let list = traffic; - if (filter !== 'all') list = list.filter((e) => e.category === filter); - if (search) { - const s = search.toLowerCase(); - list = list.filter((e) => - e.host?.toLowerCase().includes(s) || - String(e.port || '').includes(s) || - e.outbound?.toLowerCase().includes(s) || - e.matchedRule?.toLowerCase().includes(s) || - e.sourceIp?.toLowerCase().includes(s) || - getDeviceName(e.sourceIp, devices)?.toLowerCase().includes(s), - ); - } - return grouped ? groupTraffic(list, sortBy) : list; - }, [traffic, filter, search, grouped, sortBy, devices]); - - useEffect(() => { - if (!autoscroll || !containerRef.current) return; - containerRef.current.scrollTop = containerRef.current.scrollHeight; - }, [filtered, autoscroll]); - - const counts = useMemo(() => { - const c = { direct: 0, vpn: 0, block: 0 }; - for (const e of traffic) if (e.category in c) c[e.category]++; - return c; - }, [traffic]); - - return ( -
-
- setSearch(e.target.value)} - style={{ flex: 1, minWidth: 180 }} - /> - - - {grouped && ( - - )} - - - -
- - {traffic.length === 0 ? ( -
- Ожидаем трафик… Убедитесь что sing-box запущен и уровень логов не выше INFO. -
- ) : ( -
- - - - - - - - - - - - - - {filtered.map((e, i) => { - const badge = CATEGORY_BADGE[e.category] || CATEGORY_BADGE.other; - const deviceName = getDeviceName(e.sourceIp, devices); - return ( - - - - - - - - - - ); - })} - -
ВремяТуннельУстройствоХост / IPПортПравило
{formatTime(e.ts)} - {badge.label} - - {deviceName - ? {deviceName} - : e.sourceIp - ? {e.sourceIp} - : } - {e.host || '—'}{e.port || '—'} - {e.matchedRule - ? {e.matchedRule} - : } - - {e.count > 1 && ×{e.count}} -
-
- )} -
- ); -} - -export function LogsPage({ devices = [] }) { - const [tab, setTab] = useState('traffic'); // traffic | logs - const [entries, setEntries] = useState([]); - const [paused, setPaused] = useState(false); - const [filter, setFilter] = useState('all'); - const [search, setSearch] = useState(''); - const [autoscroll, setAutoscroll] = useState(true); - const [grouped, setGrouped] = useState(true); - const containerRef = useRef(null); - const pausedRef = useRef(false); - - useEffect(() => { pausedRef.current = paused; }, [paused]); - - useEffect(() => { - const source = new EventSource('/api/logs/stream'); - source.onmessage = (event) => { - if (pausedRef.current) return; - try { - const entry = JSON.parse(event.data); - setEntries((prev) => { - const next = [...prev, entry]; - if (next.length > MAX_ENTRIES) next.splice(0, next.length - MAX_ENTRIES); - return next; - }); - } catch {} - }; - return () => source.close(); - }, []); - - const filtered = useMemo(() => { - let list = entries; - if (filter !== 'all') list = list.filter((e) => e.level === filter); - if (search) { - const s = search.toLowerCase(); - list = list.filter((e) => normalizeLine(e.line).toLowerCase().includes(s)); - } - return grouped ? groupEntries(list) : list; - }, [entries, filter, search, grouped]); - - useEffect(() => { - if (!autoscroll || !containerRef.current) return; - containerRef.current.scrollTop = containerRef.current.scrollHeight; - }, [filtered, autoscroll]); - - function copy(text) { - navigator.clipboard?.writeText(text).catch(() => {}); - } - - return ( -
-
-

Логи sing-box

-
- - -
-
- - {tab === 'traffic' && } - - {tab === 'logs' && ( - <> -
- setSearch(e.target.value)} - style={{ flex: 1, minWidth: 200 }} - /> - - - - - -
- -
- {filtered.length === 0 &&

Логов пока нет.

} - {filtered.map((entry, index) => { - const text = normalizeLine(entry.line); - if (grouped && entry.count > 1) { - return ( -
- {formatTime(entry.ts)} - - {entry.level} - - {text} - ×{entry.count} -
- ); - } - return ( -
copy(`${formatTime(entry.ts)} ${entry.level} ${text}`)} - title="Двойной клик — скопировать" - > - {formatTime(entry.ts)} - {entry.level} - {text} -
- ); - })} -
- - )} -
- ); -} diff --git a/src/web/components/OverviewPage.jsx b/src/web/components/OverviewPage.jsx deleted file mode 100644 index d57e9a7..0000000 --- a/src/web/components/OverviewPage.jsx +++ /dev/null @@ -1,192 +0,0 @@ -import React, { useEffect, useState } from 'react'; -import { formatRelative, formatBytes } from '../utils/format.js'; -import { flagFor } from '../utils/country.js'; -import { api } from '../api.js'; - -function StatusHero({ state, status }) { - const text = { - running: { title: '🟢 VPN-шлюз работает', kind: 'success' }, - applying: { title: '🟠 Применяем изменения…', kind: 'warning' }, - error: { title: '🔴 Ошибка', kind: 'danger' }, - stopped: { title: '⚫ Шлюз остановлен', kind: 'neutral' }, - no_config: { title: '⚪ Шлюз не настроен', kind: 'neutral' }, - }[status]; - - const userInfo = state?.userInfo; - const traffic = userInfo - ? `${formatBytes((userInfo.upload || 0) + (userInfo.download || 0))} / ${userInfo.total ? formatBytes(userInfo.total) : 'без лимита'}` - : 'нет данных'; - - return ( -
-
-
-

{text.title}

- - {state?.appliedAt ? `Последнее применение: ${formatRelative(state.appliedAt)}` : 'Конфиг ещё не применялся'} - -
- {state?.singboxRunning ? 'sing-box online' : 'sing-box offline'} -
- -
- -
-
- Активный сервер -
- {state?.selectedTag ? ( - <> - {flagFor({ tag: state.selectedTag })} {state.selectedTag} - - ) : Не выбран} -
-
-
- Трафик -
{traffic}
-
-
- Правил маршрутизации -
{(state?.customRules || []).filter(r => r.enabled).length} активных
-
-
-
- ); -} - -function QuickActions({ state, busy, onRestart, onStop, onShowConfig, onNav, onBypassToggle }) { - return ( -
-
-

Быстрые действия

-
-
- - - - - -
-
- ); -} - -function RecentEvents({ onNav }) { - const [entries, setEntries] = useState([]); - - useEffect(() => { - let cancelled = false; - fetch('/api/logs') - .then((r) => r.json()) - .then((data) => { - if (cancelled) return; - const list = (data.logs || []).slice(-15).reverse(); - setEntries(list); - }) - .catch(() => {}); - return () => { cancelled = true; }; - }, []); - - return ( -
-
-

Последние события

- -
- {entries.length === 0 ? ( - Пока ничего нет. - ) : ( -
- {entries.slice(0, 8).map((e, i) => { - const dot = e.level === 'error' ? 'danger' - : e.level === 'warning' ? 'warning' - : 'success'; - const time = new Date(e.ts).toLocaleTimeString('ru-RU', { hour12: false }); - return ( -
- - {time} - {e.line} -
- ); - })} -
- )} -
- ); -} - -function RoutingSummary({ state, onNav, onFlushDirectCache }) { - const rules = state?.customRules || []; - const enabled = rules.filter((r) => r.enabled).length; - const cacheCount = state?.directBypassCount || 0; - const cacheAvailable = state?.directBypassAvailable && state?.directBypassEnabled; - const transparentDefault = state?.devicesConfig?.defaultTransparentMode || 'vpn'; - const proxyDefault = state?.devicesConfig?.proxyDefaultMode || 'vpn'; - return ( -
-
-

Маршрутизация

- -
-
-
Private IP→ direct
- {state?.routingRuDirect && ( -
RU (geoip/geosite)→ direct
- )} -
Global custom правил{enabled} из {rules.length}
-
Transparent fallback→ {transparentDefault}
-
Proxy fallback→ {proxyDefault}
- {cacheAvailable && ( -
- Direct bypass cache - - {cacheCount} IP - - -
- )} -
-
- ); -} - -export function OverviewPage({ state, status, busy, onRestart, onStop, onShowConfig, onNav, onBypassToggle, onFlushDirectCache }) { - return ( -
- {state?.bypassMode && ( -
- ⚠ Режим обхода правил активен - — весь трафик идёт напрямую, VPN-правила не применяются. - -
- )} - -
- - -
- -
- ); -} diff --git a/src/web/components/RouteChecker.jsx b/src/web/components/RouteChecker.jsx deleted file mode 100644 index 06b5bed..0000000 --- a/src/web/components/RouteChecker.jsx +++ /dev/null @@ -1,93 +0,0 @@ -import React, { useState } from 'react'; -import { api } from '../api.js'; - -export function RouteChecker() { - const [host, setHost] = useState(''); - const [port, setPort] = useState('443'); - const [network, setNetwork] = useState('tcp'); - const [sourceIp, setSourceIp] = useState(''); - const [inbound, setInbound] = useState('tproxy-in'); - const [busy, setBusy] = useState(false); - const [result, setResult] = useState(null); - const [error, setError] = useState(''); - - async function check() { - setBusy(true); - setError(''); - setResult(null); - try { - const data = await api.route.check({ - host, - port: port || undefined, - network, - sourceIp: sourceIp || undefined, - inbound, - }); - setResult(data); - } catch (err) { - setError(err.message); - } finally { - setBusy(false); - } - } - - const r = result?.result; - const kind = r?.outbound?.startsWith('direct') ? 'success' - : r?.outbound === 'block' ? 'danger' - : r?.outbound?.includes('VPN') || r?.outbound?.includes('vpn') ? 'info' - : 'warning'; - - return ( -
-

Проверить маршрут

-
- setHost(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && check()} - style={{ minWidth: 220, flex: 1 }} - /> - setPort(e.target.value)} - style={{ width: 90 }} - /> - - setSourceIp(e.target.value)} - style={{ width: 145 }} - /> - - -
- - {error &&
{error}
} - - {r && ( -
-
- {r.ruleIndex >= 0 ? `Правило #${r.ruleIndex + 1}: ${r.ruleName}` : r.ruleName} - → {r.outbound} -
- {result.resolvedIp && result.resolvedFrom && ( - DNS: {result.resolvedFrom} → {result.resolvedIp} - )} - {r.reason} -
- )} -
- ); -} diff --git a/src/web/components/RoutingPage.jsx b/src/web/components/RoutingPage.jsx deleted file mode 100644 index dc19005..0000000 --- a/src/web/components/RoutingPage.jsx +++ /dev/null @@ -1,384 +0,0 @@ -import React, { useEffect, useMemo, useState } from 'react'; -import { - DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, -} from '@dnd-kit/core'; -import { - arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable, -} from '@dnd-kit/sortable'; -import { CSS } from '@dnd-kit/utilities'; -import { ruleTemplates } from '../templates/ruleTemplates.js'; -import { ruleErrors, hasErrors } from '../utils/validation.js'; -import { RuleEditorDrawer } from './RuleEditorDrawer.jsx'; -import { RouteChecker } from './RouteChecker.jsx'; -import { api } from '../api.js'; - -const OUTBOUND_KIND = { - direct: { kind: 'success', label: 'direct' }, - vpn: { kind: 'info', label: 'VPN' }, - block: { kind: 'danger', label: 'block' }, -}; - -const DEVICE_MODES = { - bypass: { kind: 'warning', label: 'bypass TProxy', hint: 'мимо sing-box; ручной proxy отдельно' }, - direct: { kind: 'success', label: 'direct', hint: 'fallback после global rules' }, - vpn: { kind: 'info', label: 'VPN', hint: 'fallback после global rules' }, - rules: { kind: 'neutral', label: 'default', hint: 'использует transparent default' }, - block: { kind: 'danger', label: 'block', hint: 'fallback после global rules' }, -}; - -function DeviceModeSelect({ value, onChange }) { - return ( - - ); -} - -function DevicesCard({ devicesConfig, onDefaultsChange, onAdd, onUpdate, onRemove }) { - const devices = devicesConfig?.devices || []; - const defaultTransparentMode = devicesConfig?.defaultTransparentMode || devicesConfig?.defaultMode || 'vpn'; - const proxyDefaultMode = devicesConfig?.proxyDefaultMode || 'vpn'; - - return ( -
-
-
-

Устройства

- bypass TProxy применяется до sing-box. Остальные режимы — fallback после global rules. -
-
- - - -
-
- {devices.length === 0 ? ( -
-

Нет профилей устройств. Неизвестные transparent-устройства используют transparent default.

-
- ) : ( -
- - - - - - - - - - - - - - {devices.map((dev) => { - const mode = DEVICE_MODES[dev.mode] || DEVICE_MODES.rules; - return ( - - - - - - - - - - ); - })} - -
НазваниеIPMACModeПоведение
- onUpdate(dev.id, { enabled: e.target.checked })} - style={{ accentColor: 'var(--accent)' }} - /> - - onUpdate(dev.id, { name: e.target.value })} - placeholder="Название устройства" - style={{ width: '100%', minWidth: 120 }} - /> - - onUpdate(dev.id, { ip: e.target.value })} - placeholder="192.168.1.50" - style={{ width: '100%', minWidth: 140 }} - /> - - onUpdate(dev.id, { mac: e.target.value })} - placeholder="опционально" - style={{ width: '100%', minWidth: 120 }} - /> - - onUpdate(dev.id, { mode })} /> - - {mode.label} - {mode.hint} - - -
-
- )} -
- ); -} - -function summary(rule) { - const parts = []; - const totalDomains = (rule.domains?.length || 0) + (rule.domainSuffixes?.length || 0) + (rule.domainKeywords?.length || 0); - if (totalDomains) parts.push(`${totalDomains} дом.`); - if (rule.ipCidrs?.length) parts.push(`${rule.ipCidrs.length} CIDR`); - if (rule.ports?.length) parts.push(`${rule.ports.length} портов`); - if (rule.networks?.length) parts.push(rule.networks.join('/')); - return parts.join(' · ') || '—'; -} - -function SortableRuleRow({ rule, index, total, onEdit, onUpdate, onRemove, conflict }) { - const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: rule.id }); - const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.5 : 1 }; - const errors = ruleErrors(rule); - const invalid = hasErrors(errors); - const ob = OUTBOUND_KIND[rule.outbound] || OUTBOUND_KIND.direct; - - return ( - - - - - #{index + 1} - -
- onUpdate(rule.id, { enabled: e.target.checked })} - style={{ accentColor: 'var(--accent)' }} - /> - - {invalid && ошибки} - {conflict && конфликт} -
- - {ob.label} - {summary(rule)} - -
- - -
- - - ); -} - -function TemplatesModal({ open, onClose, onAdd }) { - if (!open) return null; - return ( -
-
e.stopPropagation()}> -
-

Шаблоны маршрутизации

- -
-
-
- {ruleTemplates.map((tpl) => ( -
-

{tpl.label}

- {tpl.description} - -
- ))} -
-
-
-
- ); -} - -export function RoutingPage({ - rules, saveStatus, busy, - onAdd, onAddTemplate, onUpdate, onRemove, onSaveNow, onReorder, - devicesConfig, onUpdateDeviceDefaults, onAddDevice, onUpdateDevice, onRemoveDevice, -}) { - const [editingId, setEditingId] = useState(null); - const [showTemplates, setShowTemplates] = useState(false); - const [conflicts, setConflicts] = useState([]); - const [availableRuleSets, setAvailableRuleSets] = useState([]); - const sensors = useSensors( - useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), - useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), - ); - - useEffect(() => { - api.ruleSets.get().then((data) => setAvailableRuleSets(data.ruleSets || [])).catch(() => {}); - }, []); - - useEffect(() => { - let cancelled = false; - const t = setTimeout(() => { - api.rules.conflicts().then((data) => { if (!cancelled) setConflicts(data.conflicts || []); }).catch(() => {}); - }, 600); - return () => { cancelled = true; clearTimeout(t); }; - }, [rules]); - - const conflictsByRuleId = useMemo(() => { - const map = {}; - for (const c of conflicts) map[c.ruleId] = c; - return map; - }, [conflicts]); - - function handleDragEnd(event) { - const { active, over } = event; - if (!over || active.id === over.id) return; - const oldIndex = rules.findIndex((r) => r.id === active.id); - const newIndex = rules.findIndex((r) => r.id === over.id); - if (oldIndex < 0 || newIndex < 0) return; - onReorder(arrayMove(rules, oldIndex, newIndex)); - } - - const editing = rules.find((r) => r.id === editingId) || null; - - return ( -
- - - - -
-
-

Правила маршрутизации

-
- - -
-
- - {conflicts.length > 0 && ( -
- -
- {conflicts.length} конфликт(ов) обнаружено -
- {conflicts.slice(0, 3).map((c, i) => ( -
- #{c.ruleIndex + 1} «{c.ruleName}» перекрывается правилом #{c.conflictWithIndex + 1} «{c.conflictWithName}» -
- ))} -
-
-
- )} - - - Применяются сверху вниз. Перетаскивай ⠿ чтобы менять порядок. - - - {rules.length === 0 ? ( -
-

Правил пока нет

-

Добавь шаблон (например «League of Legends → direct») или создай пустое правило.

- -
- ) : ( -
- - - - - - - - - - - - - - r.id)} strategy={verticalListSortingStrategy}> - {rules.map((rule, i) => ( - - ))} - - - -
#ПравилоOutboundУсловия
-
- )} -
- - setEditingId(null)} - onRemove={onRemove} - availableRuleSets={availableRuleSets} - /> - setShowTemplates(false)} onAdd={onAddTemplate} /> -
- ); -} diff --git a/src/web/components/RuleEditorDrawer.jsx b/src/web/components/RuleEditorDrawer.jsx deleted file mode 100644 index fb3b52b..0000000 --- a/src/web/components/RuleEditorDrawer.jsx +++ /dev/null @@ -1,453 +0,0 @@ -import React, { useEffect, useMemo, useRef, useState } from 'react'; -import { ChipsInput } from './ChipsInput.jsx'; -import { isValidCidr, isValidPort, ruleErrors, hasErrors } from '../utils/validation.js'; -import { api } from '../api.js'; - -const DOMAIN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i; -const RULE_SET_TAG = /^[a-z0-9][a-z0-9_.@!-]*$/i; -const validDomain = (v) => DOMAIN.test(String(v).trim()); -const validRuleSetTag = (v) => RULE_SET_TAG.test(String(v).trim()); - -const RS_PAGE_SIZE = 100; -const RS_TYPE_LABELS = { domain: 'домен', suffix: 'суффикс', keyword: 'ключ', cidr: 'CIDR', regex: 'regex' }; - -function RuleSetBrowseModal({ tag, url, rule, onPatch, onClose }) { - const [status, setStatus] = useState('loading'); - const [data, setData] = useState(null); - const [error, setError] = useState(''); - const [search, setSearch] = useState(''); - const [typeFilter, setTypeFilter] = useState('all'); - const [page, setPage] = useState(0); - const inputRef = useRef(null); - - useEffect(() => { - api.ruleSets.lookup(tag, url) - .then((d) => { setData(d); setStatus('done'); }) - .catch((err) => { setError(err.message); setStatus('error'); }); - }, [tag, url]); - - useEffect(() => { - if (status === 'done') setTimeout(() => inputRef.current?.focus(), 50); - }, [status]); - - const filtered = useMemo(() => { - if (!data?.entries) return []; - const q = search.trim().toLowerCase(); - return data.entries.filter((e) => { - if (typeFilter !== 'all' && e.type !== typeFilter) return false; - if (!q) return true; - return e.value.toLowerCase().includes(q); - }); - }, [data, search, typeFilter]); - - function onSearchChange(v) { setSearch(v); setPage(0); } - function onTypeChange(v) { setTypeFilter(v); setPage(0); } - - function addEntry(entry) { - const val = entry.value; - switch (entry.type) { - case 'domain': { - const cur = new Set(rule.domains || []); - if (!cur.has(val)) onPatch({ domains: [...(rule.domains || []), val] }); - break; - } - case 'suffix': { - const cur = new Set(rule.domainSuffixes || []); - if (!cur.has(val)) onPatch({ domainSuffixes: [...(rule.domainSuffixes || []), val] }); - break; - } - case 'keyword': { - const cur = new Set(rule.domainKeywords || []); - if (!cur.has(val)) onPatch({ domainKeywords: [...(rule.domainKeywords || []), val] }); - break; - } - case 'cidr': { - const cur = new Set(rule.ipCidrs || []); - if (!cur.has(val)) onPatch({ ipCidrs: [...(rule.ipCidrs || []), val] }); - break; - } - default: break; - } - } - - const totalPages = Math.ceil(filtered.length / RS_PAGE_SIZE); - const pageItems = filtered.slice(page * RS_PAGE_SIZE, (page + 1) * RS_PAGE_SIZE); - - const addedValues = useMemo(() => new Set([ - ...(rule.domains || []), - ...(rule.domainSuffixes || []), - ...(rule.domainKeywords || []), - ...(rule.ipCidrs || []), - ]), [rule]); - - return ( -
-
e.stopPropagation()} - > -
-
-

Содержимое: {tag}

- Кликните запись чтобы добавить в правило -
- -
- - {status === 'loading' && ( -
- Скачивание и декомпиляция…
- Может занять 10–30 секунд -
- )} - {status === 'error' && ( -
-
{error}
-
- )} - - {status === 'done' && data && ( - <> -
- всего: {data.stats.total.toLocaleString()} - {data.stats.domain > 0 && доменов: {data.stats.domain.toLocaleString()}} - {data.stats.suffix > 0 && суффиксов: {data.stats.suffix.toLocaleString()}} - {data.stats.cidr > 0 && CIDR: {data.stats.cidr.toLocaleString()}} -
-
- onSearchChange(e.target.value)} - /> - -
-
- {filtered.length === 0 ? ( -
Ничего не найдено
- ) : ( - <> -
- {filtered.length.toLocaleString()} / {data.stats.total.toLocaleString()} - {totalPages > 1 && ` · стр. ${page + 1}/${totalPages}`} - — нажмите строку чтобы добавить в правило -
- - - - - - {pageItems.map((e, i) => { - const already = addedValues.has(e.value); - return ( - !already && addEntry(e)} - title={already ? 'Уже добавлено' : `Добавить в ${e.type === 'cidr' ? 'IP/CIDR' : e.type === 'suffix' ? 'суффиксы' : e.type === 'keyword' ? 'ключевые слова' : 'домены'}`} - > - - - - - ); - })} - -
ТипЗначение
{RS_TYPE_LABELS[e.type] || e.type}{e.value}{already ? '✓' : '+'}
- {totalPages > 1 && ( -
- - - {page + 1} / {totalPages} - - -
- )} - - )} -
- - )} -
-
- ); -} - -export function RuleEditor({ rule, onUpdate, onClose, onRemove, mode = 'builder', availableRuleSets = [] }) { - const [view, setView] = useState(mode); // builder | json - const [jsonDraft, setJsonDraft] = useState(() => JSON.stringify(rule, null, 2)); - const [jsonError, setJsonError] = useState(''); - const [browseTag, setBrowseTag] = useState(null); // { tag, url } | null - const errors = ruleErrors(rule); - - // Индекс URL по тегу из доступных rule-sets - const ruleSetUrlMap = useMemo(() => { - const map = {}; - for (const rs of availableRuleSets) map[rs.tag] = rs.url; - return map; - }, [availableRuleSets]); - - function patch(p) { - onUpdate(rule.id, p); - } - - function applyJson() { - try { - const parsed = JSON.parse(jsonDraft); - onUpdate(rule.id, { ...parsed, id: rule.id }); - setJsonError(''); - } catch (err) { - setJsonError(err.message); - } - } - - return ( -
-
- - -
- - {view === 'builder' ? ( - <> -
- Название - patch({ name: e.target.value })} /> -
- -
-
- Outbound - -
-
- Состояние - -
-
- -
- Rule-sets (geo-базы) - patch({ ruleSets: v })} - placeholder="geosite-runet" - validate={validRuleSetTag} - /> - {/* Кнопки просмотра содержимого для выбранных rule-sets */} - {(rule.ruleSets || []).length > 0 && ( -
- {(rule.ruleSets || []).map((tag) => { - const url = ruleSetUrlMap[tag]; - return url ? ( - - ) : null; - })} -
- )} - {availableRuleSets.length > 0 && ( -
- Доступны:{' '} - {availableRuleSets.map((rs) => ( - - - - - ))} -
- )} - {availableRuleSets.length === 0 && ( - - Настройте rule-sets в Настройках, затем вводите их теги здесь - - )} -
- -
- Домены (точное совпадение) - patch({ domains: v })} - placeholder="riotgames.com" - validate={validDomain} - /> - {errors.domains.length > 0 && Невалидно: {errors.domains.join(', ')}} -
- -
- Суффиксы доменов - patch({ domainSuffixes: v })} - placeholder="riotcdn.net" - validate={validDomain} - /> - {errors.domainSuffixes.length > 0 && Невалидно: {errors.domainSuffixes.join(', ')}} -
- -
- IP / CIDR - patch({ ipCidrs: v })} - placeholder="104.160.128.0/19" - validate={isValidCidr} - /> - {errors.ipCidrs.length > 0 && Невалидно: {errors.ipCidrs.join(', ')}} -
- -
- Порты (число или диапазон 5000-6000) - patch({ ports: v })} - placeholder="443" - validate={(p) => { - const s = String(p); - if (s.includes('-')) { - const [a, b] = s.split('-'); - return isValidPort(a) && isValidPort(b); - } - return isValidPort(p); - }} - /> - {errors.ports.length > 0 && Невалидно: {errors.ports.join(', ')}} -
- -
- Протоколы -
- - - Если ничего — оба -
-
- - ) : ( - <> -
- Сырой JSON правила -