Added luci

This commit is contained in:
Sam Latsin 2026-10-09 17:02:44 +03:00
parent ddbe5f4ab3
commit 7dd7dc57ad
8 changed files with 392 additions and 6 deletions

View File

@ -34,6 +34,10 @@ ssh root@192.168.32.1 sh /etc/nikki/kit/install.sh
## Каждый день ## Каждый день
То же самое из веб-интерфейса: LuCI → **Службы → mihomo-kit**. Там переключение
профиля, OpenVPN вкл/выкл/переподключить с текущим OTP, ссылка для входа в Tailscale,
пересборка, обновление kit и `fix`; вывод команды показывается внизу страницы.
```sh ```sh
mihomo-kit.sh use street # уехал на белые списки mihomo-kit.sh use street # уехал на белые списки
mihomo-kit.sh use home # вернулся mihomo-kit.sh use home # вернулся
@ -130,6 +134,7 @@ presets/ профили, которые setup кладёт в profile
router/ router/
mihomo-kit.sh сборка, setup-мастер, use/update/fix mihomo-kit.sh сборка, setup-мастер, use/update/fix
bmstu-otp.sh OpenVPN BMSTU: TOTP в пароле, cron-сторож, on/off bmstu-otp.sh OpenVPN BMSTU: TOTP в пароле, cron-сторож, on/off
luci/ страница LuCI «Службы → mihomo-kit»: rpcd.sh (бэкенд), view, ACL, меню
web/ страница-конструктор: engine.js + index.src.html → index.html web/ страница-конструктор: engine.js + index.src.html → index.html
tools/ push.sh, test.sh, build-web.py, render.js tools/ push.sh, test.sh, build-web.py, render.js
tests/fixtures/ профили для test.sh (фиктивные секреты) tests/fixtures/ профили для test.sh (фиктивные секреты)

View File

@ -11,7 +11,7 @@ KIT_DIR=/etc/nikki/kit
here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo /nonexistent) here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo /nonexistent)
mkdir -p "$KIT_DIR" mkdir -p "$KIT_DIR"
if [ -f "$here/router/mihomo-kit.sh" ]; then if [ -f "$here/router/mihomo-kit.sh" ]; then
[ "$here" = "$KIT_DIR" ] || cp -r "$here/templates" "$here/presets" "$here/router" "$KIT_DIR/" [ "$here" = "$KIT_DIR" ] || cp -r "$here/templates" "$here/presets" "$here/router" "$here/luci" "$KIT_DIR/"
else else
tmp=/tmp/mihomo-kit.$$ tmp=/tmp/mihomo-kit.$$
mkdir -p "$tmp" mkdir -p "$tmp"
@ -21,7 +21,7 @@ else
src=$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1) src=$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1)
[ -n "$src" ] || { echo "error: no router/mihomo-kit.sh in $KIT_URL" >&2; exit 1; } [ -n "$src" ] || { echo "error: no router/mihomo-kit.sh in $KIT_URL" >&2; exit 1; }
src=${src%/router/mihomo-kit.sh} src=${src%/router/mihomo-kit.sh}
for d in templates presets router; do for d in templates presets router luci; do
rm -rf "${KIT_DIR:?}/$d" rm -rf "${KIT_DIR:?}/$d"
cp -r "$src/$d" "$KIT_DIR/" cp -r "$src/$d" "$KIT_DIR/"
done done

15
luci/acl.json Normal file
View File

@ -0,0 +1,15 @@
{
"luci-app-mihomo-kit": {
"description": "mihomo-kit: profiles, OpenVPN, Tailscale",
"read": {
"ubus": {
"mihomo-kit": [ "status", "ovpn_status", "job" ]
}
},
"write": {
"ubus": {
"mihomo-kit": [ "run" ]
}
}
}
}

13
luci/menu.json Normal file
View File

@ -0,0 +1,13 @@
{
"admin/services/mihomo-kit": {
"title": "mihomo-kit",
"order": 61,
"action": {
"type": "view",
"path": "mihomo-kit"
},
"depends": {
"acl": [ "luci-app-mihomo-kit" ]
}
}
}

202
luci/mihomo-kit.js Normal file
View File

@ -0,0 +1,202 @@
'use strict';
'require view';
'require rpc';
'require ui';
'require dom';
// Backend: /usr/libexec/rpcd/mihomo-kit (luci/rpcd.sh in the kit).
// Commands run as one background job; the page polls its output.
var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } });
var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', expect: { '': {} } });
var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } });
function wait(ms) {
return new Promise(function(resolve) { window.setTimeout(resolve, ms); });
}
function row(title, value) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td left', 'width': '33%' }, title),
E('td', { 'class': 'td left' }, value)
]);
}
function section(title, children) {
return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children));
}
return view.extend({
handleSaveApply: null,
handleSave: null,
handleReset: null,
load: function() {
return Promise.all([ callStatus(), callJob() ]);
},
button: function(label, style, cmd, arg, confirmText) {
var btn = E('button', {
'class': 'btn cbi-button cbi-button-' + style,
'click': ui.createHandlerFn(this, function() {
if (confirmText && !window.confirm(confirmText))
return;
return this.run(cmd, typeof arg == 'function' ? arg() : arg);
})
}, label);
btn.disabled = this.busy;
this.buttons.push(btn);
return btn;
},
renderBody: function(st) {
var sections = [];
this.buttons = [];
if (!st.configured)
sections.push(E('div', { 'class': 'alert-message warning' },
'Kit ещё не настроен: запусти по ssh mihomo-kit.sh setup'));
var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) {
return E('option', { 'value': p }, p);
}));
select.value = st.profile;
sections.push(section('Состояние', [
E('table', { 'class': 'table' }, [
row('nikki', st.running ? 'работает' : E('strong', 'остановлен')),
row('Профиль', [ select, ' ',
this.button('Включить', 'apply', 'use', function() { return select.value; }) ])
])
]));
if (st.openvpn) {
var ovpnState = E('em', 'проверяю…');
var otp = E('span', '—');
callOvpnStatus().then(function(o) {
dom.content(ovpnState, {
up: E('strong', { 'style': 'color:green' }, 'туннель работает'),
down: E('strong', { 'style': 'color:#c00' }, 'туннель не отвечает'),
off: 'выключен'
}[o.state] || o.state);
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
}).catch(function(e) { dom.content(ovpnState, String(e)); });
sections.push(section('OpenVPN', [
E('table', { 'class': 'table' }, [
row('Состояние', ovpnState),
row('OTP сейчас', otp)
]),
E('div', { 'class': 'cbi-page-actions' }, [
this.button('Включить', 'positive', 'ovpn-on'), ' ',
this.button('Выключить', 'negative', 'ovpn-off', null,
'Закрыть туннель? Сессия на сервере освободится в течение ~5 минут.'), ' ',
this.button('Переподключить', 'action', 'ovpn-refresh')
])
]));
}
if (st.tailscale)
sections.push(section('Tailscale', [
E('table', { 'class': 'table' }, [
row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла'))
]),
E('div', { 'class': 'cbi-page-actions' }, st.ts_logged_in
? [ this.button('Войти заново', 'negative', 'ts-relogin', null,
'Удалить ключ ноды и войти заново? Нода получит новый адрес 100.x.') ]
: [ this.button('Получить ссылку для входа', 'positive', 'ts-login') ])
]));
sections.push(section('Обслуживание', [
E('table', { 'class': 'table' }, [
row(this.button('Пересобрать профили', 'action', 'build'),
'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'),
row(this.button('Обновить kit', 'action', 'update', null,
'Скачать свежий kit и пересобрать профили?'),
'шаблоны, скрипты и эта страница; после обновления LuCI может попросить войти заново'),
row(this.button('Починить после обновления nikki', 'action', 'fix', null,
'Перезапустить nikki и вернуть ядро и правки?'),
'версия ядра, TS_FORCE_NOISE_443, reserved_ip')
])
]));
dom.content(this.body, sections);
},
showJob: function(j) {
if (!j.cmd) {
this.jobBox.style.display = 'none';
return;
}
this.jobBox.style.display = '';
var state = j.running ? 'выполняется…' : (j.rc === 0 ? 'готово' : 'ошибка (код ' + j.rc + ')');
dom.content(this.jobTitle, 'Последняя команда: ' + j.cmd + ' — ' + state);
var m = (j.log || '').match(/https:\/\/login\.tailscale\.com\/\S+/g);
dom.content(this.jobLink, m ? E('div', { 'class': 'alert-message notice' }, [
'Вход в Tailscale: ',
E('a', { 'href': m[m.length - 1], 'target': '_blank', 'rel': 'noreferrer' }, m[m.length - 1]),
E('br'), 'После входа в админке Tailscale — Disable key expiry для ноды.'
]) : []);
this.jobLog.textContent = j.log || '';
this.jobLog.scrollTop = this.jobLog.scrollHeight;
},
setBusy: function(busy) {
this.busy = busy;
this.buttons.forEach(function(b) { b.disabled = busy; });
},
run: function(cmd, arg) {
return callRun(cmd, arg || '').then(L.bind(function(r) {
if (r.error) {
ui.addNotification(null, E('p', r.error), 'danger');
return;
}
return this.follow();
}, this));
},
// poll the job until it ends; rpcd may restart under us (kit update)
follow: function() {
var errors = 0;
this.setBusy(true);
var loop = L.bind(function() {
return callJob().then(L.bind(function(j) {
errors = 0;
this.showJob(j);
if (j.running)
return wait(1000).then(loop);
this.setBusy(false);
if (j.rc !== 0)
ui.addNotification(null, E('p', j.cmd + ': ошибка, см. вывод внизу страницы'), 'danger');
return callStatus().then(L.bind(this.renderBody, this));
}, this)).catch(L.bind(function(e) {
if (++errors > 15) {
this.setBusy(false);
ui.addNotification(null, E('p', 'Нет связи с роутером: ' + e), 'danger');
return;
}
return wait(2000).then(loop);
}, this));
}, this);
return loop();
},
render: function(data) {
this.busy = false;
this.buttons = [];
this.body = E('div');
this.jobTitle = E('h3');
this.jobLink = E('div');
this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' });
this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLink, this.jobLog ]);
this.renderBody(data[0]);
this.showJob(data[1]);
if (data[1].running)
this.follow();
return E([], [ E('h2', 'mihomo-kit'), this.body, this.jobBox ]);
}
});

126
luci/rpcd.sh Normal file
View File

@ -0,0 +1,126 @@
#!/bin/sh
# rpcd plugin "mihomo-kit" for the LuCI page (installed as /usr/libexec/rpcd/mihomo-kit).
#
# status profile, nikki running, which features are on
# ovpn_status OpenVPN state (up/down/off) + current OTP; slow (a delay test)
# run start a whitelisted command as the background job
# job the job's command, state, exit code and output
#
# rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job.
. /usr/share/libubox/jshn.sh
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
NIKKI_DIR=/etc/nikki
PROFILES_D=$NIKKI_DIR/profiles.d
JOB=/tmp/mihomo-kit-job
# 1 if the command succeeds, else 0 (for json_add_boolean)
b() { "$@" >/dev/null 2>&1 && echo 1 || echo 0; }
# envval VAR profile -> value from common.env, overridden by <profile>.env
envval() {
cat "$PROFILES_D/common.env" "$PROFILES_D/$2.env" 2>/dev/null |
sed -n "s/^$1=//p" | tail -n 1 | tr -d "'\""
}
job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; }
reply_error() {
json_init
json_add_string error "$1"
json_dump
exit 0
}
m_status() {
prof=$(uci -q get nikki.config.profile)
prof=${prof#file:}
prof=${prof%.yaml}
json_init
json_add_string profile "$prof"
json_add_boolean running "$(b pidof mihomo)"
json_add_boolean configured "$(b test -f "$PROFILES_D/common.env")"
json_add_array profiles
for f in "$NIKKI_DIR"/profiles/*.yaml; do
[ -f "$f" ] || continue
n=${f##*/}
json_add_string "" "${n%.yaml}"
done
json_close_array
json_add_boolean openvpn "$(b test "$(envval OPENVPN "$prof")" = 1)"
json_add_boolean tailscale "$(b test "$(envval TAILSCALE "$prof")" = 1)"
json_add_boolean ts_logged_in "$(b grep -q _current-profile "$NIKKI_DIR/run/tailscale/tailscaled.state")"
json_dump
}
m_ovpn_status() {
json_init
if [ -f "$NIKKI_DIR/bmstu.off" ]; then
json_add_string state off
elif CHECK_TIMEOUT=8000 bmstu-otp.sh status 2>/dev/null | grep -q "tunnel is up"; then
json_add_string state up
else
json_add_string state down
fi
json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)"
json_add_int otp_left "$((30 - $(date +%s) % 30))"
json_dump
}
m_run() {
input=$(cat)
cmd=$(jsonfilter -s "$input" -e '@.cmd' 2>/dev/null)
arg=$(jsonfilter -s "$input" -e '@.arg' 2>/dev/null)
case "$cmd" in
ovpn-on) set -- bmstu-otp.sh on ;;
ovpn-off) set -- bmstu-otp.sh off ;;
ovpn-refresh) set -- bmstu-otp.sh refresh ;;
use)
case "$arg" in '' | *[!A-Za-z0-9_-]*) reply_error "bad profile name" ;; esac
[ -f "$NIKKI_DIR/profiles/$arg.yaml" ] || reply_error "no profile $arg"
set -- mihomo-kit.sh use "$arg"
;;
ts-login) set -- mihomo-kit.sh ts-login ;;
ts-relogin) set -- mihomo-kit.sh ts-login -f ;;
build | update | fix) set -- mihomo-kit.sh "$cmd" ;;
*) reply_error "unknown command: $cmd" ;;
esac
job_running && reply_error "busy: $(cat "$JOB/cmd")"
rm -rf "$JOB"
mkdir -p "$JOB"
echo "$*" > "$JOB/cmd"
# detached from rpcd: all fds redirected, so the call returns at once
(
"$@"
echo $? > "$JOB/rc"
) < /dev/null > "$JOB/log" 2>&1 &
echo $! > "$JOB/pid"
json_init
json_add_string started "$*"
json_dump
}
m_job() {
json_init
json_add_string cmd "$(cat "$JOB/cmd" 2>/dev/null)"
json_add_boolean running "$(b job_running)"
[ -f "$JOB/rc" ] && json_add_int rc "$(cat "$JOB/rc")"
json_add_string log "$(tail -c 20000 "$JOB/log" 2>/dev/null)"
json_dump
}
case "$1" in
list)
echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"}}'
;;
call)
case "$2" in
status) m_status ;;
ovpn_status) m_ovpn_status ;;
job) m_job ;;
run) m_run ;;
*) reply_error "unknown method" ;;
esac
;;
esac

View File

@ -5,7 +5,7 @@
# router-side fixes in place (core version, Tailscale env, nikki bypass list). # router-side fixes in place (core version, Tailscale env, nikki bypass list).
# #
# Layout on the router: # Layout on the router:
# /etc/nikki/kit/{templates,presets,router} the kit (install.sh / update / tools/push.sh) # /etc/nikki/kit/{templates,presets,router,luci} the kit (install.sh / update / tools/push.sh)
# /etc/nikki/profiles.d/common.env shared secrets/options # /etc/nikki/profiles.d/common.env shared secrets/options
# /etc/nikki/profiles.d/<name>.env one file per profile (home, street, ...) # /etc/nikki/profiles.d/<name>.env one file per profile (home, street, ...)
# /etc/nikki/profiles/<name>.yaml generated, what nikki runs # /etc/nikki/profiles/<name>.yaml generated, what nikki runs
@ -424,6 +424,31 @@ install_files() {
done done
mkdir -p "$PROFILES_D" mkdir -p "$PROFILES_D"
chmod 700 "$PROFILES_D" chmod 700 "$PROFILES_D"
install_luci
}
# LuCI page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view
install_luci() {
src=$KIT_DIR/luci
[ -d "$src" ] && [ -d /www/luci-static/resources ] || return 0
_changed=0
put() {
cmp -s "$1" "$2" && return 0
mkdir -p "$(dirname "$2")"
cp "$1" "$2"
_changed=1
}
put "$src/rpcd.sh" /usr/libexec/rpcd/mihomo-kit
chmod +x /usr/libexec/rpcd/mihomo-kit
put "$src/acl.json" /usr/share/rpcd/acl.d/luci-app-mihomo-kit.json
put "$src/menu.json" /usr/share/luci/menu.d/luci-app-mihomo-kit.json
put "$src/mihomo-kit.js" /www/luci-static/resources/view/mihomo-kit.js
[ "$_changed" = 1 ] || return 0
rm -rf /tmp/luci-indexcache* /tmp/luci-modulecache
log "LuCI page installed: Services -> mihomo-kit"
# rpcd loads plugins only on start; delayed so a job started from LuCI
# (kit update) gets to finish first
(sleep 5; /etc/init.d/rpcd restart) < /dev/null > /dev/null 2>&1 &
} }
enable_otp_cron() { enable_otp_cron() {
@ -648,9 +673,9 @@ cmd_update() {
src=$(dirname "$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1)") src=$(dirname "$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1)")
[ -n "$src" ] && [ "$src" != . ] || die "no router/mihomo-kit.sh in the archive" [ -n "$src" ] && [ "$src" != . ] || die "no router/mihomo-kit.sh in the archive"
src=${src%/router} src=${src%/router}
for d in templates presets router; do for d in templates presets router luci; do
rm -rf "${KIT_DIR:?}/$d" rm -rf "${KIT_DIR:?}/$d"
cp -r "$src/$d" "$KIT_DIR/$d" [ -d "$src/$d" ] && cp -r "$src/$d" "$KIT_DIR/$d"
done done
rm -rf "$tmp" rm -rf "$tmp"
install_files install_files

View File

@ -6,6 +6,6 @@ set -eu
host=${1:?usage: tools/push.sh root@<router>} host=${1:?usage: tools/push.sh root@<router>}
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
# ustar without macOS metadata: busybox tar on OpenWrt chokes on pax/xattr headers # ustar without macOS metadata: busybox tar on OpenWrt chokes on pax/xattr headers
COPYFILE_DISABLE=1 tar --no-xattrs --format ustar -czf - install.sh templates presets router | COPYFILE_DISABLE=1 tar --no-xattrs --format ustar -czf - install.sh templates presets router luci |
ssh "$host" 'mkdir -p /etc/nikki/kit && tar xzf - -C /etc/nikki/kit && chmod +x /etc/nikki/kit/router/*.sh' ssh "$host" 'mkdir -p /etc/nikki/kit && tar xzf - -C /etc/nikki/kit && chmod +x /etc/nikki/kit/router/*.sh'
echo "pushed to $host:/etc/nikki/kit — now: ssh $host sh /etc/nikki/kit/install.sh" echo "pushed to $host:/etc/nikki/kit — now: ssh $host sh /etc/nikki/kit/install.sh"