init commit
This commit is contained in:
+23
@@ -0,0 +1,23 @@
|
||||
# --- сборка фронтенда ---
|
||||
FROM node:22-alpine AS web
|
||||
WORKDIR /web
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY frontend/ .
|
||||
RUN npm run build
|
||||
|
||||
# --- бэкенд + готовая статика ---
|
||||
FROM python:3.13-slim
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
WORKDIR /srv
|
||||
COPY backend/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY backend/app app
|
||||
COPY backend/wsgi.py .
|
||||
COPY --from=web /web/dist /srv/dist
|
||||
RUN useradd -r -u 10001 viz && mkdir /data && chown viz /data
|
||||
USER viz
|
||||
ENV DATA_DIR=/data FRONTEND_DIST=/srv/dist
|
||||
EXPOSE 8080
|
||||
# 1 воркер: кэш и позиции живут в процессе, нагрузки почти нет
|
||||
CMD ["gunicorn", "-b", "0.0.0.0:8080", "-w", "1", "--threads", "8", "--timeout", "30", "wsgi:app"]
|
||||
@@ -0,0 +1,58 @@
|
||||
# rw-viz: карта маршрутов Remnawave
|
||||
|
||||
Интерактивный визуализатор маршрутизации: `host → inbound → rules → balancer → outbound → node`.
|
||||
Узлы перетаскиваются как в Blueprints, раскладка сохраняется. Только чтение: берутся config-профили,
|
||||
хосты и ноды из API панели, без юзеров и трафика.
|
||||
|
||||
```
|
||||
backend/ Flask: клиент панели, сборка графа, кэш, позиции узлов
|
||||
frontend/ Vue 3 + TypeScript + Vue Flow
|
||||
Dockerfile сборка обоих в один образ (Flask раздаёт собранный фронт)
|
||||
```
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
cp .env.example .env # REMNAWAVE_URL, REMNAWAVE_TOKEN, лучше ещё BASIC_AUTH_*
|
||||
docker compose up -d --build
|
||||
# http://127.0.0.1:8080
|
||||
```
|
||||
|
||||
Порт привязан к 127.0.0.1: наружу выставляй через Traefik, желательно с авторизацией.
|
||||
|
||||
### Разработка
|
||||
|
||||
```bash
|
||||
# бэкенд
|
||||
cd backend && pip install -r requirements-dev.txt
|
||||
REMNAWAVE_URL=... REMNAWAVE_TOKEN=... flask --app wsgi run --port 8080
|
||||
# фронтенд (проксирует /api на 127.0.0.1:8080, другой адрес: VITE_API_TARGET)
|
||||
cd frontend && npm install && npm run dev
|
||||
```
|
||||
|
||||
Тесты: `pytest` (backend, 29 шт.) и `npm test` (frontend, 13 шт.); `npm run build` делает ещё и typecheck.
|
||||
|
||||
## Что показывает карта
|
||||
|
||||
- **Колонки:** хосты, inbound, правила по порядку, балансер, outbound'ы, ноды.
|
||||
- **Клик по хосту** подсвечивает его путь: условные правила (BLOCK/DIRECT), применимое правило по `vlessRoute`,
|
||||
выход и ноду. Проверенные, но не подошедшие правила приглушены. **Клик по узлу** подсвечивает все хосты, которые на него выходят.
|
||||
- **Недостижимые правила** (после catch-all по `inboundTag`) рисуются пунктиром и попадают в предупреждения;
|
||||
есть переключатель «скрыть недостижимые».
|
||||
- **Отключённые и оффлайн-ноды** помечены, рёбра к ним красные пунктиром, балансер показывает «живых N / M».
|
||||
- **⚠ в шапке** открывает список предупреждений, клик по строке фокусируется на узле.
|
||||
- Привязка outbound к ноде идёт по NetBird-адресу: `ips[]` со статусом `MANAGEMENT`, затем `address`.
|
||||
Если адрес не найден ни в одной карточке, появится красный узел «???».
|
||||
|
||||
## API бэкенда
|
||||
|
||||
| Метод | Путь | |
|
||||
|---|---|---|
|
||||
| GET | `/api/health` | живость (без авторизации) |
|
||||
| GET | `/api/profiles` | список профилей |
|
||||
| GET | `/api/graph?profile=<имя\|uuid>&refresh=1` | граф, позиции, `meta` |
|
||||
| GET/PUT/DELETE | `/api/positions/<uuid профиля>` | раскладка узлов |
|
||||
|
||||
Снимок панели кэшируется на `CACHE_TTL` секунд (`?refresh=1` не чаще раза в 5 с). Если панель недоступна,
|
||||
отдаётся последний снимок с `meta.stale = true`. Конфиг Xray наружу не уходит: приватные ключи Reality,
|
||||
shortIds и пароли Shadowsocks в граф не попадают (это проверяют тесты). Позиции лежат в `DATA_DIR/positions.json`.
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Flask-бэкенд визуализатора маршрутов Remnawave."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from flask import Flask, abort, jsonify, request, send_from_directory
|
||||
|
||||
from .cache import SnapshotCache
|
||||
from .config import Settings
|
||||
from .positions import PositionStore
|
||||
from .remnawave import RemnawaveClient
|
||||
from .routes import bp
|
||||
|
||||
|
||||
def create_app(settings: Settings | None = None, client=None) -> Flask:
|
||||
settings = settings or Settings.from_env()
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
if client is None:
|
||||
client = RemnawaveClient(settings.remnawave_url, settings.remnawave_token,
|
||||
settings.http_timeout, settings.verify_tls, settings.extra_headers)
|
||||
|
||||
def load():
|
||||
data = client.fetch_all()
|
||||
data["fetchedAt"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
return data
|
||||
|
||||
app = Flask(__name__)
|
||||
app.json.ensure_ascii = False
|
||||
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
|
||||
app.extensions["rwviz"] = SimpleNamespace(
|
||||
settings=settings,
|
||||
cache=SnapshotCache(load, settings.cache_ttl),
|
||||
positions=PositionStore(settings.data_dir / "positions.json"),
|
||||
)
|
||||
app.register_blueprint(bp)
|
||||
|
||||
if settings.basic_user and settings.basic_password:
|
||||
want_user, want_pass = settings.basic_user, settings.basic_password
|
||||
|
||||
@app.before_request
|
||||
def _auth():
|
||||
if request.method == "OPTIONS" or request.path == "/api/health":
|
||||
return None
|
||||
a = request.authorization
|
||||
ok = (a is not None
|
||||
and hmac.compare_digest(a.username or "", want_user)
|
||||
and hmac.compare_digest(a.password or "", want_pass))
|
||||
if not ok:
|
||||
return jsonify(error="unauthorized", message="Нужна авторизация"), 401, {
|
||||
"WWW-Authenticate": 'Basic realm="rw-viz"'}
|
||||
return None
|
||||
else:
|
||||
logging.getLogger(__name__).warning(
|
||||
"BASIC_AUTH_USER/PASSWORD не заданы: API открыт всем, кто достанет до порта")
|
||||
|
||||
if settings.cors_origins:
|
||||
@app.after_request
|
||||
def _cors(resp):
|
||||
origin = request.headers.get("Origin")
|
||||
if origin in settings.cors_origins:
|
||||
resp.headers["Access-Control-Allow-Origin"] = origin
|
||||
resp.headers["Vary"] = "Origin"
|
||||
resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization"
|
||||
resp.headers["Access-Control-Allow-Methods"] = "GET, PUT, DELETE, OPTIONS"
|
||||
return resp
|
||||
|
||||
dist = settings.frontend_dist
|
||||
if dist and dist.is_dir():
|
||||
@app.get("/", defaults={"path": ""})
|
||||
@app.get("/<path:path>")
|
||||
def _spa(path: str):
|
||||
if path.startswith("api/"):
|
||||
abort(404)
|
||||
if path and (dist / path).is_file():
|
||||
return send_from_directory(dist, path)
|
||||
return send_from_directory(dist, "index.html")
|
||||
|
||||
@app.errorhandler(404)
|
||||
def _404(_e):
|
||||
return jsonify(error="not_found", message="Не найдено"), 404
|
||||
|
||||
@app.errorhandler(413)
|
||||
def _413(_e):
|
||||
return jsonify(error="too_large", message="Слишком большое тело запроса"), 413
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,37 @@
|
||||
"""TTL-кэш снимка панели. При ошибке панели отдаёт устаревший снимок."""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
from .remnawave import RemnawaveError
|
||||
|
||||
MIN_REFRESH_INTERVAL = 5.0 # ?refresh=1 не чаще, чем раз в 5 секунд
|
||||
|
||||
|
||||
class SnapshotCache:
|
||||
def __init__(self, loader: Callable[[], Any], ttl: float):
|
||||
self._loader = loader
|
||||
self._ttl = ttl
|
||||
self._lock = threading.Lock()
|
||||
self._value: Any = None
|
||||
self._at = 0.0
|
||||
|
||||
def get(self, force: bool = False) -> tuple[Any, dict]:
|
||||
with self._lock:
|
||||
age = time.monotonic() - self._at
|
||||
fresh = self._value is not None and age < self._ttl
|
||||
if force and age < MIN_REFRESH_INTERVAL:
|
||||
force = False
|
||||
if fresh and not force:
|
||||
return self._value, {"cached": True, "stale": False, "ageSeconds": round(age, 1)}
|
||||
try:
|
||||
self._value = self._loader()
|
||||
self._at = time.monotonic()
|
||||
return self._value, {"cached": False, "stale": False, "ageSeconds": 0.0}
|
||||
except RemnawaveError as e:
|
||||
if self._value is None:
|
||||
raise
|
||||
return self._value, {"cached": True, "stale": True,
|
||||
"ageSeconds": round(age, 1), "lastError": e.message}
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Настройки из переменных окружения."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
try: # python-dotenv необязателен: в Docker всё приходит из env_file
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
except ImportError: # pragma: no cover
|
||||
pass
|
||||
|
||||
|
||||
def _bool(value: str | None, default: bool) -> bool:
|
||||
if value is None or value == "":
|
||||
return default
|
||||
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
remnawave_url: str
|
||||
remnawave_token: str
|
||||
cache_ttl: float = 30.0
|
||||
http_timeout: float = 10.0
|
||||
verify_tls: bool = True
|
||||
extra_headers: dict[str, str] = field(default_factory=dict)
|
||||
default_profile: str | None = None
|
||||
data_dir: Path = Path("data")
|
||||
basic_user: str | None = None
|
||||
basic_password: str | None = None
|
||||
frontend_dist: Path | None = None
|
||||
cors_origins: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "Settings":
|
||||
url = os.environ.get("REMNAWAVE_URL", "").strip().rstrip("/")
|
||||
token = os.environ.get("REMNAWAVE_TOKEN", "").strip()
|
||||
if not url or not token:
|
||||
raise RuntimeError("Нужны переменные REMNAWAVE_URL и REMNAWAVE_TOKEN")
|
||||
|
||||
extra: dict[str, str] = {}
|
||||
raw_headers = os.environ.get("REMNAWAVE_EXTRA_HEADERS", "").strip()
|
||||
if raw_headers:
|
||||
try:
|
||||
extra = {str(k): str(v) for k, v in json.loads(raw_headers).items()}
|
||||
except (ValueError, AttributeError) as e:
|
||||
raise RuntimeError("REMNAWAVE_EXTRA_HEADERS должен быть JSON-объектом") from e
|
||||
|
||||
dist = os.environ.get("FRONTEND_DIST", "").strip()
|
||||
origins = tuple(o.strip() for o in os.environ.get("CORS_ORIGINS", "").split(",") if o.strip())
|
||||
return cls(
|
||||
remnawave_url=url,
|
||||
remnawave_token=token,
|
||||
cache_ttl=float(os.environ.get("CACHE_TTL", "30")),
|
||||
http_timeout=float(os.environ.get("HTTP_TIMEOUT", "10")),
|
||||
verify_tls=_bool(os.environ.get("VERIFY_TLS"), True),
|
||||
extra_headers=extra,
|
||||
default_profile=os.environ.get("DEFAULT_PROFILE", "").strip() or None,
|
||||
data_dir=Path(os.environ.get("DATA_DIR", "data")),
|
||||
basic_user=os.environ.get("BASIC_AUTH_USER") or None,
|
||||
basic_password=os.environ.get("BASIC_AUTH_PASSWORD") or None,
|
||||
frontend_dist=Path(dist) if dist else None,
|
||||
cors_origins=origins,
|
||||
)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Сборка графа маршрутизации Remnawave: профиль + хосты + ноды -> {nodes, edges, warnings}.
|
||||
|
||||
Колонки слева направо: host -> inbound -> rule(ы) -> balancer -> outbound -> node.
|
||||
Только чтение, без статистики и юзеров.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# Ключи правила, которые мы умеем вычислять точно (остальные = "условные").
|
||||
_TARGET_KEYS = {"outboundTag", "balancerTag", "ruleTag", "type"}
|
||||
_EXACT_KEYS = {"vlessRoute", "inboundTag"}
|
||||
|
||||
|
||||
def parse_vless_route(value) -> set[int] | None:
|
||||
"""1 | "8-14" | "1,3,8-10" -> множество номеров; None, если поля нет."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return {value}
|
||||
out: set[int] = set()
|
||||
for part in str(value).split(","):
|
||||
part = part.strip()
|
||||
if "-" in part:
|
||||
a, b = part.split("-", 1)
|
||||
out.update(range(int(a), int(b) + 1))
|
||||
elif part:
|
||||
out.add(int(part))
|
||||
return out
|
||||
|
||||
|
||||
def _conditions(rule: dict) -> set[str]:
|
||||
return set(rule) - _TARGET_KEYS
|
||||
|
||||
|
||||
def _opaque(rule: dict) -> set[str]:
|
||||
"""Условия, которые нельзя вычислить статически (domain, ip, port, protocol...)."""
|
||||
return _conditions(rule) - _EXACT_KEYS
|
||||
|
||||
|
||||
def rule_label(rule: dict) -> str:
|
||||
parts = []
|
||||
for k in sorted(_conditions(rule)):
|
||||
v = rule[k]
|
||||
if isinstance(v, list):
|
||||
shown = ", ".join(map(str, v[:3])) + (f" +{len(v) - 3}" if len(v) > 3 else "")
|
||||
else:
|
||||
shown = str(v)
|
||||
parts.append(f"{k}: {shown}")
|
||||
return "; ".join(parts) or "любой трафик"
|
||||
|
||||
|
||||
def find_shadowed(rules: list[dict], inbound_tags: set[str]) -> set[int]:
|
||||
"""Правила после catch-all недостижимы (Xray: первое совпавшее правило выигрывает)."""
|
||||
for i, r in enumerate(rules):
|
||||
cond = _conditions(r)
|
||||
if not cond or (cond == {"inboundTag"} and set(r["inboundTag"]) >= inbound_tags):
|
||||
return set(range(i + 1, len(rules)))
|
||||
return set()
|
||||
|
||||
|
||||
def trace_host(rules: list[dict], route: int | None, inbound_tag: str) -> list[int]:
|
||||
"""Индексы правил, через которые может пройти трафик хоста, до первого безусловного."""
|
||||
path: list[int] = []
|
||||
for i, r in enumerate(rules):
|
||||
routes = parse_vless_route(r.get("vlessRoute"))
|
||||
if routes is not None and route not in routes:
|
||||
continue
|
||||
tags = r.get("inboundTag")
|
||||
if tags and inbound_tag not in tags:
|
||||
continue
|
||||
path.append(i)
|
||||
if not _opaque(r):
|
||||
break
|
||||
return path
|
||||
|
||||
|
||||
def node_state(n: dict) -> str:
|
||||
"""disabled | connecting | offline | online."""
|
||||
if n.get("isDisabled"):
|
||||
return "disabled"
|
||||
if n.get("isConnecting"):
|
||||
return "connecting"
|
||||
return "offline" if n.get("isConnected") is False else "online"
|
||||
|
||||
|
||||
def build_node_index(nodes: list[dict]) -> dict[str, dict]:
|
||||
"""ip -> нода. MANAGEMENT-адреса в приоритете, затем address, затем остальные ips.
|
||||
|
||||
Живые ноды идут первыми: если отключённая нода хранит тот же адрес, что и рабочая,
|
||||
выигрывает рабочая.
|
||||
"""
|
||||
ordered = sorted(nodes, key=lambda n: node_state(n) != "online") # sort стабильный
|
||||
idx: dict[str, dict] = {}
|
||||
for n in ordered:
|
||||
for e in n.get("ips") or []:
|
||||
if e["status"] == "MANAGEMENT":
|
||||
idx.setdefault(e["ip"], n)
|
||||
for n in ordered:
|
||||
idx.setdefault(n["address"], n)
|
||||
for e in n.get("ips") or []:
|
||||
idx.setdefault(e["ip"], n)
|
||||
return idx
|
||||
|
||||
|
||||
def node_info(n: dict) -> dict:
|
||||
ips = n.get("ips") or []
|
||||
by = lambda st: [e["ip"] for e in ips if e["status"] == st] # noqa: E731
|
||||
ifaces = ((n.get("system") or {}).get("info") or {}).get("networkInterfaces") or []
|
||||
return {
|
||||
"name": n["name"],
|
||||
"country": n.get("countryCode"),
|
||||
"state": node_state(n),
|
||||
"connected": n.get("isConnected"),
|
||||
"disabled": bool(n.get("isDisabled")),
|
||||
"mgmt": by("MANAGEMENT"),
|
||||
"exit": by("OUTBOUND"),
|
||||
"inbound": by("INBOUND"),
|
||||
"reserve": by("RESERVE"),
|
||||
"netbird": "wt0" in ifaces,
|
||||
}
|
||||
|
||||
|
||||
def outbound_ip(ob: dict) -> str | None:
|
||||
try:
|
||||
return ob["settings"]["servers"][0]["address"]
|
||||
except (KeyError, IndexError, TypeError):
|
||||
return None # freedom / blackhole
|
||||
|
||||
|
||||
def build_graph(profile: dict, hosts: list[dict], nodes: list[dict]) -> dict:
|
||||
cfg = profile["config"]
|
||||
rules = cfg.get("routing", {}).get("rules", [])
|
||||
balancers = cfg.get("routing", {}).get("balancers", [])
|
||||
outbounds = cfg.get("outbounds", [])
|
||||
inbounds = cfg.get("inbounds", [])
|
||||
inbound_tags = {i["tag"] for i in inbounds}
|
||||
|
||||
G_nodes: list[dict] = []
|
||||
G_edges: list[dict] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
def add_node(id_, type_, label, **data):
|
||||
G_nodes.append({"id": id_, "type": type_, "label": label, "data": data})
|
||||
|
||||
def add_edge(src, dst, kind="flow", label=None, **data):
|
||||
G_edges.append({"id": f"{src}->{dst}:{kind}", "source": src, "target": dst,
|
||||
"kind": kind, "label": label, "data": data})
|
||||
|
||||
shadowed = find_shadowed(rules, inbound_tags)
|
||||
|
||||
idx = build_node_index(nodes)
|
||||
|
||||
def _out_alive(o: dict) -> bool:
|
||||
ip = outbound_ip(o)
|
||||
if ip is None: # freedom / blackhole
|
||||
return True
|
||||
n = idx.get(ip)
|
||||
return n is not None and node_state(n) == "online"
|
||||
|
||||
alive = {o["tag"]: _out_alive(o) for o in outbounds}
|
||||
bal_members = {
|
||||
b["tag"]: [o["tag"] for o in outbounds
|
||||
if any(o["tag"].startswith(x) for x in b.get("selector", []))]
|
||||
for b in balancers
|
||||
}
|
||||
|
||||
def target_alive(r: dict) -> bool:
|
||||
if "balancerTag" in r:
|
||||
return any(alive.get(m, False) for m in bal_members.get(r["balancerTag"], []))
|
||||
return alive.get(r.get("outboundTag"), False)
|
||||
|
||||
# inbounds
|
||||
for i in inbounds:
|
||||
add_node(f"inb:{i['tag']}", "inbound", i["tag"],
|
||||
port=i.get("port"), protocol=i.get("protocol"))
|
||||
|
||||
# rules + цепочка fallthrough + цель
|
||||
for i, r in enumerate(rules):
|
||||
rid = f"rule:{i}"
|
||||
add_node(rid, "rule", f"#{i} {rule_label(r)}", index=i, shadowed=i in shadowed,
|
||||
vlessRoute=sorted(parse_vless_route(r.get("vlessRoute")) or []))
|
||||
target = f"bal:{r['balancerTag']}" if "balancerTag" in r else f"out:{r.get('outboundTag')}"
|
||||
add_edge(rid, target, "target", dead=i in shadowed)
|
||||
if i + 1 < len(rules):
|
||||
add_edge(rid, f"rule:{i + 1}", "fallthrough", dead=(i + 1) in shadowed)
|
||||
if i in shadowed:
|
||||
warnings.append(f"rule #{i} ({rule_label(r)}) недостижимо: выше есть catch-all")
|
||||
if rules:
|
||||
for tag in inbound_tags:
|
||||
add_edge(f"inb:{tag}", "rule:0", "flow")
|
||||
|
||||
# balancers
|
||||
for b in balancers:
|
||||
members = bal_members[b["tag"]]
|
||||
live = [m for m in members if alive[m]]
|
||||
add_node(f"bal:{b['tag']}", "balancer", b["tag"],
|
||||
strategy=(b.get("strategy") or {}).get("type"), members=members,
|
||||
aliveMembers=live)
|
||||
for m in members:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{m}", "member", dead=not alive[m])
|
||||
fb = b.get("fallbackTag")
|
||||
if fb:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{fb}", "fallback", "fallback",
|
||||
dead=not alive.get(fb, False))
|
||||
if not live:
|
||||
warnings.append(f"balancer {b['tag']}: нет ни одного живого члена")
|
||||
elif fb and not alive.get(fb, False):
|
||||
warnings.append(f"balancer {b['tag']}: fallback {fb} ведёт на нерабочую ноду")
|
||||
|
||||
# outbounds -> ноды
|
||||
seen_nodes: set[str] = set()
|
||||
for o in outbounds:
|
||||
ip = outbound_ip(o)
|
||||
add_node(f"out:{o['tag']}", "outbound", o["tag"], protocol=o["protocol"], ip=ip,
|
||||
alive=alive[o["tag"]])
|
||||
if ip is None:
|
||||
continue
|
||||
n = idx.get(ip)
|
||||
if n is None:
|
||||
add_node(f"unresolved:{ip}", "unresolved", ip)
|
||||
add_edge(f"out:{o['tag']}", f"unresolved:{ip}", "link")
|
||||
warnings.append(f"outbound {o['tag']}: адрес {ip} не найден ни в одной карточке ноды")
|
||||
continue
|
||||
nid = f"node:{n['name']}"
|
||||
if nid not in seen_nodes:
|
||||
seen_nodes.add(nid)
|
||||
add_node(nid, "node", n["name"], **node_info(n))
|
||||
add_edge(f"out:{o['tag']}", nid, "link", ip, dead=not alive[o["tag"]])
|
||||
if not alive[o["tag"]]:
|
||||
warnings.append(f"outbound {o['tag']} → {n['name']}: нода {node_state(n)}")
|
||||
|
||||
# хосты профиля
|
||||
uuid_to_tag = {i["uuid"]: i["tag"] for i in (profile.get("inbounds") or [])}
|
||||
for h in hosts:
|
||||
tag = uuid_to_tag.get((h.get("inbound") or {}).get("configProfileInboundUuid"))
|
||||
if tag is None:
|
||||
continue # хост другого профиля
|
||||
route = h.get("vlessRouteId")
|
||||
path = trace_host(rules, route, tag)
|
||||
end = path[-1] if path else None
|
||||
hid = f"host:{h['uuid']}"
|
||||
add_node(hid, "host", h["remark"], address=h.get("address"), port=h.get("port"),
|
||||
vlessRouteId=route, disabled=h.get("isDisabled"),
|
||||
trace=[f"rule:{i}" for i in path],
|
||||
exitAlive=target_alive(rules[end]) if end is not None else False)
|
||||
add_edge(hid, f"inb:{tag}", "flow")
|
||||
if end is not None:
|
||||
add_edge(hid, f"rule:{end}", "route", f"route {route}" if route is not None else "default",
|
||||
dead=not target_alive(rules[end]))
|
||||
if not target_alive(rules[end]) and not h.get("isDisabled"):
|
||||
warnings.append(f"хост {h['remark']}: выход правила #{end} ведёт на нерабочую ноду")
|
||||
|
||||
return {"nodes": G_nodes, "edges": G_edges, "warnings": warnings}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Хранилище позиций узлов (JSON-файл, запись атомарная)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
MAX_ENTRIES = 5000
|
||||
_KEY_RE = re.compile(r"^[0-9A-Za-z-]{8,64}$")
|
||||
|
||||
|
||||
def valid_key(key: str) -> bool:
|
||||
return bool(_KEY_RE.match(key))
|
||||
|
||||
|
||||
def clean_positions(raw) -> dict[str, dict[str, float]]:
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("positions должен быть объектом {id: {x, y}}")
|
||||
if len(raw) > MAX_ENTRIES:
|
||||
raise ValueError("слишком много узлов")
|
||||
out: dict[str, dict[str, float]] = {}
|
||||
for node_id, pos in raw.items():
|
||||
if not isinstance(node_id, str) or not 0 < len(node_id) <= 200:
|
||||
raise ValueError("некорректный id узла")
|
||||
if not isinstance(pos, dict):
|
||||
raise ValueError(f"позиция {node_id!r} должна быть объектом")
|
||||
coords = []
|
||||
for axis in ("x", "y"):
|
||||
v = pos.get(axis)
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
|
||||
raise ValueError(f"{node_id!r}: {axis} должно быть конечным числом")
|
||||
coords.append(float(v))
|
||||
out[node_id] = {"x": coords[0], "y": coords[1]}
|
||||
return out
|
||||
|
||||
|
||||
class PositionStore:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _read(self) -> dict:
|
||||
try:
|
||||
return json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except ValueError:
|
||||
log.warning("positions: файл %s повреждён, начинаю с пустого", self.path)
|
||||
return {}
|
||||
|
||||
def _write(self, data: dict) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".positions-")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, self.path)
|
||||
except BaseException:
|
||||
Path(tmp).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
def get(self, key: str) -> dict:
|
||||
with self._lock:
|
||||
return self._read().get(key, {})
|
||||
|
||||
def put(self, key: str, positions: dict) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
data[key] = positions
|
||||
self._write(data)
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
if data.pop(key, None) is not None:
|
||||
self._write(data)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Клиент Remnawave API (только чтение)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
class RemnawaveError(Exception):
|
||||
"""Ошибка обращения к панели. Токен в сообщения не попадает."""
|
||||
|
||||
def __init__(self, message: str, code: str = "upstream_error", http_status: int = 502):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.http_status = http_status
|
||||
|
||||
|
||||
class RemnawaveClient:
|
||||
def __init__(self, base_url: str, token: str, timeout: float = 10.0,
|
||||
verify: bool = True, extra_headers: dict[str, str] | None = None):
|
||||
self.base = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.verify = verify
|
||||
self.headers = {"Authorization": f"Bearer {token}", "Accept": "application/json",
|
||||
**(extra_headers or {})}
|
||||
|
||||
def _get(self, path: str) -> Any:
|
||||
try:
|
||||
r = requests.get(f"{self.base}{path}", headers=self.headers,
|
||||
timeout=self.timeout, verify=self.verify)
|
||||
except requests.Timeout:
|
||||
raise RemnawaveError(f"Таймаут запроса {path}", "upstream_timeout", 504) from None
|
||||
except requests.RequestException as e:
|
||||
raise RemnawaveError(f"Не удалось подключиться к Remnawave ({type(e).__name__})",
|
||||
"upstream_unreachable") from None
|
||||
if r.status_code in (401, 403):
|
||||
raise RemnawaveError("Remnawave отклонил токен (401/403)", "upstream_auth")
|
||||
if not r.ok:
|
||||
raise RemnawaveError(f"{path}: HTTP {r.status_code}", "upstream_http")
|
||||
try:
|
||||
body = r.json()
|
||||
except ValueError:
|
||||
raise RemnawaveError(f"{path}: ответ не JSON (проверь REMNAWAVE_URL)",
|
||||
"upstream_bad_response") from None
|
||||
return body.get("response", body) if isinstance(body, dict) else body
|
||||
|
||||
def profiles(self) -> list[dict]:
|
||||
data = self._get("/api/config-profiles")
|
||||
return data.get("configProfiles", []) if isinstance(data, dict) else data
|
||||
|
||||
def hosts(self) -> list[dict]:
|
||||
return self._get("/api/hosts")
|
||||
|
||||
def nodes(self) -> list[dict]:
|
||||
return self._get("/api/nodes")
|
||||
|
||||
def fetch_all(self) -> dict[str, list[dict]]:
|
||||
"""Три запроса параллельно."""
|
||||
calls = {"profiles": self.profiles, "hosts": self.hosts, "nodes": self.nodes}
|
||||
with ThreadPoolExecutor(max_workers=3) as ex:
|
||||
futures = {k: ex.submit(fn) for k, fn in calls.items()}
|
||||
return {k: f.result() for k, f in futures.items()}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""HTTP API."""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from .graph import build_graph
|
||||
from .positions import clean_positions, valid_key
|
||||
from .remnawave import RemnawaveError
|
||||
|
||||
bp = Blueprint("api", __name__, url_prefix="/api")
|
||||
|
||||
|
||||
class ProfileNotFound(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
def _svc():
|
||||
return current_app.extensions["rwviz"]
|
||||
|
||||
|
||||
def _rules(profile: dict) -> list[dict]:
|
||||
return ((profile.get("config") or {}).get("routing") or {}).get("rules") or []
|
||||
|
||||
|
||||
def pick_profile(profiles: list[dict], wanted: str | None, default: str | None) -> dict | None:
|
||||
profiles = [p for p in profiles if isinstance(p.get("config"), dict)]
|
||||
key = (wanted or default or "").strip().lower()
|
||||
if key:
|
||||
for p in profiles:
|
||||
if p["uuid"].lower() == key or p["name"].lower() == key:
|
||||
return p
|
||||
raise ProfileNotFound(wanted or default)
|
||||
for p in profiles: # по умолчанию - первый профиль с vlessRoute
|
||||
if any("vlessRoute" in r for r in _rules(p)):
|
||||
return p
|
||||
return profiles[0] if profiles else None
|
||||
|
||||
|
||||
@bp.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@bp.get("/profiles")
|
||||
def profiles():
|
||||
snap, meta = _svc().cache.get()
|
||||
items = [{
|
||||
"uuid": p["uuid"],
|
||||
"name": p["name"],
|
||||
"inbounds": len(p.get("inbounds") or []),
|
||||
"rules": len(_rules(p)),
|
||||
"nodes": [n.get("name") for n in p.get("nodes") or []],
|
||||
} for p in snap["profiles"] if isinstance(p.get("config"), dict)]
|
||||
return jsonify({"profiles": items, "meta": {**meta, "fetchedAt": snap["fetchedAt"]}})
|
||||
|
||||
|
||||
@bp.get("/graph")
|
||||
def graph():
|
||||
svc = _svc()
|
||||
force = request.args.get("refresh", "").lower() in {"1", "true", "yes"}
|
||||
snap, meta = svc.cache.get(force=force)
|
||||
profile = pick_profile(snap["profiles"], request.args.get("profile"), svc.settings.default_profile)
|
||||
if profile is None:
|
||||
return jsonify(error="no_profiles", message="В панели нет config-профилей"), 404
|
||||
try:
|
||||
result = build_graph(profile, snap["hosts"], snap["nodes"])
|
||||
except (KeyError, TypeError, ValueError) as e:
|
||||
current_app.logger.exception("graph build failed")
|
||||
return jsonify(error="graph_build_failed",
|
||||
message=f"Не удалось разобрать профиль {profile['name']!r}: {type(e).__name__}: {e}"), 422
|
||||
return jsonify({
|
||||
"profile": {"uuid": profile["uuid"], "name": profile["name"]},
|
||||
"graph": result,
|
||||
"positions": svc.positions.get(profile["uuid"]),
|
||||
"meta": {**meta, "fetchedAt": snap["fetchedAt"]},
|
||||
})
|
||||
|
||||
|
||||
@bp.get("/positions/<key>")
|
||||
def get_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
return jsonify({"positions": _svc().positions.get(key)})
|
||||
|
||||
|
||||
@bp.put("/positions/<key>")
|
||||
def put_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict) or "positions" not in body:
|
||||
return jsonify(error="bad_body", message='Ожидается {"positions": {...}}'), 400
|
||||
try:
|
||||
positions = clean_positions(body["positions"])
|
||||
except ValueError as e:
|
||||
return jsonify(error="bad_positions", message=str(e)), 400
|
||||
_svc().positions.put(key, positions)
|
||||
return jsonify({"saved": len(positions)})
|
||||
|
||||
|
||||
@bp.delete("/positions/<key>")
|
||||
def delete_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
_svc().positions.delete(key)
|
||||
return "", 204
|
||||
|
||||
|
||||
@bp.errorhandler(RemnawaveError)
|
||||
def _upstream(e: RemnawaveError):
|
||||
return jsonify(error=e.code, message=e.message), e.http_status
|
||||
|
||||
|
||||
@bp.errorhandler(ProfileNotFound)
|
||||
def _no_profile(e: ProfileNotFound):
|
||||
return jsonify(error="profile_not_found", message=f"Профиль {e} не найден"), 404
|
||||
@@ -0,0 +1,2 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
@@ -0,0 +1,2 @@
|
||||
-r requirements.txt
|
||||
pytest>=8.0
|
||||
@@ -0,0 +1,4 @@
|
||||
Flask>=3.0,<4
|
||||
requests>=2.32,<3
|
||||
gunicorn>=22.0
|
||||
python-dotenv>=1.0
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Фикстура, повторяющая профиль BridgeOverNetbird и ноды из панели."""
|
||||
SC = ["domain:soundcloud.com", "domain:sndcdn.com", "domain:soundcloud.cloud"]
|
||||
BRIDGE_IPS = ["100.106.180.60", "100.106.64.26", "100.106.214.118",
|
||||
"100.106.134.18", "100.106.36.222", "100.106.221.7"]
|
||||
NODE_NAMES = ["FR-01", "NL-01", "FI-01", "NL-04", "CH-01", "BR-01"]
|
||||
|
||||
|
||||
def make_profile() -> dict:
|
||||
rules = [
|
||||
{"port": 25, "outboundTag": "BLOCK"},
|
||||
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
|
||||
{"domain": ["geosite:private"], "outboundTag": "BLOCK"},
|
||||
{"protocol": ["bittorrent"], "outboundTag": "BLOCK"},
|
||||
{"domain": ["geosite:category-ru", "domain:ru"], "outboundTag": "DIRECT"},
|
||||
{"ip": ["geoip:ru"], "outboundTag": "DIRECT"},
|
||||
*[{"vlessRoute": i, "outboundTag": f"BRIDGE_{i}"} for i in range(1, 7)],
|
||||
{"vlessRoute": 7, "balancerTag": "BRIDGE_AUTO"},
|
||||
{"inboundTag": ["RU_NODE_IN"], "balancerTag": "BRIDGE_AUTO"},
|
||||
*[{"domain": SC, "vlessRoute": 7 + i, "outboundTag": f"BRIDGE_{i}"} for i in range(1, 7)],
|
||||
{"domain": SC, "vlessRoute": 14, "balancerTag": "BRIDGE_AUTO"},
|
||||
{"vlessRoute": "8-14", "balancerTag": "BRIDGE_AUTO"},
|
||||
]
|
||||
config = {
|
||||
"inbounds": [{"tag": "RU_NODE_IN", "port": 443, "protocol": "vless",
|
||||
"streamSettings": {"realitySettings": {"privateKey": "SECRET-KEY"}}}],
|
||||
"outbounds": [{"tag": "DIRECT", "protocol": "freedom"},
|
||||
{"tag": "BLOCK", "protocol": "blackhole"}] + [
|
||||
{"tag": f"BRIDGE_{i + 1}", "protocol": "shadowsocks",
|
||||
"settings": {"servers": [{"address": ip, "port": 9999, "password": "SECRET-PASS"}]}}
|
||||
for i, ip in enumerate(BRIDGE_IPS)],
|
||||
"routing": {"rules": rules, "balancers": [
|
||||
{"tag": "BRIDGE_AUTO", "selector": ["BRIDGE_"], "strategy": {"type": "leastPing"},
|
||||
"fallbackTag": "BRIDGE_1"}]},
|
||||
}
|
||||
return {"uuid": "aaaaaaaa-0000-0000-0000-000000000001", "name": "BridgeOverNetbird",
|
||||
"config": config, "inbounds": [{"uuid": "inb-1", "tag": "RU_NODE_IN"}],
|
||||
"nodes": [{"uuid": "n-ru", "name": "RU-01", "countryCode": "RU"}]}
|
||||
|
||||
|
||||
def make_nodes() -> list[dict]:
|
||||
nodes = [{"name": n, "address": ip, "countryCode": "XX", "isConnected": True, "isDisabled": False,
|
||||
"ips": [{"ip": ip, "status": "MANAGEMENT"}, {"ip": f"1.1.1.{i}", "status": "OUTBOUND"}],
|
||||
"system": {"info": {"networkInterfaces": ["lo", "wt0"]}}}
|
||||
for i, (n, ip) in enumerate(zip(NODE_NAMES, BRIDGE_IPS))]
|
||||
nodes.append({"name": "US-01", "address": "78.153.155.226", "ips": [], "system": None})
|
||||
return nodes
|
||||
|
||||
|
||||
def make_hosts() -> list[dict]:
|
||||
inbound = {"configProfileInboundUuid": "inb-1"}
|
||||
hosts = [{"uuid": f"h{r}", "remark": f"host-r{r}", "vlessRouteId": r, "inbound": inbound}
|
||||
for r in (3, 7, 8)]
|
||||
hosts.append({"uuid": "hn", "remark": "no-route", "vlessRouteId": None, "inbound": inbound})
|
||||
hosts.append({"uuid": "hx", "remark": "other-profile", "vlessRouteId": 1,
|
||||
"inbound": {"configProfileInboundUuid": "foreign"}})
|
||||
return hosts
|
||||
@@ -0,0 +1,138 @@
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
|
||||
from app import create_app
|
||||
from app.config import Settings
|
||||
from app.remnawave import RemnawaveError
|
||||
from .fixtures import make_hosts, make_nodes, make_profile
|
||||
|
||||
KEY = "aaaaaaaa-0000-0000-0000-000000000001"
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self):
|
||||
self.calls = 0
|
||||
self.fail = False
|
||||
|
||||
def fetch_all(self):
|
||||
self.calls += 1
|
||||
if self.fail:
|
||||
raise RemnawaveError("панель недоступна", "upstream_unreachable")
|
||||
other = {"uuid": "bbbbbbbb-0000-0000-0000-000000000002", "name": "Default",
|
||||
"config": {"inbounds": [], "outbounds": [], "routing": {"rules": []}}, "inbounds": []}
|
||||
return {"profiles": [other, make_profile()], "hosts": make_hosts(), "nodes": make_nodes()}
|
||||
|
||||
|
||||
def make_settings(tmp_path, **kw):
|
||||
base = dict(remnawave_url="http://x", remnawave_token="t", cache_ttl=30, data_dir=tmp_path)
|
||||
base.update(kw)
|
||||
return Settings(**base)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client_and_fake(tmp_path):
|
||||
fake = FakeClient()
|
||||
app = create_app(make_settings(tmp_path), client=fake)
|
||||
return app.test_client(), fake
|
||||
|
||||
|
||||
def test_graph_default_profile_is_the_one_with_vless_route(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
r = c.get("/api/graph")
|
||||
assert r.status_code == 200
|
||||
body = r.get_json()
|
||||
assert body["profile"]["name"] == "BridgeOverNetbird"
|
||||
assert body["graph"]["warnings"]
|
||||
assert "SECRET" not in r.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_profile_by_name_and_unknown(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
assert c.get("/api/graph?profile=default").get_json()["profile"]["name"] == "Default"
|
||||
r = c.get("/api/graph?profile=nope")
|
||||
assert r.status_code == 404 and r.get_json()["error"] == "profile_not_found"
|
||||
|
||||
|
||||
def test_profiles_list(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
names = [p["name"] for p in c.get("/api/profiles").get_json()["profiles"]]
|
||||
assert names == ["Default", "BridgeOverNetbird"]
|
||||
|
||||
|
||||
def test_cache_and_refresh_throttle(client_and_fake):
|
||||
c, fake = client_and_fake
|
||||
c.get("/api/graph"); c.get("/api/graph"); c.get("/api/profiles")
|
||||
assert fake.calls == 1
|
||||
c.get("/api/graph?refresh=1") # слишком рано, игнорируется
|
||||
assert fake.calls == 1
|
||||
|
||||
|
||||
def test_stale_snapshot_on_upstream_error(tmp_path):
|
||||
fake = FakeClient()
|
||||
c = create_app(make_settings(tmp_path, cache_ttl=0), client=fake).test_client()
|
||||
assert c.get("/api/graph").status_code == 200
|
||||
fake.fail = True
|
||||
r = c.get("/api/graph")
|
||||
assert r.status_code == 200
|
||||
meta = r.get_json()["meta"]
|
||||
assert meta["stale"] is True and "недоступна" in meta["lastError"]
|
||||
|
||||
|
||||
def test_upstream_error_without_cache(tmp_path):
|
||||
fake = FakeClient()
|
||||
fake.fail = True
|
||||
c = create_app(make_settings(tmp_path), client=fake).test_client()
|
||||
r = c.get("/api/graph")
|
||||
assert r.status_code == 502 and r.get_json()["error"] == "upstream_unreachable"
|
||||
|
||||
|
||||
def test_positions_roundtrip(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
assert c.get(f"/api/positions/{KEY}").get_json() == {"positions": {}}
|
||||
r = c.put(f"/api/positions/{KEY}", json={"positions": {"rule:0": {"x": 10, "y": 20.5}}})
|
||||
assert r.get_json() == {"saved": 1}
|
||||
assert c.get("/api/graph").get_json()["positions"] == {"rule:0": {"x": 10.0, "y": 20.5}}
|
||||
assert c.delete(f"/api/positions/{KEY}").status_code == 204
|
||||
assert c.get(f"/api/positions/{KEY}").get_json() == {"positions": {}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
{"positions": []},
|
||||
{"positions": {"a": {"x": "1", "y": 2}}},
|
||||
{"positions": {"a": {"x": float("inf"), "y": 2}}},
|
||||
{"positions": {"a": {"x": True, "y": 2}}},
|
||||
{"nope": 1},
|
||||
])
|
||||
def test_positions_validation(client_and_fake, payload):
|
||||
c, _ = client_and_fake
|
||||
assert c.put(f"/api/positions/{KEY}", json=payload).status_code == 400
|
||||
|
||||
|
||||
def test_positions_bad_key(client_and_fake):
|
||||
c, _ = client_and_fake
|
||||
assert c.put("/api/positions/..%2Fetc", json={"positions": {}}).status_code in (400, 404)
|
||||
assert c.get("/api/positions/x").status_code == 400
|
||||
|
||||
|
||||
def test_basic_auth(tmp_path):
|
||||
app = create_app(make_settings(tmp_path, basic_user="u", basic_password="p"), client=FakeClient())
|
||||
c = app.test_client()
|
||||
assert c.get("/api/health").status_code == 200
|
||||
assert c.get("/api/graph").status_code == 401
|
||||
good = {"Authorization": "Basic " + base64.b64encode(b"u:p").decode()}
|
||||
bad = {"Authorization": "Basic " + base64.b64encode(b"u:x").decode()}
|
||||
assert c.get("/api/graph", headers=good).status_code == 200
|
||||
assert c.get("/api/graph", headers=bad).status_code == 401
|
||||
|
||||
|
||||
def test_spa_fallback(tmp_path):
|
||||
dist = tmp_path / "dist"
|
||||
(dist / "assets").mkdir(parents=True)
|
||||
(dist / "index.html").write_text("<h1>viz</h1>")
|
||||
(dist / "assets" / "a.js").write_text("1")
|
||||
c = create_app(make_settings(tmp_path, frontend_dist=dist), client=FakeClient()).test_client()
|
||||
assert b"viz" in c.get("/").data
|
||||
assert c.get("/assets/a.js").data == b"1"
|
||||
assert b"viz" in c.get("/some/route").data
|
||||
assert c.get("/api/unknown").status_code == 404
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Клиент против локального поддельного Remnawave (формы ответов как в спеке v3.4.11)."""
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from app.remnawave import RemnawaveClient, RemnawaveError
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
seen_auth: list = []
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
Handler.seen_auth.append(self.headers.get("Authorization"))
|
||||
if self.headers.get("Authorization") != "Bearer good":
|
||||
self.send_response(401); self.end_headers(); return
|
||||
bodies = {
|
||||
"/api/nodes": {"response": [{"name": "FR-01"}]},
|
||||
"/api/hosts": {"response": [{"remark": "h"}]},
|
||||
"/api/config-profiles": {"response": {"total": 1, "configProfiles": [{"name": "P"}]}},
|
||||
}
|
||||
if self.path == "/api/broken":
|
||||
payload = b"<html>not json</html>"
|
||||
elif self.path in bodies:
|
||||
payload = json.dumps(bodies[self.path]).encode()
|
||||
else:
|
||||
self.send_response(500); self.end_headers(); return
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base():
|
||||
srv = HTTPServer(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_port}"
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def test_fetch_all_unwraps_responses(base):
|
||||
c = RemnawaveClient(base, "good")
|
||||
data = c.fetch_all()
|
||||
assert data == {"profiles": [{"name": "P"}], "hosts": [{"remark": "h"}], "nodes": [{"name": "FR-01"}]}
|
||||
|
||||
|
||||
def test_bad_token(base):
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
RemnawaveClient(base, "bad").nodes()
|
||||
assert e.value.code == "upstream_auth" and "bad" not in e.value.message
|
||||
|
||||
|
||||
def test_non_json_and_http_error(base):
|
||||
c = RemnawaveClient(base, "good")
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
c._get("/api/broken")
|
||||
assert e.value.code == "upstream_bad_response"
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
c._get("/api/other")
|
||||
assert e.value.code == "upstream_http"
|
||||
|
||||
|
||||
def test_unreachable():
|
||||
with pytest.raises(RemnawaveError) as e:
|
||||
RemnawaveClient("http://127.0.0.1:1", "t", timeout=1).nodes()
|
||||
assert e.value.code in {"upstream_unreachable", "upstream_timeout"}
|
||||
|
||||
|
||||
def test_extra_headers_are_sent(base):
|
||||
Handler.seen_auth.clear()
|
||||
RemnawaveClient(base, "good", extra_headers={"X-Forwarded-Proto": "https"}).nodes()
|
||||
assert Handler.seen_auth == ["Bearer good"]
|
||||
assert RemnawaveClient(base, "good", extra_headers={"X-A": "1"}).headers["X-A"] == "1"
|
||||
@@ -0,0 +1,97 @@
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from app.graph import build_graph, parse_vless_route
|
||||
from .fixtures import make_hosts, make_nodes, make_profile
|
||||
|
||||
|
||||
def by_id(g):
|
||||
return {n["id"]: n for n in g["nodes"]}
|
||||
|
||||
|
||||
def targets(g, src):
|
||||
return [e["target"] for e in g["edges"] if e["source"] == src]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def g():
|
||||
return build_graph(make_profile(), make_hosts(), make_nodes())
|
||||
|
||||
|
||||
def test_parse_vless_route():
|
||||
assert parse_vless_route(None) is None
|
||||
assert parse_vless_route(5) == {5}
|
||||
assert parse_vless_route("8-14") == set(range(8, 15))
|
||||
assert parse_vless_route("1,3,8-10") == {1, 3, 8, 9, 10}
|
||||
|
||||
|
||||
def test_all_bridges_resolve(g):
|
||||
assert not [n for n in g["nodes"] if n["type"] == "unresolved"]
|
||||
expected = {"BRIDGE_1": "FR-01", "BRIDGE_2": "NL-01", "BRIDGE_3": "FI-01",
|
||||
"BRIDGE_4": "NL-04", "BRIDGE_5": "CH-01", "BRIDGE_6": "BR-01"}
|
||||
for out, node in expected.items():
|
||||
assert targets(g, f"out:{out}") == [f"node:{node}"]
|
||||
assert "node:US-01" not in by_id(g)
|
||||
|
||||
|
||||
def test_shadowed_rules(g):
|
||||
shadowed = [n["data"]["index"] for n in g["nodes"] if n["type"] == "rule" and n["data"]["shadowed"]]
|
||||
assert shadowed == list(range(14, 22))
|
||||
assert sum("недостижимо" in w for w in g["warnings"]) == 8
|
||||
|
||||
|
||||
def test_host_trace(g):
|
||||
b = by_id(g)
|
||||
assert b["host:h3"]["data"]["trace"][-1] == "rule:8" # route 3 -> BRIDGE_3
|
||||
assert b["host:h7"]["data"]["trace"][-1] == "rule:12" # route 7 -> BRIDGE_AUTO
|
||||
assert b["host:h8"]["data"]["trace"][-1] == "rule:13" # route 8 упирается в catch-all
|
||||
assert b["host:hn"]["data"]["trace"][-1] == "rule:13"
|
||||
assert "host:hx" not in b # хост другого профиля
|
||||
|
||||
|
||||
def test_no_secrets_in_output(g):
|
||||
dump = str(g)
|
||||
assert "SECRET" not in dump
|
||||
|
||||
|
||||
def test_disabled_and_offline_nodes():
|
||||
nodes = make_nodes()
|
||||
for n in nodes:
|
||||
if n["name"] == "NL-04":
|
||||
n["isDisabled"] = True
|
||||
if n["name"] == "BR-01":
|
||||
n["isConnected"] = False
|
||||
nodes.insert(0, {"name": "OLD-FR", "address": "100.106.180.60", "isDisabled": True,
|
||||
"ips": [{"ip": "100.106.180.60", "status": "MANAGEMENT"}], "system": None})
|
||||
g = build_graph(make_profile(), make_hosts(), nodes)
|
||||
b = by_id(g)
|
||||
assert targets(g, "out:BRIDGE_1") == ["node:FR-01"] # живая нода выигрывает у дубля
|
||||
assert b["node:NL-04"]["data"]["state"] == "disabled"
|
||||
assert b["node:BR-01"]["data"]["state"] == "offline"
|
||||
assert b["bal:BRIDGE_AUTO"]["data"]["aliveMembers"] == ["BRIDGE_1", "BRIDGE_2", "BRIDGE_3", "BRIDGE_5"]
|
||||
dead = {e["source"] for e in g["edges"] if e["kind"] == "link" and e["data"].get("dead")}
|
||||
assert dead == {"out:BRIDGE_4", "out:BRIDGE_6"}
|
||||
|
||||
|
||||
def test_all_nodes_down_warns():
|
||||
nodes = make_nodes()
|
||||
for n in nodes:
|
||||
n["isDisabled"] = True
|
||||
g = build_graph(make_profile(), make_hosts(), nodes)
|
||||
assert any("нет ни одного живого члена" in w for w in g["warnings"])
|
||||
assert by_id(g)["host:h3"]["data"]["exitAlive"] is False
|
||||
|
||||
|
||||
def test_unresolved_outbound():
|
||||
nodes = [n for n in make_nodes() if n["name"] != "NL-04"]
|
||||
g = build_graph(make_profile(), make_hosts(), nodes)
|
||||
assert "unresolved:100.106.134.18" in by_id(g)
|
||||
assert any("не найден" in w for w in g["warnings"])
|
||||
|
||||
|
||||
def test_input_not_mutated():
|
||||
profile, hosts, nodes = make_profile(), make_hosts(), make_nodes()
|
||||
snapshot = copy.deepcopy((profile, hosts, nodes))
|
||||
build_graph(profile, hosts, nodes)
|
||||
assert (profile, hosts, nodes) == snapshot
|
||||
@@ -0,0 +1,3 @@
|
||||
from app import create_app
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1,12 @@
|
||||
services:
|
||||
rw-viz:
|
||||
build: .
|
||||
env_file: .env
|
||||
volumes:
|
||||
- viz-data:/data
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
viz-data:
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
dist
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Remnawave · карта маршрутов</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2289
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "rw-viz-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "vue-tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vue-flow/background": "^1.3.2",
|
||||
"@vue-flow/controls": "^1.1.3",
|
||||
"@vue-flow/core": "^1.48.2",
|
||||
"@vue-flow/minimap": "^1.5.4",
|
||||
"vue": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.0.0",
|
||||
"vitest": "^3.2.0",
|
||||
"vue-tsc": "^3.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
<script setup lang="ts">
|
||||
import { Background } from '@vue-flow/background'
|
||||
import { Controls } from '@vue-flow/controls'
|
||||
import { useVueFlow, VueFlow, type Edge, type Node, type NodeMouseEvent, type NodeTypesObject } from '@vue-flow/core'
|
||||
import { MiniMap } from '@vue-flow/minimap'
|
||||
import { computed, markRaw, nextTick, onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
|
||||
import { ApiError, getGraph, getProfiles, resetPositions, savePositions } from './api'
|
||||
import BlueprintNode from './components/BlueprintNode.vue'
|
||||
import { applyView, toFlow } from './flow'
|
||||
import { autoLayout } from './layout'
|
||||
import { buildReach, highlightFor, type Reach } from './reach'
|
||||
import type { GraphResponse, Positions, ProfileItem } from './types'
|
||||
|
||||
const nodeTypes = { bp: markRaw(BlueprintNode) } as unknown as NodeTypesObject
|
||||
|
||||
const profiles = ref<ProfileItem[]>([])
|
||||
const profileKey = ref('')
|
||||
const current = ref<GraphResponse | null>(null)
|
||||
const nodes = ref([]) as Ref<Node[]>
|
||||
const edges = ref([]) as Ref<Edge[]>
|
||||
const selected = ref<string | null>(null)
|
||||
const hideShadowed = ref(false)
|
||||
const autoRefresh = ref(false)
|
||||
const showWarnings = ref(false)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const saveState = ref<'idle' | 'saving' | 'saved' | 'error'>('idle')
|
||||
|
||||
let autoPos: Positions = {}
|
||||
const { fitView, getNodes } = useVueFlow()
|
||||
|
||||
const reach = computed<Map<string, Reach>>(() => (current.value ? buildReach(current.value.graph) : new Map()))
|
||||
const warnings = computed(() => current.value?.graph.warnings ?? [])
|
||||
const meta = computed(() => current.value?.meta)
|
||||
const metaText = computed(() => {
|
||||
if (!meta.value) return ''
|
||||
const t = new Date(meta.value.fetchedAt).toLocaleTimeString('ru-RU')
|
||||
return `снимок панели ${t}` + (meta.value.cached ? ` · кэш ${Math.round(meta.value.ageSeconds)} с` : '')
|
||||
})
|
||||
const saveText = computed(
|
||||
() => ({ idle: '', saving: 'сохраняю раскладку…', saved: 'раскладка сохранена', error: 'не удалось сохранить раскладку' })[saveState.value],
|
||||
)
|
||||
|
||||
function refreshView() {
|
||||
if (!current.value) return
|
||||
const hl = highlightFor(selected.value, reach.value)
|
||||
const v = applyView(nodes.value, edges.value, hl, hideShadowed.value)
|
||||
nodes.value = v.nodes
|
||||
edges.value = v.edges
|
||||
}
|
||||
watch([selected, hideShadowed], refreshView)
|
||||
|
||||
function fit(delay = 80) {
|
||||
nextTick(() => window.setTimeout(() => fitView({ padding: 0.12 }), delay))
|
||||
}
|
||||
|
||||
async function load(opts: { force?: boolean; keep?: boolean } = {}) {
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await getGraph(profileKey.value || undefined, opts.force)
|
||||
const switched = data.profile.uuid !== current.value?.profile.uuid
|
||||
const keep = !!opts.keep && !switched
|
||||
const existing: Positions = keep
|
||||
? Object.fromEntries(getNodes.value.map((n) => [n.id, { x: n.position.x, y: n.position.y }]))
|
||||
: {}
|
||||
|
||||
current.value = data
|
||||
profileKey.value = data.profile.uuid
|
||||
autoPos = autoLayout(data.graph)
|
||||
const flow = toFlow(data.graph, { ...data.positions, ...existing }, autoPos)
|
||||
if (selected.value && !flow.nodes.some((n) => n.id === selected.value)) selected.value = null
|
||||
nodes.value = flow.nodes
|
||||
edges.value = flow.edges
|
||||
error.value = null
|
||||
refreshView()
|
||||
if (!keep) fit()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? (e.status === 401 ? 'Нужна авторизация: обнови страницу и введи логин/пароль' : e.message) : String(e)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function onProfileChange() {
|
||||
selected.value = null
|
||||
await load()
|
||||
}
|
||||
|
||||
function onNodeClick({ node }: NodeMouseEvent) {
|
||||
selected.value = selected.value === node.id ? null : node.id
|
||||
}
|
||||
|
||||
// --- сохранение раскладки ---
|
||||
let saveTimer: number | undefined
|
||||
function scheduleSave() {
|
||||
window.clearTimeout(saveTimer)
|
||||
saveTimer = window.setTimeout(async () => {
|
||||
if (!current.value) return
|
||||
const positions: Positions = Object.fromEntries(
|
||||
getNodes.value.map((n) => [n.id, { x: Math.round(n.position.x), y: Math.round(n.position.y) }]),
|
||||
)
|
||||
saveState.value = 'saving'
|
||||
try {
|
||||
await savePositions(current.value.profile.uuid, positions)
|
||||
saveState.value = 'saved'
|
||||
} catch {
|
||||
saveState.value = 'error'
|
||||
}
|
||||
}, 600)
|
||||
}
|
||||
|
||||
async function resetLayout() {
|
||||
if (!current.value) return
|
||||
try {
|
||||
await resetPositions(current.value.profile.uuid)
|
||||
nodes.value = nodes.value.map((n) => ({ ...n, position: autoPos[n.id] ?? n.position }))
|
||||
saveState.value = 'idle'
|
||||
fit()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? e.message : String(e)
|
||||
}
|
||||
}
|
||||
|
||||
// --- предупреждения ---
|
||||
function warningTarget(w: string): string | null {
|
||||
let m = w.match(/^rule #(\d+)/)
|
||||
if (m) return `rule:${m[1]}`
|
||||
m = w.match(/^outbound (\S+)/)
|
||||
if (m) return `out:${m[1]}`
|
||||
m = w.match(/^balancer (\S+):/)
|
||||
if (m) return `bal:${m[1]}`
|
||||
m = w.match(/^хост (.+?): /)
|
||||
if (m) return current.value?.graph.nodes.find((n) => n.type === 'host' && n.label === m![1])?.id ?? null
|
||||
return null
|
||||
}
|
||||
function focusWarning(w: string) {
|
||||
const id = warningTarget(w)
|
||||
if (!id) return
|
||||
selected.value = id
|
||||
nextTick(() => fitView({ nodes: [id], padding: 0.6, maxZoom: 1, duration: 300 }))
|
||||
}
|
||||
|
||||
// --- автообновление ---
|
||||
let timer: number | undefined
|
||||
watch(autoRefresh, (on) => {
|
||||
window.clearInterval(timer)
|
||||
if (on) timer = window.setInterval(() => load({ keep: true }), 30_000)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
window.clearInterval(timer)
|
||||
window.clearTimeout(saveTimer)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
profiles.value = await getProfiles()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? e.message : String(e)
|
||||
return
|
||||
}
|
||||
await load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app">
|
||||
<header class="bar">
|
||||
<h1>Remnawave · маршруты</h1>
|
||||
<select v-model="profileKey" :disabled="loading || profiles.length < 2" @change="onProfileChange">
|
||||
<option v-for="p in profiles" :key="p.uuid" :value="p.uuid">{{ p.name }} ({{ p.rules }} правил)</option>
|
||||
</select>
|
||||
<button :disabled="loading" @click="load({ force: true, keep: true })">Обновить</button>
|
||||
<button :disabled="!current" @click="resetLayout">Сбросить раскладку</button>
|
||||
<button :disabled="!current" @click="fit(0)">Вписать</button>
|
||||
<label><input v-model="hideShadowed" type="checkbox" /> скрыть недостижимые правила</label>
|
||||
<label><input v-model="autoRefresh" type="checkbox" /> автообновление 30 с</label>
|
||||
<span class="spacer" />
|
||||
<span class="meta">{{ saveText }}</span>
|
||||
<span class="meta">{{ metaText }}</span>
|
||||
<button v-if="warnings.length" class="warn-btn" @click="showWarnings = !showWarnings">⚠ {{ warnings.length }}</button>
|
||||
</header>
|
||||
|
||||
<div v-if="error" class="banner err">{{ error }}</div>
|
||||
<div v-else-if="meta?.stale" class="banner stale">
|
||||
Панель недоступна, показан старый снимок ({{ Math.round(meta.ageSeconds) }} с): {{ meta.lastError }}
|
||||
</div>
|
||||
|
||||
<div class="canvas">
|
||||
<VueFlow
|
||||
v-model:nodes="nodes"
|
||||
v-model:edges="edges"
|
||||
:node-types="nodeTypes"
|
||||
:min-zoom="0.08"
|
||||
:max-zoom="1.8"
|
||||
:nodes-connectable="false"
|
||||
:elevate-edges-on-select="false"
|
||||
@node-click="onNodeClick"
|
||||
@pane-click="selected = null"
|
||||
@node-drag-stop="scheduleSave"
|
||||
>
|
||||
<Background pattern-color="#2a3347" :gap="24" />
|
||||
<MiniMap pannable zoomable />
|
||||
<Controls :show-interactive="false" />
|
||||
</VueFlow>
|
||||
|
||||
<aside v-if="showWarnings && warnings.length" class="warnings">
|
||||
<div class="wh">
|
||||
<b>Предупреждения</b>
|
||||
<button @click="showWarnings = false">×</button>
|
||||
</div>
|
||||
<ul>
|
||||
<li v-for="w in warnings" :key="w" :class="{ link: warningTarget(w) }" @click="focusWarning(w)">{{ w }}</li>
|
||||
</ul>
|
||||
</aside>
|
||||
|
||||
<div class="legend">
|
||||
<span><i class="l route" /> маршрут хоста (vlessRoute)</span>
|
||||
<span><i class="l target" /> правило → выход</span>
|
||||
<span><i class="l link" /> мост → нода</span>
|
||||
<span><i class="l dead" /> мёртвое ребро: правило недостижимо или нода не работает</span>
|
||||
<span class="hint">клик по узлу подсвечивает путь, по пустому месту сбрасывает</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { GraphResponse, Positions, ProfileItem } from './types'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, public status: number) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
let r: Response
|
||||
try {
|
||||
r = await fetch(url, { credentials: 'same-origin', ...init })
|
||||
} catch {
|
||||
throw new ApiError('Нет связи с бэкендом', 0)
|
||||
}
|
||||
if (!r.ok) {
|
||||
let msg = `HTTP ${r.status}`
|
||||
try {
|
||||
const body = await r.json()
|
||||
if (body?.message) msg = body.message
|
||||
} catch {
|
||||
/* тело не JSON */
|
||||
}
|
||||
throw new ApiError(msg, r.status)
|
||||
}
|
||||
return r.status === 204 ? (undefined as T) : r.json()
|
||||
}
|
||||
|
||||
export const getProfiles = () =>
|
||||
request<{ profiles: ProfileItem[] }>('/api/profiles').then((d) => d.profiles)
|
||||
|
||||
export function getGraph(profile?: string, refresh = false) {
|
||||
const q = new URLSearchParams()
|
||||
if (profile) q.set('profile', profile)
|
||||
if (refresh) q.set('refresh', '1')
|
||||
return request<GraphResponse>(`/api/graph?${q}`)
|
||||
}
|
||||
|
||||
export const savePositions = (uuid: string, positions: Positions) =>
|
||||
request<{ saved: number }>(`/api/positions/${uuid}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ positions }),
|
||||
})
|
||||
|
||||
export const resetPositions = (uuid: string) =>
|
||||
request<void>(`/api/positions/${uuid}`, { method: 'DELETE' })
|
||||
@@ -0,0 +1,131 @@
|
||||
<script setup lang="ts">
|
||||
import { Handle, Position } from '@vue-flow/core'
|
||||
import { computed } from 'vue'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const props = defineProps<{ id: string; data: Record<string, any> }>()
|
||||
const d = computed(() => props.data)
|
||||
|
||||
const KIND: Record<string, string> = {
|
||||
host: 'HOST', inbound: 'INBOUND', rule: 'RULE', balancer: 'BALANCER',
|
||||
outbound: 'OUTBOUND', node: 'NODE', unresolved: '???',
|
||||
}
|
||||
const kind = computed<string>(() => d.value.kind)
|
||||
const hasIn = computed(() => kind.value !== 'host')
|
||||
const hasOut = computed(() => !['node', 'unresolved'].includes(kind.value))
|
||||
|
||||
const title = computed(() => (kind.value === 'rule' ? `#${d.value.index}` : d.value.label))
|
||||
const cond = computed(() => String(d.value.label ?? '').replace(/^#\d+\s*/, ''))
|
||||
|
||||
function tone(name?: string, targetKind?: string) {
|
||||
if (targetKind === 'balancer') return 'violet'
|
||||
if (name === 'BLOCK') return 'red'
|
||||
if (name === 'DIRECT') return 'green'
|
||||
return 'blue'
|
||||
}
|
||||
const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="bp" :class="[`k-${kind}`, { off: d.disabled || d.state === 'disabled' }]">
|
||||
<Handle v-if="hasIn" id="in" type="target" :position="Position.Left" />
|
||||
<Handle v-if="hasOut" id="out" type="source" :position="Position.Right" />
|
||||
<template v-if="kind === 'rule'">
|
||||
<Handle id="prev" type="target" :position="Position.Top" />
|
||||
<Handle id="next" type="source" :position="Position.Bottom" />
|
||||
</template>
|
||||
|
||||
<div class="hd">
|
||||
<span class="kind">{{ KIND[kind] }}</span>
|
||||
<span class="title" :title="String(title)">{{ title }}</span>
|
||||
<span v-if="kind === 'node'" class="pill" :class="`st-${d.state}`">{{ d.state }}</span>
|
||||
<span v-if="kind === 'outbound' && d.ip" class="pill" :class="d.alive ? 'st-online' : 'st-offline'">
|
||||
{{ d.alive ? 'up' : 'down' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="bd">
|
||||
<template v-if="kind === 'host'">
|
||||
<div class="row"><span class="k">адрес</span>{{ d.address }}<template v-if="d.port">:{{ d.port }}</template></div>
|
||||
<div class="row">
|
||||
<span class="pill blue">{{ d.vlessRouteId != null ? `route ${d.vlessRouteId}` : 'без route' }}</span>
|
||||
<span v-if="d.disabled" class="pill st-disabled">disabled</span>
|
||||
<span v-if="d.exitAlive === false" class="pill st-offline">выход не работает</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'inbound'">
|
||||
<div class="row">{{ d.protocol }}<template v-if="d.port"> :{{ d.port }}</template></div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'rule'">
|
||||
<div class="cond" :title="cond">{{ cond }}</div>
|
||||
<div class="row">
|
||||
<span class="arrow">→</span>
|
||||
<span class="pill" :class="tone(d.target, d.targetKind)">{{ d.target }}</span>
|
||||
<span v-if="d.shadowed" class="pill st-offline" title="выше есть catch-all, правило не сработает">недостижимо</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'balancer'">
|
||||
<div class="row"><span class="k">стратегия</span>{{ d.strategy ?? '—' }}</div>
|
||||
<div class="row">
|
||||
<span class="k">живых</span>{{ d.aliveMembers?.length ?? 0 }} / {{ d.members?.length ?? 0 }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'outbound'">
|
||||
<div class="row">{{ d.protocol }}<template v-if="d.ip"> · {{ d.ip }}</template></div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="kind === 'node'">
|
||||
<div class="row">
|
||||
<span v-if="d.country" class="pill gray">{{ d.country }}</span>
|
||||
<span v-if="d.netbird" class="pill teal">NetBird</span>
|
||||
</div>
|
||||
<div class="row"><span class="k">мост</span>{{ list(d.mgmt) }}</div>
|
||||
<div class="row"><span class="k">выход</span>{{ list(d.exit) }}</div>
|
||||
<div v-if="d.inbound?.length" class="row"><span class="k">вход</span>{{ list(d.inbound) }}</div>
|
||||
<div v-if="d.reserve?.length" class="row"><span class="k">резерв</span>{{ d.reserve.length }}</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="row">адрес не найден ни в одной карточке ноды</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.bp { width: 250px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px;
|
||||
box-shadow: 0 4px 14px rgb(0 0 0 / 35%); font-size: 12px; color: #d6deeb; overflow: visible; }
|
||||
.hd { display: flex; align-items: center; gap: 8px; padding: 6px 10px; border-radius: 7px 7px 0 0;
|
||||
background: var(--hd, #2a3550); }
|
||||
.kind { font-size: 9px; letter-spacing: .08em; opacity: .75; font-weight: 600; }
|
||||
.title { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.bd { padding: 7px 10px 9px; display: flex; flex-direction: column; gap: 5px; }
|
||||
.row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; line-height: 1.35; }
|
||||
.k { color: #7f8ba3; min-width: 52px; }
|
||||
.cond { color: #aab6cc; display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical;
|
||||
overflow: hidden; word-break: break-word; }
|
||||
.arrow { color: #7f8ba3; }
|
||||
.pill { padding: 1px 7px; border-radius: 10px; font-size: 10.5px; background: #2b3550; color: #cdd7ea; white-space: nowrap; }
|
||||
.pill.blue { background: #1e3a66; color: #9cc4ff; }
|
||||
.pill.green { background: #17402f; color: #7ee2b0; }
|
||||
.pill.red { background: #4a1f26; color: #ff9aa5; }
|
||||
.pill.violet { background: #392a63; color: #c8b3ff; }
|
||||
.pill.teal { background: #14403f; color: #6fe0d6; }
|
||||
.pill.gray { background: #2b3243; color: #aab6cc; }
|
||||
.st-online { background: #17402f; color: #7ee2b0; }
|
||||
.st-offline { background: #4a1f26; color: #ff9aa5; }
|
||||
.st-disabled { background: #343a48; color: #9aa6bd; }
|
||||
.st-connecting { background: #4a3a14; color: #ffd27a; }
|
||||
.k-host { --hd: #1f3b66; }
|
||||
.k-inbound { --hd: #14504f; }
|
||||
.k-rule { --hd: #3b2f66; }
|
||||
.k-balancer { --hd: #5a2f66; }
|
||||
.k-outbound { --hd: #2d4a2f; }
|
||||
.k-node { --hd: #5a4320; }
|
||||
.k-unresolved { --hd: #6b2431; }
|
||||
.off { opacity: .6; }
|
||||
</style>
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { Edge, Node } from '@vue-flow/core'
|
||||
import type { Highlight } from './reach'
|
||||
import type { Graph, Positions } from './types'
|
||||
|
||||
const LABELLED = new Set(['link', 'route', 'fallback'])
|
||||
|
||||
/** Граф бэкенда -> узлы и рёбра Vue Flow (без подсветки). */
|
||||
export function toFlow(graph: Graph, positions: Positions, auto: Positions): { nodes: Node[]; edges: Edge[] } {
|
||||
const targetOf = new Map(graph.edges.filter((e) => e.kind === 'target').map((e) => [e.source, e.target]))
|
||||
|
||||
const nodes: Node[] = graph.nodes.map((n) => {
|
||||
const data: Record<string, unknown> = { ...n.data, kind: n.type, label: n.label }
|
||||
if (n.type === 'rule') {
|
||||
const t = targetOf.get(n.id)
|
||||
if (t) {
|
||||
data.target = t.replace(/^(out|bal):/, '')
|
||||
data.targetKind = t.startsWith('bal:') ? 'balancer' : 'outbound'
|
||||
}
|
||||
}
|
||||
return { id: n.id, type: 'bp', position: positions[n.id] ?? auto[n.id] ?? { x: 0, y: 0 }, data }
|
||||
})
|
||||
|
||||
const edges: Edge[] = graph.edges.map((e) => ({
|
||||
id: e.id,
|
||||
source: e.source,
|
||||
target: e.target,
|
||||
sourceHandle: e.kind === 'fallthrough' ? 'next' : 'out',
|
||||
targetHandle: e.kind === 'fallthrough' ? 'prev' : 'in',
|
||||
label: LABELLED.has(e.kind) ? e.label ?? undefined : undefined,
|
||||
data: { kind: e.kind, dead: !!e.data.dead },
|
||||
}))
|
||||
return { nodes, edges }
|
||||
}
|
||||
|
||||
/** Классы подсветки и скрытие. Позиции не трогает. */
|
||||
export function applyView(nodes: Node[], edges: Edge[], hl: Highlight | null, hideShadowed: boolean) {
|
||||
const hidden = new Set(nodes.filter((n) => hideShadowed && n.data.shadowed).map((n) => n.id))
|
||||
|
||||
const outNodes = nodes.map((n) => {
|
||||
const cls: string[] = []
|
||||
if (n.data.shadowed) cls.push('shadowed')
|
||||
if (hl) cls.push(hl.active.has(n.id) ? 'active' : hl.pass.has(n.id) ? 'pass' : 'dim')
|
||||
return { ...n, hidden: hidden.has(n.id), class: cls.join(' ') }
|
||||
})
|
||||
|
||||
const outEdges = edges.map((e) => {
|
||||
const cls = [`kind-${e.data.kind}`]
|
||||
if (e.data.dead) cls.push('dead')
|
||||
const lit = !!hl?.edges.has(e.id)
|
||||
if (hl) cls.push(lit ? 'active' : 'dim')
|
||||
return {
|
||||
...e,
|
||||
hidden: hidden.has(e.source) || hidden.has(e.target),
|
||||
animated: lit,
|
||||
class: cls.join(' '),
|
||||
}
|
||||
})
|
||||
return { nodes: outNodes, edges: outEdges }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { GNode, Graph, NodeKind, Positions } from './types'
|
||||
|
||||
export const COL_X: Record<NodeKind, number> = {
|
||||
host: 0,
|
||||
inbound: 330,
|
||||
rule: 660,
|
||||
balancer: 1040,
|
||||
outbound: 1380,
|
||||
node: 1720,
|
||||
unresolved: 1720,
|
||||
}
|
||||
export const NODE_HEIGHT: Record<NodeKind, number> = {
|
||||
host: 90, inbound: 76, rule: 84, balancer: 104, outbound: 80, node: 150, unresolved: 64,
|
||||
}
|
||||
const GAP = 24
|
||||
|
||||
/** Раскладка колонками: правила по порядку, остальное выравнивается по связанным узлам. */
|
||||
export function autoLayout(g: Graph): Positions {
|
||||
const y = new Map<string, number>()
|
||||
const pos: Positions = {}
|
||||
|
||||
const place = (kinds: NodeKind[], desired: (n: GNode) => number) => {
|
||||
const items = g.nodes
|
||||
.filter((n) => kinds.includes(n.type))
|
||||
.map((n) => ({ n, d: desired(n) }))
|
||||
.sort((a, b) => a.d - b.d)
|
||||
let cursor = -Infinity
|
||||
for (const { n, d } of items) {
|
||||
const yy = Math.max(d, cursor)
|
||||
y.set(n.id, yy)
|
||||
pos[n.id] = { x: COL_X[n.type], y: yy }
|
||||
cursor = yy + NODE_HEIGHT[n.type] + GAP
|
||||
}
|
||||
}
|
||||
|
||||
const mean = (ids: string[]) => {
|
||||
const ys = ids.map((i) => y.get(i)).filter((v): v is number => v !== undefined)
|
||||
return ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : 0
|
||||
}
|
||||
const sourcesOf = (id: string, kinds: string[]) =>
|
||||
g.edges.filter((e) => e.target === id && kinds.includes(e.kind)).map((e) => e.source)
|
||||
|
||||
place(['rule'], (n) => (n.data.index ?? 0) * (NODE_HEIGHT.rule + GAP))
|
||||
place(['balancer'], (n) => mean(sourcesOf(n.id, ['target'])))
|
||||
place(['outbound'], (n) => mean(sourcesOf(n.id, ['target', 'member', 'fallback'])))
|
||||
place(['node', 'unresolved'], (n) => mean(sourcesOf(n.id, ['link'])))
|
||||
place(['host'], (n) => {
|
||||
const last = (n.data.trace as string[] | undefined)?.at(-1)
|
||||
return (last ? y.get(last) ?? 0 : 0) + (n.data.vlessRouteId ?? 99) * 0.001
|
||||
})
|
||||
place(['inbound'], (n) => mean(g.edges.filter((e) => e.target === n.id).map((e) => e.source)))
|
||||
return pos
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import '@vue-flow/core/dist/style.css'
|
||||
import '@vue-flow/core/dist/theme-default.css'
|
||||
import '@vue-flow/controls/dist/style.css'
|
||||
import '@vue-flow/minimap/dist/style.css'
|
||||
import { createApp } from 'vue'
|
||||
import App from './App.vue'
|
||||
import './styles.css'
|
||||
|
||||
createApp(App).mount('#app')
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { Graph } from './types'
|
||||
|
||||
export interface Reach {
|
||||
nodes: Set<string>
|
||||
edges: Set<string>
|
||||
/** Правила, которые трафик хоста проверяет, но не применяет (не подошёл vlessRoute) */
|
||||
pass: Set<string>
|
||||
}
|
||||
|
||||
const ruleIndex = (id: string) => Number(id.split(':')[1])
|
||||
|
||||
/** Для каждого хоста: какие узлы и рёбра лежат на его пути до выходной ноды. */
|
||||
export function buildReach(g: Graph): Map<string, Reach> {
|
||||
const from = new Map<string, Graph['edges']>()
|
||||
for (const e of g.edges) from.set(e.source, [...(from.get(e.source) ?? []), e])
|
||||
const out = (id: string, ...kinds: string[]) => (from.get(id) ?? []).filter((e) => kinds.includes(e.kind))
|
||||
|
||||
const result = new Map<string, Reach>()
|
||||
for (const host of g.nodes.filter((n) => n.type === 'host')) {
|
||||
const r: Reach = { nodes: new Set([host.id]), edges: new Set(), pass: new Set() }
|
||||
const take = (e: Graph['edges'][number]) => {
|
||||
r.edges.add(e.id)
|
||||
r.nodes.add(e.target)
|
||||
}
|
||||
|
||||
for (const e of out(host.id, 'flow')) {
|
||||
take(e) // host -> inbound
|
||||
for (const e2 of out(e.target, 'flow')) r.edges.add(e2.id) // inbound -> rule:0
|
||||
}
|
||||
for (const e of out(host.id, 'route')) take(e)
|
||||
|
||||
const trace = (host.data.trace ?? []) as string[]
|
||||
if (trace.length) {
|
||||
const last = ruleIndex(trace[trace.length - 1])
|
||||
for (let i = 0; i <= last; i++) {
|
||||
const id = `rule:${i}`
|
||||
r.nodes.add(id)
|
||||
if (!trace.includes(id)) r.pass.add(id)
|
||||
if (i < last) for (const e of out(id, 'fallthrough')) r.edges.add(e.id)
|
||||
}
|
||||
// цели всех применимых правил: условные (BLOCK/DIRECT) и итоговое
|
||||
for (const id of trace) {
|
||||
for (const e of out(id, 'target')) {
|
||||
take(e)
|
||||
for (const m of out(e.target, 'member')) take(m) // балансер: любой из членов
|
||||
}
|
||||
}
|
||||
for (const id of [...r.nodes]) for (const e of out(id, 'link')) take(e)
|
||||
}
|
||||
result.set(host.id, r)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export interface Highlight {
|
||||
hostIds: string[]
|
||||
active: Set<string>
|
||||
pass: Set<string>
|
||||
edges: Set<string>
|
||||
}
|
||||
|
||||
/** Объединённый путь всех хостов, чей маршрут проходит через выбранный узел. */
|
||||
export function highlightFor(selected: string | null, reach: Map<string, Reach>): Highlight | null {
|
||||
if (!selected) return null
|
||||
const hostIds = selected.startsWith('host:')
|
||||
? [selected]
|
||||
: [...reach.entries()]
|
||||
.filter(([, r]) => r.nodes.has(selected) && !r.pass.has(selected))
|
||||
.map(([id]) => id)
|
||||
const active = new Set<string>([selected])
|
||||
const pass = new Set<string>()
|
||||
const edges = new Set<string>()
|
||||
for (const id of hostIds) {
|
||||
const r = reach.get(id)
|
||||
if (!r) continue
|
||||
for (const n of r.nodes) if (!r.pass.has(n)) active.add(n)
|
||||
r.pass.forEach((p) => pass.add(p))
|
||||
r.edges.forEach((e) => edges.add(e))
|
||||
}
|
||||
active.forEach((n) => pass.delete(n)) // активный для одного хоста не "проходной" из-за другого
|
||||
return { hostIds, active, pass, edges }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
html, body, #app { height: 100%; margin: 0; }
|
||||
body { background: #0f1420; color: #d6deeb;
|
||||
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
||||
|
||||
.app { position: relative; height: 100%; }
|
||||
.bar { position: absolute; z-index: 20; inset: 0 0 auto 0; height: 52px; display: flex; align-items: center; gap: 10px;
|
||||
padding: 0 14px; background: #151b2b; border-bottom: 1px solid #263149; }
|
||||
.bar h1 { font-size: 15px; margin: 0 6px 0 0; font-weight: 600; white-space: nowrap; }
|
||||
.bar label { display: flex; align-items: center; gap: 5px; color: #aab6cc; white-space: nowrap; }
|
||||
.spacer { flex: 1; }
|
||||
.meta { color: #7f8ba3; font-size: 12px; white-space: nowrap; }
|
||||
button, select { background: #202a40; color: #d6deeb; border: 1px solid #33405c; border-radius: 6px;
|
||||
padding: 5px 10px; font: inherit; cursor: pointer; }
|
||||
button:hover:not(:disabled) { background: #2a3654; }
|
||||
button:disabled, select:disabled { opacity: .5; cursor: default; }
|
||||
.warn-btn { color: #ffd27a; border-color: #5a4a22; }
|
||||
|
||||
.banner { position: absolute; z-index: 15; top: 60px; left: 50%; transform: translateX(-50%); padding: 7px 14px;
|
||||
border-radius: 6px; max-width: 80%; }
|
||||
.banner.err { background: #4a1f26; color: #ffb3bc; border: 1px solid #7a2f3a; }
|
||||
.banner.stale { background: #4a3a14; color: #ffd27a; border: 1px solid #7a6020; }
|
||||
|
||||
.canvas { position: absolute; inset: 52px 0 0 0; }
|
||||
|
||||
.warnings { position: absolute; z-index: 15; top: 12px; right: 12px; width: 420px; max-height: 60%; overflow: auto;
|
||||
background: #151b2b; border: 1px solid #33405c; border-radius: 8px; padding: 10px 12px; box-shadow: 0 8px 24px rgb(0 0 0 / 45%); }
|
||||
.warnings .wh { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
|
||||
.warnings ul { margin: 0; padding-left: 16px; display: flex; flex-direction: column; gap: 5px; color: #ffd27a; }
|
||||
.warnings li.link { cursor: pointer; }
|
||||
.warnings li.link:hover { color: #fff1c9; }
|
||||
|
||||
.legend { position: absolute; z-index: 10; left: 62px; bottom: 14px; display: flex; flex-wrap: wrap; gap: 4px 16px;
|
||||
max-width: 60%; padding: 6px 10px; background: #151b2bd9; border: 1px solid #263149; border-radius: 6px;
|
||||
color: #aab6cc; font-size: 11.5px; }
|
||||
.legend .l { display: inline-block; width: 22px; height: 0; border-top: 2px solid; vertical-align: middle; margin-right: 4px; }
|
||||
.legend .l.route { border-color: #60a5fa; border-top-style: dashed; }
|
||||
.legend .l.target { border-color: #a78bfa; }
|
||||
.legend .l.link { border-color: #34d399; }
|
||||
.legend .l.dead { border-color: #ef4444; border-top-style: dashed; }
|
||||
.legend .hint { color: #7f8ba3; }
|
||||
|
||||
/* --- Vue Flow --- */
|
||||
.vue-flow { background: #0f1420; }
|
||||
.vue-flow__handle { width: 10px; height: 10px; border-radius: 50%; background: #8b9bb4; border: 2px solid #0f1420; }
|
||||
.vue-flow__handle-top, .vue-flow__handle-bottom { width: 9px; height: 9px; background: #5b6a86; }
|
||||
.vue-flow__node { transition: opacity .15s; }
|
||||
.vue-flow__node.dim { opacity: .2; }
|
||||
.vue-flow__node.pass { opacity: .5; }
|
||||
.vue-flow__node.active .bp { border-color: #6ea8ff; box-shadow: 0 0 0 1px #6ea8ff, 0 4px 18px rgb(80 140 255 / 35%); }
|
||||
.vue-flow__node.shadowed .bp { border-style: dashed; border-color: #8a3a46; }
|
||||
.vue-flow__node.shadowed { opacity: .8; }
|
||||
.vue-flow__node.shadowed.dim { opacity: .15; }
|
||||
.vue-flow__node.selected .bp { border-color: #6ea8ff; }
|
||||
|
||||
.vue-flow__edge-path { stroke: #4b5568; stroke-width: 1.6; transition: opacity .15s; }
|
||||
.vue-flow__edge.kind-flow .vue-flow__edge-path { stroke: #94a3b8; }
|
||||
.vue-flow__edge.kind-route .vue-flow__edge-path { stroke: #60a5fa; stroke-dasharray: 6 4; }
|
||||
.vue-flow__edge.kind-fallthrough .vue-flow__edge-path { stroke: #4b5568; stroke-width: 1.2; }
|
||||
.vue-flow__edge.kind-target .vue-flow__edge-path { stroke: #a78bfa; }
|
||||
.vue-flow__edge.kind-member .vue-flow__edge-path { stroke: #c084fc; }
|
||||
.vue-flow__edge.kind-fallback .vue-flow__edge-path { stroke: #f59e0b; stroke-dasharray: 4 4; }
|
||||
.vue-flow__edge.kind-link .vue-flow__edge-path { stroke: #34d399; stroke-width: 2.2; }
|
||||
.vue-flow__edge.dead .vue-flow__edge-path { stroke: #ef4444; stroke-dasharray: 5 4; }
|
||||
.vue-flow__edge.dim .vue-flow__edge-path { opacity: .08; }
|
||||
.vue-flow__edge.active .vue-flow__edge-path { stroke-width: 3; }
|
||||
.vue-flow__edge-text { font-size: 10px; fill: #aab6cc; }
|
||||
.vue-flow__edge-textbg { fill: #0f1420; }
|
||||
.vue-flow__edge.dim .vue-flow__edge-text, .vue-flow__edge.dim .vue-flow__edge-textbg { opacity: .1; }
|
||||
|
||||
.vue-flow__controls { box-shadow: none; border: 1px solid #263149; }
|
||||
.vue-flow__controls-button { background: #202a40; border-bottom: 1px solid #263149; fill: #d6deeb; }
|
||||
.vue-flow__controls-button:hover { background: #2a3654; }
|
||||
.vue-flow__minimap { background: #151b2b; border: 1px solid #263149; }
|
||||
@@ -0,0 +1,50 @@
|
||||
export type NodeKind = 'host' | 'inbound' | 'rule' | 'balancer' | 'outbound' | 'node' | 'unresolved'
|
||||
export type EdgeKind = 'flow' | 'route' | 'fallthrough' | 'target' | 'member' | 'fallback' | 'link'
|
||||
|
||||
export interface GNode {
|
||||
id: string
|
||||
type: NodeKind
|
||||
label: string
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
data: Record<string, any>
|
||||
}
|
||||
|
||||
export interface GEdge {
|
||||
id: string
|
||||
source: string
|
||||
target: string
|
||||
kind: EdgeKind
|
||||
label: string | null
|
||||
data: { dead?: boolean }
|
||||
}
|
||||
|
||||
export interface Graph {
|
||||
nodes: GNode[]
|
||||
edges: GEdge[]
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
cached: boolean
|
||||
stale: boolean
|
||||
ageSeconds: number
|
||||
fetchedAt: string
|
||||
lastError?: string
|
||||
}
|
||||
|
||||
export type Positions = Record<string, { x: number; y: number }>
|
||||
|
||||
export interface GraphResponse {
|
||||
profile: { uuid: string; name: string }
|
||||
graph: Graph
|
||||
positions: Positions
|
||||
meta: Meta
|
||||
}
|
||||
|
||||
export interface ProfileItem {
|
||||
uuid: string
|
||||
name: string
|
||||
inbounds: number
|
||||
rules: number
|
||||
nodes: string[]
|
||||
}
|
||||
Vendored
+1235
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,105 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyView, toFlow } from '../src/flow'
|
||||
import { autoLayout, COL_X, NODE_HEIGHT } from '../src/layout'
|
||||
import { buildReach, highlightFor } from '../src/reach'
|
||||
import type { Graph } from '../src/types'
|
||||
import raw from './fixtures/graph.json'
|
||||
|
||||
const graph = raw as unknown as Graph
|
||||
|
||||
describe('autoLayout', () => {
|
||||
const pos = autoLayout(graph)
|
||||
|
||||
it('даёт позицию каждому узлу', () => {
|
||||
for (const n of graph.nodes) expect(pos[n.id], n.id).toBeDefined()
|
||||
})
|
||||
|
||||
it('узлы одной колонки не перекрываются', () => {
|
||||
const byCol = new Map<number, { y: number; h: number; id: string }[]>()
|
||||
for (const n of graph.nodes) {
|
||||
const x = COL_X[n.type]
|
||||
byCol.set(x, [...(byCol.get(x) ?? []), { y: pos[n.id].y, h: NODE_HEIGHT[n.type], id: n.id }])
|
||||
}
|
||||
for (const items of byCol.values()) {
|
||||
items.sort((a, b) => a.y - b.y)
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
expect(items[i].y, `${items[i - 1].id} / ${items[i].id}`).toBeGreaterThanOrEqual(items[i - 1].y + items[i - 1].h)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('правила идут сверху вниз по порядку', () => {
|
||||
const ys = graph.nodes.filter((n) => n.type === 'rule').sort((a, b) => a.data.index - b.data.index).map((n) => pos[n.id].y)
|
||||
expect([...ys].sort((a, b) => a - b)).toEqual(ys)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reach / highlight', () => {
|
||||
const reach = buildReach(graph)
|
||||
|
||||
it('хост с route 3 доходит до BRIDGE_3 и FI-01, пропуская правила 6 и 7', () => {
|
||||
const r = reach.get('host:h3')!
|
||||
expect(r.nodes.has('out:BRIDGE_3')).toBe(true)
|
||||
expect(r.nodes.has('node:FI-01')).toBe(true)
|
||||
expect(r.nodes.has('out:BRIDGE_4')).toBe(false)
|
||||
expect([...r.pass].sort()).toEqual(['rule:6', 'rule:7'])
|
||||
expect(r.nodes.has('rule:8')).toBe(true)
|
||||
expect(r.pass.has('rule:8')).toBe(false)
|
||||
})
|
||||
|
||||
it('хост с route 8 упирается в catch-all и никогда не видит SoundCloud-правила', () => {
|
||||
const r = reach.get('host:h8')!
|
||||
expect(r.nodes.has('rule:13')).toBe(true)
|
||||
expect(r.nodes.has('rule:14')).toBe(false)
|
||||
expect(r.nodes.has('bal:BRIDGE_AUTO')).toBe(true)
|
||||
})
|
||||
|
||||
it('хост другого профиля отсутствует', () => {
|
||||
expect(reach.has('host:hx')).toBe(false)
|
||||
})
|
||||
|
||||
it('клик по ноде подсвечивает хосты, которые на неё выходят', () => {
|
||||
const hl = highlightFor('node:FI-01', reach)!
|
||||
expect(hl.hostIds.sort()).toEqual(['host:h3', 'host:h7', 'host:h8', 'host:hn'])
|
||||
expect(hl.active.has('node:FI-01')).toBe(true)
|
||||
})
|
||||
|
||||
it('клик по недостижимому правилу не подсвечивает ни одного хоста', () => {
|
||||
expect(highlightFor('rule:14', reach)!.hostIds).toEqual([])
|
||||
})
|
||||
|
||||
it('клик по DIRECT подсвечивает все хосты профиля', () => {
|
||||
expect(highlightFor('out:DIRECT', reach)!.hostIds).toHaveLength(4)
|
||||
})
|
||||
})
|
||||
|
||||
describe('toFlow / applyView', () => {
|
||||
const flow = toFlow(graph, {}, autoLayout(graph))
|
||||
|
||||
it('правило знает свою цель, цепочка идёт через нижний/верхний порт', () => {
|
||||
expect(flow.nodes.find((n) => n.id === 'rule:8')!.data.target).toBe('BRIDGE_3')
|
||||
expect(flow.nodes.find((n) => n.id === 'rule:13')!.data.targetKind).toBe('balancer')
|
||||
const ft = flow.edges.find((e) => e.id.includes('fallthrough'))!
|
||||
expect([ft.sourceHandle, ft.targetHandle]).toEqual(['next', 'prev'])
|
||||
})
|
||||
|
||||
it('сохранённая позиция важнее автоматической', () => {
|
||||
const f = toFlow(graph, { 'rule:0': { x: 1, y: 2 } }, autoLayout(graph))
|
||||
expect(f.nodes.find((n) => n.id === 'rule:0')!.position).toEqual({ x: 1, y: 2 })
|
||||
})
|
||||
|
||||
it('hideShadowed скрывает недостижимые правила и их рёбра', () => {
|
||||
const v = applyView(flow.nodes, flow.edges, null, true)
|
||||
expect(v.nodes.filter((n) => n.hidden).length).toBe(8)
|
||||
expect(v.edges.filter((e) => e.hidden).length).toBeGreaterThan(8)
|
||||
})
|
||||
|
||||
it('подсветка: остальное приглушается, позиции не меняются', () => {
|
||||
const hl = highlightFor('host:h3', buildReach(graph))
|
||||
const v = applyView(flow.nodes, flow.edges, hl, false)
|
||||
expect(v.nodes.find((n) => n.id === 'host:h3')!.class).toContain('active')
|
||||
expect(v.nodes.find((n) => n.id === 'host:h7')!.class).toContain('dim')
|
||||
expect(v.nodes.find((n) => n.id === 'rule:6')!.class).toContain('pass')
|
||||
expect(v.nodes.map((n) => n.position)).toEqual(flow.nodes.map((n) => n.position))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"jsx": "preserve",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"types": ["vite/client", "node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "tests/**/*.ts", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
// В dev /api проксируется на бэкенд (Basic-auth браузер спросит сам).
|
||||
const target = process.env.VITE_API_TARGET ?? 'http://127.0.0.1:8080'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: { port: 5173, proxy: { '/api': { target, changeOrigin: false } } },
|
||||
test: { environment: 'node' },
|
||||
})
|
||||
Reference in New Issue
Block a user