mihomo-kit/router/mihomo-kit.sh
Sam Latsin 2557a9aa49 mihomo-kit: config kit for mihomo on nikki and FlClash
Templates + router script + browser constructor that build mihomo
profiles (router home/street, mobile) with optional OpenVPN (TOTP)
and Tailscale, one-command installer and maintenance commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 00:57:28 +03:00

520 lines
16 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/sh
# mihomo config kit for nikki on OpenWrt.
#
# Builds mihomo profiles from templates/ + per-profile env files, and keeps the
# router-side fixes in place (core version, Tailscale env, nikki bypass list).
#
# Layout on the router:
# /etc/nikki/kit/{templates,presets,router} the kit (install.sh / update / tools/push.sh)
# /etc/nikki/profiles.d/common.env shared secrets/options
# /etc/nikki/profiles.d/<name>.env one file per profile (home, street, ...)
# /etc/nikki/profiles/<name>.yaml generated, what nikki runs
#
# Usage:
# mihomo-kit.sh setup first run: install + questions + build + start
# mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all)
# mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart
# mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild
# mihomo-kit.sh fix re-apply core version + fixes (after a nikki upgrade)
# mihomo-kit.sh install packages, core, fixes, links (no questions)
# mihomo-kit.sh render <env>... print the YAML for env file(s) (last wins)
set -u
# resolve the /usr/bin symlink to find the kit
SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")
KIT_DIR="${KIT_DIR:-$(cd "$(dirname "$SELF")/.." && pwd)}"
TPL_DIR="${TPL_DIR:-$KIT_DIR/templates}"
NIKKI_DIR="${NIKKI_DIR:-/etc/nikki}"
PROFILES_D="$NIKKI_DIR/profiles.d"
PROFILES_OUT="$NIKKI_DIR/profiles"
: "${MIHOMO_VERSION:=v1.19.32}"
: "${KIT_URL:=https://git.sam-hub.net/sam/mihomo-kit/archive/main.tar.gz}"
log() { echo "$*" >&2; }
die() { log "error: $*"; exit 1; }
# --- rendering --------------------------------------------------------------
# Template syntax (same in web/engine.js):
# file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
# .each = once per subscription
# line ... #@tag[,!tag] kept only if the conditions hold
# line ... ${@VAR} ... repeated for every word of VAR
# text ${VAR} replaced with the variable
set_defaults() {
: "${TARGET:=router}" "${LOCATION:=home}"
: "${BOOT:=1}" "${TORRENT:=1}" "${OPENVPN:=0}" "${TAILSCALE:=0}" "${TS_EXIT:=0}"
: "${SUBS:=}" "${RU_IPS:=}"
: "${GEOIP_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geoip.dat}"
: "${GEOSITE_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geosite.dat}"
: "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}"
: "${TS_HOSTNAME:=mihomo}" "${TS_DOMAINS:=}"
: "${OVPN_PROVIDER:=bmstu}" "${OVPN_GROUP:=BMSTU}" "${OVPN_SERVER_HOST:=openvpn4.bmstu.ru}"
: "${OVPN_SERVER_IPS:=195.19.40.7 195.19.33.86}"
: "${OVPN_ROUTES:=172.16.0.0/16 172.19.33.0/24 195.19.32.0/19}"
}
compute_tags() {
TAGS=" base sub $TARGET "
[ "$BOOT" = 1 ] && TAGS="$TAGS boot "
if [ "$TARGET" = router ]; then
TAGS="$TAGS $LOCATION "
[ "$TORRENT" = 1 ] && TAGS="$TAGS torrent "
[ "$OPENVPN" = 1 ] && TAGS="$TAGS openvpn "
if [ "$TAILSCALE" = 1 ]; then
TAGS="$TAGS tailscale "
[ "$TS_EXIT" = 1 ] && TAGS="$TAGS ts_exit "
fi
fi
SUB_LIST="" i=0
for u in $SUBS; do
SUB_LIST="${SUB_LIST:+$SUB_LIST, }sub$i"
i=$((i + 1))
done
export SUB_LIST
}
check_vars() {
[ -n "$SUBS" ] || die "SUBS is empty (subscription URLs)"
case "$TARGET" in router | mobile) ;; *) die "TARGET must be router or mobile" ;; esac
case "$LOCATION" in home | street) ;; *) die "LOCATION must be home or street" ;; esac
if [ "$BOOT" = 1 ]; then
for v in BOOT_SERVER BOOT_UUID BOOT_SNI BOOT_PBK BOOT_SID; do
eval "[ -n \"\${$v}\" ]" || die "$v is empty (BOOT=1)"
done
fi
}
render_file() {
awk -v tags="$TAGS" '
function active(c, neg) {
neg = 0
if (substr(c, 1, 1) == "!") { neg = 1; c = substr(c, 2) }
return (index(tags, " " c " ") > 0) != neg
}
function subst(s, out, i, j) {
out = ""
while ((i = index(s, "${")) > 0) {
j = index(substr(s, i + 2), "}")
if (j == 0) break
out = out substr(s, 1, i - 1) ENVIRON[substr(s, i + 2, j - 1)]
s = substr(s, i + 2 + j)
}
return out s
}
{
line = $0
if ((p = index(line, "#@")) > 0) {
n = split(substr(line, p + 2), cs, ",")
line = substr(line, 1, p - 1)
sub(/[ \t]+$/, "", line)
for (k = 1; k <= n; k++) if (!active(cs[k])) next
}
if ((i = index(line, "${@")) > 0) {
j = index(substr(line, i + 3), "}")
pre = substr(line, 1, i - 1)
post = substr(line, i + 3 + j)
n = split(ENVIRON[substr(line, i + 3, j - 1)], ws, /[ \t\n]+/)
for (k = 1; k <= n; k++) if (ws[k] != "") print subst(pre ws[k] post)
next
}
print subst(line)
}' "$1"
}
# is "<module>.<tag>...[.each]" active? sets EACH
fragment_active() {
EACH=0
_mod=${1%%.*}
case "$TAGS" in *" $_mod "*) ;; *) return 1 ;; esac
_rest=${1#"$_mod"}
_old_ifs=$IFS
IFS=.
for _t in $_rest; do
[ -z "$_t" ] && continue
if [ "$_t" = each ]; then EACH=1; continue; fi
case "$TAGS" in *" $_t "*) ;; *) IFS=$_old_ifs; return 1 ;; esac
done
IFS=$_old_ifs
return 0
}
render_section() {
_out=""
for f in "$TPL_DIR/$1"/*.yaml; do
[ -f "$f" ] || continue
_name=${f##*/}
_name=${_name%.yaml}
fragment_active "${_name#*-}" || continue
if [ "$EACH" = 1 ]; then
i=0
for u in $SUBS; do
SUB_NAME="sub$i" SUB_URL="$u"
export SUB_NAME SUB_URL
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
i=$((i + 1))
done
else
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part"
fi
done
[ -n "$_out" ] || return 0
[ -n "${2:-}" ] && printf "%s\n" "$2"
printf "%s\n" "$_out"
}
render() {
set_defaults
check_vars
compute_tags
export TARGET LOCATION GEOIP_URL GEOSITE_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \
BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \
OVPN_SERVER_IPS OVPN_ROUTES RU_IPS
_first=1
for s in head proxies:proxies providers:proxy-providers sniffer dns groups:proxy-groups rules:rules; do
_dir=${s%%:*}
_hdr=""
[ "$_dir" != "$s" ] && _hdr="${s#*:}:"
_sec=$(render_section "$_dir" "$_hdr")
[ -n "$_sec" ] || continue
[ "$_first" = 1 ] || echo
printf "%s\n" "$_sec"
_first=0
done
}
load_env() {
for e in "$@"; do
[ -f "$e" ] || die "no env file $e"
set -a
. "$e"
set +a
done
}
cmd_render() {
[ $# -gt 0 ] || die "usage: render <env>..."
load_env "$@"
render
}
cmd_build() {
[ -d "$PROFILES_D" ] || die "no $PROFILES_D (see profile.env.example)"
mkdir -p "$PROFILES_OUT"
if [ $# -eq 0 ]; then
for e in "$PROFILES_D"/*.env; do
n=${e##*/}
n=${n%.env}
[ "$n" = common ] || set -- "$@" "$n"
done
fi
for n in "$@"; do
out="$PROFILES_OUT/$n.yaml"
envs="$PROFILES_D/$n.env"
[ -f "$PROFILES_D/common.env" ] && envs="$PROFILES_D/common.env $envs"
# subshell: profiles must not leak variables into each other
# shellcheck disable=SC2086
if (cmd_render $envs) > "$out.tmp"; then
mv "$out.tmp" "$out"
log "built $out"
if command -v mihomo >/dev/null 2>&1; then
mihomo -t -d "$NIKKI_DIR/run" -f "$out" >/dev/null 2>&1 ||
log "warning: mihomo -t failed for $out (run: mihomo -t -d $NIKKI_DIR/run -f $out)"
fi
else
rm -f "$out.tmp"
die "build of $n failed"
fi
done
}
cmd_use() {
[ $# -eq 1 ] || die "usage: use <name>"
[ -f "$PROFILES_OUT/$1.yaml" ] || die "no $PROFILES_OUT/$1.yaml, run build first"
uci set nikki.config.profile="file:$1.yaml"
uci commit nikki
/etc/init.d/nikki restart
log "nikki now runs $1"
if grep -q "^OPENVPN=1" "$PROFILES_D/$1.env" "$PROFILES_D/common.env" 2>/dev/null &&
command -v bmstu-otp.sh >/dev/null 2>&1; then
sleep 5
bmstu-otp.sh refresh
fi
}
# --- router setup -----------------------------------------------------------
core_update() {
cur=$(mihomo -v 2>/dev/null | awk '{print $3; exit}')
if [ "$cur" = "$MIHOMO_VERSION" ]; then
log "mihomo core is $cur"
return 0
fi
case "$(uname -m)" in
aarch64) arch=arm64 ;;
x86_64) arch=amd64 ;;
armv7l) arch=armv7 ;;
mips) arch=mips-softfloat ;;
mipsel | mipsle) arch=mipsle-softfloat ;;
*) die "unknown arch $(uname -m), set the core manually" ;;
esac
url="https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-$arch-$MIHOMO_VERSION.gz"
log "updating mihomo core ${cur:-none} -> $MIHOMO_VERSION"
curl -fL -o /tmp/mihomo.gz "$url" || die "download failed: $url"
gunzip -f /tmp/mihomo.gz && chmod +x /tmp/mihomo || die "unpack failed"
bin=$(command -v mihomo || echo /usr/bin/mihomo)
[ -f "$bin" ] && cp "$bin" "$bin.bak"
mv /tmp/mihomo "$bin"
log "core: $(mihomo -v | head -n 1)"
}
# Tailscale control over port 80 gets broken by the ISP: force 443.
patch_init() {
f=/etc/init.d/nikki
if grep -q TS_FORCE_NOISE_443 "$f"; then
log "init script already has TS_FORCE_NOISE_443"
elif grep -q "procd_append_param env SKIP_SYSTEM_IPV6_CHECK" "$f"; then
sed -i '/procd_append_param env SKIP_SYSTEM_IPV6_CHECK/a\ procd_append_param env TS_FORCE_NOISE_443=true' "$f"
log "added TS_FORCE_NOISE_443 to $f"
else
log "warning: anchor not found in $f, add 'procd_append_param env TS_FORCE_NOISE_443=true' by hand"
fi
}
# nikki skips these ranges before mihomo; Tailscale (100.64/10) and the
# OpenVPN internal nets (172.16/12) must reach mihomo rules.
fix_reserved() {
for net in 100.64.0.0/10 172.16.0.0/12; do
uci -q del_list nikki.proxy.reserved_ip="$net" && log "removed $net from nikki reserved_ip"
done
uci commit nikki
}
install_files() {
for s in mihomo-kit.sh bmstu-otp.sh; do
chmod +x "$KIT_DIR/router/$s"
ln -sf "$KIT_DIR/router/$s" "/usr/bin/$s"
done
mkdir -p "$PROFILES_D"
chmod 700 "$PROFILES_D"
}
enable_otp_cron() {
grep -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null && return 0
echo '* * * * * /usr/bin/bmstu-otp.sh check' >> /etc/crontabs/root
/etc/init.d/cron restart
log "added bmstu-otp.sh check to cron"
}
cmd_install() {
opkg update
if [ ! -x /etc/init.d/nikki ]; then
wget -O - https://github.com/nikkinikki-org/OpenWrt-nikki/raw/refs/heads/main/feed.sh | ash
opkg install nikki luci-app-nikki
fi
for p in curl oath-toolkit; do
opkg list-installed | grep -q "^$p " || opkg install "$p"
done
# curl newer than libcurl -> "Error relocating ... symbol not found"
curl --version >/dev/null 2>&1 || opkg install --force-reinstall libcurl4 curl
install_files
cmd_fix
}
cmd_fix() {
/etc/init.d/nikki stop 2>/dev/null
core_update
patch_init
fix_reserved
/etc/init.d/nikki start
}
# --- setup wizard -----------------------------------------------------------
: "${TTY_IN:=/dev/tty}" "${TTY_OUT:=/dev/tty}"
# ask VAR "question" [default]
ask() {
printf '%s%s: ' "$2" "${3:+ [$3]}" > "$TTY_OUT"
read -r _a < "$TTY_IN" || _a=""
eval "$1=\${_a:-\${3:-}}"
}
# ask_secret VAR "question" (no echo)
ask_secret() {
printf '%s: ' "$2" > "$TTY_OUT"
stty -echo < "$TTY_IN" 2>/dev/null
read -r _a < "$TTY_IN" || _a=""
stty echo < "$TTY_IN" 2>/dev/null
echo > "$TTY_OUT"
eval "$1=\$_a"
}
# yesno VAR "question" y|n -> VAR=1|0
yesno() {
while :; do
ask _yn "$2 (y/n)" "$3"
case "$_yn" in
y | Y | yes | д | Д) eval "$1=1"; return ;;
n | N | no | н | Н) eval "$1=0"; return ;;
esac
done
}
# vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name -> BOOT_* (empty on failure)
parse_vless() {
_l=${1#vless://}
_l=${_l%%#*}
BOOT_UUID=${_l%%@*}
_hp=${_l#*@}
_hp=${_hp%%\?*}
BOOT_SERVER=${_hp%:*}
BOOT_PORT=${_hp##*:}
_q="&${_l#*\?}&"
qv() { _v=${_q#*&$1=}; [ "$_v" = "$_q" ] && return; echo "${_v%%&*}"; }
BOOT_SNI=$(qv sni)
BOOT_PBK=$(qv pbk)
BOOT_SID=$(qv sid)
}
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
wizard() {
{
echo
echo "== mihomo-kit: профиль роутера =="
echo "Ответы сохранятся в $PROFILES_D/common.env (chmod 600)."
echo
echo "Подписки: по одному URL на строку, пустая строка — конец."
} > "$TTY_OUT"
SUBS=""
while :; do
ask _u " URL"
[ -n "$_u" ] || break
SUBS="${SUBS:+$SUBS }$_u"
done
[ -n "$SUBS" ] || die "нужна хотя бы одна подписка"
ask _vless "BOOT: vless:// ссылка seed-ноды (пусто = без BOOT)"
BOOT=0
if [ -n "$_vless" ]; then
parse_vless "$_vless"
[ -n "$BOOT_SERVER" ] && [ -n "$BOOT_PBK" ] || die "не разобрал vless-ссылку: нужны host, pbk, sid"
BOOT=1
fi
yesno TORRENT "Торренты через TORRENT-SEL (порты 20000-20199)" y
ask RU_IPS "Доп. IP через RU (CIDR через пробел)" ""
yesno OPENVPN "OpenVPN BMSTU" n
if [ "$OPENVPN" = 1 ]; then
while [ ! -f "$NIKKI_DIR/bmstu.ovpn" ]; do
ask _dummy "Положи .ovpn в $NIKKI_DIR/bmstu.ovpn (scp -O file.ovpn root@router:$NIKKI_DIR/bmstu.ovpn) и нажми Enter"
done
ask VPN_USERNAME " логин"
ask_secret VPN_PASSWORD " пароль (без OTP)"
ask_secret TOTP_SECRET " TOTP-секрет (base32 из QR)"
fi
yesno TAILSCALE "Tailscale" n
if [ "$TAILSCALE" = 1 ]; then
ask TS_HOSTNAME " имя ноды" "$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo"
ask TS_DOMAINS " split-DNS домены тейлнета кроме *.ts.net (через пробел)" ""
fi
umask 077
{
echo "# written by mihomo-kit.sh setup; edit and run: mihomo-kit.sh build"
echo "TARGET=router"
echo "SUBS=$(q "$SUBS")"
echo "BOOT=$BOOT"
if [ "$BOOT" = 1 ]; then
for v in BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI BOOT_PBK BOOT_SID; do
eval "echo \"$v=\$(q \"\$$v\")\""
done
fi
echo "TORRENT=$TORRENT"
echo "RU_IPS=$(q "$RU_IPS")"
echo "OPENVPN=$OPENVPN"
echo "TAILSCALE=$TAILSCALE"
[ "$TAILSCALE" = 1 ] && echo "TS_HOSTNAME=$(q "$TS_HOSTNAME")" && echo "TS_DOMAINS=$(q "$TS_DOMAINS")"
true
} > "$PROFILES_D/common.env"
if [ "$OPENVPN" = 1 ]; then
{
echo "# written by mihomo-kit.sh setup"
echo "VPN_USERNAME=$(q "$VPN_USERNAME")"
echo "VPN_PASSWORD=$(q "$VPN_PASSWORD")"
echo "TOTP_SECRET=$(q "$TOTP_SECRET")"
} > "$NIKKI_DIR/bmstu.env"
fi
for f in "$KIT_DIR"/presets/*.env; do
[ -f "$PROFILES_D/${f##*/}" ] || cp "$f" "$PROFILES_D/"
done
umask 022
}
cmd_setup() {
[ -r "$TTY_IN" ] || die "setup needs a terminal (run it over ssh)"
cmd_install
_redo=1
if [ -f "$PROFILES_D/common.env" ]; then
yesno _redo "$PROFILES_D/common.env уже есть. Ответить на вопросы заново" n
fi
[ "$_redo" = 1 ] && wizard
cmd_build
if grep -q "^OPENVPN=1" "$PROFILES_D/common.env"; then
enable_otp_cron
echo "OTP сейчас: $(bmstu-otp.sh otp) — сверь с приложением-генератором" > "$TTY_OUT"
fi
_profiles=$(cd "$PROFILES_D" && ls *.env | sed 's/\.env$//' | grep -v '^common$' | tr '\n' ' ')
ask _start "Какой профиль включить ($_profiles)" home
cmd_use "$_start"
{
echo
echo "Готово. Дальше:"
echo " mihomo-kit.sh use street|home переключить профиль"
echo " bmstu-otp.sh off|on|status OpenVPN (одна сессия на сервере)"
grep -q "^TAILSCALE=1" "$PROFILES_D/common.env" &&
echo " Tailscale: открой любой 100.x адрес, потом: grep 'To start' /var/log/nikki/core.log"
echo " mihomo-kit.sh fix после обновления пакета nikki"
} > "$TTY_OUT"
}
cmd_update() {
tmp=$(mktemp -d)
log "downloading $KIT_URL"
wget -qO "$tmp/kit.tgz" "$KIT_URL" || die "download failed"
tar xzf "$tmp/kit.tgz" -C "$tmp" || die "bad archive"
src=$(dirname "$(find "$tmp" -path '*/router/mihomo-kit.sh' | head -n 1)")
[ -n "$src" ] && [ "$src" != . ] || die "no router/mihomo-kit.sh in the archive"
src=${src%/router}
for d in templates presets router; do
rm -rf "${KIT_DIR:?}/$d"
cp -r "$src/$d" "$KIT_DIR/$d"
done
rm -rf "$tmp"
install_files
cmd_build
cur=$(uci -q get nikki.config.profile)
log "kit updated; to apply: mihomo-kit.sh use $(basename "${cur#file:}" .yaml)"
}
case "${1:-}" in
render) shift; cmd_render "$@" ;;
build) shift; cmd_build "$@" ;;
use) shift; cmd_use "$@" ;;
setup) cmd_setup ;;
update) cmd_update ;;
install) cmd_install ;;
fix) cmd_fix ;;
*) sed -n '2,22p' "$SELF" >&2; exit 2 ;;
esac