From 2557a9aa498af037a309dac4602fdcda26884907 Mon Sep 17 00:00:00 2001 From: Sam Latsin Date: Thu, 8 Oct 2026 00:57:28 +0300 Subject: [PATCH] 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 --- .gitignore | 10 + README.md | 152 ++++++ install.sh | 31 ++ presets/home.env | 2 + presets/street.env | 2 + router/bmstu-otp.sh | 264 +++++++++++ router/bmstu.env.example | 17 + router/mihomo-kit.sh | 519 +++++++++++++++++++++ router/profile.env.example | 43 ++ templates/dns/10-base.yaml | 29 ++ templates/groups/10-boot.yaml | 3 + templates/groups/20-sub.yaml | 17 + templates/groups/30-torrent.yaml | 10 + templates/groups/40-openvpn.yaml | 3 + templates/groups/41-openvpn.street.yaml | 7 + templates/groups/50-tailscale.yaml | 3 + templates/groups/51-tailscale.ts_exit.yaml | 6 + templates/groups/90-base.yaml | 3 + templates/groups/91-torrent.yaml | 3 + templates/head/10-base.yaml | 7 + templates/providers/10-sub.each.yaml | 15 + templates/providers/20-openvpn.yaml | 10 + templates/proxies/10-boot.yaml | 15 + templates/proxies/20-tailscale.yaml | 11 + templates/rules/10-tailscale.yaml | 4 + templates/rules/20-openvpn.yaml | 7 + templates/rules/30-base.yaml | 3 + templates/rules/40-base.yaml | 1 + templates/rules/50-torrent.yaml | 1 + templates/rules/90-base.yaml | 4 + templates/sniffer/10-base.yaml | 12 + tests/fixtures/common.env | 8 + tests/fixtures/mobile.env | 1 + tests/fixtures/router-home.env | 3 + tests/fixtures/router-minimal.env | 4 + tests/fixtures/router-street.env | 5 + tools/build-web.py | 21 + tools/push.sh | 11 + tools/render.js | 22 + tools/test.sh | 31 ++ web/engine.js | 142 ++++++ web/index.html | 469 +++++++++++++++++++ web/index.src.html | 304 ++++++++++++ 43 files changed, 2235 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 install.sh create mode 100644 presets/home.env create mode 100644 presets/street.env create mode 100755 router/bmstu-otp.sh create mode 100644 router/bmstu.env.example create mode 100755 router/mihomo-kit.sh create mode 100644 router/profile.env.example create mode 100644 templates/dns/10-base.yaml create mode 100644 templates/groups/10-boot.yaml create mode 100644 templates/groups/20-sub.yaml create mode 100644 templates/groups/30-torrent.yaml create mode 100644 templates/groups/40-openvpn.yaml create mode 100644 templates/groups/41-openvpn.street.yaml create mode 100644 templates/groups/50-tailscale.yaml create mode 100644 templates/groups/51-tailscale.ts_exit.yaml create mode 100644 templates/groups/90-base.yaml create mode 100644 templates/groups/91-torrent.yaml create mode 100644 templates/head/10-base.yaml create mode 100644 templates/providers/10-sub.each.yaml create mode 100644 templates/providers/20-openvpn.yaml create mode 100644 templates/proxies/10-boot.yaml create mode 100644 templates/proxies/20-tailscale.yaml create mode 100644 templates/rules/10-tailscale.yaml create mode 100644 templates/rules/20-openvpn.yaml create mode 100644 templates/rules/30-base.yaml create mode 100644 templates/rules/40-base.yaml create mode 100644 templates/rules/50-torrent.yaml create mode 100644 templates/rules/90-base.yaml create mode 100644 templates/sniffer/10-base.yaml create mode 100644 tests/fixtures/common.env create mode 100644 tests/fixtures/mobile.env create mode 100644 tests/fixtures/router-home.env create mode 100644 tests/fixtures/router-minimal.env create mode 100644 tests/fixtures/router-street.env create mode 100755 tools/build-web.py create mode 100755 tools/push.sh create mode 100755 tools/render.js create mode 100755 tools/test.sh create mode 100644 web/engine.js create mode 100644 web/index.html create mode 100644 web/index.src.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a13053 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# secrets and real configs never go in here +*.env +!tests/fixtures/*.env +!presets/*.env +*.ovpn +/configs/ +/reference/ + +.DS_Store +__pycache__/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..35b3f19 --- /dev/null +++ b/README.md @@ -0,0 +1,152 @@ +# mihomo-kit + +Конфиги mihomo из одного набора шаблонов: роутер под nikki (профили «дом» и «улица») +и телефон (FlClash). Подписки через BOOT-ноду, `ru-inside` напрямую, остальные `.ru` +через RU, опционально OpenVPN с TOTP и Tailscale. + +## Установка на роутер + +OpenWrt с интернетом, по ssh на роутере: + +```sh +wget -qO- https://git.sam-hub.net/sam/mihomo-kit/raw/branch/main/install.sh | sh +``` + +Без доступа к репозиторию с роутера — с компьютера: + +```sh +tools/push.sh root@192.168.32.1 +ssh root@192.168.32.1 sh /etc/nikki/kit/install.sh +``` + +Установщик ставит nikki (если нет), правильное ядро и фиксы, затем спрашивает: +подписки, vless-ссылку BOOT, торренты, OpenVPN (логин, пароль, TOTP-секрет), Tailscale — +собирает профили `home` и `street` и включает выбранный. + +Перед установкой: +- **zeroblock / podkop выключить** — он перехватывает трафик самого роутера; +- для OpenVPN положить `.ovpn` в `/etc/nikki/bmstu.ovpn` (установщик подождёт): + `scp -O file.ovpn root@192.168.32.1:/etc/nikki/bmstu.ovpn`. + +После установки, если включён Tailscale: открыть с любого устройства адрес `100.x.y.z`, затем + +```sh +grep 'To start' /var/log/nikki/core.log +``` + +открыть ссылку, войти, в админке Tailscale — **Disable key expiry** для ноды. + +## Каждый день + +```sh +mihomo-kit.sh use street # уехал на белые списки +mihomo-kit.sh use home # вернулся + +bmstu-otp.sh off # OpenVPN выключить: освободить сессию для другого устройства +bmstu-otp.sh on # включить обратно +bmstu-otp.sh status +``` + +На сервере BMSTU одна сессия на пользователя. `off` закрывает туннель в mihomo и не даёт +cron поднять его снова; трафик в сети BMSTU сразу получает отказ. mihomo не отправляет +серверу EXIT, поэтому сервер держит старую сессию до своего `ping-restart` — до ~5 минут, +потом можно подключаться с другого устройства. + +На «улице» OpenVPN идёт через группу `OVPN-EXIT` — один раз выбрать в дашборде RU-ноду. + +## Обслуживание + +```sh +mihomo-kit.sh update # свежий кит из репозитория + пересборка профилей +mihomo-kit.sh fix # после обновления пакета nikki (он затирает ядро и init-скрипт) +mihomo-kit.sh build # после правки /etc/nikki/profiles.d/*.env +``` + +Где что лежит на роутере: + +| | | +|---|---| +| `/etc/nikki/kit/` | кит: шаблоны, пресеты, скрипты | +| `/etc/nikki/profiles.d/common.env` | подписки, BOOT, модули (секреты, 600) | +| `/etc/nikki/profiles.d/home.env`, `street.env` | профили поверх common.env | +| `/etc/nikki/profiles/*.yaml` | собранные конфиги, их запускает nikki | +| `/etc/nikki/bmstu.env`, `bmstu.ovpn` | OpenVPN: логин, пароль, TOTP-секрет | +| `/etc/nikki/run/tailscale/` | ключ ноды Tailscale — не удалять | + +Новый профиль = новый файл в `profiles.d/` (например `LOCATION=home` + `OPENVPN=0`), +затем `mihomo-kit.sh build && mihomo-kit.sh use <имя>`. Все опции — в +[router/profile.env.example](router/profile.env.example). + +### Что чинят `install` / `fix` + +| Фикс | Зачем | +|---|---| +| ядро mihomo `v1.19.32` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие | +| `TS_FORCE_NOISE_443=true` в `/etc/init.d/nikki` | провайдер ломает control-соединение Tailscale на порту 80, вход зависает | +| убрать `100.64.0.0/10`, `172.16.0.0/12` из `nikki.proxy.reserved_ip` | иначе nikki пускает Tailscale и внутренние сети BMSTU мимо mihomo | +| cron `bmstu-otp.sh check` раз в минуту | поднимает OpenVPN со свежим OTP, если туннель упал | +| переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` | + +## Телефон (FlClash) + +Открыть [web/index.html](web/index.html) (из репозитория или со своего хостинга) → +«Телефон» → подписки и vless-ссылка BOOT → «Скачать» → FlClash: Профили → + → Файл. +Страница всё считает в браузере и никуда ничего не отправляет. + +## Профили + +| | роутер дом | роутер улица | телефон | +|---|---|---|---| +| подписки через BOOT | ✓ | ✓ | ✓ | +| `ru-inside` напрямую, остальные `.ru` через RU | ✓ | ✓ | ✓ | +| торренты (порты 20000–20199) | ✓ | ✓ | — | +| OpenVPN | напрямую | через `OVPN-EXIT` (RU-нода) | — | +| Tailscale | напрямую | напрямую или `TS-EXIT`* | — | + +\* Tailscale через `dialer-proxy` работает только с нодами ss / hysteria2 / tuic / socks5: +vless/vmess/trojan в mihomo не дают ему UDP без адреса назначения. `TS_EXIT=1` +включает группу `TS-EXIT` из таких нод. + +## Если что-то не работает + +- **OpenVPN** `tunnel did not come up`: `bmstu-otp.sh debug` покажет настоящую ошибку. + `read hard reset response` — до сервера не доходят пакеты (zeroblock, правило для IP + сервера); `AUTH_FAILED` — формат пароля (`PASS_FORMAT` в `bmstu.env`, сейчас `otp-last`). +- **Tailscale** молчит: `grep '\[Tailscale\]' /var/log/nikki/core.log`. Строк нет — + проверить `reserved_ip`; висит без ссылки — `TS_FORCE_NOISE_443` в окружении: + `tr '\0' '\n' < /proc/$(pidof mihomo)/environ | grep TS_`. Ошибка первого запуска + Tailscale запоминается до перезапуска mihomo — после правок перезапускать nikki. + +## Разработка + +``` +install.sh загрузчик: кит в /etc/nikki/kit + mihomo-kit.sh setup +templates/ фрагменты конфига (общие для скрипта и страницы) +presets/ профили, которые setup кладёт в profiles.d +router/ + mihomo-kit.sh сборка, setup-мастер, use/update/fix + bmstu-otp.sh OpenVPN BMSTU: TOTP в пароле, cron-сторож, on/off +web/ страница-конструктор: engine.js + index.src.html → index.html +tools/ push.sh, test.sh, build-web.py, render.js +tests/fixtures/ профили для test.sh (фиктивные секреты) +``` + +Шаблоны: `templates/<секция>/NN-<модуль>[.<тег>...][.each].yaml`; секции собираются в +порядке head, proxies, providers, sniffer, dns, groups, rules, файлы — по имени. + +- файл включается, если активны модуль и все теги; `.each` — по разу на подписку + (`${SUB_NAME}`, `${SUB_URL}`); +- `строка #@тег[,!тег]` — строка остаётся, только если условия выполнены; +- `${@VAR}` — строка повторяется для каждого слова из `VAR`; +- `${VAR}` — подстановка. + +Теги: `base`, `sub`, `router`|`mobile`, `home`|`street` (роутер), `boot`, `torrent`, +`openvpn`, `tailscale`, `ts_exit`. Значения по умолчанию — `set_defaults` в +`router/mihomo-kit.sh` и `DEFAULTS` в `web/engine.js` (держать одинаковыми). + +После правки шаблонов или движка: + +```sh +MIHOMO=/path/to/mihomo tools/test.sh # sh и JS дают одинаковый YAML, mihomo -t проходит +tools/build-web.py # пересобрать web/index.html +``` diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..888c904 --- /dev/null +++ b/install.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# One-command setup of mihomo-kit on OpenWrt (nikki), over ssh on the router: +# wget -qO- https://git.sam-hub.net/sam/mihomo-kit/raw/branch/main/install.sh | sh +# or after tools/push.sh from a computer: +# sh /etc/nikki/kit/install.sh +# Installs nikki if needed, asks a few questions, builds the profiles and starts one. +set -eu +KIT_URL=${KIT_URL:-https://git.sam-hub.net/sam/mihomo-kit/archive/main.tar.gz} +KIT_DIR=/etc/nikki/kit + +here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo /nonexistent) +mkdir -p "$KIT_DIR" +if [ -f "$here/router/mihomo-kit.sh" ]; then + [ "$here" = "$KIT_DIR" ] || cp -r "$here/templates" "$here/presets" "$here/router" "$KIT_DIR/" +else + tmp=/tmp/mihomo-kit.$$ + mkdir -p "$tmp" + echo "downloading $KIT_URL" + wget -qO "$tmp/kit.tgz" "$KIT_URL" + tar xzf "$tmp/kit.tgz" -C "$tmp" + 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; } + src=${src%/router/mihomo-kit.sh} + for d in templates presets router; do + rm -rf "${KIT_DIR:?}/$d" + cp -r "$src/$d" "$KIT_DIR/" + done + rm -rf "$tmp" +fi +# stdin may be the piped script: the wizard reads answers from /dev/tty +exec sh "$KIT_DIR/router/mihomo-kit.sh" setup diff --git a/presets/home.env b/presets/home.env new file mode 100644 index 0000000..a284ee0 --- /dev/null +++ b/presets/home.env @@ -0,0 +1,2 @@ +# home: OpenVPN/Tailscale go direct +LOCATION=home diff --git a/presets/street.env b/presets/street.env new file mode 100644 index 0000000..83e2645 --- /dev/null +++ b/presets/street.env @@ -0,0 +1,2 @@ +# street (whitelisted network): OpenVPN goes through OVPN-EXIT, pick a RU node in the dashboard +LOCATION=street diff --git a/router/bmstu-otp.sh b/router/bmstu-otp.sh new file mode 100755 index 0000000..7495b44 --- /dev/null +++ b/router/bmstu-otp.sh @@ -0,0 +1,264 @@ +#!/bin/sh +# OpenVPN (BMSTU) + TOTP for mihomo / nikki on OpenWrt. +# +# mihomo has no static-challenge support: the password in the proxy config is +# static, and the tunnel is started lazily on first use. This script builds the +# file proxy-provider from the .ovpn with a fresh OTP baked into the password, +# reloads the provider via the mihomo API and immediately warms the tunnel up +# (delay test) while the code is still valid. After that the server's +# auth-token (if pushed) keeps rekeys alive without an OTP. +# +# Usage: +# bmstu-otp.sh otp print the current TOTP code +# bmstu-otp.sh authfile print username/password lines (openvpn auth-user-pass file) +# bmstu-otp.sh refresh regenerate provider with fresh OTP, reload, warm up +# bmstu-otp.sh check warm-up test; refresh only if the tunnel is dead (cron) +# bmstu-otp.sh off close the tunnel and keep it closed (BMSTU traffic is rejected); +# frees the single server session for another client +# (the server drops the old session after its ping-restart, up to ~5 min) +# bmstu-otp.sh on allow the tunnel again and bring it up +# bmstu-otp.sh status on/off and whether the tunnel answers +# bmstu-otp.sh debug show the real handshake error in the nikki log + +set -u + +ENV_FILE="${ENV_FILE:-/etc/nikki/bmstu.env}" +[ -f "$ENV_FILE" ] && . "$ENV_FILE" + +: "${OVPN_FILE:=/etc/nikki/bmstu.ovpn}" +: "${PROVIDER_FILE:=/etc/nikki/run/providers/bmstu.yaml}" +: "${PROVIDER_NAME:=bmstu}" +: "${PROXY_NAME:=bmstu-ovpn}" +: "${GROUP_NAME:=BMSTU}" +# API address/secret: from nikki's mixin settings unless set in the env file +uci_get() { uci -q get "$1" 2>/dev/null; } +: "${API:=http://127.0.0.1:$(p=$(uci_get nikki.mixin.api_listen); echo "${p##*:}" | grep -E '^[0-9]+$' || echo 9090)}" +: "${API_SECRET:=$(uci_get nikki.mixin.api_secret)}" +# while this file exists the tunnel stays off (bmstu-otp.sh off/on) +: "${OFF_FLAG:=/etc/nikki/bmstu.off}" +: "${CHECK_URL:=https://www.bmstu.ru}" +# ms, must exceed HANDSHAKE_TIMEOUT (max 32767) +: "${CHECK_TIMEOUT:=25000}" +# otp-last - (what the BMSTU server accepts) +# otp-first - +# scrv1 - what openvpn sends for "static-challenge ... 1": SCRV1:b64(pass):b64(otp) +: "${PASS_FORMAT:=otp-last}" +: "${TOTP_DIGITS:=6}" +: "${TOTP_PERIOD:=30}" +# do not use a code that expires sooner than this (seconds) +: "${TOTP_MIN_LEFT:=8}" +# 0 = omit (handshake errors then show up in "dial ... error:" log lines) +: "${HANDSHAKE_TIMEOUT:=20}" +# nikki mixed port and its login, used by "debug" +: "${MIXED_PORT:=$(uci_get nikki.mixin.mixed_port || echo 7890)}" +: "${MIXED_AUTH:=$(u=$(uci_get 'nikki.@authentication[0].username') && echo "$u:$(uci_get 'nikki.@authentication[0].password')")}" + +log() { logger -t bmstu-otp "$*" 2>/dev/null; echo "$*" >&2; } +die() { log "error: $*"; exit 1; } + +# --- TOTP (RFC 6238, HMAC-SHA1) -------------------------------------------- + +base32_to_hex() { + echo "$1" | tr -d ' =-' | tr 'a-z' 'A-Z' | awk ' + BEGIN { a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" } + { + bits = "" + for (i = 1; i <= length($0); i++) { + v = index(a, substr($0, i, 1)) - 1 + if (v < 0) { print "bad base32" > "/dev/stderr"; exit 1 } + for (b = 16; b >= 1; b /= 2) { bits = bits (v >= b ? "1" : "0"); if (v >= b) v -= b } + } + out = "" + for (i = 1; i + 7 <= length(bits); i += 8) { + n = 0 + for (j = 0; j < 8; j++) n = n * 2 + substr(bits, i + j, 1) + out = out sprintf("%02x", n) + } + print out + }' +} + +totp() { + now=$(date +%s) + if command -v oathtool >/dev/null 2>&1; then + oathtool --totp -b -d "$TOTP_DIGITS" -s "${TOTP_PERIOD}s" "$TOTP_SECRET" + return + fi + command -v openssl >/dev/null 2>&1 || die "need oathtool or openssl (opkg install oath-toolkit | openssl-util)" + key=$(base32_to_hex "$TOTP_SECRET") || die "TOTP_SECRET is not valid base32" + counter=$((now / TOTP_PERIOD)) + # 8-byte big-endian counter as octal escapes (busybox printf has no \x) + esc="" i=7 + while [ $i -ge 0 ]; do + esc="$esc$(printf '\\%03o' $(( (counter >> (i * 8)) & 255 )))" + i=$((i - 1)) + done + mac=$(printf "$esc" | openssl dgst -sha1 -mac HMAC -macopt "hexkey:$key" | awk '{print $NF}') + off=$(( 0x$(echo "$mac" | cut -c40) * 2 + 1 )) + word=$(echo "$mac" | cut -c"$off-$((off + 7))") + mod=1 i=0 + while [ $i -lt "$TOTP_DIGITS" ]; do mod=$((mod * 10)); i=$((i + 1)); done + printf "%0${TOTP_DIGITS}d\n" $(( (0x$word & 0x7fffffff) % mod )) +} + +# wait for a fresh window if the current code is about to expire +fresh_totp() { + left=$((TOTP_PERIOD - $(date +%s) % TOTP_PERIOD)) + [ "$left" -lt "$TOTP_MIN_LEFT" ] && sleep "$left" + totp +} + +b64() { printf '%s' "$1" | openssl base64 -A 2>/dev/null || printf '%s' "$1" | base64 | tr -d '\n'; } + +make_password() { + otp=$1 + case "$PASS_FORMAT" in + scrv1) echo "SCRV1:$(b64 "$VPN_PASSWORD"):$(b64 "$otp")" ;; + otp-first) echo "$otp$VPN_PASSWORD" ;; + otp-last) echo "$VPN_PASSWORD$otp" ;; + *) die "unknown PASS_FORMAT=$PASS_FORMAT" ;; + esac +} + +# --- provider generation ---------------------------------------------------- + +# print inline ... block from the .ovpn, YAML-indented, no comments +ovpn_block() { + awk -v tag="$1" ' + $0 ~ "^<" tag ">" { on = 1; next } + $0 ~ "^" { on = 0; next } + on && $0 !~ /^#/ && NF { print " " $0 } + ' "$OVPN_FILE" +} + +ovpn_opt() { awk -v k="$1" '$1 == k { $1 = ""; sub(/^ /, ""); print; exit }' "$OVPN_FILE"; } + +yaml_str() { printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')"; } + +write_provider() { + [ -f "$OVPN_FILE" ] || die "no $OVPN_FILE" + [ -n "${VPN_USERNAME:-}" ] || die "VPN_USERNAME is empty" + [ -n "${VPN_PASSWORD:-}" ] || die "VPN_PASSWORD is empty" + [ -n "${TOTP_SECRET:-}" ] || die "TOTP_SECRET is empty" + + # first "remote host port proto" line + set -- $(ovpn_opt remote) + host=$1 port=${2:-1194} proto=${3:-udp} + case "$proto" in tcp*) proto=tcp ;; *) proto=udp ;; esac + fallback=$(ovpn_opt data-ciphers-fallback) + + pass=$(make_password "$(fresh_totp)") || exit 1 + + mkdir -p "$(dirname "$PROVIDER_FILE")" + tmp="$PROVIDER_FILE.tmp" + { + echo "# generated by bmstu-otp.sh at $(date '+%F %T') - do not edit" + echo "proxies:" + echo " - name: $PROXY_NAME" + echo " type: openvpn" + echo " server: $host" + echo " port: $port" + echo " proto: $proto" + echo " udp: true" + echo " username: $(yaml_str "$VPN_USERNAME")" + echo " password: $(yaml_str "$pass")" + # the server pushes AES-256-GCM + echo " data-ciphers: [AES-256-GCM, AES-128-GCM]" + [ -n "$fallback" ] && echo " data-ciphers-fallback: $fallback" + echo " ping: 10" + echo " ping-restart: 60" + [ "$HANDSHAKE_TIMEOUT" -gt 0 ] && echo " handshake-timeout: $HANDSHAKE_TIMEOUT" + for t in ca cert key tls-crypt tls-auth; do + body=$(ovpn_block "$t") + [ -n "$body" ] && printf ' %s: |\n%s\n' "$t" "$body" + done + kd=$(ovpn_opt key-direction) + [ -n "$kd" ] && echo " key-direction: \"$kd\"" + true + } > "$tmp" && chmod 600 "$tmp" && mv "$tmp" "$PROVIDER_FILE" +} + +# --- mihomo API ------------------------------------------------------------- + +api() { + method=$1 path=$2 + shift 2 + if [ -n "$API_SECRET" ]; then + curl -fsS -m 30 -X "$method" -H "Authorization: Bearer $API_SECRET" "$@" "$API$path" + else + curl -fsS -m 30 -X "$method" "$@" "$API$path" + fi +} + +alive() { + api GET "/proxies/$GROUP_NAME/delay" -G \ + --data-urlencode "url=$CHECK_URL" --data-urlencode "timeout=$CHECK_TIMEOUT" >/dev/null 2>&1 +} + +# provider with a single reject proxy: the old tunnel gets closed with the +# outdated proxy, and BMSTU traffic fails fast instead of hanging +write_off_provider() { + mkdir -p "$(dirname "$PROVIDER_FILE")" + printf '# bmstu-otp.sh off\nproxies:\n - name: %s-off\n type: reject\n' "$PROVIDER_NAME" > "$PROVIDER_FILE" +} + +refresh() { + [ -f "$OFF_FLAG" ] && die "OpenVPN is off (bmstu-otp.sh on)" + write_provider + api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" + # handshake right now, while the OTP is valid + if alive; then + log "tunnel is up" + else + log "tunnel did not come up after refresh (check nikki log)" + return 1 + fi +} + +case "${1:-}" in + otp) totp ;; + # auth-user-pass file for testing with the real openvpn client + authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password "$(fresh_totp)")" ;; + refresh) refresh ;; + check) + [ -f "$OFF_FLAG" ] && exit 0 + alive || { log "tunnel is down, refreshing"; refresh; } + ;; + off) + touch "$OFF_FLAG" + write_off_provider + api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" + log "OpenVPN off: tunnel closed, the server frees the session within its ping-restart (~5 min)" + ;; + on) + rm -f "$OFF_FLAG" + refresh + ;; + status) + if [ -f "$OFF_FLAG" ]; then + echo "off" + elif alive; then + echo "on, tunnel is up" + else + echo "on, tunnel is down (cron brings it up within a minute)" + fi + ;; + # show the real handshake error: no handshake-timeout, debug log, + # one request through the mixed port so the dial error gets logged + debug) + HANDSHAKE_TIMEOUT=0 write_provider + api PATCH /configs -H 'Content-Type: application/json' -d '{"log-level":"debug"}' >/dev/null + api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)" + echo "password format: $PASS_FORMAT, length $(sed -n 's/^ password: "\(.*\)"$/\1/p' "$PROVIDER_FILE" | wc -c)" + curl -skS -m 25 -o /dev/null -w "request via mihomo: http %{http_code}\n" \ + ${MIXED_AUTH:+--proxy-user "$MIXED_AUTH"} \ + -x "http://127.0.0.1:$MIXED_PORT" "${DEBUG_URL:-https://195.19.34.102/}" + # let LAN clients trigger a handshake and hit the 5s dial timeout + sleep 20 + echo "--- log ---" + { cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -iE "openvpn|bmstu" | tail -n 30 + echo "--- handshake errors ---" + { cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -E "OpenVPN" | tail -n 5 + ;; + *) echo "usage: $0 otp|authfile|refresh|check|on|off|status|debug" >&2; exit 2 ;; +esac diff --git a/router/bmstu.env.example b/router/bmstu.env.example new file mode 100644 index 0000000..e8e96c4 --- /dev/null +++ b/router/bmstu.env.example @@ -0,0 +1,17 @@ +# /etc/nikki/bmstu.env on the router, chmod 600 (mihomo-kit.sh setup writes it) +VPN_USERNAME="username" +VPN_PASSWORD="your-password" +# base32 secret from the TOTP QR (otpauth://totp/...?secret=XXXX) +TOTP_SECRET="XXXXXXXXXXXXXXXX" +# otp-last (default: ) | otp-first | scrv1 +#PASS_FORMAT=otp-last + +# nikki API: read from uci (nikki.mixin.api_listen / api_secret) unless set here +#API="http://127.0.0.1:9090" +#API_SECRET="" + +# something reachable only (or at least) through the VPN +#CHECK_URL="https://www.bmstu.ru" + +#OVPN_FILE=/etc/nikki/bmstu.ovpn +#PROVIDER_FILE=/etc/nikki/run/providers/bmstu.yaml diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh new file mode 100755 index 0000000..7c0c4d7 --- /dev/null +++ b/router/mihomo-kit.sh @@ -0,0 +1,519 @@ +#!/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/.env one file per profile (home, street, ...) +# /etc/nikki/profiles/.yaml generated, what nikki runs +# +# Usage: +# mihomo-kit.sh setup first run: install + questions + build + start +# mihomo-kit.sh build [name...] profiles.d/.env -> profiles/.yaml (default: all) +# mihomo-kit.sh use switch nikki to profiles/.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 ... 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-[....][.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 "....[.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 ..." + 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 " + [ -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 diff --git a/router/profile.env.example b/router/profile.env.example new file mode 100644 index 0000000..b2c7711 --- /dev/null +++ b/router/profile.env.example @@ -0,0 +1,43 @@ +# mihomo-kit profile. On the router: +# /etc/nikki/profiles.d/common.env shared part (secrets: subscriptions, BOOT) +# /etc/nikki/profiles.d/.env per profile, overrides common.env +# e.g. home.env = "LOCATION=home", street.env = "LOCATION=street". +# Then: mihomo-kit.sh build && mihomo-kit.sh use home +# chmod 600: this file holds secrets. + +# router | mobile (mobile: no torrent/OpenVPN/Tailscale, FlClash-style DNS) +TARGET=router +# home: OpenVPN/Tailscale go direct; street: OpenVPN goes through OVPN-EXIT (RU node) +LOCATION=home + +# subscription URLs, space separated -> sub0, sub1, ... +SUBS="https://sub.example.com/sub/xxxx" + +# BOOT: whitelisted vless reality node used to download the subscriptions +BOOT=1 +BOOT_SERVER=1.2.3.4 +BOOT_PORT=443 +BOOT_UUID=00000000-0000-0000-0000-000000000000 +BOOT_SNI=eh.vk.ru +BOOT_PBK=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +BOOT_SID=xxxxxxxxxxxxxxxx + +# torrent group for clients using source ports 20000-20199 +TORRENT=1 + +# extra IPs routed through RU, space separated CIDRs +RU_IPS="194.190.191.112/32" + +# OpenVPN (BMSTU), needs /etc/nikki/bmstu.env and bmstu-otp.sh +OPENVPN=0 +#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" + +# Tailscale (first login: URL in /var/log/nikki/core.log) +TAILSCALE=0 +TS_HOSTNAME=fudy-mihomo +# split-DNS domains of the tailnet besides *.ts.net, space separated +TS_DOMAINS="" +# 1 = Tailscale through TS-EXIT (only ss/hysteria2/tuic nodes work for it) +TS_EXIT=0 diff --git a/templates/dns/10-base.yaml b/templates/dns/10-base.yaml new file mode 100644 index 0000000..862ff94 --- /dev/null +++ b/templates/dns/10-base.yaml @@ -0,0 +1,29 @@ +dns: + enable: true + ipv6: false + respect-rules: true + enhanced-mode: fake-ip + fake-ip-range: 198.18.0.1/16 + fake-ip-filter: + - '*.lan' + - '*.local' #@router + - '+.ru' + - '+.xn--p1ai' #@router + - rule-set:ru-inside #@router + + default-nameserver: + - 77.88.8.8 + - 1.1.1.1 #@router + - 223.5.5.5 #@mobile + + proxy-server-nameserver: + - https://77.88.8.8/dns-query + + direct-nameserver: + - 77.88.8.8 + - 77.88.8.1 + + nameserver: + - https://1.1.1.1/dns-query #@router + - https://dns.google/dns-query + - https://1.1.1.1/dns-query #@mobile diff --git a/templates/groups/10-boot.yaml b/templates/groups/10-boot.yaml new file mode 100644 index 0000000..7f68d55 --- /dev/null +++ b/templates/groups/10-boot.yaml @@ -0,0 +1,3 @@ + - name: BOOT + type: select + proxies: [seed] diff --git a/templates/groups/20-sub.yaml b/templates/groups/20-sub.yaml new file mode 100644 index 0000000..6abd759 --- /dev/null +++ b/templates/groups/20-sub.yaml @@ -0,0 +1,17 @@ + - name: RU + type: url-test + use: [${SUB_LIST}] + filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск" + url: "https://ya.ru" + interval: 300 + tolerance: 50 + lazy: false + + - name: FOREIGN + type: url-test + use: [${SUB_LIST}] + exclude-filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск" + url: "https://www.gstatic.com/generate_204" + interval: 300 + tolerance: 50 + lazy: false diff --git a/templates/groups/30-torrent.yaml b/templates/groups/30-torrent.yaml new file mode 100644 index 0000000..66b28e7 --- /dev/null +++ b/templates/groups/30-torrent.yaml @@ -0,0 +1,10 @@ + - name: TORRENT + type: url-test + use: [${SUB_LIST}] + filter: "(?i)torrent|\\[tor\\]" + url: "https://www.gstatic.com/generate_204" + interval: 300 + timeout: 6000 + tolerance: 500 + max-failed-times: 5 + lazy: false diff --git a/templates/groups/40-openvpn.yaml b/templates/groups/40-openvpn.yaml new file mode 100644 index 0000000..2527694 --- /dev/null +++ b/templates/groups/40-openvpn.yaml @@ -0,0 +1,3 @@ + - name: ${OVPN_GROUP} + type: select + use: [${OVPN_PROVIDER}] diff --git a/templates/groups/41-openvpn.street.yaml b/templates/groups/41-openvpn.street.yaml new file mode 100644 index 0000000..2e08432 --- /dev/null +++ b/templates/groups/41-openvpn.street.yaml @@ -0,0 +1,7 @@ + # what the OpenVPN tunnel itself goes through on a whitelisted network. + # select, not url-test: switching nodes would break the tunnel. + # Pick a concrete RU node in the dashboard, the choice is remembered. + - name: OVPN-EXIT + type: select + use: [${SUB_LIST}] + filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск" diff --git a/templates/groups/50-tailscale.yaml b/templates/groups/50-tailscale.yaml new file mode 100644 index 0000000..c7111e8 --- /dev/null +++ b/templates/groups/50-tailscale.yaml @@ -0,0 +1,3 @@ + - name: TAILSCALE + type: select + proxies: [tailscale] diff --git a/templates/groups/51-tailscale.ts_exit.yaml b/templates/groups/51-tailscale.ts_exit.yaml new file mode 100644 index 0000000..e6a4a43 --- /dev/null +++ b/templates/groups/51-tailscale.ts_exit.yaml @@ -0,0 +1,6 @@ + # Tailscale needs full-cone UDP from its dialer-proxy: vless/vmess/trojan + # cannot do it in mihomo, so only ss / hysteria2 / tuic / socks5 nodes here. + - name: TS-EXIT + type: select + use: [${SUB_LIST}] + exclude-type: "vless|vmess|trojan" diff --git a/templates/groups/90-base.yaml b/templates/groups/90-base.yaml new file mode 100644 index 0000000..c1735ed --- /dev/null +++ b/templates/groups/90-base.yaml @@ -0,0 +1,3 @@ + - name: MAIN + type: select + proxies: [FOREIGN, RU, DIRECT] diff --git a/templates/groups/91-torrent.yaml b/templates/groups/91-torrent.yaml new file mode 100644 index 0000000..2e6b8b6 --- /dev/null +++ b/templates/groups/91-torrent.yaml @@ -0,0 +1,3 @@ + - name: TORRENT-SEL + type: select + proxies: [TORRENT, FOREIGN, DIRECT] diff --git a/templates/head/10-base.yaml b/templates/head/10-base.yaml new file mode 100644 index 0000000..03a6a06 --- /dev/null +++ b/templates/head/10-base.yaml @@ -0,0 +1,7 @@ +geodata-mode: true +geodata-loader: memconservative +geo-auto-update: true +geo-update-interval: 24 +geox-url: + geoip: "${GEOIP_URL}" + geosite: "${GEOSITE_URL}" diff --git a/templates/providers/10-sub.each.yaml b/templates/providers/10-sub.each.yaml new file mode 100644 index 0000000..8533f83 --- /dev/null +++ b/templates/providers/10-sub.each.yaml @@ -0,0 +1,15 @@ + ${SUB_NAME}: + type: http + url: "${SUB_URL}" + path: ./providers/${SUB_NAME}.yaml + interval: 3600 + proxy: BOOT #@boot + exclude-filter: "(?i)app not supported|приложение не|свяжитесь" + header: + User-Agent: ["mihomo"] + health-check: + enable: true + url: "https://www.gstatic.com/generate_204" + interval: 300 + timeout: 3000 + lazy: false diff --git a/templates/providers/20-openvpn.yaml b/templates/providers/20-openvpn.yaml new file mode 100644 index 0000000..7ffc71c --- /dev/null +++ b/templates/providers/20-openvpn.yaml @@ -0,0 +1,10 @@ + # OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the + # password). No health-check here: a dead tunnel would be redialed with a + # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it. + ${OVPN_PROVIDER}: + type: file + path: ./providers/${OVPN_PROVIDER}.yaml + health-check: + enable: false + override: #@street + dialer-proxy: OVPN-EXIT #@street diff --git a/templates/proxies/10-boot.yaml b/templates/proxies/10-boot.yaml new file mode 100644 index 0000000..fe2c8b5 --- /dev/null +++ b/templates/proxies/10-boot.yaml @@ -0,0 +1,15 @@ + # BOOT: whitelisted entry node, used to download subscriptions + - name: seed + type: vless + server: ${BOOT_SERVER} + port: ${BOOT_PORT} + uuid: ${BOOT_UUID} + network: tcp + udp: true + tls: true + flow: xtls-rprx-vision + servername: ${BOOT_SNI} + client-fingerprint: firefox + reality-opts: + public-key: ${BOOT_PBK} + short-id: ${BOOT_SID} diff --git a/templates/proxies/20-tailscale.yaml b/templates/proxies/20-tailscale.yaml new file mode 100644 index 0000000..35ea386 --- /dev/null +++ b/templates/proxies/20-tailscale.yaml @@ -0,0 +1,11 @@ + # Tailscale: userspace node, starts on first use. First login: open the URL + # from the nikki log ("To start this tsnet server ... go to: ..."), then + # disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the + # mihomo environment (mihomo-kit.sh fix). + - name: tailscale + type: tailscale + hostname: ${TS_HOSTNAME} + state-dir: ./tailscale + udp: true + accept-routes: true + dialer-proxy: TS-EXIT #@ts_exit diff --git a/templates/rules/10-tailscale.yaml b/templates/rules/10-tailscale.yaml new file mode 100644 index 0000000..5ebf538 --- /dev/null +++ b/templates/rules/10-tailscale.yaml @@ -0,0 +1,4 @@ + # Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself) + - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve + - DOMAIN-SUFFIX,ts.net,TAILSCALE + - DOMAIN-SUFFIX,${@TS_DOMAINS},TAILSCALE diff --git a/templates/rules/20-openvpn.yaml b/templates/rules/20-openvpn.yaml new file mode 100644 index 0000000..09e7f00 --- /dev/null +++ b/templates/rules/20-openvpn.yaml @@ -0,0 +1,7 @@ + # OpenVPN server itself must not go into its own tunnel + - IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@home + - IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@street + - DOMAIN,${OVPN_SERVER_HOST},DIRECT #@home + - DOMAIN,${OVPN_SERVER_HOST},OVPN-EXIT #@street + # networks pushed by the server (before the private-range DIRECT rules) + - IP-CIDR,${@OVPN_ROUTES},${OVPN_GROUP},no-resolve diff --git a/templates/rules/30-base.yaml b/templates/rules/30-base.yaml new file mode 100644 index 0000000..3a34bef --- /dev/null +++ b/templates/rules/30-base.yaml @@ -0,0 +1,3 @@ + - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve + - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve + - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve diff --git a/templates/rules/40-base.yaml b/templates/rules/40-base.yaml new file mode 100644 index 0000000..cc28326 --- /dev/null +++ b/templates/rules/40-base.yaml @@ -0,0 +1 @@ + - IP-CIDR,${@RU_IPS},RU diff --git a/templates/rules/50-torrent.yaml b/templates/rules/50-torrent.yaml new file mode 100644 index 0000000..7edfbcd --- /dev/null +++ b/templates/rules/50-torrent.yaml @@ -0,0 +1 @@ + - SRC-PORT,20000-20199,TORRENT-SEL diff --git a/templates/rules/90-base.yaml b/templates/rules/90-base.yaml new file mode 100644 index 0000000..0992875 --- /dev/null +++ b/templates/rules/90-base.yaml @@ -0,0 +1,4 @@ + - GEOSITE,ru-inside,DIRECT + - DOMAIN-SUFFIX,ru,RU + - DOMAIN-SUFFIX,xn--p1ai,RU + - MATCH,MAIN diff --git a/templates/sniffer/10-base.yaml b/templates/sniffer/10-base.yaml new file mode 100644 index 0000000..9cb5d0e --- /dev/null +++ b/templates/sniffer/10-base.yaml @@ -0,0 +1,12 @@ +sniffer: + enable: true + force-dns-mapping: true + parse-pure-ip: true + override-destination: false + sniff: + HTTP: + ports: [80, 8080-8880] + TLS: + ports: [443, 8443] + QUIC: + ports: [443, 8443] diff --git a/tests/fixtures/common.env b/tests/fixtures/common.env new file mode 100644 index 0000000..16407c0 --- /dev/null +++ b/tests/fixtures/common.env @@ -0,0 +1,8 @@ +SUBS="https://sub.example.com/sub/aaa https://sub2.example.com/x?a=1&b=2" +BOOT_SERVER=1.2.3.4 +BOOT_UUID=00000000-0000-0000-0000-000000000000 +BOOT_SNI=eh.vk.ru +BOOT_PBK=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +BOOT_SID=a1b2 +RU_IPS="194.190.191.112/32" +TS_HOSTNAME=test-mihomo diff --git a/tests/fixtures/mobile.env b/tests/fixtures/mobile.env new file mode 100644 index 0000000..4aa7c3c --- /dev/null +++ b/tests/fixtures/mobile.env @@ -0,0 +1 @@ +TARGET=mobile diff --git a/tests/fixtures/router-home.env b/tests/fixtures/router-home.env new file mode 100644 index 0000000..bbec294 --- /dev/null +++ b/tests/fixtures/router-home.env @@ -0,0 +1,3 @@ +LOCATION=home +OPENVPN=1 +TAILSCALE=1 diff --git a/tests/fixtures/router-minimal.env b/tests/fixtures/router-minimal.env new file mode 100644 index 0000000..4ef9c0c --- /dev/null +++ b/tests/fixtures/router-minimal.env @@ -0,0 +1,4 @@ +TARGET=router +BOOT=0 +TORRENT=0 +RU_IPS="" diff --git a/tests/fixtures/router-street.env b/tests/fixtures/router-street.env new file mode 100644 index 0000000..7d8e7a3 --- /dev/null +++ b/tests/fixtures/router-street.env @@ -0,0 +1,5 @@ +LOCATION=street +OPENVPN=1 +TAILSCALE=1 +TS_EXIT=1 +TS_DOMAINS="corp.example internal.example" diff --git a/tools/build-web.py b/tools/build-web.py new file mode 100755 index 0000000..f56d15a --- /dev/null +++ b/tools/build-web.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +"""Build web/index.html: web/index.src.html + web/engine.js + templates/ inlined. + +The result is one self-contained file: open it from disk or put it on any +static host. Run after changing templates/ or web/. +""" +import json +import pathlib + +root = pathlib.Path(__file__).resolve().parent.parent +templates = { + f"{p.parent.name}/{p.name}": p.read_text(encoding="utf-8") + for p in sorted((root / "templates").glob("*/*.yaml")) +} +engine = (root / "web" / "engine.js").read_text(encoding="utf-8") +page = (root / "web" / "index.src.html").read_text(encoding="utf-8") + +tpl_json = json.dumps(templates, ensure_ascii=False, indent=1).replace("} +cd "$(dirname "$0")/.." +# 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 | + 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" diff --git a/tools/render.js b/tools/render.js new file mode 100755 index 0000000..0c5ccf3 --- /dev/null +++ b/tools/render.js @@ -0,0 +1,22 @@ +#!/usr/bin/env node +// Render a profile with web/engine.js. Variables come from the environment: +// sh -c 'set -a; . common.env; . home.env; node tools/render.js' +const fs = require("fs"); +const path = require("path"); +const { render, DEFAULTS } = require("../web/engine.js"); + +const tplDir = path.join(__dirname, "..", "templates"); +const templates = {}; +for (const dir of fs.readdirSync(tplDir)) { + const full = path.join(tplDir, dir); + if (!fs.statSync(full).isDirectory()) continue; + for (const f of fs.readdirSync(full)) templates[`${dir}/${f}`] = fs.readFileSync(path.join(full, f), "utf8"); +} +const vars = {}; +for (const k of Object.keys(DEFAULTS)) if (k in process.env) vars[k] = process.env[k]; +try { + process.stdout.write(render(templates, vars)); +} catch (e) { + console.error("error: " + e.message); + process.exit(1); +} diff --git a/tools/test.sh b/tools/test.sh new file mode 100755 index 0000000..b42d266 --- /dev/null +++ b/tools/test.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Render every fixture with router/mihomo-kit.sh and web/engine.js, diff them, +# and (if MIHOMO points to a mihomo binary) validate with `mihomo -t`. +# tools/test.sh parity only +# MIHOMO=/path/to/mihomo tools/test.sh +set -u +cd "$(dirname "$0")/.." +out=$(mktemp -d) +fail=0 +for f in tests/fixtures/*.env; do + n=$(basename "$f" .env) + [ "$n" = common ] && continue + sh router/mihomo-kit.sh render tests/fixtures/common.env "$f" > "$out/$n.sh.yaml" || { echo "FAIL $n: sh render"; fail=1; continue; } + sh -c 'set -a; . tests/fixtures/common.env; . "$1"; node tools/render.js' _ "$f" > "$out/$n.js.yaml" || { echo "FAIL $n: js render"; fail=1; continue; } + if ! diff -u "$out/$n.sh.yaml" "$out/$n.js.yaml"; then + echo "FAIL $n: sh and js differ" + fail=1 + continue + fi + if [ -n "${MIHOMO:-}" ]; then + mkdir -p "$out/home" + # geosite needs a download: drop those rules for the syntax check + sed '/GEOSITE/d; /rule-set:ru-inside/d' "$out/$n.sh.yaml" > "$out/home/$n.yaml" + if ! "$MIHOMO" -t -d "$out/home" -f "$out/home/$n.yaml" >"$out/$n.log" 2>&1; then + echo "FAIL $n: mihomo -t"; tail -3 "$out/$n.log"; fail=1; continue + fi + fi + echo "ok $n" +done +rm -rf "$out" +exit $fail diff --git a/web/engine.js b/web/engine.js new file mode 100644 index 0000000..3474348 --- /dev/null +++ b/web/engine.js @@ -0,0 +1,142 @@ +// mihomo-kit renderer, the browser twin of render() in router/mihomo-kit.sh. +// Keep both in sync: tools/test.sh renders the fixtures with both and diffs. +// +// Template syntax: +// file NN-[....][.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 + +(function (root) { + const 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", + }; + + const SECTIONS = [ + ["head", ""], ["proxies", "proxies:"], ["providers", "proxy-providers:"], + ["sniffer", ""], ["dns", ""], ["groups", "proxy-groups:"], ["rules", "rules:"], + ]; + + const words = (s) => (s || "").split(/\s+/).filter(Boolean); + + function withDefaults(input) { + const v = { ...DEFAULTS }; + for (const [k, val] of Object.entries(input || {})) { + if (val !== undefined && val !== null && val !== "") v[k] = String(val); + } + return v; + } + + function check(v) { + if (!words(v.SUBS).length) throw new Error("SUBS is empty (subscription URLs)"); + if (!["router", "mobile"].includes(v.TARGET)) throw new Error("TARGET must be router or mobile"); + if (!["home", "street"].includes(v.LOCATION)) throw new Error("LOCATION must be home or street"); + if (v.BOOT === "1") { + for (const k of ["BOOT_SERVER", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID"]) { + if (!v[k]) throw new Error(`${k} is empty (BOOT=1)`); + } + } + } + + function computeTags(v) { + const t = new Set(["base", "sub", v.TARGET]); + if (v.BOOT === "1") t.add("boot"); + if (v.TARGET === "router") { + t.add(v.LOCATION); + if (v.TORRENT === "1") t.add("torrent"); + if (v.OPENVPN === "1") t.add("openvpn"); + if (v.TAILSCALE === "1") { + t.add("tailscale"); + if (v.TS_EXIT === "1") t.add("ts_exit"); + } + } + return t; + } + + function subst(s, v) { + return s.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_, name) => v[name] ?? ""); + } + + function renderText(text, v, tags) { + const out = []; + for (let line of text.replace(/\n$/, "").split("\n")) { + const p = line.indexOf("#@"); + if (p >= 0) { + const conds = line.slice(p + 2).split(","); + line = line.slice(0, p).replace(/[ \t]+$/, ""); + const ok = conds.every((c) => (c.startsWith("!") ? !tags.has(c.slice(1)) : tags.has(c))); + if (!ok) continue; + } + const m = line.match(/\$\{@([A-Za-z0-9_]+)\}/); + if (m) { + const pre = line.slice(0, m.index); + const post = line.slice(m.index + m[0].length); + for (const w of words(v[m[1]])) out.push(subst(pre + w + post, v)); + continue; + } + out.push(subst(line, v)); + } + // like $(...) in sh: drop trailing empty lines + while (out.length && out[out.length - 1] === "") out.pop(); + return out.join("\n"); + } + + // "....[.each]" -> {active, each} + function fragmentInfo(spec, tags) { + const [mod, ...rest] = spec.split("."); + let each = false; + if (!tags.has(mod)) return { active: false, each }; + for (const t of rest) { + if (t === "each") { each = true; continue; } + if (!tags.has(t)) return { active: false, each }; + } + return { active: true, each }; + } + + function render(templates, input) { + const v = withDefaults(input); + check(v); + const tags = computeTags(v); + const subs = words(v.SUBS); + v.SUB_LIST = subs.map((_, i) => `sub${i}`).join(", "); + + const sections = []; + for (const [dir, header] of SECTIONS) { + const files = Object.keys(templates) + .filter((p) => p.startsWith(dir + "/") && p.endsWith(".yaml")) + .sort(); + const parts = []; + for (const path of files) { + const name = path.slice(dir.length + 1, -".yaml".length); + const info = fragmentInfo(name.slice(name.indexOf("-") + 1), tags); + if (!info.active) continue; + if (info.each) { + subs.forEach((url, i) => { + const part = renderText(templates[path], { ...v, SUB_NAME: `sub${i}`, SUB_URL: url }, tags); + if (part) parts.push(part); + }); + } else { + const part = renderText(templates[path], v, tags); + if (part) parts.push(part); + } + } + if (!parts.length) continue; + sections.push((header ? header + "\n" : "") + parts.join("\n\n")); + } + return sections.join("\n\n") + "\n"; + } + + const api = { render, DEFAULTS }; + if (typeof module !== "undefined" && module.exports) module.exports = api; + else root.MihomoKit = api; +})(typeof window !== "undefined" ? window : globalThis); diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..5dcb033 --- /dev/null +++ b/web/index.html @@ -0,0 +1,469 @@ + + + + + +mihomo-kit + + + +
+
+

mihomo-kit — конструктор конфига

+

Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у mihomo-kit.sh на роутере.

+
+ +
+
+
+ Куда +
+
+ + +
+
+ + +
+
+

Улица: OpenVPN идёт через выбранную RU-ноду (группа OVPN-EXIT).

+ + +
+ +
+ Подписки + + + + +
+ +
+ BOOT + +
+ + +
+
+
+
+ +
+
+
+
+ +
+
+ +
+ Модули роутера + + + +
+ параметры OpenVPN + + + +
+ + +
+ + + +
+
+
+ +
+
+
+ + + +
+
+ + +
+
+ +

+      

На роутере удобнее держать .env и собирать там: mihomo-kit.sh build. YAML отсюда — для телефона или разовой проверки.

+
+
+
+ + + + + diff --git a/web/index.src.html b/web/index.src.html new file mode 100644 index 0000000..52dfce8 --- /dev/null +++ b/web/index.src.html @@ -0,0 +1,304 @@ + + + + + +mihomo-kit + + + +
+
+

mihomo-kit — конструктор конфига

+

Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у mihomo-kit.sh на роутере.

+
+ +
+
+
+ Куда +
+
+ + +
+
+ + +
+
+

Улица: OpenVPN идёт через выбранную RU-ноду (группа OVPN-EXIT).

+ + +
+ +
+ Подписки + + + + +
+ +
+ BOOT + +
+ + +
+
+
+
+ +
+
+
+
+ +
+
+ +
+ Модули роутера + + + +
+ параметры OpenVPN + + + +
+ + +
+ + + +
+
+
+ +
+
+
+ + + +
+
+ + +
+
+ +

+      

На роутере удобнее держать .env и собирать там: mihomo-kit.sh build. YAML отсюда — для телефона или разовой проверки.

+
+
+
+ + + + +