fix topology of cards
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
# rw-viz: карта маршрутов Remnawave
|
||||
|
||||
Интерактивный визуализатор маршрутизации: `host → inbound → rules → balancer → outbound → node`.
|
||||
Узлы перетаскиваются как в Blueprints, раскладка сохраняется. Только чтение: берутся config-профили,
|
||||
Интерактивная карта сети: `хост → нода (профиль: инбаунды + правила) → outbound → нода-приёмник`.
|
||||
Блоки перетаскиваются как в Blueprints, раскладка сохраняется. Только чтение: берутся config-профили,
|
||||
хосты и ноды из API панели, без юзеров и трафика.
|
||||
|
||||
```
|
||||
backend/ Flask: клиент панели, сборка графа, кэш, позиции узлов
|
||||
backend/ Flask: клиент панели, сборка графа, кэш, позиции блоков
|
||||
frontend/ Vue 3 + TypeScript + Vue Flow
|
||||
Dockerfile сборка обоих в один образ (Flask раздаёт собранный фронт)
|
||||
```
|
||||
@@ -30,29 +30,38 @@ REMNAWAVE_URL=... REMNAWAVE_TOKEN=... flask --app wsgi run --port 8080
|
||||
cd frontend && npm install && npm run dev
|
||||
```
|
||||
|
||||
Тесты: `pytest` (backend, 29 шт.) и `npm test` (frontend, 13 шт.); `npm run build` делает ещё и typecheck.
|
||||
Тесты: `pytest` (backend) и `npm test` (frontend); `npm run build` делает ещё и typecheck.
|
||||
|
||||
## Что показывает карта
|
||||
## Как читать карту
|
||||
|
||||
- **Колонки:** хосты, inbound, правила по порядку, балансер, outbound'ы, ноды.
|
||||
- **Клик по хосту** подсвечивает его путь: условные правила (BLOCK/DIRECT), применимое правило по `vlessRoute`,
|
||||
выход и ноду. Проверенные, но не подошедшие правила приглушены. **Клик по узлу** подсвечивает все хосты, которые на него выходят.
|
||||
- **Недостижимые правила** (после catch-all по `inboundTag`) рисуются пунктиром и попадают в предупреждения;
|
||||
Колонки слева направо: **хосты → карточки нод → балансеры и outbound'ы → ноды-приёмники**.
|
||||
|
||||
- **Хост** ведёт одной ниткой на свою ноду и садится на строку правила, которое для него срабатывает
|
||||
(по `vlessRoute` и порядку правил). Нитка подписана `route N`. Хост без одной ноды помечается предупреждением.
|
||||
- **Карточка ноды**: имя, состояние, профиль, адреса (NetBird и публичный выход). Внутри секции активных инбаундов,
|
||||
в каждой строки-правила в порядке выполнения: правила этого инбаунда и общие (без `inboundTag`).
|
||||
У строки свой выход и своя нитка к цели. Если правил с `inboundTag` в секции нет, пометка «общее» не показывается.
|
||||
Последняя строка «иначе (по умолчанию)» это первый outbound конфига: Xray отправляет туда трафик, не попавший ни в одно правило.
|
||||
- **Outbound'ы остаются карточками**: прокси-outbound с одним назначением общий для всех нод, которые в него выходят
|
||||
(в карточке «используют: …»). `BLOCK` один на всех, `DIRECT` у каждой ноды свой (у него свой публичный IP).
|
||||
- **Нода-приёмник:** outbound, смотрящий на адрес другой ноды, ведёт зелёной ниткой в строку её инбаунда
|
||||
(по адресу и порту, например SS :9999). Дальше трафик идёт по правилам секции этого инбаунда.
|
||||
- **Подсветка:** клик по хосту, строке, ноде или блоку подсвечивает путь (или все хосты, которые через него идут).
|
||||
Проверенные, но не подошедшие правила приглушены. Для трафика, пришедшего по мосту, `vlessRoute` неизвестен:
|
||||
правила с `vlessRoute` считаются не подошедшими.
|
||||
- **Недостижимые правила** (после catch-all этого инбаунда) зачёркнуты, без нитки наружу, собраны в одно предупреждение;
|
||||
есть переключатель «скрыть недостижимые».
|
||||
- **Отключённые и оффлайн-ноды** помечены, рёбра к ним красные пунктиром, балансер показывает «живых N / M».
|
||||
- **⚠ в шапке** открывает список предупреждений, клик по строке фокусируется на узле.
|
||||
- Привязка outbound к ноде идёт по NetBird-адресу: `ips[]` со статусом `MANAGEMENT`, затем `address`.
|
||||
Если адрес не найден ни в одной карточке, появится красный узел «???».
|
||||
- **Отключённые и оффлайн-ноды:** помечены, рёбра к ним красные пунктиром, у балансера «живых N / M».
|
||||
- **Неиспользуемые ноды** (на них нет ни хостов, ни ссылок от outbound'ов) на карте не рисуются.
|
||||
|
||||
## API бэкенда
|
||||
|
||||
| Метод | Путь | |
|
||||
|---|---|---|
|
||||
| GET | `/api/health` | живость (без авторизации) |
|
||||
| GET | `/api/profiles` | список профилей |
|
||||
| GET | `/api/graph?profile=<имя\|uuid>&refresh=1` | граф, позиции, `meta` |
|
||||
| GET/PUT/DELETE | `/api/positions/<uuid профиля>` | раскладка узлов |
|
||||
| GET | `/api/graph?refresh=1` | граф всей сети: блоки, рёбра, предупреждения, пути хостов, позиции, `meta` |
|
||||
| GET/PUT/DELETE | `/api/positions/<ключ>` | раскладка блоков (ключ `network-v2` отдаётся в `positionsKey`) |
|
||||
|
||||
Снимок панели кэшируется на `CACHE_TTL` секунд (`?refresh=1` не чаще раза в 5 с). Если панель недоступна,
|
||||
отдаётся последний снимок с `meta.stale = true`. Конфиг Xray наружу не уходит: приватные ключи Reality,
|
||||
отдаётся последний снимок с `meta.stale = true`. Конфиги Xray наружу не уходят: приватные ключи Reality,
|
||||
shortIds и пароли Shadowsocks в граф не попадают (это проверяют тесты). Позиции лежат в `DATA_DIR/positions.json`.
|
||||
|
||||
@@ -28,7 +28,6 @@ class Settings:
|
||||
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
|
||||
@@ -59,7 +58,6 @@ class Settings:
|
||||
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,
|
||||
|
||||
+374
-144
@@ -1,15 +1,27 @@
|
||||
"""Сборка графа маршрутизации Remnawave: профиль + хосты + ноды -> {nodes, edges, warnings}.
|
||||
"""Граф сети Remnawave: хост -> нода (профиль: инбаунды + правила) -> балансер/outbound -> нода ...
|
||||
|
||||
Колонки слева направо: host -> inbound -> rule(ы) -> balancer -> outbound -> node.
|
||||
Только чтение, без статистики и юзеров.
|
||||
Только чтение. Секреты конфигов (ключи, пароли) в граф не попадают.
|
||||
|
||||
Модель:
|
||||
* хост ведёт ровно на одну ноду и садится на строку правила, которое для него срабатывает;
|
||||
* карточка ноды содержит секции активных инбаундов, в секции строки-правила по порядку
|
||||
(правила инбаунда + общие без inboundTag);
|
||||
* у каждой строки свой выход к outbound/балансеру; outbound'ы общие: если несколько нод
|
||||
выходят в одну точку, это одна карточка;
|
||||
* outbound, смотрящий на адрес другой ноды, ведёт в строку её инбаунда (по порту).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
|
||||
# Ключи правила, которые мы умеем вычислять точно (остальные = "условные").
|
||||
_TARGET_KEYS = {"outboundTag", "balancerTag", "ruleTag", "type"}
|
||||
_EXACT_KEYS = {"vlessRoute", "inboundTag"}
|
||||
_INTERNAL = [ipaddress.ip_network(n) for n in
|
||||
("100.64.0.0/10", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- правила
|
||||
def parse_vless_route(value) -> set[int] | None:
|
||||
"""1 | "8-14" | "1,3,8-10" -> множество номеров; None, если поля нет."""
|
||||
if value is None:
|
||||
@@ -36,43 +48,48 @@ def _opaque(rule: dict) -> set[str]:
|
||||
return _conditions(rule) - _EXACT_KEYS
|
||||
|
||||
|
||||
def _as_list(v) -> list:
|
||||
return [] if v is None else ([v] if isinstance(v, str) else list(v))
|
||||
|
||||
|
||||
def applies_to(rule: dict, inbound_tag: str | None) -> bool:
|
||||
tags = _as_list(rule.get("inboundTag"))
|
||||
return not tags or inbound_tag in tags
|
||||
|
||||
|
||||
def is_catch_all(rule: dict) -> bool:
|
||||
"""Правило без условий (кроме inboundTag) забирает весь трафик инбаунда."""
|
||||
return _conditions(rule) <= {"inboundTag"}
|
||||
|
||||
|
||||
def rule_label(rule: dict) -> str:
|
||||
parts = []
|
||||
for k in sorted(_conditions(rule)):
|
||||
for k in sorted(_conditions(rule) - {"inboundTag"}):
|
||||
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 "любой трафик"
|
||||
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 ranges(nums) -> str:
|
||||
out, start, prev = [], None, None
|
||||
for n in sorted(nums):
|
||||
if start is None:
|
||||
start = prev = n
|
||||
elif n == prev + 1:
|
||||
prev = n
|
||||
else:
|
||||
out.append((start, prev))
|
||||
start = prev = n
|
||||
if start is not None:
|
||||
out.append((start, prev))
|
||||
return ", ".join(f"#{a}" if a == b else f"#{a}–#{b}" for a, b in out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ноды
|
||||
def node_state(n: dict) -> str:
|
||||
"""disabled | connecting | offline | online."""
|
||||
if n.get("isDisabled"):
|
||||
@@ -109,8 +126,6 @@ def node_info(n: dict) -> dict:
|
||||
"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"),
|
||||
@@ -119,134 +134,349 @@ def node_info(n: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def outbound_ip(ob: dict) -> str | None:
|
||||
# ---------------------------------------------------------------- outbound'ы
|
||||
def _port(v) -> int | None:
|
||||
try:
|
||||
return ob["settings"]["servers"][0]["address"]
|
||||
except (KeyError, IndexError, TypeError):
|
||||
return None # freedom / blackhole
|
||||
return int(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
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}
|
||||
def outbound_endpoint(ob: dict) -> tuple[str, int | None] | None:
|
||||
"""(адрес, порт) назначения прокси-outbound; None для freedom/blackhole."""
|
||||
s = ob.get("settings") or {}
|
||||
try:
|
||||
for key in ("servers", "vnext"):
|
||||
if s.get(key):
|
||||
return str(s[key][0]["address"]), _port(s[key][0].get("port"))
|
||||
if s.get("peers"): # wireguard
|
||||
host, _, port = str(s["peers"][0]["endpoint"]).rpartition(":")
|
||||
return host.strip("[]"), _port(port)
|
||||
except (KeyError, IndexError, TypeError, AttributeError):
|
||||
pass
|
||||
return None
|
||||
|
||||
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 _is_internal(addr: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(addr)
|
||||
except ValueError:
|
||||
return False
|
||||
return any(ip in net for net in _INTERNAL)
|
||||
|
||||
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 _row(key: str, index: int | None, rule: dict, shadowed: bool = False, default: bool = False) -> dict:
|
||||
kind, tag = (("balancer", rule["balancerTag"]) if "balancerTag" in rule
|
||||
else ("outbound", rule.get("outboundTag")))
|
||||
routes = parse_vless_route(rule.get("vlessRoute"))
|
||||
return {
|
||||
"key": key, "index": index,
|
||||
"label": "иначе (по умолчанию)" if default else rule_label(rule),
|
||||
"common": default or not rule.get("inboundTag"),
|
||||
"shadowed": shadowed, "default": default,
|
||||
"vlessRoute": sorted(routes) if routes else [],
|
||||
"targetKind": kind, "targetTag": tag,
|
||||
"_routes": routes, "_opaque": bool(_opaque(rule)), "tid": None, "edge": None,
|
||||
}
|
||||
|
||||
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"))
|
||||
def build_sections(node: dict, profile: dict) -> list[dict]:
|
||||
"""Секции активных инбаундов ноды: правила инбаунда + общие, в порядке выполнения."""
|
||||
cfg = profile["config"]
|
||||
rules = (cfg.get("routing") or {}).get("rules") or []
|
||||
outbounds = cfg.get("outbounds") or []
|
||||
inb_defs = {i.get("uuid"): i for i in profile.get("inbounds") or []}
|
||||
cfg_inb = {i.get("tag"): i for i in cfg.get("inbounds") or []}
|
||||
sections = []
|
||||
for a in (node.get("configProfile") or {}).get("activeInbounds") or []:
|
||||
d = inb_defs.get(a.get("uuid")) or a
|
||||
tag = d.get("tag")
|
||||
c = cfg_inb.get(tag) or {}
|
||||
rows: list[dict] = []
|
||||
catch: int | None = None
|
||||
for idx, r in enumerate(rules):
|
||||
if not applies_to(r, tag):
|
||||
continue
|
||||
rows.append(_row(str(idx), idx, r, shadowed=catch is not None))
|
||||
if catch is None and is_catch_all(r):
|
||||
catch = idx
|
||||
if catch is None and outbounds: # Xray: без совпадений трафик идёт в первый outbound
|
||||
rows.append(_row("default", None, {"outboundTag": outbounds[0].get("tag")}, default=True))
|
||||
sections.append({"uuid": a.get("uuid"), "tag": tag,
|
||||
"port": _port(d.get("port") or c.get("port")),
|
||||
"protocol": d.get("type") or c.get("protocol"),
|
||||
"rows": rows, "catchAll": catch})
|
||||
return sections
|
||||
|
||||
# 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])
|
||||
def trace_rows(rows: list[dict], route: int | None) -> list[dict]:
|
||||
"""Строки, через которые может пройти трафик, до первой безусловной."""
|
||||
trace: list[dict] = []
|
||||
for r in rows:
|
||||
if r["shadowed"]:
|
||||
break
|
||||
if r["_routes"] is not None and route not in r["_routes"]:
|
||||
continue
|
||||
trace.append(r)
|
||||
if not r["_opaque"]:
|
||||
break
|
||||
return trace
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- граф
|
||||
def E(src: str, sh: str, dst: str, th: str) -> str:
|
||||
return f"{src}#{sh}>{dst}#{th}"
|
||||
|
||||
|
||||
def build_graph(profiles: list[dict], hosts: list[dict], nodes: list[dict]) -> dict:
|
||||
prof = {p["uuid"]: p for p in profiles if isinstance(p.get("config"), dict)}
|
||||
by_uuid = {n["uuid"]: n for n in nodes if n.get("uuid")}
|
||||
idx = build_node_index(nodes)
|
||||
|
||||
warnings: list[dict] = []
|
||||
seen_warn: set[str] = set()
|
||||
|
||||
def warn(text: str, target: str | None = None) -> None:
|
||||
if text not in seen_warn:
|
||||
seen_warn.add(text)
|
||||
warnings.append({"text": text, "target": target})
|
||||
|
||||
edges: list[dict] = []
|
||||
edge_ids: set[str] = set()
|
||||
|
||||
def add_edge(src, sh, dst, th, kind, label=None, dead=False) -> str:
|
||||
eid = E(src, sh, dst, th)
|
||||
if eid not in edge_ids:
|
||||
edge_ids.add(eid)
|
||||
edges.append({"id": eid, "source": src, "sourceHandle": sh, "target": dst,
|
||||
"targetHandle": th, "kind": kind, "label": label, "data": {"dead": dead}})
|
||||
return eid
|
||||
|
||||
ctxs: dict[str, dict] = {}
|
||||
queue: list[dict] = []
|
||||
|
||||
def ctx_of(n: dict) -> dict:
|
||||
nid = f"node:{n.get('uuid') or n['name']}"
|
||||
if nid not in ctxs:
|
||||
p = prof.get((n.get("configProfile") or {}).get("activeConfigProfileUuid"))
|
||||
cfg = p["config"] if p else {}
|
||||
ctx = {"id": nid, "node": n, "profile": p,
|
||||
"sections": build_sections(n, p) if p else [],
|
||||
"outbounds": {o.get("tag"): o for o in cfg.get("outbounds") or []},
|
||||
"balancers": {b.get("tag"): b for b in (cfg.get("routing") or {}).get("balancers") or []}}
|
||||
ctxs[nid] = ctx
|
||||
queue.append(ctx)
|
||||
return ctxs[nid]
|
||||
|
||||
outs: dict[str, dict] = {}
|
||||
bals: dict[str, dict] = {}
|
||||
|
||||
def alive_of(cid: str) -> bool:
|
||||
return (outs.get(cid) or bals[cid])["alive"]
|
||||
|
||||
def out_card(ctx: dict, tag: str) -> str:
|
||||
ob = ctx["outbounds"].get(tag)
|
||||
n = ctx["node"]
|
||||
protocol = (ob or {}).get("protocol", "?")
|
||||
ep = outbound_endpoint(ob) if ob else None
|
||||
if ep:
|
||||
key = f"{protocol}:{ep[0]}:{ep[1]}" # прокси: общий для всех нод с тем же назначением
|
||||
elif protocol == "blackhole":
|
||||
key = f"blackhole:{tag}" # BLOCK у всех нод одинаков: одна карточка
|
||||
else:
|
||||
key = f"{protocol}:{ctx['id']}:{tag}" # freedom: у каждой ноды свой публичный выход
|
||||
cid = f"out:{key}"
|
||||
card = outs.get(cid)
|
||||
if card is None:
|
||||
card = {"id": cid, "tags": set(), "users": set(), "protocol": protocol,
|
||||
"address": ep[0] if ep else None, "port": ep[1] if ep else None,
|
||||
"alive": True, "dest": None, "destName": None, "exit": [], "owner": None}
|
||||
outs[cid] = card
|
||||
if ob is None:
|
||||
card["alive"] = False
|
||||
warn(f"{n['name']}: правило ведёт в несуществующий outbound {tag}", ctx["id"])
|
||||
if protocol == "freedom":
|
||||
card["owner"] = n["name"]
|
||||
card["exit"] = node_info(n)["exit"]
|
||||
if ep:
|
||||
dn = idx.get(ep[0])
|
||||
if dn is not None:
|
||||
dctx = ctx_of(dn)
|
||||
sec = next((s for s in dctx["sections"] if ep[1] is not None and s["port"] == ep[1]), None)
|
||||
state = node_state(dn)
|
||||
card["alive"] = state == "online"
|
||||
card["destName"] = dn["name"]
|
||||
card["dest"] = {
|
||||
"node": dctx["id"], "uuid": sec["uuid"] if sec else None,
|
||||
"edge": add_edge(cid, "out", dctx["id"], f"inb:{sec['uuid']}" if sec else "head",
|
||||
"link", f"{ep[0]}:{ep[1]}", dead=state != "online"),
|
||||
}
|
||||
if state != "online":
|
||||
warn(f"outbound {tag} → {dn['name']}: нода {state}", cid)
|
||||
if sec is None:
|
||||
warn(f"outbound {tag} → {dn['name']}: на ноде нет активного инбаунда на порту {ep[1]}", dctx["id"])
|
||||
elif _is_internal(ep[0]):
|
||||
card["alive"] = False
|
||||
warn(f"outbound {tag}: адрес {ep[0]} не найден ни в одной карточке ноды", cid)
|
||||
card["tags"].add(tag)
|
||||
card["users"].add(n["name"])
|
||||
return cid
|
||||
|
||||
def bal_card(ctx: dict, tag: str) -> str | None:
|
||||
bid = f"bal:{ctx['id']}:{tag}"
|
||||
if bid in bals:
|
||||
return bid
|
||||
b = ctx["balancers"].get(tag)
|
||||
if b is None:
|
||||
warn(f"{ctx['node']['name']}: правило ведёт в несуществующий балансер {tag}", ctx["id"])
|
||||
return None
|
||||
sels = [str(s) for s in _as_list(b.get("selector"))]
|
||||
member_tags = [t for t in ctx["outbounds"] if any(str(t).startswith(s) for s in sels)]
|
||||
members = list(dict.fromkeys(out_card(ctx, t) for t in member_tags))
|
||||
fb = b.get("fallbackTag")
|
||||
if fb:
|
||||
add_edge(f"bal:{b['tag']}", f"out:{fb}", "fallback", "fallback",
|
||||
dead=not alive.get(fb, False))
|
||||
fb_id = out_card(ctx, fb) if fb in ctx["outbounds"] else None
|
||||
live = [m for m in members if outs[m]["alive"]]
|
||||
bals[bid] = {"id": bid, "tag": tag, "strategy": (b.get("strategy") or {}).get("type"),
|
||||
"members": members, "aliveMembers": live, "alive": bool(live),
|
||||
"node": ctx["node"]["name"]}
|
||||
for m in members: # fallback, входящий в селектор, помечается на ребре члена
|
||||
add_edge(bid, "out", m, "in", "member", "fallback" if m == fb_id else None,
|
||||
dead=not outs[m]["alive"])
|
||||
if fb_id and fb_id not in members:
|
||||
add_edge(bid, "out", fb_id, "in", "fallback", "fallback", dead=not outs[fb_id]["alive"])
|
||||
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} ведёт на нерабочую ноду")
|
||||
warn(f"{ctx['node']['name']}: балансер {tag} без живых членов", bid)
|
||||
return bid
|
||||
|
||||
# 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 [])}
|
||||
# --- хосты: к какой ноде ведут ---
|
||||
plans = []
|
||||
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} ведёт на нерабочую ноду")
|
||||
inb_uuid = (h.get("inbound") or {}).get("configProfileInboundUuid")
|
||||
if not inb_uuid:
|
||||
continue
|
||||
cand = [by_uuid[u] for u in h.get("nodes") or [] if u in by_uuid]
|
||||
if not cand:
|
||||
cand = [n for n in nodes if any(a.get("uuid") == inb_uuid for a in
|
||||
(n.get("configProfile") or {}).get("activeInbounds") or [])]
|
||||
if len(cand) != 1:
|
||||
warn(f"хост {h['remark']}: привязан к {len(cand)} нодам, ожидается ровно одна", f"host:{h['uuid']}")
|
||||
plans.append((h, inb_uuid, [ctx_of(n) for n in cand]))
|
||||
|
||||
return {"nodes": G_nodes, "edges": G_edges, "warnings": warnings}
|
||||
# --- обход нод: цели строк, outbound'ы, ноды-приёмники ---
|
||||
while queue:
|
||||
ctx = queue.pop(0)
|
||||
for sec in ctx["sections"]:
|
||||
shadowed = [r["index"] for r in sec["rows"] if r["shadowed"]]
|
||||
if shadowed:
|
||||
warn(f"{ctx['node']['name']} / {sec['tag']}: недостижимы правила {ranges(shadowed)} "
|
||||
f"(выше catch-all #{sec['catchAll']})", ctx["id"])
|
||||
for r in sec["rows"]:
|
||||
if r["shadowed"] or not r["targetTag"]:
|
||||
continue
|
||||
cid = (out_card(ctx, r["targetTag"]) if r["targetKind"] == "outbound"
|
||||
else bal_card(ctx, r["targetTag"]))
|
||||
r["tid"] = cid
|
||||
if cid:
|
||||
r["edge"] = add_edge(ctx["id"], f"rout:{sec['uuid']}:{r['key']}", cid, "in",
|
||||
"target", dead=not alive_of(cid))
|
||||
|
||||
# --- пути хостов ---
|
||||
def section_of(ctx: dict, uuid: str | None) -> dict | None:
|
||||
return next((s for s in ctx["sections"] if s["uuid"] == uuid), None)
|
||||
|
||||
def walk(ctx: dict, uuid: str | None, route: int | None, path: dict, seen: set) -> None:
|
||||
if (ctx["id"], uuid) in seen:
|
||||
return
|
||||
seen.add((ctx["id"], uuid))
|
||||
path["nodes"].add(ctx["id"])
|
||||
rows = path["rows"].setdefault(ctx["id"], {"active": set(), "pass": set()})
|
||||
sec = section_of(ctx, uuid)
|
||||
if sec is None:
|
||||
return
|
||||
rows["active"].add(f"inb:{sec['uuid']}")
|
||||
trace = trace_rows(sec["rows"], route)
|
||||
if trace:
|
||||
last = sec["rows"].index(trace[-1])
|
||||
in_trace = {id(r) for r in trace}
|
||||
for r in sec["rows"][: last + 1]:
|
||||
rows["active" if id(r) in in_trace else "pass"].add(f"{sec['uuid']}:{r['key']}")
|
||||
for r in trace:
|
||||
if r["tid"]:
|
||||
path["edges"].add(r["edge"])
|
||||
follow(r["tid"], path, seen)
|
||||
|
||||
def follow(cid: str, path: dict, seen: set) -> None:
|
||||
path["nodes"].add(cid)
|
||||
if cid in bals:
|
||||
for m in bals[cid]["members"]:
|
||||
path["edges"].add(E(cid, "out", m, "in"))
|
||||
follow_out(m, path, seen)
|
||||
else:
|
||||
follow_out(cid, path, seen)
|
||||
|
||||
def follow_out(oid: str, path: dict, seen: set) -> None:
|
||||
path["nodes"].add(oid)
|
||||
d = outs[oid]["dest"]
|
||||
if d:
|
||||
path["edges"].add(d["edge"])
|
||||
walk(ctxs[d["node"]], d["uuid"], None, path, seen) # трафик моста: vlessRoute неизвестен
|
||||
|
||||
host_nodes: list[dict] = []
|
||||
paths: dict[str, dict] = {}
|
||||
for h, inb_uuid, cands in sorted(
|
||||
plans, key=lambda p: (p[2][0]["node"]["name"] if p[2] else "", p[0].get("vlessRouteId") is None,
|
||||
p[0].get("vlessRouteId") or 0, p[0]["remark"])):
|
||||
hid = f"host:{h['uuid']}"
|
||||
route = h.get("vlessRouteId")
|
||||
path = {"nodes": {hid}, "edges": set(), "rows": {}}
|
||||
seen: set = set()
|
||||
exit_alive, tag = False, None
|
||||
for ctx in cands:
|
||||
sec = section_of(ctx, inb_uuid)
|
||||
state = node_state(ctx["node"])
|
||||
if sec is None:
|
||||
th = "head"
|
||||
warn(f"хост {h['remark']}: инбаунд хоста не активен на ноде {ctx['node']['name']}", hid)
|
||||
else:
|
||||
tag = sec["tag"]
|
||||
trace = trace_rows(sec["rows"], route)
|
||||
th = f"rin:{sec['uuid']}:{trace[-1]['key']}" if trace else f"inb:{sec['uuid']}"
|
||||
last_tid = trace[-1]["tid"] if trace else None
|
||||
exit_alive = exit_alive or (state == "online" and last_tid is not None and alive_of(last_tid))
|
||||
path["edges"].add(add_edge(hid, "out", ctx["id"], th, "host",
|
||||
f"route {route}" if route is not None else None,
|
||||
dead=state != "online"))
|
||||
walk(ctx, inb_uuid, route, path, seen)
|
||||
host_nodes.append({"id": hid, "type": "host", "label": h["remark"], "data": {
|
||||
"address": h.get("address"), "port": h.get("port"), "vlessRouteId": route,
|
||||
"disabled": bool(h.get("isDisabled")), "nodeNames": [c["node"]["name"] for c in cands],
|
||||
"inboundTag": tag, "exitAlive": exit_alive}})
|
||||
paths[hid] = {"nodes": sorted(path["nodes"]), "edges": sorted(path["edges"]),
|
||||
"rows": {k: {"active": sorted(v["active"]), "pass": sorted(v["pass"])}
|
||||
for k, v in path["rows"].items()}}
|
||||
|
||||
# --- карточки ---
|
||||
node_cards = []
|
||||
for ctx in ctxs.values():
|
||||
p = ctx["profile"]
|
||||
node_cards.append({"id": ctx["id"], "type": "node", "label": ctx["node"]["name"], "data": {
|
||||
**node_info(ctx["node"]),
|
||||
"profile": {"uuid": p["uuid"], "name": p["name"]} if p else None,
|
||||
"sections": [{
|
||||
"uuid": s["uuid"], "tag": s["tag"], "port": s["port"], "protocol": s["protocol"],
|
||||
"rows": [{"key": r["key"], "index": r["index"], "label": r["label"], "common": r["common"],
|
||||
"shadowed": r["shadowed"], "default": r["default"], "vlessRoute": r["vlessRoute"],
|
||||
"targetKind": r["targetKind"], "target": r["targetTag"],
|
||||
"hasEdge": r["edge"] is not None} for r in s["rows"]],
|
||||
} for s in ctx["sections"]]}})
|
||||
bal_cards = [{"id": b["id"], "type": "balancer", "label": b["tag"], "data": {
|
||||
"strategy": b["strategy"], "members": b["members"], "aliveMembers": b["aliveMembers"],
|
||||
"alive": b["alive"], "node": b["node"]}} for b in bals.values()]
|
||||
out_cards = [{"id": o["id"], "type": "outbound", "label": " · ".join(sorted(o["tags"])), "data": {
|
||||
"protocol": o["protocol"], "address": o["address"], "port": o["port"], "alive": o["alive"],
|
||||
"users": sorted(o["users"]), "destName": o["destName"], "exit": o["exit"], "owner": o["owner"]}}
|
||||
for o in outs.values()]
|
||||
|
||||
return {"nodes": host_nodes + node_cards + bal_cards + out_cards, "edges": edges,
|
||||
"warnings": warnings, "paths": paths}
|
||||
|
||||
+8
-49
@@ -9,69 +9,33 @@ from .remnawave import RemnawaveError
|
||||
|
||||
bp = Blueprint("api", __name__, url_prefix="/api")
|
||||
|
||||
|
||||
class ProfileNotFound(LookupError):
|
||||
pass
|
||||
NETWORK_KEY = "network-v2" # ключ, под которым хранится раскладка всей сети
|
||||
|
||||
|
||||
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"])
|
||||
result = build_graph(snap["profiles"], 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
|
||||
message=f"Не удалось разобрать данные панели: {type(e).__name__}: {e}"), 422
|
||||
return jsonify({
|
||||
"profile": {"uuid": profile["uuid"], "name": profile["name"]},
|
||||
"graph": result,
|
||||
"positions": svc.positions.get(profile["uuid"]),
|
||||
"positionsKey": NETWORK_KEY,
|
||||
"positions": svc.positions.get(NETWORK_KEY),
|
||||
"meta": {**meta, "fetchedAt": snap["fetchedAt"]},
|
||||
})
|
||||
|
||||
@@ -79,14 +43,14 @@ def graph():
|
||||
@bp.get("/positions/<key>")
|
||||
def get_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
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
|
||||
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
|
||||
@@ -101,7 +65,7 @@ def put_positions(key: str):
|
||||
@bp.delete("/positions/<key>")
|
||||
def delete_positions(key: str):
|
||||
if not valid_key(key):
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор профиля"), 400
|
||||
return jsonify(error="bad_key", message="Некорректный идентификатор раскладки"), 400
|
||||
_svc().positions.delete(key)
|
||||
return "", 204
|
||||
|
||||
@@ -109,8 +73,3 @@ def delete_positions(key: str):
|
||||
@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
|
||||
|
||||
+58
-18
@@ -1,11 +1,17 @@
|
||||
"""Фикстура, повторяющая профиль BridgeOverNetbird и ноды из панели."""
|
||||
"""Фикстура сети: вход RU-01 (профиль Bridge) + 6 выходных нод (профиль Default)."""
|
||||
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"]
|
||||
EXIT_NAMES = ["FR-01", "NL-01", "FI-01", "NL-04", "CH-01", "BR-01"]
|
||||
|
||||
BRIDGE_UUID = "aaaaaaaa-0000-0000-0000-000000000001"
|
||||
DEFAULT_UUID = "bbbbbbbb-0000-0000-0000-000000000002"
|
||||
INB_BRIDGE = "inb-bridge" # RU_NODE_IN
|
||||
INB_VLESS = "inb-def-vless" # DEFAULT_IN, 443
|
||||
INB_SS = "inb-def-ss" # BRIDGE_SS_IN, 9999
|
||||
|
||||
|
||||
def make_profile() -> dict:
|
||||
def bridge_profile() -> dict:
|
||||
rules = [
|
||||
{"port": 25, "outboundTag": "BLOCK"},
|
||||
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
|
||||
@@ -32,25 +38,59 @@ def make_profile() -> dict:
|
||||
{"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"}]}
|
||||
return {"uuid": BRIDGE_UUID, "name": "BridgeOverNetbird", "config": config,
|
||||
"inbounds": [{"uuid": INB_BRIDGE, "tag": "RU_NODE_IN", "type": "vless", "port": 443}]}
|
||||
|
||||
|
||||
def default_profile() -> dict:
|
||||
config = {
|
||||
"inbounds": [
|
||||
{"tag": "DEFAULT_IN", "port": 443, "protocol": "vless"},
|
||||
{"tag": "BRIDGE_SS_IN", "port": 9999, "protocol": "shadowsocks",
|
||||
"settings": {"password": "SECRET-SS"}},
|
||||
],
|
||||
"outbounds": [{"tag": "DIRECT", "protocol": "freedom"}, {"tag": "BLOCK", "protocol": "blackhole"}],
|
||||
"routing": {"rules": [
|
||||
{"protocol": ["bittorrent"], "outboundTag": "BLOCK"},
|
||||
{"ip": ["geoip:private"], "outboundTag": "BLOCK"},
|
||||
]},
|
||||
}
|
||||
return {"uuid": DEFAULT_UUID, "name": "Default", "config": config, "inbounds": [
|
||||
{"uuid": INB_VLESS, "tag": "DEFAULT_IN", "type": "vless", "port": 443},
|
||||
{"uuid": INB_SS, "tag": "BRIDGE_SS_IN", "type": "shadowsocks", "port": 9999}]}
|
||||
|
||||
|
||||
def make_profiles() -> list[dict]:
|
||||
return [default_profile(), bridge_profile()]
|
||||
|
||||
|
||||
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"}],
|
||||
ru = {"uuid": "n-ru", "name": "RU-01", "address": "100.106.247.44", "countryCode": "RU",
|
||||
"isConnected": True, "isDisabled": False,
|
||||
"ips": [{"ip": "91.201.43.187", "status": "OUTBOUND"}, {"ip": "100.106.247.44", "status": "MANAGEMENT"}],
|
||||
"configProfile": {"activeConfigProfileUuid": BRIDGE_UUID, "activeInbounds": [{"uuid": INB_BRIDGE}]},
|
||||
"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
|
||||
exits = [{"uuid": f"n-{i}", "name": n, "address": ip, "countryCode": "XX",
|
||||
"isConnected": True, "isDisabled": False,
|
||||
"ips": [{"ip": ip, "status": "MANAGEMENT"}, {"ip": f"1.1.1.{i}", "status": "OUTBOUND"}],
|
||||
"configProfile": {"activeConfigProfileUuid": DEFAULT_UUID,
|
||||
"activeInbounds": [{"uuid": INB_VLESS}, {"uuid": INB_SS}]},
|
||||
"system": {"info": {"networkInterfaces": ["lo", "wt0"]}}}
|
||||
for i, (n, ip) in enumerate(zip(EXIT_NAMES, BRIDGE_IPS))]
|
||||
unused = {"uuid": "n-us", "name": "US-01", "address": "78.153.155.226", "ips": [],
|
||||
"configProfile": {"activeConfigProfileUuid": None, "activeInbounds": []}, "system": None}
|
||||
return [ru, *exits, unused]
|
||||
|
||||
|
||||
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
|
||||
def host(uuid, remark, node, inbound, route=None):
|
||||
return {"uuid": uuid, "remark": remark, "address": "node-ru.example", "port": 443,
|
||||
"vlessRouteId": route, "nodes": [node],
|
||||
"inbound": {"configProfileUuid": "x", "configProfileInboundUuid": inbound}}
|
||||
return [
|
||||
host("h3", "Bridge-Ivi", "n-ru", INB_BRIDGE, 3),
|
||||
host("h7", "Bridge-Auto", "n-ru", INB_BRIDGE, 7),
|
||||
host("h8", "Bridge-Mira-SC", "n-ru", INB_BRIDGE, 8),
|
||||
host("hn", "Bridge-NoRoute", "n-ru", INB_BRIDGE, None),
|
||||
host("hd", "Direct-FI", "n-2", INB_VLESS), # прямое подключение к выходной ноде
|
||||
]
|
||||
|
||||
@@ -5,9 +5,9 @@ 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
|
||||
from .fixtures import make_hosts, make_nodes, make_profiles
|
||||
|
||||
KEY = "aaaaaaaa-0000-0000-0000-000000000001"
|
||||
KEY = "network-v2"
|
||||
|
||||
|
||||
class FakeClient:
|
||||
@@ -19,9 +19,7 @@ class FakeClient:
|
||||
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()}
|
||||
return {"profiles": make_profiles(), "hosts": make_hosts(), "nodes": make_nodes()}
|
||||
|
||||
|
||||
def make_settings(tmp_path, **kw):
|
||||
@@ -37,29 +35,18 @@ def client_and_fake(tmp_path):
|
||||
return app.test_client(), fake
|
||||
|
||||
|
||||
def test_graph_default_profile_is_the_one_with_vless_route(client_and_fake):
|
||||
def test_graph_endpoint_returns_whole_network(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"]
|
||||
g = body["graph"]
|
||||
assert {n["type"] for n in g["nodes"]} == {"host", "node", "balancer", "outbound"}
|
||||
assert g["warnings"] and g["paths"]
|
||||
assert body["positionsKey"] == KEY
|
||||
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")
|
||||
|
||||
+209
-52
@@ -2,96 +2,253 @@ import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from app.graph import build_graph, parse_vless_route
|
||||
from .fixtures import make_hosts, make_nodes, make_profile
|
||||
from app.graph import build_graph, parse_vless_route, ranges
|
||||
from .fixtures import (EXIT_NAMES, INB_BRIDGE, INB_SS, INB_VLESS, make_hosts, make_nodes, make_profiles)
|
||||
|
||||
|
||||
def build(profiles=None, hosts=None, nodes=None):
|
||||
return build_graph(profiles or make_profiles(), hosts or make_hosts(), nodes or make_nodes())
|
||||
|
||||
|
||||
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]
|
||||
def edges_from(g, src):
|
||||
return [e for e in g["edges"] if e["source"] == src]
|
||||
|
||||
|
||||
def card_by_name(g, name):
|
||||
return next(n for n in g["nodes"] if n["type"] == "node" and n["label"] == name)
|
||||
|
||||
|
||||
def out_card(g, tag):
|
||||
return next(n for n in g["nodes"] if n["type"] == "outbound" and tag in n["label"].split(" · "))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def g():
|
||||
return build_graph(make_profile(), make_hosts(), make_nodes())
|
||||
return build()
|
||||
|
||||
|
||||
def test_parse_vless_route():
|
||||
def test_parse_vless_route_and_ranges():
|
||||
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}
|
||||
assert ranges([14, 15, 16, 20]) == "#14–#16, #20"
|
||||
|
||||
|
||||
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_each_host_has_exactly_one_thread_to_its_node(g):
|
||||
for h in (n for n in g["nodes"] if n["type"] == "host"):
|
||||
assert len(edges_from(g, h["id"])) == 1
|
||||
assert {n["id"] for n in g["nodes"] if n["type"] == "host"} == {"host:h3", "host:h7", "host:h8", "host:hn", "host:hd"}
|
||||
|
||||
|
||||
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_bridge_host_lands_on_its_rule_row(g):
|
||||
land = {e["source"]: e["targetHandle"] for e in g["edges"] if e["kind"] == "host"}
|
||||
assert land["host:h3"] == f"rin:{INB_BRIDGE}:8" # vlessRoute 3 -> BRIDGE_3
|
||||
assert land["host:h7"] == f"rin:{INB_BRIDGE}:12" # vlessRoute 7 -> балансер
|
||||
assert land["host:h8"] == f"rin:{INB_BRIDGE}:13" # route 8 упирается в catch-all
|
||||
assert land["host:hn"] == f"rin:{INB_BRIDGE}:13"
|
||||
e3 = next(e for e in g["edges"] if e["source"] == "host:h3")
|
||||
assert e3["target"] == "node:n-ru" and e3["label"] == "route 3"
|
||||
|
||||
|
||||
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_direct_host_lands_on_default_row_of_exit_node(g):
|
||||
e = next(e for e in g["edges"] if e["source"] == "host:hd")
|
||||
assert e["target"] == "node:n-2"
|
||||
assert e["targetHandle"] == f"rin:{INB_VLESS}:default" # правила условные -> дальше "по умолчанию"
|
||||
|
||||
|
||||
def test_node_card_sections_and_rows(g):
|
||||
ru = card_by_name(g, "RU-01")["data"]
|
||||
assert ru["profile"]["name"] == "BridgeOverNetbird"
|
||||
(sec,) = ru["sections"]
|
||||
assert (sec["tag"], sec["port"], sec["protocol"]) == ("RU_NODE_IN", 443, "vless")
|
||||
assert len(sec["rows"]) == 22
|
||||
assert [r["index"] for r in sec["rows"] if r["shadowed"]] == list(range(14, 22))
|
||||
assert all(not r["hasEdge"] for r in sec["rows"] if r["shadowed"])
|
||||
fi = card_by_name(g, "FI-01")["data"]
|
||||
assert [s["tag"] for s in fi["sections"]] == ["DEFAULT_IN", "BRIDGE_SS_IN"]
|
||||
assert all(s["rows"][-1]["default"] for s in fi["sections"])
|
||||
assert all(r["common"] for s in fi["sections"] for r in s["rows"])
|
||||
|
||||
|
||||
def test_shadowed_warning_is_aggregated(g):
|
||||
w = [w["text"] for w in g["warnings"] if "недостижимы" in w["text"]]
|
||||
assert w == ["RU-01 / RU_NODE_IN: недостижимы правила #14–#21 (выше catch-all #13)"]
|
||||
|
||||
|
||||
def test_bridge_outbound_leads_to_exit_nodes_inbound_row(g):
|
||||
o = out_card(g, "BRIDGE_3")
|
||||
assert o["data"]["destName"] == "FI-01"
|
||||
(link,) = edges_from(g, o["id"])
|
||||
assert (link["target"], link["targetHandle"]) == ("node:n-2", f"inb:{INB_SS}")
|
||||
assert link["label"] == "100.106.214.118:9999"
|
||||
|
||||
|
||||
def test_outbound_shared_by_several_nodes_is_one_card():
|
||||
nodes = make_nodes()
|
||||
ru2 = copy.deepcopy(nodes[0])
|
||||
ru2.update(uuid="n-ru2", name="RU-02", address="100.106.247.45")
|
||||
ru2["ips"] = [{"ip": "100.106.247.45", "status": "MANAGEMENT"}]
|
||||
g = build(nodes=[*nodes, ru2], hosts=make_hosts() + [
|
||||
{"uuid": "h-ru2", "remark": "Bridge-RU2", "vlessRouteId": 3, "nodes": ["n-ru2"],
|
||||
"inbound": {"configProfileInboundUuid": INB_BRIDGE}}])
|
||||
cards = [n for n in g["nodes"] if n["type"] == "outbound" and "BRIDGE_3" in n["label"]]
|
||||
assert len(cards) == 1
|
||||
assert cards[0]["data"]["users"] == ["RU-01", "RU-02"]
|
||||
# а вот DIRECT у каждой ноды свой: у него разные публичные IP
|
||||
directs = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "freedom"]
|
||||
assert len({n["data"]["owner"] for n in directs}) == len(directs) >= 2
|
||||
|
||||
|
||||
def test_blackhole_is_shared_but_direct_is_per_node(g):
|
||||
blocks = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "blackhole"]
|
||||
assert len(blocks) == 1 and blocks[0]["data"]["users"] == sorted(["RU-01", *EXIT_NAMES])
|
||||
directs = [n for n in g["nodes"] if n["type"] == "outbound" and n["data"]["protocol"] == "freedom"]
|
||||
assert sorted(n["data"]["owner"] for n in directs) == sorted(["RU-01", *EXIT_NAMES])
|
||||
assert all(n["data"]["exit"] for n in directs) # у каждой ноды свой публичный IP
|
||||
|
||||
|
||||
def test_balancer_card_and_members(g):
|
||||
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
|
||||
assert bal["label"] == "BRIDGE_AUTO" and len(bal["data"]["members"]) == 6
|
||||
assert bal["data"]["aliveMembers"] == bal["data"]["members"]
|
||||
es = edges_from(g, bal["id"])
|
||||
assert {e["kind"] for e in es} == {"member"}
|
||||
assert [e["label"] for e in es if e["label"]] == ["fallback"] # BRIDGE_1 входит в селектор
|
||||
assert next(e for e in es if e["label"])["target"] == out_card(g, "BRIDGE_1")["id"]
|
||||
|
||||
|
||||
def test_fallback_outside_selector_gets_its_own_edge():
|
||||
profiles = make_profiles()
|
||||
profiles[1]["config"]["routing"]["balancers"][0]["fallbackTag"] = "DIRECT"
|
||||
g = build(profiles=profiles)
|
||||
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
|
||||
fb = [e for e in edges_from(g, bal["id"]) if e["kind"] == "fallback"]
|
||||
assert len(fb) == 1 and fb[0]["target"] == out_card(g, "DIRECT")["id"]
|
||||
|
||||
|
||||
def test_path_of_bridge_host_crosses_both_nodes(g):
|
||||
p = g["paths"]["host:h3"]
|
||||
o = out_card(g, "BRIDGE_3")["id"]
|
||||
assert {"node:n-ru", o, "node:n-2"} <= set(p["nodes"])
|
||||
assert "node:n-3" not in p["nodes"] # NL-04 не задействован
|
||||
ru = p["rows"]["node:n-ru"]
|
||||
assert f"{INB_BRIDGE}:8" in ru["active"] and f"{INB_BRIDGE}:0" in ru["active"]
|
||||
assert set(ru["pass"]) == {f"{INB_BRIDGE}:6", f"{INB_BRIDGE}:7"}
|
||||
fi = p["rows"]["node:n-2"]
|
||||
assert f"inb:{INB_SS}" in fi["active"] and f"{INB_SS}:default" in fi["active"]
|
||||
link = edges_from(g, o)[0]["id"]
|
||||
assert link in p["edges"]
|
||||
|
||||
|
||||
def test_path_through_balancer_reaches_every_member(g):
|
||||
p = g["paths"]["host:h7"]
|
||||
assert all(n in p["nodes"] for n in ("node:n-0", "node:n-1", "node:n-2", "node:n-3", "node:n-4", "node:n-5"))
|
||||
assert [n for n in p["nodes"] if n.startswith("bal:")]
|
||||
|
||||
|
||||
def test_direct_host_path_stays_on_one_node(g):
|
||||
p = g["paths"]["host:hd"]
|
||||
assert "node:n-ru" not in p["nodes"]
|
||||
assert f"{INB_VLESS}:default" in p["rows"]["node:n-2"]["active"]
|
||||
|
||||
|
||||
def test_unused_nodes_are_not_drawn(g):
|
||||
assert "node:n-us" not in by_id(g)
|
||||
|
||||
|
||||
def test_no_secrets_in_output(g):
|
||||
dump = str(g)
|
||||
assert "SECRET" not in dump
|
||||
assert "SECRET" not in str(g)
|
||||
|
||||
|
||||
def test_disabled_and_offline_nodes():
|
||||
def test_disabled_and_offline_exit_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"}
|
||||
g = build(nodes=nodes)
|
||||
assert card_by_name(g, "NL-04")["data"]["state"] == "disabled"
|
||||
assert card_by_name(g, "BR-01")["data"]["state"] == "offline"
|
||||
dead = {e["source"] for e in g["edges"] if e["kind"] == "link" and e["data"]["dead"]}
|
||||
assert dead == {out_card(g, "BRIDGE_4")["id"], out_card(g, "BRIDGE_6")["id"]}
|
||||
(bal,) = [n for n in g["nodes"] if n["type"] == "balancer"]
|
||||
assert len(bal["data"]["aliveMembers"]) == 4
|
||||
assert any("нода disabled" in w["text"] for w in g["warnings"])
|
||||
|
||||
|
||||
def test_all_nodes_down_warns():
|
||||
def test_all_exits_down_warns_and_marks_hosts():
|
||||
nodes = make_nodes()
|
||||
for n in nodes:
|
||||
for n in nodes[1:]:
|
||||
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
|
||||
g = build(nodes=nodes)
|
||||
assert any("без живых членов" in w["text"] for w in g["warnings"])
|
||||
assert by_id(g)["host:h7"]["data"]["exitAlive"] is False
|
||||
|
||||
|
||||
def test_unresolved_outbound():
|
||||
def test_duplicate_disabled_node_with_same_address_does_not_win():
|
||||
nodes = make_nodes()
|
||||
nodes.insert(0, {"uuid": "n-old", "name": "OLD-FR", "address": BRIDGE_FIRST, "isDisabled": True,
|
||||
"ips": [{"ip": BRIDGE_FIRST, "status": "MANAGEMENT"}], "system": None,
|
||||
"configProfile": {"activeConfigProfileUuid": None, "activeInbounds": []}})
|
||||
g = build(nodes=nodes)
|
||||
assert out_card(g, "BRIDGE_1")["data"]["destName"] == "FR-01"
|
||||
|
||||
|
||||
BRIDGE_FIRST = "100.106.180.60"
|
||||
|
||||
|
||||
def test_unresolved_internal_address_is_flagged():
|
||||
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"])
|
||||
g = build(nodes=nodes)
|
||||
o = out_card(g, "BRIDGE_4")
|
||||
assert o["data"]["alive"] is False and o["data"]["destName"] is None
|
||||
assert any("не найден" in w["text"] for w in g["warnings"])
|
||||
|
||||
|
||||
def test_host_not_bound_to_single_node_warns():
|
||||
hosts = make_hosts()
|
||||
hosts[0]["nodes"] = [] # пусто -> все ноды с этим инбаундом (здесь только RU-01)
|
||||
hosts[1]["nodes"] = ["n-ru", "n-2"]
|
||||
g = build(hosts=hosts)
|
||||
texts = [w["text"] for w in g["warnings"]]
|
||||
assert any("Bridge-Auto" in t and "2 нодам" in t for t in texts)
|
||||
assert len(edges_from(g, "host:h7")) == 2
|
||||
|
||||
|
||||
def test_host_inbound_not_active_on_node():
|
||||
hosts = make_hosts()
|
||||
hosts[4]["inbound"]["configProfileInboundUuid"] = INB_BRIDGE # у FI-01 такого инбаунда нет
|
||||
g = build(hosts=hosts)
|
||||
e = next(e for e in g["edges"] if e["source"] == "host:hd")
|
||||
assert e["targetHandle"] == "head"
|
||||
assert any("не активен на ноде FI-01" in w["text"] for w in g["warnings"])
|
||||
|
||||
|
||||
def test_missing_outbound_and_balancer_are_reported():
|
||||
profiles = make_profiles()
|
||||
profiles[1]["config"]["routing"]["rules"][0]["outboundTag"] = "NOPE"
|
||||
profiles[1]["config"]["routing"]["rules"][1]["balancerTag"] = "NOBAL"
|
||||
del profiles[1]["config"]["routing"]["rules"][1]["outboundTag"]
|
||||
g = build(profiles=profiles)
|
||||
texts = " | ".join(w["text"] for w in g["warnings"])
|
||||
assert "несуществующий outbound NOPE" in texts and "несуществующий балансер NOBAL" in texts
|
||||
|
||||
|
||||
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
|
||||
args = (make_profiles(), make_hosts(), make_nodes())
|
||||
snapshot = copy.deepcopy(args)
|
||||
build_graph(*args)
|
||||
assert args == snapshot
|
||||
|
||||
|
||||
def test_all_edge_endpoints_exist(g):
|
||||
ids = set(by_id(g))
|
||||
for e in g["edges"]:
|
||||
assert e["source"] in ids and e["target"] in ids, e["id"]
|
||||
assert len({e["id"] for e in g["edges"]}) == len(g["edges"])
|
||||
for p in g["paths"].values():
|
||||
assert set(p["edges"]) <= {e["id"] for e in g["edges"]}
|
||||
|
||||
+33
-61
@@ -3,18 +3,17 @@ 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 { computed, markRaw, nextTick, onBeforeUnmount, onMounted, provide, ref, watch, type Ref } from 'vue'
|
||||
import { ApiError, getGraph, resetPositions, savePositions } from './api'
|
||||
import BlueprintNode from './components/BlueprintNode.vue'
|
||||
import NodeCard from './components/NodeCard.vue'
|
||||
import { applyView, toFlow } from './flow'
|
||||
import { highlightFor, rowSelId } from './highlight'
|
||||
import { autoLayout } from './layout'
|
||||
import { buildReach, highlightFor, type Reach } from './reach'
|
||||
import type { GraphResponse, Positions, ProfileItem } from './types'
|
||||
import type { GraphResponse, Positions, Warning } from './types'
|
||||
|
||||
const nodeTypes = { bp: markRaw(BlueprintNode) } as unknown as NodeTypesObject
|
||||
const nodeTypes = { bp: markRaw(BlueprintNode), card: markRaw(NodeCard) } 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[]>
|
||||
@@ -29,8 +28,7 @@ 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 warnings = computed<Warning[]>(() => current.value?.graph.warnings ?? [])
|
||||
const meta = computed(() => current.value?.meta)
|
||||
const metaText = computed(() => {
|
||||
if (!meta.value) return ''
|
||||
@@ -41,9 +39,15 @@ const saveText = computed(
|
||||
() => ({ idle: '', saving: 'сохраняю раскладку…', saved: 'раскладка сохранена', error: 'не удалось сохранить раскладку' })[saveState.value],
|
||||
)
|
||||
|
||||
// клик по строке карточки: подсветить все хосты, которые через неё идут
|
||||
provide('selectRow', (nodeId: string, key: string) => {
|
||||
const id = rowSelId(nodeId, key)
|
||||
selected.value = selected.value === id ? null : id
|
||||
})
|
||||
|
||||
function refreshView() {
|
||||
if (!current.value) return
|
||||
const hl = highlightFor(selected.value, reach.value)
|
||||
const hl = highlightFor(selected.value, current.value.graph)
|
||||
const v = applyView(nodes.value, edges.value, hl, hideShadowed.value)
|
||||
nodes.value = v.nodes
|
||||
edges.value = v.edges
|
||||
@@ -51,29 +55,26 @@ function refreshView() {
|
||||
watch([selected, hideShadowed], refreshView)
|
||||
|
||||
function fit(delay = 80) {
|
||||
nextTick(() => window.setTimeout(() => fitView({ padding: 0.12 }), delay))
|
||||
nextTick(() => window.setTimeout(() => fitView({ padding: 0.1 }), 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
|
||||
const data = await getGraph(opts.force)
|
||||
const existing: Positions = opts.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
|
||||
const known = new Set(flow.nodes.map((n) => n.id))
|
||||
if (selected.value && !selected.value.startsWith('row|') && !known.has(selected.value)) selected.value = null
|
||||
nodes.value = flow.nodes
|
||||
edges.value = flow.edges
|
||||
error.value = null
|
||||
refreshView()
|
||||
if (!keep) fit()
|
||||
if (!opts.keep) fit()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? (e.status === 401 ? 'Нужна авторизация: обнови страницу и введи логин/пароль' : e.message) : String(e)
|
||||
} finally {
|
||||
@@ -81,11 +82,6 @@ async function load(opts: { force?: boolean; keep?: boolean } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function onProfileChange() {
|
||||
selected.value = null
|
||||
await load()
|
||||
}
|
||||
|
||||
function onNodeClick({ node }: NodeMouseEvent) {
|
||||
selected.value = selected.value === node.id ? null : node.id
|
||||
}
|
||||
@@ -101,7 +97,7 @@ function scheduleSave() {
|
||||
)
|
||||
saveState.value = 'saving'
|
||||
try {
|
||||
await savePositions(current.value.profile.uuid, positions)
|
||||
await savePositions(current.value.positionsKey, positions)
|
||||
saveState.value = 'saved'
|
||||
} catch {
|
||||
saveState.value = 'error'
|
||||
@@ -112,7 +108,7 @@ function scheduleSave() {
|
||||
async function resetLayout() {
|
||||
if (!current.value) return
|
||||
try {
|
||||
await resetPositions(current.value.profile.uuid)
|
||||
await resetPositions(current.value.positionsKey)
|
||||
nodes.value = nodes.value.map((n) => ({ ...n, position: autoPos[n.id] ?? n.position }))
|
||||
saveState.value = 'idle'
|
||||
fit()
|
||||
@@ -121,23 +117,10 @@ async function resetLayout() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- предупреждения ---
|
||||
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 }))
|
||||
function focusWarning(w: Warning) {
|
||||
if (!w.target) return
|
||||
selected.value = w.target
|
||||
nextTick(() => fitView({ nodes: [w.target as string], padding: 0.5, maxZoom: 1, duration: 300 }))
|
||||
}
|
||||
|
||||
// --- автообновление ---
|
||||
@@ -151,24 +134,13 @@ onBeforeUnmount(() => {
|
||||
window.clearTimeout(saveTimer)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
profiles.value = await getProfiles()
|
||||
} catch (e) {
|
||||
error.value = e instanceof ApiError ? e.message : String(e)
|
||||
return
|
||||
}
|
||||
await load()
|
||||
})
|
||||
onMounted(() => 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>
|
||||
@@ -209,16 +181,16 @@ onMounted(async () => {
|
||||
<button @click="showWarnings = false">×</button>
|
||||
</div>
|
||||
<ul>
|
||||
<li v-for="w in warnings" :key="w" :class="{ link: warningTarget(w) }" @click="focusWarning(w)">{{ w }}</li>
|
||||
<li v-for="w in warnings" :key="w.text" :class="{ link: w.target }" @click="focusWarning(w)">{{ w.text }}</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>
|
||||
<span><i class="l host" /> хост → строка правила</span>
|
||||
<span><i class="l target" /> правило → outbound/балансер</span>
|
||||
<span><i class="l link" /> outbound → инбаунд ноды-приёмника</span>
|
||||
<span><i class="l dead" /> мёртвое: нода не работает</span>
|
||||
<span class="hint">клик по хосту, ноде, блоку или строке подсвечивает путь, по пустому месту сбрасывает</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+6
-14
@@ -1,4 +1,4 @@
|
||||
import type { GraphResponse, Positions, ProfileItem } from './types'
|
||||
import type { GraphResponse, Positions } from './types'
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, public status: number) {
|
||||
@@ -26,22 +26,14 @@ async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
return r.status === 204 ? (undefined as T) : r.json()
|
||||
}
|
||||
|
||||
export const getProfiles = () =>
|
||||
request<{ profiles: ProfileItem[] }>('/api/profiles').then((d) => d.profiles)
|
||||
export const getGraph = (refresh = false) =>
|
||||
request<GraphResponse>(`/api/graph${refresh ? '?refresh=1' : ''}`)
|
||||
|
||||
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}`, {
|
||||
export const savePositions = (key: string, positions: Positions) =>
|
||||
request<{ saved: number }>(`/api/positions/${key}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ positions }),
|
||||
})
|
||||
|
||||
export const resetPositions = (uuid: string) =>
|
||||
request<void>(`/api/positions/${uuid}`, { method: 'DELETE' })
|
||||
export const resetPositions = (key: string) => request<void>(`/api/positions/${key}`, { method: 'DELETE' })
|
||||
|
||||
@@ -1,45 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
import { Handle, Position } from '@vue-flow/core'
|
||||
import { computed } from 'vue'
|
||||
import { bpHandles } from '../handles'
|
||||
|
||||
// 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 handles = computed(() => bpHandles(kind.value, d.value))
|
||||
const KIND: Record<string, string> = { host: 'HOST', balancer: 'BALANCER', outbound: 'OUTBOUND' }
|
||||
const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
const tone = computed(() => (/^BLOCK/.test(d.value.label) ? 'red' : d.value.protocol === 'freedom' ? 'green' : 'blue'))
|
||||
</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="bp" :class="[`k-${kind}`, { off: d.disabled }]">
|
||||
<Handle
|
||||
v-for="h in handles"
|
||||
:id="h.id"
|
||||
:key="h.id"
|
||||
:type="h.type"
|
||||
:position="h.type === 'target' ? Position.Left : Position.Right"
|
||||
/>
|
||||
<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'">
|
||||
<span class="title" :title="d.label">{{ d.label }}</span>
|
||||
<span v-if="kind === 'outbound'" class="pill" :class="d.alive ? 'st-online' : 'st-offline'">
|
||||
{{ d.alive ? 'up' : 'down' }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -49,83 +35,52 @@ const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
<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.inboundTag" class="pill teal">{{ d.inboundTag }}</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>
|
||||
<div class="row"><span class="k">живых</span>{{ d.aliveMembers?.length ?? 0 }} / {{ d.members?.length ?? 0 }}</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="row">адрес не найден ни в одной карточке ноды</div>
|
||||
<div class="row">
|
||||
<span class="pill" :class="tone">{{ d.protocol }}</span>
|
||||
<template v-if="d.address">{{ d.address }}<template v-if="d.port">:{{ d.port }}</template></template>
|
||||
<template v-else-if="d.owner"><span class="k">выход</span>{{ list(d.exit) }}</template>
|
||||
</div>
|
||||
<div v-if="d.destName" class="row"><span class="k">→ нода</span>{{ d.destName }}</div>
|
||||
<div class="row" :title="(d.users ?? []).join(', ')">
|
||||
<span class="k">используют</span><span class="users">{{ list(d.users) }}</span>
|
||||
</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); }
|
||||
.bp { width: 250px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px; font-size: 12px;
|
||||
color: #d6deeb; box-shadow: 0 4px 14px rgb(0 0 0 / 35%); }
|
||||
.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; }
|
||||
.users { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px; }
|
||||
.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,112 @@
|
||||
<script setup lang="ts">
|
||||
import { Handle, Position } from '@vue-flow/core'
|
||||
import { computed, inject } from 'vue'
|
||||
import { H } from '../handles'
|
||||
import type { Row, Section } from '../types'
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const props = defineProps<{ id: string; data: Record<string, any> }>()
|
||||
const d = computed(() => props.data)
|
||||
const selectRow = inject<(nodeId: string, key: string) => void>('selectRow', () => {})
|
||||
|
||||
const hl = computed(() => d.value.hl as { active: string[]; pass: string[] } | null)
|
||||
const active = computed(() => new Set(hl.value?.active ?? []))
|
||||
const pass = computed(() => new Set(hl.value?.pass ?? []))
|
||||
const state = (key: string) => (!hl.value ? '' : active.value.has(key) ? 'r-active' : pass.value.has(key) ? 'r-pass' : 'r-dim')
|
||||
|
||||
const sections = computed(() => (d.value.sections ?? []) as Section[])
|
||||
const rows = (s: Section) => (d.value.hideShadowed ? s.rows.filter((r) => !r.shadowed) : s.rows)
|
||||
const tone = (r: Row) =>
|
||||
r.targetKind === 'balancer' ? 'violet' : r.target === 'BLOCK' ? 'red' : r.target === 'DIRECT' ? 'green' : 'blue'
|
||||
// пометка «общее» нужна, только если в секции есть и правила конкретного инбаунда
|
||||
const mixed = (s: Section) => s.rows.some((r) => !r.common)
|
||||
const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="card" :class="{ off: d.state === 'disabled' }">
|
||||
<div class="hd">
|
||||
<Handle :id="H.head" type="target" :position="Position.Left" />
|
||||
<span class="kind">NODE</span>
|
||||
<span class="name" :title="d.label">{{ d.label }}</span>
|
||||
<span class="pill" :class="`st-${d.state}`">{{ d.state }}</span>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div class="line">
|
||||
<span v-if="d.profile" class="pill violet" title="профиль ноды">{{ d.profile.name }}</span>
|
||||
<span v-else class="pill gray">нет профиля</span>
|
||||
<span v-if="d.country" class="pill gray">{{ d.country }}</span>
|
||||
<span v-if="d.netbird" class="pill teal">NetBird</span>
|
||||
</div>
|
||||
<div class="line dim">мост {{ list(d.mgmt) }} · выход {{ list(d.exit) }}</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!sections.length" class="empty">нет активных инбаундов</div>
|
||||
<div v-for="s in sections" :key="s.uuid" class="sec">
|
||||
<div class="inb" :class="state(`inb:${s.uuid}`)" @click.stop="selectRow(id, `inb:${s.uuid}`)">
|
||||
<Handle :id="H.inb(s.uuid)" type="target" :position="Position.Left" />
|
||||
<span class="tag">{{ s.tag }}</span>
|
||||
<span class="proto">{{ s.protocol }}<template v-if="s.port"> :{{ s.port }}</template></span>
|
||||
</div>
|
||||
<div
|
||||
v-for="r in rows(s)"
|
||||
:key="r.key"
|
||||
class="row"
|
||||
:class="[state(`${s.uuid}:${r.key}`), { shadowed: r.shadowed, dflt: r.default }]"
|
||||
@click.stop="selectRow(id, `${s.uuid}:${r.key}`)"
|
||||
>
|
||||
<Handle :id="H.rin(s.uuid, r.key)" type="target" :position="Position.Left" />
|
||||
<span class="idx">{{ r.default ? '↳' : `#${r.index}` }}</span>
|
||||
<span class="cond" :title="r.label">{{ r.label }}</span>
|
||||
<span v-if="r.common && !r.default && mixed(s)" class="common" title="общее правило профиля (без inboundTag)">общее</span>
|
||||
<span v-if="r.shadowed" class="pill red" title="выше есть catch-all, правило не сработает">недостижимо</span>
|
||||
<span v-else class="pill" :class="tone(r)">{{ r.target }}</span>
|
||||
<Handle v-if="r.hasEdge" :id="H.rout(s.uuid, r.key)" type="source" :position="Position.Right" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.card { width: 340px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px; font-size: 12px;
|
||||
color: #d6deeb; box-shadow: 0 4px 14px rgb(0 0 0 / 35%); padding-bottom: 8px; }
|
||||
.hd { position: relative; height: 34px; display: flex; align-items: center; gap: 8px; padding: 0 10px;
|
||||
background: #5a4320; border-radius: 7px 7px 0 0; }
|
||||
.kind { font-size: 9px; letter-spacing: .08em; opacity: .75; font-weight: 600; }
|
||||
.name { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.meta { height: 42px; padding: 5px 10px 0; display: flex; flex-direction: column; gap: 4px; }
|
||||
.line { display: flex; gap: 6px; align-items: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.line.dim { color: #7f8ba3; font-size: 11px; }
|
||||
.empty { height: 28px; padding: 4px 10px; color: #7f8ba3; }
|
||||
.sec { margin-top: 10px; }
|
||||
.sec:first-of-type { margin-top: 0; }
|
||||
.inb { position: relative; height: 30px; display: flex; align-items: center; gap: 8px; padding: 0 10px;
|
||||
background: #14504f; cursor: pointer; }
|
||||
.tag { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.proto { color: #9fd9d3; font-size: 11px; }
|
||||
.row { position: relative; height: 27px; display: flex; align-items: center; gap: 7px; padding: 0 10px;
|
||||
border-bottom: 1px solid #262f45; cursor: pointer; }
|
||||
.row:hover, .inb:hover { filter: brightness(1.15); }
|
||||
.idx { color: #7f8ba3; min-width: 26px; font-variant-numeric: tabular-nums; }
|
||||
.cond { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #c3cde0; }
|
||||
.common { font-size: 9.5px; color: #7f8ba3; border: 1px solid #323d55; border-radius: 8px; padding: 0 5px; }
|
||||
.dflt .cond { color: #7f8ba3; font-style: italic; }
|
||||
.shadowed { background: #2a1c24; }
|
||||
.shadowed .cond { text-decoration: line-through; color: #8a6a74; }
|
||||
.r-active { background: #1e3a66; }
|
||||
.r-pass { opacity: .5; }
|
||||
.r-dim { opacity: .25; }
|
||||
.inb.r-active { background: #1b7a76; }
|
||||
.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; }
|
||||
.off { opacity: .65; }
|
||||
</style>
|
||||
+20
-33
@@ -1,59 +1,46 @@
|
||||
import type { Edge, Node } from '@vue-flow/core'
|
||||
import type { Highlight } from './reach'
|
||||
import type { Highlight } from './highlight'
|
||||
import type { Graph, Positions } from './types'
|
||||
|
||||
const LABELLED = new Set(['link', 'route', 'fallback'])
|
||||
const LABELLED = new Set(['host', 'link', 'fallback', 'member'])
|
||||
|
||||
/** Граф бэкенда -> узлы и рёбра 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 nodes: Node[] = graph.nodes.map((n) => ({
|
||||
id: n.id,
|
||||
type: n.type === 'node' ? 'card' : 'bp',
|
||||
position: positions[n.id] ?? auto[n.id] ?? { x: 0, y: 0 },
|
||||
data: { ...n.data, kind: n.type, label: n.label },
|
||||
}))
|
||||
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',
|
||||
sourceHandle: e.sourceHandle,
|
||||
targetHandle: e.targetHandle,
|
||||
label: LABELLED.has(e.kind) ? e.label ?? undefined : undefined,
|
||||
data: { kind: e.kind, dead: !!e.data.dead },
|
||||
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 data = { ...n.data, hideShadowed }
|
||||
if (n.type === 'card') {
|
||||
const r = hl?.rows.get(n.id)
|
||||
data.hl = hl ? { active: [...(r?.active ?? [])], pass: [...(r?.pass ?? [])] } : null
|
||||
}
|
||||
const cls = hl ? (hl.nodes.has(n.id) ? 'active' : 'dim') : ''
|
||||
return { ...n, data, class: cls }
|
||||
})
|
||||
|
||||
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 { ...e, animated: lit, class: cls.join(' ') }
|
||||
})
|
||||
return { nodes: outNodes, edges: outEdges }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Section } from './types'
|
||||
|
||||
/** Идентификаторы портов. Бэкенд пишет их в рёбра, карточки рисуют по тем же правилам. */
|
||||
export const H = {
|
||||
head: 'head',
|
||||
inb: (uuid: string) => `inb:${uuid}`,
|
||||
rin: (uuid: string, key: string) => `rin:${uuid}:${key}`,
|
||||
rout: (uuid: string, key: string) => `rout:${uuid}:${key}`,
|
||||
}
|
||||
|
||||
export interface HandleDef {
|
||||
id: string
|
||||
type: 'source' | 'target'
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function cardHandles(data: Record<string, any>): HandleDef[] {
|
||||
const out: HandleDef[] = [{ id: H.head, type: 'target' }]
|
||||
for (const s of (data.sections ?? []) as Section[]) {
|
||||
out.push({ id: H.inb(s.uuid), type: 'target' })
|
||||
for (const r of s.rows) {
|
||||
out.push({ id: H.rin(s.uuid, r.key), type: 'target' })
|
||||
if (r.hasEdge) out.push({ id: H.rout(s.uuid, r.key), type: 'source' })
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function bpHandles(kind: string, data: Record<string, any>): HandleDef[] {
|
||||
if (kind === 'host') return [{ id: 'out', type: 'source' }]
|
||||
if (kind === 'balancer') return [{ id: 'in', type: 'target' }, { id: 'out', type: 'source' }]
|
||||
return [{ id: 'in', type: 'target' }, ...(data.destName ? [{ id: 'out', type: 'source' as const }] : [])]
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Graph } from './types'
|
||||
|
||||
export interface Highlight {
|
||||
hostIds: string[]
|
||||
nodes: Set<string>
|
||||
edges: Set<string>
|
||||
/** по картам нод: активные и "проверенные, но не подошедшие" строки */
|
||||
rows: Map<string, { active: Set<string>; pass: Set<string> }>
|
||||
}
|
||||
|
||||
export const rowSelId = (nodeId: string, key: string) => `row|${nodeId}|${key}`
|
||||
|
||||
/** Выбранный хост, строка, блок или нода -> объединённый путь всех хостов, которые через них идут. */
|
||||
export function highlightFor(selected: string | null, g: Graph): Highlight | null {
|
||||
if (!selected) return null
|
||||
const hosts = Object.keys(g.paths)
|
||||
let ids: string[]
|
||||
const nodes = new Set<string>()
|
||||
if (selected.startsWith('host:')) {
|
||||
ids = [selected]
|
||||
} else if (selected.startsWith('row|')) {
|
||||
const [, nodeId, key] = selected.split('|')
|
||||
ids = hosts.filter((h) => g.paths[h].rows[nodeId]?.active.includes(key))
|
||||
nodes.add(nodeId)
|
||||
} else {
|
||||
ids = hosts.filter((h) => g.paths[h].nodes.includes(selected))
|
||||
nodes.add(selected)
|
||||
}
|
||||
|
||||
const edges = new Set<string>()
|
||||
const rows = new Map<string, { active: Set<string>; pass: Set<string> }>()
|
||||
for (const h of ids) {
|
||||
const p = g.paths[h]
|
||||
p.nodes.forEach((n) => nodes.add(n))
|
||||
p.edges.forEach((e) => edges.add(e))
|
||||
for (const [nodeId, r] of Object.entries(p.rows)) {
|
||||
const cur = rows.get(nodeId) ?? { active: new Set<string>(), pass: new Set<string>() }
|
||||
r.active.forEach((k) => cur.active.add(k))
|
||||
r.pass.forEach((k) => cur.pass.add(k))
|
||||
rows.set(nodeId, cur)
|
||||
}
|
||||
}
|
||||
for (const r of rows.values()) r.active.forEach((k) => r.pass.delete(k)) // активная для одного хоста не "проходная"
|
||||
return { hostIds: ids, nodes, edges, rows }
|
||||
}
|
||||
+89
-41
@@ -1,53 +1,101 @@
|
||||
import type { GNode, Graph, NodeKind, Positions } from './types'
|
||||
import type { GNode, Graph, Positions, Section } 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 const WIDTH: Record<string, number> = { host: 250, node: 340, balancer: 250, outbound: 250 }
|
||||
const GAP_X = 150
|
||||
const GAP_Y = 26
|
||||
// размеры частей карточки ноды (CSS держит их фиксированными)
|
||||
const HEAD = 76, INB = 30, ROW = 27, SEC_GAP = 10, PAD = 8
|
||||
|
||||
/** Раскладка колонками: правила по порядку, остальное выравнивается по связанным узлам. */
|
||||
const sections = (n: GNode) => (n.data.sections ?? []) as Section[]
|
||||
|
||||
export function heightOf(n: GNode): number {
|
||||
if (n.type === 'host') return 96
|
||||
if (n.type === 'balancer') return 104
|
||||
if (n.type === 'outbound') return 112
|
||||
const secs = sections(n)
|
||||
const body = secs.length ? secs.reduce((a, s) => a + INB + s.rows.length * ROW + SEC_GAP, 0) : 28
|
||||
return HEAD + body + PAD
|
||||
}
|
||||
|
||||
/** Вертикальный центр порта внутри карточки (для выравнивания связанных блоков). */
|
||||
export function handleCenter(n: GNode, handle: string): number {
|
||||
if (n.type !== 'node') return heightOf(n) / 2
|
||||
if (handle === 'head') return HEAD / 2
|
||||
let y = HEAD
|
||||
for (const s of sections(n)) {
|
||||
if (handle === `inb:${s.uuid}`) return y + INB / 2
|
||||
const i = s.rows.findIndex((r) => handle === `rin:${s.uuid}:${r.key}` || handle === `rout:${s.uuid}:${r.key}`)
|
||||
if (i >= 0) return y + INB + i * ROW + ROW / 2
|
||||
y += INB + s.rows.length * ROW + SEC_GAP
|
||||
}
|
||||
return heightOf(n) / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Колонки по длиннейшему пути от хостов: хост -> нода -> балансер/outbound -> нода-приёмник...
|
||||
* Внутри колонки блоки выравниваются по связанным портам.
|
||||
*/
|
||||
export function autoLayout(g: Graph): Positions {
|
||||
const y = new Map<string, number>()
|
||||
const pos: Positions = {}
|
||||
const byId = new Map(g.nodes.map((n) => [n.id, n]))
|
||||
const layer = new Map(g.nodes.map((n) => [n.id, 0]))
|
||||
for (let i = 0; i < 40; i++) {
|
||||
let changed = false
|
||||
for (const e of g.edges) {
|
||||
const l = (layer.get(e.source) ?? 0) + 1
|
||||
if (l > (layer.get(e.target) ?? 0)) {
|
||||
layer.set(e.target, l)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (!changed) break
|
||||
}
|
||||
|
||||
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)
|
||||
const layers = [...new Set(layer.values())].sort((a, b) => a - b)
|
||||
const colX = new Map<number, number>()
|
||||
let x = 0
|
||||
for (const L of layers) {
|
||||
colX.set(L, x)
|
||||
x += Math.max(...g.nodes.filter((n) => layer.get(n.id) === L).map((n) => WIDTH[n.type])) + GAP_X
|
||||
}
|
||||
|
||||
const top = new Map<string, number>()
|
||||
const mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0)
|
||||
|
||||
const place = (items: GNode[], desiredCenter: (n: GNode) => number) => {
|
||||
const sorted = items
|
||||
.map((n) => ({ n, c: desiredCenter(n) }))
|
||||
.sort((a, b) => a.c - b.c || a.n.label.localeCompare(b.n.label))
|
||||
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
|
||||
for (const { n, c } of sorted) {
|
||||
const t = Math.max(c - heightOf(n) / 2, cursor)
|
||||
top.set(n.id, t)
|
||||
cursor = t + heightOf(n) + GAP_Y
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
for (const L of layers) {
|
||||
place(
|
||||
g.nodes.filter((n) => layer.get(n.id) === L && n.type !== 'host'),
|
||||
(n) =>
|
||||
mean(
|
||||
g.edges
|
||||
.filter((e) => e.target === n.id && top.has(e.source))
|
||||
.map((e) => top.get(e.source)! + handleCenter(byId.get(e.source)!, e.sourceHandle)),
|
||||
),
|
||||
)
|
||||
}
|
||||
const sourcesOf = (id: string, kinds: string[]) =>
|
||||
g.edges.filter((e) => e.target === id && kinds.includes(e.kind)).map((e) => e.source)
|
||||
// хосты в последнюю очередь: напротив строки, на которой садится их нитка
|
||||
place(
|
||||
g.nodes.filter((n) => n.type === 'host'),
|
||||
(n) =>
|
||||
mean(
|
||||
g.edges
|
||||
.filter((e) => e.source === n.id && top.has(e.target))
|
||||
.map((e) => top.get(e.target)! + handleCenter(byId.get(e.target)!, e.targetHandle)),
|
||||
),
|
||||
)
|
||||
|
||||
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)))
|
||||
const pos: Positions = {}
|
||||
for (const n of g.nodes) pos[n.id] = { x: colX.get(layer.get(n.id) ?? 0) ?? 0, y: top.get(n.id) ?? 0 }
|
||||
return pos
|
||||
}
|
||||
|
||||
+4
-10
@@ -35,7 +35,7 @@ button:disabled, select:disabled { opacity: .5; cursor: default; }
|
||||
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.host { 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; }
|
||||
@@ -47,17 +47,11 @@ button:disabled, select:disabled { opacity: .5; cursor: default; }
|
||||
.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__node.active .card, .vue-flow__node.active .bp { border-color: #6ea8ff; box-shadow: 0 0 0 1px #6ea8ff, 0 4px 18px rgb(80 140 255 / 30%); }
|
||||
.vue-flow__node.selected .card, .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-host .vue-flow__edge-path { stroke: #60a5fa; stroke-dasharray: 6 4; }
|
||||
.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; }
|
||||
|
||||
+40
-13
@@ -1,5 +1,5 @@
|
||||
export type NodeKind = 'host' | 'inbound' | 'rule' | 'balancer' | 'outbound' | 'node' | 'unresolved'
|
||||
export type EdgeKind = 'flow' | 'route' | 'fallthrough' | 'target' | 'member' | 'fallback' | 'link'
|
||||
export type NodeKind = 'host' | 'node' | 'balancer' | 'outbound'
|
||||
export type EdgeKind = 'host' | 'target' | 'member' | 'fallback' | 'link'
|
||||
|
||||
export interface GNode {
|
||||
id: string
|
||||
@@ -12,16 +12,51 @@ export interface GNode {
|
||||
export interface GEdge {
|
||||
id: string
|
||||
source: string
|
||||
sourceHandle: string
|
||||
target: string
|
||||
targetHandle: string
|
||||
kind: EdgeKind
|
||||
label: string | null
|
||||
data: { dead?: boolean }
|
||||
data: { dead: boolean }
|
||||
}
|
||||
|
||||
export interface Row {
|
||||
key: string
|
||||
index: number | null
|
||||
label: string
|
||||
common: boolean
|
||||
shadowed: boolean
|
||||
default: boolean
|
||||
vlessRoute: number[]
|
||||
targetKind: 'outbound' | 'balancer'
|
||||
target: string
|
||||
hasEdge: boolean
|
||||
}
|
||||
|
||||
export interface Section {
|
||||
uuid: string
|
||||
tag: string
|
||||
port: number | null
|
||||
protocol: string | null
|
||||
rows: Row[]
|
||||
}
|
||||
|
||||
export interface PathInfo {
|
||||
nodes: string[]
|
||||
edges: string[]
|
||||
rows: Record<string, { active: string[]; pass: string[] }>
|
||||
}
|
||||
|
||||
export interface Warning {
|
||||
text: string
|
||||
target: string | null
|
||||
}
|
||||
|
||||
export interface Graph {
|
||||
nodes: GNode[]
|
||||
edges: GEdge[]
|
||||
warnings: string[]
|
||||
warnings: Warning[]
|
||||
paths: Record<string, PathInfo>
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
@@ -35,16 +70,8 @@ export interface Meta {
|
||||
export type Positions = Record<string, { x: number; y: number }>
|
||||
|
||||
export interface GraphResponse {
|
||||
profile: { uuid: string; name: string }
|
||||
graph: Graph
|
||||
positionsKey: string
|
||||
positions: Positions
|
||||
meta: Meta
|
||||
}
|
||||
|
||||
export interface ProfileItem {
|
||||
uuid: string
|
||||
name: string
|
||||
inbounds: number
|
||||
rules: number
|
||||
nodes: string[]
|
||||
}
|
||||
|
||||
Vendored
+1
-1235
File diff suppressed because one or more lines are too long
@@ -1,105 +1,125 @@
|
||||
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 { bpHandles, cardHandles } from '../src/handles'
|
||||
import { highlightFor, rowSelId } from '../src/highlight'
|
||||
import { autoLayout, heightOf, WIDTH } from '../src/layout'
|
||||
import type { Graph } from '../src/types'
|
||||
import raw from './fixtures/graph.json'
|
||||
|
||||
const graph = raw as unknown as Graph
|
||||
const RU = 'node:n-ru'
|
||||
const FI = 'node:n-2'
|
||||
|
||||
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 }])
|
||||
describe('handles: карточки рисуют ровно те порты, к которым привязаны рёбра', () => {
|
||||
const nodes = new Map(graph.nodes.map((n) => [n.id, n]))
|
||||
const portsOf = (id: string) => {
|
||||
const n = nodes.get(id)!
|
||||
const defs = n.type === 'node' ? cardHandles(n.data) : bpHandles(n.type, n.data)
|
||||
return { source: new Set(defs.filter((h) => h.type === 'source').map((h) => h.id)), target: new Set(defs.filter((h) => h.type === 'target').map((h) => h.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('у каждого ребра есть исходящий и входящий порт', () => {
|
||||
for (const e of graph.edges) {
|
||||
expect(portsOf(e.source).source.has(e.sourceHandle), `${e.id} (source)`).toBe(true)
|
||||
expect(portsOf(e.target).target.has(e.targetHandle), `${e.id} (target)`).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
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)
|
||||
describe('autoLayout', () => {
|
||||
const pos = autoLayout(graph)
|
||||
const nodes = new Map(graph.nodes.map((n) => [n.id, n]))
|
||||
|
||||
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('даёт позицию каждому блоку', () => {
|
||||
for (const n of graph.nodes) expect(pos[n.id], n.id).toBeDefined()
|
||||
})
|
||||
|
||||
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('блоки одной колонки не перекрываются', () => {
|
||||
const cols = new Map<number, string[]>()
|
||||
for (const n of graph.nodes) cols.set(pos[n.id].x, [...(cols.get(pos[n.id].x) ?? []), n.id])
|
||||
for (const ids of cols.values()) {
|
||||
const sorted = ids.sort((a, b) => pos[a].y - pos[b].y)
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
const prev = nodes.get(sorted[i - 1])!
|
||||
expect(pos[sorted[i]].y, `${sorted[i - 1]} / ${sorted[i]}`).toBeGreaterThanOrEqual(pos[sorted[i - 1]].y + heightOf(prev))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('хост другого профиля отсутствует', () => {
|
||||
expect(reach.has('host:hx')).toBe(false)
|
||||
it('поток идёт слева направо: источник каждого ребра левее приёмника', () => {
|
||||
for (const e of graph.edges) {
|
||||
expect(pos[e.source].x + WIDTH[nodes.get(e.source)!.type], e.id).toBeLessThan(pos[e.target].x)
|
||||
}
|
||||
})
|
||||
|
||||
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('хост стоит напротив строки, на которую садится его нитка', () => {
|
||||
const h3 = graph.edges.find((e) => e.source === 'host:h3')!
|
||||
const hostY = pos['host:h3'].y + heightOf(nodes.get('host:h3')!) / 2
|
||||
const ruY = pos[RU].y
|
||||
expect(h3.targetHandle).toBe('rin:inb-bridge:8')
|
||||
// правило #8 лежит ниже шапки карточки; хост не должен висеть выше карточки
|
||||
expect(hostY).toBeGreaterThan(ruY)
|
||||
})
|
||||
})
|
||||
|
||||
describe('highlight', () => {
|
||||
it('хост: путь через обе ноды, проверенные строки приглушены', () => {
|
||||
const hl = highlightFor('host:h3', graph)!
|
||||
expect(hl.hostIds).toEqual(['host:h3'])
|
||||
expect(hl.nodes.has(RU) && hl.nodes.has(FI)).toBe(true)
|
||||
const ru = hl.rows.get(RU)!
|
||||
expect(ru.active.has('inb-bridge:8')).toBe(true)
|
||||
expect([...ru.pass].sort()).toEqual(['inb-bridge:6', 'inb-bridge:7'])
|
||||
expect(hl.rows.get(FI)!.active.has('inb:inb-def-ss')).toBe(true)
|
||||
})
|
||||
|
||||
it('клик по недостижимому правилу не подсвечивает ни одного хоста', () => {
|
||||
expect(highlightFor('rule:14', reach)!.hostIds).toEqual([])
|
||||
it('строка: подсвечиваются только хосты, которых она касается', () => {
|
||||
expect(highlightFor(rowSelId(RU, 'inb-bridge:8'), graph)!.hostIds).toEqual(['host:h3'])
|
||||
expect(highlightFor(rowSelId(RU, 'inb-bridge:13'), graph)!.hostIds.sort()).toEqual(['host:h8', 'host:hn'])
|
||||
})
|
||||
|
||||
it('клик по DIRECT подсвечивает все хосты профиля', () => {
|
||||
expect(highlightFor('out:DIRECT', reach)!.hostIds).toHaveLength(4)
|
||||
it('нода-приёмник: и мост, и прямое подключение', () => {
|
||||
const ids = highlightFor(FI, graph)!.hostIds
|
||||
expect(ids).toContain('host:hd')
|
||||
expect(ids).toContain('host:h3')
|
||||
expect(ids).toContain('host:h7') // через балансер
|
||||
expect(ids).not.toContain('host:nonexistent')
|
||||
})
|
||||
|
||||
it('недостижимая строка не подсвечивает хостов', () => {
|
||||
expect(highlightFor(rowSelId(RU, 'inb-bridge:14'), graph)!.hostIds).toEqual([])
|
||||
})
|
||||
|
||||
it('без выбора подсветки нет', () => {
|
||||
expect(highlightFor(null, graph)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
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('нода рисуется карточкой, остальное простыми блоками', () => {
|
||||
expect(flow.nodes.filter((n) => n.type === 'card')).toHaveLength(graph.nodes.filter((n) => n.type === 'node').length)
|
||||
expect(flow.nodes.find((n) => n.id === 'host:h3')!.type).toBe('bp')
|
||||
})
|
||||
|
||||
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 })
|
||||
const f = toFlow(graph, { [RU]: { x: 1, y: 2 } }, autoLayout(graph))
|
||||
expect(f.nodes.find((n) => n.id === RU)!.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))
|
||||
it('подсветка: остальное приглушается, карточки получают строки, позиции не меняются', () => {
|
||||
const hl = highlightFor('host:h3', 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.find((n) => n.id === 'host:h3')!.class).toBe('active')
|
||||
expect(v.nodes.find((n) => n.id === 'host:h7')!.class).toBe('dim')
|
||||
expect(v.nodes.find((n) => n.id === RU)!.data.hl.active).toContain('inb-bridge:8')
|
||||
expect(v.edges.filter((e) => e.animated).length).toBe(hl!.edges.size)
|
||||
expect(v.nodes.map((n) => n.position)).toEqual(flow.nodes.map((n) => n.position))
|
||||
})
|
||||
|
||||
it('hideShadowed и пустая подсветка пробрасываются в карточки', () => {
|
||||
const v = applyView(flow.nodes, flow.edges, null, true)
|
||||
expect(v.nodes.find((n) => n.id === RU)!.data.hideShadowed).toBe(true)
|
||||
expect(v.nodes.find((n) => n.id === RU)!.data.hl).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user