Added core select, added import export kit config

This commit is contained in:
Sam Latsin 2026-10-11 12:18:51 +03:00
parent 4308645b4e
commit 99e13e0307
5 changed files with 275 additions and 16 deletions

View File

@ -44,6 +44,13 @@ TOTP-секрет), Tailscale; «Сохранить и применить» со
профиля, OpenVPN вкл/выкл/переподключить с текущим OTP, ссылка для входа в Tailscale,
пересборка, обновление kit и `fix`; вывод команды показывается внизу страницы.
Перенос настроек на другой роутер — «Экспорт настроек» там же: один файл `.kit` с
профилями, подписками, BOOT, своими серверами и OpenVPN (с паролями и `.ovpn` — хранить
как секрет). На другом роутере «Импорт настроек» заменяет его настройки и перезапускает
профиль; галка «оставить имя ноды Tailscale и x-hwid» сохраняет `TS_HOSTNAME` и `HWID_ID`
этого роутера. Выбор ядра, ключ ноды Tailscale и ссылка для телефона не переносятся.
Из терминала: `mihomo-kit.sh export > file.kit`, `mihomo-kit.sh import file.kit --keep-local`.
Автообновление — «Включить автообновление» там же (или `mihomo-kit.sh auto-update on|off`):
cron каждый день в 4:00 по времени роутера (часовой пояс — Система → Система) проверяет
коммит на сервере; если он новее — скачивает kit, пересобирает профили, при смене версии
@ -190,9 +197,19 @@ control-сервер и DERP идут по TCP через `dialer-proxy`. На
Сборка ядра: `tools/core/build.sh v1.19.32 ts1` → `tools/core/dist/*.gz` → релиз
`core-v1.19.32-ts1` в репозитории kit (`MIHOMO_VERSION` / `MIHOMO_BASE` в
`router/mihomo-kit.sh`). Если ядро не скачалось, `fix` оставляет текущее и запускает
nikki. Другое ядро на конкретном роутере — `/etc/nikki/kit.env`, например
`MIHOMO_VERSION=v1.19.32` (версии без `-ts` качаются с GitHub MetaCubeX), затем
`mihomo-kit.sh fix`. Когда исправление появится в mihomo, вернуть официальный релиз.
nikki.
Какое ядро на конкретном роутере — селект в «Обслуживании» (или
`mihomo-kit.sh core stock|official|kit`), выбор хранится в `/etc/nikki/kit.env` как `CORE=`:
- `stock` — ядро из пакета nikki/прошивки (`/usr/libexec/mihomo`), ничего не качается, место
во флеше освобождается;
- `official` — официальный релиз MetaCubeX `CORE_OFFICIAL`;
- `kit` (по умолчанию) — своя сборка `CORE_KIT` с правкой для Tailscale.
Распакованному ядру нужно ~56 МБ во флеше: на роутерах с маленьким `/overlay` остаётся
`stock`. Версии `CORE_OFFICIAL`/`CORE_KIT` задаются в `router/mihomo-kit.sh` — роутеры с
выбором `official`/`kit` подтягивают их при обновлении kit. Явный `MIHOMO_VERSION=…` в
`kit.env` главнее выбора. Когда исправление появится в mihomo, вернуть официальный релиз.
## Если что-то не работает

View File

@ -8,7 +8,7 @@
},
"write": {
"ubus": {
"mihomo-kit": [ "run", "config_get", "config_set" ]
"mihomo-kit": [ "run", "config_get", "config_set", "export", "import" ]
}
}
}

View File

@ -13,6 +13,8 @@ var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {
var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } });
var callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', expect: { '': {} } });
var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', expect: { '': {} } });
var callExport = rpc.declare({ object: 'mihomo-kit', method: 'export', expect: { '': {} } });
var callImport = rpc.declare({ object: 'mihomo-kit', method: 'import', params: [ 'data', 'keep_local' ], expect: { '': {} } });
var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } });
var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], expect: { '': {} } });
@ -250,8 +252,10 @@ return view.extend({
: E('strong', 'остановлен')),
row('Ядро mihomo', [ st.core_version || 'не найдено' ]
.concat(/-ts\d+$/.test(st.core_version || '') ? [ ' — сборка kit с правкой для Tailscale' ] : [])
.concat(st.core_wanted && st.core_version != st.core_wanted
? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'kit ждёт ' + st.core_wanted), ': нажми «Починить» в «Обслуживании»' ]
.concat(st.core && st.core.ok == '0'
? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'выбрано ' +
(st.core.wanted == 'stock' ? 'ядро из прошивки' : st.core.wanted)),
': нажми «Починить» в «Обслуживании»' ]
: [])),
row('Версия kit', [ st.kit_version || 'неизвестна (появится после «Обновить kit»)', ' ', updState ]),
row('Профиль', [ select, ' ',
@ -348,6 +352,17 @@ return view.extend({
E('table', { 'class': 'table' }, [
row(this.button('Пересобрать профили', 'action', 'build'),
'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'),
row(E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() {
return callExport().then(function(r) {
var a = E('a', { 'href': URL.createObjectURL(new Blob([ r.data ], { 'type': 'text/plain' })), 'download': r.name });
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}) }, 'Экспорт настроек'), 'один файл: подписки, BOOT, профили, свои серверы, OpenVPN (с паролями и .ovpn) — ' +
'для другого роутера; без выбора ядра, ключа Tailscale и ссылки для телефона'),
row(this.importBox(), 'заменит настройки этого роутера файлом экспорта и перезапустит профиль'),
row(this.coreSelect(st.core || {}), 'ядро mihomo для этого роутера; применяется сразу (перезапуск nikki)'),
row(st.auto_update
? this.button('Выключить автообновление', 'negative', 'autoupdate-off')
: this.button('Включить автообновление', 'positive', 'autoupdate-on'),
@ -661,6 +676,59 @@ return view.extend({
]);
},
importBox: function() {
var file = E('input', { 'type': 'file', 'accept': '.kit,.txt' });
var keep = check(true);
var btn = E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': ui.createHandlerFn(this, function() {
if (!file.files.length)
return ui.addNotification(null, E('p', 'Выбери файл экспорта (.kit)'), 'warning');
if (!window.confirm('Заменить все настройки этого роутера файлом ' + file.files[0].name + '?'))
return;
return readFile(file).then(L.bind(function(text) {
return callImport(text, keep.checked);
}, this)).then(L.bind(function(r) {
if (r.error)
return ui.addNotification(null, E('p', r.error), 'danger');
return this.follow();
}, this));
}) }, 'Импорт настроек');
btn.disabled = this.busy;
this.buttons.push(btn);
return E('div', [ file, ' ', btn, E('div', { 'style': 'margin-top:.3em' }, E('label', [ keep,
' оставить имя ноды Tailscale и x-hwid этого роутера' ])) ]);
},
// select stock / official / kit + "Установить"
coreSelect: function(c) {
var freeMb = Math.floor((+c.free_kb || 0) / 1024), needMb = Math.ceil((+c.need_kb || 0) / 1024);
var low = freeMb < needMb;
var opts = [
[ 'stock', 'Из прошивки' + (c.stock ? ' (' + c.stock + ')' : ' (нет)'), !c.stock ],
[ 'official', 'Официальное ' + (c.official || ''), false ],
[ 'kit', 'kit ' + (c.kit || '') + ' (правка для Tailscale)', false ]
];
var sel = E('select', { 'class': 'cbi-input-select' }, opts.map(function(o) {
var opt = E('option', { 'value': o[0] }, o[1]);
opt.disabled = o[2];
return opt;
}));
// MIHOMO_VERSION=... in kit.env: shown as is until a choice replaces it
if (c.pinned == '1')
sel.insertBefore(E('option', { 'value': '' }, 'закреплено в kit.env: ' + c.wanted), sel.firstChild);
sel.value = c.pinned == '1' ? '' : (c.choice || 'kit');
var hint = E('div', { 'class': 'cbi-value-description' });
var update = function() {
dom.content(hint, (sel.value == 'official' || sel.value == 'kit') && low
? 'Во флеше свободно ' + freeMb + ' МБ, ядру нужно около ' + needMb +
' МБ: скорее всего не встанет (установка тогда откатится сама)'
: '');
};
sel.addEventListener('change', update);
update();
return E('div', [ sel, ' ', this.button('Установить', 'apply', 'core', function() { return sel.value; },
'Поставить выбранное ядро? nikki перезапустится.'), hint ]);
},
showJob: function(j) {
if (!j.cmd) {
this.jobBox.style.display = 'none';

View File

@ -8,6 +8,8 @@
# job the job's command, state, exit code and output
# update_check latest kit commit on the git server vs the installed one
# ts_check Tailscale delay test to TS_CHECK_URL through the mihomo API
# export all settings as one text file (mihomo-kit.sh export)
# 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
#
@ -72,7 +74,14 @@ m_status() {
json_add_string kit_version "$(cat "$NIKKI_DIR/kit/VERSION" 2>/dev/null)"
# installed core vs the one the kit pins (MIHOMO_VERSION default in mihomo-kit.sh)
json_add_string core_version "$(mihomo -v 2>/dev/null | awk '{print $3; exit}')"
json_add_string core_wanted "$(mihomo-kit.sh core-wanted 2>/dev/null)"
# choice, wanted, ok, stock/official/kit versions, free_kb, need_kb
json_add_object core
mihomo-kit.sh core-info > /tmp/mihomo-kit-core.$$ 2>/dev/null
while read -r k v; do
json_add_string "$k" "$v"
done < /tmp/mihomo-kit-core.$$
rm -f /tmp/mihomo-kit-core.$$
json_close_object
json_add_boolean auto_update "$(b grep -q 'mihomo-kit.sh auto-update' /etc/crontabs/root)"
# phone config (MOBILE=1): /mihomo-kit/<token>.yaml served by uhttpd
mob=$(ls /www/mihomo-kit/*.yaml 2>/dev/null | head -n 1)
@ -144,6 +153,10 @@ m_run() {
autoupdate-on) set -- mihomo-kit.sh auto-update on ;;
autoupdate-off) set -- mihomo-kit.sh auto-update off ;;
mobile-new) set -- mihomo-kit.sh mobile new ;;
core)
case "$arg" in stock | official | kit) ;; *) reply_error "bad core choice" ;; esac
set -- mihomo-kit.sh core "$arg"
;;
*) reply_error "unknown command: $cmd" ;;
esac
start_job "$@"
@ -335,6 +348,30 @@ m_update_check() {
json_dump
}
m_export() {
json_init
json_add_string name "mihomo-kit-$(uci -q get 'system.@system[0].hostname')-$(date '+%Y%m%d').kit"
json_add_string data "$(mihomo-kit.sh export 2>/dev/null)"
json_dump
}
m_import() {
json_load "$(cat)" || reply_error "bad request"
json_get_var data data ""
json_get_var keep keep_local 0
job_running && reply_error "busy: $(cat "$JOB/cmd")"
umask 077
f=$(mktemp /tmp/mihomo-kit-import.XXXXXX) || reply_error "mktemp failed"
printf '%s\n' "$data" > "$f"
umask 022
head -n 1 "$f" | grep -q '^# mihomo-kit export v1' || { rm -f "$f"; reply_error "это не файл экспорта mihomo-kit"; }
if [ "$keep" = 1 ]; then
start_job mihomo-kit.sh import "$f" --keep-local
else
start_job mihomo-kit.sh import "$f"
fi
}
m_job() {
json_init
json_add_string cmd "$(cat "$JOB/cmd" 2>/dev/null)"
@ -346,7 +383,7 @@ m_job() {
case "$1" in
list)
echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{}}'
echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true}}'
;;
call)
case "$2" in
@ -358,6 +395,8 @@ case "$1" in
config_set) m_config_set ;;
update_check) m_update_check ;;
ts_check) m_ts_check ;;
export) m_export ;;
import) m_import ;;
*) reply_error "unknown method" ;;
esac
;;

View File

@ -23,7 +23,9 @@
# mihomo-kit.sh fix re-apply core version + fixes (after a nikki upgrade)
# mihomo-kit.sh ts-login [-f] fresh Tailscale node, print its login URL
# (-f: also when the node is already logged in)
# mihomo-kit.sh export > file all settings as one file; import <file> [--keep-local] on another router
# mihomo-kit.sh mobile new new secret link for the phone config (MOBILE=1)
# mihomo-kit.sh core <choice> mihomo core: stock (package) | official | kit (Tailscale fix)
# mihomo-kit.sh install packages, core, fixes, links (no questions)
# mihomo-kit.sh render <env>... print the YAML for env file(s) (last wins)
@ -36,9 +38,24 @@ TPL_DIR="${TPL_DIR:-$KIT_DIR/templates}"
NIKKI_DIR="${NIKKI_DIR:-/etc/nikki}"
PROFILES_D="$NIKKI_DIR/profiles.d"
PROFILES_OUT="$NIKKI_DIR/profiles"
# per-router overrides (MIHOMO_VERSION, MIHOMO_BASE, ...), e.g. MIHOMO_VERSION=v1.19.32
[ -f /etc/nikki/kit.env ] && . /etc/nikki/kit.env
: "${MIHOMO_VERSION:=v1.19.32-ts1}"
# mihomo core: the choice CORE in /etc/nikki/kit.env (LuCI select, "core <choice>")
# stock the core of the mihomo package (/usr/libexec/mihomo), nothing downloaded
# official MetaCubeX release CORE_OFFICIAL
# kit own build CORE_KIT (official + tools/core/*.patch: Tailscale through dialer-proxy)
# An explicit MIHOMO_VERSION in kit.env wins (e.g. MIHOMO_VERSION=v1.19.29).
CORE_OFFICIAL=v1.19.32
CORE_KIT=v1.19.32-ts1
STOCK_CORE=/usr/libexec/mihomo
KIT_ENV=${KIT_ENV:-/etc/nikki/kit.env}
[ -f "$KIT_ENV" ] && . "$KIT_ENV"
: "${CORE:=kit}"
if [ -z "${MIHOMO_VERSION:-}" ]; then
case "$CORE" in
stock) MIHOMO_VERSION=stock ;;
official) MIHOMO_VERSION=$CORE_OFFICIAL ;;
*) MIHOMO_VERSION=$CORE_KIT ;;
esac
fi
# where mihomo-linux-<arch>-<version>.gz is downloaded from. -tsN: own build with
# tools/core/*.patch (Tailscale through dialer-proxy, MetaCubeX/mihomo#3142) in the
# kit repo's releases; other versions: upstream MetaCubeX/mihomo releases.
@ -613,12 +630,35 @@ cmd_ts_login() {
# --- router setup -----------------------------------------------------------
# unpacked core size to expect, for the free space check (KiB)
CORE_NEED_KB=60000
# is the installed core the wanted one?
core_ok() {
if [ "$MIHOMO_VERSION" = stock ]; then
[ "$(readlink /usr/bin/mihomo)" = "$STOCK_CORE" ]
else
[ "$(mihomo -v 2>/dev/null | awk '{print $3; exit}')" = "$MIHOMO_VERSION" ]
fi
}
core_update() {
cur=$(mihomo -v 2>/dev/null | awk '{print $3; exit}')
if [ "$cur" = "$MIHOMO_VERSION" ]; then
if core_ok; then
log "mihomo core is $cur"
return 0
fi
if [ "$MIHOMO_VERSION" = stock ]; then
# back to the package's core: /usr/bin/mihomo becomes a symlink to it again
if [ ! -x "$STOCK_CORE" ]; then
log "warning: no package core at $STOCK_CORE, keeping $cur"
return 1
fi
rm -f /usr/bin/mihomo /usr/bin/mihomo.new /usr/bin/mihomo.bak
ln -s "$STOCK_CORE" /usr/bin/mihomo
log "core: the package's $("$STOCK_CORE" -v 2>/dev/null | awk '{print $3; exit}')"
return 0
fi
case "$(uname -m)" in
aarch64) arch=arm64 ;;
x86_64) arch=amd64 ;;
@ -1065,8 +1105,14 @@ cmd_configure() {
fi
write_config
log "saved $PROFILES_D/common.env"
cmd_apply
}
# settings in profiles.d (+ bmstu.*) -> build, OpenVPN cron, restart the current
# profile, Tailscale login if needed (after configure / import)
cmd_apply() {
cmd_build
if [ "$OPENVPN" = 1 ]; then
if grep -q '^OPENVPN=1' "$PROFILES_D/common.env"; then
enable_otp_cron
elif grep -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null; then
sed -i '/bmstu-otp.sh check/d' /etc/crontabs/root
@ -1078,10 +1124,69 @@ cmd_configure() {
cur=${cur%.yaml}
[ -f "$PROFILES_D/$cur.env" ] || cur=main
cmd_use "$cur"
[ "$TAILSCALE" = 1 ] && cmd_ts_login
grep -q '^TAILSCALE=1' "$PROFILES_D/common.env" && cmd_ts_login
true
}
# Settings bundle: one text file with profiles.d/*.env, bmstu.env, bmstu.ovpn
# (secrets inside). Not in it: kit.env (core choice), the Tailscale node key,
# the phone link token - all per router.
EXPORT_HEAD='# mihomo-kit export v1'
cmd_export() {
echo "$EXPORT_HEAD $(uci -q get 'system.@system[0].hostname') $(date '+%Y-%m-%d %H:%M')"
for _f in "$PROFILES_D"/*.env "$NIKKI_DIR/bmstu.env" "$NIKKI_DIR/bmstu.ovpn"; do
[ -f "$_f" ] || continue
echo "#%% file ${_f#"$NIKKI_DIR"/}"
cat "$_f"
[ -z "$(tail -c 1 "$_f")" ] || echo
done
}
# import <file> [--keep-local]: replace the settings with the bundle and apply;
# --keep-local keeps this router's TS_HOSTNAME and HWID_ID (node name, device id)
cmd_import() {
[ -f "${1:-}" ] || die "usage: import <file> [--keep-local]"
head -n 1 "$1" | grep -q "^$EXPORT_HEAD" || die "not a mihomo-kit export"
_files=$(sed -n 's/^#%% file //p' "$1")
echo "$_files" | grep -q '^profiles.d/common.env$' || die "no profiles.d/common.env in the export"
for _f in $_files; do
case "$_f" in
profiles.d/*.env | bmstu.env | bmstu.ovpn) ;;
*) die "unexpected file in the export: $_f" ;;
esac
case "${_f#profiles.d/}" in */* | *[!A-Za-z0-9_.-]*) die "bad file name: $_f" ;; esac
done
_keep=""
if [ "${2:-}" = --keep-local ]; then
for _k in TS_HOSTNAME HWID_ID; do
_l=$(grep "^$_k=" "$PROFILES_D/common.env" 2>/dev/null | tail -n 1)
[ -n "$_l" ] && _keep="$_keep$_l
"
done
fi
_tmp=$(mktemp -d)
mkdir -p "$_tmp/profiles.d"
awk -v d="$_tmp" '/^#%% file /{ f = d "/" $3; next } f { print > f }' "$1"
umask 077
rm -f "$PROFILES_D"/*.env
cp "$_tmp"/profiles.d/*.env "$PROFILES_D/"
for _f in bmstu.env bmstu.ovpn; do
[ -f "$_tmp/$_f" ] && cp "$_tmp/$_f" "$NIKKI_DIR/$_f"
done
if [ -n "$_keep" ]; then
grep -vE '^(TS_HOSTNAME|HWID_ID)=' "$PROFILES_D/common.env" > "$_tmp/common.env"
printf '%s' "$_keep" >> "$_tmp/common.env"
cp "$_tmp/common.env" "$PROFILES_D/common.env"
fi
chmod 600 "$PROFILES_D"/*.env
umask 022
rm -rf "$_tmp"
log "imported $(echo "$_files" | wc -l | tr -d ' ') files from: $(head -n 1 "$1" | cut -d' ' -f5-)"
# the upload from LuCI holds secrets
case "$1" in /tmp/mihomo-kit-import.*) rm -f "$1" ;; esac
cmd_apply
}
# install only; settings in LuCI (or questions here with --cli / without LuCI)
cmd_setup() {
cmd_install
@ -1151,6 +1256,31 @@ cmd_check_update() {
esac
}
# core <stock|official|kit>: save the choice in kit.env (other keys kept) and apply it
cmd_core() {
case "${1:-}" in stock | official | kit) ;; *) die "usage: core stock|official|kit" ;; esac
touch "$KIT_ENV"
grep -vE '^(CORE|MIHOMO_VERSION|MIHOMO_BASE)=' "$KIT_ENV" > "$KIT_ENV.tmp"
echo "CORE=$1" >> "$KIT_ENV.tmp"
mv "$KIT_ENV.tmp" "$KIT_ENV"
log "core choice: $1"
exec sh "$SELF" fix
}
# for the LuCI select: "key value" lines
cmd_core_info() {
echo "choice $CORE"
echo "pinned $(grep -q '^MIHOMO_VERSION=' "$KIT_ENV" 2>/dev/null && echo 1 || echo 0)"
echo "wanted $MIHOMO_VERSION"
echo "ok $(core_ok && echo 1 || echo 0)"
echo "stock $("$STOCK_CORE" -v 2>/dev/null | awk '{print $3; exit}')"
echo "official $CORE_OFFICIAL"
echo "kit $CORE_KIT"
_bin=$(command -v mihomo || echo /usr/bin/mihomo)
echo "free_kb $(df -k "${_bin%/*}" 2>/dev/null | awk 'NR==2 {print $4}')"
echo "need_kb $CORE_NEED_KB"
}
cmd_update() {
_apply=${1:-}
tmp=$(mktemp -d)
@ -1181,7 +1311,7 @@ cmd_post_update() {
return 0
fi
# a new kit may pin another core version
[ "$(mihomo -v 2>/dev/null | awk '{print $3; exit}')" = "$MIHOMO_VERSION" ] || cmd_fix
core_ok || cmd_fix
[ -f "$PROFILES_OUT/$cur.yaml" ] && cmd_use "$cur"
auto_log "updated to $(cut -d' ' -f1 "$KIT_DIR/VERSION"), profile $cur restarted"
}
@ -1230,16 +1360,21 @@ case "${1:-}" in
use) shift; cmd_use "$@" ;;
setup) shift; cmd_setup "$@" ;;
configure) shift; cmd_configure "$@" ;;
apply) cmd_apply ;;
export) cmd_export ;;
import) shift; cmd_import "$@" ;;
mobile) shift; cmd_mobile "$@" ;;
sub-ids) cmd_sub_ids ;;
# the core version the kit wants on this router (LuCI)
core-wanted) echo "$MIHOMO_VERSION" ;;
update) shift; cmd_update "$@" ;;
core) shift; cmd_core "$@" ;;
core-info) cmd_core_info ;;
auto-update) shift; cmd_auto_update "$@" ;;
check-update) cmd_check_update ;;
post-update) shift; cmd_post_update "$@" ;;
install) cmd_install ;;
fix) cmd_fix ;;
ts-login) shift; cmd_ts_login "$@" ;;
*) sed -n '2,30p' "$SELF" >&2; exit 2 ;;
*) sed -n '2,32p' "$SELF" >&2; exit 2 ;;
esac