Added network graph

This commit is contained in:
Sam Latsin 2026-10-29 20:52:06 +03:00
parent bb6391844e
commit c2fda5d015
10 changed files with 1422 additions and 10 deletions

View File

@ -113,6 +113,28 @@ Connect, и сессия освобождается за секунды — мо
На `whitelist` OpenVPN идёт через группу `OVPN-EXIT` — один раз выбрать в дашборде RU-ноду.
### Граф
LuCI → **Службы → mihomo-kit → Граф** — собранный профиль картинкой, слева направо:
правила (сверху вниз — в порядке, в котором mihomo их проверяет) → группы → подписки и
свои серверы → через что они подключаются (`dialer-proxy`, фиолетовый пунктир). Зелёный
пунктир — через что качается подписка (`proxy:` провайдера, обычно `BOOT-AUTO`) и
`<имя>-my`, читающий файл основной подписки. На рёбрах группа → подписка — фильтры
(`∋` filter, `∌` exclude-filter). Правило в `DIRECT`/`REJECT` заканчивается на самом
правиле.
Для запущенного профиля поверх схемы — живое состояние из API mihomo (раз в 3 секунды,
пока вкладка открыта): что выбрано в каждой группе сейчас (синее) с задержкой, сколько нод
подписки живы, и куда идут соединения (оранжевое, с числом на узлах) — по `chains`
соединения и дальше по цепочке `dialer-proxy`. Наведи или нажми на узел — подсветится всё,
что в него приходит и что из него выходит, снизу — подробности и «путь сейчас». «Только
выбранное» прячет невыбранные пункты групп. Другие профили (`whitelist`, `foreign`) — из
списка, без живого состояния. Страница только показывает; правки — на «Управлении».
Без роутера: [tools/graph.html](tools/graph.html) из репозитория открыть в браузере и выбрать
или перетащить любой конфиг mihomo. Для живого состояния — адрес API и secret (они в ссылке
«открыть дашборд»).
### OpenVPN под видом OpenVPN Connect
Для сервера BMSTU роутер выглядит как OpenVPN Connect 3.7.1 (5558) на macOS. Обычный

View File

@ -3,7 +3,7 @@
"description": "mihomo-kit: profiles, OpenVPN, Tailscale, CSQTT",
"read": {
"ubus": {
"mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "csqtt_status", "job", "update_check", "ts_check" ]
"mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "csqtt_status", "job", "update_check", "ts_check", "graph", "api" ]
}
},
"write": {

1041
luci/graph.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -3,11 +3,26 @@
"title": "mihomo-kit",
"order": 61,
"action": {
"type": "view",
"path": "mihomo-kit"
"type": "firstchild"
},
"depends": {
"acl": [ "luci-app-mihomo-kit" ]
}
},
"admin/services/mihomo-kit/main": {
"title": "Управление",
"order": 1,
"action": {
"type": "view",
"path": "mihomo-kit"
}
},
"admin/services/mihomo-kit/graph": {
"title": "Граф",
"order": 2,
"action": {
"type": "view",
"path": "mihomo-kit-graph"
}
}
}

103
luci/mihomo-kit-graph.js Normal file
View File

@ -0,0 +1,103 @@
'use strict';
'require view';
'require rpc';
'require dom';
// LuCI "Службы → mihomo-kit → Граф": a built profile as a graph (luci/graph.js), with the
// live state of the running mihomo through the rpcd plugin (method api: read-only paths).
var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } });
var callGraph = rpc.declare({ object: 'mihomo-kit', method: 'graph', params: [ 'profile' ], expect: { '': {} } });
var callApi = rpc.declare({ object: 'mihomo-kit', method: 'api', params: [ 'path' ], nobatch: true, expect: { '': {} } });
// the YAML reader of the own servers (luci/servers.js) and the graph: globals mkServers, mkGraph
function loadScript(name, global) {
if (window[global])
return Promise.resolve(window[global]);
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.src = L.resource('mihomo-kit/' + name);
s.onload = function() { resolve(window[global]); };
s.onerror = function() { reject(new Error(name + ' not loaded')); };
document.head.appendChild(s);
});
}
return view.extend({
load: function() {
return Promise.all([ loadScript('servers.js', 'mkServers'), loadScript('graph.js', 'mkGraph'), callGraph(''), callStatus() ]);
},
// /proxies every 10 s, /connections every 3 s; only for the running profile and a visible tab
poll: function() {
var tick = 0;
var loop = L.bind(function() {
if (this.stopped)
return;
if (document.hidden || !this.liveOn)
return void (this.timer = window.setTimeout(loop, 3000));
var want = tick++ % 3 == 0 ? callApi('/proxies') : Promise.resolve(null);
Promise.all([ want, callApi('/connections') ]).then(L.bind(function(r) {
if (r[0] && r[0].error || r[1].error)
throw new Error((r[0] && r[0].error) || r[1].error);
this.graph.live(r[0] && r[0].proxies, r[1].connections || []);
dom.content(this.state, '');
}, this)).catch(L.bind(function(e) {
dom.content(this.state, E('em', 'живое состояние недоступно: ' + (e.message || e)));
}, this)).then(L.bind(function() {
this.timer = window.setTimeout(loop, 3000);
}, this));
}, this);
loop();
},
show: function(g) {
if (g.error) {
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, g.error));
return;
}
try {
this.graph.show(window.mkServers.yamlLoad(g.yaml));
} catch (e) {
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, 'Не разобрал профиль: ' + e.message));
return;
}
this.liveOn = g.active && g.profile == g.running;
dom.content(this.state, this.liveOn ? '' : E('em', g.profile == g.running ? 'nikki остановлен: только схема'
: 'профиль ' + g.profile + ' сейчас не запущен: только схема, без живого состояния'));
},
render: function(data) {
var g = data[2], st = data[3];
this.state = E('div', { 'style': 'margin:.3em 0' });
var box = E('div');
var select = E('select', { 'class': 'cbi-input-select', 'change': L.bind(function(ev) {
return callGraph(ev.target.value).then(L.bind(this.show, this));
}, this) });
(st.profiles || []).forEach(function(p) {
select.appendChild(E('option', { 'value': p }, p + (p == st.profile ? ' (запущен)' : '')));
});
select.value = g.profile || st.profile;
var page = E([], [
E('h2', 'mihomo-kit: граф'),
E('div', { 'class': 'cbi-map-descr' }, 'Как устроен профиль: правила (сверху вниз — в порядке проверки) → группы → ' +
'подписки и серверы → через что они подключаются (dialer-proxy). Наведи или нажми на узел — подсветится всё, ' +
'что через него идёт; колесо — масштаб, перетаскивание — сдвиг. Для запущенного профиля видно, что выбрано ' +
'в группах сейчас и куда идут соединения. Править — на странице «Управление».'),
E('div', { 'style': 'margin:.5em 0' }, [ 'Профиль: ', select ]),
this.state,
box
]);
// once the page is in the document: the graph fits its box and takes the theme's background
window.setTimeout(L.bind(function() {
this.graph = window.mkGraph.view(box);
this.show(g);
this.poll();
}, this), 0);
return page;
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});

View File

@ -15,6 +15,8 @@
# import {data, keep_local}: replace the settings with an export, as the job
# config_get settings for the form (secrets: only whether they are set)
# config_set save the form (via "mihomo-kit.sh configure") as the job
# graph {profile}: the built profile's YAML for the graph page (default: the running one)
# api {path}: GET /proxies, /connections or /providers/proxies of the mihomo API
#
# rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job.
@ -462,6 +464,36 @@ m_config_set() {
start_job mihomo-kit.sh configure "$env"
}
m_graph() {
json_load "$(cat)"
json_get_var want profile ""
prof=$(uci -q get nikki.config.profile)
prof=${prof#file:}
prof=${prof%.yaml}
case "$want" in '' | *[!A-Za-z0-9_-]*) want=$prof ;; esac
[ -f "$NIKKI_DIR/profiles/$want.yaml" ] || reply_error "нет профиля $want (mihomo-kit.sh build)"
json_init
json_add_string running "$prof"
json_add_boolean active "$(b pidof mihomo)"
json_add_string profile "$want"
json_add_string yaml "$(cat "$NIKKI_DIR/profiles/$want.yaml")"
json_dump
}
# the API's answer as it is: only these read-only paths
m_api() {
json_load "$(cat)"
json_get_var path path ""
case "$path" in /proxies | /connections | /providers/proxies) ;; *) reply_error "path not allowed" ;; esac
sec=$(uci -q get nikki.mixin.api_secret)
res=$(curl -fsS -m 10 ${sec:+-H "Authorization: Bearer $sec"} "$(api_url)$path" 2>&1) ||
reply_error "mihomo API: $res"
# connections without their metadata (flat, most of the size): the graph needs the
# rule and chains, and ubus has a limit on the answer
[ "$path" = /connections ] && res=$(printf '%s' "$res" | sed 's/"metadata":{[^}]*},//g')
printf '%s\n' "$res"
}
m_ts_check() {
json_init
delay_check TAILSCALE TS_CHECK_URL http://100.69.216.50:8080
@ -514,7 +546,7 @@ m_job() {
case "$1" in
list)
echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true}}'
echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true},"graph":{"profile":"str"},"api":{"path":"str"}}'
;;
call)
case "$2" in
@ -530,6 +562,8 @@ case "$1" in
ts_check) m_ts_check ;;
export) m_export ;;
import) m_import ;;
graph) m_graph ;;
api) m_api ;;
*) reply_error "unknown method" ;;
esac
;;

View File

@ -1340,8 +1340,8 @@ install_files() {
install_luci
}
# LuCI page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view.
# The view goes to view/mihomo-kit/v<hash>.js and the menu points there: LuCI
# LuCI pages "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, views.
# A view goes to view/mihomo-kit/<v|g><hash>.js and the menu points there: LuCI
# loads views by script with a ?v= of its own version, which neither a kit
# update nor a hard reload changes, so a fixed name stays cached in the browser.
install_luci() {
@ -1364,14 +1364,20 @@ install_luci() {
_rpcd=$_changed
put "$src/qrcode.js" /www/luci-static/resources/mihomo-kit/qrcode.js 644
put "$src/servers.js" /www/luci-static/resources/mihomo-kit/servers.js 644
put "$src/graph.js" /www/luci-static/resources/mihomo-kit/graph.js 644
# pages: "Управление" (mihomo-kit.js -> v<hash>.js) and "Граф" (mihomo-kit-graph.js -> g<hash>.js)
_views=/www/luci-static/resources/view
_v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8)
_g=g$(md5sum < "$src/mihomo-kit-graph.js" | cut -c1-8)
put "$src/mihomo-kit.js" "$_views/mihomo-kit/$_v.js" 644
put "$src/mihomo-kit-graph.js" "$_views/mihomo-kit/$_g.js" 644
for _f in "$_views/mihomo-kit.js" "$_views"/mihomo-kit/*.js; do
[ -f "$_f" ] && [ "$_f" != "$_views/mihomo-kit/$_v.js" ] && rm -f "$_f" && _changed=1
case "$_f" in "$_views/mihomo-kit/$_v.js" | "$_views/mihomo-kit/$_g.js") continue ;; esac
[ -f "$_f" ] && rm -f "$_f" && _changed=1
done
sed "s|\"path\": \"mihomo-kit\"|\"path\": \"mihomo-kit/$_v\"|" "$src/menu.json" > /tmp/mihomo-kit-menu.json
sed -e "s|\"path\": \"mihomo-kit\"|\"path\": \"mihomo-kit/$_v\"|" \
-e "s|\"path\": \"mihomo-kit-graph\"|\"path\": \"mihomo-kit/$_g\"|" "$src/menu.json" > /tmp/mihomo-kit-menu.json
put /tmp/mihomo-kit-menu.json /usr/share/luci/menu.d/luci-app-mihomo-kit.json 644
rm -f /tmp/mihomo-kit-menu.json

124
tools/graph.html Normal file
View File

@ -0,0 +1,124 @@
<!doctype html>
<!-- The config graph (luci/graph.js) without the router: open this file from the repo,
pick or drop any mihomo config. Live state: the router's mihomo API address and secret
(LuCI → mihomo-kit, the dashboard link has both); mihomo allows any origin by default. -->
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mihomo graph</title>
<style>
:root { color-scheme: light dark; --bg: #fff; --fg: #1f2328; --mute: #6b7280; --b: #c9ced6; }
@media (prefers-color-scheme: dark) { :root { --bg: #16181d; --fg: #e6e8eb; --mute: #9aa1ab; --b: #454c57; } }
body { margin: 0; padding: 12px 16px; background: var(--bg); color: var(--fg); font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; }
h1 { font-size: 16px; margin: 0 0 8px; }
.top { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; margin-bottom: 8px; }
.top input[type=text], .top input[type=password] { width: 14em; padding: 3px 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--b); border-radius: 4px; }
button { padding: 3px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--b); border-radius: 4px; cursor: pointer; }
.hint { color: var(--mute); }
#drop { border: 2px dashed var(--b); border-radius: 6px; padding: 24px; text-align: center; color: var(--mute); }
#drop.over { border-color: #4c7cf0; }
textarea { width: 100%; box-sizing: border-box; font: 12px monospace; background: var(--bg); color: var(--fg); border: 1px solid var(--b); border-radius: 4px; }
#err { color: #e03131; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Граф конфига mihomo</h1>
<div class="top">
<input type="file" id="file" accept=".yaml,.yml,.txt">
<button id="paste">Вставить текст</button>
<span class="hint">API:</span>
<input type="text" id="api" placeholder="http://192.168.1.1:9090">
<input type="password" id="secret" placeholder="secret">
<button id="connect">Подключить</button>
<span id="apiState" class="hint"></span>
</div>
<div id="pasteBox" style="display:none;margin-bottom:8px">
<textarea id="text" rows="10" placeholder="proxies: …"></textarea>
<button id="show">Показать</button>
</div>
<div id="drop">Перетащи сюда конфиг mihomo (.yaml) или выбери файл</div>
<div id="err"></div>
<div id="graph"></div>
<script src="../luci/servers.js"></script>
<script src="../luci/graph.js"></script>
<script>
(function() {
var $ = function(id) { return document.getElementById(id); };
var g = null, timer = null;
var store = function(k, v) {
try {
if (v === undefined)
return localStorage.getItem('mkg-' + k) || '';
localStorage.setItem('mkg-' + k, v);
} catch (e) {
return '';
}
};
$('api').value = store('api');
var show = function(text) {
$('err').textContent = '';
try {
var cfg = mkServers.yamlLoad(text);
if (!cfg || typeof cfg != 'object' || !cfg.rules && !cfg['proxy-groups'])
throw new Error('не похоже на конфиг mihomo: нет rules и proxy-groups');
if (!g)
g = mkGraph.view($('graph'));
g.show(cfg);
$('drop').style.display = 'none';
} catch (e) {
$('err').textContent = 'Не разобрал: ' + e.message;
}
};
var read = function(f) {
var r = new FileReader();
r.onload = function() { show(r.result); };
r.readAsText(f);
};
$('file').addEventListener('change', function() { if (this.files[0]) read(this.files[0]); });
$('paste').addEventListener('click', function() {
$('pasteBox').style.display = $('pasteBox').style.display == 'none' ? '' : 'none';
});
$('show').addEventListener('click', function() { show($('text').value); });
var drop = $('drop');
document.addEventListener('dragover', function(e) { e.preventDefault(); drop.classList.add('over'); });
document.addEventListener('dragleave', function() { drop.classList.remove('over'); });
document.addEventListener('drop', function(e) {
e.preventDefault();
drop.classList.remove('over');
if (e.dataTransfer.files[0])
read(e.dataTransfer.files[0]);
});
// live: /proxies every 10 s, /connections every 2 s
var api = function(path) {
var base = $('api').value.trim().replace(/\/+$/, ''), sec = $('secret').value;
return fetch(base + path, { headers: sec ? { Authorization: 'Bearer ' + sec } : {} }).then(function(r) {
if (!r.ok)
throw new Error(path + ': HTTP ' + r.status);
return r.json();
});
};
$('connect').addEventListener('click', function() {
store('api', $('api').value.trim());
if (timer)
clearTimeout(timer);
if (!g)
return ($('apiState').textContent = 'сначала конфиг');
var tick = 0;
var loop = function() {
var want = tick++ % 5 == 0 ? api('/proxies') : Promise.resolve(null);
Promise.all([ want, api('/connections') ]).then(function(r) {
g.live(r[0] && r[0].proxies, r[1].connections || []);
$('apiState').textContent = 'подключено';
}).catch(function(e) {
$('apiState').textContent = 'ошибка: ' + e.message;
}).then(function() { timer = setTimeout(loop, 2000); });
};
loop();
});
})();
</script>
</body>
</html>

65
tools/test-graph.js Normal file
View File

@ -0,0 +1,65 @@
#!/usr/bin/env node
// luci/graph.js on the rendered profiles (tests/expected/*.yaml): every name resolves,
// the layout has no overlaps and runs left to right, and live() follows a connection
// through the groups' choice and the dialer-proxy chain.
const fs = require("fs");
const path = require("path");
const S = require("../luci/servers.js");
const G = require("../luci/graph.js");
let fail = 0;
const check = (name, ok, msg) => {
if (ok)
return;
fail = 1;
console.log("FAIL " + name + ": " + msg);
};
const dir = path.join(__dirname, "..", "tests", "expected");
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) {
const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, f), "utf8"));
const m = G.model(cfg);
check(f, !m.warnings.length, m.warnings.join("; "));
check(f, m.list.filter((n) => n.kind == "rule").length > 0, "no rule nodes");
const lay = G.layout(m);
const cols = {};
for (const n of m.list) {
const b = lay.nodes[n.id];
check(f, b && [b.x, b.y, b.w, b.h].every(Number.isFinite), "no position for " + n.id);
(cols[b.x] = cols[b.x] || []).push(b);
}
for (const x in cols) {
const c = cols[x].sort((a, b) => a.y - b.y);
for (let i = 1; i < c.length; i++)
check(f, c[i].y >= c[i - 1].y + c[i - 1].h - 0.01, "nodes overlap in column x=" + x);
}
for (const le of lay.edges)
if (le.pts)
for (let i = 1; i < le.pts.length; i++)
check(f, le.pts[i].x > le.pts[i - 1].x, "edge runs right to left: " + le.e.from + " -> " + le.e.to);
if (!fail)
console.log("ok graph " + f + " (" + m.list.length + " nodes, " + lay.ranks + " columns)");
}
// live: a connection by MATCH through MAIN -> FOREIGN -> a node of "example", which dials
// through UPLINK -> CSQTT (router-csqtt: subscription nodes with dialer-proxy UPLINK)
{
const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, "router-csqtt.yaml"), "utf8"));
const m = G.model(cfg);
const proxies = {
MAIN: { now: "FOREIGN" }, FOREIGN: { now: "nl-1" }, UPLINK: { now: "CSQTT" },
"nl-1": { "provider-name": "example", alive: true, history: [{ delay: 42 }] },
};
const conns = [{ id: "c1", rule: "Match", rulePayload: "", chains: ["nl-1", "FOREIGN", "MAIN"], upload: 10, download: 20 }];
const L = G.live(m, proxies, conns);
const match = m.ruleIndex["match|"];
const want = [match, "g:MAIN", "g:FOREIGN", "v:example", "g:UPLINK", "p:CSQTT"];
const got = Object.keys(L.nodes);
check("live", want.every((id) => L.nodes[id] && L.nodes[id].n == 1), "path " + JSON.stringify(got) + ", want " + JSON.stringify(want));
check("live", Object.keys(L.edges).length == want.length - 1, "edges on the path: " + Object.keys(L.edges).length);
check("live", L.provider["v:example"] && L.provider["v:example"].alive == 1, "alive nodes of example");
check("live", L.delay["g:FOREIGN"] == 42, "delay of FOREIGN's choice");
if (!fail)
console.log("ok graph live");
}
process.exit(fail);

View File

@ -1,7 +1,8 @@
#!/bin/sh
# Render every fixture with router/mihomo-kit.sh and compare with tests/expected/,
# validate with `mihomo -t` when MIHOMO points to a mihomo binary, and check
# luci/servers.js (share links, YAML) against the outputs of mihomo's own Go code.
# validate with `mihomo -t` when MIHOMO points to a mihomo binary, check
# luci/servers.js (share links, YAML) against the outputs of mihomo's own Go code,
# and luci/graph.js (the config graph) on the rendered profiles.
# tools/test.sh
# UPDATE=1 tools/test.sh rewrite tests/expected/ (review the diff)
# MIHOMO=/path/to/mihomo tools/test.sh
@ -39,6 +40,7 @@ for f in tests/fixtures/*.env; do
done
if command -v node >/dev/null 2>&1; then
node tools/test-servers.js || fail=1
node tools/test-graph.js || fail=1
else
echo "skip luci/servers.js: no node"
fi