Compare commits
17 Commits
codex-wind
...
9d4f312595
| Author | SHA1 | Date | |
|---|---|---|---|
| 9d4f312595 | |||
| e19d33adb9 | |||
| 99f7f58fcb | |||
| 6bc7840fb1 | |||
| d3b7f0d613 | |||
| efa46d1ee5 | |||
| 149bb999dc | |||
| 288acbf0c8 | |||
| b45dd2ae05 | |||
| c5bdb10445 | |||
| 7dbf786c56 | |||
| 59f2264a2e | |||
| a0f41baa36 | |||
| c3d3aaa699 | |||
| 301b76c03e | |||
| ab6de6996f | |||
| 0092ec4cde |
43
.codex/skills/design-vpn-client-ui/SKILL.md
Normal file
43
.codex/skills/design-vpn-client-ui/SKILL.md
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
---
|
||||||
|
name: design-vpn-client-ui
|
||||||
|
description: Design, implement, review, or refine the client-facing VPN interfaces in this repository using the established calm monospace visual language and smooth state-driven motion. Use for the current macOS client and future end-user gateway client screens, especially power controls, subscriptions, traffic usage, proxy copy controls, server selection, responsive layout, hover feedback, transitions, and animation polish. Do not use for the administrative gateway UI unless the user explicitly asks to apply the client visual language there.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Design VPN Client UI
|
||||||
|
|
||||||
|
Preserve the repo's focused one-screen VPN client language: a centered primary action, quiet technical typography, restrained green state color, and motion that feels slow, fluid, and deliberate without moving layout.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. Read `PRODUCT.md` and the complete client component and styles before editing.
|
||||||
|
2. Inspect the supplied screenshot or live UI. Trace the real DOM and state change that causes the visual issue.
|
||||||
|
3. Read [visual-language.md](references/visual-language.md) for layout, hierarchy, color, and typography work.
|
||||||
|
4. Read [motion-and-interaction.md](references/motion-and-interaction.md) for animation, hover, refresh, input, copy, or state-transition work.
|
||||||
|
5. Reuse existing React state, CSS variables, formatters, and API paths. Prefer a narrow CSS/markup change over a new abstraction or dependency.
|
||||||
|
6. Keep geometry stable across every state. Reserve space before animating content.
|
||||||
|
7. Implement `prefers-reduced-motion` alongside every new animation.
|
||||||
|
8. Run `npm test`, `npm run build`, and `git diff --check`. Visually inspect when a runnable client is available.
|
||||||
|
|
||||||
|
## Non-negotiable decisions
|
||||||
|
|
||||||
|
- Keep the power action on the screen's central vertical axis. Place subscription content to its right without shifting that axis.
|
||||||
|
- Keep the power hit target generous while rendering only the icon, never a large enclosing green circle.
|
||||||
|
- Use green only for active, selected, successful, or refreshed states. Keep inactive power gray, including hover.
|
||||||
|
- Never let labels, timers, feedback, icons, progress, or server rows shift neighboring content.
|
||||||
|
- Animate state, opacity, blur, glow, color, filter, and transform. Do not animate layout properties.
|
||||||
|
- Let visible cycles finish. Never stop a spinner mid-turn or remount a list before its exit animation completes.
|
||||||
|
- Prefer one clear value over unsupported detail. Hide subscription fields the provider does not supply.
|
||||||
|
- Keep client UI compact and calm. Do not introduce dashboard cards, decorative chrome, or admin-console density.
|
||||||
|
|
||||||
|
## Acceptance pass
|
||||||
|
|
||||||
|
Before handing off, verify:
|
||||||
|
|
||||||
|
- Power on/off is unmistakable without reading the label.
|
||||||
|
- Switching on/off preserves the exact positions of title, timer, and hint.
|
||||||
|
- Refresh and copy feedback cannot change element width or alignment.
|
||||||
|
- Server separators are compact and only slightly wider than their content.
|
||||||
|
- Repeated polling does not replay decorative list animations.
|
||||||
|
- Manual refresh has an obvious but non-jarring response.
|
||||||
|
- Keyboard focus remains visible even when the text caret is intentionally hidden.
|
||||||
|
- Narrow screens return to a simple single-column layout.
|
||||||
4
.codex/skills/design-vpn-client-ui/agents/openai.yaml
Normal file
4
.codex/skills/design-vpn-client-ui/agents/openai.yaml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
interface:
|
||||||
|
display_name: "Design VPN Client UI"
|
||||||
|
short_description: "Design the repo's calm animated VPN client UI."
|
||||||
|
default_prompt: "Use $design-vpn-client-ui to design or refine the VPN client interface in this repository."
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# Motion and interaction
|
||||||
|
|
||||||
|
## Motion character
|
||||||
|
|
||||||
|
Aim for fluid, slightly viscous motion: noticeable, calm, and complete. Avoid bounce, elastic easing, abrupt unmounts, decorative page choreography, or tiny effects too weak to communicate feedback.
|
||||||
|
|
||||||
|
Use exponential ease-out curves such as `cubic-bezier(0.16, 1, 0.3, 1)` for arrivals. Typical timing:
|
||||||
|
|
||||||
|
- hover and press: 180-300 ms;
|
||||||
|
- state color and glow: 600-900 ms;
|
||||||
|
- content reveal: 600-850 ms;
|
||||||
|
- numeric tween and progress: about 900 ms;
|
||||||
|
- copy feedback: about 800 ms;
|
||||||
|
- server cascade: 620-760 ms per row with 90-110 ms stagger.
|
||||||
|
|
||||||
|
## Power state
|
||||||
|
|
||||||
|
- Transition gray to green slowly when connecting and green to gray when disconnecting.
|
||||||
|
- Animate icon color, localized light, and SVG shadow together.
|
||||||
|
- Let the light expand and brighten on enable, then contract and fade on disable.
|
||||||
|
- Keep the hit target and all surrounding geometry fixed.
|
||||||
|
- Use a short press compression, followed by a slower release.
|
||||||
|
|
||||||
|
## Changing text and numbers
|
||||||
|
|
||||||
|
- Put alternate labels in fixed-size slots.
|
||||||
|
- Reveal connection title, timer, and hint with opacity plus light blur, never vertical layout movement.
|
||||||
|
- Do not reanimate the timer every second; animate only its initial appearance.
|
||||||
|
- Tween numeric traffic values from old to new with `requestAnimationFrame` or an equivalent stable counter.
|
||||||
|
- Animate progress width concurrently and add a brief glow that fully fades.
|
||||||
|
- Never translate changing numbers if the user asked for a fluid morph; use numerical interpolation, opacity, color, blur, and light.
|
||||||
|
|
||||||
|
## Refresh
|
||||||
|
|
||||||
|
- Use a clean, symmetric SVG refresh icon aligned in the same flex row as its label.
|
||||||
|
- Spin for at least one full cycle. If the request finishes mid-cycle, continue to the next cycle boundary before stopping.
|
||||||
|
- Update data immediately when it arrives; finishing the icon cycle must not delay the data.
|
||||||
|
- Manual refresh may replay meaningful data and server transitions.
|
||||||
|
- Background polling should update quietly and must not repeatedly replay the server cascade.
|
||||||
|
- On updated traffic, tween the number, advance the bar, and emit a visible but brief green flare.
|
||||||
|
|
||||||
|
## Server cascade
|
||||||
|
|
||||||
|
- On initial display, reveal rows from top to bottom with a small negative Y offset, opacity, and blur.
|
||||||
|
- On manual refresh, animate an explicit exit phase first. Fade rows top to bottom, then remount and enter top to bottom.
|
||||||
|
- Wait for the last exit delay and duration before starting entry.
|
||||||
|
- Disable pointer interaction during exit.
|
||||||
|
- Do not replay on ping updates or unrelated renders.
|
||||||
|
|
||||||
|
## Subscription input
|
||||||
|
|
||||||
|
- Show the public domain while retaining the full URL internally.
|
||||||
|
- Disable browser autocomplete suggestions and neutralize autofill backgrounds.
|
||||||
|
- Hide the blinking caret when the paste-first interaction does not need it, while preserving keyboard input and focus outline.
|
||||||
|
- When an existing subscription is being edited and the field is idle, use the green underline as a five-second timeout indicator: start bright, fade to quiet, then restore display mode.
|
||||||
|
- Pause the timeout once the user enters content.
|
||||||
|
- Close and clear unfinished input on outside click or Escape.
|
||||||
|
|
||||||
|
## First-run initialization
|
||||||
|
|
||||||
|
- With no subscription, show only the centered subscription input. Hide power, proxy controls, usage, and servers.
|
||||||
|
- After a valid subscription loads, keep the subscription and server list centered. Require an explicit server choice instead of silently selecting the first server.
|
||||||
|
- On server choice, slide the subscription column to the right while revealing the power column on the viewport's central axis.
|
||||||
|
- Preserve the chosen server on later visits, but return to first-run initialization after subscription deletion.
|
||||||
|
- Deleting a subscription must stop the VPN, clear its cached/configured state, and return the UI to the centered input without leaving stale controls visible.
|
||||||
|
|
||||||
|
## Copy feedback
|
||||||
|
|
||||||
|
- Keep protocol buttons fixed-size and centered.
|
||||||
|
- Copy the complete protocol URL while showing a shared address separately.
|
||||||
|
- Overlay green `Copied` feedback in the same fixed box; do not append text or move the label.
|
||||||
|
- Make feedback appear immediately, hold briefly, and fade fully before restoring the original label. Keep the whole cycle near 800 ms.
|
||||||
|
|
||||||
|
## Reduced motion
|
||||||
|
|
||||||
|
Under `prefers-reduced-motion: reduce`, remove transitions and keyframe animations while preserving final state, focus, color contrast, copy wording, and all functionality.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# Visual language
|
||||||
|
|
||||||
|
## Scene and character
|
||||||
|
|
||||||
|
Design for a macOS user glancing at a small VPN control surface in a quiet desktop environment. The UI should feel soft, precise, dependable, and slightly terminal-like, not like a network administration dashboard.
|
||||||
|
|
||||||
|
## Composition
|
||||||
|
|
||||||
|
- Make one primary action dominant: the VPN power icon.
|
||||||
|
- Keep the power control centered on the viewport's vertical axis, not merely centered inside a left column.
|
||||||
|
- Build the left flow vertically: power icon, stable connection copy, proxy address, copy actions.
|
||||||
|
- Place subscription identity, usage, expiry, and servers in a compact column to the right.
|
||||||
|
- Collapse to one centered column on narrow screens.
|
||||||
|
- Avoid cards and enclosing frames. Use spacing, type, thin rules, and state color for hierarchy.
|
||||||
|
- Keep server rows vertical and narrow. Underlines should be only slightly wider than the server label and ping.
|
||||||
|
|
||||||
|
## Geometry and alignment
|
||||||
|
|
||||||
|
- Reserve identical height for mutually exclusive content such as timer versus connection hint.
|
||||||
|
- Give copy buttons fixed width. Overlay temporary feedback instead of replacing text in normal flow.
|
||||||
|
- Align icons and labels in the same flex row. Do not position an icon by guessed absolute offsets.
|
||||||
|
- Preserve a generous invisible hit area around icon-only controls.
|
||||||
|
- Center proxy address and protocol actions with the power column.
|
||||||
|
- Treat one-pixel optical misalignment as a defect when controls sit beside uppercase labels.
|
||||||
|
|
||||||
|
## Typography
|
||||||
|
|
||||||
|
- Prefer the existing JetBrains Mono / SF Mono stack for the client surface.
|
||||||
|
- Use uppercase, tracked, muted micro-labels for metadata.
|
||||||
|
- Use stronger weight and size for the subscription domain and connection state.
|
||||||
|
- Use tabular numerals for timers and changing numeric data.
|
||||||
|
- Avoid display fonts, oversized headings, and mixed type families.
|
||||||
|
|
||||||
|
## Color and light
|
||||||
|
|
||||||
|
- Preserve green-tinted dark and light neutrals through the existing OKLCH variables.
|
||||||
|
- Inactive power stays neutral gray even on hover; active power becomes green.
|
||||||
|
- Use green for active VPN, selected server underline, progress, copy success, refresh success, and focus.
|
||||||
|
- Prefer localized `drop-shadow`, `text-shadow`, or a soft radial light layer over filled green containers.
|
||||||
|
- Let glow support state recognition. Do not leave every element glowing continuously.
|
||||||
|
|
||||||
|
## Data presentation
|
||||||
|
|
||||||
|
- Show subscription domain, not the credential-like full URL.
|
||||||
|
- Show used traffic and total limit as the primary statistic.
|
||||||
|
- Omit upload/download breakdown when provider support is absent or ambiguous.
|
||||||
|
- Show expiry as both date and remaining days, with correct Russian forms.
|
||||||
|
- If there is no total, say `без лимита` and omit the progress bar.
|
||||||
|
- Hide unavailable rows instead of showing empty placeholders or zeros that imply real measurements.
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
node_modules
|
node_modules
|
||||||
.vpn-proxy
|
.vpn-proxy
|
||||||
_archive
|
|
||||||
.git
|
.git
|
||||||
.gitea
|
.gitea
|
||||||
.github
|
.github
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
PORT=3456
|
PORT=3456
|
||||||
APP_MODE=gateway
|
APP_MODE=gateway
|
||||||
CLIENT_UI_PORT=3456
|
CLIENT_UI_PORT=3456
|
||||||
CLIENT_PROXY_PORT_START=8080
|
CLIENT_PROXY_PORT=8082
|
||||||
CLIENT_PROXY_PORT_END=8090
|
|
||||||
BASE_IMAGE=debian:bookworm-slim
|
BASE_IMAGE=debian:bookworm-slim
|
||||||
SINGBOX_VERSION=1.12.13
|
SINGBOX_VERSION=1.12.13
|
||||||
INSTALL_RUNTIME_DEPS=true
|
INSTALL_RUNTIME_DEPS=true
|
||||||
@@ -13,5 +12,4 @@ TPROXY_PORT=7895
|
|||||||
TPROXY_MARK=1
|
TPROXY_MARK=1
|
||||||
TPROXY_TABLE=100
|
TPROXY_TABLE=100
|
||||||
TPROXY_CHAIN=VPN_PROXY_TPROXY
|
TPROXY_CHAIN=VPN_PROXY_TPROXY
|
||||||
ROUTING_RU_DIRECT=true
|
|
||||||
LOG_LEVEL=info
|
LOG_LEVEL=info
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,12 +1,8 @@
|
|||||||
# Local archive with the previous implementation and runtime secrets
|
|
||||||
_archive/
|
|
||||||
|
|
||||||
# Runtime state
|
# Runtime state
|
||||||
.env
|
.env
|
||||||
*.env.local
|
*.env.local
|
||||||
data/
|
data/
|
||||||
.vpn-proxy/
|
.vpn-proxy/
|
||||||
.superpowers/
|
|
||||||
.worktrees/
|
.worktrees/
|
||||||
|
|
||||||
# Node/Vite
|
# Node/Vite
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ RUN chmod +x /entrypoint.client.sh \
|
|||||||
|
|
||||||
ENV APP_MODE=client \
|
ENV APP_MODE=client \
|
||||||
PORT=3456 \
|
PORT=3456 \
|
||||||
PROXY_PORT=8080 \
|
PROXY_PORT=8082 \
|
||||||
PROXY_BIND_IP=0.0.0.0 \
|
PROXY_BIND_IP=0.0.0.0 \
|
||||||
DATA_DIR=/var/lib/vpn-proxy \
|
DATA_DIR=/var/lib/vpn-proxy \
|
||||||
SING_BOX_CONFIG=/etc/sing-box/config.json \
|
SING_BOX_CONFIG=/etc/sing-box/config.json \
|
||||||
@@ -49,6 +49,6 @@ ENV APP_MODE=client \
|
|||||||
ROUTING_RU_DIRECT=true \
|
ROUTING_RU_DIRECT=true \
|
||||||
LOG_LEVEL=info
|
LOG_LEVEL=info
|
||||||
|
|
||||||
EXPOSE 3456 8080
|
EXPOSE 3456 8082
|
||||||
|
|
||||||
ENTRYPOINT ["dumb-init", "/entrypoint.client.sh"]
|
ENTRYPOINT ["dumb-init", "/entrypoint.client.sh"]
|
||||||
|
|||||||
35
PRODUCT.md
Normal file
35
PRODUCT.md
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
# Product
|
||||||
|
|
||||||
|
## Register
|
||||||
|
|
||||||
|
product
|
||||||
|
|
||||||
|
## Users
|
||||||
|
|
||||||
|
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 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
|
||||||
|
|
||||||
|
Soft, calm, precise. Familiar to macOS users, with sharper geometry and a quiet monospace character.
|
||||||
|
|
||||||
|
## Anti-references
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
- One screen, one primary action.
|
||||||
|
- Use plain language and hide implementation details.
|
||||||
|
- Make connection state unmistakable without relying on color alone.
|
||||||
|
- Prefer native controls and predictable macOS behavior.
|
||||||
|
- Show saved subscriptions as a domain, not as a credential-like URL.
|
||||||
|
- Make servers directly selectable instead of hiding them in a dropdown.
|
||||||
|
- Keep advanced and server-only features out of the client path.
|
||||||
|
|
||||||
|
## Accessibility & Inclusion
|
||||||
|
|
||||||
|
Support keyboard navigation, visible focus, sufficient contrast, system light and dark themes, and reduced motion preferences.
|
||||||
492
README.md
492
README.md
@@ -1,483 +1,43 @@
|
|||||||
# VPN Proxy
|
# 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
|
```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://<gateway-ip>:3456`.
|
||||||
|
|
||||||
- UI: `http://127.0.0.1:3456`
|
После подключения экран показывает:
|
||||||
- HTTP/SOCKS proxy: `127.0.0.1:8080` по умолчанию; в UI можно выбрать порт из Docker-диапазона `8080–8090`
|
|
||||||
|
|
||||||
Установщик интерактивно спросит proxy-порт. Если стандартный UI-порт `3456` занят другим контейнером, установщик попросит выбрать свободный UI-порт. Для неинтерактивного запуска можно задать порты заранее; тогда вопросы не появятся:
|
- `Gateway` — адрес, который можно назначить устройству как основной шлюз;
|
||||||
|
- `Proxy` — один адрес на порту `8080`, доступный как `HTTP` и `SOCKS5`.
|
||||||
|
|
||||||
|
Весь перехваченный публичный TCP/UDP и весь proxy-трафик идут через выбранный VPN. Приватные и локальные сети не перехватываются, чтобы сохранить доступ к Gateway и LAN.
|
||||||
|
|
||||||
|
Proxy по умолчанию разрешён только из приватных сетей. Диапазоны задаются через `PROXY_ALLOWED_CIDRS`.
|
||||||
|
|
||||||
|
## macOS client
|
||||||
|
|
||||||
```bash
|
```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
|
```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://<gateway-ui-host>: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:<proxy-port>` в режим 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: app proxy client
|
|
||||||
|
|
||||||
Windows mode restores the native workflow for Discord, Vesktop, games, and other apps that do not expose proxy settings.
|
|
||||||
|
|
||||||
Run PowerShell 7 as Administrator. While this branch is being tested, install from `codex-windows-client`:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
irm https://git.dokops.ru/dokril/vpn-proxy/raw/branch/codex-windows-client/scripts/install-windows-client.ps1 | iex
|
|
||||||
```
|
|
||||||
|
|
||||||
Installer modes:
|
|
||||||
|
|
||||||
- `Full install`: local native `sing-box.exe` on `127.0.0.1:1080` plus ProxiFyre/WinPacketFilter.
|
|
||||||
- `ProxiFyre only`: ProxiFyre/WinPacketFilter only, pointed at an existing SOCKS5 proxy such as `127.0.0.1:8080` or `192.168.50.111:8080`.
|
|
||||||
|
|
||||||
The installer keeps profile data under `C:\Tools\vpn-proxy-windows\data`, so rerunning it can replace app files without deleting saved profiles.
|
|
||||||
|
|
||||||
Local UI:
|
|
||||||
|
|
||||||
```text
|
|
||||||
http://127.0.0.1:3456
|
|
||||||
```
|
|
||||||
|
|
||||||
Recovery commands:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
& "C:\Tools\vpn-proxy-windows\app\scripts\windows\manage.ps1" -OpenUi
|
|
||||||
& "C:\Tools\vpn-proxy-windows\app\scripts\windows\manage.ps1" -Status
|
|
||||||
& "C:\Tools\vpn-proxy-windows\app\scripts\windows\manage.ps1" -RestartServices
|
|
||||||
```
|
|
||||||
|
|
||||||
The UI manages profiles made of process names, folders, and explicit `.exe` files. It generates ProxiFyre config and restarts ProxiFyre only when the user applies changes.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
# 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
|
|
||||||
│
|
|
||||||
├─ 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
|
|
||||||
-m addrtype --dst-type LOCAL → RETURN # ответы самого sing-box
|
|
||||||
-m mark --mark 1 → RETURN # уже помеченные пакеты
|
|
||||||
-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.
|
|
||||||
|
|
||||||
### 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://<gateway-ip>: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_START/END` |
|
|
||||||
| `CLIENT_PROXY_PORT_START` | `8080` | Первый host/container proxy-порт для `docker-compose.client.yml` |
|
|
||||||
| `CLIENT_PROXY_PORT_END` | `8090` | Последний host/container proxy-порт для `docker-compose.client.yml` |
|
|
||||||
| `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 |
|
|
||||||
| `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 и порты.
|
|
||||||
|
|||||||
@@ -9,15 +9,11 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
APP_MODE: client
|
APP_MODE: client
|
||||||
PORT: ${PORT:-3456}
|
PORT: ${PORT:-3456}
|
||||||
PROXY_PORT: ${CLIENT_PROXY_PORT_START:-8080}
|
PROXY_PORT: ${CLIENT_PROXY_PORT:-8082}
|
||||||
CLIENT_PROXY_PORT_START: ${CLIENT_PROXY_PORT_START:-8080}
|
|
||||||
CLIENT_PROXY_PORT_END: ${CLIENT_PROXY_PORT_END:-8090}
|
|
||||||
PROXY_BIND_IP: 0.0.0.0
|
PROXY_BIND_IP: 0.0.0.0
|
||||||
DATA_DIR: /var/lib/vpn-proxy
|
DATA_DIR: /var/lib/vpn-proxy
|
||||||
SING_BOX_CONFIG: /etc/sing-box/config.json
|
SING_BOX_CONFIG: /etc/sing-box/config.json
|
||||||
SING_BOX_CACHE: /var/lib/sing-box/cache.db
|
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}
|
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||||
HTTP_PROXY: ""
|
HTTP_PROXY: ""
|
||||||
HTTPS_PROXY: ""
|
HTTPS_PROXY: ""
|
||||||
@@ -29,13 +25,13 @@ services:
|
|||||||
no_proxy: "localhost,127.0.0.1,host.docker.internal"
|
no_proxy: "localhost,127.0.0.1,host.docker.internal"
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:${CLIENT_UI_PORT:-3456}:${PORT:-3456}"
|
- "127.0.0.1:${CLIENT_UI_PORT:-3456}:${PORT:-3456}"
|
||||||
- "127.0.0.1:${CLIENT_PROXY_PORT_START:-8080}-${CLIENT_PROXY_PORT_END:-8090}:${CLIENT_PROXY_PORT_START:-8080}-${CLIENT_PROXY_PORT_END:-8090}"
|
- "127.0.0.1:${CLIENT_PROXY_PORT:-8082}:${CLIENT_PROXY_PORT:-8082}"
|
||||||
volumes:
|
volumes:
|
||||||
- vpn-proxy-client-data:/var/lib/vpn-proxy
|
- vpn-proxy-client-data:/var/lib/vpn-proxy
|
||||||
- sing-box-client-cache:/var/lib/sing-box
|
- sing-box-client-cache:/var/lib/sing-box
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:${PORT:-3456}/api/state"]
|
test: ["CMD", "curl", "--noproxy", "*", "-fsS", "http://127.0.0.1:${PORT:-3456}/api/state"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 3
|
retries: 3
|
||||||
|
|||||||
@@ -14,7 +14,8 @@ services:
|
|||||||
- NET_ADMIN
|
- NET_ADMIN
|
||||||
- NET_RAW
|
- NET_RAW
|
||||||
env_file:
|
env_file:
|
||||||
- .env
|
- path: .env
|
||||||
|
required: false
|
||||||
environment:
|
environment:
|
||||||
DATA_DIR: /var/lib/vpn-proxy
|
DATA_DIR: /var/lib/vpn-proxy
|
||||||
SING_BOX_CACHE: /var/lib/sing-box/cache.db
|
SING_BOX_CACHE: /var/lib/sing-box/cache.db
|
||||||
|
|||||||
105
docs/roadmap.md
105
docs/roadmap.md
@@ -1,105 +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 | native `sing-box.exe` + ProxiFyre | позже приводим в порядок |
|
|
||||||
|
|
||||||
## 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
|
|
||||||
|
|
||||||
Цель: сохранить сценарий для Discord/Vesktop/игр.
|
|
||||||
|
|
||||||
Требования:
|
|
||||||
|
|
||||||
- Native `sing-box.exe`.
|
|
||||||
- Scheduled task или Windows service.
|
|
||||||
- ProxiFyre + WinPacketFilter для приложений, которые не умеют proxy.
|
|
||||||
- Управление из PowerShell helper.
|
|
||||||
- Позже можно сделать Electron/Tauri UI поверх privileged helper.
|
|
||||||
|
|
||||||
## Рабочий порядок
|
|
||||||
|
|
||||||
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 mode к новой архитектуре.
|
|
||||||
@@ -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.
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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`.
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
# Windows Client Design
|
|
||||||
|
|
||||||
## Goal
|
|
||||||
|
|
||||||
Restore the old Windows workflow in a cleaner product shape: a one-command PowerShell installer can install either a full local `sing-box` + ProxiFyre setup or ProxiFyre-only routing to an existing proxy, then expose a small local web UI for profiles, folders, executable files, status, and logs.
|
|
||||||
|
|
||||||
## Product Shape
|
|
||||||
|
|
||||||
The Windows mode is script-first and UI-assisted. The installer remains the durable entrypoint because Windows driver/service setup needs administrator rights and must stay easy to debug from PowerShell. The web UI is a local control surface on top of the same scripts, not a separate desktop app in the first version.
|
|
||||||
|
|
||||||
The installer supports two paths:
|
|
||||||
|
|
||||||
- **Full install:** install native `sing-box.exe`, configure a local SOCKS/HTTP proxy on `127.0.0.1:1080`, install WinPacketFilter and ProxiFyre, then route selected Windows apps through the local proxy.
|
|
||||||
- **ProxiFyre only:** install WinPacketFilter and ProxiFyre, then point selected Windows apps to an existing proxy target such as `127.0.0.1:8080`, `192.168.50.111:8080`, or another reachable SOCKS5 endpoint.
|
|
||||||
|
|
||||||
The default UI direction is the approved cleaner mockup: one route status, profiles as the main object, selected profile details on the right, and a short recent activity/log section below. The first screen should answer: what is the active proxy target, whether services are running, and which profiles are currently enabled.
|
|
||||||
|
|
||||||
## User Flows
|
|
||||||
|
|
||||||
### Install
|
|
||||||
|
|
||||||
The user opens PowerShell 7 as Administrator and runs:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
irm https://git.dokops.ru/dokril/vpn-proxy/raw/branch/master/scripts/install-windows-client.ps1 | iex
|
|
||||||
```
|
|
||||||
|
|
||||||
The installer checks administrator rights, PowerShell version, architecture, internet access, and required paths. It installs under `C:\Tools\vpn-proxy-windows` and keeps third-party runtime files in focused subdirectories:
|
|
||||||
|
|
||||||
- `C:\Tools\vpn-proxy-windows\app` for this project checkout or archive.
|
|
||||||
- `C:\Tools\vpn-proxy-windows\runtime\node` for portable Node.js when no suitable Node is installed.
|
|
||||||
- `C:\Tools\vpn-proxy-windows\runtime\sing-box` for `sing-box.exe`, config, and logs.
|
|
||||||
- `C:\Tools\ProxiFyre` for ProxiFyre, matching the legacy script path.
|
|
||||||
|
|
||||||
If the user chooses Full install, the installer asks for a subscription or VLESS link, parses it through the existing subscription logic where possible, lets the user select a server, writes the native `sing-box` config, installs a scheduled task for `sing-box`, and starts it.
|
|
||||||
|
|
||||||
If the user chooses ProxiFyre only, the installer asks for a SOCKS5 proxy target and verifies TCP connectivity before writing ProxiFyre config.
|
|
||||||
|
|
||||||
After setup, the installer starts the local control UI on `http://127.0.0.1:3456` and prints recovery commands:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
& "C:\Tools\vpn-proxy-windows\manage.ps1"
|
|
||||||
& "C:\Tools\vpn-proxy-windows\manage.ps1" -OpenUi
|
|
||||||
& "C:\Tools\vpn-proxy-windows\manage.ps1" -Status
|
|
||||||
```
|
|
||||||
|
|
||||||
### Profile Management
|
|
||||||
|
|
||||||
Profiles are the central unit. A profile contains a name, enabled flag, proxy target, protocol list, and app items. Supported item types:
|
|
||||||
|
|
||||||
- `process`: process name such as `Discord`, `Update`, or `Vesktop`.
|
|
||||||
- `folder`: folder path; the system scans `.exe` files and converts them to routable entries.
|
|
||||||
- `exe`: explicit executable file path; the system resolves it to the executable name for ProxiFyre and keeps the full path for display and diagnostics.
|
|
||||||
|
|
||||||
Folder and exe entries are intentionally stored as user-facing source items, while the generated ProxiFyre config is derived. This keeps the UI understandable and makes future ProxiFyre/Proxifier adapter changes possible without changing the profile model.
|
|
||||||
|
|
||||||
When a profile changes, the UI marks it as pending. The user applies changes once. Apply regenerates ProxiFyre `app-config.json`, restarts the ProxiFyre service, then writes an activity entry showing what changed.
|
|
||||||
|
|
||||||
### Runtime Operations
|
|
||||||
|
|
||||||
The UI exposes these actions:
|
|
||||||
|
|
||||||
- start, stop, restart `sing-box` when local mode is installed;
|
|
||||||
- start, stop, restart ProxiFyre;
|
|
||||||
- switch a profile between `local-singbox` and an external proxy target;
|
|
||||||
- add process, folder, or exe entries;
|
|
||||||
- scan folder entries again;
|
|
||||||
- copy diagnostics for support/debugging;
|
|
||||||
- open logs.
|
|
||||||
|
|
||||||
The UI does not auto-change global Windows proxy settings. Routing happens only through ProxiFyre profiles.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
The active project already has a plain Node API server, React/Vite UI, subscription parser, `sing-box` config generator, logs, traffic parsing, and client/gateway modes. Windows mode should reuse those pieces and add a Windows helper boundary.
|
|
||||||
|
|
||||||
### App Mode
|
|
||||||
|
|
||||||
Add `APP_MODE=windows`. In Windows mode:
|
|
||||||
|
|
||||||
- the HTTP server binds to `127.0.0.1`;
|
|
||||||
- the UI uses Windows labels and hides gateway-only TProxy/device controls;
|
|
||||||
- config generation is proxy-only like client mode, but it targets native `sing-box.exe` rather than Docker;
|
|
||||||
- service and driver actions go through the PowerShell helper, not direct Node assumptions.
|
|
||||||
|
|
||||||
### Windows Helper Boundary
|
|
||||||
|
|
||||||
Create a PowerShell helper module that owns privileged Windows operations:
|
|
||||||
|
|
||||||
- install/update `sing-box.exe`;
|
|
||||||
- install/start/stop scheduled tasks;
|
|
||||||
- install/update WinPacketFilter;
|
|
||||||
- install/update ProxiFyre;
|
|
||||||
- write ProxiFyre config;
|
|
||||||
- query service/task status;
|
|
||||||
- read recent log files;
|
|
||||||
- test proxy connectivity;
|
|
||||||
- manage firewall rules for local proxy ports.
|
|
||||||
|
|
||||||
The Node server calls the helper with explicit command names and JSON input/output. The helper returns structured JSON for every operation:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": true,
|
|
||||||
"action": "proxies.apply",
|
|
||||||
"changed": true,
|
|
||||||
"message": "ProxiFyre config applied and service restarted"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Errors use the same shape with `success: false`, `error`, and optional `details`. The UI never parses raw PowerShell text.
|
|
||||||
|
|
||||||
### Data Files
|
|
||||||
|
|
||||||
Windows mode stores state under `C:\Tools\vpn-proxy-windows\data`:
|
|
||||||
|
|
||||||
- `windows-profiles.json` for profile source data.
|
|
||||||
- `proxy-targets.json` for `local-singbox` and external proxy targets.
|
|
||||||
- `windows-state.json` for last applied profile revision and UI status.
|
|
||||||
- `subscription-cache.json` and `state.json` stay compatible with existing subscription/server selection logic.
|
|
||||||
|
|
||||||
Profile shape:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"id": "discord-vesktop",
|
|
||||||
"name": "Discord + Vesktop",
|
|
||||||
"enabled": true,
|
|
||||||
"proxyTargetId": "local-singbox",
|
|
||||||
"protocols": ["TCP", "UDP"],
|
|
||||||
"items": [
|
|
||||||
{ "type": "process", "value": "Discord" },
|
|
||||||
{ "type": "process", "value": "Update" },
|
|
||||||
{
|
|
||||||
"type": "folder",
|
|
||||||
"value": "%LOCALAPPDATA%\\vesktop",
|
|
||||||
"recursive": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "exe",
|
|
||||||
"value": "C:\\Games\\SomeGame\\game.exe"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Generated ProxiFyre config is not edited directly. It is derived from enabled profiles and proxy targets, then written to `C:\Tools\ProxiFyre\app-config.json`.
|
|
||||||
|
|
||||||
### API Surface
|
|
||||||
|
|
||||||
Add Windows-specific endpoints:
|
|
||||||
|
|
||||||
- `GET /api/windows/status`: returns install mode, `sing-box` status, ProxiFyre status, active target, pending changes, and recent activity.
|
|
||||||
- `GET /api/windows/profiles`: returns profile source data with resolved executable counts.
|
|
||||||
- `PUT /api/windows/profiles`: saves profiles without applying.
|
|
||||||
- `POST /api/windows/profiles/apply`: generates ProxiFyre config and restarts service.
|
|
||||||
- `POST /api/windows/profiles/scan`: resolves folder and exe entries for preview.
|
|
||||||
- `GET /api/windows/targets`: returns `local-singbox` and external proxy targets.
|
|
||||||
- `PUT /api/windows/targets`: saves external proxy targets after validation.
|
|
||||||
- `POST /api/windows/service`: start, stop, or restart `sing-box`, ProxiFyre, or the UI service.
|
|
||||||
- `GET /api/windows/logs`: returns recent helper, `sing-box`, and ProxiFyre logs.
|
|
||||||
|
|
||||||
Existing generic endpoints for subscription fetch, server selection, apply, logs, and config validation should be reused where the behavior matches Windows mode.
|
|
||||||
|
|
||||||
## UI Design
|
|
||||||
|
|
||||||
The approved direction is a restrained operational UI:
|
|
||||||
|
|
||||||
- top bar: product name, restart/stop/add profile actions;
|
|
||||||
- left nav: Overview, Profiles, Targets, Logs, Settings;
|
|
||||||
- main status panel: one sentence describing the active route, plus a compact route line such as `Selected apps -> ProxiFyre -> sing-box -> VPN`;
|
|
||||||
- main workspace: profile list on the left, selected profile details on the right;
|
|
||||||
- profile details: target selector, add process/folder/exe input, resolved items list, save/apply controls;
|
|
||||||
- activity panel: recent traffic/service events, not a full noisy log dump.
|
|
||||||
|
|
||||||
Avoid duplicate status blocks. Avoid showing raw implementation concepts like WinPacketFilter unless the user is in diagnostics/settings. The primary terms should be `Profile`, `Proxy target`, `Local sing-box`, `Existing proxy`, `App/folder/exe`, and `Apply changes`.
|
|
||||||
|
|
||||||
## Safety And Constraints
|
|
||||||
|
|
||||||
The UI binds only to `127.0.0.1`. Windows actions that require elevation stay in the installer/helper path. The installer must not delete existing `C:\Tools\vpn-proxy` legacy folders without confirmation.
|
|
||||||
|
|
||||||
Folder and exe routing needs a clear diagnostic note: ProxiFyre routing ultimately depends on what the installed ProxiFyre version accepts. The first implementation should resolve folders and exe paths to executable names for compatibility, while preserving full paths in profile data and diagnostics. If direct path matching is verified in ProxiFyre, the adapter can emit full paths without changing the UI model.
|
|
||||||
|
|
||||||
The installer should be idempotent:
|
|
||||||
|
|
||||||
- re-running it updates project files;
|
|
||||||
- existing subscriptions and profiles are preserved unless the user chooses reset;
|
|
||||||
- existing ProxiFyre config is backed up before overwrite;
|
|
||||||
- failed applies leave the previous generated config available for rollback.
|
|
||||||
|
|
||||||
## Testing And Verification
|
|
||||||
|
|
||||||
Use focused tests for pure logic:
|
|
||||||
|
|
||||||
- profile normalization;
|
|
||||||
- folder/exe item resolution;
|
|
||||||
- ProxiFyre config generation;
|
|
||||||
- proxy target validation;
|
|
||||||
- Windows helper JSON command contract;
|
|
||||||
- `APP_MODE=windows` public state and config generation.
|
|
||||||
|
|
||||||
Use manual Windows verification for privileged operations:
|
|
||||||
|
|
||||||
- fresh Full install;
|
|
||||||
- fresh ProxiFyre-only install;
|
|
||||||
- re-run installer over existing install;
|
|
||||||
- add process profile;
|
|
||||||
- add folder profile;
|
|
||||||
- add explicit exe profile;
|
|
||||||
- switch a profile from local sing-box to external proxy;
|
|
||||||
- restart ProxiFyre and verify service status;
|
|
||||||
- copy diagnostics after a failed proxy target check.
|
|
||||||
|
|
||||||
Local non-Windows development should still run `npm test` and `npm run build`. Windows-only helper commands should have dry-run or mockable modes so logic can be tested without installing drivers on the development machine.
|
|
||||||
|
|
||||||
## Non-Goals For First Version
|
|
||||||
|
|
||||||
- No Electron or Tauri wrapper.
|
|
||||||
- No global Windows system proxy changes.
|
|
||||||
- No transparent routing without ProxiFyre.
|
|
||||||
- No remote multi-device management.
|
|
||||||
- No automatic uninstall of unrelated WinPacketFilter users.
|
|
||||||
- No Proxifier support until ProxiFyre behavior is stable.
|
|
||||||
|
|
||||||
## Implementation Defaults
|
|
||||||
|
|
||||||
- The UI server runs when opened by `manage.ps1 -OpenUi` in the first version. An at-logon scheduled UI task can be added later after the helper and UI are stable.
|
|
||||||
- Full install uses portable Node/npm when the machine has no suitable Node.js. The installer builds the React UI locally for MVP; a prebuilt release artifact can replace that later without changing user-facing behavior.
|
|
||||||
- ProxiFyre generation emits process names in the first version for compatibility. Full folder and exe paths remain in profile data and diagnostics; the adapter can start emitting full paths later if ProxiFyre path matching is verified.
|
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
PORT="${PORT:-3456}"
|
PORT="${PORT:-3456}"
|
||||||
PROXY_PORT="${PROXY_PORT:-8080}"
|
PROXY_PORT="${PROXY_PORT:-8082}"
|
||||||
DATA_DIR="${DATA_DIR:-/var/lib/vpn-proxy}"
|
DATA_DIR="${DATA_DIR:-/var/lib/vpn-proxy}"
|
||||||
SING_BOX_CONFIG="${SING_BOX_CONFIG:-/etc/sing-box/config.json}"
|
SING_BOX_CONFIG="${SING_BOX_CONFIG:-/etc/sing-box/config.json}"
|
||||||
SING_BOX_CACHE="${SING_BOX_CACHE:-/var/lib/sing-box/cache.db}"
|
SING_BOX_CACHE="${SING_BOX_CACHE:-/var/lib/sing-box/cache.db}"
|
||||||
|
|||||||
40
entrypoint.sh
Normal file → Executable file
40
entrypoint.sh
Normal file → Executable file
@@ -11,12 +11,6 @@ PROXY_INPUT_CHAIN="${PROXY_INPUT_CHAIN:-VPN_PROXY_INPUT}"
|
|||||||
PROXY_FIREWALL="${PROXY_FIREWALL:-true}"
|
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}"
|
PROXY_ALLOWED_CIDRS="${PROXY_ALLOWED_CIDRS:-10.0.0.0/8 172.16.0.0/12 192.168.0.0/16}"
|
||||||
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}"
|
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() {
|
log() {
|
||||||
printf '[gateway-entrypoint] %s\n' "$*"
|
printf '[gateway-entrypoint] %s\n' "$*"
|
||||||
@@ -34,26 +28,19 @@ cleanup_proxy_firewall() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cleanup_tproxy() {
|
cleanup_tproxy() {
|
||||||
log "cleanup tproxy rules"
|
|
||||||
ipt -t mangle -D PREROUTING -j "$TPROXY_CHAIN" 2>/dev/null || true
|
ipt -t mangle -D PREROUTING -j "$TPROXY_CHAIN" 2>/dev/null || true
|
||||||
ipt -t mangle -F "$TPROXY_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 -X "$TPROXY_CHAIN" 2>/dev/null || true
|
||||||
ip rule del fwmark "$TPROXY_MARK" table "$TPROXY_TABLE" 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
|
ip route flush table "$TPROXY_TABLE" 2>/dev/null || true
|
||||||
# ipset не чистим при завершении — TTL сам истечёт
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setup_direct_bypass_set() {
|
enable_ip_forwarding() {
|
||||||
if [[ "$DIRECT_BYPASS_CACHE" != "true" ]]; then
|
if [[ -w /proc/sys/net/ipv4/ip_forward ]]; then
|
||||||
export DIRECT_BYPASS_CACHE
|
printf '1' > /proc/sys/net/ipv4/ip_forward || true
|
||||||
return
|
elif command -v sysctl >/dev/null 2>&1; then
|
||||||
|
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
|
||||||
fi
|
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() {
|
setup_proxy_firewall() {
|
||||||
@@ -61,9 +48,7 @@ setup_proxy_firewall() {
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
log "setup proxy firewall for :${PROXY_PORT} (${PROXY_ALLOWED_CIDRS})"
|
|
||||||
cleanup_proxy_firewall
|
cleanup_proxy_firewall
|
||||||
|
|
||||||
ipt -N "$PROXY_INPUT_CHAIN"
|
ipt -N "$PROXY_INPUT_CHAIN"
|
||||||
for cidr in $PROXY_ALLOWED_CIDRS; do
|
for cidr in $PROXY_ALLOWED_CIDRS; do
|
||||||
ipt -A "$PROXY_INPUT_CHAIN" -s "$cidr" -j RETURN
|
ipt -A "$PROXY_INPUT_CHAIN" -s "$cidr" -j RETURN
|
||||||
@@ -74,23 +59,17 @@ setup_proxy_firewall() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setup_tproxy() {
|
setup_tproxy() {
|
||||||
log "setup tproxy on port ${TPROXY_PORT}, mark ${TPROXY_MARK}, table ${TPROXY_TABLE}"
|
log "setup tproxy on port ${TPROXY_PORT}"
|
||||||
cleanup_tproxy
|
cleanup_tproxy
|
||||||
|
enable_ip_forwarding
|
||||||
|
|
||||||
ip rule add fwmark "$TPROXY_MARK" table "$TPROXY_TABLE" 2>/dev/null || true
|
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"
|
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_CHAIN"
|
||||||
# Пропускаем пакеты, адресованные самому хосту (ответы на исходящие соединения sing-box)
|
|
||||||
ipt -t mangle -A "$TPROXY_CHAIN" -m addrtype --dst-type LOCAL -j RETURN
|
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" -m mark --mark "$TPROXY_MARK" -j RETURN
|
||||||
|
|
||||||
if [[ "$DIRECT_BYPASS_CACHE" == "true" ]]; then
|
# Private/local destinations stay reachable; every intercepted public packet goes to VPN.
|
||||||
# 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
|
|
||||||
|
|
||||||
for cidr in $BYPASS_CIDRS; do
|
for cidr in $BYPASS_CIDRS; do
|
||||||
ipt -t mangle -A "$TPROXY_CHAIN" -d "$cidr" -j RETURN
|
ipt -t mangle -A "$TPROXY_CHAIN" -d "$cidr" -j RETURN
|
||||||
done
|
done
|
||||||
@@ -100,7 +79,6 @@ setup_tproxy() {
|
|||||||
ipt -t mangle -A PREROUTING -j "$TPROXY_CHAIN"
|
ipt -t mangle -A PREROUTING -j "$TPROXY_CHAIN"
|
||||||
}
|
}
|
||||||
|
|
||||||
setup_direct_bypass_set
|
|
||||||
setup_tproxy
|
setup_tproxy
|
||||||
setup_proxy_firewall
|
setup_proxy_firewall
|
||||||
|
|
||||||
@@ -108,7 +86,6 @@ node /app/src/server/index.js &
|
|||||||
APP_PID=$!
|
APP_PID=$!
|
||||||
|
|
||||||
shutdown() {
|
shutdown() {
|
||||||
log "shutdown requested"
|
|
||||||
kill "$APP_PID" 2>/dev/null || true
|
kill "$APP_PID" 2>/dev/null || true
|
||||||
wait "$APP_PID" 2>/dev/null || true
|
wait "$APP_PID" 2>/dev/null || true
|
||||||
cleanup_proxy_firewall
|
cleanup_proxy_firewall
|
||||||
@@ -116,7 +93,6 @@ shutdown() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
trap 'shutdown; exit 0' SIGTERM SIGINT
|
trap 'shutdown; exit 0' SIGTERM SIGINT
|
||||||
|
|
||||||
wait "$APP_PID"
|
wait "$APP_PID"
|
||||||
STATUS=$?
|
STATUS=$?
|
||||||
cleanup_proxy_firewall
|
cleanup_proxy_firewall
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>VPN Proxy Gateway</title>
|
<title>VPN</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
65
package-lock.json
generated
65
package-lock.json
generated
@@ -8,15 +8,11 @@
|
|||||||
"name": "vpn-proxy-gateway",
|
"name": "vpn-proxy-gateway",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"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",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"vite": "^7.0.0"
|
"vite": "^7.0.0"
|
||||||
},
|
}
|
||||||
"devDependencies": {}
|
|
||||||
},
|
},
|
||||||
"node_modules/@babel/code-frame": {
|
"node_modules/@babel/code-frame": {
|
||||||
"version": "7.29.0",
|
"version": "7.29.0",
|
||||||
@@ -281,59 +277,6 @@
|
|||||||
"node": ">=6.9.0"
|
"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": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
"version": "0.27.7",
|
"version": "0.27.7",
|
||||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",
|
||||||
@@ -1606,12 +1549,6 @@
|
|||||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
"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": {
|
"node_modules/update-browserslist-db": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
|
||||||
|
|||||||
@@ -11,9 +11,6 @@
|
|||||||
"start": "node src/server/index.js"
|
"start": "node src/server/index.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"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",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
|
|||||||
@@ -47,6 +47,10 @@ TPROXY_PORT=7895
|
|||||||
TPROXY_MARK=1
|
TPROXY_MARK=1
|
||||||
TPROXY_TABLE=100
|
TPROXY_TABLE=100
|
||||||
TPROXY_CHAIN=VPN_PROXY_TPROXY
|
TPROXY_CHAIN=VPN_PROXY_TPROXY
|
||||||
|
TPROXY_SOURCE_BYPASS_CHAIN=VPN_PROXY_SRC_BYPASS
|
||||||
|
TPROXY_SOURCE_FORWARD_CHAIN=VPN_PROXY_FWD_BYPASS
|
||||||
|
TPROXY_SOURCE_NAT_CHAIN=VPN_PROXY_NAT_BYPASS
|
||||||
|
TPROXY_BYPASS_SOURCE_CIDRS=
|
||||||
ROUTING_RU_DIRECT=true
|
ROUTING_RU_DIRECT=true
|
||||||
LOG_LEVEL=info
|
LOG_LEVEL=info
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ INSTALL_DIR="${VPN_PROXY_INSTALL_DIR:-$HOME/.vpn-proxy-client}"
|
|||||||
REPO_URL="${VPN_PROXY_REPO_URL:-https://git.dokops.ru/dokril/vpn-proxy.git}"
|
REPO_URL="${VPN_PROXY_REPO_URL:-https://git.dokops.ru/dokril/vpn-proxy.git}"
|
||||||
BRANCH="${VPN_PROXY_BRANCH:-master}"
|
BRANCH="${VPN_PROXY_BRANCH:-master}"
|
||||||
COMPOSE_FILE="docker-compose.client.yml"
|
COMPOSE_FILE="docker-compose.client.yml"
|
||||||
DEFAULT_PROXY_PORT="8080"
|
DEFAULT_PROXY_PORT="8082"
|
||||||
REQUESTED_PROXY_PORT="${VPN_PROXY_CLIENT_PORT:-}"
|
REQUESTED_PROXY_PORT="${VPN_PROXY_CLIENT_PORT:-}"
|
||||||
REQUESTED_UI_PORT="${VPN_PROXY_CLIENT_UI_PORT:-${CLIENT_UI_PORT:-}}"
|
REQUESTED_UI_PORT="${VPN_PROXY_CLIENT_UI_PORT:-${CLIENT_UI_PORT:-}}"
|
||||||
CLIENT_CONTAINER_NAME="vpn-proxy-client"
|
CLIENT_CONTAINER_NAME="vpn-proxy-client"
|
||||||
@@ -59,15 +59,6 @@ ask_proxy_port() {
|
|||||||
printf '%s\n' "$DEFAULT_PROXY_PORT"
|
printf '%s\n' "$DEFAULT_PROXY_PORT"
|
||||||
}
|
}
|
||||||
|
|
||||||
port_range_end() {
|
|
||||||
local start="$1"
|
|
||||||
local end="$((start + 10))"
|
|
||||||
if [ "$end" -gt 65535 ]; then
|
|
||||||
end=65535
|
|
||||||
fi
|
|
||||||
printf '%s\n' "$end"
|
|
||||||
}
|
|
||||||
|
|
||||||
published_port_conflicts() {
|
published_port_conflicts() {
|
||||||
local port="$1"
|
local port="$1"
|
||||||
local line
|
local line
|
||||||
@@ -82,18 +73,7 @@ published_port_conflicts() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxy_port_conflicts() {
|
proxy_port_conflicts() {
|
||||||
local start="$1"
|
published_port_conflicts "$1"
|
||||||
local end
|
|
||||||
local port
|
|
||||||
local conflicts
|
|
||||||
|
|
||||||
end="$(port_range_end "$start")"
|
|
||||||
for port in $(seq "$start" "$end"); do
|
|
||||||
conflicts="$(published_port_conflicts "$port")"
|
|
||||||
if [ -n "$conflicts" ]; then
|
|
||||||
printf 'port %s: %s\n' "$port" "$conflicts"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
}
|
}
|
||||||
|
|
||||||
assert_proxy_port_available() {
|
assert_proxy_port_available() {
|
||||||
@@ -105,8 +85,8 @@ assert_proxy_port_available() {
|
|||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
printf '[vpn-proxy-client] proxy port range %s-%s is already used:\n%s\n' \
|
printf '[vpn-proxy-client] proxy port %s is already used:\n%s\n' \
|
||||||
"$port" "$(port_range_end "$port")" "$conflicts" >&2
|
"$port" "$conflicts" >&2
|
||||||
die "choose another proxy port with VPN_PROXY_CLIENT_PORT=<port> or stop the conflicting container"
|
die "choose another proxy port with VPN_PROXY_CLIENT_PORT=<port> or stop the conflicting container"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,8 +150,8 @@ choose_ui_port() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
assert_ui_outside_proxy_range() {
|
assert_ui_outside_proxy_range() {
|
||||||
if [ "$UI_PORT" -ge "$PROXY_PORT" ] && [ "$UI_PORT" -le "$PROXY_PORT_END" ]; then
|
if [ "$UI_PORT" = "$PROXY_PORT" ]; then
|
||||||
die "UI port ${UI_PORT} overlaps proxy port range ${PROXY_PORT}-${PROXY_PORT_END}"
|
die "UI port ${UI_PORT} overlaps proxy port"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +161,7 @@ wait_for_client_ui() {
|
|||||||
local attempt
|
local attempt
|
||||||
|
|
||||||
for attempt in $(seq 1 30); do
|
for attempt in $(seq 1 30); do
|
||||||
if curl -fsS "$ui_url" >/dev/null 2>&1; then
|
if curl --noproxy "*" -fsS "$ui_url" >/dev/null 2>&1; then
|
||||||
return 0
|
return 0
|
||||||
fi
|
fi
|
||||||
sleep 1
|
sleep 1
|
||||||
@@ -254,7 +234,6 @@ fi
|
|||||||
|
|
||||||
PROXY_PORT="$(ask_proxy_port)"
|
PROXY_PORT="$(ask_proxy_port)"
|
||||||
assert_proxy_port_available "$PROXY_PORT"
|
assert_proxy_port_available "$PROXY_PORT"
|
||||||
PROXY_PORT_END="$(port_range_end "$PROXY_PORT")"
|
|
||||||
UI_PORT="${REQUESTED_UI_PORT:-$(get_env_value CLIENT_UI_PORT)}"
|
UI_PORT="${REQUESTED_UI_PORT:-$(get_env_value CLIENT_UI_PORT)}"
|
||||||
UI_PORT="${UI_PORT:-3456}"
|
UI_PORT="${UI_PORT:-3456}"
|
||||||
UI_PORT="$(choose_ui_port "$UI_PORT")"
|
UI_PORT="$(choose_ui_port "$UI_PORT")"
|
||||||
@@ -263,12 +242,10 @@ assert_ui_outside_proxy_range
|
|||||||
set_env_value APP_MODE client
|
set_env_value APP_MODE client
|
||||||
set_env_value CLIENT_UI_PORT "$UI_PORT"
|
set_env_value CLIENT_UI_PORT "$UI_PORT"
|
||||||
set_env_value CLIENT_PROXY_PORT "$PROXY_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"
|
set_env_value PROXY_PORT "$PROXY_PORT"
|
||||||
|
|
||||||
log "UI port: http://127.0.0.1:${UI_PORT}"
|
log "UI port: http://127.0.0.1:${UI_PORT}"
|
||||||
log "proxy port: 127.0.0.1:${PROXY_PORT} (reserved range ${PROXY_PORT}-${PROXY_PORT_END})"
|
log "proxy port: 127.0.0.1:${PROXY_PORT}"
|
||||||
|
|
||||||
log "building and starting Docker client"
|
log "building and starting Docker client"
|
||||||
docker compose -f "$COMPOSE_FILE" up -d --build
|
docker compose -f "$COMPOSE_FILE" up -d --build
|
||||||
@@ -283,7 +260,7 @@ UI:
|
|||||||
|
|
||||||
Proxy:
|
Proxy:
|
||||||
HTTP/SOCKS5 127.0.0.1:${PROXY_PORT}
|
HTTP/SOCKS5 127.0.0.1:${PROXY_PORT}
|
||||||
UI can switch proxy port within the Docker-published ${PROXY_PORT}-${PROXY_PORT_END} range.
|
This is the only Docker-published proxy port. Re-run the installer with VPN_PROXY_CLIENT_PORT=<port> to change it.
|
||||||
|
|
||||||
Useful commands:
|
Useful commands:
|
||||||
cd ~/.vpn-proxy-client
|
cd ~/.vpn-proxy-client
|
||||||
|
|||||||
@@ -1,296 +0,0 @@
|
|||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
|
|
||||||
$InstallRoot = $env:VPN_PROXY_WINDOWS_ROOT
|
|
||||||
if ([string]::IsNullOrWhiteSpace($InstallRoot)) { $InstallRoot = "C:\Tools\vpn-proxy-windows" }
|
|
||||||
|
|
||||||
$RepoBranch = $env:VPN_PROXY_WINDOWS_BRANCH
|
|
||||||
if ([string]::IsNullOrWhiteSpace($RepoBranch)) { $RepoBranch = "codex-windows-client" }
|
|
||||||
|
|
||||||
$AppDir = Join-Path $InstallRoot "app"
|
|
||||||
$DataDir = Join-Path $InstallRoot "data"
|
|
||||||
$RuntimeDir = Join-Path $InstallRoot "runtime"
|
|
||||||
$NodeDir = Join-Path $RuntimeDir "node"
|
|
||||||
$SingBoxDir = Join-Path $RuntimeDir "sing-box"
|
|
||||||
$ProxiFyreRoot = $env:PROXIFYRE_ROOT
|
|
||||||
if ([string]::IsNullOrWhiteSpace($ProxiFyreRoot)) { $ProxiFyreRoot = "C:\Tools\ProxiFyre" }
|
|
||||||
|
|
||||||
$RepoZipUrl = "https://git.dokops.ru/dokril/vpn-proxy/archive/$RepoBranch.zip"
|
|
||||||
$SingBoxVersion = "1.12.13"
|
|
||||||
$SingBoxUrl = "https://github.com/SagerNet/sing-box/releases/download/v$SingBoxVersion/sing-box-$SingBoxVersion-windows-amd64.zip"
|
|
||||||
$Headers = @{ "User-Agent" = "vpn-proxy-windows-installer" }
|
|
||||||
|
|
||||||
function Assert-Admin {
|
|
||||||
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
|
||||||
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
|
||||||
throw "Run PowerShell 7 as Administrator"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Assert-PowerShell7 {
|
|
||||||
if ($PSVersionTable.PSVersion.Major -lt 7) {
|
|
||||||
throw "PowerShell 7 is required"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-Arch {
|
|
||||||
if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") { return "arm64" }
|
|
||||||
if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64") { return "x64" }
|
|
||||||
return "x86"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Download-File {
|
|
||||||
param([string]$Url, [string]$Destination)
|
|
||||||
Write-Host "Downloading $Url"
|
|
||||||
Invoke-WebRequest -Uri $Url -OutFile $Destination -UseBasicParsing -Headers $Headers
|
|
||||||
Unblock-File -Path $Destination -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
|
|
||||||
function Invoke-CheckedProcess {
|
|
||||||
param(
|
|
||||||
[string]$FilePath,
|
|
||||||
[string[]]$ArgumentList,
|
|
||||||
[int[]]$AllowedExitCodes = @(0)
|
|
||||||
)
|
|
||||||
|
|
||||||
$process = Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -Wait -PassThru
|
|
||||||
if ($AllowedExitCodes -notcontains $process.ExitCode) {
|
|
||||||
throw "$FilePath failed with exit code $($process.ExitCode)"
|
|
||||||
}
|
|
||||||
return $process.ExitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-GitHubReleaseAsset {
|
|
||||||
param(
|
|
||||||
[string]$Repo,
|
|
||||||
[scriptblock]$AssetFilter
|
|
||||||
)
|
|
||||||
|
|
||||||
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/$Repo/releases/latest" -Headers $Headers
|
|
||||||
$asset = @($release.assets | Where-Object $AssetFilter | Select-Object -First 1)
|
|
||||||
if (-not $asset) {
|
|
||||||
throw "No matching release asset found for $Repo"
|
|
||||||
}
|
|
||||||
return $asset[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-AppFiles {
|
|
||||||
New-Item -ItemType Directory -Force -Path $InstallRoot, $DataDir, $RuntimeDir | Out-Null
|
|
||||||
$zip = Join-Path $env:TEMP "vpn-proxy-windows.zip"
|
|
||||||
$extract = Join-Path $env:TEMP "vpn-proxy-windows-extract"
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
|
|
||||||
Download-File -Url $RepoZipUrl -Destination $zip
|
|
||||||
Expand-Archive -Path $zip -DestinationPath $extract -Force
|
|
||||||
$source = Get-ChildItem $extract -Directory | Select-Object -First 1
|
|
||||||
if (-not $source) { throw "Downloaded archive layout is not recognized" }
|
|
||||||
|
|
||||||
if (Test-Path $AppDir) {
|
|
||||||
$backup = "$AppDir.backup"
|
|
||||||
Remove-Item $backup -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
Move-Item $AppDir $backup
|
|
||||||
}
|
|
||||||
|
|
||||||
Move-Item $source.FullName $AppDir
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-NodeRuntime {
|
|
||||||
$existing = Get-Command node -ErrorAction SilentlyContinue
|
|
||||||
if ($existing) { return $existing.Source }
|
|
||||||
|
|
||||||
New-Item -ItemType Directory -Force -Path $RuntimeDir | Out-Null
|
|
||||||
$arch = Get-Arch
|
|
||||||
$index = Invoke-RestMethod -Uri "https://nodejs.org/dist/index.json" -Headers $Headers
|
|
||||||
$release = @($index | Where-Object { $_.lts -ne $false } | Select-Object -First 1)[0]
|
|
||||||
if (-not $release) { throw "Cannot resolve latest Node.js LTS release" }
|
|
||||||
|
|
||||||
$version = [string]$release.version
|
|
||||||
$assetName = "node-$version-win-$arch.zip"
|
|
||||||
$zip = Join-Path $env:TEMP $assetName
|
|
||||||
$extract = Join-Path $env:TEMP "node-windows-extract"
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $NodeDir -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
|
|
||||||
Download-File -Url "https://nodejs.org/dist/$version/$assetName" -Destination $zip
|
|
||||||
Expand-Archive -Path $zip -DestinationPath $extract -Force
|
|
||||||
$nodeSource = Get-ChildItem $extract -Directory | Select-Object -First 1
|
|
||||||
if (-not $nodeSource) { throw "Downloaded Node.js archive layout is not recognized" }
|
|
||||||
Move-Item $nodeSource.FullName $NodeDir
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
return (Join-Path $NodeDir "node.exe")
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-NpmCommand {
|
|
||||||
param([string]$NodeCommand)
|
|
||||||
|
|
||||||
$portableNpm = Join-Path (Split-Path -Parent $NodeCommand) "npm.cmd"
|
|
||||||
if (Test-Path $portableNpm) { return $portableNpm }
|
|
||||||
$existing = Get-Command npm -ErrorAction SilentlyContinue
|
|
||||||
if ($existing) { return $existing.Source }
|
|
||||||
throw "npm was not found"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-VisualCRedistributable {
|
|
||||||
$arch = Get-Arch
|
|
||||||
$vcArch = if ($arch -eq "arm64") { "arm64" } elseif ($arch -eq "x86") { "x86" } else { "x64" }
|
|
||||||
$exe = Join-Path $env:TEMP "vc_redist.$vcArch.exe"
|
|
||||||
Download-File -Url "https://aka.ms/vs/17/release/vc_redist.$vcArch.exe" -Destination $exe
|
|
||||||
$code = Invoke-CheckedProcess -FilePath $exe -ArgumentList @("/install", "/quiet", "/norestart") -AllowedExitCodes @(0, 3010)
|
|
||||||
if ($code -eq 3010) {
|
|
||||||
Write-Warning "Visual C++ Redistributable requested a reboot"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-WinPacketFilter {
|
|
||||||
$service = Get-Service -Name "ndisrd" -ErrorAction SilentlyContinue
|
|
||||||
if ($service -and $service.Status -eq "Running") {
|
|
||||||
Write-Host "WinPacketFilter driver is already running"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
$arch = Get-Arch
|
|
||||||
$assetToken = if ($arch -eq "arm64") { "ARM64" } elseif ($arch -eq "x86") { "x86" } else { "x64" }
|
|
||||||
$asset = Get-GitHubReleaseAsset -Repo "wiresock/ndisapi" -AssetFilter {
|
|
||||||
param($item)
|
|
||||||
$item.name -match "\.msi$" -and $item.name -match $assetToken
|
|
||||||
}
|
|
||||||
|
|
||||||
$msi = Join-Path $env:TEMP $asset.name
|
|
||||||
Download-File -Url $asset.browser_download_url -Destination $msi
|
|
||||||
$code = Invoke-CheckedProcess -FilePath "msiexec.exe" -ArgumentList @("/i", "`"$msi`"", "/qn", "/norestart") -AllowedExitCodes @(0, 3010)
|
|
||||||
if ($code -eq 3010) {
|
|
||||||
Write-Warning "WinPacketFilter requested a reboot before first use"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-ProxiFyre {
|
|
||||||
New-Item -ItemType Directory -Force -Path $ProxiFyreRoot | Out-Null
|
|
||||||
if (Test-Path (Join-Path $ProxiFyreRoot "ProxiFyre.exe")) {
|
|
||||||
Write-Host "ProxiFyre is already installed at $ProxiFyreRoot"
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
$asset = Get-GitHubReleaseAsset -Repo "wiresock/proxifyre" -AssetFilter {
|
|
||||||
param($item)
|
|
||||||
$item.name -match "\.zip$" -and $item.name -notmatch "source"
|
|
||||||
}
|
|
||||||
|
|
||||||
$zip = Join-Path $env:TEMP $asset.name
|
|
||||||
$extract = Join-Path $env:TEMP "proxifyre-extract"
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
|
|
||||||
Download-File -Url $asset.browser_download_url -Destination $zip
|
|
||||||
Expand-Archive -Path $zip -DestinationPath $extract -Force
|
|
||||||
$exe = Get-ChildItem $extract -Recurse -Filter "ProxiFyre.exe" | Select-Object -First 1
|
|
||||||
if (-not $exe) { throw "ProxiFyre.exe was not found in release archive" }
|
|
||||||
|
|
||||||
Copy-Item (Join-Path (Split-Path -Parent $exe.FullName) "*") $ProxiFyreRoot -Recurse -Force
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-SingBox {
|
|
||||||
New-Item -ItemType Directory -Force -Path $SingBoxDir | Out-Null
|
|
||||||
if (Test-Path (Join-Path $SingBoxDir "sing-box.exe")) { return }
|
|
||||||
|
|
||||||
$zip = Join-Path $env:TEMP "sing-box-windows.zip"
|
|
||||||
$extract = Join-Path $env:TEMP "sing-box-windows-extract"
|
|
||||||
Remove-Item $zip -Force -ErrorAction SilentlyContinue
|
|
||||||
Remove-Item $extract -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
Download-File -Url $SingBoxUrl -Destination $zip
|
|
||||||
Expand-Archive -Path $zip -DestinationPath $extract -Force
|
|
||||||
$exe = Get-ChildItem $extract -Recurse -Filter "sing-box.exe" | Select-Object -First 1
|
|
||||||
if (-not $exe) { throw "sing-box.exe was not found in archive" }
|
|
||||||
Copy-Item $exe.FullName (Join-Path $SingBoxDir "sing-box.exe") -Force
|
|
||||||
}
|
|
||||||
|
|
||||||
function Select-InstallMode {
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host "Choose install mode:"
|
|
||||||
Write-Host " [1] Full install: local sing-box + ProxiFyre"
|
|
||||||
Write-Host " [2] ProxiFyre only: use existing proxy target"
|
|
||||||
$choice = Read-Host "Mode [1]"
|
|
||||||
if ($choice -eq "2") { return "proxifyre-only" }
|
|
||||||
return "full"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Test-TcpEndpoint {
|
|
||||||
param([string]$HostName, [int]$Port)
|
|
||||||
|
|
||||||
$client = [System.Net.Sockets.TcpClient]::new()
|
|
||||||
try {
|
|
||||||
$task = $client.ConnectAsync($HostName, $Port)
|
|
||||||
if (-not $task.Wait(2000)) { return $false }
|
|
||||||
return $client.Connected
|
|
||||||
} finally {
|
|
||||||
$client.Dispose()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-InitialTargets {
|
|
||||||
param([string]$Mode)
|
|
||||||
|
|
||||||
$targetsPath = Join-Path $DataDir "proxy-targets.json"
|
|
||||||
if (Test-Path $targetsPath) { return }
|
|
||||||
|
|
||||||
if ($Mode -eq "proxifyre-only") {
|
|
||||||
$target = Read-Host "Existing SOCKS5 proxy target host:port"
|
|
||||||
if ($target -notmatch "^([^:]+):(\d+)$") { throw "Expected host:port" }
|
|
||||||
$hostName = $matches[1]
|
|
||||||
$port = [int]$matches[2]
|
|
||||||
if (-not (Test-TcpEndpoint -HostName $hostName -Port $port)) {
|
|
||||||
Write-Warning "Proxy target $target did not accept a TCP connection during install"
|
|
||||||
}
|
|
||||||
@(@{ id = "existing-proxy"; name = "Existing proxy"; protocol = "socks5"; host = $hostName; port = $port }) |
|
|
||||||
ConvertTo-Json -Depth 5 |
|
|
||||||
Set-Content $targetsPath -Encoding UTF8
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Install-NodeDependencies {
|
|
||||||
$node = Install-NodeRuntime
|
|
||||||
$npm = Get-NpmCommand -NodeCommand $node
|
|
||||||
$env:PATH = "$(Split-Path -Parent $node);$env:PATH"
|
|
||||||
Push-Location $AppDir
|
|
||||||
try {
|
|
||||||
& $npm install
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "npm install failed" }
|
|
||||||
& $npm run build
|
|
||||||
if ($LASTEXITCODE -ne 0) { throw "npm run build failed" }
|
|
||||||
} finally {
|
|
||||||
Pop-Location
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Start-Ui {
|
|
||||||
$manage = Join-Path $AppDir "scripts\windows\manage.ps1"
|
|
||||||
Start-Process pwsh -ArgumentList "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "`"$manage`"", "-OpenUi"
|
|
||||||
}
|
|
||||||
|
|
||||||
Assert-Admin
|
|
||||||
Assert-PowerShell7
|
|
||||||
$mode = Select-InstallMode
|
|
||||||
Install-AppFiles
|
|
||||||
Install-NodeDependencies
|
|
||||||
Install-VisualCRedistributable
|
|
||||||
Install-WinPacketFilter
|
|
||||||
Install-ProxiFyre
|
|
||||||
if ($mode -eq "full") { Install-SingBox }
|
|
||||||
Write-InitialTargets -Mode $mode
|
|
||||||
Set-Content -Path (Join-Path $DataDir "windows-state.json") -Encoding UTF8 -Value (@{ installMode = $mode } | ConvertTo-Json)
|
|
||||||
Start-Ui
|
|
||||||
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host "VPN Proxy Windows is installed."
|
|
||||||
Write-Host "UI: http://127.0.0.1:3456"
|
|
||||||
Write-Host "Recovery:"
|
|
||||||
Write-Host "& `"$AppDir\scripts\windows\manage.ps1`" -OpenUi"
|
|
||||||
Write-Host "& `"$AppDir\scripts\windows\manage.ps1`" -Status"
|
|
||||||
Write-Host "& `"$AppDir\scripts\windows\manage.ps1`" -RestartServices"
|
|
||||||
@@ -1,154 +0,0 @@
|
|||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
|
|
||||||
$script:InstallRoot = $env:VPN_PROXY_WINDOWS_ROOT
|
|
||||||
if ([string]::IsNullOrWhiteSpace($script:InstallRoot)) {
|
|
||||||
$script:InstallRoot = "C:\Tools\vpn-proxy-windows"
|
|
||||||
}
|
|
||||||
|
|
||||||
$script:ProxiFyreRoot = $env:PROXIFYRE_ROOT
|
|
||||||
if ([string]::IsNullOrWhiteSpace($script:ProxiFyreRoot)) {
|
|
||||||
$script:ProxiFyreRoot = "C:\Tools\ProxiFyre"
|
|
||||||
}
|
|
||||||
|
|
||||||
function New-VpnProxyResult {
|
|
||||||
param(
|
|
||||||
[string]$Action,
|
|
||||||
[bool]$Success,
|
|
||||||
[object]$Result = $null,
|
|
||||||
[string]$Message = "",
|
|
||||||
[string]$ErrorMessage = ""
|
|
||||||
)
|
|
||||||
|
|
||||||
$value = [ordered]@{
|
|
||||||
success = $Success
|
|
||||||
action = $Action
|
|
||||||
}
|
|
||||||
if ($null -ne $Result) { $value.result = $Result }
|
|
||||||
if ($Message) { $value.message = $Message }
|
|
||||||
if ($ErrorMessage) { $value.error = $ErrorMessage }
|
|
||||||
return $value
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-VpnProxyStatus {
|
|
||||||
$task = Get-ScheduledTask -TaskName "SingBoxProxy" -ErrorAction SilentlyContinue
|
|
||||||
$singboxProcess = Get-Process -Name "sing-box" -ErrorAction SilentlyContinue
|
|
||||||
$proxifyre = Get-Service -Name "ProxiFyreService" -ErrorAction SilentlyContinue
|
|
||||||
|
|
||||||
return [ordered]@{
|
|
||||||
singbox = if ($singboxProcess) { "Running" } elseif ($task) { [string]$task.State } else { "NotInstalled" }
|
|
||||||
proxifyre = if ($proxifyre) { [string]$proxifyre.Status } else { "NotInstalled" }
|
|
||||||
installRoot = $script:InstallRoot
|
|
||||||
proxifyreRoot = $script:ProxiFyreRoot
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function Write-ProxiFyreConfig {
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory=$true)][string]$ConfigPath,
|
|
||||||
[Parameter(Mandatory=$true)][object]$Config
|
|
||||||
)
|
|
||||||
|
|
||||||
$dir = Split-Path -Parent $ConfigPath
|
|
||||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
|
||||||
if (Test-Path $ConfigPath) {
|
|
||||||
Copy-Item $ConfigPath "$ConfigPath.bak" -Force
|
|
||||||
}
|
|
||||||
$Config | ConvertTo-Json -Depth 20 | Set-Content -Path $ConfigPath -Encoding UTF8
|
|
||||||
}
|
|
||||||
|
|
||||||
function Restart-ProxiFyre {
|
|
||||||
$exe = Join-Path $script:ProxiFyreRoot "ProxiFyre.exe"
|
|
||||||
if (-not (Test-Path $exe)) {
|
|
||||||
throw "ProxiFyre.exe not found at $exe"
|
|
||||||
}
|
|
||||||
|
|
||||||
& $exe stop 2>$null | Out-Null
|
|
||||||
& $exe install 2>$null | Out-Null
|
|
||||||
& $exe start 2>$null | Out-Null
|
|
||||||
}
|
|
||||||
|
|
||||||
function Invoke-ProxiFyreApply {
|
|
||||||
param([object]$Payload)
|
|
||||||
|
|
||||||
Write-ProxiFyreConfig -ConfigPath $Payload.configPath -Config $Payload.config
|
|
||||||
Restart-ProxiFyre
|
|
||||||
return New-VpnProxyResult -Action "proxifyre.apply" -Success $true -Message "ProxiFyre config applied and service restarted"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Invoke-ServiceControl {
|
|
||||||
param([object]$Payload)
|
|
||||||
|
|
||||||
$service = [string]$Payload.service
|
|
||||||
$action = [string]$Payload.action
|
|
||||||
|
|
||||||
if ($service -eq "proxifyre") {
|
|
||||||
if ($action -eq "restart") { Restart-ProxiFyre }
|
|
||||||
elseif ($action -eq "start") { Start-Service -Name "ProxiFyreService" }
|
|
||||||
elseif ($action -eq "stop") { Stop-Service -Name "ProxiFyreService" -Force }
|
|
||||||
else { throw "Unknown ProxiFyre action: $action" }
|
|
||||||
} elseif ($service -eq "sing-box") {
|
|
||||||
if ($action -eq "restart") {
|
|
||||||
Stop-ScheduledTask -TaskName "SingBoxProxy" -ErrorAction SilentlyContinue
|
|
||||||
Start-ScheduledTask -TaskName "SingBoxProxy"
|
|
||||||
} elseif ($action -eq "start") {
|
|
||||||
Start-ScheduledTask -TaskName "SingBoxProxy"
|
|
||||||
} elseif ($action -eq "stop") {
|
|
||||||
Stop-ScheduledTask -TaskName "SingBoxProxy"
|
|
||||||
} else {
|
|
||||||
throw "Unknown sing-box action: $action"
|
|
||||||
}
|
|
||||||
} elseif ($service -eq "ui") {
|
|
||||||
return New-VpnProxyResult -Action "service.control" -Success $true -Message "UI is controlled by manage.ps1 -OpenUi"
|
|
||||||
} else {
|
|
||||||
throw "Unknown service: $service"
|
|
||||||
}
|
|
||||||
|
|
||||||
return New-VpnProxyResult -Action "service.control" -Success $true -Message "$service $action complete"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-VpnProxyLogs {
|
|
||||||
$paths = @(
|
|
||||||
(Join-Path $script:InstallRoot "runtime\sing-box\singbox.log"),
|
|
||||||
(Join-Path $script:ProxiFyreRoot "ProxiFyre.log")
|
|
||||||
)
|
|
||||||
$logs = @()
|
|
||||||
|
|
||||||
foreach ($path in $paths) {
|
|
||||||
if (Test-Path $path) {
|
|
||||||
$logs += [ordered]@{
|
|
||||||
path = $path
|
|
||||||
lines = @(Get-Content $path -Tail 120 -ErrorAction SilentlyContinue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $logs
|
|
||||||
}
|
|
||||||
|
|
||||||
function Invoke-VpnProxyAction {
|
|
||||||
param(
|
|
||||||
[Parameter(Mandatory=$true)][string]$Action,
|
|
||||||
[object]$Payload = @{}
|
|
||||||
)
|
|
||||||
|
|
||||||
switch ($Action) {
|
|
||||||
"status.get" {
|
|
||||||
return New-VpnProxyResult -Action $Action -Success $true -Result (Get-VpnProxyStatus)
|
|
||||||
}
|
|
||||||
"proxifyre.apply" {
|
|
||||||
return Invoke-ProxiFyreApply -Payload $Payload
|
|
||||||
}
|
|
||||||
"service.control" {
|
|
||||||
return Invoke-ServiceControl -Payload $Payload
|
|
||||||
}
|
|
||||||
"logs.get" {
|
|
||||||
return New-VpnProxyResult -Action $Action -Success $true -Result (Get-VpnProxyLogs)
|
|
||||||
}
|
|
||||||
default {
|
|
||||||
throw "Unknown action: $Action"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Export-ModuleMember -Function Invoke-VpnProxyAction, Get-VpnProxyStatus
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
|
|
||||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
|
||||||
Import-Module (Join-Path $ScriptDir "VpnProxy.Windows.psm1") -Force
|
|
||||||
|
|
||||||
try {
|
|
||||||
$raw = [Console]::In.ReadToEnd()
|
|
||||||
if ([string]::IsNullOrWhiteSpace($raw)) {
|
|
||||||
throw "Missing JSON input"
|
|
||||||
}
|
|
||||||
|
|
||||||
$request = $raw | ConvertFrom-Json
|
|
||||||
$payload = if ($request.PSObject.Properties.Name -contains "payload") { $request.payload } else { @{} }
|
|
||||||
$result = Invoke-VpnProxyAction -Action ([string]$request.action) -Payload $payload
|
|
||||||
$result | ConvertTo-Json -Depth 30 -Compress
|
|
||||||
exit 0
|
|
||||||
} catch {
|
|
||||||
$errorResult = [ordered]@{
|
|
||||||
success = $false
|
|
||||||
action = "error"
|
|
||||||
error = $_.Exception.Message
|
|
||||||
}
|
|
||||||
$errorResult | ConvertTo-Json -Depth 10 -Compress
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
param(
|
|
||||||
[switch]$OpenUi,
|
|
||||||
[switch]$Status,
|
|
||||||
[switch]$RestartServices
|
|
||||||
)
|
|
||||||
|
|
||||||
Set-StrictMode -Version Latest
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
|
|
||||||
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
|
||||||
$AppDir = Split-Path -Parent (Split-Path -Parent $ScriptDir)
|
|
||||||
if (-not (Test-Path (Join-Path $AppDir "package.json"))) {
|
|
||||||
throw "Cannot locate app root from $ScriptDir"
|
|
||||||
}
|
|
||||||
|
|
||||||
$Root = $env:VPN_PROXY_WINDOWS_ROOT
|
|
||||||
if ([string]::IsNullOrWhiteSpace($Root)) {
|
|
||||||
if ((Split-Path -Leaf $AppDir) -eq "app") {
|
|
||||||
$Root = Split-Path -Parent $AppDir
|
|
||||||
} else {
|
|
||||||
$Root = $AppDir
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$env:VPN_PROXY_WINDOWS_ROOT = $Root
|
|
||||||
$env:APP_MODE = "windows"
|
|
||||||
$env:DATA_DIR = Join-Path $Root "data"
|
|
||||||
$env:DIST_DIR = Join-Path $AppDir "dist"
|
|
||||||
$env:PROXY_PORT = "1080"
|
|
||||||
$env:PROXY_BIND_IP = "127.0.0.1"
|
|
||||||
$env:SING_BOX_CONFIG = Join-Path $Root "runtime\sing-box\config.json"
|
|
||||||
$env:SING_BOX_CACHE = Join-Path $Root "runtime\sing-box\cache.db"
|
|
||||||
$env:WINDOWS_HELPER = Join-Path $AppDir "scripts\windows\helper.ps1"
|
|
||||||
$env:PATH = "$(Join-Path $Root "runtime\sing-box");$env:PATH"
|
|
||||||
|
|
||||||
function Get-NodeCommand {
|
|
||||||
$portable = Join-Path $Root "runtime\node\node.exe"
|
|
||||||
if (Test-Path $portable) { return $portable }
|
|
||||||
return "node"
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($Status) {
|
|
||||||
$inputJson = @{ action = "status.get"; payload = @{} } | ConvertTo-Json -Compress
|
|
||||||
$inputJson | & $env:WINDOWS_HELPER
|
|
||||||
exit $LASTEXITCODE
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($RestartServices) {
|
|
||||||
$helper = $env:WINDOWS_HELPER
|
|
||||||
(@{ action = "service.control"; payload = @{ service = "proxifyre"; action = "restart" } } | ConvertTo-Json -Compress) | & $helper
|
|
||||||
(@{ action = "service.control"; payload = @{ service = "sing-box"; action = "restart" } } | ConvertTo-Json -Compress) | & $helper
|
|
||||||
exit 0
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($OpenUi) {
|
|
||||||
$node = Get-NodeCommand
|
|
||||||
Start-Process "http://127.0.0.1:3456"
|
|
||||||
& $node (Join-Path $AppDir "src\server\index.js")
|
|
||||||
exit $LASTEXITCODE
|
|
||||||
}
|
|
||||||
|
|
||||||
Write-Host "VPN Proxy Windows"
|
|
||||||
Write-Host " -OpenUi Start local UI"
|
|
||||||
Write-Host " -Status Print JSON status"
|
|
||||||
Write-Host " -RestartServices Restart ProxiFyre and sing-box"
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -1,18 +1,20 @@
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
const dataDir = process.env.DATA_DIR || path.resolve(".vpn-proxy");
|
const dataDir = process.env.DATA_DIR || path.resolve(".vpn-proxy");
|
||||||
const rawAppMode = String(process.env.APP_MODE || "gateway").toLowerCase();
|
const parsePort = (value, fallback) => {
|
||||||
const appMode = ["gateway", "client", "windows"].includes(rawAppMode)
|
const parsed = Number.parseInt(value, 10);
|
||||||
? rawAppMode
|
return Number.isInteger(parsed) ? parsed : fallback;
|
||||||
: "gateway";
|
};
|
||||||
|
const proxyPort = parsePort(
|
||||||
|
process.env.PROXY_PORT,
|
||||||
|
process.env.APP_MODE === "client" ? 8082 : 8080,
|
||||||
|
);
|
||||||
|
|
||||||
export const settings = {
|
export const settings = {
|
||||||
appMode,
|
appMode: process.env.APP_MODE === "client" ? "client" : "gateway",
|
||||||
port: Number(process.env.PORT || 3456),
|
port: parsePort(process.env.PORT, 3456),
|
||||||
proxyPort: Number(process.env.PROXY_PORT || 8080),
|
proxyPort,
|
||||||
clientProxyPortStart: Number(process.env.CLIENT_PROXY_PORT_START || 8080),
|
tproxyPort: parsePort(process.env.TPROXY_PORT, 7895),
|
||||||
clientProxyPortEnd: Number(process.env.CLIENT_PROXY_PORT_END || 8090),
|
|
||||||
tproxyPort: Number(process.env.TPROXY_PORT || 7895),
|
|
||||||
bindIp: process.env.PROXY_BIND_IP || "0.0.0.0",
|
bindIp: process.env.PROXY_BIND_IP || "0.0.0.0",
|
||||||
dataDir,
|
dataDir,
|
||||||
distDir: process.env.DIST_DIR || "/app/dist",
|
distDir: process.env.DIST_DIR || "/app/dist",
|
||||||
@@ -20,30 +22,9 @@ export const settings = {
|
|||||||
process.env.SING_BOX_CONFIG || path.join(dataDir, "sing-box-config.json"),
|
process.env.SING_BOX_CONFIG || path.join(dataDir, "sing-box-config.json"),
|
||||||
cachePath: process.env.SING_BOX_CACHE || "/var/lib/sing-box/cache.db",
|
cachePath: process.env.SING_BOX_CACHE || "/var/lib/sing-box/cache.db",
|
||||||
statePath: path.join(dataDir, "state.json"),
|
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"),
|
subscriptionCachePath: path.join(dataDir, "subscription-cache.json"),
|
||||||
windowsProfilesPath: path.join(dataDir, "windows-profiles.json"),
|
|
||||||
windowsTargetsPath: path.join(dataDir, "proxy-targets.json"),
|
|
||||||
windowsStatePath: path.join(dataDir, "windows-state.json"),
|
|
||||||
windowsActivityPath: path.join(dataDir, "windows-activity.json"),
|
|
||||||
windowsHelperPath:
|
|
||||||
process.env.WINDOWS_HELPER || path.resolve("scripts/windows/helper.ps1"),
|
|
||||||
proxifyreConfigPath:
|
|
||||||
process.env.PROXIFYRE_CONFIG ||
|
|
||||||
"C:\\Tools\\ProxiFyre\\app-config.json",
|
|
||||||
sharedProxyHost: process.env.SHARED_PROXY_HOST || "",
|
sharedProxyHost: process.env.SHARED_PROXY_HOST || "",
|
||||||
hwidPath: path.join(dataDir, "hwid"),
|
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",
|
logLevel: process.env.LOG_LEVEL || "info",
|
||||||
appName:
|
appName: "VPN Proxy Gateway",
|
||||||
appMode === "windows"
|
|
||||||
? "VPN Proxy Windows"
|
|
||||||
: appMode === "client"
|
|
||||||
? "VPN Proxy Client"
|
|
||||||
: "VPN Proxy Gateway",
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,153 +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"]);
|
|
||||||
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();
|
|
||||||
if (value === "bypass") return "direct";
|
|
||||||
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,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
1749
src/server/index.js
1749
src/server/index.js
File diff suppressed because it is too large
Load Diff
@@ -1,325 +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),
|
|
||||||
);
|
|
||||||
|
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
@@ -1,382 +1,81 @@
|
|||||||
import fs from "node:fs";
|
import fs from 'node:fs';
|
||||||
import path from "node:path";
|
import path from 'node:path';
|
||||||
import { settings } from "./config.js";
|
import { settings } from './config.js';
|
||||||
import {
|
|
||||||
MIXED_INBOUND,
|
|
||||||
TPROXY_INBOUND,
|
|
||||||
normalizeCidr,
|
|
||||||
readDeviceProfiles,
|
|
||||||
} from "./devices.js";
|
|
||||||
import { readClientSettings } from "./clientSettings.js";
|
|
||||||
|
|
||||||
const PROXY_TYPES = new Set([
|
const PROXY_TYPES = new Set(['vless', 'vmess', 'trojan', 'shadowsocks', 'hysteria2']);
|
||||||
"vless",
|
const MIXED_INBOUND = 'mixed-in';
|
||||||
"vmess",
|
const TPROXY_INBOUND = 'tproxy-in';
|
||||||
"trojan",
|
|
||||||
"shadowsocks",
|
|
||||||
"hysteria2",
|
|
||||||
]);
|
|
||||||
const CUSTOM_OUTBOUNDS = new Set(["direct", "vpn", "block"]);
|
|
||||||
|
|
||||||
function clone(value) {
|
|
||||||
return JSON.parse(JSON.stringify(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
function findOutbound(subscriptionConfig, selectedTag) {
|
function findOutbound(subscriptionConfig, selectedTag) {
|
||||||
const outbounds = Array.isArray(subscriptionConfig?.outbounds)
|
const outbounds = Array.isArray(subscriptionConfig?.outbounds)
|
||||||
? subscriptionConfig.outbounds
|
? subscriptionConfig.outbounds
|
||||||
: [];
|
: [];
|
||||||
const exact = outbounds.find(
|
const tag = String(selectedTag || '').trim();
|
||||||
(outbound) =>
|
return outbounds.find((outbound) => (
|
||||||
outbound.tag === selectedTag && PROXY_TYPES.has(outbound.type),
|
String(outbound.tag || '').trim() === tag && 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),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function readCustomRuleSets() {
|
export function buildGatewayConfig(subscriptionConfig, selectedTag) {
|
||||||
try {
|
const clientMode = settings.appMode === 'client';
|
||||||
if (!fs.existsSync(settings.customRuleSetsPath)) return [];
|
const vpnOutbound = structuredClone(findOutbound(subscriptionConfig, selectedTag));
|
||||||
const data = JSON.parse(
|
if (!vpnOutbound) throw new Error(`Outbound не найден: ${selectedTag}`);
|
||||||
fs.readFileSync(settings.customRuleSetsPath, "utf8"),
|
if (!vpnOutbound.tag) vpnOutbound.tag = 'vpn-out';
|
||||||
);
|
if (vpnOutbound.type === 'vless' && !vpnOutbound.packet_encoding) {
|
||||||
return Array.isArray(data) ? data : [];
|
vpnOutbound.packet_encoding = 'xudp';
|
||||||
} 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 proxyOnlyMode =
|
|
||||||
settings.appMode === "client" || settings.appMode === "windows";
|
|
||||||
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 = [
|
const inbounds = [
|
||||||
...(proxyOnlyMode
|
...(!clientMode ? [{
|
||||||
? []
|
type: 'tproxy',
|
||||||
: [
|
tag: TPROXY_INBOUND,
|
||||||
{
|
listen: '::',
|
||||||
type: "tproxy",
|
|
||||||
tag: "tproxy-in",
|
|
||||||
listen: "::",
|
|
||||||
listen_port: settings.tproxyPort,
|
listen_port: settings.tproxyPort,
|
||||||
sniff: true,
|
sniff: true,
|
||||||
sniff_override_destination: true,
|
sniff_override_destination: true,
|
||||||
},
|
}] : []),
|
||||||
]),
|
|
||||||
{
|
{
|
||||||
type: "mixed",
|
type: 'mixed',
|
||||||
tag: "mixed-in",
|
tag: MIXED_INBOUND,
|
||||||
listen: settings.bindIp,
|
listen: settings.bindIp,
|
||||||
listen_port: mixedProxyPort,
|
listen_port: settings.proxyPort,
|
||||||
sniff: true,
|
sniff: true,
|
||||||
set_system_proxy: false,
|
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 {
|
return {
|
||||||
log: {
|
log: { level: settings.logLevel, timestamp: true },
|
||||||
level: settings.logLevel,
|
|
||||||
timestamp: true,
|
|
||||||
},
|
|
||||||
experimental: {
|
experimental: {
|
||||||
cache_file: {
|
cache_file: { enabled: true, path: settings.cachePath },
|
||||||
enabled: true,
|
|
||||||
path: settings.cachePath,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
dns: {
|
|
||||||
independent_cache: true,
|
|
||||||
},
|
},
|
||||||
|
dns: { independent_cache: true },
|
||||||
inbounds,
|
inbounds,
|
||||||
outbounds: [
|
outbounds: [
|
||||||
...(sharedOutbound ? [sharedOutbound] : vpnOutbound ? [vpnOutbound] : []),
|
vpnOutbound,
|
||||||
{ type: "direct", tag: "direct" },
|
{ type: 'direct', tag: 'direct' },
|
||||||
{ type: "block", tag: "block" },
|
{ type: 'block', tag: 'block' },
|
||||||
],
|
],
|
||||||
route: {
|
route: {
|
||||||
rule_set:
|
rule_set: [],
|
||||||
bypassAll || proxyOnlyMode
|
rules,
|
||||||
? []
|
final: vpnOutbound.tag,
|
||||||
: ruleSets(customRuleSets, vpnOutbound.tag),
|
...(clientMode ? {} : { auto_detect_interface: true }),
|
||||||
rules: bypassAll
|
|
||||||
? [{ ip_is_private: true, outbound: "direct" }]
|
|
||||||
: proxyOnlyMode
|
|
||||||
? proxyOnlyRules
|
|
||||||
: routeRules(subscriptionConfig.customRules, vpnOutbound.tag, {
|
|
||||||
includeTransparent: !proxyOnlyMode,
|
|
||||||
}),
|
|
||||||
final: "direct",
|
|
||||||
auto_detect_interface: true,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function writeSingboxConfig(config) {
|
export function writeSingboxConfig(config) {
|
||||||
fs.mkdirSync(path.dirname(settings.configPath), { recursive: true });
|
fs.mkdirSync(path.dirname(settings.configPath), { recursive: true });
|
||||||
fs.writeFileSync(
|
fs.writeFileSync(settings.configPath, JSON.stringify(config, null, 2), 'utf8');
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function removeSingboxConfig() {
|
export function removeSingboxConfig() {
|
||||||
if (fs.existsSync(settings.configPath)) {
|
fs.rmSync(settings.configPath, { force: true });
|
||||||
fs.rmSync(settings.configPath);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ export function parseSubscriptionBody(body) {
|
|||||||
const servers = outbounds
|
const servers = outbounds
|
||||||
.filter((outbound) => PROXY_TYPES.has(outbound.type))
|
.filter((outbound) => PROXY_TYPES.has(outbound.type))
|
||||||
.map((outbound) => ({
|
.map((outbound) => ({
|
||||||
tag: outbound.tag || `${outbound.type}-${outbound.server || 'server'}`,
|
tag: String(outbound.tag || `${outbound.type}-${outbound.server || 'server'}`).trim(),
|
||||||
type: outbound.type,
|
type: outbound.type,
|
||||||
server: outbound.server || 'unknown',
|
server: outbound.server || 'unknown',
|
||||||
server_port: outbound.server_port || 443,
|
server_port: outbound.server_port || 443,
|
||||||
@@ -136,7 +136,7 @@ export function parseSubscriptionBody(body) {
|
|||||||
return { config: parsedConfig, servers };
|
return { config: parsedConfig, servers };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchSubscription(url) {
|
async function requestSubscription(url) {
|
||||||
let parsedUrl;
|
let parsedUrl;
|
||||||
try {
|
try {
|
||||||
parsedUrl = new URL(url);
|
parsedUrl = new URL(url);
|
||||||
@@ -157,6 +157,21 @@ export async function fetchSubscription(url) {
|
|||||||
throw new Error(`Subscription request failed: HTTP ${response.status}`);
|
throw new Error(`Subscription request failed: HTTP ${response.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchSubscriptionInfo(url) {
|
||||||
|
const response = await requestSubscription(url);
|
||||||
|
await response.body?.cancel();
|
||||||
|
return {
|
||||||
|
userInfo: parseUserInfo(response.headers.get('subscription-userinfo')),
|
||||||
|
fetchedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchSubscription(url) {
|
||||||
|
const response = await requestSubscription(url);
|
||||||
|
|
||||||
const body = await response.text();
|
const body = await response.text();
|
||||||
const userInfo = parseUserInfo(response.headers.get('subscription-userinfo'));
|
const userInfo = parseUserInfo(response.headers.get('subscription-userinfo'));
|
||||||
const parsed = parseSubscriptionBody(body);
|
const parsed = parseSubscriptionBody(body);
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
import { spawn } from "node:child_process";
|
|
||||||
import { settings } from "./config.js";
|
|
||||||
|
|
||||||
function defaultRunner(command, args, options = {}) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
const child = spawn(command, args, {
|
|
||||||
stdio: ["pipe", "pipe", "pipe"],
|
|
||||||
windowsHide: true,
|
|
||||||
});
|
|
||||||
let stdout = "";
|
|
||||||
let stderr = "";
|
|
||||||
child.stdout.on("data", (chunk) => {
|
|
||||||
stdout += chunk.toString("utf8");
|
|
||||||
});
|
|
||||||
child.stderr.on("data", (chunk) => {
|
|
||||||
stderr += chunk.toString("utf8");
|
|
||||||
});
|
|
||||||
child.on("error", (error) => {
|
|
||||||
resolve({ status: 1, stdout, stderr: error.message });
|
|
||||||
});
|
|
||||||
child.on("close", (status) => {
|
|
||||||
resolve({ status, stdout, stderr });
|
|
||||||
});
|
|
||||||
child.stdin.end(options.input || "");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createWindowsHelper(options = {}) {
|
|
||||||
const helperPath = options.helperPath || settings.windowsHelperPath;
|
|
||||||
const command = options.command || "pwsh";
|
|
||||||
const runner = options.runner || defaultRunner;
|
|
||||||
return {
|
|
||||||
async run(action, payload = {}) {
|
|
||||||
const input = JSON.stringify({ action, payload });
|
|
||||||
const result = await runner(
|
|
||||||
command,
|
|
||||||
["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", helperPath],
|
|
||||||
{ input },
|
|
||||||
);
|
|
||||||
if (result.status !== 0) {
|
|
||||||
throw new Error(
|
|
||||||
`Windows helper failed: ${(result.stderr || result.stdout || "helper exited without stderr").trim()}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return JSON.parse(result.stdout);
|
|
||||||
} catch {
|
|
||||||
throw new Error(`Windows helper returned invalid JSON: ${result.stdout}`);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const windowsHelper = createWindowsHelper();
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
const ITEM_TYPES = new Set(["process", "folder", "exe"]);
|
|
||||||
const PROTOCOLS = new Set(["TCP", "UDP"]);
|
|
||||||
|
|
||||||
function slug(value, fallback) {
|
|
||||||
const cleaned = String(value || "")
|
|
||||||
.trim()
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/[^a-z0-9]+/g, "-")
|
|
||||||
.replace(/^-+|-+$/g, "");
|
|
||||||
return cleaned || fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanString(value) {
|
|
||||||
return String(value || "").trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
function processName(value) {
|
|
||||||
const base = cleanString(value).split(/[\\/]/).pop() || "";
|
|
||||||
return base.replace(/\.exe$/i, "").trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
function unique(values) {
|
|
||||||
return Array.from(new Set(values.filter(Boolean)));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeWindowsProfiles(input) {
|
|
||||||
return (Array.isArray(input) ? input : [])
|
|
||||||
.map((profile, index) => {
|
|
||||||
const name = cleanString(profile.name) || `Profile ${index + 1}`;
|
|
||||||
const items = (Array.isArray(profile.items) ? profile.items : [])
|
|
||||||
.filter((item) => ITEM_TYPES.has(item?.type))
|
|
||||||
.map((item) => ({
|
|
||||||
type: item.type,
|
|
||||||
value:
|
|
||||||
item.type === "process"
|
|
||||||
? processName(item.value)
|
|
||||||
: cleanString(item.value),
|
|
||||||
recursive: item.type === "folder" ? item.recursive !== false : false,
|
|
||||||
}))
|
|
||||||
.filter((item) => item.value);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: slug(profile.id || name, `profile-${index + 1}`),
|
|
||||||
name,
|
|
||||||
enabled: profile.enabled !== false,
|
|
||||||
proxyTargetId: cleanString(profile.proxyTargetId) || "local-singbox",
|
|
||||||
protocols: unique(
|
|
||||||
(Array.isArray(profile.protocols)
|
|
||||||
? profile.protocols
|
|
||||||
: ["TCP", "UDP"])
|
|
||||||
.map((protocol) => cleanString(protocol).toUpperCase())
|
|
||||||
.filter((protocol) => PROTOCOLS.has(protocol)),
|
|
||||||
),
|
|
||||||
items,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.map((profile) => ({
|
|
||||||
...profile,
|
|
||||||
protocols: profile.protocols.length ? profile.protocols : ["TCP", "UDP"],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeProxyTargets(input) {
|
|
||||||
const local = {
|
|
||||||
id: "local-singbox",
|
|
||||||
name: "Local sing-box",
|
|
||||||
protocol: "socks5",
|
|
||||||
host: "127.0.0.1",
|
|
||||||
port: 1080,
|
|
||||||
managed: true,
|
|
||||||
};
|
|
||||||
const seen = new Set([local.id]);
|
|
||||||
const custom = (Array.isArray(input) ? input : [])
|
|
||||||
.map((target, index) => ({
|
|
||||||
id: slug(target.id || target.name, `target-${index + 1}`),
|
|
||||||
name: cleanString(target.name) || `Proxy target ${index + 1}`,
|
|
||||||
protocol:
|
|
||||||
cleanString(target.protocol || "socks5").toLowerCase() === "http"
|
|
||||||
? "http"
|
|
||||||
: "socks5",
|
|
||||||
host: cleanString(target.host),
|
|
||||||
port: Number.parseInt(target.port, 10),
|
|
||||||
managed: false,
|
|
||||||
}))
|
|
||||||
.filter((target) => {
|
|
||||||
if (!target.host || !Number.isInteger(target.port)) return false;
|
|
||||||
if (target.port <= 0 || target.port > 65535) return false;
|
|
||||||
if (seen.has(target.id)) return false;
|
|
||||||
seen.add(target.id);
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
return [local, ...custom];
|
|
||||||
}
|
|
||||||
|
|
||||||
function joinPath(base, name, pathSep) {
|
|
||||||
return base.endsWith(pathSep) ? `${base}${name}` : `${base}${pathSep}${name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function walkExeFiles(dir, { fsAdapter, recursive, pathSep }) {
|
|
||||||
const entries = fsAdapter.readdirSync(dir, { withFileTypes: true });
|
|
||||||
const results = [];
|
|
||||||
for (const entry of entries) {
|
|
||||||
const fullPath = joinPath(dir, entry.name, pathSep);
|
|
||||||
if (entry.isFile() && /\.exe$/i.test(entry.name)) results.push(fullPath);
|
|
||||||
if (recursive && entry.isDirectory()) {
|
|
||||||
results.push(...walkExeFiles(fullPath, { fsAdapter, recursive, pathSep }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveProfileItems(items, options = {}) {
|
|
||||||
const fsAdapter = options.fsAdapter || fs;
|
|
||||||
const pathSep = options.pathSep || path.sep;
|
|
||||||
const resolved = [];
|
|
||||||
for (const item of Array.isArray(items) ? items : []) {
|
|
||||||
if (item.type === "process") {
|
|
||||||
const appName = processName(item.value);
|
|
||||||
if (appName) resolved.push({ ...item, appName, source: item.value });
|
|
||||||
}
|
|
||||||
if (item.type === "exe") {
|
|
||||||
const appName = processName(item.value);
|
|
||||||
if (appName) resolved.push({ ...item, appName, source: item.value });
|
|
||||||
}
|
|
||||||
if (item.type === "folder" && fsAdapter.existsSync(item.value)) {
|
|
||||||
const stat = fsAdapter.statSync(item.value);
|
|
||||||
if (stat.isDirectory()) {
|
|
||||||
for (const filePath of walkExeFiles(item.value, {
|
|
||||||
fsAdapter,
|
|
||||||
recursive: item.recursive !== false,
|
|
||||||
pathSep,
|
|
||||||
})) {
|
|
||||||
resolved.push({
|
|
||||||
...item,
|
|
||||||
appName: processName(filePath),
|
|
||||||
source: filePath,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const byName = new Map();
|
|
||||||
for (const item of resolved) {
|
|
||||||
if (!byName.has(item.appName)) byName.set(item.appName, item);
|
|
||||||
}
|
|
||||||
return Array.from(byName.values());
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildProxiFyreConfig(profiles, targets, options = {}) {
|
|
||||||
const normalizedTargets = normalizeProxyTargets(targets);
|
|
||||||
const targetById = new Map(
|
|
||||||
normalizedTargets.map((target) => [target.id, target]),
|
|
||||||
);
|
|
||||||
const groups = new Map();
|
|
||||||
for (const profile of normalizeWindowsProfiles(profiles).filter(
|
|
||||||
(item) => item.enabled,
|
|
||||||
)) {
|
|
||||||
const target =
|
|
||||||
targetById.get(profile.proxyTargetId) || targetById.get("local-singbox");
|
|
||||||
const resolved = resolveProfileItems(profile.items, options);
|
|
||||||
if (!target || resolved.length === 0) continue;
|
|
||||||
const key = `${target.id}|${profile.protocols.join(",")}`;
|
|
||||||
const existing = groups.get(key) || {
|
|
||||||
appNames: [],
|
|
||||||
socks5ProxyEndpoint: `${target.host}:${target.port}`,
|
|
||||||
supportedProtocols: profile.protocols,
|
|
||||||
};
|
|
||||||
existing.appNames.push(...resolved.map((item) => item.appName));
|
|
||||||
existing.appNames = unique(existing.appNames).sort((a, b) =>
|
|
||||||
a.localeCompare(b),
|
|
||||||
);
|
|
||||||
groups.set(key, existing);
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
logLevel: "Info",
|
|
||||||
proxies: Array.from(groups.values()),
|
|
||||||
excludes: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function summarizeProfiles(profiles, targets, options = {}) {
|
|
||||||
const normalizedTargets = normalizeProxyTargets(targets);
|
|
||||||
const targetById = new Map(
|
|
||||||
normalizedTargets.map((target) => [target.id, target]),
|
|
||||||
);
|
|
||||||
return normalizeWindowsProfiles(profiles).map((profile) => {
|
|
||||||
const resolvedItems = resolveProfileItems(profile.items, options);
|
|
||||||
const target =
|
|
||||||
targetById.get(profile.proxyTargetId) || targetById.get("local-singbox");
|
|
||||||
return {
|
|
||||||
...profile,
|
|
||||||
target,
|
|
||||||
resolvedCount: resolvedItems.length,
|
|
||||||
resolvedItems,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createActivityEntry(type, message, details = {}) {
|
|
||||||
return {
|
|
||||||
id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
|
||||||
ts: new Date().toISOString(),
|
|
||||||
type,
|
|
||||||
message,
|
|
||||||
details,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
541
src/web/App.jsx
541
src/web/App.jsx
@@ -1,91 +1,22 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { createRoot } from 'react-dom/client';
|
import { createRoot } from 'react-dom/client';
|
||||||
import './styles.css';
|
import './styles.css';
|
||||||
import { api } from './api.js';
|
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 { ClientOverviewPage } from './components/ClientOverviewPage.jsx';
|
||||||
import { WindowsOverviewPage } from './components/WindowsOverviewPage.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() {
|
function App() {
|
||||||
const [page, setPage] = useState(getInitialPage());
|
|
||||||
const [state, setState] = useState(null);
|
const [state, setState] = useState(null);
|
||||||
const [subscriptionUrl, setSubscriptionUrl] = useState('');
|
const [subscriptionUrl, setSubscriptionUrl] = useState('');
|
||||||
const [servers, setServers] = useState([]);
|
const [servers, setServers] = useState([]);
|
||||||
const [customRules, setCustomRules] = useState([]);
|
|
||||||
const [devicesConfig, setDevicesConfig] = useState({
|
|
||||||
defaultTransparentMode: 'vpn',
|
|
||||||
proxyDefaultMode: 'vpn',
|
|
||||||
devices: [],
|
|
||||||
});
|
|
||||||
const [clientSettings, setClientSettings] = useState({
|
|
||||||
homeBypassEnabled: false,
|
|
||||||
sharedProxyEnabled: false,
|
|
||||||
});
|
|
||||||
const [selectedTag, setSelectedTag] = useState('');
|
|
||||||
const [pendingTag, setPendingTag] = useState('');
|
const [pendingTag, setPendingTag] = useState('');
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState('');
|
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() {
|
async function loadState() {
|
||||||
const data = await api.state();
|
const data = await api.state();
|
||||||
setState(data);
|
setState(data);
|
||||||
setServers(data.servers || []);
|
setServers(data.servers || []);
|
||||||
if (!rulesDirtyRef.current) setCustomRules(data.customRules || []);
|
setPendingTag((current) => current || data.selectedTag || '');
|
||||||
setDevicesConfig(data.devicesConfig || {
|
|
||||||
defaultTransparentMode: 'vpn',
|
|
||||||
proxyDefaultMode: 'vpn',
|
|
||||||
devices: data.devices || [],
|
|
||||||
});
|
|
||||||
setClientSettings(data.clientSettings || { homeBypassEnabled: false, sharedProxyEnabled: false });
|
|
||||||
setSelectedTag((prev) => prev || data.selectedTag || '');
|
|
||||||
setPendingTag((prev) => prev || data.selectedTag || '');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -94,488 +25,72 @@ function App() {
|
|||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
async function run(action) {
|
||||||
if (state?.mode === 'client' && page !== 'overview') {
|
|
||||||
navigate('overview');
|
|
||||||
}
|
|
||||||
if (state?.mode === 'windows' && (page === 'servers' || page === 'routing')) {
|
|
||||||
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 } = {}) {
|
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError('');
|
setError('');
|
||||||
try {
|
try {
|
||||||
const result = await fn();
|
await action();
|
||||||
if (!quiet && label) pushToast({ kind: 'success', title: label });
|
await loadState();
|
||||||
return result;
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
pushToast({ kind: 'danger', title: 'Ошибка', message: err.message, duration: 6000 });
|
|
||||||
throw err;
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// === Subscription ===
|
|
||||||
async function fetchSubscription() {
|
async function fetchSubscription() {
|
||||||
return withBusy('Подписка обновлена', async () => {
|
return run(async () => {
|
||||||
const data = await api.subscription.fetch(subscriptionUrl || state?.subscriptionHost || '');
|
const data = await api.subscription.fetch(subscriptionUrl);
|
||||||
setServers(data.servers || []);
|
setServers(data.servers || []);
|
||||||
if (!selectedTag && data.servers?.length) {
|
setPendingTag('');
|
||||||
setSelectedTag(data.servers[0].tag);
|
|
||||||
setPendingTag(data.servers[0].tag);
|
|
||||||
}
|
|
||||||
await loadState();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function refreshSubscriptionInfo() {
|
||||||
|
const data = await api.subscription.refreshInfo();
|
||||||
|
setState((current) => current ? {
|
||||||
|
...current,
|
||||||
|
userInfo: data.userInfo,
|
||||||
|
fetchedAt: data.fetchedAt,
|
||||||
|
} : current);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
async function forgetSubscription() {
|
async function forgetSubscription() {
|
||||||
if (!confirm('Удалить подписку и остановить sing-box?')) return;
|
if (!confirm('Удалить подписку и остановить VPN?')) return;
|
||||||
return withBusy('Подписка удалена', async () => {
|
return run(async () => {
|
||||||
await api.subscription.forget();
|
await api.subscription.forget();
|
||||||
setSubscriptionUrl('');
|
setSubscriptionUrl('');
|
||||||
setServers([]);
|
setServers([]);
|
||||||
setSelectedTag('');
|
|
||||||
setPendingTag('');
|
setPendingTag('');
|
||||||
await loadState();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// === Apply with rollback offer ===
|
if (!state) return <div className="app-loading">VPN</div>;
|
||||||
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 (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() {
|
|
||||||
if (!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 } : prev);
|
|
||||||
} 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function saveClientSettings(nextSettings) {
|
|
||||||
return withBusy(null, async () => {
|
|
||||||
const data = await api.clientSettings.save(nextSettings);
|
|
||||||
setClientSettings(data.clientSettings || { homeBypassEnabled: false, sharedProxyEnabled: false });
|
|
||||||
await loadState();
|
|
||||||
}, { quiet: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkSharedProxy(url) {
|
|
||||||
return withBusy('Общий proxy подключён', async () => {
|
|
||||||
const data = await api.clientSettings.checkSharedProxy(url);
|
|
||||||
setClientSettings(data.clientSettings || { homeBypassEnabled: false, sharedProxyEnabled: false });
|
|
||||||
await loadState();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// === 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 isWindowsMode = state?.mode === 'windows';
|
|
||||||
|
|
||||||
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 ===
|
|
||||||
return (
|
return (
|
||||||
<div className="app">
|
<div className="app client-app">
|
||||||
<Topbar
|
<div className="app-body client-mode">
|
||||||
state={state}
|
|
||||||
status={status}
|
|
||||||
activeServer={activeServer}
|
|
||||||
dirty={dirty}
|
|
||||||
onRestart={restartSingbox}
|
|
||||||
onTryApply={rollback}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className={`app-body${isClientMode ? ' client-mode' : ''}${isWindowsMode ? ' windows-mode' : ''}`}>
|
|
||||||
{!isClientMode && <Sidebar active={page} onChange={navigate} badges={sidebarBadges} mode={state?.mode} />}
|
|
||||||
|
|
||||||
<main className="app-main">
|
<main className="app-main">
|
||||||
{page === 'overview' && isWindowsMode && (
|
|
||||||
<WindowsOverviewPage pushToast={pushToast} />
|
|
||||||
)}
|
|
||||||
{(page === 'overview' || isClientMode) && !isWindowsMode && (
|
|
||||||
isClientMode ? (
|
|
||||||
<ClientOverviewPage
|
<ClientOverviewPage
|
||||||
state={state}
|
state={state}
|
||||||
status={status}
|
|
||||||
activeServer={activeServer}
|
|
||||||
busy={busy}
|
busy={busy}
|
||||||
|
error={error}
|
||||||
subscriptionUrl={subscriptionUrl}
|
subscriptionUrl={subscriptionUrl}
|
||||||
setSubscriptionUrl={setSubscriptionUrl}
|
setSubscriptionUrl={setSubscriptionUrl}
|
||||||
servers={servers}
|
servers={servers}
|
||||||
pendingTag={pendingTag}
|
pendingTag={pendingTag}
|
||||||
setPendingTag={setPendingTag}
|
setPendingTag={setPendingTag}
|
||||||
clientSettings={clientSettings}
|
|
||||||
onSaveClientSettings={saveClientSettings}
|
|
||||||
onCheckSharedProxy={checkSharedProxy}
|
|
||||||
onFetchSubscription={fetchSubscription}
|
|
||||||
onApply={applyServer}
|
|
||||||
onRestart={restartSingbox}
|
|
||||||
onStop={stopSingbox}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<OverviewPage
|
|
||||||
state={state}
|
|
||||||
status={status}
|
|
||||||
busy={busy}
|
|
||||||
onRestart={restartSingbox}
|
|
||||||
onStop={stopSingbox}
|
|
||||||
onShowConfig={() => setConfigOpen(true)}
|
|
||||||
onNav={navigate}
|
|
||||||
onBypassToggle={toggleBypass}
|
|
||||||
onFlushDirectCache={flushDirectCache}
|
|
||||||
/>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
{page === 'servers' && !isClientMode && !isWindowsMode && (
|
|
||||||
<ServersPage
|
|
||||||
state={state}
|
|
||||||
servers={servers}
|
|
||||||
selectedTag={selectedTag}
|
|
||||||
setSelectedTag={setSelectedTag}
|
|
||||||
pendingTag={pendingTag}
|
|
||||||
setPendingTag={setPendingTag}
|
|
||||||
busy={busy}
|
|
||||||
onApply={applyServer}
|
|
||||||
onRollback={rollback}
|
|
||||||
pings={pings}
|
|
||||||
setPings={setPings}
|
|
||||||
pushToast={pushToast}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{page === 'routing' && !isClientMode && !isWindowsMode && (
|
|
||||||
<RoutingPage
|
|
||||||
rules={customRules}
|
|
||||||
saveStatus={rulesSaveStatus}
|
|
||||||
busy={busy}
|
|
||||||
onAdd={addRule}
|
|
||||||
onAddTemplate={addRuleFromTemplate}
|
|
||||||
onUpdate={updateRule}
|
|
||||||
onRemove={removeRule}
|
|
||||||
onSaveNow={saveRulesNow}
|
|
||||||
onReorder={reorderRules}
|
|
||||||
devicesConfig={devicesConfig}
|
|
||||||
onUpdateDeviceDefaults={updateDeviceDefaults}
|
|
||||||
onAddDevice={addDevice}
|
|
||||||
onUpdateDevice={updateDevice}
|
|
||||||
onRemoveDevice={removeDevice}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{page === 'logs' && !isClientMode && <LogsPage devices={devicesConfig.devices} />}
|
|
||||||
{page === 'settings' && !isClientMode && (
|
|
||||||
<SettingsPage
|
|
||||||
state={state}
|
|
||||||
subscriptionUrl={subscriptionUrl}
|
|
||||||
setSubscriptionUrl={setSubscriptionUrl}
|
|
||||||
busy={busy}
|
|
||||||
onFetchSubscription={fetchSubscription}
|
onFetchSubscription={fetchSubscription}
|
||||||
|
onRefreshSubscriptionInfo={refreshSubscriptionInfo}
|
||||||
onForgetSubscription={forgetSubscription}
|
onForgetSubscription={forgetSubscription}
|
||||||
onShowConfig={() => setConfigOpen(true)}
|
onApply={(tag) => run(() => api.apply(tag))}
|
||||||
onClearConfig={clearConfig}
|
onRestart={() => run(api.singbox.restart)}
|
||||||
pushToast={pushToast}
|
onStop={() => run(api.singbox.stop)}
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Sticky bar — для routing/servers */}
|
|
||||||
{(page === 'routing' && dirtyRouting && !isWindowsMode) && (
|
|
||||||
<div className="sticky-bar">
|
|
||||||
<div className="flex">
|
|
||||||
<span className={`dot ${rulesSaveStatus === 'error' ? 'danger' : 'warning'}`} />
|
|
||||||
<strong>
|
|
||||||
{rulesSaveStatus === 'saving' && 'Сохраняем…'}
|
|
||||||
{rulesSaveStatus === 'pending' && 'Есть несохранённые изменения'}
|
|
||||||
{rulesSaveStatus === 'saved' && dirtyDevices && 'Изменения устройств сохранены'}
|
|
||||||
{rulesSaveStatus === 'error' && 'Ошибка сохранения'}
|
|
||||||
</strong>
|
|
||||||
<small className="muted">Конфиг sing-box нужно пересобрать и применить.</small>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
{rulesSaveStatus !== 'saved' && (
|
|
||||||
<button className="btn btn-secondary sm" onClick={saveRulesNow}>Сохранить сейчас</button>
|
|
||||||
)}
|
|
||||||
{state?.selectedTag && (
|
|
||||||
<button className="btn btn-primary sm" onClick={() => applyServer(state.selectedTag)} disabled={busy}>
|
|
||||||
Применить config
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{(page === 'servers' && dirtyServer && !isWindowsMode) && (
|
|
||||||
<div className="sticky-bar">
|
|
||||||
<div className="flex">
|
|
||||||
<span className="dot warning" />
|
|
||||||
<strong>Сервер не применён</strong>
|
|
||||||
<small className="muted">Выбран: {pendingTag}</small>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => setPendingTag(state?.selectedTag || '')}>Отменить</button>
|
|
||||||
<button className="btn btn-primary sm" onClick={() => applyServer(pendingTag)} disabled={busy}>
|
|
||||||
Применить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{!isClientMode && !isWindowsMode && (
|
|
||||||
<StatusPane
|
|
||||||
state={state}
|
|
||||||
busy={busy}
|
|
||||||
onStop={stopSingbox}
|
|
||||||
onRestart={restartSingbox}
|
|
||||||
onShowConfig={() => setConfigOpen(true)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ConfigViewer open={configOpen} onClose={() => setConfigOpen(false)} />
|
|
||||||
<Toasts items={toasts} onDismiss={dismissToast} />
|
|
||||||
|
|
||||||
{rollbackOffer && (
|
|
||||||
<div className="toasts">
|
|
||||||
<div className="toast warning">
|
|
||||||
<span className="dot warning" style={{ marginTop: 4 }} />
|
|
||||||
<div className="body">
|
|
||||||
<strong>Сервер применён</strong>
|
|
||||||
<small>Можно откатиться к «{rollbackOffer.to}»</small>
|
|
||||||
<button className="btn btn-link" onClick={rollback} style={{ padding: 0, marginTop: 4 }}>
|
|
||||||
↶ Откатить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<button onClick={() => setRollbackOffer(null)}>×</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
151
src/web/api.js
151
src/web/api.js
@@ -2,161 +2,36 @@ async function request(url, options = {}) {
|
|||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
"content-type": "application/json",
|
'content-type': 'application/json',
|
||||||
...(options.headers || {}),
|
...(options.headers || {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const data = await response.json().catch(() => ({}));
|
const data = await response.json().catch(() => ({}));
|
||||||
if (!response.ok || (data && data.success === false)) {
|
if (!response.ok || data?.success === false) {
|
||||||
throw new Error(
|
throw new Error(data?.error || `Запрос ${url} завершился ошибкой ${response.status}`);
|
||||||
data?.error || `Запрос ${url} завершился ошибкой ${response.status}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
state: () => request("/api/state"),
|
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),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
|
|
||||||
clientSettings: {
|
|
||||||
get: () => request("/api/client-settings"),
|
|
||||||
save: (clientSettings) =>
|
|
||||||
request("/api/client-settings", {
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify({ clientSettings }),
|
|
||||||
}),
|
|
||||||
checkSharedProxy: (url) =>
|
|
||||||
request("/api/client-settings/shared-proxy/check", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ url }),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
|
|
||||||
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"),
|
|
||||||
},
|
|
||||||
|
|
||||||
subscription: {
|
subscription: {
|
||||||
fetch: (url) =>
|
fetch: (url) => request('/api/subscription/fetch', {
|
||||||
request("/api/subscription/fetch", {
|
method: 'POST',
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ url }),
|
body: JSON.stringify({ url }),
|
||||||
}),
|
}),
|
||||||
forget: () => request("/api/subscription", { method: "DELETE" }),
|
refreshInfo: () => request('/api/subscription/refresh-info', { method: 'POST' }),
|
||||||
|
forget: () => request('/api/subscription', { method: 'DELETE' }),
|
||||||
},
|
},
|
||||||
|
apply: (selectedTag) => request('/api/apply', {
|
||||||
apply: (selectedTag) =>
|
method: 'POST',
|
||||||
request("/api/apply", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ selectedTag }),
|
body: JSON.stringify({ selectedTag }),
|
||||||
}),
|
}),
|
||||||
rollback: () => request("/api/apply/rollback", { method: "POST" }),
|
|
||||||
|
|
||||||
singbox: {
|
singbox: {
|
||||||
stop: () => request("/api/singbox/stop", { method: "POST" }),
|
stop: () => request('/api/singbox/stop', { method: 'POST' }),
|
||||||
restart: () => request("/api/singbox/restart", { method: "POST" }),
|
restart: () => request('/api/singbox/restart', { method: 'POST' }),
|
||||||
clear: () => request("/api/singbox/clear", { method: "POST" }),
|
|
||||||
},
|
},
|
||||||
|
|
||||||
servers: {
|
servers: {
|
||||||
ping: (host, port) =>
|
pingAll: () => request('/api/servers/ping-all', { method: 'POST' }),
|
||||||
request("/api/servers/ping", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ host, port }),
|
|
||||||
}),
|
|
||||||
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 }),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
|
|
||||||
windows: {
|
|
||||||
status: () => request("/api/windows/status"),
|
|
||||||
profiles: {
|
|
||||||
get: () => request("/api/windows/profiles"),
|
|
||||||
save: (profiles) =>
|
|
||||||
request("/api/windows/profiles", {
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify({ profiles }),
|
|
||||||
}),
|
|
||||||
scan: (profiles) =>
|
|
||||||
request("/api/windows/profiles/scan", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ profiles }),
|
|
||||||
}),
|
|
||||||
apply: () =>
|
|
||||||
request("/api/windows/profiles/apply", {
|
|
||||||
method: "POST",
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
targets: {
|
|
||||||
get: () => request("/api/windows/targets"),
|
|
||||||
save: (targets) =>
|
|
||||||
request("/api/windows/targets", {
|
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify({ targets }),
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
service: (service, action) =>
|
|
||||||
request("/api/windows/service", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({ service, action }),
|
|
||||||
}),
|
|
||||||
logs: () => request("/api/windows/logs"),
|
|
||||||
},
|
|
||||||
|
|
||||||
configValidate: () => request("/api/config/validate", { method: "POST" }),
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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 (
|
|
||||||
<div className="chips" onClick={(e) => e.currentTarget.querySelector('input')?.focus()}>
|
|
||||||
{value.map((item) => {
|
|
||||||
const invalid = validate ? !validate(item) : false;
|
|
||||||
return (
|
|
||||||
<span key={item} className={`chip ${invalid ? 'error' : ''}`}>
|
|
||||||
{item}
|
|
||||||
<button type="button" onClick={() => remove(item)} title="Убрать">×</button>
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
<input
|
|
||||||
className="chip-input"
|
|
||||||
value={draft}
|
|
||||||
onChange={(e) => setDraft(e.target.value)}
|
|
||||||
onKeyDown={onKeyDown}
|
|
||||||
onPaste={onPaste}
|
|
||||||
onBlur={() => draft.trim() && commit(draft)}
|
|
||||||
placeholder={value.length ? '' : placeholder}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,365 +1,423 @@
|
|||||||
import React, { useEffect, useMemo, useState } from 'react';
|
import React, { useEffect, useRef, useState } from 'react';
|
||||||
import { flagFor } from '../utils/country.js';
|
import { api } from '../api.js';
|
||||||
import { formatRelative } from '../utils/format.js';
|
import {
|
||||||
import { resolveClientRoute } from '../utils/clientRoute.js';
|
connectionAction,
|
||||||
|
formatConnectionDuration,
|
||||||
function CopyValue({ value }) {
|
localProxyUrls,
|
||||||
const [copied, setCopied] = useState(false);
|
subscriptionDomain,
|
||||||
|
subscriptionDaysLeft,
|
||||||
async function copy() {
|
subscriptionUsage,
|
||||||
await navigator.clipboard.writeText(value);
|
} from '../utils/clientControls.js';
|
||||||
setCopied(true);
|
import { formatBytes } from '../utils/format.js';
|
||||||
setTimeout(() => setCopied(false), 1200);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button className="client-copy" type="button" onClick={copy}>
|
|
||||||
<span>{value}</span>
|
|
||||||
<strong>{copied ? 'OK' : 'Copy'}</strong>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function StatusPanel({ route, state }) {
|
|
||||||
const statusLabel = {
|
|
||||||
connected: 'Работает',
|
|
||||||
stopped: 'Остановлен',
|
|
||||||
empty: 'Не настроен',
|
|
||||||
}[route.status];
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className={`client-status-panel ${route.status}`}>
|
|
||||||
<div className="client-status-main">
|
|
||||||
<span className={`client-status-dot ${route.status}`} />
|
|
||||||
<div>
|
|
||||||
<div className="client-eyebrow">Текущий маршрут</div>
|
|
||||||
<h1>{route.title}</h1>
|
|
||||||
<p>{route.description}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="client-status-facts">
|
|
||||||
<div>
|
|
||||||
<small>Куда</small>
|
|
||||||
<strong>{route.target}</strong>
|
|
||||||
<span>{route.targetDetail}</span>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<small>Локальный proxy</small>
|
|
||||||
<strong>{route.localProxy}</strong>
|
|
||||||
<span>HTTP и SOCKS5</span>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<small>Сервис</small>
|
|
||||||
<strong>{statusLabel}</strong>
|
|
||||||
<span>{state?.appliedAt ? `применено ${formatRelative(state.appliedAt)}` : 'нет примененного config'}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function RouteLine({ route }) {
|
|
||||||
return (
|
|
||||||
<div className="client-route-line">
|
|
||||||
{route.path.map((item, index) => (
|
|
||||||
<React.Fragment key={`${item}-${index}`}>
|
|
||||||
<span>{item}</span>
|
|
||||||
{index < route.path.length - 1 && <b>→</b>}
|
|
||||||
</React.Fragment>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ModeButton({ active, selected, title, subtitle, onClick, disabled }) {
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`client-mode-button ${selected ? 'selected' : ''} ${active ? 'active' : ''}`}
|
|
||||||
disabled={disabled}
|
|
||||||
onClick={onClick}
|
|
||||||
>
|
|
||||||
<strong>{title}</strong>
|
|
||||||
<span>{subtitle}</span>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function GatewaySettings({ settings, busy, onCheck }) {
|
|
||||||
const [draftUrl, setDraftUrl] = useState(settings?.sharedProxyControlUrl || '');
|
|
||||||
const sharedProxy = settings?.sharedProxy;
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setDraftUrl(settings?.sharedProxyControlUrl || '');
|
|
||||||
}, [settings?.sharedProxyControlUrl]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="client-mode-settings">
|
|
||||||
<div className="field">
|
|
||||||
<label className="field-label">Адрес gateway UI</label>
|
|
||||||
<div className="client-inline-form">
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="http://192.168.50.111:3456"
|
|
||||||
value={draftUrl}
|
|
||||||
onChange={(e) => setDraftUrl(e.target.value)}
|
|
||||||
onKeyDown={(e) => e.key === 'Enter' && draftUrl && onCheck(draftUrl)}
|
|
||||||
/>
|
|
||||||
<button className="btn btn-primary" disabled={busy || !draftUrl} onClick={() => onCheck(draftUrl)}>
|
|
||||||
Подключить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{sharedProxy && (
|
|
||||||
<div className="client-current-target">
|
|
||||||
<small>Найден общий proxy</small>
|
|
||||||
<strong>{sharedProxy.host}:{sharedProxy.port}</strong>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function VpnSettings({
|
|
||||||
state,
|
|
||||||
servers,
|
|
||||||
subscriptionUrl,
|
|
||||||
setSubscriptionUrl,
|
|
||||||
pendingTag,
|
|
||||||
setPendingTag,
|
|
||||||
busy,
|
|
||||||
onFetchSubscription,
|
|
||||||
onApply,
|
|
||||||
}) {
|
|
||||||
const selected = pendingTag || state?.selectedTag || '';
|
|
||||||
const activeServer = servers.find((server) => server.tag === selected);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="client-mode-settings">
|
|
||||||
<div className="field">
|
|
||||||
<label className="field-label">Подписка или VLESS</label>
|
|
||||||
<div className="client-inline-form">
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="https://… или vless://…"
|
|
||||||
value={subscriptionUrl}
|
|
||||||
onChange={(e) => setSubscriptionUrl(e.target.value)}
|
|
||||||
onKeyDown={(e) => e.key === 'Enter' && subscriptionUrl && onFetchSubscription()}
|
|
||||||
/>
|
|
||||||
<button className="btn btn-secondary" disabled={busy || !subscriptionUrl} onClick={onFetchSubscription}>
|
|
||||||
Загрузить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="field">
|
|
||||||
<label className="field-label">VPN-сервер</label>
|
|
||||||
<div className="client-inline-form">
|
|
||||||
<select
|
|
||||||
className="select"
|
|
||||||
value={selected}
|
|
||||||
disabled={!servers.length}
|
|
||||||
onChange={(e) => setPendingTag(e.target.value)}
|
|
||||||
>
|
|
||||||
<option value="">Выберите сервер</option>
|
|
||||||
{servers.map((server) => (
|
|
||||||
<option key={server.tag} value={server.tag}>
|
|
||||||
{flagFor(server)} {server.tag}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<button className="btn btn-primary" disabled={busy || !selected} onClick={() => onApply(selected)}>
|
|
||||||
Подключить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{activeServer && <small className="field-hint">Выбран {flagFor(activeServer)} {activeServer.tag}</small>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DirectSettings({ busy, onEnable }) {
|
|
||||||
return (
|
|
||||||
<div className="client-mode-settings direct">
|
|
||||||
<div>
|
|
||||||
<strong>Прямой режим</strong>
|
|
||||||
<p className="muted">Приложения продолжают использовать локальный proxy, но трафик идет без VPN и без gateway.</p>
|
|
||||||
</div>
|
|
||||||
<button className="btn btn-primary" disabled={busy} onClick={onEnable}>
|
|
||||||
Включить напрямую
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ProxySettings({ state, settings, busy, onSave }) {
|
|
||||||
const range = state?.clientProxyPortRange || { start: 8080, end: 8090 };
|
|
||||||
const port = settings?.proxyPort || state?.proxyPort || 8080;
|
|
||||||
const [draftPort, setDraftPort] = useState(String(port));
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setDraftPort(String(port));
|
|
||||||
}, [port]);
|
|
||||||
|
|
||||||
const parsed = Number.parseInt(draftPort, 10);
|
|
||||||
const invalid = !Number.isInteger(parsed) || parsed < range.start || parsed > range.end;
|
|
||||||
const dirty = !invalid && parsed !== port;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<aside className="client-side-panel">
|
|
||||||
<div>
|
|
||||||
<div className="client-panel-title">Адрес для приложений</div>
|
|
||||||
<div className="client-copy-stack">
|
|
||||||
<CopyValue value={`http://127.0.0.1:${port}`} />
|
|
||||||
<CopyValue value={`socks5://127.0.0.1:${port}`} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="field">
|
|
||||||
<label className="field-label">Порт proxy</label>
|
|
||||||
<div className="client-port-row">
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
type="number"
|
|
||||||
min={range.start}
|
|
||||||
max={range.end}
|
|
||||||
value={draftPort}
|
|
||||||
onChange={(e) => setDraftPort(e.target.value)}
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary"
|
|
||||||
disabled={busy || !dirty}
|
|
||||||
onClick={() => onSave({ ...settings, proxyPort: parsed })}
|
|
||||||
>
|
|
||||||
Save
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<small className={invalid ? 'field-error' : 'field-hint'}>{range.start}–{range.end}</small>
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ClientOverviewPage({
|
export function ClientOverviewPage({
|
||||||
state,
|
state,
|
||||||
activeServer,
|
|
||||||
busy,
|
busy,
|
||||||
|
error,
|
||||||
subscriptionUrl,
|
subscriptionUrl,
|
||||||
setSubscriptionUrl,
|
setSubscriptionUrl,
|
||||||
servers,
|
servers,
|
||||||
pendingTag,
|
pendingTag,
|
||||||
setPendingTag,
|
setPendingTag,
|
||||||
clientSettings,
|
|
||||||
onSaveClientSettings,
|
|
||||||
onCheckSharedProxy,
|
|
||||||
onFetchSubscription,
|
onFetchSubscription,
|
||||||
|
onRefreshSubscriptionInfo,
|
||||||
|
onForgetSubscription,
|
||||||
onApply,
|
onApply,
|
||||||
|
onRestart,
|
||||||
|
onStop,
|
||||||
}) {
|
}) {
|
||||||
const route = useMemo(
|
const isGateway = state?.mode === 'gateway';
|
||||||
() => resolveClientRoute({ state, activeServer }),
|
const connected = Boolean(state?.singboxRunning);
|
||||||
[state, activeServer],
|
const hasSubscription = Boolean(state?.hasSubscription);
|
||||||
|
const selectedTag = pendingTag || state?.selectedTag || '';
|
||||||
|
const showPower = hasSubscription && Boolean(selectedTag);
|
||||||
|
const canStart = Boolean(selectedTag || state?.configExists);
|
||||||
|
const [now, setNow] = useState(Date.now());
|
||||||
|
const [editingSubscription, setEditingSubscription] = useState(!state?.hasSubscription);
|
||||||
|
const [pings, setPings] = useState({});
|
||||||
|
const [copiedProxy, setCopiedProxy] = useState('');
|
||||||
|
const [refreshingInfo, setRefreshingInfo] = useState(false);
|
||||||
|
const [usageUpdated, setUsageUpdated] = useState(false);
|
||||||
|
const [serverRevealVersion, setServerRevealVersion] = useState(0);
|
||||||
|
const [serversLeaving, setServersLeaving] = useState(false);
|
||||||
|
const subscriptionInputRef = useRef(null);
|
||||||
|
const subscriptionRef = useRef(null);
|
||||||
|
const serverKey = servers.map((server) => `${server.tag}:${server.server}:${server.server_port}`).join('|');
|
||||||
|
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(
|
||||||
|
state?.userInfo && ['upload', 'download', 'total', 'expire'].some((key) => key in state.userInfo),
|
||||||
);
|
);
|
||||||
const [setupMode, setSetupMode] = useState(route.mode === 'none' ? 'gateway' : route.mode);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (route.mode !== 'none') setSetupMode(route.mode);
|
setNow(Date.now());
|
||||||
}, [route.mode]);
|
if (!connected || !state?.singboxStartedAt) return undefined;
|
||||||
|
|
||||||
function enableDirect() {
|
const timer = setInterval(() => setNow(Date.now()), 1000);
|
||||||
return onSaveClientSettings({
|
return () => clearInterval(timer);
|
||||||
...clientSettings,
|
}, [connected, state?.singboxStartedAt]);
|
||||||
homeBypassEnabled: true,
|
|
||||||
sharedProxyEnabled: false,
|
useEffect(() => {
|
||||||
|
if (!servers.length) {
|
||||||
|
setPings({});
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cancelled = false;
|
||||||
|
setPings(Object.fromEntries(servers.map((server) => [server.tag, { checking: true }])));
|
||||||
|
api.servers.pingAll()
|
||||||
|
.then((data) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
setPings(Object.fromEntries((data.results || []).map((ping) => [
|
||||||
|
String(ping.tag || '').trim(),
|
||||||
|
ping,
|
||||||
|
])));
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) {
|
||||||
|
setPings(Object.fromEntries(servers.map((server) => [server.tag, { ok: false }])));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [serverKey]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (editingSubscription) subscriptionInputRef.current?.focus();
|
||||||
|
}, [editingSubscription]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasSubscription) setEditingSubscription(true);
|
||||||
|
}, [hasSubscription]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editingSubscription || !state?.hasSubscription || subscriptionUrl) return undefined;
|
||||||
|
const timer = setTimeout(() => setEditingSubscription(false), 5000);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [editingSubscription, state?.hasSubscription, subscriptionUrl]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editingSubscription || !hasSubscription) return undefined;
|
||||||
|
const closeOnOutsideClick = (event) => {
|
||||||
|
if (subscriptionRef.current?.contains(event.target)) return;
|
||||||
|
setSubscriptionUrl('');
|
||||||
|
setEditingSubscription(false);
|
||||||
|
};
|
||||||
|
document.addEventListener('pointerdown', closeOnOutsideClick);
|
||||||
|
return () => document.removeEventListener('pointerdown', closeOnOutsideClick);
|
||||||
|
}, [editingSubscription, hasSubscription, setSubscriptionUrl]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!state?.hasSubscription) return undefined;
|
||||||
|
const refresh = () => onRefreshSubscriptionInfo().catch(() => {});
|
||||||
|
refresh();
|
||||||
|
const timer = setInterval(refresh, 60_000);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [state?.hasSubscription]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const from = displayedUsed;
|
||||||
|
const to = usage.used;
|
||||||
|
if (from === to) return undefined;
|
||||||
|
const startedAt = performance.now();
|
||||||
|
let frame;
|
||||||
|
const tick = (now) => {
|
||||||
|
const progress = Math.min(1, (now - startedAt) / 900);
|
||||||
|
const eased = 1 - Math.pow(1 - progress, 4);
|
||||||
|
setDisplayedUsed(from + (to - from) * eased);
|
||||||
|
if (progress < 1) frame = requestAnimationFrame(tick);
|
||||||
|
};
|
||||||
|
frame = requestAnimationFrame(tick);
|
||||||
|
return () => cancelAnimationFrame(frame);
|
||||||
|
}, [usage.used]);
|
||||||
|
|
||||||
|
async function toggleConnection() {
|
||||||
|
const action = connectionAction({ connected, selectedTag, configExists: state?.configExists });
|
||||||
|
if (action?.type === 'stop') return onStop();
|
||||||
|
if (action?.type === 'apply') return onApply(action.selectedTag);
|
||||||
|
if (action?.type === 'restart') return onRestart();
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectGateway() {
|
function selectServer(tag) {
|
||||||
setSetupMode('gateway');
|
setPendingTag(tag);
|
||||||
if (clientSettings?.sharedProxyControlUrl) {
|
if (connected && tag) onApply(tag);
|
||||||
return onCheckSharedProxy(clientSettings.sharedProxyControlUrl);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectVpn() {
|
async function submitSubscription(event) {
|
||||||
setSetupMode('vpn');
|
event.preventDefault();
|
||||||
if (state?.selectedTag) {
|
if (!subscriptionUrl.trim()) return;
|
||||||
return onApply(state.selectedTag);
|
await onFetchSubscription();
|
||||||
|
setSubscriptionUrl('');
|
||||||
|
setEditingSubscription(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyProxy(kind) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(kind === 'gateway' ? gatewayAddress : proxyUrls[kind]);
|
||||||
|
setCopiedProxy(kind);
|
||||||
|
setTimeout(() => setCopiedProxy(''), 800);
|
||||||
|
} catch {
|
||||||
|
setCopiedProxy('error');
|
||||||
|
setTimeout(() => setCopiedProxy(''), 800);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshInfo() {
|
||||||
|
const startedAt = performance.now();
|
||||||
|
setRefreshingInfo(true);
|
||||||
|
try {
|
||||||
|
await onRefreshSubscriptionInfo();
|
||||||
|
setUsageUpdated(false);
|
||||||
|
requestAnimationFrame(() => setUsageUpdated(true));
|
||||||
|
setTimeout(() => setUsageUpdated(false), 900);
|
||||||
|
setServersLeaving(true);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 420 + Math.max(0, servers.length - 1) * 90));
|
||||||
|
setServerRevealVersion((version) => version + 1);
|
||||||
|
setServersLeaving(false);
|
||||||
|
} finally {
|
||||||
|
const elapsed = performance.now() - startedAt;
|
||||||
|
const completeCyclesAt = Math.max(900, Math.ceil(elapsed / 900) * 900);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, completeCyclesAt - elapsed));
|
||||||
|
setRefreshingInfo(false);
|
||||||
}
|
}
|
||||||
return onSaveClientSettings({
|
|
||||||
...clientSettings,
|
|
||||||
homeBypassEnabled: false,
|
|
||||||
sharedProxyEnabled: false,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="client-dashboard">
|
<div className="client-shell">
|
||||||
<StatusPanel route={route} state={state} />
|
<main className={`client-panel${showPower ? '' : ' is-setup'}`}>
|
||||||
<RouteLine route={route} />
|
{showPower && (
|
||||||
|
<section className="client-power-section" aria-labelledby="connection-title">
|
||||||
|
<button
|
||||||
|
className="client-power"
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={connected}
|
||||||
|
aria-label={connected ? `Выключить ${isGateway ? 'Gateway' : 'VPN'}` : `Включить ${isGateway ? 'Gateway' : 'VPN'}`}
|
||||||
|
disabled={busy || (!connected && !canStart)}
|
||||||
|
onClick={toggleConnection}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M12 2v10M5.6 5.6a9 9 0 1 0 12.8 0" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<div className="client-state-copy" aria-live="polite">
|
||||||
|
<h2 key={connected ? 'connected' : 'disconnected'} id="connection-title">
|
||||||
|
{isGateway
|
||||||
|
? connected ? 'Gateway включён' : 'Gateway выключен'
|
||||||
|
: connected ? 'VPN включён' : 'VPN выключен'}
|
||||||
|
</h2>
|
||||||
|
<div className="client-state-detail">
|
||||||
|
{connected ? (
|
||||||
|
<time key="duration" className="client-duration">
|
||||||
|
{formatConnectionDuration(state?.singboxStartedAt, now)}
|
||||||
|
</time>
|
||||||
|
) : (
|
||||||
|
<p key="hint">
|
||||||
|
{canStart ? 'Нажмите, чтобы включить' : 'Добавьте ссылку и выберите сервер'}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<section className="client-workspace">
|
<section className="client-proxies" aria-label={isGateway ? 'Адреса Gateway и Proxy' : 'Локальный прокси'}>
|
||||||
<div className="client-main-panel">
|
{isGateway && (
|
||||||
<div className="client-mode-grid">
|
<div className="client-access-point">
|
||||||
<ModeButton
|
<span className="client-proxy-label">Gateway</span>
|
||||||
active={route.mode === 'gateway'}
|
<strong className="client-proxy-address">{gatewayAddress}</strong>
|
||||||
selected={setupMode === 'gateway'}
|
<button
|
||||||
title="Общий gateway"
|
className={copiedProxy === 'gateway' ? 'is-copied' : ''}
|
||||||
subtitle={clientSettings?.sharedProxy ? `${clientSettings.sharedProxy.host}:${clientSettings.sharedProxy.port}` : 'серверная proxy'}
|
type="button"
|
||||||
|
aria-label={`Скопировать Gateway: ${gatewayAddress}`}
|
||||||
|
onClick={() => copyProxy('gateway')}
|
||||||
|
>
|
||||||
|
<span className="client-copy-label">КОПИРОВАТЬ</span>
|
||||||
|
{copiedProxy === 'gateway' && <span className="client-copy-feedback">Copied</span>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="client-access-point">
|
||||||
|
<span className="client-proxy-label">{isGateway ? 'Proxy' : 'Адрес'}</span>
|
||||||
|
<strong className="client-proxy-address">
|
||||||
|
{proxyUrls.http.replace(/^https?:\/\//, '')}
|
||||||
|
</strong>
|
||||||
|
<div className="client-proxy-actions">
|
||||||
|
{[
|
||||||
|
['socks5', 'SOCKS5'],
|
||||||
|
['http', 'HTTP'],
|
||||||
|
].map(([kind, label]) => (
|
||||||
|
<button
|
||||||
|
className={copiedProxy === kind ? 'is-copied' : ''}
|
||||||
|
type="button"
|
||||||
|
key={kind}
|
||||||
|
aria-label={`Скопировать ${label}: ${proxyUrls[kind]}`}
|
||||||
|
onClick={() => copyProxy(kind)}
|
||||||
|
>
|
||||||
|
<span className="client-copy-label">{label}</span>
|
||||||
|
{copiedProxy === kind && <span className="client-copy-feedback">Copied</span>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <p className="client-error" role="alert">{error}</p>}
|
||||||
|
|
||||||
|
<div className="client-form">
|
||||||
|
<div
|
||||||
|
ref={subscriptionRef}
|
||||||
|
className={`client-subscription ${editingSubscription ? 'is-editing' : ''}${editingSubscription && state?.hasSubscription && !subscriptionUrl ? ' is-timing-out' : ''}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="client-subscription-summary"
|
||||||
|
aria-hidden={editingSubscription}
|
||||||
|
inert={editingSubscription ? true : undefined}
|
||||||
|
>
|
||||||
|
<div className="client-subscription-heading">
|
||||||
|
<span>Ваша подписка</span>
|
||||||
|
<button
|
||||||
|
className="client-subscription-refresh"
|
||||||
|
type="button"
|
||||||
|
aria-label="Обновить статистику подписки"
|
||||||
|
title="Обновить статистику"
|
||||||
|
disabled={refreshingInfo}
|
||||||
|
onClick={refreshInfo}
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M21 12a9 9 0 0 0-15.2-6.5L3 8m0-5v5h5M3 12a9 9 0 0 0 15.2 6.5L21 16m0 5v-5h-5" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="client-subscription-delete"
|
||||||
|
type="button"
|
||||||
|
aria-label="Удалить подписку"
|
||||||
|
title="Удалить подписку"
|
||||||
disabled={busy}
|
disabled={busy}
|
||||||
onClick={selectGateway}
|
onClick={onForgetSubscription}
|
||||||
/>
|
>
|
||||||
<ModeButton
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
active={route.mode === 'vpn'}
|
<path d="M4 7h16M9 7V4h6v3m-9 0 1 13h10l1-13M10 11v5M14 11v5" />
|
||||||
selected={setupMode === 'vpn'}
|
</svg>
|
||||||
title="Локальный VPN"
|
</button>
|
||||||
subtitle={state?.selectedTag || 'выбрать сервер'}
|
</div>
|
||||||
disabled={busy}
|
<button
|
||||||
onClick={selectVpn}
|
className="client-subscription-domain-button"
|
||||||
/>
|
type="button"
|
||||||
<ModeButton
|
tabIndex={editingSubscription ? -1 : 0}
|
||||||
active={route.mode === 'direct'}
|
onClick={() => setEditingSubscription(true)}
|
||||||
selected={setupMode === 'direct'}
|
>
|
||||||
title="Напрямую"
|
<strong>{subscriptionDomain(state?.subscriptionHost)}</strong>
|
||||||
subtitle="без VPN"
|
</button>
|
||||||
disabled={busy}
|
</div>
|
||||||
onClick={() => {
|
|
||||||
setSetupMode('direct');
|
<form
|
||||||
enableDirect();
|
className="client-subscription-edit"
|
||||||
|
autoComplete="off"
|
||||||
|
aria-hidden={!editingSubscription}
|
||||||
|
inert={!editingSubscription ? true : undefined}
|
||||||
|
onSubmit={submitSubscription}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={subscriptionInputRef}
|
||||||
|
id="subscription-url"
|
||||||
|
type="url"
|
||||||
|
inputMode="url"
|
||||||
|
autoComplete="off"
|
||||||
|
tabIndex={editingSubscription ? 0 : -1}
|
||||||
|
aria-label="Ссылка подписки"
|
||||||
|
placeholder="Вставьте ссылку подписки"
|
||||||
|
className={subscriptionUrl ? 'has-value' : ''}
|
||||||
|
value={subscriptionUrl}
|
||||||
|
onChange={(event) => setSubscriptionUrl(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Escape' && state?.hasSubscription) {
|
||||||
|
setSubscriptionUrl('');
|
||||||
|
setEditingSubscription(false);
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
{subscriptionUrl && (
|
||||||
|
<span className="client-subscription-domain">
|
||||||
|
{subscriptionDomain(subscriptionUrl)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{subscriptionUrl.trim() && (
|
||||||
|
<button type="submit" aria-label="Сохранить подписку" disabled={busy}>✓</button>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{setupMode === 'gateway' && (
|
{hasSubscription && hasUsage && (
|
||||||
<GatewaySettings
|
<section className={`client-usage${usageUpdated ? ' is-updated' : ''}`} aria-label="Статистика подписки">
|
||||||
settings={clientSettings}
|
<span>Использовано</span>
|
||||||
busy={busy}
|
<strong>
|
||||||
onCheck={onCheckSharedProxy}
|
{formatBytes(displayedUsed)}
|
||||||
/>
|
<small> / {usage.total ? formatBytes(usage.total) : 'без лимита'}</small>
|
||||||
|
</strong>
|
||||||
|
{usage.percent !== null && (
|
||||||
|
<div
|
||||||
|
className="client-usage-bar"
|
||||||
|
role="progressbar"
|
||||||
|
aria-label="Использованный трафик"
|
||||||
|
aria-valuemin="0"
|
||||||
|
aria-valuemax="100"
|
||||||
|
aria-valuenow={Math.round(usage.percent)}
|
||||||
|
>
|
||||||
|
<i style={{ width: `${usage.percent}%` }} />
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
{setupMode === 'vpn' && (
|
<div className="client-usage-details">
|
||||||
<VpnSettings
|
{usage.expiresAt && !Number.isNaN(usage.expiresAt.getTime()) && (
|
||||||
state={state}
|
<span>
|
||||||
servers={servers}
|
до {usage.expiresAt.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })}
|
||||||
subscriptionUrl={subscriptionUrl}
|
{' · '}{subscriptionDaysLeft(usage.expiresAt)}
|
||||||
setSubscriptionUrl={setSubscriptionUrl}
|
</span>
|
||||||
pendingTag={pendingTag}
|
|
||||||
setPendingTag={setPendingTag}
|
|
||||||
busy={busy}
|
|
||||||
onFetchSubscription={onFetchSubscription}
|
|
||||||
onApply={onApply}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{setupMode === 'direct' && (
|
|
||||||
<DirectSettings busy={busy} onEnable={enableDirect} />
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ProxySettings
|
|
||||||
state={state}
|
|
||||||
settings={clientSettings}
|
|
||||||
busy={busy}
|
|
||||||
onSave={onSaveClientSettings}
|
|
||||||
/>
|
|
||||||
</section>
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{hasSubscription && (
|
||||||
|
<section className="client-servers" aria-label="Выберите сервер">
|
||||||
|
{!showPower && <span className="client-server-prompt">Выберите сервер</span>}
|
||||||
|
<div
|
||||||
|
className={`client-server-grid${serversLeaving ? ' is-leaving' : ''}`}
|
||||||
|
key={`${serverKey}:${serverRevealVersion}`}
|
||||||
|
>
|
||||||
|
{servers.map((server, index) => {
|
||||||
|
const ping = pings[server.tag];
|
||||||
|
const selected = server.tag === selectedTag;
|
||||||
|
const pingText = ping?.checking
|
||||||
|
? 'Проверка…'
|
||||||
|
: ping?.ok ? `${ping.latency} ms` : 'Недоступен';
|
||||||
|
const pingClass = ping?.ok
|
||||||
|
? ping.latency < 100 ? 'good' : ping.latency < 250 ? 'medium' : 'slow'
|
||||||
|
: '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className={`client-server ${selected ? 'is-selected' : ''}`}
|
||||||
|
type="button"
|
||||||
|
key={server.tag}
|
||||||
|
disabled={busy}
|
||||||
|
aria-pressed={selected}
|
||||||
|
style={{ '--server-index': index }}
|
||||||
|
onClick={() => selectServer(server.tag)}
|
||||||
|
>
|
||||||
|
<strong>{server.tag}</strong>
|
||||||
|
<small className={pingClass}>{pingText}</small>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,85 +0,0 @@
|
|||||||
import React, { useEffect, useMemo, useState } from 'react';
|
|
||||||
import { api } from '../api.js';
|
|
||||||
|
|
||||||
export function ConfigViewer({ open, onClose }) {
|
|
||||||
const [config, setConfig] = useState(null);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [search, setSearch] = useState('');
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
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 (
|
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
|
||||||
<div className="modal lg" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="modal-head">
|
|
||||||
<div>
|
|
||||||
<h3>sing-box config</h3>
|
|
||||||
<small className="muted">Автогенерируемый, перезаписывается при apply</small>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="Поиск…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
style={{ width: 160 }}
|
|
||||||
/>
|
|
||||||
<button className="btn btn-ghost sm" disabled={!config} onClick={copy}>Копировать</button>
|
|
||||||
<button className="btn btn-ghost sm" disabled={!config} onClick={download}>Скачать</button>
|
|
||||||
<button className="btn btn-secondary sm" onClick={onClose}>Закрыть</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="modal-body">
|
|
||||||
{error && <div className="conflict-banner danger">{error}</div>}
|
|
||||||
{!error && !config && <p className="muted">Конфиг ещё не сгенерирован.</p>}
|
|
||||||
{config && (
|
|
||||||
<pre className="config-view">
|
|
||||||
{Array.isArray(highlighted)
|
|
||||||
? highlighted.map((part, i) => (
|
|
||||||
<React.Fragment key={i}>
|
|
||||||
{part}
|
|
||||||
{i < highlighted.length - 1 && <mark style={{ background: 'var(--warning-dim)', color: 'var(--warning)' }}>{search}</mark>}
|
|
||||||
</React.Fragment>
|
|
||||||
))
|
|
||||||
: text}
|
|
||||||
</pre>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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 (
|
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>
|
|
||||||
<div className="filter-bar" style={{ marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="Поиск: host, порт, правило…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
style={{ flex: 1, minWidth: 180 }}
|
|
||||||
/>
|
|
||||||
<select className="select" value={filter} onChange={(e) => setFilter(e.target.value)}>
|
|
||||||
<option value="all">Все ({traffic.length})</option>
|
|
||||||
<option value="direct">direct ({counts.direct})</option>
|
|
||||||
<option value="vpn">VPN ({counts.vpn})</option>
|
|
||||||
<option value="block">block ({counts.block})</option>
|
|
||||||
</select>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input type="checkbox" checked={grouped} onChange={(e) => setGrouped(e.target.checked)} />
|
|
||||||
Группировать
|
|
||||||
</label>
|
|
||||||
{grouped && (
|
|
||||||
<select className="select" value={sortBy} onChange={(e) => setSortBy(e.target.value)} style={{ width: 'auto' }}>
|
|
||||||
<option value="count">По частоте</option>
|
|
||||||
<option value="time">По времени</option>
|
|
||||||
</select>
|
|
||||||
)}
|
|
||||||
<label className="checkbox">
|
|
||||||
<input type="checkbox" checked={autoscroll} onChange={(e) => setAutoscroll(e.target.checked)} />
|
|
||||||
Автоскролл
|
|
||||||
</label>
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => setPaused((p) => !p)}>
|
|
||||||
{paused ? '▶ Продолжить' : '⏸ Пауза'}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
onClick={() => { setTraffic([]); fetch('/api/traffic', { method: 'DELETE' }).catch(() => {}); }}
|
|
||||||
>
|
|
||||||
Очистить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{traffic.length === 0 ? (
|
|
||||||
<div className="muted" style={{ padding: '20px 0', textAlign: 'center' }}>
|
|
||||||
Ожидаем трафик… Убедитесь что sing-box запущен и уровень логов не выше INFO.
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div ref={containerRef} style={{ flex: 1, overflow: 'auto' }}>
|
|
||||||
<table className="table" style={{ fontSize: 12 }}>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th style={{ width: 70 }}>Время</th>
|
|
||||||
<th style={{ width: 70 }}>Туннель</th>
|
|
||||||
<th style={{ width: 110 }}>Устройство</th>
|
|
||||||
<th>Хост / IP</th>
|
|
||||||
<th style={{ width: 55 }}>Порт</th>
|
|
||||||
<th>Правило</th>
|
|
||||||
<th style={{ width: 40 }}></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{filtered.map((e, i) => {
|
|
||||||
const badge = CATEGORY_BADGE[e.category] || CATEGORY_BADGE.other;
|
|
||||||
const deviceName = getDeviceName(e.sourceIp, devices);
|
|
||||||
return (
|
|
||||||
<tr key={i} style={{ opacity: e.category === 'block' ? 0.6 : 1 }}>
|
|
||||||
<td className="muted text-mono" style={{ whiteSpace: 'nowrap' }}>{formatTime(e.ts)}</td>
|
|
||||||
<td>
|
|
||||||
<span className={`badge ${badge.cls}`} style={{ fontSize: 11 }}>{badge.label}</span>
|
|
||||||
</td>
|
|
||||||
<td className="text-mono" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 110 }}>
|
|
||||||
{deviceName
|
|
||||||
? <span style={{ fontSize: 11 }}>{deviceName}</span>
|
|
||||||
: e.sourceIp
|
|
||||||
? <span className="muted" style={{ fontSize: 10 }}>{e.sourceIp}</span>
|
|
||||||
: <span className="muted" style={{ fontSize: 11 }}>—</span>}
|
|
||||||
</td>
|
|
||||||
<td className="text-mono" style={{ wordBreak: 'break-all' }}>{e.host || '—'}</td>
|
|
||||||
<td className="muted text-mono">{e.port || '—'}</td>
|
|
||||||
<td>
|
|
||||||
{e.matchedRule
|
|
||||||
? <span className="badge info" style={{ fontSize: 11 }}>{e.matchedRule}</span>
|
|
||||||
: <span className="muted" style={{ fontSize: 11 }}>—</span>}
|
|
||||||
</td>
|
|
||||||
<td className="muted text-mono" style={{ textAlign: 'right', fontSize: 11 }}>
|
|
||||||
{e.count > 1 && <span className="repeat">×{e.count}</span>}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="card" style={{ display: 'flex', flexDirection: 'column', minHeight: 'calc(100vh - 160px)' }}>
|
|
||||||
<div className="card-header">
|
|
||||||
<h2>Логи sing-box</h2>
|
|
||||||
<div className="tabs" style={{ marginLeft: 'auto', marginBottom: 0 }}>
|
|
||||||
<button className={`tab ${tab === 'traffic' ? 'active' : ''}`} onClick={() => setTab('traffic')}>Трафик</button>
|
|
||||||
<button className={`tab ${tab === 'logs' ? 'active' : ''}`} onClick={() => setTab('logs')}>Системные логи</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{tab === 'traffic' && <TrafficTab devices={devices} />}
|
|
||||||
|
|
||||||
{tab === 'logs' && (
|
|
||||||
<>
|
|
||||||
<div className="filter-bar" style={{ marginBottom: 12 }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="Поиск по тексту…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
style={{ flex: 1, minWidth: 200 }}
|
|
||||||
/>
|
|
||||||
<select className="select" value={filter} onChange={(e) => setFilter(e.target.value)}>
|
|
||||||
<option value="all">Все уровни</option>
|
|
||||||
<option value="info">info</option>
|
|
||||||
<option value="warning">warning</option>
|
|
||||||
<option value="error">error</option>
|
|
||||||
<option value="debug">debug</option>
|
|
||||||
</select>
|
|
||||||
<label className="checkbox"><input type="checkbox" checked={grouped} onChange={(e) => setGrouped(e.target.checked)} /> Группировать</label>
|
|
||||||
<label className="checkbox"><input type="checkbox" checked={autoscroll} onChange={(e) => setAutoscroll(e.target.checked)} /> Автоскролл</label>
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => setPaused((p) => !p)}>{paused ? '▶ Продолжить' : '⏸ Пауза'}</button>
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => setEntries([])}>Очистить</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div ref={containerRef} className="logs-stream">
|
|
||||||
{filtered.length === 0 && <p className="muted">Логов пока нет.</p>}
|
|
||||||
{filtered.map((entry, index) => {
|
|
||||||
const text = normalizeLine(entry.line);
|
|
||||||
if (grouped && entry.count > 1) {
|
|
||||||
return (
|
|
||||||
<div key={`${entry.ts}-${index}`} className="log-group">
|
|
||||||
<span className="log-time mono">{formatTime(entry.ts)}</span>
|
|
||||||
<span className={`log-level text-${entry.level === 'error' ? 'danger' : entry.level === 'warning' ? 'warning' : 'info'}`}>
|
|
||||||
{entry.level}
|
|
||||||
</span>
|
|
||||||
<span className="log-text">{text}</span>
|
|
||||||
<span className="repeat">×{entry.count}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={`${entry.ts}-${index}`}
|
|
||||||
className={`log-line ${entry.level}`}
|
|
||||||
onDoubleClick={() => copy(`${formatTime(entry.ts)} ${entry.level} ${text}`)}
|
|
||||||
title="Двойной клик — скопировать"
|
|
||||||
>
|
|
||||||
<span className="log-time">{formatTime(entry.ts)}</span>
|
|
||||||
<span className="log-level">{entry.level}</span>
|
|
||||||
<span className="log-text">{text}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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 (
|
|
||||||
<div className="card">
|
|
||||||
<div className="flex-between">
|
|
||||||
<div>
|
|
||||||
<h2 style={{ marginBottom: 4 }}>{text.title}</h2>
|
|
||||||
<small className="muted">
|
|
||||||
{state?.appliedAt ? `Последнее применение: ${formatRelative(state.appliedAt)}` : 'Конфиг ещё не применялся'}
|
|
||||||
</small>
|
|
||||||
</div>
|
|
||||||
<span className={`badge ${text.kind}`}>{state?.singboxRunning ? 'sing-box online' : 'sing-box offline'}</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="divider" />
|
|
||||||
|
|
||||||
<div className="grid-3">
|
|
||||||
<div>
|
|
||||||
<small className="muted">Активный сервер</small>
|
|
||||||
<div style={{ marginTop: 4 }}>
|
|
||||||
{state?.selectedTag ? (
|
|
||||||
<>
|
|
||||||
<strong>{flagFor({ tag: state.selectedTag })} {state.selectedTag}</strong>
|
|
||||||
</>
|
|
||||||
) : <span className="muted">Не выбран</span>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<small className="muted">Трафик</small>
|
|
||||||
<div style={{ marginTop: 4 }}><strong>{traffic}</strong></div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<small className="muted">Правил маршрутизации</small>
|
|
||||||
<div style={{ marginTop: 4 }}><strong>{(state?.customRules || []).filter(r => r.enabled).length} активных</strong></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function QuickActions({ state, busy, onRestart, onStop, onShowConfig, onNav, onBypassToggle }) {
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h3>Быстрые действия</h3>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
<button className="btn btn-primary" disabled={busy} onClick={() => onNav('servers')}>
|
|
||||||
⋆ Сменить сервер
|
|
||||||
</button>
|
|
||||||
<button className="btn btn-secondary" disabled={busy || !state?.configExists} onClick={onRestart}>
|
|
||||||
↻ Перезапустить
|
|
||||||
</button>
|
|
||||||
<button className="btn btn-secondary" disabled={busy || !state?.singboxRunning} onClick={onStop}>
|
|
||||||
■ Остановить
|
|
||||||
</button>
|
|
||||||
<button className="btn btn-ghost" disabled={!state?.configExists} onClick={onShowConfig}>
|
|
||||||
⌘ Показать config
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className={`btn ${state?.bypassMode ? 'btn-warning' : 'btn-ghost'}`}
|
|
||||||
disabled={busy || !state?.singboxRunning}
|
|
||||||
onClick={onBypassToggle}
|
|
||||||
title="Весь трафик напрямую — для диагностики"
|
|
||||||
>
|
|
||||||
{state?.bypassMode ? '⚠ Обход правил ВКЛЮЧЁН' : '↗ Весь трафик напрямую'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h3>Последние события</h3>
|
|
||||||
<button className="btn btn-link" onClick={() => onNav('logs')}>Открыть логи →</button>
|
|
||||||
</div>
|
|
||||||
{entries.length === 0 ? (
|
|
||||||
<small className="muted">Пока ничего нет.</small>
|
|
||||||
) : (
|
|
||||||
<div className="events-list">
|
|
||||||
{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 (
|
|
||||||
<div key={`${e.ts}-${i}`} className="event-row">
|
|
||||||
<span className={`dot ${dot}`} />
|
|
||||||
<span className="event-time">{time}</span>
|
|
||||||
<span className="text-truncate" title={e.line}>{e.line}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h3>Маршрутизация</h3>
|
|
||||||
<button className="btn btn-link" onClick={() => onNav('routing')}>Открыть правила →</button>
|
|
||||||
</div>
|
|
||||||
<div className="kv-list">
|
|
||||||
<div className="row"><span className="key">Private IP</span><span className="val text-success">→ direct</span></div>
|
|
||||||
{state?.routingRuDirect && (
|
|
||||||
<div className="row"><span className="key">RU (geoip/geosite)</span><span className="val text-success">→ direct</span></div>
|
|
||||||
)}
|
|
||||||
<div className="row"><span className="key">Global custom правил</span><span className="val">{enabled} из {rules.length}</span></div>
|
|
||||||
<div className="row"><span className="key">Transparent fallback</span><span className="val">→ {transparentDefault}</span></div>
|
|
||||||
<div className="row"><span className="key">Proxy fallback</span><span className="val text-warning">→ {proxyDefault}</span></div>
|
|
||||||
{cacheAvailable && (
|
|
||||||
<div className="row">
|
|
||||||
<span className="key">Direct bypass cache</span>
|
|
||||||
<span className="val" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
|
||||||
<span className="text-success">{cacheCount} IP</span>
|
|
||||||
<button className="btn btn-ghost" style={{ fontSize: 11, padding: '1px 6px' }} onClick={onFlushDirectCache} title="Сбросить — все IP снова пройдут через sing-box один раз">
|
|
||||||
✕ сбросить
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function OverviewPage({ state, status, busy, onRestart, onStop, onShowConfig, onNav, onBypassToggle, onFlushDirectCache }) {
|
|
||||||
return (
|
|
||||||
<div className="section-stack">
|
|
||||||
{state?.bypassMode && (
|
|
||||||
<div className="alert alert-warning" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
|
|
||||||
<strong>⚠ Режим обхода правил активен</strong>
|
|
||||||
<span className="muted">— весь трафик идёт напрямую, VPN-правила не применяются.</span>
|
|
||||||
<button className="btn btn-sm btn-warning" style={{ marginLeft: 'auto' }} onClick={onBypassToggle}>
|
|
||||||
Отключить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<StatusHero state={state} status={status} />
|
|
||||||
<div className="grid-2">
|
|
||||||
<QuickActions state={state} busy={busy} onRestart={onRestart} onStop={onStop} onShowConfig={onShowConfig} onNav={onNav} onBypassToggle={onBypassToggle} />
|
|
||||||
<RoutingSummary state={state} onNav={onNav} onFlushDirectCache={onFlushDirectCache} />
|
|
||||||
</div>
|
|
||||||
<RecentEvents onNav={onNav} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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 (
|
|
||||||
<div className="card flat compact">
|
|
||||||
<div className="card-header no-margin"><h3>Проверить маршрут</h3></div>
|
|
||||||
<div className="filter-bar" style={{ marginTop: 12 }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="домен или IP (riotgames.com)"
|
|
||||||
value={host}
|
|
||||||
onChange={(e) => setHost(e.target.value)}
|
|
||||||
onKeyDown={(e) => e.key === 'Enter' && check()}
|
|
||||||
style={{ minWidth: 220, flex: 1 }}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="port"
|
|
||||||
value={port}
|
|
||||||
onChange={(e) => setPort(e.target.value)}
|
|
||||||
style={{ width: 90 }}
|
|
||||||
/>
|
|
||||||
<select className="select" value={network} onChange={(e) => setNetwork(e.target.value)} style={{ width: 90 }}>
|
|
||||||
<option value="tcp">tcp</option>
|
|
||||||
<option value="udp">udp</option>
|
|
||||||
</select>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="source IP"
|
|
||||||
value={sourceIp}
|
|
||||||
onChange={(e) => setSourceIp(e.target.value)}
|
|
||||||
style={{ width: 145 }}
|
|
||||||
/>
|
|
||||||
<select className="select" value={inbound} onChange={(e) => setInbound(e.target.value)} style={{ width: 130 }}>
|
|
||||||
<option value="tproxy-in">tproxy-in</option>
|
|
||||||
<option value="mixed-in">mixed-in</option>
|
|
||||||
</select>
|
|
||||||
<button className="btn btn-primary" onClick={check} disabled={busy || !host}>Проверить</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && <div className="field-error" style={{ marginTop: 10 }}>{error}</div>}
|
|
||||||
|
|
||||||
{r && (
|
|
||||||
<div className="route-result" style={{ marginTop: 12 }}>
|
|
||||||
<div className="flex-between">
|
|
||||||
<strong>{r.ruleIndex >= 0 ? `Правило #${r.ruleIndex + 1}: ${r.ruleName}` : r.ruleName}</strong>
|
|
||||||
<span className={`badge ${kind}`}>→ {r.outbound}</span>
|
|
||||||
</div>
|
|
||||||
{result.resolvedIp && result.resolvedFrom && (
|
|
||||||
<small className="muted text-mono">DNS: {result.resolvedFrom} → {result.resolvedIp}</small>
|
|
||||||
)}
|
|
||||||
<small className="muted">{r.reason}</small>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,382 +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 = {
|
|
||||||
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 (
|
|
||||||
<select className="select sm" value={value || 'rules'} onChange={(e) => onChange(e.target.value)}>
|
|
||||||
<option value="direct">direct</option>
|
|
||||||
<option value="vpn">VPN</option>
|
|
||||||
<option value="rules">default</option>
|
|
||||||
<option value="block">block</option>
|
|
||||||
</select>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DevicesCard({ devicesConfig, onDefaultsChange, onAdd, onUpdate, onRemove }) {
|
|
||||||
const devices = devicesConfig?.devices || [];
|
|
||||||
const defaultTransparentMode = devicesConfig?.defaultTransparentMode || devicesConfig?.defaultMode || 'vpn';
|
|
||||||
const proxyDefaultMode = devicesConfig?.proxyDefaultMode || 'vpn';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<div>
|
|
||||||
<h2>Устройства</h2>
|
|
||||||
<small className="muted">Global rules применяются первыми. Эти значения — fallback после них.</small>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
<label className="field" style={{ minWidth: 180, margin: 0 }}>
|
|
||||||
<span className="field-label">Transparent default</span>
|
|
||||||
<select
|
|
||||||
className="select sm"
|
|
||||||
value={defaultTransparentMode}
|
|
||||||
onChange={(e) => onDefaultsChange({ defaultTransparentMode: e.target.value })}
|
|
||||||
>
|
|
||||||
<option value="direct">direct</option>
|
|
||||||
<option value="vpn">VPN</option>
|
|
||||||
<option value="block">block</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<label className="field" style={{ minWidth: 160, margin: 0 }}>
|
|
||||||
<span className="field-label">Proxy default</span>
|
|
||||||
<select
|
|
||||||
className="select sm"
|
|
||||||
value={proxyDefaultMode}
|
|
||||||
onChange={(e) => onDefaultsChange({ proxyDefaultMode: e.target.value })}
|
|
||||||
>
|
|
||||||
<option value="vpn">VPN</option>
|
|
||||||
<option value="direct">direct</option>
|
|
||||||
<option value="block">block</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<button className="btn btn-primary sm" onClick={onAdd}>
|
|
||||||
+ Добавить устройство
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{devices.length === 0 ? (
|
|
||||||
<div className="empty-state" style={{ padding: '16px 0' }}>
|
|
||||||
<p style={{ margin: 0 }}>Нет профилей устройств. Неизвестные transparent-устройства используют transparent default.</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div style={{ overflowX: 'auto' }}>
|
|
||||||
<table className="table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th style={{ width: 40 }}></th>
|
|
||||||
<th>Название</th>
|
|
||||||
<th style={{ width: 170 }}>IP</th>
|
|
||||||
<th style={{ width: 150 }}>MAC</th>
|
|
||||||
<th style={{ width: 150 }}>Mode</th>
|
|
||||||
<th>Поведение</th>
|
|
||||||
<th style={{ width: 40 }}></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{devices.map((dev) => {
|
|
||||||
const mode = DEVICE_MODES[dev.mode] || DEVICE_MODES.rules;
|
|
||||||
return (
|
|
||||||
<tr key={dev.id} className={dev.enabled !== false ? '' : 'disabled'}>
|
|
||||||
<td>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={dev.enabled !== false}
|
|
||||||
onChange={(e) => onUpdate(dev.id, { enabled: e.target.checked })}
|
|
||||||
style={{ accentColor: 'var(--accent)' }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<input
|
|
||||||
className="input sm"
|
|
||||||
value={dev.name || ''}
|
|
||||||
onChange={(e) => onUpdate(dev.id, { name: e.target.value })}
|
|
||||||
placeholder="Название устройства"
|
|
||||||
style={{ width: '100%', minWidth: 120 }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<input
|
|
||||||
className="input sm"
|
|
||||||
value={dev.ip || ''}
|
|
||||||
onChange={(e) => onUpdate(dev.id, { ip: e.target.value })}
|
|
||||||
placeholder="192.168.1.50"
|
|
||||||
style={{ width: '100%', minWidth: 140 }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<input
|
|
||||||
className="input sm"
|
|
||||||
value={dev.mac || ''}
|
|
||||||
onChange={(e) => onUpdate(dev.id, { mac: e.target.value })}
|
|
||||||
placeholder="опционально"
|
|
||||||
style={{ width: '100%', minWidth: 120 }}
|
|
||||||
/>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<DeviceModeSelect value={dev.mode} onChange={(mode) => onUpdate(dev.id, { mode })} />
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span className={`badge ${mode.kind}`}>{mode.label}</span>
|
|
||||||
<small className="muted" style={{ marginLeft: 8 }}>{mode.hint}</small>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
onClick={() => {
|
|
||||||
if (confirm('Удалить устройство?')) onRemove(dev.id);
|
|
||||||
}}
|
|
||||||
>×</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<tr ref={setNodeRef} style={style} className={`rule-row ${rule.enabled ? '' : 'disabled'} ${invalid ? 'invalid' : ''}`}>
|
|
||||||
<td style={{ width: 30 }}>
|
|
||||||
<span className="drag-handle" {...attributes} {...listeners} title="Перетащить">⠿</span>
|
|
||||||
</td>
|
|
||||||
<td style={{ width: 36 }} className="muted text-mono">#{index + 1}</td>
|
|
||||||
<td>
|
|
||||||
<div className="flex" style={{ alignItems: 'center' }}>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={rule.enabled !== false}
|
|
||||||
onChange={(e) => onUpdate(rule.id, { enabled: e.target.checked })}
|
|
||||||
style={{ accentColor: 'var(--accent)' }}
|
|
||||||
/>
|
|
||||||
<button className="btn btn-link" style={{ padding: 0, fontWeight: 600 }} onClick={() => onEdit(rule.id)}>
|
|
||||||
{rule.name || '(без названия)'}
|
|
||||||
</button>
|
|
||||||
{invalid && <span className="badge danger">ошибки</span>}
|
|
||||||
{conflict && <span className={`badge ${conflict.severity === 'warning' ? 'warning' : 'info'}`} title={`Перекрывается с #${conflict.conflictWithIndex + 1}`}>конфликт</span>}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td><span className={`badge ${ob.kind}`}>{ob.label}</span></td>
|
|
||||||
<td className="muted" style={{ fontSize: 12 }}>{summary(rule)}</td>
|
|
||||||
<td style={{ textAlign: 'right' }}>
|
|
||||||
<div className="row-actions">
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => onEdit(rule.id)}>Редактировать</button>
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => { if (confirm('Удалить правило?')) onRemove(rule.id); }}>×</button>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function TemplatesModal({ open, onClose, onAdd }) {
|
|
||||||
if (!open) return null;
|
|
||||||
return (
|
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
|
||||||
<div className="modal lg" onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="modal-head">
|
|
||||||
<h3>Шаблоны маршрутизации</h3>
|
|
||||||
<button className="btn btn-ghost sm" onClick={onClose}>Закрыть</button>
|
|
||||||
</div>
|
|
||||||
<div className="modal-body">
|
|
||||||
<div className="template-grid">
|
|
||||||
{ruleTemplates.map((tpl) => (
|
|
||||||
<div key={tpl.key} className="template-card">
|
|
||||||
<h4>{tpl.label}</h4>
|
|
||||||
<small>{tpl.description}</small>
|
|
||||||
<button className="btn btn-secondary sm" onClick={() => { onAdd(tpl.build()); onClose(); }}>
|
|
||||||
+ Добавить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="section-stack">
|
|
||||||
<RouteChecker />
|
|
||||||
|
|
||||||
<DevicesCard
|
|
||||||
devicesConfig={devicesConfig}
|
|
||||||
onDefaultsChange={onUpdateDeviceDefaults}
|
|
||||||
onAdd={onAddDevice}
|
|
||||||
onUpdate={onUpdateDevice}
|
|
||||||
onRemove={onRemoveDevice}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h2>Правила маршрутизации</h2>
|
|
||||||
<div className="btn-group">
|
|
||||||
<button className="btn btn-secondary sm" onClick={() => setShowTemplates(true)}>Шаблоны</button>
|
|
||||||
<button className="btn btn-primary sm" onClick={() => { const newId = `rule-${Date.now()}`; onAdd(); setTimeout(() => setEditingId(newId), 50); }}>
|
|
||||||
+ Добавить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{conflicts.length > 0 && (
|
|
||||||
<div className="conflict-banner" style={{ marginBottom: 12 }}>
|
|
||||||
<span>⚠</span>
|
|
||||||
<div>
|
|
||||||
<strong>{conflicts.length} конфликт(ов) обнаружено</strong>
|
|
||||||
<div style={{ marginTop: 4 }}>
|
|
||||||
{conflicts.slice(0, 3).map((c, i) => (
|
|
||||||
<div key={i} style={{ fontSize: 12 }}>
|
|
||||||
#{c.ruleIndex + 1} «{c.ruleName}» перекрывается правилом #{c.conflictWithIndex + 1} «{c.conflictWithName}»
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<small className="muted" style={{ display: 'block', marginBottom: 8 }}>
|
|
||||||
Применяются <strong>сверху вниз</strong>. Перетаскивай ⠿ чтобы менять порядок.
|
|
||||||
</small>
|
|
||||||
|
|
||||||
{rules.length === 0 ? (
|
|
||||||
<div className="empty-state">
|
|
||||||
<h3>Правил пока нет</h3>
|
|
||||||
<p>Добавь шаблон (например «League of Legends → direct») или создай пустое правило.</p>
|
|
||||||
<button className="btn btn-primary" onClick={() => setShowTemplates(true)} style={{ marginTop: 12 }}>
|
|
||||||
Открыть шаблоны
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div style={{ overflowX: 'auto' }}>
|
|
||||||
<table className="table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th></th>
|
|
||||||
<th>#</th>
|
|
||||||
<th>Правило</th>
|
|
||||||
<th>Outbound</th>
|
|
||||||
<th>Условия</th>
|
|
||||||
<th></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
|
||||||
<SortableContext items={rules.map((r) => r.id)} strategy={verticalListSortingStrategy}>
|
|
||||||
{rules.map((rule, i) => (
|
|
||||||
<SortableRuleRow
|
|
||||||
key={rule.id}
|
|
||||||
rule={rule}
|
|
||||||
index={i}
|
|
||||||
total={rules.length}
|
|
||||||
onEdit={setEditingId}
|
|
||||||
onUpdate={onUpdate}
|
|
||||||
onRemove={onRemove}
|
|
||||||
conflict={conflictsByRuleId[rule.id]}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</SortableContext>
|
|
||||||
</DndContext>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<RuleEditorDrawer
|
|
||||||
rule={editing}
|
|
||||||
onUpdate={onUpdate}
|
|
||||||
onClose={() => setEditingId(null)}
|
|
||||||
onRemove={onRemove}
|
|
||||||
availableRuleSets={availableRuleSets}
|
|
||||||
/>
|
|
||||||
<TemplatesModal open={showTemplates} onClose={() => setShowTemplates(false)} onAdd={onAddTemplate} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -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 (
|
|
||||||
<div className="modal-backdrop" style={{ zIndex: 1100 }} onClick={onClose}>
|
|
||||||
<div
|
|
||||||
className="modal lg"
|
|
||||||
style={{ maxWidth: 680, maxHeight: '85vh', display: 'flex', flexDirection: 'column' }}
|
|
||||||
onClick={(e) => e.stopPropagation()}
|
|
||||||
>
|
|
||||||
<div className="modal-head">
|
|
||||||
<div>
|
|
||||||
<h3 style={{ margin: 0 }}>Содержимое: <code style={{ fontSize: 14 }}>{tag}</code></h3>
|
|
||||||
<small className="muted">Кликните запись чтобы добавить в правило</small>
|
|
||||||
</div>
|
|
||||||
<button className="btn btn-ghost sm" onClick={onClose}>Закрыть</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{status === 'loading' && (
|
|
||||||
<div style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)' }}>
|
|
||||||
Скачивание и декомпиляция…<br />
|
|
||||||
<small>Может занять 10–30 секунд</small>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{status === 'error' && (
|
|
||||||
<div style={{ padding: 24 }}>
|
|
||||||
<div className="conflict-banner danger"><span>✗</span><div>{error}</div></div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{status === 'done' && data && (
|
|
||||||
<>
|
|
||||||
<div style={{ padding: '8px 20px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
|
|
||||||
<span className="badge info">всего: {data.stats.total.toLocaleString()}</span>
|
|
||||||
{data.stats.domain > 0 && <span className="badge">доменов: {data.stats.domain.toLocaleString()}</span>}
|
|
||||||
{data.stats.suffix > 0 && <span className="badge">суффиксов: {data.stats.suffix.toLocaleString()}</span>}
|
|
||||||
{data.stats.cidr > 0 && <span className="badge">CIDR: {data.stats.cidr.toLocaleString()}</span>}
|
|
||||||
</div>
|
|
||||||
<div style={{ padding: '8px 20px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 8 }}>
|
|
||||||
<input
|
|
||||||
ref={inputRef}
|
|
||||||
className="input"
|
|
||||||
style={{ flex: 1 }}
|
|
||||||
placeholder="Поиск: youtube, 149.154, .ru…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => onSearchChange(e.target.value)}
|
|
||||||
/>
|
|
||||||
<select className="select" style={{ width: 130 }} value={typeFilter} onChange={(e) => onTypeChange(e.target.value)}>
|
|
||||||
<option value="all">Все типы</option>
|
|
||||||
{Object.entries(RS_TYPE_LABELS).map(([k, v]) => (
|
|
||||||
<option key={k} value={k}>{v}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div style={{ flex: 1, overflow: 'auto', padding: '0 20px' }}>
|
|
||||||
{filtered.length === 0 ? (
|
|
||||||
<div className="muted" style={{ padding: '20px 0', textAlign: 'center' }}>Ничего не найдено</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div style={{ fontSize: 12, color: 'var(--text-muted)', padding: '6px 0' }}>
|
|
||||||
{filtered.length.toLocaleString()} / {data.stats.total.toLocaleString()}
|
|
||||||
{totalPages > 1 && ` · стр. ${page + 1}/${totalPages}`}
|
|
||||||
<span className="muted" style={{ marginLeft: 12 }}>— нажмите строку чтобы добавить в правило</span>
|
|
||||||
</div>
|
|
||||||
<table className="table" style={{ fontSize: 12 }}>
|
|
||||||
<thead>
|
|
||||||
<tr><th style={{ width: 70 }}>Тип</th><th>Значение</th><th style={{ width: 30 }}></th></tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{pageItems.map((e, i) => {
|
|
||||||
const already = addedValues.has(e.value);
|
|
||||||
return (
|
|
||||||
<tr
|
|
||||||
key={i}
|
|
||||||
style={{ cursor: already ? 'default' : 'pointer', opacity: already ? 0.5 : 1 }}
|
|
||||||
onClick={() => !already && addEntry(e)}
|
|
||||||
title={already ? 'Уже добавлено' : `Добавить в ${e.type === 'cidr' ? 'IP/CIDR' : e.type === 'suffix' ? 'суффиксы' : e.type === 'keyword' ? 'ключевые слова' : 'домены'}`}
|
|
||||||
>
|
|
||||||
<td><span className="badge" style={{ fontSize: 10 }}>{RS_TYPE_LABELS[e.type] || e.type}</span></td>
|
|
||||||
<td className="text-mono" style={{ wordBreak: 'break-all', userSelect: 'all' }}>{e.value}</td>
|
|
||||||
<td style={{ color: 'var(--text-muted)', fontSize: 14 }}>{already ? '✓' : '+'}</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<div className="flex" style={{ gap: 8, padding: '10px 0', justifyContent: 'center' }}>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page === 0} onClick={() => setPage(0)}>«</button>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page === 0} onClick={() => setPage((p) => p - 1)}>‹</button>
|
|
||||||
<span className="muted" style={{ lineHeight: '28px', fontSize: 12 }}>{page + 1} / {totalPages}</span>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page >= totalPages - 1} onClick={() => setPage((p) => p + 1)}>›</button>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page >= totalPages - 1} onClick={() => setPage(totalPages - 1)}>»</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 (
|
|
||||||
<div className="drawer-body">
|
|
||||||
<div className="tabs">
|
|
||||||
<button className={`tab ${view === 'builder' ? 'active' : ''}`} onClick={() => setView('builder')}>Конструктор</button>
|
|
||||||
<button className={`tab ${view === 'json' ? 'active' : ''}`} onClick={() => { setJsonDraft(JSON.stringify(rule, null, 2)); setView('json'); }}>Raw JSON</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{view === 'builder' ? (
|
|
||||||
<>
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Название</span>
|
|
||||||
<input className="input" value={rule.name} onChange={(e) => patch({ name: e.target.value })} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field-row">
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Outbound</span>
|
|
||||||
<select className="select" value={rule.outbound} onChange={(e) => patch({ outbound: e.target.value })}>
|
|
||||||
<option value="direct">direct (напрямую)</option>
|
|
||||||
<option value="vpn">vpn (через выбранный сервер)</option>
|
|
||||||
<option value="block">block (заблокировать)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Состояние</span>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={rule.enabled !== false}
|
|
||||||
onChange={(e) => patch({ enabled: e.target.checked })}
|
|
||||||
/>
|
|
||||||
Правило включено
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Rule-sets (geo-базы)</span>
|
|
||||||
<ChipsInput
|
|
||||||
value={rule.ruleSets || []}
|
|
||||||
onChange={(v) => patch({ ruleSets: v })}
|
|
||||||
placeholder="geosite-runet"
|
|
||||||
validate={validRuleSetTag}
|
|
||||||
/>
|
|
||||||
{/* Кнопки просмотра содержимого для выбранных rule-sets */}
|
|
||||||
{(rule.ruleSets || []).length > 0 && (
|
|
||||||
<div className="field-hint" style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>
|
|
||||||
{(rule.ruleSets || []).map((tag) => {
|
|
||||||
const url = ruleSetUrlMap[tag];
|
|
||||||
return url ? (
|
|
||||||
<button
|
|
||||||
key={tag}
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
style={{ padding: '0 6px', fontSize: 11 }}
|
|
||||||
onClick={() => setBrowseTag({ tag, url })}
|
|
||||||
title={`Просмотреть содержимое ${tag}`}
|
|
||||||
>
|
|
||||||
🔍 {tag}
|
|
||||||
</button>
|
|
||||||
) : null;
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{availableRuleSets.length > 0 && (
|
|
||||||
<div className="field-hint">
|
|
||||||
Доступны:{' '}
|
|
||||||
{availableRuleSets.map((rs) => (
|
|
||||||
<span key={rs.tag} style={{ display: 'inline-flex', alignItems: 'center', marginRight: 4 }}>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
style={{ padding: '0 6px', marginRight: 2 }}
|
|
||||||
onClick={() => {
|
|
||||||
const current = new Set(rule.ruleSets || []);
|
|
||||||
if (!current.has(rs.tag)) {
|
|
||||||
patch({ ruleSets: [...(rule.ruleSets || []), rs.tag] });
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
+ {rs.tag}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
style={{ padding: '0 4px', fontSize: 12 }}
|
|
||||||
onClick={() => setBrowseTag({ tag: rs.tag, url: rs.url })}
|
|
||||||
title="Просмотреть содержимое"
|
|
||||||
>
|
|
||||||
🔍
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{availableRuleSets.length === 0 && (
|
|
||||||
<span className="field-hint">
|
|
||||||
Настройте rule-sets в Настройках, затем вводите их теги здесь
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Домены (точное совпадение)</span>
|
|
||||||
<ChipsInput
|
|
||||||
value={rule.domains || []}
|
|
||||||
onChange={(v) => patch({ domains: v })}
|
|
||||||
placeholder="riotgames.com"
|
|
||||||
validate={validDomain}
|
|
||||||
/>
|
|
||||||
{errors.domains.length > 0 && <span className="field-error">Невалидно: {errors.domains.join(', ')}</span>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Суффиксы доменов</span>
|
|
||||||
<ChipsInput
|
|
||||||
value={rule.domainSuffixes || []}
|
|
||||||
onChange={(v) => patch({ domainSuffixes: v })}
|
|
||||||
placeholder="riotcdn.net"
|
|
||||||
validate={validDomain}
|
|
||||||
/>
|
|
||||||
{errors.domainSuffixes.length > 0 && <span className="field-error">Невалидно: {errors.domainSuffixes.join(', ')}</span>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">IP / CIDR</span>
|
|
||||||
<ChipsInput
|
|
||||||
value={rule.ipCidrs || []}
|
|
||||||
onChange={(v) => patch({ ipCidrs: v })}
|
|
||||||
placeholder="104.160.128.0/19"
|
|
||||||
validate={isValidCidr}
|
|
||||||
/>
|
|
||||||
{errors.ipCidrs.length > 0 && <span className="field-error">Невалидно: {errors.ipCidrs.join(', ')}</span>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Порты (число или диапазон 5000-6000)</span>
|
|
||||||
<ChipsInput
|
|
||||||
value={rule.ports || []}
|
|
||||||
onChange={(v) => 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 && <span className="field-error">Невалидно: {errors.ports.join(', ')}</span>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Протоколы</span>
|
|
||||||
<div className="flex">
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={(rule.networks || []).includes('tcp')}
|
|
||||||
onChange={(e) => {
|
|
||||||
const set = new Set(rule.networks || []);
|
|
||||||
e.target.checked ? set.add('tcp') : set.delete('tcp');
|
|
||||||
patch({ networks: Array.from(set) });
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
TCP
|
|
||||||
</label>
|
|
||||||
<label className="checkbox">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={(rule.networks || []).includes('udp')}
|
|
||||||
onChange={(e) => {
|
|
||||||
const set = new Set(rule.networks || []);
|
|
||||||
e.target.checked ? set.add('udp') : set.delete('udp');
|
|
||||||
patch({ networks: Array.from(set) });
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
UDP
|
|
||||||
</label>
|
|
||||||
<span className="field-hint">Если ничего — оба</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Сырой JSON правила</span>
|
|
||||||
<textarea
|
|
||||||
className="textarea"
|
|
||||||
style={{ minHeight: 320 }}
|
|
||||||
value={jsonDraft}
|
|
||||||
onChange={(e) => setJsonDraft(e.target.value)}
|
|
||||||
/>
|
|
||||||
{jsonError && <span className="field-error">{jsonError}</span>}
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
<button className="btn btn-primary" onClick={applyJson}>Применить JSON</button>
|
|
||||||
<button className="btn btn-ghost" onClick={() => setJsonDraft(JSON.stringify(rule, null, 2))}>Сбросить</button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{browseTag && (
|
|
||||||
<RuleSetBrowseModal
|
|
||||||
tag={browseTag.tag}
|
|
||||||
url={browseTag.url}
|
|
||||||
rule={rule}
|
|
||||||
onPatch={(p) => patch(p)}
|
|
||||||
onClose={() => setBrowseTag(null)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RuleEditorDrawer({ rule, onUpdate, onClose, onRemove, availableRuleSets = [] }) {
|
|
||||||
if (!rule) return null;
|
|
||||||
const errors = ruleErrors(rule);
|
|
||||||
const invalid = hasErrors(errors);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div className="drawer-backdrop" onClick={onClose} />
|
|
||||||
<aside className="drawer">
|
|
||||||
<div className="drawer-head">
|
|
||||||
<div>
|
|
||||||
<h3>Редактирование правила</h3>
|
|
||||||
<small className="muted">{rule.name || '(без названия)'}</small>
|
|
||||||
</div>
|
|
||||||
<button className="btn btn-ghost sm" onClick={onClose}>Закрыть</button>
|
|
||||||
</div>
|
|
||||||
<RuleEditor rule={rule} onUpdate={onUpdate} onClose={onClose} onRemove={onRemove} availableRuleSets={availableRuleSets} />
|
|
||||||
<div className="drawer-foot">
|
|
||||||
<button className="btn btn-danger" onClick={() => { if (confirm('Удалить правило?')) { onRemove(rule.id); onClose(); } }}>Удалить</button>
|
|
||||||
<div className="btn-group">
|
|
||||||
{invalid && <span className="badge danger">Есть ошибки</span>}
|
|
||||||
<button className="btn btn-primary" onClick={onClose}>Готово</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
import React, { useMemo, useState } from 'react';
|
|
||||||
import { api } from '../api.js';
|
|
||||||
import { flagFor } from '../utils/country.js';
|
|
||||||
import { formatRelative } from '../utils/format.js';
|
|
||||||
|
|
||||||
function PingCell({ ping }) {
|
|
||||||
if (!ping) return <span className="muted">—</span>;
|
|
||||||
if (ping.checking) return <span className="badge neutral pulse">проверяем…</span>;
|
|
||||||
if (!ping.ok) return <span className="badge danger" title={ping.error}>offline</span>;
|
|
||||||
const ms = ping.latency;
|
|
||||||
const kind = ms < 80 ? 'success' : ms < 200 ? 'warning' : 'danger';
|
|
||||||
return <span className={`badge ${kind}`}>{ms} ms</span>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function StatusCell({ ping }) {
|
|
||||||
if (!ping) return <span className="badge neutral">unknown</span>;
|
|
||||||
if (ping.checking) return <span className="badge neutral pulse">…</span>;
|
|
||||||
return ping.ok
|
|
||||||
? <span className="badge success">● online</span>
|
|
||||||
: <span className="badge danger">● offline</span>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ServersPage({
|
|
||||||
state,
|
|
||||||
servers,
|
|
||||||
selectedTag,
|
|
||||||
setSelectedTag,
|
|
||||||
pendingTag,
|
|
||||||
setPendingTag,
|
|
||||||
busy,
|
|
||||||
onApply,
|
|
||||||
onRollback,
|
|
||||||
pings,
|
|
||||||
setPings,
|
|
||||||
pushToast,
|
|
||||||
}) {
|
|
||||||
const [filter, setFilter] = useState('all'); // all | online
|
|
||||||
const [search, setSearch] = useState('');
|
|
||||||
|
|
||||||
async function pingOne(server) {
|
|
||||||
setPings((prev) => ({ ...prev, [server.tag]: { checking: true } }));
|
|
||||||
try {
|
|
||||||
const res = await api.servers.ping(server.server, server.server_port);
|
|
||||||
setPings((prev) => ({
|
|
||||||
...prev,
|
|
||||||
[server.tag]: { ok: res.ok, latency: res.latency, error: res.error, checkedAt: new Date().toISOString() },
|
|
||||||
}));
|
|
||||||
} catch (err) {
|
|
||||||
setPings((prev) => ({ ...prev, [server.tag]: { ok: false, error: err.message } }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pingAll() {
|
|
||||||
setPings((prev) => {
|
|
||||||
const next = { ...prev };
|
|
||||||
for (const s of servers) next[s.tag] = { checking: true };
|
|
||||||
return next;
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
const res = await api.servers.pingAll();
|
|
||||||
const map = {};
|
|
||||||
for (const r of res.results || []) {
|
|
||||||
map[r.tag] = { ok: r.ok, latency: r.latency, error: r.error, checkedAt: r.checkedAt };
|
|
||||||
}
|
|
||||||
setPings((prev) => ({ ...prev, ...map }));
|
|
||||||
pushToast({ kind: 'success', title: 'Пинг завершён' });
|
|
||||||
} catch (err) {
|
|
||||||
pushToast({ kind: 'danger', title: 'Ошибка пинга', message: err.message });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
|
||||||
return servers.filter((s) => {
|
|
||||||
if (search && !s.tag.toLowerCase().includes(search.toLowerCase()) && !s.server.toLowerCase().includes(search.toLowerCase())) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (filter === 'online' && !pings[s.tag]?.ok) return false;
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
}, [servers, search, filter, pings]);
|
|
||||||
|
|
||||||
const pendingDifferent = pendingTag && pendingTag !== state?.selectedTag;
|
|
||||||
const activeServer = servers.find((s) => s.tag === state?.selectedTag);
|
|
||||||
const pendingServer = servers.find((s) => s.tag === pendingTag);
|
|
||||||
|
|
||||||
if (!servers.length) {
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="empty-state">
|
|
||||||
<h3>Серверы ещё не загружены</h3>
|
|
||||||
<p>Загрузите подписку в разделе «Настройки», чтобы получить список серверов.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="section-stack">
|
|
||||||
{pendingDifferent && (
|
|
||||||
<div className="card" style={{ borderColor: 'var(--warning)' }}>
|
|
||||||
<div className="flex-between">
|
|
||||||
<div>
|
|
||||||
<strong>Выбран: {flagFor(pendingServer)} {pendingServer?.tag}</strong>
|
|
||||||
<div className="muted" style={{ fontSize: 12, marginTop: 4 }}>
|
|
||||||
Текущий: {state?.selectedTag ? `${flagFor(activeServer)} ${state.selectedTag}` : 'нет'}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group">
|
|
||||||
<button className="btn btn-ghost" onClick={() => setPendingTag(state?.selectedTag || '')} disabled={busy}>
|
|
||||||
Отменить
|
|
||||||
</button>
|
|
||||||
<button className="btn btn-primary" onClick={() => onApply(pendingTag)} disabled={busy}>
|
|
||||||
Применить изменения
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h2>Серверы ({servers.length})</h2>
|
|
||||||
<div className="btn-group">
|
|
||||||
<button className="btn btn-secondary sm" onClick={pingAll} disabled={busy}>
|
|
||||||
⚡ Проверить все
|
|
||||||
</button>
|
|
||||||
{state?.previousTag && (
|
|
||||||
<button className="btn btn-ghost sm" onClick={onRollback} disabled={busy}>
|
|
||||||
↶ Откатить ({state.previousTag})
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="filter-bar" style={{ marginBottom: 12 }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
placeholder="Поиск по тегу или хосту…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
/>
|
|
||||||
<select className="select" value={filter} onChange={(e) => setFilter(e.target.value)}>
|
|
||||||
<option value="all">Все</option>
|
|
||||||
<option value="online">Только online</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div style={{ overflowX: 'auto' }}>
|
|
||||||
<table className="table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th style={{ width: 16 }}></th>
|
|
||||||
<th>Сервер</th>
|
|
||||||
<th>Хост</th>
|
|
||||||
<th>Тип</th>
|
|
||||||
<th>Ping</th>
|
|
||||||
<th>Статус</th>
|
|
||||||
<th style={{ textAlign: 'right' }}>Действие</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{filtered.map((server) => {
|
|
||||||
const isActive = server.tag === state?.selectedTag;
|
|
||||||
const isPending = server.tag === pendingTag && !isActive;
|
|
||||||
const ping = pings[server.tag];
|
|
||||||
return (
|
|
||||||
<tr key={server.tag} className={isActive ? 'active' : ''}>
|
|
||||||
<td>{flagFor(server)}</td>
|
|
||||||
<td>
|
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
|
||||||
<strong>{server.tag}</strong>
|
|
||||||
{isActive && <span className="badge success">ACTIVE</span>}
|
|
||||||
{isPending && <span className="badge warning">pending</span>}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className="text-mono muted">{server.server}:{server.server_port}</td>
|
|
||||||
<td><span className="badge neutral">{server.type}</span></td>
|
|
||||||
<td><PingCell ping={ping} /></td>
|
|
||||||
<td><StatusCell ping={ping} /></td>
|
|
||||||
<td>
|
|
||||||
<div className="row-actions">
|
|
||||||
<button className="btn btn-ghost sm" onClick={() => pingOne(server)} disabled={busy}>
|
|
||||||
Ping
|
|
||||||
</button>
|
|
||||||
{isActive ? (
|
|
||||||
<button className="btn btn-secondary sm" disabled>Активен</button>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
className="btn btn-primary sm"
|
|
||||||
onClick={() => { setSelectedTag(server.tag); setPendingTag(server.tag); }}
|
|
||||||
disabled={busy}
|
|
||||||
>
|
|
||||||
Выбрать
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{!filtered.length && (
|
|
||||||
<tr><td colSpan={7} className="muted" style={{ padding: 24, textAlign: 'center' }}>Ничего не найдено</td></tr>
|
|
||||||
)}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,784 +0,0 @@
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
|
||||||
import { api } from '../api.js';
|
|
||||||
import { formatRelative } from '../utils/format.js';
|
|
||||||
|
|
||||||
const TYPE_LABELS = { domain: 'домен', suffix: 'суффикс', keyword: 'ключевое слово', cidr: 'CIDR', regex: 'regex' };
|
|
||||||
const PAGE_SIZE = 100;
|
|
||||||
|
|
||||||
function RuleSetLookupModal({ tag, url, onClose }) {
|
|
||||||
const [state, setState] = useState('idle'); // idle | loading | done | error
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [data, setData] = useState(null); // { entries, stats, cachedAt }
|
|
||||||
const [search, setSearch] = useState('');
|
|
||||||
const [filterType, setFilterType] = useState('all');
|
|
||||||
const [page, setPage] = useState(0);
|
|
||||||
const inputRef = useRef(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setState('loading');
|
|
||||||
api.ruleSets.lookup(tag, url)
|
|
||||||
.then((res) => { setData(res); setState('done'); })
|
|
||||||
.catch((err) => { setError(err.message); setState('error'); });
|
|
||||||
}, [tag, url]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (state === 'done') setTimeout(() => inputRef.current?.focus(), 50);
|
|
||||||
}, [state]);
|
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
|
||||||
if (!data?.entries) return [];
|
|
||||||
const q = search.trim().toLowerCase();
|
|
||||||
return data.entries.filter((e) => {
|
|
||||||
if (filterType !== 'all' && e.type !== filterType) return false;
|
|
||||||
if (!q) return true;
|
|
||||||
return e.value.toLowerCase().includes(q);
|
|
||||||
});
|
|
||||||
}, [data, search, filterType]);
|
|
||||||
|
|
||||||
const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
|
|
||||||
const pageItems = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
|
|
||||||
|
|
||||||
function onSearchChange(v) { setSearch(v); setPage(0); }
|
|
||||||
function onTypeChange(v) { setFilterType(v); setPage(0); }
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="modal-backdrop" onClick={onClose}>
|
|
||||||
<div className="modal lg" style={{ maxWidth: 720, maxHeight: '85vh', display: 'flex', flexDirection: 'column' }} onClick={(e) => e.stopPropagation()}>
|
|
||||||
<div className="modal-head">
|
|
||||||
<div>
|
|
||||||
<h3 style={{ margin: 0 }}>Содержимое: <code style={{ fontSize: 14 }}>{tag}</code></h3>
|
|
||||||
<small className="muted">{url}</small>
|
|
||||||
</div>
|
|
||||||
<button className="btn btn-ghost sm" onClick={onClose}>Закрыть</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{state === 'loading' && (
|
|
||||||
<div style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)' }}>
|
|
||||||
Скачивание и декомпиляция…<br />
|
|
||||||
<small>Может занять 10–30 секунд</small>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{state === 'error' && (
|
|
||||||
<div style={{ padding: 24 }}>
|
|
||||||
<div className="conflict-banner danger"><span>✗</span><div>{error}</div></div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{state === 'done' && data && (
|
|
||||||
<>
|
|
||||||
<div style={{ padding: '10px 20px', borderBottom: '1px solid var(--border)' }}>
|
|
||||||
<div className="flex" style={{ gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
|
|
||||||
<span className="badge info">всего: {data.stats.total.toLocaleString()}</span>
|
|
||||||
{data.stats.domain > 0 && <span className="badge">доменов: {data.stats.domain.toLocaleString()}</span>}
|
|
||||||
{data.stats.suffix > 0 && <span className="badge">суффиксов: {data.stats.suffix.toLocaleString()}</span>}
|
|
||||||
{data.stats.keyword > 0 && <span className="badge">ключ. слов: {data.stats.keyword.toLocaleString()}</span>}
|
|
||||||
{data.stats.cidr > 0 && <span className="badge">CIDR: {data.stats.cidr.toLocaleString()}</span>}
|
|
||||||
{data.stats.regex > 0 && <span className="badge">regex: {data.stats.regex.toLocaleString()}</span>}
|
|
||||||
<span className="muted" style={{ fontSize: 12, marginLeft: 'auto' }}>
|
|
||||||
кеш: {formatRelative(data.cachedAt)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div style={{ padding: '10px 20px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 8 }}>
|
|
||||||
<input
|
|
||||||
ref={inputRef}
|
|
||||||
className="input"
|
|
||||||
style={{ flex: 1 }}
|
|
||||||
placeholder="Поиск: youtube, 149.154, .ru…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => onSearchChange(e.target.value)}
|
|
||||||
/>
|
|
||||||
<select className="select" style={{ width: 140 }} value={filterType} onChange={(e) => onTypeChange(e.target.value)}>
|
|
||||||
<option value="all">Все типы</option>
|
|
||||||
{Object.entries(TYPE_LABELS).map(([k, v]) => (
|
|
||||||
<option key={k} value={k}>{v}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div style={{ flex: 1, overflow: 'auto', padding: '0 20px' }}>
|
|
||||||
{filtered.length === 0 ? (
|
|
||||||
<div className="muted" style={{ padding: '20px 0', textAlign: 'center' }}>Ничего не найдено</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div style={{ fontSize: 12, color: 'var(--text-muted)', padding: '8px 0' }}>
|
|
||||||
Найдено: {filtered.length.toLocaleString()} / {data.stats.total.toLocaleString()}
|
|
||||||
{totalPages > 1 && ` · страница ${page + 1} из ${totalPages}`}
|
|
||||||
</div>
|
|
||||||
<table className="table" style={{ fontSize: 13 }}>
|
|
||||||
<thead>
|
|
||||||
<tr><th style={{ width: 80 }}>Тип</th><th>Значение</th></tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{pageItems.map((e, i) => (
|
|
||||||
<tr key={i}>
|
|
||||||
<td><span className="badge">{TYPE_LABELS[e.type] || e.type}</span></td>
|
|
||||||
<td className="text-mono" style={{ wordBreak: 'break-all', userSelect: 'all' }}>{e.value}</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
{totalPages > 1 && (
|
|
||||||
<div className="flex" style={{ gap: 8, padding: '12px 0', justifyContent: 'center' }}>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page === 0} onClick={() => setPage(0)}>«</button>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page === 0} onClick={() => setPage((p) => p - 1)}>‹</button>
|
|
||||||
<span className="muted" style={{ lineHeight: '28px', fontSize: 13 }}>{page + 1} / {totalPages}</span>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page >= totalPages - 1} onClick={() => setPage((p) => p + 1)}>›</button>
|
|
||||||
<button className="btn btn-ghost sm" disabled={page >= totalPages - 1} onClick={() => setPage(totalPages - 1)}>»</button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Каталог готовых rule-set источников для sing-box (.srs формат)
|
|
||||||
// Источники: SagerNet (официальные, используются как встроенные), runetfreedom (RKN-реестр)
|
|
||||||
const RULE_SET_CATALOG = [
|
|
||||||
{
|
|
||||||
tag: 'geosite-runet',
|
|
||||||
url: 'https://github.com/runetfreedom/russia-blocked-geosite/releases/latest/download/rule-set/ru.srs',
|
|
||||||
source: 'runetfreedom',
|
|
||||||
category: 'RU',
|
|
||||||
description: 'Заблокированные в РФ домены по реестру РКН. Обновляется автоматически из официальных источников.',
|
|
||||||
examples: ['rutracker.org', 'youtube.com', 'instagram.com', 'facebook.com', 'twitter.com'],
|
|
||||||
use: 'vpn — маршрутизировать заблокированные домены через VPN.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geoip-ru',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geoip@rule-set/geoip-ru.srs',
|
|
||||||
source: 'SagerNet/sing-geoip',
|
|
||||||
category: 'RU',
|
|
||||||
description: 'IP-диапазоны, зарегистрированные в России (RIPE NCC). Покрывает российские хостинги, банки, госсайты.',
|
|
||||||
examples: ['77.88.0.0/18 (Яндекс)', '95.173.128.0/19 (МТС)', '213.180.192.0/19 (Яндекс)'],
|
|
||||||
use: 'direct — российские сервисы без VPN.',
|
|
||||||
builtIn: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-category-ru',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-category-ru.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'RU',
|
|
||||||
description: 'Домены российских сервисов: Яндекс, VK, Mail.ru, Сбербанк, банки, госуслуги. Не заблокированные, а просто российские.',
|
|
||||||
examples: ['yandex.ru', 'vk.com', 'mail.ru', 'sberbank.ru', 'gosuslugi.ru', 'ozon.ru'],
|
|
||||||
use: 'direct — чтобы российские сайты открывались с российским IP (нужно для оплаты и т.п.).',
|
|
||||||
builtIn: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-google',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-google.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Сервисы',
|
|
||||||
description: 'Все домены Google: поиск, Gmail, YouTube, Drive, Maps, Google API, reCAPTCHA и пр.',
|
|
||||||
examples: ['google.com', 'googleapis.com', 'googlevideo.com', 'gstatic.com', 'ggpht.com'],
|
|
||||||
use: 'vpn — если Google заблокирован или нужна стабильная работа сервисов.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-youtube',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-youtube.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Сервисы',
|
|
||||||
description: 'Только домены YouTube и связанных CDN. Меньше чем полный Google.',
|
|
||||||
examples: ['youtube.com', 'youtu.be', 'ytimg.com', 'googlevideo.com'],
|
|
||||||
use: 'vpn — для разблокировки YouTube.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-telegram',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-telegram.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Сервисы',
|
|
||||||
description: 'Домены и IP Telegram. Включает CDN, API и голосовые серверы.',
|
|
||||||
examples: ['telegram.org', 't.me', 'telegra.ph', '149.154.160.0/20'],
|
|
||||||
use: 'vpn — разблокировка в РФ. direct — если хочешь избежать задержек.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-openai',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-openai.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Сервисы',
|
|
||||||
description: 'ChatGPT, OpenAI API, Dall-E и другие сервисы OpenAI.',
|
|
||||||
examples: ['openai.com', 'chatgpt.com', 'oaistatic.com', 'oaiusercontent.com'],
|
|
||||||
use: 'vpn — OpenAI заблокирован в РФ и ряде других стран.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-apple',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-apple.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Сервисы',
|
|
||||||
description: 'App Store, iCloud, Apple CDN, push-уведомления (APNs), iMessage.',
|
|
||||||
examples: ['apple.com', 'icloud.com', 'mzstatic.com', 'apple-cloudkit.com'],
|
|
||||||
use: 'direct — Apple обычно работает без VPN. vpn — если нужен другой регион App Store.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-github',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-github.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Разработка',
|
|
||||||
description: 'GitHub, GitHub Actions, GitHub Pages, raw.githubusercontent.com.',
|
|
||||||
examples: ['github.com', 'githubusercontent.com', 'github.io', 'githubassets.com'],
|
|
||||||
use: 'vpn — если GitHub замедлен или заблокирован.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
tag: 'geosite-category-ads-all',
|
|
||||||
url: 'https://cdn.jsdelivr.net/gh/SagerNet/sing-geosite@rule-set/geosite-category-ads-all.srs',
|
|
||||||
source: 'SagerNet/sing-geosite',
|
|
||||||
category: 'Блокировка',
|
|
||||||
description: 'Рекламные сети, трекеры, аналитика. Тысячи доменов.',
|
|
||||||
examples: ['doubleclick.net', 'googlesyndication.com', 'amazon-adsystem.com'],
|
|
||||||
use: 'block — блокировка рекламы и трекеров на уровне DNS.',
|
|
||||||
builtIn: false,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
function SubscriptionCard({ state, subscriptionUrl, setSubscriptionUrl, busy, onFetch, onForget, pushToast }) {
|
|
||||||
const [editing, setEditing] = useState(!state?.hasSubscription);
|
|
||||||
|
|
||||||
useEffect(() => { if (!state?.hasSubscription) setEditing(true); }, [state?.hasSubscription]);
|
|
||||||
|
|
||||||
const masked = state?.hasSubscription && !editing;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h2>Подписка</h2>
|
|
||||||
{state?.hasSubscription && (
|
|
||||||
<span className="badge success">● активна</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{masked ? (
|
|
||||||
<div className="kv-list">
|
|
||||||
<div className="row">
|
|
||||||
<span className="key">URL</span>
|
|
||||||
<span className="val text-mono">{state.subscriptionHost}</span>
|
|
||||||
</div>
|
|
||||||
<div className="row">
|
|
||||||
<span className="key">Серверов</span>
|
|
||||||
<span className="val">{state.servers?.length || 0}</span>
|
|
||||||
</div>
|
|
||||||
<div className="row">
|
|
||||||
<span className="key">Загружено</span>
|
|
||||||
<span className="val">{state.fetchedAt ? formatRelative(state.fetchedAt) : '—'}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="field">
|
|
||||||
<span className="field-label">Subscription URL</span>
|
|
||||||
<div className="subscription-input">
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
value={subscriptionUrl}
|
|
||||||
onChange={(e) => setSubscriptionUrl(e.target.value)}
|
|
||||||
placeholder="https://provider.example/sub/..."
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="btn-group" style={{ marginTop: 16 }}>
|
|
||||||
{masked ? (
|
|
||||||
<>
|
|
||||||
<button className="btn btn-secondary" onClick={() => setEditing(true)} disabled={busy}>Изменить URL</button>
|
|
||||||
<button className="btn btn-secondary" onClick={onFetch} disabled={busy}>↻ Обновить серверы</button>
|
|
||||||
<button className="btn btn-danger" onClick={onForget} disabled={busy}>Удалить подписку</button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
className="btn btn-primary"
|
|
||||||
onClick={async () => { await onFetch(); setEditing(false); }}
|
|
||||||
disabled={busy || !subscriptionUrl}
|
|
||||||
>
|
|
||||||
{busy ? 'Загрузка…' : 'Загрузить серверы'}
|
|
||||||
</button>
|
|
||||||
{state?.hasSubscription && (
|
|
||||||
<button className="btn btn-ghost" onClick={() => setEditing(false)}>Отмена</button>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConfigCard({ state, busy, onShowConfig, onClearConfig, pushToast }) {
|
|
||||||
const [validation, setValidation] = useState(null);
|
|
||||||
const [validating, setValidating] = useState(false);
|
|
||||||
|
|
||||||
async function validate() {
|
|
||||||
setValidating(true);
|
|
||||||
try {
|
|
||||||
const data = await api.configValidate();
|
|
||||||
setValidation(data);
|
|
||||||
pushToast({
|
|
||||||
kind: data.valid ? 'success' : 'danger',
|
|
||||||
title: data.valid ? 'Config валиден' : 'Config невалиден',
|
|
||||||
message: data.error || data.note,
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
pushToast({ kind: 'danger', title: 'Ошибка проверки', message: err.message });
|
|
||||||
} finally {
|
|
||||||
setValidating(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h2>sing-box config</h2>
|
|
||||||
{validation && (
|
|
||||||
<span className={`badge ${validation.valid ? 'success' : 'danger'}`}>
|
|
||||||
{validation.valid ? '✓ валиден' : '✗ ошибка'}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="kv-list">
|
|
||||||
<div className="row"><span className="key">Файл</span><span className="val">{state?.configExists ? 'есть' : 'нет'}</span></div>
|
|
||||||
<div className="row"><span className="key">Применено</span><span className="val">{state?.appliedAt ? formatRelative(state.appliedAt) : '—'}</span></div>
|
|
||||||
</div>
|
|
||||||
<div className="btn-group" style={{ marginTop: 16 }}>
|
|
||||||
<button className="btn btn-secondary" disabled={!state?.configExists} onClick={onShowConfig}>Показать config</button>
|
|
||||||
<button className="btn btn-secondary" disabled={validating || !state?.configExists} onClick={validate}>
|
|
||||||
{validating ? 'Проверяем…' : '✓ Валидировать'}
|
|
||||||
</button>
|
|
||||||
<button className="btn btn-danger" disabled={busy || !state?.configExists} onClick={onClearConfig}>
|
|
||||||
Сбросить config
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{validation && !validation.valid && validation.error && (
|
|
||||||
<div className="conflict-banner danger" style={{ marginTop: 12 }}>
|
|
||||||
<span>✗</span><div>{validation.error}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const CATALOG_CATEGORIES = ['Все', ...Array.from(new Set(RULE_SET_CATALOG.map((r) => r.category)))];
|
|
||||||
|
|
||||||
function CatalogEntry({ entry, added, busy, onAdd, onLookup }) {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
return (
|
|
||||||
<div style={{ border: '1px solid var(--border)', borderRadius: 8, padding: '10px 14px', marginBottom: 8 }}>
|
|
||||||
<div className="flex" style={{ alignItems: 'center', gap: 8 }}>
|
|
||||||
<div style={{ flex: 1 }}>
|
|
||||||
<div className="flex" style={{ alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
|
|
||||||
<strong className="text-mono" style={{ fontSize: 13 }}>{entry.tag}</strong>
|
|
||||||
<span className="badge info" style={{ fontSize: 11 }}>{entry.category}</span>
|
|
||||||
<span className="muted" style={{ fontSize: 12 }}>{entry.source}</span>
|
|
||||||
{entry.builtIn && (
|
|
||||||
<span className="badge success" style={{ fontSize: 11 }} title="Загружается автоматически при включённом RU direct">встроен</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div style={{ fontSize: 13, marginTop: 2, color: 'var(--text)' }}>{entry.description}</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex" style={{ gap: 6, flexShrink: 0 }}>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
onClick={() => setOpen((o) => !o)}
|
|
||||||
title="Примеры и подсказка"
|
|
||||||
>
|
|
||||||
{open ? '▲' : '▼'}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm"
|
|
||||||
onClick={() => onLookup(entry)}
|
|
||||||
title="Просмотреть содержимое и искать внутри"
|
|
||||||
>
|
|
||||||
🔍
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary sm"
|
|
||||||
disabled={busy || added}
|
|
||||||
onClick={() => onAdd(entry)}
|
|
||||||
>
|
|
||||||
{added ? '✓ добавлен' : '+ Добавить'}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{open && (
|
|
||||||
<div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
|
|
||||||
<div style={{ fontSize: 12, marginBottom: 6 }}>
|
|
||||||
<span className="muted">Примеры содержимого: </span>
|
|
||||||
{entry.examples.map((ex, i) => (
|
|
||||||
<span key={i}>
|
|
||||||
<code style={{ background: 'var(--bg-muted)', borderRadius: 3, padding: '1px 5px', fontSize: 11 }}>{ex}</code>
|
|
||||||
{i < entry.examples.length - 1 ? ' ' : ''}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div style={{ fontSize: 12 }}>
|
|
||||||
<span className="muted">Рекомендуемый outbound: </span>
|
|
||||||
<span>{entry.use}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SagerNetSearchCard({ ruleSets, onAdd, busy }) {
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [status, setStatus] = useState('idle'); // idle | loading | done | error
|
|
||||||
const [catalog, setCatalog] = useState(null); // { geosite, geoip, cachedAt }
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [query, setQuery] = useState('');
|
|
||||||
const [repoFilter, setRepoFilter] = useState('all'); // all | geosite | geoip
|
|
||||||
|
|
||||||
function load() {
|
|
||||||
if (status !== 'idle') return;
|
|
||||||
setStatus('loading');
|
|
||||||
api.ruleSets.sagernetCatalog()
|
|
||||||
.then((d) => { setCatalog(d); setStatus('done'); })
|
|
||||||
.catch((err) => { setError(err.message); setStatus('error'); });
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggle() {
|
|
||||||
if (!open && status === 'idle') load();
|
|
||||||
setOpen((o) => !o);
|
|
||||||
}
|
|
||||||
|
|
||||||
const results = useMemo(() => {
|
|
||||||
if (!catalog) return [];
|
|
||||||
const q = query.trim().toLowerCase();
|
|
||||||
const toItem = (repo) => (name) => ({ name, repo, url: `https://cdn.jsdelivr.net/gh/SagerNet/sing-${repo}@rule-set/${name}.srs` });
|
|
||||||
const gs = repoFilter !== 'geoip' ? (catalog.geosite || []).map(toItem('geosite')) : [];
|
|
||||||
const gi = repoFilter !== 'geosite' ? (catalog.geoip || []).map(toItem('geoip')) : [];
|
|
||||||
const all = [...gs, ...gi];
|
|
||||||
if (!q) return all;
|
|
||||||
return all.filter((item) => item.name.includes(q));
|
|
||||||
}, [catalog, query, repoFilter]);
|
|
||||||
|
|
||||||
const addedTags = new Set(ruleSets.map((rs) => rs.tag));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header" style={{ cursor: 'pointer' }} onClick={toggle}>
|
|
||||||
<h2>Поиск в каталоге SagerNet</h2>
|
|
||||||
<div className="flex" style={{ gap: 8, alignItems: 'center' }}>
|
|
||||||
{status === 'done' && catalog && (
|
|
||||||
<span className="badge info" style={{ fontSize: 11 }}>
|
|
||||||
{(catalog.geosite?.length || 0) + (catalog.geoip?.length || 0)} rule-sets
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<span className="muted" style={{ fontSize: 13 }}>{open ? '▲' : '▼'}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{open && (
|
|
||||||
<>
|
|
||||||
{status === 'loading' && (
|
|
||||||
<div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--text-muted)' }}>
|
|
||||||
Загрузка списка из GitHub…
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{status === 'error' && (
|
|
||||||
<div className="conflict-banner danger" style={{ marginTop: 8 }}>
|
|
||||||
<span>✗</span><div>{error}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{status === 'done' && (
|
|
||||||
<>
|
|
||||||
<small className="muted" style={{ display: 'block', marginBottom: 12 }}>
|
|
||||||
Полный список rule-sets из репозиториев <strong>SagerNet/sing-geosite</strong> и <strong>SagerNet/sing-geoip</strong>.
|
|
||||||
Ищите по имени: <code>steam</code>, <code>gaming</code>, <code>netflix</code>, <code>apple</code> и т.д.
|
|
||||||
Кеш обновляется раз в 24 ч.
|
|
||||||
</small>
|
|
||||||
{catalog.fallback && (
|
|
||||||
<div className="conflict-banner warning" style={{ marginBottom: 12 }}>
|
|
||||||
<span>!</span><div>{catalog.warning || 'Показан встроенный fallback-каталог.'}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="flex" style={{ gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
style={{ flex: 1, minWidth: 180 }}
|
|
||||||
placeholder="steam, gaming, netflix, cloudflare…"
|
|
||||||
value={query}
|
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
|
||||||
autoFocus
|
|
||||||
/>
|
|
||||||
<select className="select" style={{ width: 130 }} value={repoFilter} onChange={(e) => setRepoFilter(e.target.value)}>
|
|
||||||
<option value="all">geosite + geoip</option>
|
|
||||||
<option value="geosite">только geosite</option>
|
|
||||||
<option value="geoip">только geoip</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{query.trim() === '' ? (
|
|
||||||
<div className="muted" style={{ fontSize: 13, padding: '8px 0' }}>
|
|
||||||
Введите запрос — покажем совпадения ({(catalog.geosite?.length || 0) + (catalog.geoip?.length || 0)} доступно)
|
|
||||||
</div>
|
|
||||||
) : results.length === 0 ? (
|
|
||||||
<div className="muted" style={{ fontSize: 13, padding: '8px 0' }}>Ничего не найдено</div>
|
|
||||||
) : (
|
|
||||||
<table className="table" style={{ fontSize: 13 }}>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th style={{ width: 60 }}>Тип</th>
|
|
||||||
<th>Тег</th>
|
|
||||||
<th style={{ width: 120 }}></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{results.slice(0, 100).map((item) => (
|
|
||||||
<tr key={item.name}>
|
|
||||||
<td><span className={`badge ${item.repo === 'geosite' ? 'info' : ''}`} style={{ fontSize: 11 }}>{item.repo}</span></td>
|
|
||||||
<td className="text-mono">{item.name}</td>
|
|
||||||
<td style={{ textAlign: 'right' }}>
|
|
||||||
{addedTags.has(item.name) ? (
|
|
||||||
<span className="badge success" style={{ fontSize: 11 }}>✓ добавлен</span>
|
|
||||||
) : (
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary sm"
|
|
||||||
disabled={busy}
|
|
||||||
onClick={() => onAdd({ tag: item.name, url: item.url })}
|
|
||||||
>
|
|
||||||
+ Добавить
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
)}
|
|
||||||
{results.length > 100 && (
|
|
||||||
<div className="muted" style={{ fontSize: 12, marginTop: 8 }}>
|
|
||||||
Показано 100 из {results.length} — уточните запрос
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="muted" style={{ fontSize: 11, marginTop: 12 }}>
|
|
||||||
кеш: {catalog.cachedAt ? formatRelative(catalog.cachedAt) : '—'}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function RuleSetsCard({ pushToast }) {
|
|
||||||
const [ruleSets, setRuleSets] = useState([]);
|
|
||||||
const [newTag, setNewTag] = useState('');
|
|
||||||
const [newUrl, setNewUrl] = useState('');
|
|
||||||
const [busy, setBusy] = useState(false);
|
|
||||||
const [search, setSearch] = useState('');
|
|
||||||
const [category, setCategory] = useState('Все');
|
|
||||||
const [lookup, setLookup] = useState(null); // { tag, url }
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
api.ruleSets.get().then((d) => setRuleSets(d.ruleSets || [])).catch(() => {});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
async function save(next) {
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
const data = await api.ruleSets.save(next);
|
|
||||||
setRuleSets(data.ruleSets || []);
|
|
||||||
pushToast({ kind: 'success', title: 'Rule-sets сохранены' });
|
|
||||||
} catch (err) {
|
|
||||||
pushToast({ kind: 'danger', title: 'Ошибка', message: err.message });
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addNew() {
|
|
||||||
const tag = newTag.trim();
|
|
||||||
const url = newUrl.trim();
|
|
||||||
if (!tag || !url) return;
|
|
||||||
if (!/^[a-z0-9][a-z0-9_.@!-]*$/i.test(tag)) {
|
|
||||||
pushToast({ kind: 'danger', title: 'Невалидный тег', message: 'Буквы, цифры и символы - _ . @ !' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (ruleSets.some((rs) => rs.tag === tag)) {
|
|
||||||
pushToast({ kind: 'danger', title: 'Тег уже существует' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const next = [...ruleSets, { tag, url }];
|
|
||||||
setNewTag('');
|
|
||||||
setNewUrl('');
|
|
||||||
save(next);
|
|
||||||
}
|
|
||||||
|
|
||||||
function remove(tag) {
|
|
||||||
save(ruleSets.filter((rs) => rs.tag !== tag));
|
|
||||||
}
|
|
||||||
|
|
||||||
function addFromCatalog(entry) {
|
|
||||||
if (ruleSets.some((rs) => rs.tag === entry.tag)) {
|
|
||||||
pushToast({ kind: 'info', title: `${entry.tag} уже добавлен` });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
save([...ruleSets, { tag: entry.tag, url: entry.url }]);
|
|
||||||
}
|
|
||||||
|
|
||||||
const q = search.trim().toLowerCase();
|
|
||||||
const filtered = RULE_SET_CATALOG.filter((entry) => {
|
|
||||||
if (category !== 'Все' && entry.category !== category) return false;
|
|
||||||
if (!q) return true;
|
|
||||||
return (
|
|
||||||
entry.tag.includes(q) ||
|
|
||||||
entry.description.toLowerCase().includes(q) ||
|
|
||||||
entry.source.toLowerCase().includes(q) ||
|
|
||||||
entry.examples.some((ex) => ex.toLowerCase().includes(q))
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header">
|
|
||||||
<h2>Источники (rule-sets)</h2>
|
|
||||||
</div>
|
|
||||||
<small className="muted" style={{ display: 'block', marginBottom: 16 }}>
|
|
||||||
Geo-базы в формате <strong>.srs</strong> (sing-box). Sing-box скачает их автоматически при применении.
|
|
||||||
<strong> .dat файлы (v2ray) не поддерживаются</strong>.
|
|
||||||
</small>
|
|
||||||
|
|
||||||
{ruleSets.length > 0 && (
|
|
||||||
<>
|
|
||||||
<div className="field-label" style={{ marginBottom: 6 }}>Подключённые</div>
|
|
||||||
<table className="table" style={{ marginBottom: 20 }}>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Тег</th>
|
|
||||||
<th>URL</th>
|
|
||||||
<th></th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{ruleSets.map((rs) => (
|
|
||||||
<tr key={rs.tag}>
|
|
||||||
<td className="text-mono" style={{ whiteSpace: 'nowrap' }}>{rs.tag}</td>
|
|
||||||
<td className="muted" style={{ fontSize: 12, wordBreak: 'break-all' }}>{rs.url}</td>
|
|
||||||
<td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
|
|
||||||
<button className="btn btn-ghost sm" style={{ marginRight: 4 }} onClick={() => setLookup(rs)} title="Просмотреть содержимое">🔍</button>
|
|
||||||
<button className="btn btn-ghost sm" disabled={busy} onClick={() => remove(rs.tag)}>×</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="field-label" style={{ marginBottom: 8 }}>Каталог</div>
|
|
||||||
<div className="flex" style={{ gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
style={{ flex: 1, minWidth: 180 }}
|
|
||||||
placeholder="Поиск: telegram, реклама, youtube…"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
/>
|
|
||||||
<select className="select" style={{ width: 140 }} value={category} onChange={(e) => setCategory(e.target.value)}>
|
|
||||||
{CATALOG_CATEGORIES.map((c) => <option key={c}>{c}</option>)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{filtered.length === 0 && (
|
|
||||||
<div className="muted" style={{ fontSize: 13, marginBottom: 12 }}>Ничего не найдено</div>
|
|
||||||
)}
|
|
||||||
{filtered.map((entry) => (
|
|
||||||
<CatalogEntry
|
|
||||||
key={entry.tag}
|
|
||||||
entry={entry}
|
|
||||||
added={ruleSets.some((rs) => rs.tag === entry.tag)}
|
|
||||||
busy={busy}
|
|
||||||
onAdd={addFromCatalog}
|
|
||||||
onLookup={(e) => setLookup(e)}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
|
|
||||||
<div className="field" style={{ marginTop: 16 }}>
|
|
||||||
<span className="field-label">Добавить свой .srs</span>
|
|
||||||
<div className="flex" style={{ gap: 8, flexWrap: 'wrap' }}>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
style={{ width: 200 }}
|
|
||||||
placeholder="тег (напр. geosite-custom)"
|
|
||||||
value={newTag}
|
|
||||||
onChange={(e) => setNewTag(e.target.value)}
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
style={{ flex: 1, minWidth: 200 }}
|
|
||||||
placeholder="https://…/rule-set.srs"
|
|
||||||
value={newUrl}
|
|
||||||
onChange={(e) => setNewUrl(e.target.value)}
|
|
||||||
/>
|
|
||||||
<button className="btn btn-primary" disabled={busy || !newTag || !newUrl} onClick={addNew}>
|
|
||||||
Добавить
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<SagerNetSearchCard ruleSets={ruleSets} onAdd={addFromCatalog} busy={busy} />
|
|
||||||
{lookup && (
|
|
||||||
<RuleSetLookupModal
|
|
||||||
tag={lookup.tag}
|
|
||||||
url={lookup.url}
|
|
||||||
onClose={() => setLookup(null)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PortsCard({ state }) {
|
|
||||||
const isClient = state?.mode === 'client';
|
|
||||||
return (
|
|
||||||
<div className="card">
|
|
||||||
<div className="card-header"><h2>{isClient ? 'Локальные порты' : 'Порты и маршруты'}</h2></div>
|
|
||||||
<div className="kv-list">
|
|
||||||
<div className="row"><span className="key">UI</span><span className="val text-mono">:{state?.port || 3456}</span></div>
|
|
||||||
<div className="row"><span className="key">HTTP/SOCKS proxy</span><span className="val text-mono">{isClient ? '127.0.0.1' : state?.proxyBindIp || '0.0.0.0'}:{state?.proxyPort || 8080}</span></div>
|
|
||||||
{!isClient && <div className="row"><span className="key">TProxy</span><span className="val text-mono">:{state?.tproxyPort || 7895}</span></div>}
|
|
||||||
<div className="row"><span className="key">RU direct (geoip-ru)</span><span className="val">{state?.routingRuDirect ? 'включено' : 'выключено'}</span></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function SettingsPage({
|
|
||||||
state, subscriptionUrl, setSubscriptionUrl, busy,
|
|
||||||
onFetchSubscription, onForgetSubscription, onShowConfig, onClearConfig, pushToast,
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="section-stack">
|
|
||||||
<SubscriptionCard
|
|
||||||
state={state}
|
|
||||||
subscriptionUrl={subscriptionUrl}
|
|
||||||
setSubscriptionUrl={setSubscriptionUrl}
|
|
||||||
busy={busy}
|
|
||||||
onFetch={onFetchSubscription}
|
|
||||||
onForget={onForgetSubscription}
|
|
||||||
pushToast={pushToast}
|
|
||||||
/>
|
|
||||||
<ConfigCard
|
|
||||||
state={state}
|
|
||||||
busy={busy}
|
|
||||||
onShowConfig={onShowConfig}
|
|
||||||
onClearConfig={onClearConfig}
|
|
||||||
pushToast={pushToast}
|
|
||||||
/>
|
|
||||||
<RuleSetsCard pushToast={pushToast} />
|
|
||||||
<PortsCard state={state} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
|
|
||||||
const NAV = [
|
|
||||||
{ id: 'overview', label: 'Обзор', ico: '◉' },
|
|
||||||
{ id: 'servers', label: 'Серверы', ico: '⋆' },
|
|
||||||
{ id: 'routing', label: 'Маршрутизация', ico: '⇅' },
|
|
||||||
{ id: 'logs', label: 'Логи', ico: '≡' },
|
|
||||||
{ id: 'settings', label: 'Настройки', ico: '⚙' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const WINDOWS_NAV = [
|
|
||||||
{ id: 'overview', label: 'Overview', ico: 'O' },
|
|
||||||
{ id: 'logs', label: 'Logs', ico: 'L' },
|
|
||||||
{ id: 'settings', label: 'Settings', ico: 'S' },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function Sidebar({ active, onChange, badges = {}, mode = 'gateway' }) {
|
|
||||||
const items = mode === 'windows'
|
|
||||||
? WINDOWS_NAV
|
|
||||||
: mode === 'client'
|
|
||||||
? NAV.filter((item) => item.id !== 'routing')
|
|
||||||
: NAV;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<nav className="sidebar">
|
|
||||||
{items.map((item) => {
|
|
||||||
const badge = badges[item.id];
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={item.id}
|
|
||||||
type="button"
|
|
||||||
className={`sidebar-item${active === item.id ? ' active' : ''}`}
|
|
||||||
onClick={() => onChange(item.id)}
|
|
||||||
>
|
|
||||||
<span className="ico">{item.ico}</span>
|
|
||||||
{item.label}
|
|
||||||
{badge && (
|
|
||||||
<span className={`badge ${badge.kind || ''}`}>{badge.text}</span>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import { formatBytes, formatRelative } from '../utils/format.js';
|
|
||||||
|
|
||||||
function StatusRow({ label, value, kind }) {
|
|
||||||
return (
|
|
||||||
<div className="row">
|
|
||||||
<span className="key">{label}</span>
|
|
||||||
<span className={`val ${kind ? 'text-' + kind : ''}`}>{value}</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function StatusPane({ state, busy, onStop, onRestart, onShowConfig }) {
|
|
||||||
const userInfo = state?.userInfo;
|
|
||||||
const traffic = userInfo
|
|
||||||
? `${formatBytes((userInfo.upload || 0) + (userInfo.download || 0))} / ${userInfo.total ? formatBytes(userInfo.total) : '∞'}`
|
|
||||||
: '—';
|
|
||||||
|
|
||||||
let singboxStatus = 'Остановлен';
|
|
||||||
let singboxKind = 'muted';
|
|
||||||
if (state?.singboxRunning) {
|
|
||||||
singboxStatus = `работает · ${formatRelative(state.singboxStartedAt)}`;
|
|
||||||
singboxKind = 'success';
|
|
||||||
} else if (state?.configExists) {
|
|
||||||
singboxStatus = 'остановлен (конфиг есть)';
|
|
||||||
singboxKind = 'warning';
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<aside className="status-pane">
|
|
||||||
<div className="card compact flat">
|
|
||||||
<div className="card-header no-margin">
|
|
||||||
<h3>sing-box</h3>
|
|
||||||
<span className={`badge ${state?.singboxRunning ? 'success' : 'neutral'}`}>
|
|
||||||
{state?.singboxRunning ? '● online' : '○ offline'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="kv-list" style={{ marginTop: 12 }}>
|
|
||||||
<StatusRow label="Статус" value={singboxStatus} kind={singboxKind} />
|
|
||||||
<StatusRow label="UI порт" value={`:${state?.port || 3456}`} />
|
|
||||||
<StatusRow label="Mixed proxy" value={`${state?.proxyBindIp || '0.0.0.0'}:${state?.proxyPort || 8080}`} />
|
|
||||||
<StatusRow label="TProxy" value={`:${state?.tproxyPort || 7895}`} />
|
|
||||||
<StatusRow label="RU direct" value={state?.routingRuDirect ? 'включено' : 'выключено'} />
|
|
||||||
<StatusRow label="Трафик" value={traffic} />
|
|
||||||
<StatusRow
|
|
||||||
label="Применено"
|
|
||||||
value={state?.appliedAt ? formatRelative(state.appliedAt) : 'не применено'}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="btn-group" style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary sm block"
|
|
||||||
disabled={busy || !state?.configExists}
|
|
||||||
onClick={onRestart}
|
|
||||||
>
|
|
||||||
↻ Перезапустить
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm block"
|
|
||||||
disabled={busy || !state?.singboxRunning}
|
|
||||||
onClick={onStop}
|
|
||||||
>
|
|
||||||
■ Остановить
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="btn btn-ghost sm block"
|
|
||||||
disabled={!state?.configExists}
|
|
||||||
onClick={onShowConfig}
|
|
||||||
>
|
|
||||||
⌘ Показать config
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{state?.appliedHistory?.length > 0 && (
|
|
||||||
<div className="card compact flat">
|
|
||||||
<h4 style={{ marginBottom: 8 }}>История применений</h4>
|
|
||||||
<div className="events-list">
|
|
||||||
{state.appliedHistory.slice(0, 5).map((h) => (
|
|
||||||
<div key={h.at} className="event-row" style={{ gridTemplateColumns: '1fr auto' }}>
|
|
||||||
<span className="text-truncate">{h.tag}</span>
|
|
||||||
<span className="event-time">{formatRelative(h.at)}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</aside>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import React, { useEffect } from 'react';
|
|
||||||
|
|
||||||
export function Toasts({ items, onDismiss }) {
|
|
||||||
useEffect(() => {
|
|
||||||
const timers = items.map((t) =>
|
|
||||||
t.sticky ? null : setTimeout(() => onDismiss(t.id), t.duration || 4000),
|
|
||||||
);
|
|
||||||
return () => timers.forEach((t) => t && clearTimeout(t));
|
|
||||||
}, [items, onDismiss]);
|
|
||||||
|
|
||||||
if (!items.length) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="toasts">
|
|
||||||
{items.map((t) => (
|
|
||||||
<div key={t.id} className={`toast ${t.kind || ''}`}>
|
|
||||||
<span className={`dot ${t.kind || ''}`} style={{ marginTop: 4 }} />
|
|
||||||
<div className="body">
|
|
||||||
<strong>{t.title}</strong>
|
|
||||||
{t.message && <small>{t.message}</small>}
|
|
||||||
{t.action && (
|
|
||||||
<button className="btn btn-link sm" onClick={t.action.onClick} style={{ marginTop: 4, padding: 0 }}>
|
|
||||||
{t.action.label}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<button onClick={() => onDismiss(t.id)} title="Закрыть">×</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
import React from 'react';
|
|
||||||
import { formatBytes, formatRelative } from '../utils/format.js';
|
|
||||||
import { flagFor } from '../utils/country.js';
|
|
||||||
|
|
||||||
function StatusBadge({ status }) {
|
|
||||||
const map = {
|
|
||||||
running: { dot: 'success', text: 'Работает', cls: '' },
|
|
||||||
applying: { dot: 'warning pulse', text: 'Применяем…', cls: '' },
|
|
||||||
error: { dot: 'danger', text: 'Ошибка', cls: '' },
|
|
||||||
stopped: { dot: '', text: 'Остановлен', cls: '' },
|
|
||||||
no_config: { dot: '', text: 'Не настроен', cls: '' },
|
|
||||||
};
|
|
||||||
const cfg = map[status] || map.stopped;
|
|
||||||
return (
|
|
||||||
<span className="flex">
|
|
||||||
<span className={`dot ${cfg.dot}`} />
|
|
||||||
<strong>{cfg.text}</strong>
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Topbar({ state, status, activeServer, dirty, onRestart, onTryApply }) {
|
|
||||||
const userInfo = state?.userInfo;
|
|
||||||
const traffic = userInfo
|
|
||||||
? `${formatBytes((userInfo.upload || 0) + (userInfo.download || 0))}${userInfo.total ? ' / ' + formatBytes(userInfo.total) : ''}`
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const isClient = state?.mode === 'client';
|
|
||||||
const isWindows = state?.mode === 'windows';
|
|
||||||
const brand = isWindows ? 'VPN Proxy Windows' : isClient ? 'VPN Client' : 'VPN Gateway';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<header className="topbar">
|
|
||||||
<div className="topbar-brand">
|
|
||||||
<span className="logo-dot" />
|
|
||||||
{brand}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="topbar-status">
|
|
||||||
<StatusBadge status={status} />
|
|
||||||
{isWindows && (
|
|
||||||
<small className="muted">App profiles and ProxiFyre routing</small>
|
|
||||||
)}
|
|
||||||
{!isWindows && activeServer && (
|
|
||||||
<div className="status-text">
|
|
||||||
<strong>
|
|
||||||
{flagFor(activeServer)} {activeServer.tag}
|
|
||||||
</strong>
|
|
||||||
<small>
|
|
||||||
{activeServer.server}:{activeServer.server_port}
|
|
||||||
{state?.appliedAt ? ` · применено ${formatRelative(state.appliedAt)}` : ''}
|
|
||||||
</small>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!isWindows && !activeServer && (
|
|
||||||
<small className="muted">Сервер не выбран</small>
|
|
||||||
)}
|
|
||||||
{!isWindows && traffic && <span className="badge neutral">{traffic}</span>}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="topbar-actions">
|
|
||||||
{!isClient && !isWindows && dirty && (
|
|
||||||
<span className="badge warning">● Несохранённые изменения</span>
|
|
||||||
)}
|
|
||||||
{!isClient && !isWindows && state?.previousTag && (
|
|
||||||
<button className="btn btn-ghost sm" onClick={onTryApply} title="Откатить">
|
|
||||||
↶ Откат
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{!isWindows && (
|
|
||||||
<button
|
|
||||||
className="btn btn-secondary sm"
|
|
||||||
onClick={onRestart}
|
|
||||||
disabled={!state?.configExists}
|
|
||||||
title="Перезапустить sing-box"
|
|
||||||
>
|
|
||||||
↻ Перезапуск
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,261 +0,0 @@
|
|||||||
import React, { useEffect, useMemo, useState } from 'react';
|
|
||||||
import { api } from '../api.js';
|
|
||||||
|
|
||||||
function targetLabel(target) {
|
|
||||||
if (!target) return 'No proxy target';
|
|
||||||
return `${target.name} - ${target.host}:${target.port}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function routeTitle(status) {
|
|
||||||
const helper = status?.helperStatus;
|
|
||||||
const proxifyre = helper?.result?.proxifyre || helper?.proxifyre;
|
|
||||||
const singbox = helper?.result?.singbox || helper?.singbox;
|
|
||||||
if (proxifyre === 'Running' && singbox === 'Running') return 'Apps are routed through local sing-box';
|
|
||||||
if (proxifyre === 'Running') return 'Apps are routed through an existing proxy';
|
|
||||||
return 'App routing is stopped';
|
|
||||||
}
|
|
||||||
|
|
||||||
function routeState(status) {
|
|
||||||
const helper = status?.helperStatus;
|
|
||||||
const proxifyre = helper?.result?.proxifyre || helper?.proxifyre;
|
|
||||||
if (proxifyre === 'Running') return 'running';
|
|
||||||
if (helper?.success === false) return 'error';
|
|
||||||
return 'stopped';
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyProfile() {
|
|
||||||
return {
|
|
||||||
id: `profile-${Date.now()}`,
|
|
||||||
name: 'New profile',
|
|
||||||
enabled: true,
|
|
||||||
proxyTargetId: 'local-singbox',
|
|
||||||
protocols: ['TCP', 'UDP'],
|
|
||||||
items: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function ProfileList({ profiles, selectedId, onSelect }) {
|
|
||||||
return (
|
|
||||||
<div className="win-profile-list">
|
|
||||||
{profiles.map((profile) => (
|
|
||||||
<button
|
|
||||||
key={profile.id}
|
|
||||||
className={`win-profile-row ${profile.id === selectedId ? 'active' : ''}`}
|
|
||||||
onClick={() => onSelect(profile.id)}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
<span className={`win-profile-check ${profile.enabled ? 'on' : ''}`}>on</span>
|
|
||||||
<span>
|
|
||||||
<strong>{profile.name}</strong>
|
|
||||||
<small>{profile.items.length} items - target: {profile.proxyTargetId}</small>
|
|
||||||
</span>
|
|
||||||
<em>{profile.resolvedCount ?? profile.items.length}</em>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ProfileDetails({ profile, targets, onChange }) {
|
|
||||||
const [newItem, setNewItem] = useState('');
|
|
||||||
const [newType, setNewType] = useState('process');
|
|
||||||
if (!profile) {
|
|
||||||
return <div className="win-profile-empty">Select or add a profile.</div>;
|
|
||||||
}
|
|
||||||
function patch(patchValue) {
|
|
||||||
onChange({ ...profile, ...patchValue });
|
|
||||||
}
|
|
||||||
function addItem() {
|
|
||||||
const value = newItem.trim();
|
|
||||||
if (!value) return;
|
|
||||||
patch({
|
|
||||||
items: [
|
|
||||||
...profile.items,
|
|
||||||
{ type: newType, value, recursive: newType === 'folder' },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
setNewItem('');
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<div className="win-detail">
|
|
||||||
<label className="checkbox win-enabled">
|
|
||||||
<input
|
|
||||||
checked={profile.enabled}
|
|
||||||
type="checkbox"
|
|
||||||
onChange={(event) => patch({ enabled: event.target.checked })}
|
|
||||||
/>
|
|
||||||
Enabled profile
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<span>Name</span>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
value={profile.name}
|
|
||||||
onChange={(event) => patch({ name: event.target.value })}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<span>Proxy target</span>
|
|
||||||
<select
|
|
||||||
className="select"
|
|
||||||
value={profile.proxyTargetId}
|
|
||||||
onChange={(event) => patch({ proxyTargetId: event.target.value })}
|
|
||||||
>
|
|
||||||
{targets.map((target) => (
|
|
||||||
<option key={target.id} value={target.id}>{targetLabel(target)}</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<div className="win-add-item">
|
|
||||||
<select className="select" value={newType} onChange={(event) => setNewType(event.target.value)}>
|
|
||||||
<option value="process">Process</option>
|
|
||||||
<option value="folder">Folder</option>
|
|
||||||
<option value="exe">EXE file</option>
|
|
||||||
</select>
|
|
||||||
<input
|
|
||||||
className="input"
|
|
||||||
value={newItem}
|
|
||||||
placeholder="Discord, %LOCALAPPDATA%\\vesktop, or C:\\Games\\game.exe"
|
|
||||||
onChange={(event) => setNewItem(event.target.value)}
|
|
||||||
onKeyDown={(event) => event.key === 'Enter' && addItem()}
|
|
||||||
/>
|
|
||||||
<button className="btn btn-secondary" onClick={addItem} type="button">Add</button>
|
|
||||||
</div>
|
|
||||||
<div className="win-items">
|
|
||||||
{profile.items.map((item, index) => (
|
|
||||||
<div key={`${item.type}-${item.value}-${index}`} className="win-item">
|
|
||||||
<span>{item.value}</span>
|
|
||||||
<small>{item.type}</small>
|
|
||||||
<button
|
|
||||||
className="btn btn-link sm"
|
|
||||||
onClick={() => patch({ items: profile.items.filter((_, i) => i !== index) })}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
Remove
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function WindowsOverviewPage({ pushToast }) {
|
|
||||||
const [status, setStatus] = useState(null);
|
|
||||||
const [profiles, setProfiles] = useState([]);
|
|
||||||
const [targets, setTargets] = useState([]);
|
|
||||||
const [selectedId, setSelectedId] = useState('');
|
|
||||||
const [busy, setBusy] = useState(false);
|
|
||||||
|
|
||||||
async function load() {
|
|
||||||
const data = await api.windows.status();
|
|
||||||
setStatus(data);
|
|
||||||
const nextProfiles = data.profiles || [];
|
|
||||||
setProfiles(nextProfiles);
|
|
||||||
setTargets(data.targets || []);
|
|
||||||
setSelectedId((current) => current || nextProfiles[0]?.id || '');
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
load().catch((error) => pushToast?.({ kind: 'danger', title: 'Windows status failed', message: error.message }));
|
|
||||||
const timer = setInterval(() => load().catch(() => {}), 5000);
|
|
||||||
return () => clearInterval(timer);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const selected = useMemo(
|
|
||||||
() => profiles.find((profile) => profile.id === selectedId) || null,
|
|
||||||
[profiles, selectedId],
|
|
||||||
);
|
|
||||||
|
|
||||||
function replaceProfile(nextProfile) {
|
|
||||||
setProfiles((prev) => prev.map((profile) => profile.id === nextProfile.id ? nextProfile : profile));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function saveProfiles(nextProfiles = profiles) {
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
const data = await api.windows.profiles.save(nextProfiles);
|
|
||||||
setProfiles(data.summaries || data.profiles || []);
|
|
||||||
pushToast?.({ kind: 'success', title: 'Profiles saved' });
|
|
||||||
} catch (error) {
|
|
||||||
pushToast?.({ kind: 'danger', title: 'Save failed', message: error.message });
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function applyProfiles() {
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
await api.windows.profiles.save(profiles);
|
|
||||||
await api.windows.profiles.apply();
|
|
||||||
await load();
|
|
||||||
pushToast?.({ kind: 'success', title: 'ProxiFyre updated' });
|
|
||||||
} catch (error) {
|
|
||||||
pushToast?.({ kind: 'danger', title: 'Apply failed', message: error.message });
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addProfile() {
|
|
||||||
const profile = emptyProfile();
|
|
||||||
setProfiles((prev) => [...prev, profile]);
|
|
||||||
setSelectedId(profile.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="windows-page">
|
|
||||||
<section className="windows-status-panel">
|
|
||||||
<div className="windows-status-main">
|
|
||||||
<span className={`windows-status-dot ${routeState(status)}`} />
|
|
||||||
<div>
|
|
||||||
<h1>{routeTitle(status)}</h1>
|
|
||||||
<p>Profiles send selected apps through ProxiFyre to local sing-box or an existing proxy target.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="windows-route-line">
|
|
||||||
<span>Selected apps</span><b>-></b><span>ProxiFyre</span><b>-></b><span>Proxy target</span>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="windows-workspace">
|
|
||||||
<div className="panel">
|
|
||||||
<div className="panel-head">
|
|
||||||
<div>
|
|
||||||
<h2>Profiles</h2>
|
|
||||||
<small>{profiles.filter((profile) => profile.enabled).length} enabled</small>
|
|
||||||
</div>
|
|
||||||
<button className="btn btn-secondary" onClick={addProfile} type="button">Add profile</button>
|
|
||||||
</div>
|
|
||||||
<ProfileList profiles={profiles} selectedId={selectedId} onSelect={setSelectedId} />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="panel">
|
|
||||||
<div className="panel-head">
|
|
||||||
<div>
|
|
||||||
<h2>{selected?.name || 'Profile'}</h2>
|
|
||||||
<small>{selected ? targetLabel(targets.find((target) => target.id === selected.proxyTargetId)) : 'No selection'}</small>
|
|
||||||
</div>
|
|
||||||
<button className="btn btn-primary" disabled={busy} onClick={applyProfiles} type="button">Apply changes</button>
|
|
||||||
</div>
|
|
||||||
<ProfileDetails profile={selected} targets={targets} onChange={replaceProfile} />
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="panel windows-activity">
|
|
||||||
<div className="panel-head">
|
|
||||||
<h2>Recent activity</h2>
|
|
||||||
<button className="btn btn-secondary" disabled={busy} onClick={() => saveProfiles()} type="button">Save only</button>
|
|
||||||
</div>
|
|
||||||
{(status?.activity || []).slice(0, 5).map((entry) => (
|
|
||||||
<div key={entry.id} className="windows-activity-row">
|
|
||||||
<strong>{entry.type}</strong>
|
|
||||||
<span>{entry.message}</span>
|
|
||||||
<small>{entry.ts}</small>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
2123
src/web/styles.css
2123
src/web/styles.css
File diff suppressed because it is too large
Load Diff
@@ -1,127 +0,0 @@
|
|||||||
// Готовые шаблоны правил роутинга. domains/suffixes/cidr/ports собраны из публичных
|
|
||||||
// reference-конфигов sing-box. Это пресеты «на старт», а не исчерпывающие списки.
|
|
||||||
|
|
||||||
let counter = 0;
|
|
||||||
function id(prefix) {
|
|
||||||
counter += 1;
|
|
||||||
return `${prefix}-${Date.now()}-${counter}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function template(name, outbound, fields) {
|
|
||||||
return {
|
|
||||||
id: id("tpl"),
|
|
||||||
name,
|
|
||||||
enabled: true,
|
|
||||||
outbound,
|
|
||||||
domains: [],
|
|
||||||
domainSuffixes: [],
|
|
||||||
domainKeywords: [],
|
|
||||||
ipCidrs: [],
|
|
||||||
ports: [],
|
|
||||||
networks: [],
|
|
||||||
...fields,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const ruleTemplates = [
|
|
||||||
{
|
|
||||||
key: "lol-direct",
|
|
||||||
label: "League of Legends → direct",
|
|
||||||
description: "Riot/LoL домены и порты — играть напрямую без VPN.",
|
|
||||||
build: () =>
|
|
||||||
template("League of Legends", "direct", {
|
|
||||||
domainSuffixes: [
|
|
||||||
"leagueoflegends.com",
|
|
||||||
"riotgames.com",
|
|
||||||
"riotcdn.net",
|
|
||||||
"dyn.riotcdn.net",
|
|
||||||
],
|
|
||||||
ports: ["5000", "5223", "5222", "8088"],
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "discord-direct",
|
|
||||||
label: "Discord/Vesktop → direct",
|
|
||||||
description: "Discord voice/video и WebSocket напрямую.",
|
|
||||||
build: () =>
|
|
||||||
template("Discord", "direct", {
|
|
||||||
domainSuffixes: [
|
|
||||||
"discord.com",
|
|
||||||
"discord.gg",
|
|
||||||
"discord.media",
|
|
||||||
"discordapp.com",
|
|
||||||
"discordapp.net",
|
|
||||||
],
|
|
||||||
ports: ["50000-65535"],
|
|
||||||
networks: ["udp"],
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "telegram-vpn",
|
|
||||||
label: "Telegram → VPN",
|
|
||||||
description: "Telegram через выбранный VPN outbound.",
|
|
||||||
build: () =>
|
|
||||||
template("Telegram", "vpn", {
|
|
||||||
domainSuffixes: [
|
|
||||||
"telegram.org",
|
|
||||||
"t.me",
|
|
||||||
"telegram.me",
|
|
||||||
"telegra.ph",
|
|
||||||
"tdesktop.com",
|
|
||||||
],
|
|
||||||
ipCidrs: [
|
|
||||||
"149.154.160.0/20",
|
|
||||||
"91.108.4.0/22",
|
|
||||||
"91.108.8.0/22",
|
|
||||||
"91.108.12.0/22",
|
|
||||||
"91.108.16.0/22",
|
|
||||||
"91.108.56.0/22",
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "youtube-vpn",
|
|
||||||
label: "YouTube → VPN",
|
|
||||||
description: "YouTube/Google Video через VPN.",
|
|
||||||
build: () =>
|
|
||||||
template("YouTube", "vpn", {
|
|
||||||
domainSuffixes: [
|
|
||||||
"youtube.com",
|
|
||||||
"youtu.be",
|
|
||||||
"ytimg.com",
|
|
||||||
"googlevideo.com",
|
|
||||||
"youtube-nocookie.com",
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "steam-direct",
|
|
||||||
label: "Steam → direct",
|
|
||||||
description: "Загрузка/обновления Steam напрямую.",
|
|
||||||
build: () =>
|
|
||||||
template("Steam", "direct", {
|
|
||||||
domainSuffixes: [
|
|
||||||
"steampowered.com",
|
|
||||||
"steamcontent.com",
|
|
||||||
"steamcommunity.com",
|
|
||||||
"steamserver.net",
|
|
||||||
"cm.steampowered.com",
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "ads-block",
|
|
||||||
label: "Реклама → block",
|
|
||||||
description: "Базовый набор рекламных доменов — заблокировать.",
|
|
||||||
build: () =>
|
|
||||||
template("Реклама (block)", "block", {
|
|
||||||
domainSuffixes: [
|
|
||||||
"doubleclick.net",
|
|
||||||
"googlesyndication.com",
|
|
||||||
"googleadservices.com",
|
|
||||||
"adservice.google.com",
|
|
||||||
"adnxs.com",
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
65
src/web/utils/clientControls.js
Normal file
65
src/web/utils/clientControls.js
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
export function connectionAction({ connected, selectedTag, configExists }) {
|
||||||
|
if (connected) return { type: 'stop' };
|
||||||
|
if (selectedTag) return { type: 'apply', selectedTag };
|
||||||
|
if (configExists) return { type: 'restart' };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatConnectionDuration(startedAt, now = Date.now()) {
|
||||||
|
const started = Date.parse(startedAt);
|
||||||
|
const totalSeconds = Number.isFinite(started)
|
||||||
|
? Math.max(0, Math.floor((now - started) / 1000))
|
||||||
|
: 0;
|
||||||
|
const hours = Math.floor(totalSeconds / 3600);
|
||||||
|
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||||
|
const seconds = totalSeconds % 60;
|
||||||
|
|
||||||
|
return [hours, minutes, seconds]
|
||||||
|
.map((part) => String(part).padStart(2, '0'))
|
||||||
|
.join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscriptionDomain(subscriptionHost) {
|
||||||
|
const value = String(subscriptionHost || '');
|
||||||
|
try {
|
||||||
|
return new URL(value).host;
|
||||||
|
} catch {
|
||||||
|
return value.split('/')[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function localProxyUrls(port = 8082, host = '127.0.0.1') {
|
||||||
|
const urlHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
|
||||||
|
return {
|
||||||
|
socks5: `socks5://${urlHost}:${port}`,
|
||||||
|
http: `http://${urlHost}:${port}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscriptionUsage(userInfo = {}) {
|
||||||
|
const upload = Math.max(0, Number(userInfo.upload) || 0);
|
||||||
|
const download = Math.max(0, Number(userInfo.download) || 0);
|
||||||
|
const total = Math.max(0, Number(userInfo.total) || 0);
|
||||||
|
const used = upload + download;
|
||||||
|
|
||||||
|
return {
|
||||||
|
upload,
|
||||||
|
download,
|
||||||
|
total,
|
||||||
|
used,
|
||||||
|
percent: total ? Math.min(100, (used / total) * 100) : null,
|
||||||
|
expiresAt: userInfo.expire ? new Date(Number(userInfo.expire) * 1000) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscriptionDaysLeft(expiresAt, now = Date.now()) {
|
||||||
|
const days = Math.ceil((expiresAt?.getTime() - now) / 86_400_000);
|
||||||
|
if (!Number.isFinite(days)) return '';
|
||||||
|
if (days <= 0) return 'срок истёк';
|
||||||
|
const mod10 = days % 10;
|
||||||
|
const mod100 = days % 100;
|
||||||
|
const unit = mod10 === 1 && mod100 !== 11
|
||||||
|
? 'день'
|
||||||
|
: mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14) ? 'дня' : 'дней';
|
||||||
|
return `${days === 1 ? 'остался' : 'осталось'} ${days} ${unit}`;
|
||||||
|
}
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
export function resolveClientRoute({ state, activeServer } = {}) {
|
|
||||||
const settings = state?.clientSettings || {};
|
|
||||||
const localProxy = `127.0.0.1:${state?.proxyPort || settings.proxyPort || 8080}`;
|
|
||||||
const running = Boolean(state?.singboxRunning);
|
|
||||||
const hasConfig = Boolean(state?.configExists);
|
|
||||||
|
|
||||||
let mode = "none";
|
|
||||||
let target = "выберите режим";
|
|
||||||
let targetDetail = "Gateway, локальный VPN или напрямую";
|
|
||||||
let title = "Не подключено";
|
|
||||||
let description = "Выберите режим подключения и примените его.";
|
|
||||||
let pathTarget = "не выбран";
|
|
||||||
|
|
||||||
if (settings.sharedProxyEnabled && settings.sharedProxy) {
|
|
||||||
mode = "gateway";
|
|
||||||
target = `${settings.sharedProxy.host}:${settings.sharedProxy.port}`;
|
|
||||||
targetDetail = "общий gateway proxy";
|
|
||||||
title = running ? "Подключено к gateway" : "Gateway настроен, но остановлен";
|
|
||||||
description = "Локальный proxy на Mac отправляет трафик на серверный gateway.";
|
|
||||||
pathTarget = `Gateway ${target}`;
|
|
||||||
} else if (settings.homeBypassEnabled) {
|
|
||||||
mode = "direct";
|
|
||||||
target = "без VPN";
|
|
||||||
targetDetail = "прямое подключение";
|
|
||||||
title = running ? "Подключено напрямую" : "Direct настроен, но остановлен";
|
|
||||||
description = "Приложения используют локальный proxy, но трафик идет напрямую.";
|
|
||||||
pathTarget = "Direct";
|
|
||||||
} else if (state?.selectedTag) {
|
|
||||||
mode = "vpn";
|
|
||||||
target = activeServer?.tag || state.selectedTag;
|
|
||||||
targetDetail = "локальный VPN";
|
|
||||||
title = running ? "Подключено через VPN" : "VPN настроен, но остановлен";
|
|
||||||
description = "Локальный proxy на Mac отправляет трафик через выбранный VPN-сервер.";
|
|
||||||
pathTarget = `VPN ${target}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const status = running
|
|
||||||
? "connected"
|
|
||||||
: hasConfig && mode !== "none"
|
|
||||||
? "stopped"
|
|
||||||
: "empty";
|
|
||||||
|
|
||||||
if (status === "empty") {
|
|
||||||
title = "Не подключено";
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
mode,
|
|
||||||
status,
|
|
||||||
localProxy,
|
|
||||||
title,
|
|
||||||
target,
|
|
||||||
targetDetail,
|
|
||||||
description,
|
|
||||||
path: ["Mac apps", localProxy, pathTarget, "Internet"],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
// Грубое определение страны по тегу сервера и/или хосту.
|
|
||||||
// Это эвристика — мы не делаем GeoIP-lookup.
|
|
||||||
|
|
||||||
const COUNTRIES = [
|
|
||||||
{ re: /\b(ru|россия|russia|moscow|spb)\b/i, code: "RU", flag: "🇷🇺" },
|
|
||||||
{ re: /\b(de|germany|frankfurt|berlin|deu)\b/i, code: "DE", flag: "🇩🇪" },
|
|
||||||
{ re: /\b(nl|netherlands|amsterdam|holland)\b/i, code: "NL", flag: "🇳🇱" },
|
|
||||||
{
|
|
||||||
re: /\b(us|usa|america|new[-_ ]?york|chicago|miami)\b/i,
|
|
||||||
code: "US",
|
|
||||||
flag: "🇺🇸",
|
|
||||||
},
|
|
||||||
{ re: /\b(uk|britain|london|england)\b/i, code: "GB", flag: "🇬🇧" },
|
|
||||||
{ re: /\b(fr|france|paris)\b/i, code: "FR", flag: "🇫🇷" },
|
|
||||||
{ re: /\b(jp|japan|tokyo)\b/i, code: "JP", flag: "🇯🇵" },
|
|
||||||
{ re: /\b(sg|singapore)\b/i, code: "SG", flag: "🇸🇬" },
|
|
||||||
{ re: /\b(hk|hongkong|hong[-_ ]?kong)\b/i, code: "HK", flag: "🇭🇰" },
|
|
||||||
{ re: /\b(fi|finland|helsinki)\b/i, code: "FI", flag: "🇫🇮" },
|
|
||||||
{ re: /\b(se|sweden|stockholm)\b/i, code: "SE", flag: "🇸🇪" },
|
|
||||||
{ re: /\b(pl|poland|warsaw)\b/i, code: "PL", flag: "🇵🇱" },
|
|
||||||
{ re: /\b(tr|turkey|istanbul)\b/i, code: "TR", flag: "🇹🇷" },
|
|
||||||
{ re: /\b(ua|ukraine|kiev|kyiv)\b/i, code: "UA", flag: "🇺🇦" },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function detectCountry(...inputs) {
|
|
||||||
const text = inputs.filter(Boolean).join(" ").toLowerCase();
|
|
||||||
for (const c of COUNTRIES) {
|
|
||||||
if (c.re.test(text)) return c;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function flagFor(server) {
|
|
||||||
if (!server) return "";
|
|
||||||
const detected = detectCountry(server.tag, server.server);
|
|
||||||
return detected?.flag || "🌐";
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
// Простые валидаторы для полей правил роутинга. Возвращают массив ошибочных строк.
|
|
||||||
|
|
||||||
const IPV4 =
|
|
||||||
/^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/;
|
|
||||||
const IPV6 = /^[0-9a-f:]+$/i;
|
|
||||||
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;
|
|
||||||
|
|
||||||
export function invalidCidrs(values) {
|
|
||||||
return (values || []).filter((value) => !isValidCidr(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isValidCidr(value) {
|
|
||||||
const trimmed = String(value || "").trim();
|
|
||||||
if (!trimmed) return false;
|
|
||||||
const [addr, mask] = trimmed.split("/");
|
|
||||||
if (!addr) return false;
|
|
||||||
|
|
||||||
if (IPV4.test(addr)) {
|
|
||||||
if (mask === undefined) return true;
|
|
||||||
const m = Number(mask);
|
|
||||||
return Number.isInteger(m) && m >= 0 && m <= 32;
|
|
||||||
}
|
|
||||||
if (IPV6.test(addr) && addr.includes(":")) {
|
|
||||||
if (mask === undefined) return true;
|
|
||||||
const m = Number(mask);
|
|
||||||
return Number.isInteger(m) && m >= 0 && m <= 128;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function invalidPorts(values) {
|
|
||||||
return (values || []).filter((value) => !isValidPort(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isValidPort(value) {
|
|
||||||
const n = Number.parseInt(String(value).trim(), 10);
|
|
||||||
return Number.isInteger(n) && n > 0 && n <= 65535;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function invalidDomains(values) {
|
|
||||||
return (values || []).filter((value) => !DOMAIN.test(String(value).trim()));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ruleErrors(rule) {
|
|
||||||
return {
|
|
||||||
domains: invalidDomains(rule.domains),
|
|
||||||
domainSuffixes: invalidDomains(rule.domainSuffixes),
|
|
||||||
ipCidrs: invalidCidrs(rule.ipCidrs),
|
|
||||||
ports: invalidPorts(rule.ports),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function hasErrors(errors) {
|
|
||||||
return Object.values(errors).some((arr) => arr.length > 0);
|
|
||||||
}
|
|
||||||
15
test/server/entrypoint-tproxy.test.js
Normal file
15
test/server/entrypoint-tproxy.test.js
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
const entrypoint = fs.readFileSync(
|
||||||
|
path.resolve(import.meta.dirname, '../../entrypoint.sh'),
|
||||||
|
'utf8',
|
||||||
|
);
|
||||||
|
|
||||||
|
test('gateway intercepts all public TCP and UDP traffic without source bypasses', () => {
|
||||||
|
assert.match(entrypoint, /-p tcp -j TPROXY --on-port "\$TPROXY_PORT"/);
|
||||||
|
assert.match(entrypoint, /-p udp -j TPROXY --on-port "\$TPROXY_PORT"/);
|
||||||
|
assert.doesNotMatch(entrypoint, /TPROXY_BYPASS_SOURCE_CIDRS|DIRECT_BYPASS_CACHE|ipset/);
|
||||||
|
});
|
||||||
@@ -1,130 +1,34 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from 'node:assert/strict';
|
||||||
import fs from "node:fs";
|
import fs from 'node:fs';
|
||||||
import os from "node:os";
|
import os from 'node:os';
|
||||||
import path from "node:path";
|
import path from 'node:path';
|
||||||
import test from "node:test";
|
import test from 'node:test';
|
||||||
|
|
||||||
process.env.APP_MODE = "client";
|
process.env.APP_MODE = 'client';
|
||||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "vpn-proxy-test-"));
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'vpn-proxy-client-test-'));
|
||||||
process.env.SING_BOX_CACHE = path.join(process.env.DATA_DIR, "cache.db");
|
process.env.SING_BOX_CACHE = path.join(process.env.DATA_DIR, 'cache.db');
|
||||||
|
|
||||||
const { buildGatewayConfig } = await import(
|
const { buildGatewayConfig } = await import(`../../src/server/singbox.js?client=${Date.now()}`);
|
||||||
`../../src/server/singbox.js?client-mode=${Date.now()}`
|
|
||||||
);
|
|
||||||
const clientSettingsPath = path.join(process.env.DATA_DIR, "client-settings.json");
|
|
||||||
|
|
||||||
const subscriptionConfig = {
|
const subscriptionConfig = {
|
||||||
outbounds: [
|
outbounds: [{
|
||||||
{
|
type: 'vless',
|
||||||
type: "vless",
|
tag: 'test-vpn',
|
||||||
tag: "test-vpn",
|
server: 'vpn.example.test',
|
||||||
server: "vpn.example.test",
|
|
||||||
server_port: 443,
|
server_port: 443,
|
||||||
uuid: "00000000-0000-4000-8000-000000000000",
|
uuid: '00000000-0000-4000-8000-000000000000',
|
||||||
tls: { enabled: true },
|
tls: { enabled: true },
|
||||||
},
|
}],
|
||||||
],
|
|
||||||
customRules: [],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
test("client mode exposes only the local mixed proxy inbound", () => {
|
test('client exposes one local proxy and routes it through the selected VPN', () => {
|
||||||
fs.rmSync(clientSettingsPath, { force: true });
|
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn');
|
||||||
const config = buildGatewayConfig(subscriptionConfig, "test-vpn");
|
|
||||||
|
|
||||||
assert.deepEqual(
|
assert.deepEqual(config.inbounds.map((inbound) => inbound.tag), ['mixed-in']);
|
||||||
config.inbounds.map((inbound) => inbound.tag),
|
assert.equal(config.inbounds[0].listen_port, 8082);
|
||||||
["mixed-in"],
|
|
||||||
);
|
|
||||||
assert.equal(config.inbounds[0].type, "mixed");
|
|
||||||
assert.equal(config.inbounds[0].listen_port, 8080);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("client mode routes mixed proxy fallback to the selected VPN", () => {
|
|
||||||
fs.rmSync(clientSettingsPath, { force: true });
|
|
||||||
const config = buildGatewayConfig(subscriptionConfig, "test-vpn");
|
|
||||||
|
|
||||||
assert.deepEqual(config.route.rule_set, []);
|
|
||||||
assert.deepEqual(config.route.rules, [
|
assert.deepEqual(config.route.rules, [
|
||||||
{ inbound: ["mixed-in"], outbound: "test-vpn" },
|
{ inbound: ['mixed-in'], outbound: 'test-vpn' },
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("client home bypass routes the local proxy directly", () => {
|
|
||||||
fs.rmSync(clientSettingsPath, { force: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
clientSettingsPath,
|
|
||||||
JSON.stringify({ homeBypassEnabled: true }),
|
|
||||||
);
|
|
||||||
|
|
||||||
const config = buildGatewayConfig(subscriptionConfig, "test-vpn");
|
|
||||||
|
|
||||||
assert.deepEqual(config.route.rule_set, []);
|
|
||||||
assert.deepEqual(config.route.rules, [
|
|
||||||
{ inbound: ["mixed-in"], outbound: "direct" },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("client home bypass can build direct proxy without local VPN", () => {
|
|
||||||
fs.rmSync(clientSettingsPath, { force: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
clientSettingsPath,
|
|
||||||
JSON.stringify({ homeBypassEnabled: true }),
|
|
||||||
);
|
|
||||||
|
|
||||||
const config = buildGatewayConfig({ outbounds: [], customRules: [] }, "");
|
|
||||||
|
|
||||||
assert.deepEqual(config.outbounds, [
|
|
||||||
{ type: "direct", tag: "direct" },
|
|
||||||
{ type: "block", tag: "block" },
|
|
||||||
]);
|
|
||||||
assert.deepEqual(config.route.rules, [
|
|
||||||
{ inbound: ["mixed-in"], outbound: "direct" },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("client mode uses selected proxy port from client settings", () => {
|
|
||||||
fs.rmSync(clientSettingsPath, { force: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
clientSettingsPath,
|
|
||||||
JSON.stringify({ proxyPort: 8085 }),
|
|
||||||
);
|
|
||||||
|
|
||||||
const config = buildGatewayConfig(subscriptionConfig, "test-vpn");
|
|
||||||
|
|
||||||
assert.equal(config.inbounds[0].listen_port, 8085);
|
|
||||||
assert.deepEqual(config.route.rules, [
|
|
||||||
{ inbound: ["mixed-in"], outbound: "test-vpn" },
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("client shared proxy mode routes local proxy to gateway socks outbound", () => {
|
|
||||||
fs.rmSync(clientSettingsPath, { force: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
clientSettingsPath,
|
|
||||||
JSON.stringify({
|
|
||||||
sharedProxyEnabled: true,
|
|
||||||
sharedProxy: {
|
|
||||||
host: "192.168.50.111",
|
|
||||||
port: 8080,
|
|
||||||
protocol: "socks5",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const config = buildGatewayConfig({ outbounds: [], customRules: [] }, "");
|
|
||||||
|
|
||||||
assert.deepEqual(config.inbounds.map((inbound) => inbound.tag), ["mixed-in"]);
|
|
||||||
assert.deepEqual(
|
|
||||||
config.outbounds.find((outbound) => outbound.tag === "shared-proxy"),
|
|
||||||
{
|
|
||||||
type: "socks",
|
|
||||||
tag: "shared-proxy",
|
|
||||||
server: "192.168.50.111",
|
|
||||||
server_port: 8080,
|
|
||||||
version: "5",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert.deepEqual(config.route.rules, [
|
|
||||||
{ inbound: ["mixed-in"], outbound: "shared-proxy" },
|
|
||||||
]);
|
]);
|
||||||
|
assert.equal(config.route.final, 'test-vpn');
|
||||||
|
assert.equal(config.route.auto_detect_interface, undefined);
|
||||||
});
|
});
|
||||||
|
|||||||
33
test/server/singbox-gateway-mode.test.js
Normal file
33
test/server/singbox-gateway-mode.test.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
process.env.APP_MODE = 'gateway';
|
||||||
|
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'vpn-proxy-gateway-test-'));
|
||||||
|
process.env.SING_BOX_CACHE = path.join(process.env.DATA_DIR, 'cache.db');
|
||||||
|
|
||||||
|
const { buildGatewayConfig } = await import(`../../src/server/singbox.js?gateway=${Date.now()}`);
|
||||||
|
|
||||||
|
const subscriptionConfig = {
|
||||||
|
outbounds: [{
|
||||||
|
type: 'vless',
|
||||||
|
tag: 'test-vpn',
|
||||||
|
server: 'vpn.example.test',
|
||||||
|
server_port: 443,
|
||||||
|
uuid: '00000000-0000-4000-8000-000000000000',
|
||||||
|
tls: { enabled: true },
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
|
||||||
|
test('gateway routes transparent and proxy traffic only through the selected VPN', () => {
|
||||||
|
const config = buildGatewayConfig(subscriptionConfig, 'test-vpn');
|
||||||
|
|
||||||
|
assert.deepEqual(config.route.rule_set, []);
|
||||||
|
assert.deepEqual(config.route.rules, [
|
||||||
|
{ inbound: ['tproxy-in'], outbound: 'test-vpn' },
|
||||||
|
{ inbound: ['mixed-in'], outbound: 'test-vpn' },
|
||||||
|
]);
|
||||||
|
assert.equal(config.route.final, 'test-vpn');
|
||||||
|
});
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import fs from "node:fs";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import test from "node:test";
|
|
||||||
|
|
||||||
process.env.APP_MODE = "windows";
|
|
||||||
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "vpn-proxy-windows-test-"));
|
|
||||||
process.env.SING_BOX_CACHE = path.join(process.env.DATA_DIR, "cache.db");
|
|
||||||
process.env.PROXY_PORT = "1080";
|
|
||||||
process.env.PROXY_BIND_IP = "127.0.0.1";
|
|
||||||
|
|
||||||
const { settings } = await import(
|
|
||||||
`../../src/server/config.js?windows-mode=${Date.now()}`
|
|
||||||
);
|
|
||||||
const { buildGatewayConfig } = await import(
|
|
||||||
`../../src/server/singbox.js?windows-mode=${Date.now()}`
|
|
||||||
);
|
|
||||||
|
|
||||||
const subscriptionConfig = {
|
|
||||||
outbounds: [
|
|
||||||
{
|
|
||||||
type: "vless",
|
|
||||||
tag: "win-vpn",
|
|
||||||
server: "vpn.example.test",
|
|
||||||
server_port: 443,
|
|
||||||
uuid: "00000000-0000-4000-8000-000000000000",
|
|
||||||
tls: { enabled: true },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
customRules: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
test("settings accepts APP_MODE=windows", () => {
|
|
||||||
assert.equal(settings.appMode, "windows");
|
|
||||||
assert.equal(settings.proxyPort, 1080);
|
|
||||||
assert.equal(settings.bindIp, "127.0.0.1");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("windows mode exposes only local mixed proxy inbound", () => {
|
|
||||||
const config = buildGatewayConfig(subscriptionConfig, "win-vpn");
|
|
||||||
|
|
||||||
assert.deepEqual(config.inbounds.map((inbound) => inbound.tag), ["mixed-in"]);
|
|
||||||
assert.equal(config.inbounds[0].type, "mixed");
|
|
||||||
assert.equal(config.inbounds[0].listen, "127.0.0.1");
|
|
||||||
assert.equal(config.inbounds[0].listen_port, 1080);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("windows mode routes mixed proxy to selected VPN outbound", () => {
|
|
||||||
const config = buildGatewayConfig(subscriptionConfig, "win-vpn");
|
|
||||||
|
|
||||||
assert.deepEqual(config.route.rule_set, []);
|
|
||||||
assert.deepEqual(config.route.rules, [
|
|
||||||
{ inbound: ["mixed-in"], outbound: "win-vpn" },
|
|
||||||
]);
|
|
||||||
assert.deepEqual(config.outbounds.map((outbound) => outbound.tag), [
|
|
||||||
"win-vpn",
|
|
||||||
"direct",
|
|
||||||
"block",
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
12
test/server/subscription.test.js
Normal file
12
test/server/subscription.test.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import { parseSubscriptionBody } from '../../src/server/subscription.js';
|
||||||
|
|
||||||
|
test('subscription server tags are trimmed for selection', () => {
|
||||||
|
const { servers } = parseSubscriptionBody(JSON.stringify({
|
||||||
|
outbounds: [{ type: 'vless', tag: 'de-frankfurt ', server: 'de.example', server_port: 443 }],
|
||||||
|
}));
|
||||||
|
|
||||||
|
assert.equal(servers[0].tag, 'de-frankfurt');
|
||||||
|
});
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
import {
|
|
||||||
buildProxiFyreConfig,
|
|
||||||
normalizeProxyTargets,
|
|
||||||
normalizeWindowsProfiles,
|
|
||||||
summarizeProfiles,
|
|
||||||
} from "../../src/server/windowsProfiles.js";
|
|
||||||
|
|
||||||
test("windows API model returns summaries and generated config", () => {
|
|
||||||
const profiles = normalizeWindowsProfiles([
|
|
||||||
{
|
|
||||||
name: "Discord",
|
|
||||||
proxyTargetId: "local-singbox",
|
|
||||||
items: [{ type: "process", value: "Discord" }],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const targets = normalizeProxyTargets([]);
|
|
||||||
|
|
||||||
const summaries = summarizeProfiles(profiles, targets);
|
|
||||||
const config = buildProxiFyreConfig(profiles, targets);
|
|
||||||
|
|
||||||
assert.equal(summaries[0].resolvedCount, 1);
|
|
||||||
assert.equal(summaries[0].target.id, "local-singbox");
|
|
||||||
assert.deepEqual(config.proxies[0].appNames, ["Discord"]);
|
|
||||||
});
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
import { createWindowsHelper } from "../../src/server/windowsHelper.js";
|
|
||||||
|
|
||||||
test("windows helper sends action and payload as JSON", async () => {
|
|
||||||
const calls = [];
|
|
||||||
const helper = createWindowsHelper({
|
|
||||||
helperPath: "scripts/windows/helper.ps1",
|
|
||||||
runner: async (command, args, options) => {
|
|
||||||
calls.push({ command, args, input: options.input });
|
|
||||||
return {
|
|
||||||
status: 0,
|
|
||||||
stdout: JSON.stringify({
|
|
||||||
success: true,
|
|
||||||
action: "status.get",
|
|
||||||
result: { proxifyre: "Running" },
|
|
||||||
}),
|
|
||||||
stderr: "",
|
|
||||||
};
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await helper.run("status.get", { service: "ProxiFyre" });
|
|
||||||
|
|
||||||
assert.deepEqual(result, {
|
|
||||||
success: true,
|
|
||||||
action: "status.get",
|
|
||||||
result: { proxifyre: "Running" },
|
|
||||||
});
|
|
||||||
assert.equal(calls[0].command, "pwsh");
|
|
||||||
assert.deepEqual(calls[0].args, [
|
|
||||||
"-NoProfile",
|
|
||||||
"-ExecutionPolicy",
|
|
||||||
"Bypass",
|
|
||||||
"-File",
|
|
||||||
"scripts/windows/helper.ps1",
|
|
||||||
]);
|
|
||||||
assert.deepEqual(JSON.parse(calls[0].input), {
|
|
||||||
action: "status.get",
|
|
||||||
payload: { service: "ProxiFyre" },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("windows helper normalizes non-zero exit into structured error", async () => {
|
|
||||||
const helper = createWindowsHelper({
|
|
||||||
helperPath: "scripts/windows/helper.ps1",
|
|
||||||
runner: async () => ({
|
|
||||||
status: 1,
|
|
||||||
stdout: "",
|
|
||||||
stderr: "service failed",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
await assert.rejects(
|
|
||||||
() => helper.run("service.restart", { name: "proxifyre" }),
|
|
||||||
/Windows helper failed: service failed/,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("windows helper rejects invalid JSON stdout", async () => {
|
|
||||||
const helper = createWindowsHelper({
|
|
||||||
helperPath: "scripts/windows/helper.ps1",
|
|
||||||
runner: async () => ({
|
|
||||||
status: 0,
|
|
||||||
stdout: "not-json",
|
|
||||||
stderr: "",
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
await assert.rejects(
|
|
||||||
() => helper.run("status.get", {}),
|
|
||||||
/Windows helper returned invalid JSON/,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
import {
|
|
||||||
buildProxiFyreConfig,
|
|
||||||
normalizeProxyTargets,
|
|
||||||
normalizeWindowsProfiles,
|
|
||||||
resolveProfileItems,
|
|
||||||
} from "../../src/server/windowsProfiles.js";
|
|
||||||
|
|
||||||
test("normalizeWindowsProfiles keeps process folder and exe source items", () => {
|
|
||||||
const profiles = normalizeWindowsProfiles([
|
|
||||||
{
|
|
||||||
id: "Discord + Vesktop",
|
|
||||||
name: "Discord + Vesktop",
|
|
||||||
enabled: true,
|
|
||||||
proxyTargetId: "local-singbox",
|
|
||||||
protocols: ["TCP", "UDP", "bad"],
|
|
||||||
items: [
|
|
||||||
{ type: "process", value: "Discord.exe" },
|
|
||||||
{ type: "folder", value: "%LOCALAPPDATA%\\vesktop", recursive: true },
|
|
||||||
{ type: "exe", value: "C:\\Games\\SomeGame\\game.exe" },
|
|
||||||
{ type: "bad", value: "ignored" },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.deepEqual(profiles, [
|
|
||||||
{
|
|
||||||
id: "discord-vesktop",
|
|
||||||
name: "Discord + Vesktop",
|
|
||||||
enabled: true,
|
|
||||||
proxyTargetId: "local-singbox",
|
|
||||||
protocols: ["TCP", "UDP"],
|
|
||||||
items: [
|
|
||||||
{ type: "process", value: "Discord", recursive: false },
|
|
||||||
{ type: "folder", value: "%LOCALAPPDATA%\\vesktop", recursive: true },
|
|
||||||
{ type: "exe", value: "C:\\Games\\SomeGame\\game.exe", recursive: false },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("normalizeProxyTargets always includes local-singbox", () => {
|
|
||||||
const targets = normalizeProxyTargets([
|
|
||||||
{ id: "gateway", name: "Home gateway", host: "192.168.50.111", port: 8080 },
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.deepEqual(targets, [
|
|
||||||
{
|
|
||||||
id: "local-singbox",
|
|
||||||
name: "Local sing-box",
|
|
||||||
protocol: "socks5",
|
|
||||||
host: "127.0.0.1",
|
|
||||||
port: 1080,
|
|
||||||
managed: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "gateway",
|
|
||||||
name: "Home gateway",
|
|
||||||
protocol: "socks5",
|
|
||||||
host: "192.168.50.111",
|
|
||||||
port: 8080,
|
|
||||||
managed: false,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("resolveProfileItems expands folders and exe paths into process names", () => {
|
|
||||||
const files = new Map([
|
|
||||||
["C:\\Users\\me\\App\\a.exe", true],
|
|
||||||
["C:\\Users\\me\\App\\nested\\b.exe", true],
|
|
||||||
["C:\\Games\\Game\\game.exe", true],
|
|
||||||
]);
|
|
||||||
const dirs = new Map([
|
|
||||||
["C:\\Users\\me\\App", ["a.exe", "nested", "note.txt"]],
|
|
||||||
["C:\\Users\\me\\App\\nested", ["b.exe"]],
|
|
||||||
]);
|
|
||||||
const fsAdapter = {
|
|
||||||
existsSync: (value) => files.has(value) || dirs.has(value),
|
|
||||||
statSync: (value) => ({
|
|
||||||
isDirectory: () => dirs.has(value),
|
|
||||||
isFile: () => files.has(value),
|
|
||||||
}),
|
|
||||||
readdirSync: (value, options) =>
|
|
||||||
dirs.get(value).map((name) => ({
|
|
||||||
name,
|
|
||||||
isDirectory: () => dirs.has(`${value}\\${name}`),
|
|
||||||
isFile: () => files.has(`${value}\\${name}`),
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
|
|
||||||
const resolved = resolveProfileItems(
|
|
||||||
[
|
|
||||||
{ type: "process", value: "Discord", recursive: false },
|
|
||||||
{ type: "folder", value: "C:\\Users\\me\\App", recursive: true },
|
|
||||||
{ type: "exe", value: "C:\\Games\\Game\\game.exe", recursive: false },
|
|
||||||
],
|
|
||||||
{ fsAdapter, pathSep: "\\" },
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.deepEqual(resolved.map((item) => item.appName), [
|
|
||||||
"Discord",
|
|
||||||
"a",
|
|
||||||
"b",
|
|
||||||
"game",
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("buildProxiFyreConfig groups enabled profiles by target", () => {
|
|
||||||
const profiles = normalizeWindowsProfiles([
|
|
||||||
{
|
|
||||||
id: "discord",
|
|
||||||
name: "Discord",
|
|
||||||
enabled: true,
|
|
||||||
proxyTargetId: "local-singbox",
|
|
||||||
protocols: ["TCP", "UDP"],
|
|
||||||
items: [{ type: "process", value: "Discord" }],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "work",
|
|
||||||
name: "Work",
|
|
||||||
enabled: true,
|
|
||||||
proxyTargetId: "gateway",
|
|
||||||
protocols: ["TCP"],
|
|
||||||
items: [{ type: "process", value: "Code" }],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "off",
|
|
||||||
name: "Disabled",
|
|
||||||
enabled: false,
|
|
||||||
proxyTargetId: "local-singbox",
|
|
||||||
items: [{ type: "process", value: "Ignored" }],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const targets = normalizeProxyTargets([
|
|
||||||
{ id: "gateway", name: "Gateway", host: "192.168.50.111", port: 8080 },
|
|
||||||
]);
|
|
||||||
|
|
||||||
const config = buildProxiFyreConfig(profiles, targets);
|
|
||||||
|
|
||||||
assert.deepEqual(config, {
|
|
||||||
logLevel: "Info",
|
|
||||||
proxies: [
|
|
||||||
{
|
|
||||||
appNames: ["Discord"],
|
|
||||||
socks5ProxyEndpoint: "127.0.0.1:1080",
|
|
||||||
supportedProtocols: ["TCP", "UDP"],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
appNames: ["Code"],
|
|
||||||
socks5ProxyEndpoint: "192.168.50.111:8080",
|
|
||||||
supportedProtocols: ["TCP"],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
excludes: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
73
test/web/client-controls.test.js
Normal file
73
test/web/client-controls.test.js
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
import {
|
||||||
|
connectionAction,
|
||||||
|
formatConnectionDuration,
|
||||||
|
localProxyUrls,
|
||||||
|
subscriptionDomain,
|
||||||
|
subscriptionDaysLeft,
|
||||||
|
subscriptionUsage,
|
||||||
|
} from '../../src/web/utils/clientControls.js';
|
||||||
|
|
||||||
|
test('connection button chooses the only valid client action', () => {
|
||||||
|
assert.deepEqual(connectionAction({ connected: true }), { type: 'stop' });
|
||||||
|
assert.deepEqual(connectionAction({ selectedTag: 'nl-amsterdam' }), {
|
||||||
|
type: 'apply',
|
||||||
|
selectedTag: 'nl-amsterdam',
|
||||||
|
});
|
||||||
|
assert.deepEqual(connectionAction({ configExists: true }), { type: 'restart' });
|
||||||
|
assert.equal(connectionAction({}), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('connection duration is derived from the backend start time', () => {
|
||||||
|
const startedAt = '2026-07-10T10:00:00.000Z';
|
||||||
|
const now = Date.parse('2026-07-11T12:03:04.900Z');
|
||||||
|
|
||||||
|
assert.equal(formatConnectionDuration(startedAt, now), '26:03:04');
|
||||||
|
assert.equal(formatConnectionDuration(null, now), '00:00:00');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saved subscription is reduced to its public domain', () => {
|
||||||
|
assert.equal(subscriptionDomain('sub.example.com/…'), 'sub.example.com');
|
||||||
|
assert.equal(subscriptionDomain(''), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('local proxy exposes both supported URLs', () => {
|
||||||
|
assert.deepEqual(localProxyUrls(18080), {
|
||||||
|
socks5: 'socks5://127.0.0.1:18080',
|
||||||
|
http: 'http://127.0.0.1:18080',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('local proxy defaults to the macOS client port', () => {
|
||||||
|
assert.deepEqual(localProxyUrls(), {
|
||||||
|
socks5: 'socks5://127.0.0.1:8082',
|
||||||
|
http: 'http://127.0.0.1:8082',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('gateway proxy URLs use its network address', () => {
|
||||||
|
assert.deepEqual(localProxyUrls(8080, '192.168.50.111'), {
|
||||||
|
socks5: 'socks5://192.168.50.111:8080',
|
||||||
|
http: 'http://192.168.50.111:8080',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('subscription usage combines traffic and caps progress', () => {
|
||||||
|
assert.deepEqual(subscriptionUsage({ upload: 30, download: 80, total: 100, expire: 2 }), {
|
||||||
|
upload: 30,
|
||||||
|
download: 80,
|
||||||
|
total: 100,
|
||||||
|
used: 110,
|
||||||
|
percent: 100,
|
||||||
|
expiresAt: new Date(2000),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('subscription expiry uses Russian day forms', () => {
|
||||||
|
const now = Date.parse('2026-07-11T00:00:00Z');
|
||||||
|
assert.equal(subscriptionDaysLeft(new Date('2026-07-12T00:00:00Z'), now), 'остался 1 день');
|
||||||
|
assert.equal(subscriptionDaysLeft(new Date('2026-07-13T00:00:00Z'), now), 'осталось 2 дня');
|
||||||
|
assert.equal(subscriptionDaysLeft(new Date('2026-07-16T00:00:00Z'), now), 'осталось 5 дней');
|
||||||
|
});
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import assert from "node:assert/strict";
|
|
||||||
import test from "node:test";
|
|
||||||
|
|
||||||
import { resolveClientRoute } from "../../src/web/utils/clientRoute.js";
|
|
||||||
|
|
||||||
test("shows gateway route as the active Mac connection", () => {
|
|
||||||
const route = resolveClientRoute({
|
|
||||||
state: {
|
|
||||||
singboxRunning: true,
|
|
||||||
proxyPort: 18080,
|
|
||||||
clientSettings: {
|
|
||||||
sharedProxyEnabled: true,
|
|
||||||
sharedProxy: { host: "192.168.50.111", port: 8080, protocol: "socks5" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(route.mode, "gateway");
|
|
||||||
assert.equal(route.status, "connected");
|
|
||||||
assert.equal(route.title, "Подключено к gateway");
|
|
||||||
assert.equal(route.target, "192.168.50.111:8080");
|
|
||||||
assert.deepEqual(route.path, [
|
|
||||||
"Mac apps",
|
|
||||||
"127.0.0.1:18080",
|
|
||||||
"Gateway 192.168.50.111:8080",
|
|
||||||
"Internet",
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shows local VPN route with selected server", () => {
|
|
||||||
const route = resolveClientRoute({
|
|
||||||
state: {
|
|
||||||
singboxRunning: true,
|
|
||||||
proxyPort: 8082,
|
|
||||||
selectedTag: "nl-amsterdam",
|
|
||||||
clientSettings: {},
|
|
||||||
},
|
|
||||||
activeServer: { tag: "nl-amsterdam", country: "NL" },
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(route.mode, "vpn");
|
|
||||||
assert.equal(route.status, "connected");
|
|
||||||
assert.equal(route.title, "Подключено через VPN");
|
|
||||||
assert.equal(route.target, "nl-amsterdam");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shows direct route when home mode is enabled", () => {
|
|
||||||
const route = resolveClientRoute({
|
|
||||||
state: {
|
|
||||||
singboxRunning: true,
|
|
||||||
proxyPort: 8082,
|
|
||||||
clientSettings: { homeBypassEnabled: true },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(route.mode, "direct");
|
|
||||||
assert.equal(route.status, "connected");
|
|
||||||
assert.equal(route.title, "Подключено напрямую");
|
|
||||||
assert.equal(route.target, "без VPN");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shows configured but stopped route clearly", () => {
|
|
||||||
const route = resolveClientRoute({
|
|
||||||
state: {
|
|
||||||
singboxRunning: false,
|
|
||||||
configExists: true,
|
|
||||||
proxyPort: 8082,
|
|
||||||
selectedTag: "nl-amsterdam",
|
|
||||||
clientSettings: {},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(route.mode, "vpn");
|
|
||||||
assert.equal(route.status, "stopped");
|
|
||||||
assert.equal(route.title, "VPN настроен, но остановлен");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("shows missing setup when nothing is configured", () => {
|
|
||||||
const route = resolveClientRoute({
|
|
||||||
state: {
|
|
||||||
singboxRunning: false,
|
|
||||||
configExists: false,
|
|
||||||
proxyPort: 8082,
|
|
||||||
clientSettings: {},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(route.mode, "none");
|
|
||||||
assert.equal(route.status, "empty");
|
|
||||||
assert.equal(route.title, "Не подключено");
|
|
||||||
assert.equal(route.target, "выберите режим");
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user