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>
This commit is contained in:
commit
2557a9aa49
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
# secrets and real configs never go in here
|
||||||
|
*.env
|
||||||
|
!tests/fixtures/*.env
|
||||||
|
!presets/*.env
|
||||||
|
*.ovpn
|
||||||
|
/configs/
|
||||||
|
/reference/
|
||||||
|
|
||||||
|
.DS_Store
|
||||||
|
__pycache__/
|
||||||
152
README.md
Normal file
152
README.md
Normal file
@ -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
|
||||||
|
```
|
||||||
31
install.sh
Executable file
31
install.sh
Executable file
@ -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
|
||||||
2
presets/home.env
Normal file
2
presets/home.env
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# home: OpenVPN/Tailscale go direct
|
||||||
|
LOCATION=home
|
||||||
2
presets/street.env
Normal file
2
presets/street.env
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
# street (whitelisted network): OpenVPN goes through OVPN-EXIT, pick a RU node in the dashboard
|
||||||
|
LOCATION=street
|
||||||
264
router/bmstu-otp.sh
Executable file
264
router/bmstu-otp.sh
Executable file
@ -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 - <password><otp> (what the BMSTU server accepts)
|
||||||
|
# otp-first - <otp><password>
|
||||||
|
# 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 <tag>...</tag> block from the .ovpn, YAML-indented, no comments
|
||||||
|
ovpn_block() {
|
||||||
|
awk -v tag="$1" '
|
||||||
|
$0 ~ "^<" tag ">" { on = 1; next }
|
||||||
|
$0 ~ "^</" tag ">" { 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
|
||||||
17
router/bmstu.env.example
Normal file
17
router/bmstu.env.example
Normal file
@ -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: <password><otp>) | 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
|
||||||
519
router/mihomo-kit.sh
Executable file
519
router/mihomo-kit.sh
Executable file
@ -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/<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
|
||||||
43
router/profile.env.example
Normal file
43
router/profile.env.example
Normal file
@ -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/<name>.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
|
||||||
29
templates/dns/10-base.yaml
Normal file
29
templates/dns/10-base.yaml
Normal file
@ -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
|
||||||
3
templates/groups/10-boot.yaml
Normal file
3
templates/groups/10-boot.yaml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
- name: BOOT
|
||||||
|
type: select
|
||||||
|
proxies: [seed]
|
||||||
17
templates/groups/20-sub.yaml
Normal file
17
templates/groups/20-sub.yaml
Normal file
@ -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
|
||||||
10
templates/groups/30-torrent.yaml
Normal file
10
templates/groups/30-torrent.yaml
Normal file
@ -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
|
||||||
3
templates/groups/40-openvpn.yaml
Normal file
3
templates/groups/40-openvpn.yaml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
- name: ${OVPN_GROUP}
|
||||||
|
type: select
|
||||||
|
use: [${OVPN_PROVIDER}]
|
||||||
7
templates/groups/41-openvpn.street.yaml
Normal file
7
templates/groups/41-openvpn.street.yaml
Normal file
@ -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|росси|моск"
|
||||||
3
templates/groups/50-tailscale.yaml
Normal file
3
templates/groups/50-tailscale.yaml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
- name: TAILSCALE
|
||||||
|
type: select
|
||||||
|
proxies: [tailscale]
|
||||||
6
templates/groups/51-tailscale.ts_exit.yaml
Normal file
6
templates/groups/51-tailscale.ts_exit.yaml
Normal file
@ -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"
|
||||||
3
templates/groups/90-base.yaml
Normal file
3
templates/groups/90-base.yaml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
- name: MAIN
|
||||||
|
type: select
|
||||||
|
proxies: [FOREIGN, RU, DIRECT]
|
||||||
3
templates/groups/91-torrent.yaml
Normal file
3
templates/groups/91-torrent.yaml
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
- name: TORRENT-SEL
|
||||||
|
type: select
|
||||||
|
proxies: [TORRENT, FOREIGN, DIRECT]
|
||||||
7
templates/head/10-base.yaml
Normal file
7
templates/head/10-base.yaml
Normal file
@ -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}"
|
||||||
15
templates/providers/10-sub.each.yaml
Normal file
15
templates/providers/10-sub.each.yaml
Normal file
@ -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
|
||||||
10
templates/providers/20-openvpn.yaml
Normal file
10
templates/providers/20-openvpn.yaml
Normal file
@ -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
|
||||||
15
templates/proxies/10-boot.yaml
Normal file
15
templates/proxies/10-boot.yaml
Normal file
@ -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}
|
||||||
11
templates/proxies/20-tailscale.yaml
Normal file
11
templates/proxies/20-tailscale.yaml
Normal file
@ -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
|
||||||
4
templates/rules/10-tailscale.yaml
Normal file
4
templates/rules/10-tailscale.yaml
Normal file
@ -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
|
||||||
7
templates/rules/20-openvpn.yaml
Normal file
7
templates/rules/20-openvpn.yaml
Normal file
@ -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
|
||||||
3
templates/rules/30-base.yaml
Normal file
3
templates/rules/30-base.yaml
Normal file
@ -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
|
||||||
1
templates/rules/40-base.yaml
Normal file
1
templates/rules/40-base.yaml
Normal file
@ -0,0 +1 @@
|
|||||||
|
- IP-CIDR,${@RU_IPS},RU
|
||||||
1
templates/rules/50-torrent.yaml
Normal file
1
templates/rules/50-torrent.yaml
Normal file
@ -0,0 +1 @@
|
|||||||
|
- SRC-PORT,20000-20199,TORRENT-SEL
|
||||||
4
templates/rules/90-base.yaml
Normal file
4
templates/rules/90-base.yaml
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
- GEOSITE,ru-inside,DIRECT
|
||||||
|
- DOMAIN-SUFFIX,ru,RU
|
||||||
|
- DOMAIN-SUFFIX,xn--p1ai,RU
|
||||||
|
- MATCH,MAIN
|
||||||
12
templates/sniffer/10-base.yaml
Normal file
12
templates/sniffer/10-base.yaml
Normal file
@ -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]
|
||||||
8
tests/fixtures/common.env
vendored
Normal file
8
tests/fixtures/common.env
vendored
Normal file
@ -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
|
||||||
1
tests/fixtures/mobile.env
vendored
Normal file
1
tests/fixtures/mobile.env
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
TARGET=mobile
|
||||||
3
tests/fixtures/router-home.env
vendored
Normal file
3
tests/fixtures/router-home.env
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
LOCATION=home
|
||||||
|
OPENVPN=1
|
||||||
|
TAILSCALE=1
|
||||||
4
tests/fixtures/router-minimal.env
vendored
Normal file
4
tests/fixtures/router-minimal.env
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
TARGET=router
|
||||||
|
BOOT=0
|
||||||
|
TORRENT=0
|
||||||
|
RU_IPS=""
|
||||||
5
tests/fixtures/router-street.env
vendored
Normal file
5
tests/fixtures/router-street.env
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
LOCATION=street
|
||||||
|
OPENVPN=1
|
||||||
|
TAILSCALE=1
|
||||||
|
TS_EXIT=1
|
||||||
|
TS_DOMAINS="corp.example internal.example"
|
||||||
21
tools/build-web.py
Executable file
21
tools/build-web.py
Executable file
@ -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("</", "<\\/")
|
||||||
|
page = page.replace("/*__ENGINE__*/", engine).replace("/*__TEMPLATES__*/", tpl_json)
|
||||||
|
(root / "web" / "index.html").write_text(page, encoding="utf-8")
|
||||||
|
print(f"web/index.html: {len(templates)} templates")
|
||||||
11
tools/push.sh
Executable file
11
tools/push.sh
Executable file
@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Copy the kit to the router's /etc/nikki/kit, then run the installer there:
|
||||||
|
# tools/push.sh root@192.168.32.1
|
||||||
|
# ssh root@192.168.32.1 sh /etc/nikki/kit/install.sh
|
||||||
|
set -eu
|
||||||
|
host=${1:?usage: tools/push.sh root@<router>}
|
||||||
|
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"
|
||||||
22
tools/render.js
Executable file
22
tools/render.js
Executable file
@ -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);
|
||||||
|
}
|
||||||
31
tools/test.sh
Executable file
31
tools/test.sh
Executable file
@ -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
|
||||||
142
web/engine.js
Normal file
142
web/engine.js
Normal file
@ -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-<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
|
||||||
|
|
||||||
|
(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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// "<module>.<tag>...[.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);
|
||||||
469
web/index.html
Normal file
469
web/index.html
Normal file
@ -0,0 +1,469 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>mihomo-kit</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #f6f6f3; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e2e1dc;
|
||||||
|
--accent: #2f6f4f; --accent-soft: #e4efe8; --err: #b3261e; --code-bg: #f1f0ec;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
|
||||||
|
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
|
||||||
|
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0; background: var(--bg); color: var(--text);
|
||||||
|
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
.wrap { max-width: 1280px; margin: 0 auto; padding: 24px 16px 48px; }
|
||||||
|
header h1 { font-size: 20px; margin: 0 0 4px; }
|
||||||
|
header p { margin: 0 0 20px; color: var(--muted); }
|
||||||
|
.grid { display: grid; grid-template-columns: minmax(0, 420px) minmax(0, 1fr); gap: 20px; align-items: start; }
|
||||||
|
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
|
||||||
|
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
|
||||||
|
fieldset { border: 0; border-top: 1px solid var(--line); margin: 0; padding: 14px 0 4px; }
|
||||||
|
fieldset:first-child { border-top: 0; padding-top: 0; }
|
||||||
|
legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
|
||||||
|
label { display: block; margin: 8px 0 4px; color: var(--muted); font-size: 13px; }
|
||||||
|
input[type=text], textarea {
|
||||||
|
width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px;
|
||||||
|
background: var(--bg); color: var(--text); font: 13px ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
}
|
||||||
|
textarea { min-height: 64px; resize: vertical; }
|
||||||
|
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
|
||||||
|
.seg label { margin: 0; padding: 6px 12px; cursor: pointer; color: var(--text); font-size: 13px; }
|
||||||
|
.seg input { display: none; }
|
||||||
|
.seg label:has(input:checked) { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
|
||||||
|
.row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
|
||||||
|
.check { display: flex; gap: 8px; align-items: center; margin: 6px 0; color: var(--text); font-size: 14px; }
|
||||||
|
.check input { margin: 0; }
|
||||||
|
.hint { color: var(--muted); font-size: 12px; margin: 4px 0 0; }
|
||||||
|
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; }
|
||||||
|
details summary { cursor: pointer; color: var(--muted); font-size: 13px; margin-top: 8px; }
|
||||||
|
.tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 10px; }
|
||||||
|
.tabs button, .actions button {
|
||||||
|
border: 1px solid var(--line); background: var(--panel); color: var(--text);
|
||||||
|
padding: 6px 12px; border-radius: 6px; cursor: pointer; font: inherit; font-size: 13px;
|
||||||
|
}
|
||||||
|
.tabs button[aria-selected=true] { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); font-weight: 600; }
|
||||||
|
.actions { display: flex; gap: 6px; margin-left: auto; }
|
||||||
|
.out-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||||
|
pre {
|
||||||
|
margin: 0; padding: 14px; background: var(--code-bg); border: 1px solid var(--line); border-radius: 8px;
|
||||||
|
overflow: auto; max-height: 78vh; font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre;
|
||||||
|
}
|
||||||
|
.error { color: var(--err); margin: 0 0 10px; font-weight: 600; }
|
||||||
|
.note { color: var(--muted); font-size: 12px; margin-top: 10px; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap">
|
||||||
|
<header>
|
||||||
|
<h1>mihomo-kit — конструктор конфига</h1>
|
||||||
|
<p>Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у <code>mihomo-kit.sh</code> на роутере.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="grid">
|
||||||
|
<form class="panel" id="form" autocomplete="off">
|
||||||
|
<fieldset>
|
||||||
|
<legend>Куда</legend>
|
||||||
|
<div class="row">
|
||||||
|
<div class="seg">
|
||||||
|
<label><input type="radio" name="TARGET" value="router" checked>Роутер (nikki)</label>
|
||||||
|
<label><input type="radio" name="TARGET" value="mobile">Телефон (FlClash)</label>
|
||||||
|
</div>
|
||||||
|
<div class="seg" data-router>
|
||||||
|
<label><input type="radio" name="LOCATION" value="home" checked>Дом</label>
|
||||||
|
<label><input type="radio" name="LOCATION" value="street">Улица</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="hint" data-router>Улица: OpenVPN идёт через выбранную RU-ноду (группа OVPN-EXIT).</p>
|
||||||
|
<label for="PROFILE_NAME" data-router>Имя профиля на роутере</label>
|
||||||
|
<input type="text" id="PROFILE_NAME" value="home" data-router>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>Подписки</legend>
|
||||||
|
<label for="SUBS">URL, по одному на строку → sub0, sub1, …</label>
|
||||||
|
<textarea id="SUBS" placeholder="https://sub.example.com/sub/xxxx"></textarea>
|
||||||
|
<label for="RU_IPS">Доп. IP через RU (CIDR через пробел)</label>
|
||||||
|
<input type="text" id="RU_IPS" value="194.190.191.112/32">
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>BOOT</legend>
|
||||||
|
<label class="check"><input type="checkbox" id="BOOT" checked>Качать подписки через BOOT (seed)</label>
|
||||||
|
<div data-boot>
|
||||||
|
<label for="vless">Вставить vless:// ссылку — поля заполнятся сами</label>
|
||||||
|
<input type="text" id="vless" placeholder="vless://uuid@host:443?security=reality&sni=…&pbk=…&sid=…">
|
||||||
|
<div class="two">
|
||||||
|
<div><label for="BOOT_SERVER">server</label><input type="text" id="BOOT_SERVER"></div>
|
||||||
|
<div><label for="BOOT_PORT">port</label><input type="text" id="BOOT_PORT" value="443"></div>
|
||||||
|
</div>
|
||||||
|
<label for="BOOT_UUID">uuid</label><input type="text" id="BOOT_UUID">
|
||||||
|
<div class="two">
|
||||||
|
<div><label for="BOOT_SNI">servername (SNI)</label><input type="text" id="BOOT_SNI" value="eh.vk.ru"></div>
|
||||||
|
<div><label for="BOOT_SID">short-id</label><input type="text" id="BOOT_SID"></div>
|
||||||
|
</div>
|
||||||
|
<label for="BOOT_PBK">public-key</label><input type="text" id="BOOT_PBK">
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset data-router>
|
||||||
|
<legend>Модули роутера</legend>
|
||||||
|
<label class="check"><input type="checkbox" id="TORRENT" checked>Торренты (порты 20000–20199 → TORRENT-SEL)</label>
|
||||||
|
|
||||||
|
<label class="check"><input type="checkbox" id="OPENVPN">OpenVPN (BMSTU, OTP через bmstu-otp.sh)</label>
|
||||||
|
<details data-openvpn>
|
||||||
|
<summary>параметры OpenVPN</summary>
|
||||||
|
<label for="OVPN_SERVER_HOST">сервер</label><input type="text" id="OVPN_SERVER_HOST">
|
||||||
|
<label for="OVPN_SERVER_IPS">IP сервера (не пускать в туннель)</label><input type="text" id="OVPN_SERVER_IPS">
|
||||||
|
<label for="OVPN_ROUTES">сети через туннель</label><input type="text" id="OVPN_ROUTES">
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<label class="check"><input type="checkbox" id="TAILSCALE">Tailscale</label>
|
||||||
|
<div data-tailscale>
|
||||||
|
<label for="TS_HOSTNAME">hostname ноды</label><input type="text" id="TS_HOSTNAME" value="fudy-mihomo">
|
||||||
|
<label for="TS_DOMAINS">split-DNS домены тейлнета, кроме *.ts.net</label><input type="text" id="TS_DOMAINS">
|
||||||
|
<label class="check"><input type="checkbox" id="TS_EXIT">Через TS-EXIT (только ss/hysteria2/tuic ноды)</label>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="out-head">
|
||||||
|
<div class="tabs" role="tablist">
|
||||||
|
<button type="button" data-tab="yaml" aria-selected="true">config.yaml</button>
|
||||||
|
<button type="button" data-tab="env" aria-selected="false" data-router>profile .env</button>
|
||||||
|
<button type="button" data-tab="steps" aria-selected="false">Что дальше</button>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button type="button" id="copy">Копировать</button>
|
||||||
|
<button type="button" id="download">Скачать</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="error" id="error" hidden></p>
|
||||||
|
<pre id="out"></pre>
|
||||||
|
<p class="note">На роутере удобнее держать <code>.env</code> и собирать там: <code>mihomo-kit.sh build</code>. YAML отсюда — для телефона или разовой проверки.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
// 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-<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
|
||||||
|
|
||||||
|
(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");
|
||||||
|
}
|
||||||
|
|
||||||
|
// "<module>.<tag>...[.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);
|
||||||
|
|
||||||
|
</script>
|
||||||
|
<script>
|
||||||
|
const TEMPLATES = {
|
||||||
|
"dns/10-base.yaml": "dns:\n enable: true\n ipv6: false\n respect-rules: true\n enhanced-mode: fake-ip\n fake-ip-range: 198.18.0.1/16\n fake-ip-filter:\n - '*.lan'\n - '*.local' #@router\n - '+.ru'\n - '+.xn--p1ai' #@router\n - rule-set:ru-inside #@router\n\n default-nameserver:\n - 77.88.8.8\n - 1.1.1.1 #@router\n - 223.5.5.5 #@mobile\n\n proxy-server-nameserver:\n - https://77.88.8.8/dns-query\n\n direct-nameserver:\n - 77.88.8.8\n - 77.88.8.1\n\n nameserver:\n - https://1.1.1.1/dns-query #@router\n - https://dns.google/dns-query\n - https://1.1.1.1/dns-query #@mobile\n",
|
||||||
|
"groups/10-boot.yaml": " - name: BOOT\n type: select\n proxies: [seed]\n",
|
||||||
|
"groups/20-sub.yaml": " - name: RU\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://ya.ru\"\n interval: 300\n tolerance: 50\n lazy: false\n\n - name: FOREIGN\n type: url-test\n use: [${SUB_LIST}]\n exclude-filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n tolerance: 50\n lazy: false\n",
|
||||||
|
"groups/30-torrent.yaml": " - name: TORRENT\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)torrent|\\\\[tor\\\\]\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 6000\n tolerance: 500\n max-failed-times: 5\n lazy: false\n",
|
||||||
|
"groups/40-openvpn.yaml": " - name: ${OVPN_GROUP}\n type: select\n use: [${OVPN_PROVIDER}]\n",
|
||||||
|
"groups/41-openvpn.street.yaml": " # what the OpenVPN tunnel itself goes through on a whitelisted network.\n # select, not url-test: switching nodes would break the tunnel.\n # Pick a concrete RU node in the dashboard, the choice is remembered.\n - name: OVPN-EXIT\n type: select\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n",
|
||||||
|
"groups/50-tailscale.yaml": " - name: TAILSCALE\n type: select\n proxies: [tailscale]\n",
|
||||||
|
"groups/51-tailscale.ts_exit.yaml": " # Tailscale needs full-cone UDP from its dialer-proxy: vless/vmess/trojan\n # cannot do it in mihomo, so only ss / hysteria2 / tuic / socks5 nodes here.\n - name: TS-EXIT\n type: select\n use: [${SUB_LIST}]\n exclude-type: \"vless|vmess|trojan\"\n",
|
||||||
|
"groups/90-base.yaml": " - name: MAIN\n type: select\n proxies: [FOREIGN, RU, DIRECT]\n",
|
||||||
|
"groups/91-torrent.yaml": " - name: TORRENT-SEL\n type: select\n proxies: [TORRENT, FOREIGN, DIRECT]\n",
|
||||||
|
"head/10-base.yaml": "geodata-mode: true\ngeodata-loader: memconservative\ngeo-auto-update: true\ngeo-update-interval: 24\ngeox-url:\n geoip: \"${GEOIP_URL}\"\n geosite: \"${GEOSITE_URL}\"\n",
|
||||||
|
"providers/10-sub.each.yaml": " ${SUB_NAME}:\n type: http\n url: \"${SUB_URL}\"\n path: ./providers/${SUB_NAME}.yaml\n interval: 3600\n proxy: BOOT #@boot\n exclude-filter: \"(?i)app not supported|приложение не|свяжитесь\"\n header:\n User-Agent: [\"mihomo\"]\n health-check:\n enable: true\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 3000\n lazy: false\n",
|
||||||
|
"providers/20-openvpn.yaml": " # OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the\n # password). No health-check here: a dead tunnel would be redialed with a\n # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.\n ${OVPN_PROVIDER}:\n type: file\n path: ./providers/${OVPN_PROVIDER}.yaml\n health-check:\n enable: false\n override: #@street\n dialer-proxy: OVPN-EXIT #@street\n",
|
||||||
|
"proxies/10-boot.yaml": " # BOOT: whitelisted entry node, used to download subscriptions\n - name: seed\n type: vless\n server: ${BOOT_SERVER}\n port: ${BOOT_PORT}\n uuid: ${BOOT_UUID}\n network: tcp\n udp: true\n tls: true\n flow: xtls-rprx-vision\n servername: ${BOOT_SNI}\n client-fingerprint: firefox\n reality-opts:\n public-key: ${BOOT_PBK}\n short-id: ${BOOT_SID}\n",
|
||||||
|
"proxies/20-tailscale.yaml": " # Tailscale: userspace node, starts on first use. First login: open the URL\n # from the nikki log (\"To start this tsnet server ... go to: ...\"), then\n # disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the\n # mihomo environment (mihomo-kit.sh fix).\n - name: tailscale\n type: tailscale\n hostname: ${TS_HOSTNAME}\n state-dir: ./tailscale\n udp: true\n accept-routes: true\n dialer-proxy: TS-EXIT #@ts_exit\n",
|
||||||
|
"rules/10-tailscale.yaml": " # Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)\n - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve\n - DOMAIN-SUFFIX,ts.net,TAILSCALE\n - DOMAIN-SUFFIX,${@TS_DOMAINS},TAILSCALE\n",
|
||||||
|
"rules/20-openvpn.yaml": " # OpenVPN server itself must not go into its own tunnel\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@home\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@street\n - DOMAIN,${OVPN_SERVER_HOST},DIRECT #@home\n - DOMAIN,${OVPN_SERVER_HOST},OVPN-EXIT #@street\n # networks pushed by the server (before the private-range DIRECT rules)\n - IP-CIDR,${@OVPN_ROUTES},${OVPN_GROUP},no-resolve\n",
|
||||||
|
"rules/30-base.yaml": " - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve\n - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve\n - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve\n",
|
||||||
|
"rules/40-base.yaml": " - IP-CIDR,${@RU_IPS},RU\n",
|
||||||
|
"rules/50-torrent.yaml": " - SRC-PORT,20000-20199,TORRENT-SEL\n",
|
||||||
|
"rules/90-base.yaml": " - GEOSITE,ru-inside,DIRECT\n - DOMAIN-SUFFIX,ru,RU\n - DOMAIN-SUFFIX,xn--p1ai,RU\n - MATCH,MAIN\n",
|
||||||
|
"sniffer/10-base.yaml": "sniffer:\n enable: true\n force-dns-mapping: true\n parse-pure-ip: true\n override-destination: false\n sniff:\n HTTP:\n ports: [80, 8080-8880]\n TLS:\n ports: [443, 8443]\n QUIC:\n ports: [443, 8443]\n"
|
||||||
|
};
|
||||||
|
const D = MihomoKit.DEFAULTS;
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
const form = $("form");
|
||||||
|
let tab = "yaml";
|
||||||
|
let current = { yaml: "", env: "", steps: "" };
|
||||||
|
|
||||||
|
for (const k of ["OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) $(k).value = D[k];
|
||||||
|
|
||||||
|
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
|
||||||
|
function flag(id) { return $(id).checked ? "1" : "0"; }
|
||||||
|
|
||||||
|
function readVars() {
|
||||||
|
const v = {
|
||||||
|
TARGET: radio("TARGET"), LOCATION: radio("LOCATION"),
|
||||||
|
SUBS: $("SUBS").value.trim().split(/\s+/).filter(Boolean).join(" "),
|
||||||
|
RU_IPS: $("RU_IPS").value.trim(),
|
||||||
|
BOOT: flag("BOOT"), TORRENT: flag("TORRENT"), OPENVPN: flag("OPENVPN"),
|
||||||
|
TAILSCALE: flag("TAILSCALE"), TS_EXIT: flag("TS_EXIT"),
|
||||||
|
};
|
||||||
|
for (const k of ["BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID",
|
||||||
|
"TS_HOSTNAME", "TS_DOMAINS", "OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) {
|
||||||
|
v[k] = $(k).value.trim();
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
|
||||||
|
|
||||||
|
function envFile(v) {
|
||||||
|
const keys = ["TARGET", "LOCATION", "SUBS", "BOOT"];
|
||||||
|
if (v.BOOT === "1") keys.push("BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID");
|
||||||
|
keys.push("TORRENT", "RU_IPS", "OPENVPN");
|
||||||
|
if (v.OPENVPN === "1") keys.push("OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES");
|
||||||
|
keys.push("TAILSCALE");
|
||||||
|
if (v.TAILSCALE === "1") keys.push("TS_HOSTNAME", "TS_DOMAINS", "TS_EXIT");
|
||||||
|
return "# mihomo-kit profile (secrets inside: chmod 600)\n" +
|
||||||
|
keys.map((k) => `${k}=${q(v[k] ?? "")}`).join("\n") + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
function steps(v) {
|
||||||
|
const name = $("PROFILE_NAME").value.trim() || "home";
|
||||||
|
if (v.TARGET === "mobile") {
|
||||||
|
return [
|
||||||
|
"Телефон (FlClash):",
|
||||||
|
"1. Скачай config.yaml (кнопка «Скачать»).",
|
||||||
|
"2. FlClash → Профили → + → Файл → выбери config.yaml.",
|
||||||
|
"3. Включи профиль; геобазы скачаются при первом запуске.",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
const s = [
|
||||||
|
"Роутер (nikki). Один раз на новом роутере — см. README, раздел «Новый роутер».",
|
||||||
|
"",
|
||||||
|
`1. Сохрани profile .env как /etc/nikki/profiles.d/${name}.env`,
|
||||||
|
` (общие секреты можно вынести в /etc/nikki/profiles.d/common.env)`,
|
||||||
|
` chmod 600 /etc/nikki/profiles.d/*.env`,
|
||||||
|
"2. Собери и включи:",
|
||||||
|
` mihomo-kit.sh build ${name}`,
|
||||||
|
` mihomo-kit.sh use ${name}`,
|
||||||
|
];
|
||||||
|
if (v.OPENVPN === "1") s.push("", "OpenVPN: заполни /etc/nikki/bmstu.env, положи .ovpn в /etc/nikki/bmstu.ovpn,",
|
||||||
|
" cron (bmstu-otp.sh check) ставит mihomo-kit.sh install.",
|
||||||
|
v.LOCATION === "street" ? " На улице выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
|
||||||
|
if (v.TAILSCALE === "1") s.push("", "Tailscale: открой любой 100.x адрес, ссылка для входа появится в логе:",
|
||||||
|
" grep 'To start' /var/log/nikki/core.log",
|
||||||
|
" Потом в админке Tailscale: Disable key expiry для " + (v.TS_HOSTNAME || "ноды") + ".");
|
||||||
|
return s.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function update() {
|
||||||
|
const v = readVars();
|
||||||
|
const router = v.TARGET === "router";
|
||||||
|
document.querySelectorAll("[data-router]").forEach((el) => (el.hidden = !router));
|
||||||
|
document.querySelectorAll("[data-boot]").forEach((el) => (el.hidden = v.BOOT !== "1"));
|
||||||
|
document.querySelectorAll("[data-openvpn]").forEach((el) => (el.hidden = v.OPENVPN !== "1"));
|
||||||
|
document.querySelectorAll("[data-tailscale]").forEach((el) => (el.hidden = v.TAILSCALE !== "1"));
|
||||||
|
if (!router && tab === "env") setTab("yaml");
|
||||||
|
|
||||||
|
const err = $("error");
|
||||||
|
try {
|
||||||
|
current.yaml = MihomoKit.render(TEMPLATES, v);
|
||||||
|
err.hidden = true;
|
||||||
|
} catch (e) {
|
||||||
|
current.yaml = "";
|
||||||
|
err.textContent = e.message;
|
||||||
|
err.hidden = false;
|
||||||
|
}
|
||||||
|
current.env = envFile(v);
|
||||||
|
current.steps = steps(v);
|
||||||
|
$("out").textContent = current[tab];
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTab(t) {
|
||||||
|
tab = t;
|
||||||
|
document.querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tab === t)));
|
||||||
|
$("out").textContent = current[t];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseVless(link) {
|
||||||
|
try {
|
||||||
|
const u = new URL(link.trim());
|
||||||
|
if (u.protocol !== "vless:") return;
|
||||||
|
const p = u.searchParams;
|
||||||
|
$("BOOT_UUID").value = decodeURIComponent(u.username);
|
||||||
|
$("BOOT_SERVER").value = u.hostname.replace(/^\[|\]$/g, "");
|
||||||
|
$("BOOT_PORT").value = u.port || "443";
|
||||||
|
if (p.get("sni")) $("BOOT_SNI").value = p.get("sni");
|
||||||
|
if (p.get("pbk")) $("BOOT_PBK").value = p.get("pbk");
|
||||||
|
if (p.get("sid")) $("BOOT_SID").value = p.get("sid");
|
||||||
|
} catch (_) { /* not a full link yet */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
form.addEventListener("input", (e) => {
|
||||||
|
if (e.target.id === "vless") parseVless(e.target.value);
|
||||||
|
update();
|
||||||
|
});
|
||||||
|
document.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => setTab(b.dataset.tab)));
|
||||||
|
$("copy").addEventListener("click", async () => {
|
||||||
|
try { await navigator.clipboard.writeText(current[tab]); $("copy").textContent = "Скопировано"; }
|
||||||
|
catch (_) { $("copy").textContent = "Не вышло"; }
|
||||||
|
setTimeout(() => ($("copy").textContent = "Копировать"), 1200);
|
||||||
|
});
|
||||||
|
$("download").addEventListener("click", () => {
|
||||||
|
const name = tab === "env" ? `${$("PROFILE_NAME").value.trim() || "home"}.env`
|
||||||
|
: tab === "yaml" ? (radio("TARGET") === "mobile" ? "flclash.yaml" : `${$("PROFILE_NAME").value.trim() || "home"}.yaml`)
|
||||||
|
: "steps.txt";
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = URL.createObjectURL(new Blob([current[tab]], { type: "text/plain" }));
|
||||||
|
a.download = name;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(a.href);
|
||||||
|
});
|
||||||
|
update();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
304
web/index.src.html
Normal file
304
web/index.src.html
Normal file
@ -0,0 +1,304 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>mihomo-kit</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #f6f6f3; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e2e1dc;
|
||||||
|
--accent: #2f6f4f; --accent-soft: #e4efe8; --err: #b3261e; --code-bg: #f1f0ec;
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root:not([data-theme="light"]) {
|
||||||
|
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
|
||||||
|
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
|
||||||
|
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0; background: var(--bg); color: var(--text);
|
||||||
|
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
.wrap { max-width: 1280px; margin: 0 auto; padding: 24px 16px 48px; }
|
||||||
|
header h1 { font-size: 20px; margin: 0 0 4px; }
|
||||||
|
header p { margin: 0 0 20px; color: var(--muted); }
|
||||||
|
.grid { display: grid; grid-template-columns: minmax(0, 420px) minmax(0, 1fr); gap: 20px; align-items: start; }
|
||||||
|
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
|
||||||
|
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
|
||||||
|
fieldset { border: 0; border-top: 1px solid var(--line); margin: 0; padding: 14px 0 4px; }
|
||||||
|
fieldset:first-child { border-top: 0; padding-top: 0; }
|
||||||
|
legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
|
||||||
|
label { display: block; margin: 8px 0 4px; color: var(--muted); font-size: 13px; }
|
||||||
|
input[type=text], textarea {
|
||||||
|
width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px;
|
||||||
|
background: var(--bg); color: var(--text); font: 13px ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
}
|
||||||
|
textarea { min-height: 64px; resize: vertical; }
|
||||||
|
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
|
||||||
|
.seg label { margin: 0; padding: 6px 12px; cursor: pointer; color: var(--text); font-size: 13px; }
|
||||||
|
.seg input { display: none; }
|
||||||
|
.seg label:has(input:checked) { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
|
||||||
|
.row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
|
||||||
|
.check { display: flex; gap: 8px; align-items: center; margin: 6px 0; color: var(--text); font-size: 14px; }
|
||||||
|
.check input { margin: 0; }
|
||||||
|
.hint { color: var(--muted); font-size: 12px; margin: 4px 0 0; }
|
||||||
|
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; }
|
||||||
|
details summary { cursor: pointer; color: var(--muted); font-size: 13px; margin-top: 8px; }
|
||||||
|
.tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 10px; }
|
||||||
|
.tabs button, .actions button {
|
||||||
|
border: 1px solid var(--line); background: var(--panel); color: var(--text);
|
||||||
|
padding: 6px 12px; border-radius: 6px; cursor: pointer; font: inherit; font-size: 13px;
|
||||||
|
}
|
||||||
|
.tabs button[aria-selected=true] { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); font-weight: 600; }
|
||||||
|
.actions { display: flex; gap: 6px; margin-left: auto; }
|
||||||
|
.out-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||||
|
pre {
|
||||||
|
margin: 0; padding: 14px; background: var(--code-bg); border: 1px solid var(--line); border-radius: 8px;
|
||||||
|
overflow: auto; max-height: 78vh; font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre;
|
||||||
|
}
|
||||||
|
.error { color: var(--err); margin: 0 0 10px; font-weight: 600; }
|
||||||
|
.note { color: var(--muted); font-size: 12px; margin-top: 10px; }
|
||||||
|
[hidden] { display: none !important; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap">
|
||||||
|
<header>
|
||||||
|
<h1>mihomo-kit — конструктор конфига</h1>
|
||||||
|
<p>Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у <code>mihomo-kit.sh</code> на роутере.</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="grid">
|
||||||
|
<form class="panel" id="form" autocomplete="off">
|
||||||
|
<fieldset>
|
||||||
|
<legend>Куда</legend>
|
||||||
|
<div class="row">
|
||||||
|
<div class="seg">
|
||||||
|
<label><input type="radio" name="TARGET" value="router" checked>Роутер (nikki)</label>
|
||||||
|
<label><input type="radio" name="TARGET" value="mobile">Телефон (FlClash)</label>
|
||||||
|
</div>
|
||||||
|
<div class="seg" data-router>
|
||||||
|
<label><input type="radio" name="LOCATION" value="home" checked>Дом</label>
|
||||||
|
<label><input type="radio" name="LOCATION" value="street">Улица</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="hint" data-router>Улица: OpenVPN идёт через выбранную RU-ноду (группа OVPN-EXIT).</p>
|
||||||
|
<label for="PROFILE_NAME" data-router>Имя профиля на роутере</label>
|
||||||
|
<input type="text" id="PROFILE_NAME" value="home" data-router>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>Подписки</legend>
|
||||||
|
<label for="SUBS">URL, по одному на строку → sub0, sub1, …</label>
|
||||||
|
<textarea id="SUBS" placeholder="https://sub.example.com/sub/xxxx"></textarea>
|
||||||
|
<label for="RU_IPS">Доп. IP через RU (CIDR через пробел)</label>
|
||||||
|
<input type="text" id="RU_IPS" value="194.190.191.112/32">
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<legend>BOOT</legend>
|
||||||
|
<label class="check"><input type="checkbox" id="BOOT" checked>Качать подписки через BOOT (seed)</label>
|
||||||
|
<div data-boot>
|
||||||
|
<label for="vless">Вставить vless:// ссылку — поля заполнятся сами</label>
|
||||||
|
<input type="text" id="vless" placeholder="vless://uuid@host:443?security=reality&sni=…&pbk=…&sid=…">
|
||||||
|
<div class="two">
|
||||||
|
<div><label for="BOOT_SERVER">server</label><input type="text" id="BOOT_SERVER"></div>
|
||||||
|
<div><label for="BOOT_PORT">port</label><input type="text" id="BOOT_PORT" value="443"></div>
|
||||||
|
</div>
|
||||||
|
<label for="BOOT_UUID">uuid</label><input type="text" id="BOOT_UUID">
|
||||||
|
<div class="two">
|
||||||
|
<div><label for="BOOT_SNI">servername (SNI)</label><input type="text" id="BOOT_SNI" value="eh.vk.ru"></div>
|
||||||
|
<div><label for="BOOT_SID">short-id</label><input type="text" id="BOOT_SID"></div>
|
||||||
|
</div>
|
||||||
|
<label for="BOOT_PBK">public-key</label><input type="text" id="BOOT_PBK">
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset data-router>
|
||||||
|
<legend>Модули роутера</legend>
|
||||||
|
<label class="check"><input type="checkbox" id="TORRENT" checked>Торренты (порты 20000–20199 → TORRENT-SEL)</label>
|
||||||
|
|
||||||
|
<label class="check"><input type="checkbox" id="OPENVPN">OpenVPN (BMSTU, OTP через bmstu-otp.sh)</label>
|
||||||
|
<details data-openvpn>
|
||||||
|
<summary>параметры OpenVPN</summary>
|
||||||
|
<label for="OVPN_SERVER_HOST">сервер</label><input type="text" id="OVPN_SERVER_HOST">
|
||||||
|
<label for="OVPN_SERVER_IPS">IP сервера (не пускать в туннель)</label><input type="text" id="OVPN_SERVER_IPS">
|
||||||
|
<label for="OVPN_ROUTES">сети через туннель</label><input type="text" id="OVPN_ROUTES">
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<label class="check"><input type="checkbox" id="TAILSCALE">Tailscale</label>
|
||||||
|
<div data-tailscale>
|
||||||
|
<label for="TS_HOSTNAME">hostname ноды</label><input type="text" id="TS_HOSTNAME" value="fudy-mihomo">
|
||||||
|
<label for="TS_DOMAINS">split-DNS домены тейлнета, кроме *.ts.net</label><input type="text" id="TS_DOMAINS">
|
||||||
|
<label class="check"><input type="checkbox" id="TS_EXIT">Через TS-EXIT (только ss/hysteria2/tuic ноды)</label>
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="out-head">
|
||||||
|
<div class="tabs" role="tablist">
|
||||||
|
<button type="button" data-tab="yaml" aria-selected="true">config.yaml</button>
|
||||||
|
<button type="button" data-tab="env" aria-selected="false" data-router>profile .env</button>
|
||||||
|
<button type="button" data-tab="steps" aria-selected="false">Что дальше</button>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button type="button" id="copy">Копировать</button>
|
||||||
|
<button type="button" id="download">Скачать</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="error" id="error" hidden></p>
|
||||||
|
<pre id="out"></pre>
|
||||||
|
<p class="note">На роутере удобнее держать <code>.env</code> и собирать там: <code>mihomo-kit.sh build</code>. YAML отсюда — для телефона или разовой проверки.</p>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
/*__ENGINE__*/
|
||||||
|
</script>
|
||||||
|
<script>
|
||||||
|
const TEMPLATES = /*__TEMPLATES__*/;
|
||||||
|
const D = MihomoKit.DEFAULTS;
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
const form = $("form");
|
||||||
|
let tab = "yaml";
|
||||||
|
let current = { yaml: "", env: "", steps: "" };
|
||||||
|
|
||||||
|
for (const k of ["OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) $(k).value = D[k];
|
||||||
|
|
||||||
|
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
|
||||||
|
function flag(id) { return $(id).checked ? "1" : "0"; }
|
||||||
|
|
||||||
|
function readVars() {
|
||||||
|
const v = {
|
||||||
|
TARGET: radio("TARGET"), LOCATION: radio("LOCATION"),
|
||||||
|
SUBS: $("SUBS").value.trim().split(/\s+/).filter(Boolean).join(" "),
|
||||||
|
RU_IPS: $("RU_IPS").value.trim(),
|
||||||
|
BOOT: flag("BOOT"), TORRENT: flag("TORRENT"), OPENVPN: flag("OPENVPN"),
|
||||||
|
TAILSCALE: flag("TAILSCALE"), TS_EXIT: flag("TS_EXIT"),
|
||||||
|
};
|
||||||
|
for (const k of ["BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID",
|
||||||
|
"TS_HOSTNAME", "TS_DOMAINS", "OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) {
|
||||||
|
v[k] = $(k).value.trim();
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
|
||||||
|
|
||||||
|
function envFile(v) {
|
||||||
|
const keys = ["TARGET", "LOCATION", "SUBS", "BOOT"];
|
||||||
|
if (v.BOOT === "1") keys.push("BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID");
|
||||||
|
keys.push("TORRENT", "RU_IPS", "OPENVPN");
|
||||||
|
if (v.OPENVPN === "1") keys.push("OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES");
|
||||||
|
keys.push("TAILSCALE");
|
||||||
|
if (v.TAILSCALE === "1") keys.push("TS_HOSTNAME", "TS_DOMAINS", "TS_EXIT");
|
||||||
|
return "# mihomo-kit profile (secrets inside: chmod 600)\n" +
|
||||||
|
keys.map((k) => `${k}=${q(v[k] ?? "")}`).join("\n") + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
function steps(v) {
|
||||||
|
const name = $("PROFILE_NAME").value.trim() || "home";
|
||||||
|
if (v.TARGET === "mobile") {
|
||||||
|
return [
|
||||||
|
"Телефон (FlClash):",
|
||||||
|
"1. Скачай config.yaml (кнопка «Скачать»).",
|
||||||
|
"2. FlClash → Профили → + → Файл → выбери config.yaml.",
|
||||||
|
"3. Включи профиль; геобазы скачаются при первом запуске.",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
const s = [
|
||||||
|
"Роутер (nikki). Один раз на новом роутере — см. README, раздел «Новый роутер».",
|
||||||
|
"",
|
||||||
|
`1. Сохрани profile .env как /etc/nikki/profiles.d/${name}.env`,
|
||||||
|
` (общие секреты можно вынести в /etc/nikki/profiles.d/common.env)`,
|
||||||
|
` chmod 600 /etc/nikki/profiles.d/*.env`,
|
||||||
|
"2. Собери и включи:",
|
||||||
|
` mihomo-kit.sh build ${name}`,
|
||||||
|
` mihomo-kit.sh use ${name}`,
|
||||||
|
];
|
||||||
|
if (v.OPENVPN === "1") s.push("", "OpenVPN: заполни /etc/nikki/bmstu.env, положи .ovpn в /etc/nikki/bmstu.ovpn,",
|
||||||
|
" cron (bmstu-otp.sh check) ставит mihomo-kit.sh install.",
|
||||||
|
v.LOCATION === "street" ? " На улице выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
|
||||||
|
if (v.TAILSCALE === "1") s.push("", "Tailscale: открой любой 100.x адрес, ссылка для входа появится в логе:",
|
||||||
|
" grep 'To start' /var/log/nikki/core.log",
|
||||||
|
" Потом в админке Tailscale: Disable key expiry для " + (v.TS_HOSTNAME || "ноды") + ".");
|
||||||
|
return s.join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function update() {
|
||||||
|
const v = readVars();
|
||||||
|
const router = v.TARGET === "router";
|
||||||
|
document.querySelectorAll("[data-router]").forEach((el) => (el.hidden = !router));
|
||||||
|
document.querySelectorAll("[data-boot]").forEach((el) => (el.hidden = v.BOOT !== "1"));
|
||||||
|
document.querySelectorAll("[data-openvpn]").forEach((el) => (el.hidden = v.OPENVPN !== "1"));
|
||||||
|
document.querySelectorAll("[data-tailscale]").forEach((el) => (el.hidden = v.TAILSCALE !== "1"));
|
||||||
|
if (!router && tab === "env") setTab("yaml");
|
||||||
|
|
||||||
|
const err = $("error");
|
||||||
|
try {
|
||||||
|
current.yaml = MihomoKit.render(TEMPLATES, v);
|
||||||
|
err.hidden = true;
|
||||||
|
} catch (e) {
|
||||||
|
current.yaml = "";
|
||||||
|
err.textContent = e.message;
|
||||||
|
err.hidden = false;
|
||||||
|
}
|
||||||
|
current.env = envFile(v);
|
||||||
|
current.steps = steps(v);
|
||||||
|
$("out").textContent = current[tab];
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTab(t) {
|
||||||
|
tab = t;
|
||||||
|
document.querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tab === t)));
|
||||||
|
$("out").textContent = current[t];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseVless(link) {
|
||||||
|
try {
|
||||||
|
const u = new URL(link.trim());
|
||||||
|
if (u.protocol !== "vless:") return;
|
||||||
|
const p = u.searchParams;
|
||||||
|
$("BOOT_UUID").value = decodeURIComponent(u.username);
|
||||||
|
$("BOOT_SERVER").value = u.hostname.replace(/^\[|\]$/g, "");
|
||||||
|
$("BOOT_PORT").value = u.port || "443";
|
||||||
|
if (p.get("sni")) $("BOOT_SNI").value = p.get("sni");
|
||||||
|
if (p.get("pbk")) $("BOOT_PBK").value = p.get("pbk");
|
||||||
|
if (p.get("sid")) $("BOOT_SID").value = p.get("sid");
|
||||||
|
} catch (_) { /* not a full link yet */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
form.addEventListener("input", (e) => {
|
||||||
|
if (e.target.id === "vless") parseVless(e.target.value);
|
||||||
|
update();
|
||||||
|
});
|
||||||
|
document.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => setTab(b.dataset.tab)));
|
||||||
|
$("copy").addEventListener("click", async () => {
|
||||||
|
try { await navigator.clipboard.writeText(current[tab]); $("copy").textContent = "Скопировано"; }
|
||||||
|
catch (_) { $("copy").textContent = "Не вышло"; }
|
||||||
|
setTimeout(() => ($("copy").textContent = "Копировать"), 1200);
|
||||||
|
});
|
||||||
|
$("download").addEventListener("click", () => {
|
||||||
|
const name = tab === "env" ? `${$("PROFILE_NAME").value.trim() || "home"}.env`
|
||||||
|
: tab === "yaml" ? (radio("TARGET") === "mobile" ? "flclash.yaml" : `${$("PROFILE_NAME").value.trim() || "home"}.yaml`)
|
||||||
|
: "steps.txt";
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = URL.createObjectURL(new Blob([current[tab]], { type: "text/plain" }));
|
||||||
|
a.download = name;
|
||||||
|
a.click();
|
||||||
|
URL.revokeObjectURL(a.href);
|
||||||
|
});
|
||||||
|
update();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Loading…
Reference in New Issue
Block a user