init commit

This commit is contained in:
Udo
2026-12-01 10:02:27 +05:00
commit 200083e3ef
36 changed files with 5611 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
node_modules
dist
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Remnawave · карта маршрутов</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+2289
View File
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "rw-viz-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "vue-tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@vue-flow/background": "^1.3.2",
"@vue-flow/controls": "^1.1.3",
"@vue-flow/core": "^1.48.2",
"@vue-flow/minimap": "^1.5.4",
"vue": "^3.5.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"@vitejs/plugin-vue": "^6.0.0",
"typescript": "~5.9.3",
"vite": "^7.0.0",
"vitest": "^3.2.0",
"vue-tsc": "^3.0.0"
}
}
+225
View File
@@ -0,0 +1,225 @@
<script setup lang="ts">
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import { useVueFlow, VueFlow, type Edge, type Node, type NodeMouseEvent, type NodeTypesObject } from '@vue-flow/core'
import { MiniMap } from '@vue-flow/minimap'
import { computed, markRaw, nextTick, onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
import { ApiError, getGraph, getProfiles, resetPositions, savePositions } from './api'
import BlueprintNode from './components/BlueprintNode.vue'
import { applyView, toFlow } from './flow'
import { autoLayout } from './layout'
import { buildReach, highlightFor, type Reach } from './reach'
import type { GraphResponse, Positions, ProfileItem } from './types'
const nodeTypes = { bp: markRaw(BlueprintNode) } as unknown as NodeTypesObject
const profiles = ref<ProfileItem[]>([])
const profileKey = ref('')
const current = ref<GraphResponse | null>(null)
const nodes = ref([]) as Ref<Node[]>
const edges = ref([]) as Ref<Edge[]>
const selected = ref<string | null>(null)
const hideShadowed = ref(false)
const autoRefresh = ref(false)
const showWarnings = ref(false)
const loading = ref(false)
const error = ref<string | null>(null)
const saveState = ref<'idle' | 'saving' | 'saved' | 'error'>('idle')
let autoPos: Positions = {}
const { fitView, getNodes } = useVueFlow()
const reach = computed<Map<string, Reach>>(() => (current.value ? buildReach(current.value.graph) : new Map()))
const warnings = computed(() => current.value?.graph.warnings ?? [])
const meta = computed(() => current.value?.meta)
const metaText = computed(() => {
if (!meta.value) return ''
const t = new Date(meta.value.fetchedAt).toLocaleTimeString('ru-RU')
return `снимок панели ${t}` + (meta.value.cached ? ` · кэш ${Math.round(meta.value.ageSeconds)} с` : '')
})
const saveText = computed(
() => ({ idle: '', saving: 'сохраняю раскладку…', saved: 'раскладка сохранена', error: 'не удалось сохранить раскладку' })[saveState.value],
)
function refreshView() {
if (!current.value) return
const hl = highlightFor(selected.value, reach.value)
const v = applyView(nodes.value, edges.value, hl, hideShadowed.value)
nodes.value = v.nodes
edges.value = v.edges
}
watch([selected, hideShadowed], refreshView)
function fit(delay = 80) {
nextTick(() => window.setTimeout(() => fitView({ padding: 0.12 }), delay))
}
async function load(opts: { force?: boolean; keep?: boolean } = {}) {
loading.value = true
try {
const data = await getGraph(profileKey.value || undefined, opts.force)
const switched = data.profile.uuid !== current.value?.profile.uuid
const keep = !!opts.keep && !switched
const existing: Positions = keep
? Object.fromEntries(getNodes.value.map((n) => [n.id, { x: n.position.x, y: n.position.y }]))
: {}
current.value = data
profileKey.value = data.profile.uuid
autoPos = autoLayout(data.graph)
const flow = toFlow(data.graph, { ...data.positions, ...existing }, autoPos)
if (selected.value && !flow.nodes.some((n) => n.id === selected.value)) selected.value = null
nodes.value = flow.nodes
edges.value = flow.edges
error.value = null
refreshView()
if (!keep) fit()
} catch (e) {
error.value = e instanceof ApiError ? (e.status === 401 ? 'Нужна авторизация: обнови страницу и введи логин/пароль' : e.message) : String(e)
} finally {
loading.value = false
}
}
async function onProfileChange() {
selected.value = null
await load()
}
function onNodeClick({ node }: NodeMouseEvent) {
selected.value = selected.value === node.id ? null : node.id
}
// --- сохранение раскладки ---
let saveTimer: number | undefined
function scheduleSave() {
window.clearTimeout(saveTimer)
saveTimer = window.setTimeout(async () => {
if (!current.value) return
const positions: Positions = Object.fromEntries(
getNodes.value.map((n) => [n.id, { x: Math.round(n.position.x), y: Math.round(n.position.y) }]),
)
saveState.value = 'saving'
try {
await savePositions(current.value.profile.uuid, positions)
saveState.value = 'saved'
} catch {
saveState.value = 'error'
}
}, 600)
}
async function resetLayout() {
if (!current.value) return
try {
await resetPositions(current.value.profile.uuid)
nodes.value = nodes.value.map((n) => ({ ...n, position: autoPos[n.id] ?? n.position }))
saveState.value = 'idle'
fit()
} catch (e) {
error.value = e instanceof ApiError ? e.message : String(e)
}
}
// --- предупреждения ---
function warningTarget(w: string): string | null {
let m = w.match(/^rule #(\d+)/)
if (m) return `rule:${m[1]}`
m = w.match(/^outbound (\S+)/)
if (m) return `out:${m[1]}`
m = w.match(/^balancer (\S+):/)
if (m) return `bal:${m[1]}`
m = w.match(/^хост (.+?): /)
if (m) return current.value?.graph.nodes.find((n) => n.type === 'host' && n.label === m![1])?.id ?? null
return null
}
function focusWarning(w: string) {
const id = warningTarget(w)
if (!id) return
selected.value = id
nextTick(() => fitView({ nodes: [id], padding: 0.6, maxZoom: 1, duration: 300 }))
}
// --- автообновление ---
let timer: number | undefined
watch(autoRefresh, (on) => {
window.clearInterval(timer)
if (on) timer = window.setInterval(() => load({ keep: true }), 30_000)
})
onBeforeUnmount(() => {
window.clearInterval(timer)
window.clearTimeout(saveTimer)
})
onMounted(async () => {
try {
profiles.value = await getProfiles()
} catch (e) {
error.value = e instanceof ApiError ? e.message : String(e)
return
}
await load()
})
</script>
<template>
<div class="app">
<header class="bar">
<h1>Remnawave · маршруты</h1>
<select v-model="profileKey" :disabled="loading || profiles.length < 2" @change="onProfileChange">
<option v-for="p in profiles" :key="p.uuid" :value="p.uuid">{{ p.name }} ({{ p.rules }} правил)</option>
</select>
<button :disabled="loading" @click="load({ force: true, keep: true })">Обновить</button>
<button :disabled="!current" @click="resetLayout">Сбросить раскладку</button>
<button :disabled="!current" @click="fit(0)">Вписать</button>
<label><input v-model="hideShadowed" type="checkbox" /> скрыть недостижимые правила</label>
<label><input v-model="autoRefresh" type="checkbox" /> автообновление 30 с</label>
<span class="spacer" />
<span class="meta">{{ saveText }}</span>
<span class="meta">{{ metaText }}</span>
<button v-if="warnings.length" class="warn-btn" @click="showWarnings = !showWarnings">⚠ {{ warnings.length }}</button>
</header>
<div v-if="error" class="banner err">{{ error }}</div>
<div v-else-if="meta?.stale" class="banner stale">
Панель недоступна, показан старый снимок ({{ Math.round(meta.ageSeconds) }} с): {{ meta.lastError }}
</div>
<div class="canvas">
<VueFlow
v-model:nodes="nodes"
v-model:edges="edges"
:node-types="nodeTypes"
:min-zoom="0.08"
:max-zoom="1.8"
:nodes-connectable="false"
:elevate-edges-on-select="false"
@node-click="onNodeClick"
@pane-click="selected = null"
@node-drag-stop="scheduleSave"
>
<Background pattern-color="#2a3347" :gap="24" />
<MiniMap pannable zoomable />
<Controls :show-interactive="false" />
</VueFlow>
<aside v-if="showWarnings && warnings.length" class="warnings">
<div class="wh">
<b>Предупреждения</b>
<button @click="showWarnings = false">×</button>
</div>
<ul>
<li v-for="w in warnings" :key="w" :class="{ link: warningTarget(w) }" @click="focusWarning(w)">{{ w }}</li>
</ul>
</aside>
<div class="legend">
<span><i class="l route" /> маршрут хоста (vlessRoute)</span>
<span><i class="l target" /> правило → выход</span>
<span><i class="l link" /> мост → нода</span>
<span><i class="l dead" /> мёртвое ребро: правило недостижимо или нода не работает</span>
<span class="hint">клик по узлу подсвечивает путь, по пустому месту сбрасывает</span>
</div>
</div>
</div>
</template>
+47
View File
@@ -0,0 +1,47 @@
import type { GraphResponse, Positions, ProfileItem } from './types'
export class ApiError extends Error {
constructor(message: string, public status: number) {
super(message)
}
}
async function request<T>(url: string, init?: RequestInit): Promise<T> {
let r: Response
try {
r = await fetch(url, { credentials: 'same-origin', ...init })
} catch {
throw new ApiError('Нет связи с бэкендом', 0)
}
if (!r.ok) {
let msg = `HTTP ${r.status}`
try {
const body = await r.json()
if (body?.message) msg = body.message
} catch {
/* тело не JSON */
}
throw new ApiError(msg, r.status)
}
return r.status === 204 ? (undefined as T) : r.json()
}
export const getProfiles = () =>
request<{ profiles: ProfileItem[] }>('/api/profiles').then((d) => d.profiles)
export function getGraph(profile?: string, refresh = false) {
const q = new URLSearchParams()
if (profile) q.set('profile', profile)
if (refresh) q.set('refresh', '1')
return request<GraphResponse>(`/api/graph?${q}`)
}
export const savePositions = (uuid: string, positions: Positions) =>
request<{ saved: number }>(`/api/positions/${uuid}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ positions }),
})
export const resetPositions = (uuid: string) =>
request<void>(`/api/positions/${uuid}`, { method: 'DELETE' })
+131
View File
@@ -0,0 +1,131 @@
<script setup lang="ts">
import { Handle, Position } from '@vue-flow/core'
import { computed } from 'vue'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const props = defineProps<{ id: string; data: Record<string, any> }>()
const d = computed(() => props.data)
const KIND: Record<string, string> = {
host: 'HOST', inbound: 'INBOUND', rule: 'RULE', balancer: 'BALANCER',
outbound: 'OUTBOUND', node: 'NODE', unresolved: '???',
}
const kind = computed<string>(() => d.value.kind)
const hasIn = computed(() => kind.value !== 'host')
const hasOut = computed(() => !['node', 'unresolved'].includes(kind.value))
const title = computed(() => (kind.value === 'rule' ? `#${d.value.index}` : d.value.label))
const cond = computed(() => String(d.value.label ?? '').replace(/^#\d+\s*/, ''))
function tone(name?: string, targetKind?: string) {
if (targetKind === 'balancer') return 'violet'
if (name === 'BLOCK') return 'red'
if (name === 'DIRECT') return 'green'
return 'blue'
}
const list = (v?: string[]) => (v && v.length ? v.join(', ') : '—')
</script>
<template>
<div class="bp" :class="[`k-${kind}`, { off: d.disabled || d.state === 'disabled' }]">
<Handle v-if="hasIn" id="in" type="target" :position="Position.Left" />
<Handle v-if="hasOut" id="out" type="source" :position="Position.Right" />
<template v-if="kind === 'rule'">
<Handle id="prev" type="target" :position="Position.Top" />
<Handle id="next" type="source" :position="Position.Bottom" />
</template>
<div class="hd">
<span class="kind">{{ KIND[kind] }}</span>
<span class="title" :title="String(title)">{{ title }}</span>
<span v-if="kind === 'node'" class="pill" :class="`st-${d.state}`">{{ d.state }}</span>
<span v-if="kind === 'outbound' && d.ip" class="pill" :class="d.alive ? 'st-online' : 'st-offline'">
{{ d.alive ? 'up' : 'down' }}
</span>
</div>
<div class="bd">
<template v-if="kind === 'host'">
<div class="row"><span class="k">адрес</span>{{ d.address }}<template v-if="d.port">:{{ d.port }}</template></div>
<div class="row">
<span class="pill blue">{{ d.vlessRouteId != null ? `route ${d.vlessRouteId}` : 'без route' }}</span>
<span v-if="d.disabled" class="pill st-disabled">disabled</span>
<span v-if="d.exitAlive === false" class="pill st-offline">выход не работает</span>
</div>
</template>
<template v-else-if="kind === 'inbound'">
<div class="row">{{ d.protocol }}<template v-if="d.port"> :{{ d.port }}</template></div>
</template>
<template v-else-if="kind === 'rule'">
<div class="cond" :title="cond">{{ cond }}</div>
<div class="row">
<span class="arrow">→</span>
<span class="pill" :class="tone(d.target, d.targetKind)">{{ d.target }}</span>
<span v-if="d.shadowed" class="pill st-offline" title="выше есть catch-all, правило не сработает">недостижимо</span>
</div>
</template>
<template v-else-if="kind === 'balancer'">
<div class="row"><span class="k">стратегия</span>{{ d.strategy ?? '—' }}</div>
<div class="row">
<span class="k">живых</span>{{ d.aliveMembers?.length ?? 0 }} / {{ d.members?.length ?? 0 }}
</div>
</template>
<template v-else-if="kind === 'outbound'">
<div class="row">{{ d.protocol }}<template v-if="d.ip"> · {{ d.ip }}</template></div>
</template>
<template v-else-if="kind === 'node'">
<div class="row">
<span v-if="d.country" class="pill gray">{{ d.country }}</span>
<span v-if="d.netbird" class="pill teal">NetBird</span>
</div>
<div class="row"><span class="k">мост</span>{{ list(d.mgmt) }}</div>
<div class="row"><span class="k">выход</span>{{ list(d.exit) }}</div>
<div v-if="d.inbound?.length" class="row"><span class="k">вход</span>{{ list(d.inbound) }}</div>
<div v-if="d.reserve?.length" class="row"><span class="k">резерв</span>{{ d.reserve.length }}</div>
</template>
<template v-else>
<div class="row">адрес не найден ни в одной карточке ноды</div>
</template>
</div>
</div>
</template>
<style scoped>
.bp { width: 250px; background: #1b2130; border: 1px solid #323d55; border-radius: 8px;
box-shadow: 0 4px 14px rgb(0 0 0 / 35%); font-size: 12px; color: #d6deeb; overflow: visible; }
.hd { display: flex; align-items: center; gap: 8px; padding: 6px 10px; border-radius: 7px 7px 0 0;
background: var(--hd, #2a3550); }
.kind { font-size: 9px; letter-spacing: .08em; opacity: .75; font-weight: 600; }
.title { font-weight: 600; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bd { padding: 7px 10px 9px; display: flex; flex-direction: column; gap: 5px; }
.row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; line-height: 1.35; }
.k { color: #7f8ba3; min-width: 52px; }
.cond { color: #aab6cc; display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical;
overflow: hidden; word-break: break-word; }
.arrow { color: #7f8ba3; }
.pill { padding: 1px 7px; border-radius: 10px; font-size: 10.5px; background: #2b3550; color: #cdd7ea; white-space: nowrap; }
.pill.blue { background: #1e3a66; color: #9cc4ff; }
.pill.green { background: #17402f; color: #7ee2b0; }
.pill.red { background: #4a1f26; color: #ff9aa5; }
.pill.violet { background: #392a63; color: #c8b3ff; }
.pill.teal { background: #14403f; color: #6fe0d6; }
.pill.gray { background: #2b3243; color: #aab6cc; }
.st-online { background: #17402f; color: #7ee2b0; }
.st-offline { background: #4a1f26; color: #ff9aa5; }
.st-disabled { background: #343a48; color: #9aa6bd; }
.st-connecting { background: #4a3a14; color: #ffd27a; }
.k-host { --hd: #1f3b66; }
.k-inbound { --hd: #14504f; }
.k-rule { --hd: #3b2f66; }
.k-balancer { --hd: #5a2f66; }
.k-outbound { --hd: #2d4a2f; }
.k-node { --hd: #5a4320; }
.k-unresolved { --hd: #6b2431; }
.off { opacity: .6; }
</style>
+59
View File
@@ -0,0 +1,59 @@
import type { Edge, Node } from '@vue-flow/core'
import type { Highlight } from './reach'
import type { Graph, Positions } from './types'
const LABELLED = new Set(['link', 'route', 'fallback'])
/** Граф бэкенда -> узлы и рёбра Vue Flow (без подсветки). */
export function toFlow(graph: Graph, positions: Positions, auto: Positions): { nodes: Node[]; edges: Edge[] } {
const targetOf = new Map(graph.edges.filter((e) => e.kind === 'target').map((e) => [e.source, e.target]))
const nodes: Node[] = graph.nodes.map((n) => {
const data: Record<string, unknown> = { ...n.data, kind: n.type, label: n.label }
if (n.type === 'rule') {
const t = targetOf.get(n.id)
if (t) {
data.target = t.replace(/^(out|bal):/, '')
data.targetKind = t.startsWith('bal:') ? 'balancer' : 'outbound'
}
}
return { id: n.id, type: 'bp', position: positions[n.id] ?? auto[n.id] ?? { x: 0, y: 0 }, data }
})
const edges: Edge[] = graph.edges.map((e) => ({
id: e.id,
source: e.source,
target: e.target,
sourceHandle: e.kind === 'fallthrough' ? 'next' : 'out',
targetHandle: e.kind === 'fallthrough' ? 'prev' : 'in',
label: LABELLED.has(e.kind) ? e.label ?? undefined : undefined,
data: { kind: e.kind, dead: !!e.data.dead },
}))
return { nodes, edges }
}
/** Классы подсветки и скрытие. Позиции не трогает. */
export function applyView(nodes: Node[], edges: Edge[], hl: Highlight | null, hideShadowed: boolean) {
const hidden = new Set(nodes.filter((n) => hideShadowed && n.data.shadowed).map((n) => n.id))
const outNodes = nodes.map((n) => {
const cls: string[] = []
if (n.data.shadowed) cls.push('shadowed')
if (hl) cls.push(hl.active.has(n.id) ? 'active' : hl.pass.has(n.id) ? 'pass' : 'dim')
return { ...n, hidden: hidden.has(n.id), class: cls.join(' ') }
})
const outEdges = edges.map((e) => {
const cls = [`kind-${e.data.kind}`]
if (e.data.dead) cls.push('dead')
const lit = !!hl?.edges.has(e.id)
if (hl) cls.push(lit ? 'active' : 'dim')
return {
...e,
hidden: hidden.has(e.source) || hidden.has(e.target),
animated: lit,
class: cls.join(' '),
}
})
return { nodes: outNodes, edges: outEdges }
}
+53
View File
@@ -0,0 +1,53 @@
import type { GNode, Graph, NodeKind, Positions } from './types'
export const COL_X: Record<NodeKind, number> = {
host: 0,
inbound: 330,
rule: 660,
balancer: 1040,
outbound: 1380,
node: 1720,
unresolved: 1720,
}
export const NODE_HEIGHT: Record<NodeKind, number> = {
host: 90, inbound: 76, rule: 84, balancer: 104, outbound: 80, node: 150, unresolved: 64,
}
const GAP = 24
/** Раскладка колонками: правила по порядку, остальное выравнивается по связанным узлам. */
export function autoLayout(g: Graph): Positions {
const y = new Map<string, number>()
const pos: Positions = {}
const place = (kinds: NodeKind[], desired: (n: GNode) => number) => {
const items = g.nodes
.filter((n) => kinds.includes(n.type))
.map((n) => ({ n, d: desired(n) }))
.sort((a, b) => a.d - b.d)
let cursor = -Infinity
for (const { n, d } of items) {
const yy = Math.max(d, cursor)
y.set(n.id, yy)
pos[n.id] = { x: COL_X[n.type], y: yy }
cursor = yy + NODE_HEIGHT[n.type] + GAP
}
}
const mean = (ids: string[]) => {
const ys = ids.map((i) => y.get(i)).filter((v): v is number => v !== undefined)
return ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : 0
}
const sourcesOf = (id: string, kinds: string[]) =>
g.edges.filter((e) => e.target === id && kinds.includes(e.kind)).map((e) => e.source)
place(['rule'], (n) => (n.data.index ?? 0) * (NODE_HEIGHT.rule + GAP))
place(['balancer'], (n) => mean(sourcesOf(n.id, ['target'])))
place(['outbound'], (n) => mean(sourcesOf(n.id, ['target', 'member', 'fallback'])))
place(['node', 'unresolved'], (n) => mean(sourcesOf(n.id, ['link'])))
place(['host'], (n) => {
const last = (n.data.trace as string[] | undefined)?.at(-1)
return (last ? y.get(last) ?? 0 : 0) + (n.data.vlessRouteId ?? 99) * 0.001
})
place(['inbound'], (n) => mean(g.edges.filter((e) => e.target === n.id).map((e) => e.source)))
return pos
}
+9
View File
@@ -0,0 +1,9 @@
import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import '@vue-flow/controls/dist/style.css'
import '@vue-flow/minimap/dist/style.css'
import { createApp } from 'vue'
import App from './App.vue'
import './styles.css'
createApp(App).mount('#app')
+82
View File
@@ -0,0 +1,82 @@
import type { Graph } from './types'
export interface Reach {
nodes: Set<string>
edges: Set<string>
/** Правила, которые трафик хоста проверяет, но не применяет (не подошёл vlessRoute) */
pass: Set<string>
}
const ruleIndex = (id: string) => Number(id.split(':')[1])
/** Для каждого хоста: какие узлы и рёбра лежат на его пути до выходной ноды. */
export function buildReach(g: Graph): Map<string, Reach> {
const from = new Map<string, Graph['edges']>()
for (const e of g.edges) from.set(e.source, [...(from.get(e.source) ?? []), e])
const out = (id: string, ...kinds: string[]) => (from.get(id) ?? []).filter((e) => kinds.includes(e.kind))
const result = new Map<string, Reach>()
for (const host of g.nodes.filter((n) => n.type === 'host')) {
const r: Reach = { nodes: new Set([host.id]), edges: new Set(), pass: new Set() }
const take = (e: Graph['edges'][number]) => {
r.edges.add(e.id)
r.nodes.add(e.target)
}
for (const e of out(host.id, 'flow')) {
take(e) // host -> inbound
for (const e2 of out(e.target, 'flow')) r.edges.add(e2.id) // inbound -> rule:0
}
for (const e of out(host.id, 'route')) take(e)
const trace = (host.data.trace ?? []) as string[]
if (trace.length) {
const last = ruleIndex(trace[trace.length - 1])
for (let i = 0; i <= last; i++) {
const id = `rule:${i}`
r.nodes.add(id)
if (!trace.includes(id)) r.pass.add(id)
if (i < last) for (const e of out(id, 'fallthrough')) r.edges.add(e.id)
}
// цели всех применимых правил: условные (BLOCK/DIRECT) и итоговое
for (const id of trace) {
for (const e of out(id, 'target')) {
take(e)
for (const m of out(e.target, 'member')) take(m) // балансер: любой из членов
}
}
for (const id of [...r.nodes]) for (const e of out(id, 'link')) take(e)
}
result.set(host.id, r)
}
return result
}
export interface Highlight {
hostIds: string[]
active: Set<string>
pass: Set<string>
edges: Set<string>
}
/** Объединённый путь всех хостов, чей маршрут проходит через выбранный узел. */
export function highlightFor(selected: string | null, reach: Map<string, Reach>): Highlight | null {
if (!selected) return null
const hostIds = selected.startsWith('host:')
? [selected]
: [...reach.entries()]
.filter(([, r]) => r.nodes.has(selected) && !r.pass.has(selected))
.map(([id]) => id)
const active = new Set<string>([selected])
const pass = new Set<string>()
const edges = new Set<string>()
for (const id of hostIds) {
const r = reach.get(id)
if (!r) continue
for (const n of r.nodes) if (!r.pass.has(n)) active.add(n)
r.pass.forEach((p) => pass.add(p))
r.edges.forEach((e) => edges.add(e))
}
active.forEach((n) => pass.delete(n)) // активный для одного хоста не "проходной" из-за другого
return { hostIds, active, pass, edges }
}
+75
View File
@@ -0,0 +1,75 @@
:root { color-scheme: dark; }
* { box-sizing: border-box; }
html, body, #app { height: 100%; margin: 0; }
body { background: #0f1420; color: #d6deeb;
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
.app { position: relative; height: 100%; }
.bar { position: absolute; z-index: 20; inset: 0 0 auto 0; height: 52px; display: flex; align-items: center; gap: 10px;
padding: 0 14px; background: #151b2b; border-bottom: 1px solid #263149; }
.bar h1 { font-size: 15px; margin: 0 6px 0 0; font-weight: 600; white-space: nowrap; }
.bar label { display: flex; align-items: center; gap: 5px; color: #aab6cc; white-space: nowrap; }
.spacer { flex: 1; }
.meta { color: #7f8ba3; font-size: 12px; white-space: nowrap; }
button, select { background: #202a40; color: #d6deeb; border: 1px solid #33405c; border-radius: 6px;
padding: 5px 10px; font: inherit; cursor: pointer; }
button:hover:not(:disabled) { background: #2a3654; }
button:disabled, select:disabled { opacity: .5; cursor: default; }
.warn-btn { color: #ffd27a; border-color: #5a4a22; }
.banner { position: absolute; z-index: 15; top: 60px; left: 50%; transform: translateX(-50%); padding: 7px 14px;
border-radius: 6px; max-width: 80%; }
.banner.err { background: #4a1f26; color: #ffb3bc; border: 1px solid #7a2f3a; }
.banner.stale { background: #4a3a14; color: #ffd27a; border: 1px solid #7a6020; }
.canvas { position: absolute; inset: 52px 0 0 0; }
.warnings { position: absolute; z-index: 15; top: 12px; right: 12px; width: 420px; max-height: 60%; overflow: auto;
background: #151b2b; border: 1px solid #33405c; border-radius: 8px; padding: 10px 12px; box-shadow: 0 8px 24px rgb(0 0 0 / 45%); }
.warnings .wh { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.warnings ul { margin: 0; padding-left: 16px; display: flex; flex-direction: column; gap: 5px; color: #ffd27a; }
.warnings li.link { cursor: pointer; }
.warnings li.link:hover { color: #fff1c9; }
.legend { position: absolute; z-index: 10; left: 62px; bottom: 14px; display: flex; flex-wrap: wrap; gap: 4px 16px;
max-width: 60%; padding: 6px 10px; background: #151b2bd9; border: 1px solid #263149; border-radius: 6px;
color: #aab6cc; font-size: 11.5px; }
.legend .l { display: inline-block; width: 22px; height: 0; border-top: 2px solid; vertical-align: middle; margin-right: 4px; }
.legend .l.route { border-color: #60a5fa; border-top-style: dashed; }
.legend .l.target { border-color: #a78bfa; }
.legend .l.link { border-color: #34d399; }
.legend .l.dead { border-color: #ef4444; border-top-style: dashed; }
.legend .hint { color: #7f8ba3; }
/* --- Vue Flow --- */
.vue-flow { background: #0f1420; }
.vue-flow__handle { width: 10px; height: 10px; border-radius: 50%; background: #8b9bb4; border: 2px solid #0f1420; }
.vue-flow__handle-top, .vue-flow__handle-bottom { width: 9px; height: 9px; background: #5b6a86; }
.vue-flow__node { transition: opacity .15s; }
.vue-flow__node.dim { opacity: .2; }
.vue-flow__node.pass { opacity: .5; }
.vue-flow__node.active .bp { border-color: #6ea8ff; box-shadow: 0 0 0 1px #6ea8ff, 0 4px 18px rgb(80 140 255 / 35%); }
.vue-flow__node.shadowed .bp { border-style: dashed; border-color: #8a3a46; }
.vue-flow__node.shadowed { opacity: .8; }
.vue-flow__node.shadowed.dim { opacity: .15; }
.vue-flow__node.selected .bp { border-color: #6ea8ff; }
.vue-flow__edge-path { stroke: #4b5568; stroke-width: 1.6; transition: opacity .15s; }
.vue-flow__edge.kind-flow .vue-flow__edge-path { stroke: #94a3b8; }
.vue-flow__edge.kind-route .vue-flow__edge-path { stroke: #60a5fa; stroke-dasharray: 6 4; }
.vue-flow__edge.kind-fallthrough .vue-flow__edge-path { stroke: #4b5568; stroke-width: 1.2; }
.vue-flow__edge.kind-target .vue-flow__edge-path { stroke: #a78bfa; }
.vue-flow__edge.kind-member .vue-flow__edge-path { stroke: #c084fc; }
.vue-flow__edge.kind-fallback .vue-flow__edge-path { stroke: #f59e0b; stroke-dasharray: 4 4; }
.vue-flow__edge.kind-link .vue-flow__edge-path { stroke: #34d399; stroke-width: 2.2; }
.vue-flow__edge.dead .vue-flow__edge-path { stroke: #ef4444; stroke-dasharray: 5 4; }
.vue-flow__edge.dim .vue-flow__edge-path { opacity: .08; }
.vue-flow__edge.active .vue-flow__edge-path { stroke-width: 3; }
.vue-flow__edge-text { font-size: 10px; fill: #aab6cc; }
.vue-flow__edge-textbg { fill: #0f1420; }
.vue-flow__edge.dim .vue-flow__edge-text, .vue-flow__edge.dim .vue-flow__edge-textbg { opacity: .1; }
.vue-flow__controls { box-shadow: none; border: 1px solid #263149; }
.vue-flow__controls-button { background: #202a40; border-bottom: 1px solid #263149; fill: #d6deeb; }
.vue-flow__controls-button:hover { background: #2a3654; }
.vue-flow__minimap { background: #151b2b; border: 1px solid #263149; }
+50
View File
@@ -0,0 +1,50 @@
export type NodeKind = 'host' | 'inbound' | 'rule' | 'balancer' | 'outbound' | 'node' | 'unresolved'
export type EdgeKind = 'flow' | 'route' | 'fallthrough' | 'target' | 'member' | 'fallback' | 'link'
export interface GNode {
id: string
type: NodeKind
label: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data: Record<string, any>
}
export interface GEdge {
id: string
source: string
target: string
kind: EdgeKind
label: string | null
data: { dead?: boolean }
}
export interface Graph {
nodes: GNode[]
edges: GEdge[]
warnings: string[]
}
export interface Meta {
cached: boolean
stale: boolean
ageSeconds: number
fetchedAt: string
lastError?: string
}
export type Positions = Record<string, { x: number; y: number }>
export interface GraphResponse {
profile: { uuid: string; name: string }
graph: Graph
positions: Positions
meta: Meta
}
export interface ProfileItem {
uuid: string
name: string
inbounds: number
rules: number
nodes: string[]
}
+1235
View File
File diff suppressed because it is too large Load Diff
+105
View File
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest'
import { applyView, toFlow } from '../src/flow'
import { autoLayout, COL_X, NODE_HEIGHT } from '../src/layout'
import { buildReach, highlightFor } from '../src/reach'
import type { Graph } from '../src/types'
import raw from './fixtures/graph.json'
const graph = raw as unknown as Graph
describe('autoLayout', () => {
const pos = autoLayout(graph)
it('даёт позицию каждому узлу', () => {
for (const n of graph.nodes) expect(pos[n.id], n.id).toBeDefined()
})
it('узлы одной колонки не перекрываются', () => {
const byCol = new Map<number, { y: number; h: number; id: string }[]>()
for (const n of graph.nodes) {
const x = COL_X[n.type]
byCol.set(x, [...(byCol.get(x) ?? []), { y: pos[n.id].y, h: NODE_HEIGHT[n.type], id: n.id }])
}
for (const items of byCol.values()) {
items.sort((a, b) => a.y - b.y)
for (let i = 1; i < items.length; i++) {
expect(items[i].y, `${items[i - 1].id} / ${items[i].id}`).toBeGreaterThanOrEqual(items[i - 1].y + items[i - 1].h)
}
}
})
it('правила идут сверху вниз по порядку', () => {
const ys = graph.nodes.filter((n) => n.type === 'rule').sort((a, b) => a.data.index - b.data.index).map((n) => pos[n.id].y)
expect([...ys].sort((a, b) => a - b)).toEqual(ys)
})
})
describe('reach / highlight', () => {
const reach = buildReach(graph)
it('хост с route 3 доходит до BRIDGE_3 и FI-01, пропуская правила 6 и 7', () => {
const r = reach.get('host:h3')!
expect(r.nodes.has('out:BRIDGE_3')).toBe(true)
expect(r.nodes.has('node:FI-01')).toBe(true)
expect(r.nodes.has('out:BRIDGE_4')).toBe(false)
expect([...r.pass].sort()).toEqual(['rule:6', 'rule:7'])
expect(r.nodes.has('rule:8')).toBe(true)
expect(r.pass.has('rule:8')).toBe(false)
})
it('хост с route 8 упирается в catch-all и никогда не видит SoundCloud-правила', () => {
const r = reach.get('host:h8')!
expect(r.nodes.has('rule:13')).toBe(true)
expect(r.nodes.has('rule:14')).toBe(false)
expect(r.nodes.has('bal:BRIDGE_AUTO')).toBe(true)
})
it('хост другого профиля отсутствует', () => {
expect(reach.has('host:hx')).toBe(false)
})
it('клик по ноде подсвечивает хосты, которые на неё выходят', () => {
const hl = highlightFor('node:FI-01', reach)!
expect(hl.hostIds.sort()).toEqual(['host:h3', 'host:h7', 'host:h8', 'host:hn'])
expect(hl.active.has('node:FI-01')).toBe(true)
})
it('клик по недостижимому правилу не подсвечивает ни одного хоста', () => {
expect(highlightFor('rule:14', reach)!.hostIds).toEqual([])
})
it('клик по DIRECT подсвечивает все хосты профиля', () => {
expect(highlightFor('out:DIRECT', reach)!.hostIds).toHaveLength(4)
})
})
describe('toFlow / applyView', () => {
const flow = toFlow(graph, {}, autoLayout(graph))
it('правило знает свою цель, цепочка идёт через нижний/верхний порт', () => {
expect(flow.nodes.find((n) => n.id === 'rule:8')!.data.target).toBe('BRIDGE_3')
expect(flow.nodes.find((n) => n.id === 'rule:13')!.data.targetKind).toBe('balancer')
const ft = flow.edges.find((e) => e.id.includes('fallthrough'))!
expect([ft.sourceHandle, ft.targetHandle]).toEqual(['next', 'prev'])
})
it('сохранённая позиция важнее автоматической', () => {
const f = toFlow(graph, { 'rule:0': { x: 1, y: 2 } }, autoLayout(graph))
expect(f.nodes.find((n) => n.id === 'rule:0')!.position).toEqual({ x: 1, y: 2 })
})
it('hideShadowed скрывает недостижимые правила и их рёбра', () => {
const v = applyView(flow.nodes, flow.edges, null, true)
expect(v.nodes.filter((n) => n.hidden).length).toBe(8)
expect(v.edges.filter((e) => e.hidden).length).toBeGreaterThan(8)
})
it('подсветка: остальное приглушается, позиции не меняются', () => {
const hl = highlightFor('host:h3', buildReach(graph))
const v = applyView(flow.nodes, flow.edges, hl, false)
expect(v.nodes.find((n) => n.id === 'host:h3')!.class).toContain('active')
expect(v.nodes.find((n) => n.id === 'host:h7')!.class).toContain('dim')
expect(v.nodes.find((n) => n.id === 'rule:6')!.class).toContain('pass')
expect(v.nodes.map((n) => n.position)).toEqual(flow.nodes.map((n) => n.position))
})
})
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "preserve",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"skipLibCheck": true,
"isolatedModules": true,
"resolveJsonModule": true,
"types": ["vite/client", "node"]
},
"include": ["src/**/*.ts", "src/**/*.vue", "tests/**/*.ts", "vite.config.ts"]
}
+11
View File
@@ -0,0 +1,11 @@
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vitest/config'
// В dev /api проксируется на бэкенд (Basic-auth браузер спросит сам).
const target = process.env.VITE_API_TARGET ?? 'http://127.0.0.1:8080'
export default defineConfig({
plugins: [vue()],
server: { port: 5173, proxy: { '/api': { target, changeOrigin: false } } },
test: { environment: 'node' },
})