Compare commits

..

No commits in common. "main" and "core-v1.19.33-ts7" have entirely different histories.

85 changed files with 555 additions and 6613 deletions

6
.gitignore vendored
View File

@ -3,7 +3,6 @@
!tests/fixtures/*.env !tests/fixtures/*.env
!presets/*.env !presets/*.env
*.ovpn *.ovpn
!tests/fixtures/*.ovpn
/configs/ /configs/
/reference/ /reference/
@ -11,8 +10,3 @@
__pycache__/ __pycache__/
tools/core/work/ tools/core/work/
tools/core/dist/ tools/core/dist/
tools/nikki-work/
# Local agent notes
/AGENTS.md
/PROJECT_NOTES.md

438
README.md
View File

@ -1,9 +1,8 @@
# mihomo-kit # mihomo-kit
Конфиги mihomo из одного набора шаблонов: роутер под nikki (профили `main` — дома в России, `whitelist` — белые списки, `foreign` — за рубежом) Конфиги mihomo из одного набора шаблонов: роутер под nikki (профили `main` — дома в России, `whitelist` — белые списки, `foreign` — за рубежом)
и приложения на телефоне и компьютере (FlClash, Clash Mi и другие на ядре mihomo). Подписки через и телефон (FlClash). Подписки через BOOT-ноду, `ru-inside` напрямую, остальные `.ru`
BOOT-ноду, `ru-inside` напрямую, остальные `.ru` через RU, опционально OpenVPN (рабочая или через RU, опционально OpenVPN с TOTP и Tailscale.
учебная сеть, с одноразовыми кодами TOTP или без) и Tailscale.
## Установка на роутер ## Установка на роутер
@ -21,47 +20,15 @@ ssh root@192.168.32.1 sh /etc/nikki/kit/install.sh
``` ```
Установщик ставит nikki (если нет), правильное ядро, фиксы и kit со страницей LuCI — Установщик ставит nikki (если нет), правильное ядро, фиксы и kit со страницей LuCI —
ничего не спрашивает. Пакеты nikki берутся из релиза `nikki-<версия>` этого репозитория ничего не спрашивает. Дальше всё в браузере: LuCI → **Службы → mihomo-kit → Настройка**
(зеркало релиза [OpenWrt-nikki](https://github.com/nikkinikki-org/OpenWrt-nikki/releases)),
и только если там нет — с GitHub; зависимости — из обычных фидов OpenWrt. Нужна OpenWrt 24.10
(opkg); 25.12 с apk пока не поддерживается.
Если роутер не достаёт ни до одного источника — на компьютере скачать архив под свой роутер
(`nikki_<DISTRIB_ARCH>-openwrt-24.10.tar.gz`, арх — `grep DISTRIB_ARCH /etc/openwrt_release`;
установщик сам печатает имя и ссылку), положить в `/tmp` роутера и запустить с `NIKKI_TGZ`:
```sh
scp -O nikki_aarch64_cortex-a53-openwrt-24.10.tar.gz root@192.168.32.1:/tmp/
ssh root@192.168.32.1 'NIKKI_TGZ=/tmp/nikki_aarch64_cortex-a53-openwrt-24.10.tar.gz sh /etc/nikki/kit/install.sh'
```
Архив релиза nikki — это готовый подписанный фид: установщик распаковывает его в `/tmp`,
временно подключает к opkg (подпись проверяется ключом nikki из kit,
`router/nikki-key-build.pub`), ставит `mihomo-meta nikki luci-app-nikki luci-i18n-nikki-ru`
и убирает фид. Не скачалось или не поставилось — установка останавливается с ошибкой. Дальше всё в браузере: LuCI → **Службы → mihomo-kit**
(адрес установщик печатает в конце; если пункта нет — выйти из LuCI и войти снова). (адрес установщик печатает в конце; если пункта нет — выйти из LuCI и войти снова).
Страница разбита на вкладки по темам: «Обзор» (состояние, профиль), «Подписки» (подписки, Там подписки, vless-ссылки BOOT, торренты, OpenVPN (файл `.ovpn`, логин, пароль,
vless-ссылки BOOT), «Правила» (торренты, пуши, свои домены и IP), «Свои серверы», «Пулы и TOTP-секрет), Tailscale; «Сохранить и применить» собирает профили `main`, `whitelist` и `foreign`,
сервисы», «OpenVPN», «Tailscale», «CSQTT», «Телефон», «Система» (облегчённый режим, ядро,
обновления, экспорт). На вкладке сверху её состояние и кнопки, ниже настройки. Одна кнопка
«Сохранить и применить» под вкладками сохраняет все вкладки разом: собирает профили `main`, `whitelist` и `foreign`,
включает профиль и, если включён Tailscale, показывает ссылку для входа — открыть её, включает профиль и, если включён Tailscale, показывает ссылку для входа — открыть её,
войти, в админке Tailscale **Disable key expiry** для ноды. войти, в админке Tailscale **Disable key expiry** для ноды.
На новом роутере (ещё без настроек) установщик сразу настраивает nikki: перехват без TUN Позже настройки меняются там же — «Изменить настройки»; ключи, добавленные в
(TCP — redirect, UDP — tproxy, `tun_enabled=0`, как в облегчённом режиме) и IPv6 выключен `common.env` / `bmstu.env` руками, сохраняются.
везде (`mixin.ipv6`, `mixin.dns_ipv6`, `proxy.ipv6_dns_hijack`, `proxy.ipv6_proxy`). В форме
торренты и обход для пушей по умолчанию выключены, а конфиг для телефона включён. Включение
профиля (`use`, «Сохранить и применить») включает и nikki, в том числе автозапуск.
Маленькая флешка: opkg сравнивает свободное место с распакованным размером пакетов (у mihomo
около 55 МБ), а сжимающий overlay (ubifs, jffs2) хранит их примерно в размере .ipk (около 20 МБ).
Поэтому установщик сам считает место по .ipk и ставит с `--force-space`, а если места правда нет,
останавливается до установки. Пакеты качаются в `/tmp`, весь вывод установки сохраняется в
`/tmp/mihomo-kit-install.log`.
Позже настройки меняются там же; ключи, добавленные в
`common.env` / `openvpn.env` руками, сохраняются.
Роутер без LuCI или вопросы в терминале по-старому: Роутер без LuCI или вопросы в терминале по-старому:
`wget -qO- …/install.sh | sh -s -- --cli` (или `mihomo-kit.sh setup --cli`). `wget -qO- …/install.sh | sh -s -- --cli` (или `mihomo-kit.sh setup --cli`).
@ -74,7 +41,7 @@ vless-ссылки BOOT), «Правила» (торренты, пуши, сво
## Каждый день ## Каждый день
То же самое из веб-интерфейса: LuCI → **Службы → mihomo-kit**. Там переключение То же самое из веб-интерфейса: LuCI → **Службы → mihomo-kit**. Там переключение
профиля, OpenVPN вкл/выкл/переподключить (с текущим кодом, если он нужен), ссылка для входа в Tailscale, профиля, OpenVPN вкл/выкл/переподключить с текущим OTP, ссылка для входа в Tailscale,
пересборка, обновление kit и `fix`; вывод команды показывается внизу страницы. пересборка, обновление kit и `fix`; вывод команды показывается внизу страницы.
Перенос настроек на другой роутер — «Экспорт настроек» там же: один файл `.kit` с Перенос настроек на другой роутер — «Экспорт настроек» там же: один файл `.kit` с
@ -98,16 +65,16 @@ mihomo-kit.sh use whitelist # попал на белые списки
mihomo-kit.sh use main # обычный интернет в России mihomo-kit.sh use main # обычный интернет в России
mihomo-kit.sh use foreign # за рубежом: российское через RU, остальное напрямую mihomo-kit.sh use foreign # за рубежом: российское через RU, остальное напрямую
ovpn.sh off # OpenVPN выключить: освободить сессию для другого устройства bmstu-otp.sh off # OpenVPN выключить: освободить сессию для другого устройства
ovpn.sh on # включить постоянно bmstu-otp.sh on # включить постоянно
ovpn.sh sched on # работать по расписанию; sched off — выключить (как off) bmstu-otp.sh sched on # работать по расписанию; sched off — выключить (как off)
ovpn.sh sched 09:00 17:00 # запомнить часы расписания (время роутера), включает их sched on bmstu-otp.sh sched 09:00 17:00 # запомнить часы расписания (МСК), включает их sched on
ovpn.sh sched 09:00 17:00 weekdays # то же, только по будням (дни: 12345, weekend, all) bmstu-otp.sh sched 09:00 17:00 weekdays # то же, только по будням (дни: 12345, weekend, all)
ovpn.sh sched days 12345 # поменять только дни (1 — пн … 7 — вс) bmstu-otp.sh sched days 12345 # поменять только дни (1 — пн … 7 — вс)
ovpn.sh for 60 # поднять на 60 минут поверх режима, потом вернуть режим bmstu-otp.sh for 60 # поднять на 60 минут поверх режима, потом вернуть режим
ovpn.sh extend 60 # продлить таймер на 60 минут (не дальше 12 ч от сейчас) bmstu-otp.sh extend 60 # продлить таймер на 60 минут (не дальше 12 ч от сейчас)
ovpn.sh stop # остановить таймер bmstu-otp.sh stop # остановить таймер
ovpn.sh status # что решает сейчас, когда следующее переключение, отвечает ли туннель bmstu-otp.sh status # что решает сейчас, когда следующее переключение, отвечает ли туннель
``` ```
Эти же кнопки и часы расписания есть на странице LuCI (Службы → mihomo-kit). Там же видно, Эти же кнопки и часы расписания есть на странице LuCI (Службы → mihomo-kit). Там же видно,
@ -126,96 +93,32 @@ ovpn.sh status # что решает сейчас, когда с
режима, а когда истекает или по «Остановить таймер», возвращает режим. Так можно держать режима, а когда истекает или по «Остановить таймер», возвращает режим. Так можно держать
OpenVPN выключенным и включать его только на время, не трогая расписание. OpenVPN выключенным и включать его только на время, не трогая расписание.
Дни недели — галки Пн…Вс рядом с расписанием (`OVPN_SCHED_DAYS` в `openvpn.env`, по умолчанию Дни недели — галки Пн…Вс рядом с расписанием (`OVPN_SCHED_DAYS` в `bmstu.env`, по умолчанию
все); окно через полночь относится ко дню, в который началось: «22:00–02:00 по будням» работает и все); окно через полночь относится ко дню, в который началось: «22:00–02:00 по будням» работает и
в ночь с пятницы на субботу, но не с воскресенья на понедельник. в ночь с пятницы на субботу, но не с воскресенья на понедельник.
Время — локальное на роутере (Система → Система → часовой пояс). Границы окна каждый день сдвигаются на случайные, но Время — локальное на роутере (МСК). Границы окна каждый день сдвигаются на случайные, но
постоянные в течение дня ±10 минут (`OVPN_SCHED_JITTER`), чтобы включение и выключение не постоянные в течение дня ±10 минут (`OVPN_SCHED_JITTER`), чтобы включение и выключение не
приходились каждый раз на одну и ту же секунду. Поэтому окно короче 20 минут (или длиннее приходились каждый раз на одну и ту же секунду. Поэтому окно короче 20 минут (или длиннее
23 ч 40 мин) не принимается. Сети VPN (`OVPN_ROUTES`) следуют за туннелем: пока он 23 ч 40 мин) не принимается. Маршруты BMSTU (`OVPN_ROUTES`) следуют за туннелем: пока он
выключен по любой причине, они убраны. выключен по любой причине, они убраны.
Многие VPN-серверы пускают только одну сессию на пользователя. `off` закрывает туннель в На сервере BMSTU одна сессия на пользователя. `off` закрывает туннель в mihomo и не даёт
mihomo и не даёт cron поднять его снова, и убирает его сети (`OVPN_ROUTES`) из cron поднять его снова, и убирает его подсети (`OVPN_ROUTES`) из маршрутизации: они лежат в
маршрутизации: они лежат в rule-provider `openvpn-routes`, который `off` очищает, а `on` rule-provider `bmstu-routes`, который `off` очищает, а `on` возвращает, без перезапуска nikki.
возвращает, без перезапуска nikki. Эти адреса тогда идут по обычным правилам, как любые Адреса BMSTU тогда идут по обычным правилам, как любые другие сайты: публичные открываются,
другие сайты: публичные открываются, внутренние — нет. Ядро kit при закрытии туннеля внутренние (`172.x`) — нет. Ядро kit при закрытии туннеля отправляет серверу EXIT, как
отправляет серверу EXIT, как OpenVPN Connect, и сессия освобождается за секунды — можно сразу Connect, и сессия освобождается за секунды — можно сразу подключаться с другого устройства.
подключаться с другого устройства. С другим ядром EXIT не уходит, и сервер держит сессию до С другим ядром EXIT не уходит, и сервер держит сессию до своего `ping-restart` (~5 минут).
своего `ping-restart` (~5 минут).
На `whitelist` и `foreign` OpenVPN идёт через группу `OVPN-EXIT` — один раз выбрать в На `whitelist` OpenVPN идёт через группу `OVPN-EXIT` — один раз выбрать в дашборде RU-ноду.
дашборде RU-ноду (рассчитано на VPN-сервер в России).
### OpenVPN
LuCI → вкладка «OpenVPN» → галка «Включить OpenVPN»:
- **Файл .ovpn** — профиль, который выдал администратор VPN (тот же, что для OpenVPN Connect
или openvpn). Сервер берётся из его строк `remote`.
- **Логин** и **пароль** — обычный пароль, без одноразового кода.
- **Сети через VPN** — адреса, которые открываются только через VPN (CIDR через пробел). При
загрузке `.ovpn` сюда подставляются его строки `route`; остальной трафик идёт как обычно.
- **TOTP-секрет** — только если VPN просит одноразовый код из приложения (Google
Authenticator и т. п.): секрет из QR-кода, строка из букв и цифр (`secret=…` в ссылке
`otpauth://`). Роутер сам считает код и подставляет его при каждом подключении. Без секрета
пароль уходит как есть.
- **Как отправлять код** — «сам» подходит обычно: если в `.ovpn` есть `static-challenge`,
код уходит отдельным полем (как у OpenVPN Connect), иначе — сразу за паролем. Если сервер не
принимает код, попробовать другие варианты (`PASS_FORMAT` в `openvpn.env`).
- **Адрес для проверки** — страница за VPN для кнопки «Проверить».
Файлы на роутере: `/etc/nikki/openvpn.ovpn`, `/etc/nikki/openvpn.env` (логин, пароль, секрет,
600). Группа в дашборде — `OPENVPN`.
Обновление со старых версий kit (там OpenVPN был только для BMSTU и файлы назывались
`bmstu.*`) переносит всё само: `bmstu.env` / `bmstu.ovpn` → `openvpn.env` / `openvpn.ovpn`,
строки cron и init-скрипта nikki — на `ovpn.sh`, а сети, адреса сервера и адрес проверки,
которые раньше были зашиты в kit, записываются в `common.env`. Старая команда `bmstu-otp.sh`
работает как ссылка на `ovpn.sh`. Старые файлы экспорта импортируются так же.
### Граф
LuCI → **Службы → mihomo-kit → Граф** — собранный профиль картинкой, слева направо:
правила (сверху вниз — в порядке, в котором mihomo их проверяет) → группы → подписки и
свои серверы → через что они подключаются → выходы. Выходы — последняя колонка: `DIRECT`
и прокси `type: direct` (`CSQTT`, интерфейс `csqtt0`). Фиолетовый пунктир — `dialer-proxy`,
серый — к серверу напрямую (у прокси и подписки нет `dialer-proxy`: Tailscale и OpenVPN на
`main`). Зелёный — через что качается подписка (`proxy:` провайдера, обычно `BOOT-AUTO`) и
`<имя>-my`, читающий файл основной подписки. То, куда правила не ведут (`BOOT-AUTO`, `BOOT`,
seed-ноды), — под чертой «служебное». Правило в `DIRECT`/`REJECT` заканчивается на самом
правиле. Фильтры групп (`∋` filter, `∌` exclude-filter) видны на рёбрах при наведении;
⛶ — на весь экран.
Для запущенного профиля поверх схемы — живое состояние из API mihomo (раз в 3 секунды,
пока вкладка открыта): что выбрано в каждой группе сейчас (синее) с задержкой, сколько нод
подписки живы, и куда идут соединения (оранжевое, с числом на узлах) — по `chains`
соединения и дальше по цепочке `dialer-proxy`. Наведи или нажми на узел — подсветится всё,
что в него приходит и что из него выходит, снизу — подробности и «путь сейчас». «Только
выбранное» прячет невыбранные пункты групп. Другие профили (`whitelist`, `foreign`) — из
списка, без живого состояния.
Править на графе (запущенный профиль):
- нажать на группу — справа её пункты с последней задержкой: выбрать (`select`) или закрепить
(`fallback` / `url-test`, «Снять закрепление» возвращает автовыбор), «Проверить задержки» —
все пункты разом. Сразу через API mihomo, без пересборки; выбор запоминается и переживает
перезапуск (`cache.db`), до следующей смены в дашборде;
- сервисы и пулы: «+ сервис» (есть «как Claude»), «+ пул» или нажать на группу сервиса / пула;
«через что» у сервиса можно и перетащить от его группы на MY / FOREIGN / RU / MAIN / DIRECT /
пул. «Сохранить и применить» меняет в `common.env` только `SERVICES`/`SVC_*` и
`POOLS`/`POOL_*` (`mihomo-kit.sh services`), проверяет, что все профили собираются, и
перезапускает текущий. Это те же ключи, что на «Управлении»: где удобнее, там и правь.
Без роутера: [tools/graph.html](tools/graph.html) из репозитория открыть в браузере и выбрать
или перетащить любой конфиг mihomo. Для живого состояния — адрес API и secret (они в ссылке
«открыть дашборд»).
### OpenVPN под видом OpenVPN Connect ### OpenVPN под видом OpenVPN Connect
Для VPN-сервера роутер выглядит как OpenVPN Connect 3.7.1 (5558) на macOS. Обычный Для сервера BMSTU роутер выглядит как OpenVPN Connect 3.7.1 (5558) на macOS. Обычный
mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=22`, своя строка опций), и в mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=22`, своя строка опций), и в
логах сервера это видно. Маскировку дают ядро kit (правка логах сервера это видно. Маскировку дают ядро kit (правка
`tools/core/openvpn-connect-mimic.patch`) и `ovpn.sh`, который пишет в провайдер `tools/core/openvpn-connect-mimic.patch`) и `bmstu-otp.sh`, который пишет в провайдер
поля `options-string` и `peer-info-raw`. поля `options-string` и `peer-info-raw`.
Совпадает с Connect: Совпадает с Connect:
@ -228,16 +131,16 @@ mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=2
повторяет позже, а не считает пароль отклонённым), `DNS_OPTION_V2` (DNS из `dns server …` повторяет позже, а не считает пароль отклонённым), `DNS_OPTION_V2` (DNS из `dns server …`
ядро берёт так же, как из `dhcp-option DNS`), `AUTH_PENDING_KW` и `PUSH_UPDATE` (сообщения, ядро берёт так же, как из `dhcp-option DNS`), `AUTH_PENDING_KW` и `PUSH_UPDATE` (сообщения,
которые ядро пропускает); которые ядро пропускает);
- код TOTP в формате `SCRV1`, как отправляет Connect при `static-challenge`; - пароль в формате `SCRV1`, как отправляет Connect при `static-challenge`;
- `ping 60`, `ping-restart 300` — то, что обычно присылает сервер; - `ping 60`, `ping-restart 300` — то, что присылает сервер;
- туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу - туннель держится всё время, как у Connect (`auto-connect` у прокси). Он поднимается сразу
при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo при загрузке провайдера, без ожидания трафика: init-скрипт nikki перед стартом mihomo
пишет провайдер со свежим кодом (`ovpn.sh write`). После обрыва ядро переподключается пишет провайдер со свежим OTP (`bmstu-otp.sh write`). После обрыва ядро переподключается
само, с auth-token сессии вместо пароля и кода. Если сервер токен не принял (AUTH_FAILED), само, с auth-token сессии вместо пароля и OTP. Если сервер токен не принял (AUTH_FAILED),
ядро больше не пробует — как Connect, который тогда просит новый код, — и туннель ядро больше не пробует — как Connect, который тогда просит новый OTP, — и туннель
поднимает cron (`ovpn.sh check`) со свежим кодом; поднимает cron (`bmstu-otp.sh check`) со свежим OTP;
- быстрых переподключений нет: некоторые серверы на моментальный реконнект после обрыва - быстрых переподключений нет: на моментальный реконнект после обрыва или кика сервер
или кика отвечают блокировкой учётки. После любого обрыва (в том числе молчаливого), неудачной отвечает блокировкой учётки. После любого обрыва (в том числе молчаливого), неудачной
попытки или отказа в авторизации ядро ждёт `OVPN_RECONNECT_PAUSE` секунд (по умолчанию попытки или отказа в авторизации ядро ждёт `OVPN_RECONNECT_PAUSE` секунд (по умолчанию
120). Пауза удваивается, пока попытки не удаются или туннель падает раньше чем через 5 120). Пауза удваивается, пока попытки не удаются или туннель падает раньше чем через 5
минут после подъёма, но не больше 10 минут. Если сессию закрыл сам сервер (RESTART/HALT — минут после подъёма, но не больше 10 минут. Если сессию закрыл сам сервер (RESTART/HALT —
@ -245,8 +148,8 @@ mihomo представляется сам (`IV_VER=mihomo-openvpn`, `IV_PROTO=2
`OVPN_RECONNECT_PAUSE`). Она удваивается за каждый кик подряд, до 30 минут; сессия, `OVPN_RECONNECT_PAUSE`). Она удваивается за каждый кик подряд, до 30 минут; сессия,
продержавшаяся 30 минут, сбрасывает счёт. К каждой паузе добавляется случайный разброс продержавшаяся 30 минут, сбрасывает счёт. К каждой паузе добавляется случайный разброс
±`OVPN_RECONNECT_JITTER` секунд (по умолчанию 30), чтобы попытки не шли по часам. Пауза ±`OVPN_RECONNECT_JITTER` секунд (по умолчанию 30), чтобы попытки не шли по часам. Пауза
переживает перезагрузку провайдера и конфига, и трафик в сети VPN в это время туннель не переживает перезагрузку провайдера и конфига, и трафик в BMSTU в это время туннель не
поднимает. Новый код cron в паузе не берёт, кнопки LuCI тоже не переподключают; в поднимает. Новый OTP cron в паузе не берёт, кнопки LuCI тоже не переподключают; в
«Состоянии» видны причина (оборвался, не подключился, сервер отключил) и время следующей «Состоянии» видны причина (оборвался, не подключился, сервер отключил) и время следующей
попытки; попытки;
- при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT - при закрытии (`off`, перезапуск nikki, новый провайдер) сервер получает EXIT
@ -257,10 +160,10 @@ OpenSSL, поэтому набор шифров и расширений в Clien
разборе трафика, в логах сервера — нет. разборе трафика, в логах сервера — нет.
Без ядра kit (`stock`, `official`) эти поля игнорируются, и сервер снова видит mihomo. Без ядра kit (`stock`, `official`) эти поля игнорируются, и сервер снова видит mihomo.
Выключить маскировку: `OVPN_MIMIC=mihomo` в `openvpn.env`. После обновления Connect — взять Выключить маскировку: `OVPN_MIMIC=mihomo` в `bmstu.env`. После обновления Connect — взять
новые строки `Tunnel Options` и `Sending Peer Info` из его лога новые строки `Tunnel Options` и `Sending Peer Info` из его лога
(`~/Library/Application Support/OpenVPN Connect/log/ovpn.log`) и поправить (`~/Library/Application Support/OpenVPN Connect/log/ovpn.log`) и поправить
`mimic_connect_mac` в `router/ovpn.sh`. `mimic_connect_mac` в `router/bmstu-otp.sh`.
## Обслуживание ## Обслуживание
@ -278,7 +181,7 @@ mihomo-kit.sh build # после правки /etc/nikki/profiles.d/*.
| `/etc/nikki/profiles.d/common.env` | подписки, BOOT, модули (секреты, 600) | | `/etc/nikki/profiles.d/common.env` | подписки, BOOT, модули (секреты, 600) |
| `/etc/nikki/profiles.d/main.env`, `whitelist.env` | профили поверх common.env | | `/etc/nikki/profiles.d/main.env`, `whitelist.env` | профили поверх common.env |
| `/etc/nikki/profiles/*.yaml` | собранные конфиги, их запускает nikki | | `/etc/nikki/profiles/*.yaml` | собранные конфиги, их запускает nikki |
| `/etc/nikki/openvpn.env`, `openvpn.ovpn` | OpenVPN: логин, пароль, TOTP-секрет; профиль `.ovpn` | | `/etc/nikki/bmstu.env`, `bmstu.ovpn` | OpenVPN: логин, пароль, TOTP-секрет |
| `/etc/nikki/run/tailscale/` | ключ ноды Tailscale — не удалять | | `/etc/nikki/run/tailscale/` | ключ ноды Tailscale — не удалять |
У каждой подписки есть имя — так называется провайдер в дашборде, и к нему привязаны У каждой подписки есть имя — так называется провайдер в дашборде, и к нему привязаны
@ -308,109 +211,7 @@ BOOT — whitelisted seed-ноды для скачивания подписок:
рвётся, когда меняется нода под ним, — отсюда пропадающие уведомления. Отключается рвётся, когда меняется нода под ним, — отсюда пропадающие уведомления. Отключается
галочкой «Обход для пушей» (`PUSH=0` в `common.env`) — тогда пуши идут по общим правилам. галочкой «Обход для пушей» (`PUSH=0` в `common.env`) — тогда пуши идут по общим правилам.
Сервисы — сайты и приложения, которые всегда идут своим путём, что бы ни было выбрано в Свои серверы — LuCI → Настройка → «Свои серверы». Каждый сервер — карточка: имя (так он
`MAIN`: LuCI → вкладка «Пулы и сервисы» (кнопка «+ Claude» добавляет готовый). У каждого
сервиса своя группа в дашборде (имя заглавными: `claude` → `CLAUDE`) и свои правила —
выше «Своих правил», ниже туннелей, локальной сети и пушей. Чем матчить: списки geosite из
[MetaCubeX/meta-rules-dat](https://github.com/MetaCubeX/meta-rules-dat) (`anthropic` —
claude.ai, claude.com, anthropic.com, clau.de, claudeusercontent.com…; `openai`, `youtube`, …
— rule-provider `geosite-<имя>`, раз в сутки с jsdelivr), свои домены и IP. Куда:
- `MY` (по умолчанию) — группа `fallback` из своих серверов и `[MY]`-нод подписок: первый
живой, а не самый быстрый, как в `MY`. Выходной IP не скачет между серверами, пока сервер
жив, — сайт, который проверяет регион (Claude), видит одну страну. Другой сервер — выбрать
в дашборде, выбор запоминается. Если все свои серверы лежат, сервис не открывается, а не
уходит в `FOREIGN`. На `whitelist` и телефоне к своим серверам — через `MY-EXIT`, как всегда:
клиент → `CLAUDE` → свой сервер → `MY-EXIT` → нода подписки;
- `FOREIGN`, `RU`, `DIRECT`, `MAIN` или пул (ниже) — группа `select`, где это первый пункт, а
остальные можно выбрать в дашборде.
Списки доменов из файлов — поле «Списки доменов» (`SVC_<ИМЯ>_HOSTLIST`, пути через пробел): по
домену в строке, как хостлисты zapret. Если на роутере стоит zapret2 / zapret, под полем есть
кнопки с его списками из `/opt/zapret2/ipset/` и `/opt/zapret/ipset/` (без `*exclude*`): нажал —
файл добавлен, ещё раз — убран. Копировать ничего не нужно: файл читается при каждой сборке
профиля (поменялся список в zapret — «Применить»), домены уходят в inline rule-provider
`hostlist-<имя>` (`behavior: domain`, поиск по дереву — тысячи доменов не тормозят правила) и
попадают и в конфиг телефона. Как в zapret: `youtube.com` — с поддоменами, `^youtube.com` —
только он сам; `#`-комментарии, IP и мусор пропускаются, `.gz` читается. Файла нет — сборка
предупреждает и идёт дальше без него.
Чтобы сервис сохранял **один конкретный выходной сервер** при смене main/whitelist/foreign,
на графе откройте сервис → «Выход сервиса» → «Фиксированный сервер». Выберите источник
(«Свои серверы» или конкретную подписку) и имя из подсказок, затем «Сохранить и применить».
Имя можно ввести вручную, если подписка ещё не загружена. Это постоянная настройка сервиса,
а не закрепление через API: она переносится экспортом и действует также в конфиге телефона.
В обычной форме «Сервисы» те же поля называются «Фиксированный сервер» и «Источник сервера».
В env это `SVC_<ИМЯ>_SERVER="точное имя"` и `SVC_<ИМЯ>_PROVIDER="id-my"` (пустой PROVIDER —
свой сервер из настроек). VIA при фиксированном сервере не выбирает выход. Kit создаёт
внутренний односерверный пул `SVC-FIXED-<ИМЯ>`; сервис имеет только этот путь. Внутренние
пулы не нужно создавать вручную. Для подписки имя сопоставляется точно, включая эмодзи,
скобки и регистр, только в указанном провайдере. Если ноду переименовали, удалили или
подписка выключена, сервис закрывается через REJECT; на другую ноду или DIRECT он не
переключается. Недоступность самой ноды тоже не меняет выходной сервер.
«Вход» (CHAIN) по-прежнему задаёт путь подключения к выбранному серверу. С «как обычно»
свои серверы и [MY]-ноды на whitelist и телефоне доступны через MY-EXIT, а на main —
напрямую либо через UPLINK. Для обычных нод подписки сохраняется путь их провайдера.
Перетаскивание сервиса на группу в графе возвращает режим группы после сохранения.
Пулы — свои наборы серверов: LuCI → вкладка «Пулы и сервисы» или «+ пул» на графе. У пула своя
группа (имя заглавными: `de` → `DE`), и сервис можно пустить через неё — тогда выход сервиса
задан настройками, а не выбором в дашборде, и одинаков на роутере и телефоне (закрепление в
дашборде живёт только в `cache.db` своего устройства). В пул входят:
- свои серверы — галками (по имени);
- ноды подписок — отметить подписку (`sam_hub` — её ноды без `[MY]`, `sam_hub-my` — только
`[MY]`) и задать фильтр по имени ноды: `filter` / `exclude-filter` mihomo, регулярное
выражение (`\[WL\]` — метка в своей подписке, `(?i)🇩🇪|\bde\b` — страна в чужой; несколько
через `` ` ``; пусто — все ноды). К своим серверам фильтр не применяется.
Как выбирать: первый живой (`fallback`, по умолчанию), самый быстрый (`url-test`) или вручную
(`select`). Встроенные группы (`MY`, `FOREIGN`, `MY-EXIT`, …) от пулов не меняются: пока пулов нет,
профили собираются как раньше. Если из пула всё пропало (сервер переименован, подписка
выключена), он собирается с `REJECT` — его сервисы закрыты, а не идут мимо, — и сборка пишет
предупреждение. Пул, через который идёт сервис, не удалить, пока сервис не переключён.
Цепочки — когда до выхода надо добираться через что-то ещё:
- **вход сервиса** («Вход» у сервиса, `SVC_<ИМЯ>_CHAIN`): выход — MY или пул, вход — DIRECT,
FOREIGN, RU, MY, MY-EXIT или другой пул. Например, OpenAI выходит с IP своего сервера из пула
`DE`, а к самому серверу подключается через пул `WL`: клиент → `OPENAI` → `DE ⟶ WL` →
`de-1 ⟶ WL` → `WL` → наружу. Без входа — как обычно: на whitelist и телефоне свои серверы
и так идут через `MY-EXIT`;
- **пул в UPLINK** (галка «В UPLINK» у пула, `POOL_<ИМЯ>_UPLINK=1`): в группе `UPLINK` появляется
пункт `<ПУЛ> ⟶ DIRECT`; выбрать его (граф, дашборд) — и ноды подписок, BOOT и свои серверы
сначала идут через пул, а дальше как обычно (выход из блокировок). Серверы самого пула туда
подключаются напрямую, иначе была бы петля. По умолчанию в `UPLINK` выбран `DIRECT`; выбор,
как у любой группы, хранится в `cache.db` роутера.
mihomo строит цепочку только через `dialer-proxy` самой прокси, поэтому kit делает копии:
свои серверы — `<сервер> ⟶ <вход>`, ноды подписок — file-провайдер `<подписка>@<вход>` на тот
же скачанный файл (второго скачивания нет; на телефоне — да, как у `<имя>-my`), группа
`<ПУЛ> ⟶ <вход>`. На графе это видно отдельной веткой.
В `common.env`:
```sh
SERVICES="claude"
SVC_CLAUDE_GEOSITE="anthropic" # через пробел, если списков несколько
SVC_CLAUDE_DOMAINS="" # ещё домены (с поддоменами)
SVC_CLAUDE_IPS="" # ещё IP / подсети
SVC_CLAUDE_HOSTLIST="" # файлы со списками доменов (хостлисты zapret), через пробел
SVC_CLAUDE_VIA=MY # MY | FOREIGN | RU | DIRECT | MAIN | пул (DE)
SVC_CLAUDE_CHAIN="" # вход для MY / пула: DIRECT | FOREIGN | RU | MY | MY-EXIT | пул
POOLS="de"
POOL_DE_TYPE=fallback # fallback | url-test | select
POOL_DE_SERVERS="de-1; nl-2" # свои серверы по имени, через ;
POOL_DE_SUBS="sam_hub sam_hub-my" # подписки (<id> без [MY], <id>-my — только [MY])
POOL_DE_FILTER='(?i)🇩🇪|\bde\b' # по имени ноды подписки
POOL_DE_EXCLUDE='(?i)torrent'
POOL_DE_UPLINK=1 # предлагать в UPLINK
```
Сервисы попадают и в конфиг телефона. Правила по доменам не работают для трафика, который
спрашивает DNS в обход роутера («Безопасный DNS» в браузере) — см. ниже про ECH и DoH.
Свои серверы — LuCI → вкладка «Свои серверы». Каждый сервер — карточка: имя (так он
виден в дашборде), тип и адрес, «Настройки (YAML)» — весь сервер в формате mihomo, правится виден в дашборде), тип и адрес, «Настройки (YAML)» — весь сервер в формате mihomo, правится
на месте. «Добавить из ссылки / YAML» принимает сразу несколько: ссылки `vless://`, `vmess://`, на месте. «Добавить из ссылки / YAML» принимает сразу несколько: ссылки `vless://`, `vmess://`,
`trojan://`, `ss://`, `hysteria2://`, `tuic://`, `anytls://` (и `socks5://`, `http(s)://`, `trojan://`, `ss://`, `hysteria2://`, `tuic://`, `anytls://` (и `socks5://`, `http(s)://`,
@ -420,35 +221,6 @@ mihomo разбирает подписку (`luci/servers.js` — перенос
сверяет с ним): reality, xhttp, ws, grpc и прочее — как в приложении. «Скопировать» отдаёт сверяет с ним): reality, xhttp, ws, grpc и прочее — как в приложении. «Скопировать» отдаёт
сервер как YAML для другого роутера. сервер как YAML для другого роутера.
«Вход» в карточке — через что подключаться к самому серверу. «Как обычно» — как остальные
свои серверы: на `main` напрямую, на `whitelist` и телефоне через `MY-EXIT`, с CSQTT через
`UPLINK`. «Через FOREIGN», «через RU», «напрямую» или «через пул» действует только для этого
сервера и во всех профилях и в конфиге телефона: например, сервер, до которого напрямую не
достучаться, идёт через ноды FOREIGN, а остальные свои серверы — как раньше. Хранится как
`dialer-proxy` в строке сервера (`/etc/nikki/my-servers`); `dialer-proxy`, вписанный в
«Настройки (YAML)», становится тем же «Входом». Пул, в который сервер входит сам, как вход
нельзя — это петля.
Тот же «Вход» есть у серверов, которые лежат в своей подписке с `[MY]` в имени: блок «Из
подписок ([MY])» на той же вкладке. Их список страница берёт из работающего mihomo (nikki не
запущен — видны только ноды, у которых вход уже задан). Нода с входом уходит из провайдера
`<подписка>-my` в `<подписка>-my-via-<вход>`: тот же файл подписки (на телефоне — ещё одна
загрузка), только эти ноды, `dialer-proxy` = вход. Он стоит везде, где `<подписка>-my`: в MY,
пулах, сервисах. В `common.env` это `MY_NODE_1='FOREIGN|<подписка>-my|<точное имя>'`,
`MY_NODE_2=…`. Ноду ищут по точному имени: переименовали в подписке — вход перестаёт
действовать, нода снова идёт как остальные `[MY]`.
AmneziaWG: туда же вставляется ключ AmneziaVPN `vpn://…` («Поделиться» в приложении; файл
`.vpn` тоже можно выбрать) или `.conf` AmneziaWG / обычного WireGuard (текст `[Interface]` …
`[Peer]` … или файл — тогда сервер называется по имени файла). Получается сервер
`type: wireguard` с `amnezia-wg-option` (AmneziaWG 1.0 / 1.5 / 2.0 / 3 — параметры как в
конфиге; без Jc/H1/… — обычный WireGuard) в упрощённом виде mihomo, с одним `[Peer]`;
`AllowedIPs` и `DNS` не переносятся — что куда идёт, решают правила kit. Из ключа берутся
только контейнеры AmneziaWG / WireGuard (Xray — его `vless://`-ссылкой), ключи Amnezia
Free / Premium не подходят: в них нет сервера. WireGuard — это UDP: на `whitelist` и с
телефона он идёт через `MY-EXIT`, поэтому нода там должна пропускать UDP (hysteria2, tuic,
ss, vless/trojan с UDP); на телефоне нужно ядро FlClash с поддержкой AmneziaWG.
Серверы хранятся в `/etc/nikki/my-servers` (права 600, по одному JSON-объекту прокси на Серверы хранятся в `/etc/nikki/my-servers` (права 600, по одному JSON-объекту прокси на
строку) и переносятся экспортом настроек. Сборка вписывает их в `proxies:` профилей роутера строку) и переносятся экспортом настроек. Сборка вписывает их в `proxies:` профилей роутера
и в конфиг телефона и собирает в группу `MY` (url-test: самый быстрый живой; в дашборде и в конфиг телефона и собирает в группу `MY` (url-test: самый быстрый живой; в дашборде
@ -476,7 +248,7 @@ ss, vless/trojan с UDP); на телефоне нужно ядро FlClash с
умолчанию `FOREIGN`. умолчанию `FOREIGN`.
CSQTT ([star-panel-csqtt](https://github.com/starkugz/csqtt-openwrt)) — резервный выход из белых CSQTT ([star-panel-csqtt](https://github.com/starkugz/csqtt-openwrt)) — резервный выход из белых
списков: галка «Включить CSQTT» на вкладке «CSQTT» в LuCI (`CSQTT=1` в `common.env`). Пакет ставится и списков: галка «CSQTT» в LuCI → Настройка (`CSQTT=1` в `common.env`). Пакет ставится и
настраивается отдельно, в своей панели (Службы → star-panel-csqtt); он поднимает интерфейс настраивается отдельно, в своей панели (Службы → star-panel-csqtt); он поднимает интерфейс
`csqtt0` и маршруты не меняет. Kit добавляет прокси `CSQTT` (`type: direct`, `csqtt0` и маршруты не меняет. Kit добавляет прокси `CSQTT` (`type: direct`,
`interface-name: csqtt0`) и группу `UPLINK` — через что подключаться к нодам подписок, BOOT `interface-name: csqtt0`) и группу `UPLINK` — через что подключаться к нодам подписок, BOOT
@ -509,19 +281,19 @@ VK-токен). Кнопка Stop в панели csqtt останавливае
и трафик идёт по правилу `100.64.0.0/10` в `TAILSCALE`. В тейлнете должен быть включён и трафик идёт по правилу `100.64.0.0/10` в `TAILSCALE`. В тейлнете должен быть включён
MagicDNS (админка Tailscale → DNS). MagicDNS (админка Tailscale → DNS).
Проверка туннелей: у групп `OPENVPN` и `TAILSCALE` свой адрес проверки — LuCI, вкладки Проверка туннелей: у групп `BMSTU` и `TAILSCALE` свой адрес проверки — LuCI → Настройка
«OpenVPN» и «Tailscale» («Адрес для проверки») или `OVPN_CHECK_URL` (страница за VPN; («Адрес для проверки» в блоках OpenVPN и Tailscale) или `OVPN_CHECK_URL` (по умолчанию
пусто — `generate_204` Google) / `TS_CHECK_URL` (HTTP-сервис на ноде тейлнета, по умолчанию `https://eu.bmstu.ru`) / `TS_CHECK_URL` (HTTP-сервис на ноде тейлнета, по умолчанию
`http://100.69.216.50:8080`) в `common.env`. `http://100.69.216.50:8080`) в `common.env`.
Кнопка проверки задержки этих групп в дашборде открывает его через туннель (если дашборд Кнопка проверки задержки этих групп в дашборде открывает его через туннель (если дашборд
берёт адрес из группы); сами по таймеру они не проверяются. На странице mihomo-kit их берёт адрес из группы); сами по таймеру они не проверяются. На странице mihomo-kit их
открывает кнопка «Проверить» (у OpenVPN — «Проверка сайта», `ovpn.sh probe`). открывает кнопка «Проверить» (у OpenVPN — «Проверка сайта», `bmstu-otp.sh probe`).
OpenVPN сам ничего через туннель не проверяет. Connect таких запросов не делает, а OpenVPN сам ничего через туннель не проверяет. Connect таких запросов не делает, а
URL-тест виден в логах сайта, который он открывает: `HEAD /` от Go-клиента, по таймеру. URL-тест виден в логах сайта, который он открывает: `HEAD /` от Go-клиента, по таймеру.
Поэтому с ядром kit состояние туннеля (подключён с такого-то времени, подключается, сервер Поэтому с ядром kit состояние туннеля (подключён с такого-то времени, подключается, сервер
не принял сессию) берётся из API mihomo — ядро отдаёт его в поле `openvpn` прокси, — и не принял сессию) берётся из API mihomo — ядро отдаёт его в поле `openvpn` прокси, — и
cron, LuCI («Состояние») и `ovpn.sh status` не шлют ни одного запроса. Новый код cron, LuCI («Состояние») и `bmstu-otp.sh status` не шлют ни одного запроса. Новый OTP
cron даёт, только если сервер не принял токен сессии или туннель не поднимается 5 минут cron даёт, только если сервер не принял токен сессии или туннель не поднимается 5 минут
(`DOWN_GRACE`). Ядра `stock`/`official` состояние не отдают: с ними cron открывает адрес (`DOWN_GRACE`). Ядра `stock`/`official` состояние не отдают: с ними cron открывает адрес
проверки не чаще раза в 10 минут (`PROBE_EVERY`), в случайную секунду. проверки не чаще раза в 10 минут (`PROBE_EVERY`), в случайную секунду.
@ -534,13 +306,13 @@ cron даёт, только если сервер не принял токен
| Фикс | Зачем | | Фикс | Зачем |
|---|---| |---|---|
| ядро kit `v1.19.34-ts8` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие; Tailscale через `dialer-proxy` и маскировка OpenVPN — только в ядре kit | | ядро kit `v1.19.33-ts6` вместо ядра из пакета | в v1.19.29 OpenVPN не проходит рукопожатие; Tailscale через `dialer-proxy` и маскировка OpenVPN — только в ядре kit |
| `TS_FORCE_NOISE_443=true` в `/etc/init.d/nikki` | провайдер ломает control-соединение Tailscale на порту 80, вход зависает | | `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 и внутренние сети VPN (172.16/12) мимо mihomo | | убрать `100.64.0.0/10`, `172.16.0.0/12` из `nikki.proxy.reserved_ip` | иначе nikki пускает Tailscale и внутренние сети BMSTU мимо mihomo |
| `ts.net` в `rebind_domain` dnsmasq | иначе защита от DNS rebinding отбрасывает адреса 100.x тейлнета | | `ts.net` в `rebind_domain` dnsmasq | иначе защита от DNS rebinding отбрасывает адреса 100.x тейлнета |
| metric: `wan`/`wan6` — 10, остальные выходы (модемы, wifi-клиент) — 50, 60, … (если не заданы руками) | при живом проводе интернет идёт по проводу, модемы — запасные | | metric: `wan`/`wan6` — 10, остальные выходы (модемы, wifi-клиент) — 50, 60, … (если не заданы руками) | при живом проводе интернет идёт по проводу, модемы — запасные |
| cron `ovpn.sh check` раз в минуту | держит туннель по расписанию/таймеру; со свежим кодом поднимает, если сервер не принял токен сессии или туннель долго лежит (состояние из ядра, без запросов через туннель) | | cron `bmstu-otp.sh check` раз в минуту | держит туннель по расписанию/таймеру; со свежим OTP поднимает, если сервер не принял токен сессии или туннель долго лежит (состояние из ядра, без запросов через туннель) |
| `ovpn.sh write` в `/etc/init.d/nikki` | провайдер OpenVPN (со свежим кодом, если нужен) перед стартом mihomo: ядро kit подключается сразу | | `bmstu-otp.sh write` в `/etc/init.d/nikki` | провайдер OpenVPN со свежим OTP перед стартом mihomo: ядро kit подключается сразу |
| `GOMEMLIMIT` в `/etc/init.d/nikki` (только с `LITE=1`) | лимит памяти ядра для слабых роутеров, см. «Облегчённый режим» | | `GOMEMLIMIT` в `/etc/init.d/nikki` (только с `LITE=1`) | лимит памяти ядра для слабых роутеров, см. «Облегчённый режим» |
| переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` | | переустановка `libcurl4 curl`, если curl сломан | `Error relocating ... symbol not found` |
@ -549,24 +321,16 @@ cron даёт, только если сервер не принял токен
при старте пишет `Error: IPv6 is disabled on nexthop device` (`ip -6 route ... dev lo` для при старте пишет `Error: IPv6 is disabled on nexthop device` (`ip -6 route ... dev lo` для
tproxy). Включить обратно — `uci set nikki.proxy.ipv6_proxy=1`, когда IPv6 появится. tproxy). Включить обратно — `uci set nikki.proxy.ipv6_proxy=1`, когда IPv6 появится.
## Телефон и компьютер ## Телефон (FlClash)
Тот же обход можно взять в приложение на ядре mihomo (Clash Meta): С роутера: LuCI → Настройка → галка «Конфиг для телефона» → «Сохранить и применить». На
- Android — FlClash или Clash Meta for Android; странице появится блок «Телефон (FlClash)» с QR-кодом и ссылкой
- iPhone, iPad — Clash Mi; `http://<роутер>/mihomo-kit/<токен>.yaml`: FlClash → Профили → + → по ссылке (или QR).
- Windows, macOS, Linux — FlClash или Clash Verge Rev.
С роутера: LuCI → вкладка «Телефон» → галка «Конфиг для телефона» (на новом роутере уже стоит) →
«Сохранить и применить». На той же вкладке появится блок «Подключить приложение» с QR-кодом и
ссылкой `http://<роутер>/mihomo-kit/<токен>.yaml`. В приложении: профили (подписки) →
добавить → по ссылке или QR-коду; QR сканировать сканером в самом приложении (камера телефона
просто покажет ссылку). «Скопировать ссылку» — вставить вручную; «Открыть в приложении»
(`clash://install-config?url=…`) — если страница открыта на самом телефоне.
Это `common.env`, собранный с `TARGET=mobile`: те же подписки, BOOT/`BOOT-AUTO`, HWID и Это `common.env`, собранный с `TARGET=mobile`: те же подписки, BOOT/`BOOT-AUTO`, HWID и
RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; свои серверы — в `MY`, к ним всегда RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; свои серверы — в `MY`, к ним всегда
через `MY-EXIT` (телефон часто на белых списках). Пересобирается вместе с профилями. через `MY-EXIT` (телефон часто на белых списках). Пересобирается вместе с профилями.
Ссылка открывается только в сети роутера (вне дома приложение просто не обновит профиль) и Ссылка открывается только в сети роутера (вне дома FlClash просто не обновит профиль) и
содержит ссылки подписок — токен и есть секрет; «Новая ссылка» (`mihomo-kit.sh mobile new`) содержит ссылки подписок — токен и есть секрет; «Новая ссылка» (`mihomo-kit.sh mobile new`)
отзывает старую. отзывает старую.
@ -576,8 +340,7 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво
|---|---|---|---|---| |---|---|---|---|---|
| подписки через `BOOT-AUTO` | ✓ | ✓ | ✓ | ✓ | | подписки через `BOOT-AUTO` | ✓ | ✓ | ✓ | ✓ |
| `ru-inside` | напрямую | напрямую | через RU | напрямую | | `ru-inside` | напрямую | напрямую | через RU | напрямую |
| `ru-services` (русские сервисы вне ru-inside и вне .ru/.su/.рф) | напрямую | через RU | через RU | через RU | | остальные `.ru` / `.рф`, доп. IP (`RU_IPS`) | напрямую | через RU | через RU | через RU |
| остальные `.ru` / `.su` / `.рф`, доп. IP (`RU_IPS`) | напрямую | через RU | через RU | через RU |
| доп. IP / домены через FOREIGN, MY (`FOREIGN_*`, `MY_*`) | `FOREIGN` / `MY` | `FOREIGN` / `MY` | `FOREIGN` / `MY` | `FOREIGN` / `MY` | | доп. IP / домены через FOREIGN, MY (`FOREIGN_*`, `MY_*`) | `FOREIGN` / `MY` | `FOREIGN` / `MY` | `FOREIGN` / `MY` | `FOREIGN` / `MY` |
| доп. домены через RU (`RU_DOMAINS`) | напрямую | через RU | через RU | через RU | | доп. домены через RU (`RU_DOMAINS`) | напрямую | через RU | через RU | через RU |
| локальные адреса (`LOCAL_HOSTS`) | по LAN | по LAN | по LAN | — | | локальные адреса (`LOCAL_HOSTS`) | по LAN | по LAN | по LAN | — |
@ -587,10 +350,9 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво
| Tailscale | напрямую | через `MY` (свои серверы и `[MY]`-ноды подписки), без них напрямую* | напрямую | — | | Tailscale | напрямую | через `MY` (свои серверы и `[MY]`-ноды подписки), без них напрямую* | напрямую | — |
| свои серверы | напрямую | через `MY-EXIT` | напрямую | через `MY-EXIT` | | свои серверы | напрямую | через `MY-EXIT` | напрямую | через `MY-EXIT` |
| пуши (`PUSH`, отключаемо) | `DIRECT` | `MY` | `DIRECT` | — | | пуши (`PUSH`, отключаемо) | `DIRECT` | `MY` | `DIRECT` | — |
| сервисы (`SERVICES`) | своя группа | своя группа | своя группа | своя группа |
`LOCAL_HOSTS` — свои серверы в локальной сети этого роутера: «Локальные адреса» в LuCI → `LOCAL_HOSTS` — свои серверы в локальной сети этого роутера: «Локальные адреса» в LuCI →
вкладка «Правила» (или `LOCAL_HOSTS="sam-hub.net=192.168.64.20"` в `common.env`, Настройка → «Свои правила» (или `LOCAL_HOSTS="sam-hub.net=192.168.64.20"` в `common.env`,
пар может быть несколько, домен — вместе с поддоменами). Без этого mihomo разрешает свой пар может быть несколько, домен — вместе с поддоменами). Без этого mihomo разрешает свой
домен во внешний (белый) IP роутера и стучится сам в себя: вместо сервера отвечает LuCI с домен во внешний (белый) IP роутера и стучится сам в себя: вместо сервера отвечает LuCI с
сертификатом `OpenWrt`. С ним домен попадает в `hosts` mihomo и в исключения fake-ip: сертификатом `OpenWrt`. С ним домен попадает в `hosts` mihomo и в исключения fake-ip:
@ -601,22 +363,6 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво
`wget`/`opkg` самого роутера (обновления kit, ядро) нужна ещё запись в dnsmasq: `wget`/`opkg` самого роутера (обновления kit, ядро) нужна ещё запись в dnsmasq:
`uci add_list dhcp.@dnsmasq[0].address='/sam-hub.net/192.168.64.20'`. `uci add_list dhcp.@dnsmasq[0].address='/sam-hub.net/192.168.64.20'`.
Клиенты мимо mihomo — LuCI → вкладка «Правила» → «Клиенты мимо mihomo» (`BYPASS_CLIENTS` в
`common.env`): IP-адреса, подсети и MAC-адреса через пробел. Их трафик и DNS nikki вообще не
отдаёт в mihomo, они идут напрямую. Нужно, например, когда за этим роутером второй роутер со
своим kit: иначе его трафик дважды заворачивается в прокси (сначала на втором, потом на этом).
MAC надёжнее IP: адрес по DHCP может смениться (или закрепить его в Сеть → DHCP и DNS). Это
секция `lan_access_control` самого nikki (`proxy 0`, `dns 0`), которую `use` и «Сохранить и
применить» ставят первой — первое совпадение побеждает. Только для этого роутера: при импорте
с `--keep-local` остаётся своя.
Правила выбираются по имени сайта: его mihomo знает из своего DNS или достаёт сниффером из
рукопожатия TLS/QUIC. Сайты за Cloudflare с ECH (браузер получил ключи через свой DoH)
показывают в рукопожатии не своё имя, а `cloudflare-ech.com`. Такое имя сниффер пропускает
(`skip-domain`), иначе `.ru`-сайт за Cloudflare уходил бы в `MAIN`. Если устройство спрашивает DNS
в обход роутера («Безопасный DNS» в браузере, «Частный DNS» на Android), имени у mihomo нет
вовсе, и правила по доменам для такого трафика не работают.
На `foreign` российские домены не попадают в исключения fake-ip: их разрешает RU-нода, а На `foreign` российские домены не попадают в исключения fake-ip: их разрешает RU-нода, а
для прямого трафика DNS — Cloudflare/Google вместо Яндекса. для прямого трафика DNS — Cloudflare/Google вместо Яндекса.
@ -624,24 +370,16 @@ MAC надёжнее IP: адрес по DHCP может смениться (и
он открывает UDP-сокет без адреса назначения, и любой прокси mihomo падает на его он открывает UDP-сокет без адреса назначения, и любой прокси mihomo падает на его
резолве (`magicsock: Rebind IPv4 failed: failed to bind any ports`, резолве (`magicsock: Rebind IPv4 failed: failed to bind any ports`,
[MetaCubeX/mihomo#3142](https://github.com/MetaCubeX/mihomo/issues/3142)). Поэтому kit [MetaCubeX/mihomo#3142](https://github.com/MetaCubeX/mihomo/issues/3142)). Поэтому kit
ставит своё ядро `v1.19.34-ts8` — официальный v1.19.34 с правкой ставит своё ядро `v1.19.33-ts6` — официальный v1.19.33 с правкой
`tools/core/tailscale-packet-listener.patch`: UDP-сокет открывается на роутере, а `tools/core/tailscale-packet-listener.patch`: UDP-сокет открывается на роутере, а
control-сервер и DERP идут по TCP через `dialer-proxy`. На белых списках прямой UDP не control-сервер и DERP идут по TCP через `dialer-proxy`. На белых списках прямой UDP не
проходит, и Tailscale работает через DERP — медленнее прямого соединения, но работает. проходит, и Tailscale работает через DERP — медленнее прямого соединения, но работает.
Вторая правка того же ядра — `tools/core/openvpn-connect-mimic.patch`, маскировка OpenVPN Вторая правка того же ядра — `tools/core/openvpn-connect-mimic.patch`, маскировка OpenVPN
под OpenVPN Connect (см. «OpenVPN под видом OpenVPN Connect»). под OpenVPN Connect (см. «OpenVPN под видом OpenVPN Connect»). Как собрать — в «Разработке».
Третья — `tools/core/reality-client-version.patch`: в рукопожатии REALITY клиент сообщает
серверу версию Xray, и mihomo всегда шлёт 1.8.2. Серверы с `minClientVer` выше (его ставят
некоторые панели) такого клиента отвергают — в логе ядра `REALITY Authentication: false`, —
а клиенты на Xray (Happ, v2rayN) с той же ссылкой проходят. Ядро kit сообщает свежую версию
Xray (26.10.21); для отдельного сервера можно задать свою в YAML сервера:
`reality-opts: {client-version: "25.3.6"}` (если сервер ограничивает и сверху, `maxClientVer`).
Как собрать — в «Разработке».
Если ядро не скачалось, `fix` оставляет текущее и запускает nikki. Если ядро не скачалось, `fix` оставляет текущее и запускает nikki.
Какое ядро на конкретном роутере — селект на вкладке «Система» (или Какое ядро на конкретном роутере — селект в «Обслуживании» (или
`mihomo-kit.sh core stock|official|kit`), выбор хранится в `/etc/nikki/kit.env` как `CORE=`: `mihomo-kit.sh core stock|official|kit`), выбор хранится в `/etc/nikki/kit.env` как `CORE=`:
- `stock` — ядро из пакета nikki/прошивки (`/usr/libexec/mihomo`), ничего не качается, место - `stock` — ядро из пакета nikki/прошивки (`/usr/libexec/mihomo`), ничего не качается, место
во флеше освобождается; во флеше освобождается;
@ -673,7 +411,7 @@ opkg сравнивает полный размер новых пакетов с
новых, с запасом 2 МБ (`PKG_RESERVE_KB`). Не влезает — ничего не ставит. Влезает — новых, с запасом 2 МБ (`PKG_RESERVE_KB`). Не влезает — ничего не ставит. Влезает —
останавливает nikki (запущенное ядро держит свой старый файл на флеше), ставит с останавливает nikki (запущенное ядро держит свой старый файл на флеше), ставит с
`--force-space` и делает `fix`: обновление nikki перезаписывает `/etc/init.d/nikki`, и `--force-space` и делает `fix`: обновление nikki перезаписывает `/etc/init.d/nikki`, и
правки kit (`TS_FORCE_NOISE_443`, провайдер OpenVPN, `GOMEMLIMIT`) нужно вернуть. правки kit (`TS_FORCE_NOISE_443`, OTP, `GOMEMLIMIT`) нужно вернуть.
### Облегчённый режим (`LITE=1`) ### Облегчённый режим (`LITE=1`)
@ -699,10 +437,9 @@ opkg сравнивает полный размер новых пакетов с
## Если что-то не работает ## Если что-то не работает
- **OpenVPN** `tunnel did not come up`: `ovpn.sh debug` покажет настоящую ошибку. - **OpenVPN** `tunnel did not come up`: `bmstu-otp.sh debug` покажет настоящую ошибку.
`read hard reset response` — до сервера не доходят пакеты (zeroblock, правило для IP `read hard reset response` — до сервера не доходят пакеты (zeroblock, правило для IP
сервера); `AUTH_FAILED` — неверный логин или пароль, а с TOTP ещё и формат кода: «Как сервера); `AUTH_FAILED` — формат пароля (`PASS_FORMAT` в `bmstu.env`, сейчас `scrv1`, как у OpenVPN Connect).
отправлять код» в настройках (`PASS_FORMAT` в `openvpn.env`) или неверное время на роутере.
- **Tailscale** без ссылки: `mihomo-kit.sh ts-login`. Ссылка пишется в лог один раз и - **Tailscale** без ссылки: `mihomo-kit.sh ts-login`. Ссылка пишется в лог один раз и
только на уровне `info` (у nikki по умолчанию `warning`), а неудачный первый запуск только на уровне `info` (у nikki по умолчанию `warning`), а неудачный первый запуск
оставляет в `/etc/nikki/run/tailscale` состояние, с которым нода молчит — команда оставляет в `/etc/nikki/run/tailscale` состояние, с которым нода молчит — команда
@ -718,12 +455,11 @@ templates/ фрагменты конфига
presets/ профили, которые setup кладёт в profiles.d presets/ профили, которые setup кладёт в profiles.d
router/ router/
mihomo-kit.sh сборка, setup-мастер, use/update/fix mihomo-kit.sh сборка, setup-мастер, use/update/fix
ovpn.sh OpenVPN: провайдер из .ovpn (TOTP в пароле), cron-сторож, on/off, расписание bmstu-otp.sh OpenVPN BMSTU: TOTP в пароле, cron-сторож, on/off
luci/ страница LuCI «Службы → mihomo-kit»: rpcd.sh (бэкенд), view, ACL, меню, luci/ страница LuCI «Службы → mihomo-kit»: rpcd.sh (бэкенд), view, ACL, меню,
servers.js (ссылки и YAML своих серверов), qrcode.js servers.js (ссылки и YAML своих серверов), qrcode.js
tools/ push.sh, test.sh, test-servers.js, servers-ref.sh + servers-ref/ (эталоны tools/ push.sh, test.sh, test-servers.js, servers-ref.sh + servers-ref/ (эталоны
для servers.js из Go-кода mihomo), core/ (ядро kit), для servers.js из Go-кода mihomo), core/ (ядро kit)
nikki-mirror.sh (зеркало пакетов nikki в релизах)
tests/fixtures/ профили для test.sh (фиктивные секреты), own.servers tests/fixtures/ профили для test.sh (фиктивные секреты), own.servers
tests/expected/ эталонный YAML каждого профиля tests/expected/ эталонный YAML каждого профиля
tests/links/, yaml/ ссылки и YAML с выводом Go-кода mihomo для luci/servers.js tests/links/, yaml/ ссылки и YAML с выводом Go-кода mihomo для luci/servers.js
@ -746,41 +482,23 @@ tests/links/, yaml/ ссылки и YAML с выводом Go-кода mihomo д
### Ядро kit ### Ядро kit
Официальный mihomo плюс правки из `tools/core/*.patch` (Tailscale через `dialer-proxy`, Официальный mihomo плюс правки из `tools/core/*.patch` (Tailscale через `dialer-proxy`,
маскировка OpenVPN, версия клиента REALITY). Нужны git и Go. маскировка OpenVPN). Нужны git и Go.
1. `tools/core/build.sh v1.19.34 ts8` — клонирует mihomo `v1.19.34`, накладывает патчи и 1. `tools/core/build.sh v1.19.33 ts6` — клонирует mihomo `v1.19.33`, накладывает патчи и
собирает `tools/core/dist/mihomo-linux-<arch>-v1.19.34-ts8.gz` для arm64, amd64, armv7, собирает `tools/core/dist/mihomo-linux-<arch>-v1.19.33-ts6.gz` для arm64, amd64, armv7,
mips-softfloat, mipsle-softfloat. mips-softfloat, mipsle-softfloat.
2. В репозитории kit создать релиз с тегом `core-v1.19.34-ts8` и приложить все `.gz`, не 2. В репозитории kit создать релиз с тегом `core-v1.19.33-ts6` и приложить все `.gz`, не
переименовывая: роутер качает `$MIHOMO_BASE/mihomo-linux-<arch>-<версия>.gz`. переименовывая: роутер качает `$MIHOMO_BASE/mihomo-linux-<arch>-<версия>.gz`.
3. `CORE_KIT` в `router/mihomo-kit.sh` — та же версия. Пушить кит только после релиза: 3. `CORE_KIT` в `router/mihomo-kit.sh` — та же версия. Пушить кит только после релиза:
роутеры берут кит из `main` и иначе не найдут ядро. роутеры берут кит из `main` и иначе не найдут ядро.
4. На роутере: `mihomo-kit.sh update` (новый кит; ядро меняется, если версия другая), 4. На роутере: `mihomo-kit.sh update` (новый кит; ядро меняется, если версия другая),
`mihomo-kit.sh fix` (ядро и init-скрипт nikki: провайдер OpenVPN перед стартом mihomo), затем `mihomo-kit.sh fix` (ядро и init-скрипт nikki: свежий OTP перед стартом mihomo), затем
`ovpn.sh refresh` (провайдер OpenVPN с новыми полями). Проверить: `bmstu-otp.sh refresh` (провайдер OpenVPN с новыми полями). Проверить:
`mihomo-kit.sh core-info`, `ovpn.sh status`. `mihomo-kit.sh core-info`, `bmstu-otp.sh status`.
Новая версия mihomo или новая правка — следующий суффикс (`ts9`) в шагах 1–3. Патчи Новая версия mihomo или новая правка — следующий суффикс (`ts6`) в шагах 1–3. Патчи
применяются по алфавиту; если не накладываются, поправить их на новом теге. применяются по алфавиту; если не накладываются, поправить их на новом теге.
### Зеркало nikki
Роутер ставит nikki из релиза `nikki-<NIKKI_VERSION>` репозитория kit (GitHub из России
часто недоступен). Обновить зеркало на новый релиз nikki (нужны curl, jq; токен Gitea с
правом `write:repository`):
```sh
GITEA_TOKEN=... tools/nikki-mirror.sh latest # все архитектуры, OpenWrt 24.10
GITEA_TOKEN=... tools/nikki-mirror.sh v1.26.2 aarch64_cortex-a53 mipsel_24kc # только эти
```
Скрипт создаёт релиз `nikki-<версия>`, качает `nikki_<arch>-openwrt-24.10.tar.gz` с GitHub,
убирает из них `mihomo-alpha` и переводы zh (меньше памяти на роутере; `Packages` и подпись
не меняются) и выкладывает. Уже выложенные пропускает — можно дозапустить. Потом
`NIKKI_VERSION` в `router/mihomo-kit.sh` — та же версия, и пушить кит. Ключ nikki
(`router/nikki-key-build.pub`) менять, только если nikki сменит ключ подписи
(`https://nikkinikki.pages.dev/key-build.pub`).
После правки шаблонов, скрипта или `luci/servers.js`: После правки шаблонов, скрипта или `luci/servers.js`:
```sh ```sh

60
TODO.md
View File

@ -1,60 +0,0 @@
# Технический долг и планы
Что стоит сделать в kit дальше. Сверху — то, что страхует от поломок, ниже — новые возможности.
## Надёжность кода
- **`local` в функциях `router/mihomo-kit.sh`.** Переменные в sh глобальные, и функции затирают
их друг другу. Уже было: `pool_vars` перезаписывал `_n` у `own_entries_check`, и проверка
петли молча не срабатывала. ash в busybox понимает `local` — перевести на него хотя бы функции,
которые вызывают другие (`pool_vars`, `variant_members`, `sub_vars`, `*_vars`).
- **Тесты роутерной части.** `tools/test.sh` проверяет только рендер. Миграции
(`migrate_openvpn`, `migrate_profiles`), `bypass_uci`, `nikki_defaults`, `opkg_fit`, cron,
`ovpn.sh` (пароль с TOTP и без, шифры из `.ovpn`, `routes_set`) проверялись руками. Добавить
прогоны с поддельными `uci`, `opkg`, `curl`, `/etc/init.d/*` в `PATH`, которые пишут вызовы в
лог, и сравнивать лог с эталоном.
- **Проверка JS.** Страницы LuCI правились без запуска: `node --check luci/*.js` в
`tools/test.sh` (когда есть node) и тесты `tools/test-*.js` в CI.
- **CI на Gitea Actions.** `tools/test.sh` с node и `MIHOMO=…` (`mihomo -t` по всем профилям)
на каждый пуш: роутеры берут kit прямо из `main`.
- **Разбить `luci/mihomo-kit.js`.** `renderSettings` — одна функция на сотни строк. После вкладок
естественно резать её по вкладке на функцию (подписки, правила, свои серверы, OpenVPN, …).
## Известные слабые места
- **OpenVPN сразу после старта nikki.** Имя сервера резолвится через DNS mihomo (`respect-rules`,
через `MAIN`); пока он не готов, туннель не находит сервер и поднимается только через
`DOWN_GRACE` (5 минут). Узнавать IP сервера в `ovpn.sh` при записи провайдера напрямую
(77.88.8.8) и писать IP вместо имени.
- **`MAIN = DIRECT` переезжает между профилями** (`cache.db` по имени группы): выбрал дома —
на whitelist нет интернета. Хотя бы предупреждение на «Обзоре», а лучше сброс `MAIN` при
смене профиля или отдельный профиль `behind` (за другим роутером: только OpenVPN и Tailscale,
остальное `DIRECT`).
- **`OVPN-EXIT` только из RU-нод** — рассчитано на VPN-сервер в России. Дать выбор страны или
любой ноды.
- **OpenVPN:** профили только с сертификатом (без `auth-user-pass`) сейчас требуют логин;
внутренние домены за VPN не резолвятся через DNS самого VPN.
- **Ноды `[MY]` с входом ищутся по точному имени:** переименовали в подписке — вход молча
перестаёт действовать. Показывать в LuCI заданные входы, для которых ноды больше нет.
- **`opkg_fit`** не проверен на живом маленьком роутере: печатает ли `opkg --noaction` строки
`Installing …` (иначе откатывается к обычному `opkg install`).
## Порт на OpenWrt 25.12
opkg заменён на apk: `cmd_install`, `opkg_fit`, `pkg-install` (`.ipk` → `.apk`, нет
`--force-space`, свой подсчёт места), `lite_intercept`. Определять менеджер пакетов и держать
обе ветки. Генерация конфигов, LuCI, `use`, `fix`, ядро от этого не зависят.
## Новые возможности
- **Автоопределение белых списков:** роутер раз в N минут проверяет, открываются ли зарубежные
адреса напрямую, и сам переключает `main` ↔ `whitelist` (с гистерезисом, чтобы не прыгать).
- **Маршрут по устройству:** развитие `BYPASS_CLIENTS` — не только «мимо mihomo», но и «это
устройство всегда через FOREIGN / MY / пул» (`SRC-IP-CIDR` в начале правил; MAC → IP по
DHCP-арендам).
- **Выбор из DHCP-клиентов** в LuCI для `BYPASS_CLIENTS` и маршрутов по устройству, а не ввод MAC
руками.
- **Уведомления в Telegram:** OpenVPN не поднимается, обновление kit упало, подписка не
скачивается, ядро откатилось.
- **Откат обновления kit:** сохранять предыдущую версию перед `update`, кнопка «вернуть
предыдущую».

View File

@ -12,13 +12,7 @@ KIT_DIR=/etc/nikki/kit
here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo /nonexistent) here=$(cd "$(dirname "$0")" 2>/dev/null && pwd || echo /nonexistent)
mkdir -p "$KIT_DIR" mkdir -p "$KIT_DIR"
if [ -f "$here/router/mihomo-kit.sh" ]; then if [ -f "$here/router/mihomo-kit.sh" ]; then
# whole directories, as below: a template renamed in the kit must not stay behind [ "$here" = "$KIT_DIR" ] || cp -r "$here/templates" "$here/presets" "$here/router" "$here/luci" "$KIT_DIR/"
if [ "$here" != "$KIT_DIR" ]; then
for d in templates presets router luci; do
rm -rf "${KIT_DIR:?}/$d"
cp -r "$here/$d" "$KIT_DIR/"
done
fi
else else
tmp=/tmp/mihomo-kit.$$ tmp=/tmp/mihomo-kit.$$
mkdir -p "$tmp" mkdir -p "$tmp"
@ -38,16 +32,5 @@ else
echo "${sha:-?} $(date '+%Y-%m-%d %H:%M')" > "$KIT_DIR/VERSION" echo "${sha:-?} $(date '+%Y-%m-%d %H:%M')" > "$KIT_DIR/VERSION"
rm -rf "$tmp" rm -rf "$tmp"
fi fi
# stdin may be the piped script: the wizard (setup --cli) reads answers from /dev/tty. # stdin may be the piped script: the wizard (setup --cli) reads answers from /dev/tty
# The output is also kept in RAM: the flash may be full by the time something fails. exec sh "$KIT_DIR/router/mihomo-kit.sh" setup "$@"
log=/tmp/mihomo-kit-install.log
rc=/tmp/mihomo-kit-install.rc
{
code=0
sh "$KIT_DIR/router/mihomo-kit.sh" setup "$@" 2>&1 || code=$?
echo "$code" > "$rc"
} | tee "$log"
code=$(cat "$rc" 2>/dev/null || echo 1)
rm -f "$rc"
echo "install log: $log"
exit "$code"

View File

@ -3,12 +3,12 @@
"description": "mihomo-kit: profiles, OpenVPN, Tailscale, CSQTT", "description": "mihomo-kit: profiles, OpenVPN, Tailscale, CSQTT",
"read": { "read": {
"ubus": { "ubus": {
"mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "csqtt_status", "job", "update_check", "ts_check", "graph", "api" ] "mihomo-kit": [ "status", "ovpn_status", "ovpn_probe", "csqtt_status", "job", "update_check", "ts_check" ]
} }
}, },
"write": { "write": {
"ubus": { "ubus": {
"mihomo-kit": [ "run", "config_get", "config_set", "export", "import", "group", "services_set" ] "mihomo-kit": [ "run", "config_get", "config_set", "export", "import" ]
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -3,26 +3,11 @@
"title": "mihomo-kit", "title": "mihomo-kit",
"order": 61, "order": 61,
"action": { "action": {
"type": "firstchild" "type": "view",
"path": "mihomo-kit"
}, },
"depends": { "depends": {
"acl": [ "luci-app-mihomo-kit" ] "acl": [ "luci-app-mihomo-kit" ]
} }
},
"admin/services/mihomo-kit/main": {
"title": "Управление",
"order": 1,
"action": {
"type": "view",
"path": "mihomo-kit"
}
},
"admin/services/mihomo-kit/graph": {
"title": "Граф",
"order": 2,
"action": {
"type": "view",
"path": "mihomo-kit-graph"
}
} }
} }

View File

@ -1,157 +0,0 @@
'use strict';
'require view';
'require rpc';
'require dom';
// LuCI "Службы → mihomo-kit → Граф": a built profile as a graph (luci/graph.js), with the
// live state of the running mihomo through the rpcd plugin (method api: read-only paths)
// and the choice in its groups (method group); the services and pools of the settings are
// edited here too (method services_set: rebuild and restart as the job).
var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } });
var callGraph = rpc.declare({ object: 'mihomo-kit', method: 'graph', params: [ 'profile' ], expect: { '': {} } });
var callApi = rpc.declare({ object: 'mihomo-kit', method: 'api', params: [ 'path' ], nobatch: true, expect: { '': {} } });
var callServicesSet = rpc.declare({ object: 'mihomo-kit', method: 'services_set', params: [ 'services', 'pools' ], expect: { '': {} } });
var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
var callGroup = rpc.declare({ object: 'mihomo-kit', method: 'group', params: [ 'group', 'action', 'name', 'url' ],
nobatch: true, expect: { '': {} } });
function checked(r) {
if (r && r.error)
throw new Error(r.error);
return r;
}
function wait(ms) {
return new Promise(function(resolve) { window.setTimeout(resolve, ms); });
}
// the job to its end (rpcd may be unreachable while nikki restarts): its output on failure
function followJob() {
var errors = 0;
var loop = function() {
return wait(1500).then(callJob).then(function(j) {
errors = 0;
if (j.running)
return loop();
if (j.rc !== 0)
throw new Error((j.log || 'ошибка').trim().split('\n').slice(-3).join('\n'));
return j;
}, function(e) {
if (++errors > 20)
throw e;
return loop();
});
};
return loop();
}
// the YAML reader of the own servers (luci/servers.js) and the graph: globals mkServers, mkGraph
function loadScript(name, global) {
var version = '__MIHOMO_KIT_ASSETS__'; // substituted by install_luci
if (window[global] && window[global + 'Version'] === version)
return Promise.resolve(window[global]);
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.src = L.resource('mihomo-kit/' + name) + '?v=' + version;
s.onload = function() { window[global + 'Version'] = version; resolve(window[global]); };
s.onerror = function() { reject(new Error(name + ' not loaded')); };
document.head.appendChild(s);
});
}
return view.extend({
load: function() {
return Promise.all([ loadScript('servers.js', 'mkServers'), loadScript('graph.js', 'mkGraph'), callGraph(''), callStatus() ]);
},
// /proxies and /providers/proxies every 9 s, /connections every 3 s; only for the running
// profile and a visible tab
// one poll; full: also the groups and the subscriptions' nodes
fetchLive: function(full) {
return Promise.all([ full ? callApi('/proxies') : null, callApi('/connections'), full ? callApi('/providers/proxies') : null ]).then(L.bind(function(r) {
r.forEach(checked);
this.graph.live(r[0] && r[0].proxies, r[1].connections || [], r[2] && r[2].providers);
dom.content(this.state, '');
}, this)).catch(L.bind(function(e) {
dom.content(this.state, E('em', 'живое состояние недоступно: ' + (e.message || e)));
}, this));
},
poll: function() {
var tick = 0;
var loop = L.bind(function() {
if (document.hidden || !this.liveOn)
return void (this.timer = window.setTimeout(loop, 3000));
this.fetchLive(tick++ % 3 == 0).then(L.bind(function() {
this.timer = window.setTimeout(loop, 3000);
}, this));
}, this);
loop();
},
show: function(g) {
if (g.error) {
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, g.error));
return;
}
try {
this.graph.show(window.mkServers.yamlLoad(g.yaml),
{ services: g.services || [], pools: g.pools || [], servers: g.servers || [], subs: g.subs || [], hostlists: g.hostlists || [] });
} catch (e) {
dom.content(this.state, E('p', { 'class': 'alert-message warning' }, 'Не разобрал профиль: ' + e.message));
return;
}
this.liveOn = g.active && g.profile == g.running;
dom.content(this.state, this.liveOn ? '' : E('em', g.profile == g.running ? 'nikki остановлен: только схема'
: 'профиль ' + g.profile + ' сейчас не запущен: только схема, без живого состояния'));
},
render: function(data) {
var g = data[2], st = data[3];
this.state = E('div', { 'style': 'margin:.3em 0' });
var box = E('div');
var select = this.profileSelect = E('select', { 'class': 'cbi-input-select', 'change': L.bind(function(ev) {
return callGraph(ev.target.value).then(L.bind(this.show, this));
}, this) });
(st.profiles || []).forEach(function(p) {
select.appendChild(E('option', { 'value': p }, p + (p == st.profile ? ' (запущен)' : '')));
});
select.value = g.profile || st.profile;
var page = E([], [
E('h2', 'mihomo-kit: граф'),
E('div', { 'class': 'cbi-map-descr' }, 'Как устроен профиль: правила (сверху вниз — в порядке проверки) → группы → ' +
'подписки и серверы → через что они подключаются (dialer-proxy). Наведи или нажми на узел — подсветится всё, ' +
'что через него идёт; колесо — масштаб, перетаскивание — сдвиг. Для запущенного профиля видно, что выбрано ' +
'в группах сейчас и куда идут соединения; нажми на группу — выбрать или закрепить пункт (сразу, без ' +
'перезапуска). Настройки — на странице «Управление».'),
E('div', { 'style': 'margin:.5em 0' }, [ 'Профиль: ', select ]),
this.state,
box
]);
// once the page is in the document: the graph fits its box and takes the theme's background
window.setTimeout(L.bind(function() {
this.graph = window.mkGraph.view(box, {
select: function(g, name) { return callGroup(g, 'select', name, '').then(checked); },
unfix: function(g) { return callGroup(g, 'unfix', '', '').then(checked); },
delay: function(g, url) { return callGroup(g, 'delay', '', url || '').then(checked); },
refresh: L.bind(function() { return this.fetchLive(true); }, this),
saveServices: L.bind(function(list, pools) {
return callServicesSet(list, pools).then(checked).then(followJob).then(L.bind(function() {
return callGraph(this.profileSelect.value);
}, this)).then(L.bind(function(r) {
this.show(checked(r));
return this.fetchLive(true);
}, this));
}, this)
});
this.show(g);
this.poll();
}, this), 0);
return page;
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});

View File

@ -19,7 +19,6 @@ var callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', nobatc
var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', nobatch: true, expect: { '': {} } }); var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', nobatch: true, expect: { '': {} } });
var callExport = rpc.declare({ object: 'mihomo-kit', method: 'export', expect: { '': {} } }); var callExport = rpc.declare({ object: 'mihomo-kit', method: 'export', expect: { '': {} } });
var callImport = rpc.declare({ object: 'mihomo-kit', method: 'import', params: [ 'data', 'keep_local' ], expect: { '': {} } }); var callImport = rpc.declare({ object: 'mihomo-kit', method: 'import', params: [ 'data', 'keep_local' ], expect: { '': {} } });
var callApi = rpc.declare({ object: 'mihomo-kit', method: 'api', params: [ 'path' ], nobatch: true, expect: { '': {} } });
var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } }); var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } });
var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], expect: { '': {} } }); var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], expect: { '': {} } });
@ -38,30 +37,8 @@ function section(title, children) {
return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children)); return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children));
} }
// the page's tabs, drawn as LuCI draws its own (ul.cbi-tabmenu): [[id, title, pane]];
// the open one is remembered for the browser session
function tabs(list, key) {
var menu = E('ul', { 'class': 'cbi-tabmenu' }), panes = {}, items = {};
var show = function(id) {
list.forEach(function(t) {
panes[t[0]].style.display = t[0] == id ? '' : 'none';
items[t[0]].className = t[0] == id ? 'cbi-tab' : 'cbi-tab-disabled';
});
try { window.sessionStorage.setItem(key, id); } catch (e) {}
};
list.forEach(function(t) {
panes[t[0]] = t[2];
items[t[0]] = E('li', {}, E('a', { 'href': '#', 'click': function(ev) { ev.preventDefault(); show(t[0]); } }, t[1]));
menu.appendChild(items[t[0]]);
});
var cur = null;
try { cur = window.sessionStorage.getItem(key); } catch (e) {}
show(panes[cur] ? cur : list[0][0]);
return E('div', [ menu ].concat(list.map(function(t) { return t[2]; })));
}
// OpenVPN: what decides the tunnel now and what happens next, from // OpenVPN: what decides the tunnel now and what happens next, from
// ovpn.sh state (via ovpn_status) -> { now, next, pending } // bmstu-otp.sh state (via ovpn_status) -> { now, next, pending }
function ovpnMode(o) { function ovpnMode(o) {
var at = function(hm, day) { var at = function(hm, day) {
return (day == 'today' ? 'сегодня' : day == 'tomorrow' ? 'завтра' : day) + ' в ' + hm; return (day == 'today' ? 'сегодня' : day == 'tomorrow' ? 'завтра' : day) + ' в ' + hm;
@ -113,36 +90,6 @@ function check(value) {
return c; return c;
} }
// zapret hostlists (cfg.hostlists [{path, lines}]) as buttons under the service's hostlist
// field: a click adds the file to it or takes it out; nothing when zapret has no lists
function hostlistPicker(input, files) {
if (!files || !files.length)
return [];
var words = function() { return input.value.trim().split(/\s+/).filter(Boolean); };
var buttons = files.map(function(f) {
var b = E('button', { 'class': 'btn cbi-button', 'title': f.path, 'style': 'margin:.2em .3em 0 0', 'click': function(ev) {
ev.preventDefault();
var w = words(), i = w.indexOf(f.path);
if (i < 0) w.push(f.path); else w.splice(i, 1);
input.value = w.join(' ');
mark();
} });
b.mkFile = f;
return b;
});
var mark = function() {
var w = words();
buttons.forEach(function(b) {
var on = w.indexOf(b.mkFile.path) >= 0;
b.textContent = (on ? '✓ ' : '+ ') + b.mkFile.path.replace(/^.*\//, '') + ' (' + b.mkFile.lines + ')';
b.className = 'btn cbi-button' + (on ? ' cbi-button-positive' : '');
});
};
input.addEventListener('input', mark);
mark();
return [ E('div', {}, [ E('small', {}, 'из zapret: ') ].concat(buttons)) ];
}
function field(title, el, desc) { function field(title, el, desc) {
return E('div', { 'class': 'cbi-value' }, [ return E('div', { 'class': 'cbi-value' }, [
E('label', { 'class': 'cbi-value-title' }, title), E('label', { 'class': 'cbi-value-title' }, title),
@ -152,12 +99,12 @@ function field(title, el, desc) {
// qrcode-generator (luci/qrcode.js, installed with the page): a global "qrcode" // qrcode-generator (luci/qrcode.js, installed with the page): a global "qrcode"
function loadQr() { function loadQr() {
if (window.qrcode && window.qrcodeVersion === '__MIHOMO_KIT_ASSETS__') if (window.qrcode)
return Promise.resolve(window.qrcode); return Promise.resolve(window.qrcode);
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
var s = document.createElement('script'); var s = document.createElement('script');
s.src = L.resource('mihomo-kit/qrcode.js') + '?v=__MIHOMO_KIT_ASSETS__'; s.src = L.resource('mihomo-kit/qrcode.js');
s.onload = function() { window.qrcodeVersion = '__MIHOMO_KIT_ASSETS__'; resolve(window.qrcode); }; s.onload = function() { resolve(window.qrcode); };
s.onerror = function() { reject(new Error('qrcode.js not loaded')); }; s.onerror = function() { reject(new Error('qrcode.js not loaded')); };
document.head.appendChild(s); document.head.appendChild(s);
}); });
@ -165,12 +112,12 @@ function loadQr() {
// own servers: luci/servers.js (links and YAML -> proxies), a global "mkServers" // own servers: luci/servers.js (links and YAML -> proxies), a global "mkServers"
function loadServers() { function loadServers() {
if (window.mkServers && window.mkServersVersion === '__MIHOMO_KIT_ASSETS__') if (window.mkServers)
return Promise.resolve(window.mkServers); return Promise.resolve(window.mkServers);
return new Promise(function(resolve, reject) { return new Promise(function(resolve, reject) {
var s = document.createElement('script'); var s = document.createElement('script');
s.src = L.resource('mihomo-kit/servers.js') + '?v=__MIHOMO_KIT_ASSETS__'; s.src = L.resource('mihomo-kit/servers.js');
s.onload = function() { window.mkServersVersion = '__MIHOMO_KIT_ASSETS__'; resolve(window.mkServers); }; s.onload = function() { resolve(window.mkServers); };
s.onerror = function() { reject(new Error('servers.js not loaded')); }; s.onerror = function() { reject(new Error('servers.js not loaded')); };
document.head.appendChild(s); document.head.appendChild(s);
}); });
@ -190,20 +137,6 @@ function copyText(text) {
return Promise.resolve(ok); return Promise.resolve(ok);
} }
// "route <net> [mask]" lines of an .ovpn as CIDR (as ovpn_routes_of in mihomo-kit.sh)
function ovpnRoutes(text) {
return String(text).split('\n').map(function(l) {
var w = l.trim().split(/\s+/);
if (w[0] != 'route' || !/^[0-9.]+$/.test(w[1] || ''))
return null;
var bits = (/^[0-9.]+$/.test(w[2] || '') ? w[2] : '255.255.255.255').split('.').reduce(function(a, o) {
for (var x = +o; x > 0; x = Math.floor(x / 2)) a += x % 2;
return a;
}, 0);
return w[1] + '/' + bits;
}).filter(Boolean).join(' ');
}
function readFile(input) { function readFile(input) {
var f = input.files && input.files[0]; var f = input.files && input.files[0];
if (!f) if (!f)
@ -240,15 +173,12 @@ return view.extend({
}, },
renderBody: function(st) { renderBody: function(st) {
// what goes into the status part of each tab var sections = [];
var out = {};
var put = function(tab, el) { (out[tab] = out[tab] || []).push(el); };
this.buttons = []; this.buttons = [];
if (!st.configured) if (!st.configured)
put('overview', E('div', { 'class': 'alert-message warning' }, sections.push(E('div', { 'class': 'alert-message warning' },
'Kit ещё не настроен: добавь подписку на вкладке «Подписки», при желании загляни в остальные вкладки ' + 'Kit ещё не настроен: заполни «Настройка» ниже и нажми «Сохранить и применить».'));
'и нажми «Сохранить и применить» внизу страницы.'));
var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) { var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) {
return E('option', { 'value': p }, p); return E('option', { 'value': p }, p);
@ -256,8 +186,6 @@ return view.extend({
select.value = st.profile; select.value = st.profile;
// mihomo serves its external-ui at /ui; metacubexd/zashboard take the API from the query // mihomo serves its external-ui at /ui; metacubexd/zashboard take the API from the query
var updState = E('em', 'проверяю обновления…'); var updState = E('em', 'проверяю обновления…');
// shown only next to "есть обновление"; the same command as on «Система»
var updBtn = this.button('Обновить', 'apply', 'update', null, 'Скачать свежий kit и пересобрать профили?');
callUpdateCheck().then(function(u) { callUpdateCheck().then(function(u) {
if (u.error) if (u.error)
return dom.content(updState, '— не удалось проверить обновления: ' + u.error); return dom.content(updState, '— не удалось проверить обновления: ' + u.error);
@ -265,12 +193,12 @@ return view.extend({
if (u.installed && u.installed.indexOf(u.latest) == 0) if (u.installed && u.installed.indexOf(u.latest) == 0)
return dom.content(updState, '— актуальная'); return dom.content(updState, '— актуальная');
dom.content(updState, [ '— ', E('strong', 'есть обновление: '), link(u.commit, u.latest), ' ' + (u.message || '') ] dom.content(updState, [ '— ', E('strong', 'есть обновление: '), link(u.commit, u.latest), ' ' + (u.message || '') ]
.concat(u.compare ? [ ' (', link(u.compare, 'что изменилось'), ')' ] : []).concat([ ' ', updBtn ])); .concat(u.compare ? [ ' (', link(u.compare, 'что изменилось'), ')' ] : []));
}).catch(function(e) { dom.content(updState, '— не удалось проверить обновления: ' + e); }); }).catch(function(e) { dom.content(updState, '— не удалось проверить обновления: ' + e); });
var host = window.location.hostname; var host = window.location.hostname;
var dash = 'http://' + host + ':' + st.api_port + '/ui/?hostname=' + encodeURIComponent(host) + var dash = 'http://' + host + ':' + st.api_port + '/ui/?hostname=' + encodeURIComponent(host) +
'&port=' + st.api_port + (st.api_secret ? '&secret=' + encodeURIComponent(st.api_secret) : ''); '&port=' + st.api_port + (st.api_secret ? '&secret=' + encodeURIComponent(st.api_secret) : '');
put('overview', section('Состояние', [ sections.push(section('Состояние', [
E('table', { 'class': 'table' }, [ E('table', { 'class': 'table' }, [
row('nikki', st.running ? [ 'работает — ', row('nikki', st.running ? [ 'работает — ',
E('a', { 'href': dash, 'target': '_blank', 'rel': 'noreferrer' }, 'открыть дашборд') ] E('a', { 'href': dash, 'target': '_blank', 'rel': 'noreferrer' }, 'открыть дашборд') ]
@ -280,7 +208,7 @@ return view.extend({
.concat(st.core && st.core.ok == '0' .concat(st.core && st.core.ok == '0'
? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'выбрано ' + ? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'выбрано ' +
(st.core.wanted == 'stock' ? 'ядро из прошивки' : st.core.wanted)), (st.core.wanted == 'stock' ? 'ядро из прошивки' : st.core.wanted)),
': нажми «Починить» на вкладке «Система»' ] ': нажми «Починить» в «Обслуживании»' ]
: [])), : [])),
row('Память mihomo', st.mem_kb ? [ Math.round(st.mem_kb / 1024) + ' МБ (RSS)', row('Память mihomo', st.mem_kb ? [ Math.round(st.mem_kb / 1024) + ' МБ (RSS)',
st.lite ? ' — облегчённый режим' : '' ] : '—'), st.lite ? ' — облегчённый режим' : '' ] : '—'),
@ -323,8 +251,8 @@ return view.extend({
connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'), connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'),
o.err ? desc(' — ' + o.err) : '' ], o.err ? desc(' — ' + o.err) : '' ],
rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'), rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'),
desc(o.retry_hm ? ' — роутер подключится заново после паузы, в ' + o.retry_hm desc(o.retry_hm ? ' — cron возьмёт новый OTP после паузы, в ' + o.retry_hm
: ' — роутер подключится заново в течение минуты') ], : ' — cron возьмёт новый OTP в течение минуты') ],
held: [ E('strong', { 'style': 'color:#c60' }, { held: [ E('strong', { 'style': 'color:#c60' }, {
kick: 'сервер отключил сессию', kick: 'сервер отключил сессию',
drop: 'туннель оборвался', drop: 'туннель оборвался',
@ -333,8 +261,8 @@ return view.extend({
desc(' — следующая попытка в ' + o.retry_hm + ' (без быстрых переподключений)' + desc(' — следующая попытка в ' + o.retry_hm + ' (без быстрых переподключений)' +
(o.err ? '; ' + o.err : '')) ], (o.err ? '; ' + o.err : '')) ],
unknown: [ E('strong', 'ядро не сообщает состояние'), unknown: [ E('strong', 'ядро не сообщает состояние'),
desc(' — с этим ядром роутер проверяет туннель запросом к адресу проверки раз в ~10 минут, ' + desc(' — с этим ядром cron проверяет туннель запросом к сайту раз в ~10 минут, ' +
'и маскировка под OpenVPN Connect неполная. Лучше ядро kit (вкладка «Система» → ядро).') ] 'и маскировка под Connect неполная. Нужно ядро kit («Обслуживание» → ядро).') ]
}[o.link] || o.link || '—'); }[o.link] || o.link || '—');
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—'); dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
var m = ovpnMode(o); var m = ovpnMode(o);
@ -342,7 +270,7 @@ return view.extend({
? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : [])); ? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : []));
dom.content(modeNext, m.next || '—'); dom.content(modeNext, m.next || '—');
dom.content(schedInfo, o.sched_start dom.content(schedInfo, o.sched_start
? (o.sched_active ? 'включено: ' : 'выключено (часы сохранены): ') + daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (по времени роутера), границы сдвигаются до ±' + o.jitter + ? (o.sched_active ? 'включено: ' : 'выключено (часы сохранены): ') + daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter +
' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '') ' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '')
: 'выключено'); : 'выключено');
// one of each pair, by the state: timer running or not, schedule on or not // one of each pair, by the state: timer running or not, schedule on or not
@ -370,7 +298,7 @@ return view.extend({
'Выключить расписание? Туннель выключится и сам не включится, пока не нажмёшь «Включить» или «Включить расписание».'); 'Выключить расписание? Туннель выключится и сам не включится, пока не нажмёшь «Включить» или «Включить расписание».');
schedStopBtn.style.display = 'none'; schedStopBtn.style.display = 'none';
ovpnCheck(); ovpnCheck();
put('ovpn', section('Состояние', [ sections.push(section('OpenVPN', [
E('table', { 'class': 'table' }, [ E('table', { 'class': 'table' }, [
row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, ovpnCheck) }, 'Обновить') ]), 'click': ui.createHandlerFn(this, ovpnCheck) }, 'Обновить') ]),
@ -386,8 +314,8 @@ return view.extend({
}) }, 'Проверить'), ' ', probeRes, }) }, 'Проверить'), ' ', probeRes,
E('div', { 'class': 'cbi-value-description' }, E('div', { 'class': 'cbi-value-description' },
'Открывает адрес проверки через туннель. Только по кнопке: сайт видит такой запрос в логах, ' + 'Открывает адрес проверки через туннель. Только по кнопке: сайт видит такой запрос в логах, ' +
'а обычный клиент OpenVPN их не делает. Адрес лучше взять из тех, что и так открываешь в браузере.') ]), 'а сам Connect их не делает. Адрес лучше взять из тех, что и так открываешь в браузере.') ]),
row('Код сейчас', otp), row('OTP сейчас', otp),
row('Сейчас', modeNow), row('Сейчас', modeNow),
row('Дальше', modeNext), row('Дальше', modeNext),
row('Расписание', schedInfo) row('Расписание', schedInfo)
@ -398,12 +326,12 @@ return view.extend({
this.button('Выключить', 'negative', 'ovpn-off', null, this.button('Выключить', 'negative', 'ovpn-off', null,
'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить» или «Включить расписание»? ' + 'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить» или «Включить расписание»? ' +
'Расписание и таймер выключатся. ' + 'Расписание и таймер выключатся. ' +
'С ядром kit сервер сразу узнаёт об отключении, с другим ядром — через ~5 минут.'), ' ', 'С ядром kit сессия на сервере освобождается сразу, с другим ядром — через ~5 минут.'), ' ',
schedStartBtn, schedStopBtn, ' ', schedStartBtn, schedStopBtn, ' ',
timerStart, timerMore, ' ', timerStop, ' ', timerStart, timerMore, ' ', timerStop, ' ',
this.button('Переподключить', 'action', 'ovpn-refresh') this.button('Переподключить', 'action', 'ovpn-refresh')
]), ]),
field('Часы расписания', [ schedStart, ' – ', schedEnd, ' ', field('Часы расписания (MSK)', [ schedStart, ' – ', schedEnd, ' ',
E('span', { 'style': 'white-space:nowrap' }, schedDays.reduce(function(a, c, i) { E('span', { 'style': 'white-space:nowrap' }, schedDays.reduce(function(a, c, i) {
return a.concat([ ' ', E('label', [ c, ' ', dayNames[i] ]) ]); return a.concat([ ' ', E('label', [ c, ' ', dayNames[i] ]) ]);
}, [])), ' ', }, [])), ' ',
@ -411,8 +339,7 @@ return view.extend({
var d = schedDays.reduce(function(a, c, i) { return c.checked ? a + (i + 1) : a; }, ''); var d = schedDays.reduce(function(a, c, i) { return c.checked ? a + (i + 1) : a; }, '');
return schedStart.value + ' ' + schedEnd.value + ' ' + d; return schedStart.value + ' ' + schedEnd.value + ' ' + d;
}) ], }) ],
'По времени роутера (Система → Система → часовой пояс). «Сохранить» только запоминает часы и дни, ' + '«Сохранить» только запоминает часы и дни, включает их «Включить расписание». ' +
'включает их «Включить расписание». ' +
'Режим один из трёх: «Включить» — постоянно, «Выключить» — выключен, «Включить расписание» — ' + 'Режим один из трёх: «Включить» — постоянно, «Выключить» — выключен, «Включить расписание» — ' +
'только в эти часы и в отмеченные дни (окно через полночь относится ко дню, в который началось). ' + 'только в эти часы и в отмеченные дни (окно через полночь относится ко дню, в который началось). ' +
'Выключенное расписание туннель не включает. Таймер («на 1 ч», «+1 ч», до 12 ч вперёд) поднимает туннель ' + 'Выключенное расписание туннель не включает. Таймер («на 1 ч», «+1 ч», до 12 ч вперёд) поднимает туннель ' +
@ -444,7 +371,7 @@ return view.extend({
}; };
if (st.csqtt_installed) if (st.csqtt_installed)
cqCheck(); cqCheck();
put('csqtt', section('Состояние', st.csqtt_installed ? [ sections.push(section('CSQTT', st.csqtt_installed ? [
E('table', { 'class': 'table' }, [ E('table', { 'class': 'table' }, [
row('Туннель', [ cqState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', row('Туннель', [ cqState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, cqCheck) }, 'Обновить') ]), 'click': ui.createHandlerFn(this, cqCheck) }, 'Обновить') ]),
@ -477,7 +404,7 @@ return view.extend({
}; };
if (st.ts_logged_in) if (st.ts_logged_in)
tsCheck(); tsCheck();
put('ts', section('Состояние', [ sections.push(section('Tailscale', [
E('table', { 'class': 'table' }, [ E('table', { 'class': 'table' }, [
row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла')), row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла')),
row('Связь', [ tsState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', row('Связь', [ tsState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
@ -495,60 +422,30 @@ return view.extend({
if (st.mobile_path) { if (st.mobile_path) {
var mobUrl = window.location.protocol + '//' + window.location.host + st.mobile_path; var mobUrl = window.location.protocol + '//' + window.location.host + st.mobile_path;
// the QR holds the plain link: any app's "add by QR / URL" takes it; the import link
// (clash://) opens the app straight away when this page is open on the phone itself
var importUrl = 'clash://install-config?url=' + encodeURIComponent(mobUrl) + '&name=mihomo-kit';
var qrBox = E('div', { 'style': 'width:220px;max-width:100%;background:#fff;padding:8px;border-radius:4px' }, E('em', 'QR…')); var qrBox = E('div', { 'style': 'width:220px;max-width:100%;background:#fff;padding:8px;border-radius:4px' }, E('em', 'QR…'));
var copied = E('span', { 'class': 'cbi-value-description' });
var copy = function() {
var done = function() { copied.textContent = ' скопировано'; };
if (navigator.clipboard && window.isSecureContext)
return navigator.clipboard.writeText(mobUrl).then(done);
// http LuCI: no Clipboard API
var t = E('textarea', { 'style': 'position:fixed;opacity:0' }, mobUrl);
document.body.appendChild(t);
t.select();
document.execCommand('copy');
document.body.removeChild(t);
done();
};
loadQr().then(function(qrcode) { loadQr().then(function(qrcode) {
var q = qrcode(0, 'M'); var q = qrcode(0, 'M');
q.addData(mobUrl); q.addData(mobUrl);
q.make(); q.make();
qrBox.innerHTML = q.createSvgTag({ cellSize: 4, margin: 2, scalable: true }); qrBox.innerHTML = q.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
}).catch(function(e) { dom.content(qrBox, String(e)); }); }).catch(function(e) { dom.content(qrBox, String(e)); });
put('phone', section('Подключить приложение', [ sections.push(section('Телефон (FlClash)', [
E('div', { 'style': 'display:flex;gap:1.5em;flex-wrap:wrap;align-items:flex-start' }, [ E('div', { 'style': 'display:flex;gap:1.5em;flex-wrap:wrap;align-items:flex-start' }, [
qrBox, qrBox,
E('div', { 'style': 'flex:1;min-width:16em' }, [ E('div', { 'style': 'flex:1;min-width:16em' }, [
E('p', 'Тот же обход в приложении на телефоне или компьютере: те же подписки и правила, ' + E('p', 'FlClash → Профили → + → по ссылке (или QR) — профиль из тех же подписок и BOOT, ' +
'без OpenVPN, Tailscale и торрентов. Подойдёт приложение на ядре mihomo (Clash Meta):'), 'без OpenVPN, Tailscale и торрентов; свои серверы — через MY-EXIT.'),
E('ul', [ E('p', [ E('a', { 'href': mobUrl, 'target': '_blank', 'rel': 'noreferrer' }, mobUrl) ]),
E('li', [ E('strong', 'Android'), ' — FlClash или Clash Meta for Android' ]), E('p', { 'class': 'cbi-value-description' }, 'Ссылка работает только в сети роутера: вне дома FlClash ' +
E('li', [ E('strong', 'iPhone, iPad'), ' — Clash Mi' ]), 'просто не обновит профиль. В ней ссылки подписок — не пересылай; «Новая ссылка» отзывает старую.'),
E('li', [ E('strong', 'Windows, macOS, Linux'), ' — FlClash или Clash Verge Rev' ])
]),
E('p', 'В приложении: профили (подписки) → добавить → по ссылке или QR-коду. Отсканируй QR сканером ' +
'в приложении или скопируй ссылку и вставь её. Профиль обновляется по этой ссылке сам.'),
E('p', [ E('code', { 'style': 'word-break:break-all' }, mobUrl) ]),
E('p', [
E('button', { 'class': 'btn cbi-button', 'click': copy }, 'Скопировать ссылку'), ' ',
E('a', { 'class': 'btn cbi-button', 'href': importUrl,
'title': 'если эта страница открыта на телефоне: откроет приложение и добавит профиль' }, 'Открыть в приложении'),
copied
]),
E('p', { 'class': 'cbi-value-description' }, 'Добавлять профиль нужно дома, в сети этого роутера: ' +
'снаружи ссылка не открывается, и приложение просто не обновит профиль до возвращения домой. ' +
'В профиле ссылки подписок — не пересылай ссылку чужим; «Новая ссылка» отзывает старую.'),
this.button('Новая ссылка', 'negative', 'mobile-new', null, this.button('Новая ссылка', 'negative', 'mobile-new', null,
'Выдать новую ссылку? Старая перестанет работать, в приложениях профиль надо будет добавить заново.') 'Выдать новую ссылку? Старая перестанет работать, в FlClash профиль надо будет добавить заново.')
]) ])
]) ])
])); ]));
} }
put('system', section('Обслуживание', [ sections.push(section('Обслуживание', [
E('table', { 'class': 'table' }, [ E('table', { 'class': 'table' }, [
row(this.button('Пересобрать профили', 'action', 'build'), row(this.button('Пересобрать профили', 'action', 'build'),
'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'), 'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'),
@ -578,14 +475,20 @@ return view.extend({
]) ])
])); ]));
Object.keys(this.slots).forEach(function(k) { dom.content(this.slots[k].status, out[k] || []); }, this); dom.content(this.body, sections);
}, },
// the settings parts of the tabs, from the saved settings // collapsed: a button; open: the form (always open until configured)
renderSettingsBox: function() { renderSettingsBox: function(open) {
return Promise.all([ callConfigGet(), loadServers() ]).then(L.bind(function(r) { if (open)
return this.renderSettings(r[0]); return Promise.all([ callConfigGet(), loadServers() ]).then(L.bind(function(r) {
}, this)); return this.renderSettings(r[0]);
}, this));
dom.content(this.settingsBox, [ E('h3', 'Настройка'), E('button', {
'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function() { return this.renderSettingsBox(true); })
}, 'Изменить настройки') ]);
return Promise.resolve();
}, },
renderSettings: function(cfg) { renderSettings: function(cfg) {
@ -606,40 +509,22 @@ return view.extend({
foreign_domains: text(cfg.foreign_domains, 'example.com *.example.org'), foreign_domains: text(cfg.foreign_domains, 'example.com *.example.org'),
my_domains: text(cfg.my_domains, 'example.com *.example.org'), my_domains: text(cfg.my_domains, 'example.com *.example.org'),
local_hosts: text(cfg.local_hosts, 'example.com=192.168.1.10'), local_hosts: text(cfg.local_hosts, 'example.com=192.168.1.10'),
bypass_clients: text(cfg.bypass_clients, '192.168.1.50 aa:bb:cc:dd:ee:ff'),
openvpn: check(cfg.openvpn), openvpn: check(cfg.openvpn),
csqtt: check(cfg.csqtt), csqtt: check(cfg.csqtt),
ovpn: E('input', { 'type': 'file', 'accept': '.ovpn,.conf' }), ovpn: E('input', { 'type': 'file', 'accept': '.ovpn,.conf' }),
vpn_username: text(cfg.vpn_username), vpn_username: text(cfg.vpn_username),
vpn_password: text('', cfg.has_vpn_password ? 'сохранён — пусто, чтобы не менять' : '', 'password'), vpn_password: text('', cfg.has_vpn_password ? 'сохранён — пусто, чтобы не менять' : '', 'password'),
totp_secret: text('', cfg.has_totp ? 'сохранён — пусто, чтобы не менять' : 'необязательно', 'password'), totp_secret: text('', cfg.has_totp ? 'сохранён — пусто, чтобы не менять' : 'base32 из QR', 'password'),
totp_clear: check(false),
pass_format: E('select', { 'class': 'cbi-input-select' }, [
[ 'auto', 'сам: как просит файл .ovpn' ],
[ 'scrv1', 'отдельным полем (static-challenge, как OpenVPN Connect)' ],
[ 'otp-last', 'пароль, сразу за ним код' ],
[ 'otp-first', 'код, сразу за ним пароль' ]
].map(function(o) { return E('option', { 'value': o[0] }, o[1]); })),
ovpn_routes: text(cfg.ovpn_routes, '10.0.0.0/8 192.168.50.0/24'),
tailscale: check(cfg.tailscale), tailscale: check(cfg.tailscale),
ts_hostname: text(cfg.ts_hostname), ts_hostname: text(cfg.ts_hostname),
ts_domains: text(cfg.ts_domains, 'corp.example.com'), ts_domains: text(cfg.ts_domains, 'corp.example.com'),
ovpn_check_url: text(cfg.ovpn_check_url, 'https://intranet.example.com'), ovpn_check_url: text(cfg.ovpn_check_url, 'https://eu.bmstu.ru'),
ts_check_url: text(cfg.ts_check_url, 'http://100.69.216.50:8080'), ts_check_url: text(cfg.ts_check_url, 'http://100.69.216.50:8080'),
mobile: check(cfg.mobile), mobile: check(cfg.mobile),
lite: check(cfg.lite), lite: check(cfg.lite),
lite_gomemlimit: text(cfg.lite_gomemlimit, '64MiB') lite_gomemlimit: text(cfg.lite_gomemlimit, '64MiB')
}; };
f.pass_format.value = cfg.pass_format || 'auto';
// a new .ovpn: its route lines, unless the networks are filled in already
f.ovpn.addEventListener('change', function() {
readFile(f.ovpn).then(function(t) {
var r = ovpnRoutes(t);
if (r && !f.ovpn_routes.value.trim())
f.ovpn_routes.value = r;
});
});
var update = function() { var update = function() {
hwidBox.style.display = subs.some(function(s) { return s.hwid.checked; }) ? '' : 'none'; hwidBox.style.display = subs.some(function(s) { return s.hwid.checked; }) ? '' : 'none';
ovpnBox.style.display = f.openvpn.checked ? '' : 'none'; ovpnBox.style.display = f.openvpn.checked ? '' : 'none';
@ -674,77 +559,6 @@ return view.extend({
}; };
(cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub); (cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub);
// services (SERVICES): a site or app with its own group and way, a row each;
// "через": the built-in groups or a pool (pools below, read when the list opens)
var svcList = E('div'), services = [], pools = [];
var viaOptions = function(sel) {
var cur = sel.value || sel.getAttribute('data-via');
var names = pools.length ? pools.map(function(p) { return p.name.value.trim().toUpperCase(); })
: (cfg.pools || []).map(function(p) { return p.name.toUpperCase(); });
dom.content(sel, [
[ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ]
].concat(names.filter(Boolean).map(function(n) { return [ n, 'пул ' + n ]; }))
.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
sel.value = cur;
};
// "вход" of a service (SVC_<NAME>_CHAIN): what its exit servers dial through
var chainOptions = function(sel) {
var cur = sel.value || sel.getAttribute('data-chain') || '';
var names = pools.length ? pools.map(function(p) { return p.name.value.trim().toUpperCase(); })
: (cfg.pools || []).map(function(p) { return p.name.toUpperCase(); });
dom.content(sel, [ [ '', 'как обычно' ], [ 'DIRECT', 'напрямую' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'MY', 'MY' ], [ 'MY-EXIT', 'MY-EXIT (whitelist, телефон)' ] ]
.concat(names.filter(Boolean).map(function(n) { return [ n, 'пул ' + n ]; }))
.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
sel.value = cur;
};
var addService = function(v) {
var e = {
name: text(v.name || '', 'claude'),
via: E('select', { 'class': 'cbi-input-select', 'data-via': v.via || 'MY' }),
chain: E('select', { 'class': 'cbi-input-select', 'data-chain': v.chain || '' }),
server: text(v.server || '', 'пусто — группа / автовыбор'),
provider: text(v.provider || '', 'пусто — свои серверы; иначе ID провайдера'),
geosite: text(v.geosite || '', 'anthropic'),
domains: text(v.domains || '', 'example.com'),
ips: text(v.ips || '', '1.2.3.0/24'),
hostlist: text(v.hostlist || '', '/opt/zapret2/ipset/zapret_hosts_youtube.txt')
};
e.name.style.width = '9em';
viaOptions(e.via);
e.via.addEventListener('focus', function() { viaOptions(e.via); });
e.via.addEventListener('mousedown', function() { viaOptions(e.via); });
e.via.disabled = !!e.server.value.trim();
e.server.addEventListener('input', function() { e.via.disabled = !!e.server.value.trim(); });
chainOptions(e.chain);
e.chain.addEventListener('focus', function() { chainOptions(e.chain); });
e.chain.addEventListener('mousedown', function() { chainOptions(e.chain); });
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
e.name, 'через', e.via,
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить сервис', 'click': function() {
svcList.removeChild(el);
services.splice(services.indexOf(e), 1);
} }, '✕')
]),
field('geosite', e.geosite, 'списки MetaCubeX/meta-rules-dat через пробел: anthropic, openai, youtube…'),
field('Домены', e.domains, 'ещё домены, с поддоменами'),
field('IP', e.ips, 'ещё адреса, без маски = /32'),
field('Списки доменов', [ e.hostlist ].concat(hostlistPicker(e.hostlist, cfg.hostlists)),
'файлы со списком доменов, по одному в строке (хостлисты zapret), через пробел; читаются при каждой ' +
'сборке профиля — изменился список в zapret: «Применить»'),
field('Фиксированный сервер', e.server, 'точное имя; выбор сохраняется во всех профилях. Удобнее выбирать на графе'),
field('Источник сервера', e.provider, 'для подписки — ID провайдера, например sam_hub-my; для своего сервера оставить пустым'),
field('Вход', e.chain, 'для фиксированного сервера, MY или пула: через что подключаться к его серверам (например, ' +
'сервер с нужным IP доступен только через другой пул). «Как обычно» — на whitelist и телефоне через MY-EXIT, ' +
'иначе напрямую')
]);
services.push(e);
svcList.appendChild(el);
};
(cfg.services || []).forEach(addService);
// own servers (luci/servers.js): a card each - the name, type and address, the // own servers (luci/servers.js): a card each - the name, type and address, the
// proxy as YAML to edit; share links / YAML pasted below become cards // proxy as YAML to edit; share links / YAML pasted below become cards
var S = window.mkServers; var S = window.mkServers;
@ -754,39 +568,17 @@ return view.extend({
servers.forEach(function(e) { t[e.name.value.trim()] = true; }); servers.forEach(function(e) { t[e.name.value.trim()] = true; });
return t; return t;
}; };
// "Вход" of an own server (its own dialer-proxy): what it dials through in every
// profile instead of what the kit puts in front (MY-EXIT, UPLINK, directly)
var entryOptions = function(sel) {
var cur = sel.value || sel.getAttribute('data-entry') || '';
var names = pools.map(function(p) { return p.name.value.trim().toUpperCase(); }).filter(Boolean);
var opts = [ [ '', 'вход: как обычно' ], [ 'FOREIGN', 'вход: через FOREIGN' ], [ 'RU', 'вход: через RU' ],
[ 'DIRECT', 'вход: напрямую' ] ].concat(names.map(function(n) { return [ n, 'вход: через пул ' + n ]; }));
if (cur && !opts.some(function(o) { return o[0] == cur; }))
opts.push([ cur, 'вход: ' + cur + ' (такого нет)' ]);
dom.content(sel, opts.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
sel.value = cur;
};
var addServer = function(p, open) { var addServer = function(p, open) {
var e = { proxy: {}, error: null }; var e = { proxy: {}, error: null };
Object.keys(p).forEach(function(k) { Object.keys(p).forEach(function(k) {
if (k != 'name' && k != 'dialer-proxy') if (k != 'name' && k != 'dialer-proxy')
e.proxy[k] = p[k]; e.proxy[k] = p[k];
}); });
e.entry = E('select', { 'class': 'cbi-input-select', 'data-entry': p['dialer-proxy'] || '',
'title': 'через что подключаться к этому серверу, во всех профилях и на телефоне: например, через FOREIGN, ' +
'если сам сервер напрямую недоступен. «Как обычно» — как остальные свои серверы' });
entryOptions(e.entry);
e.entry.addEventListener('focus', function() { entryOptions(e.entry); });
e.entry.addEventListener('mousedown', function() { entryOptions(e.entry); });
// "как обычно" is an empty value: keep the choice for the next rebuild of the list
e.entry.addEventListener('change', function() { e.entry.setAttribute('data-entry', e.entry.value); });
e.name = text(S.freeName(p.name, taken()), 'имя в дашборде'); e.name = text(S.freeName(p.name, taken()), 'имя в дашборде');
e.name.style.width = '16em'; e.name.style.width = '16em';
e.get = function() { e.get = function() {
var o = { name: e.name.value.trim() }; var o = { name: e.name.value.trim() };
Object.keys(e.proxy).forEach(function(k) { o[k] = e.proxy[k]; }); Object.keys(e.proxy).forEach(function(k) { o[k] = e.proxy[k]; });
if (e.entry.value)
o['dialer-proxy'] = e.entry.value;
return o; return o;
}; };
var info = E('code', {}, S.summary(e.proxy)); var info = E('code', {}, S.summary(e.proxy));
@ -802,12 +594,6 @@ return view.extend({
if (!v.type || v.server === undefined || v.server === null || v.server === '') if (!v.type || v.server === undefined || v.server === null || v.server === '')
throw new Error('нужны type и server'); throw new Error('нужны type и server');
delete v.name; delete v.name;
// dialer-proxy typed in the YAML: the same as the entry select
if (v['dialer-proxy']) {
e.entry.setAttribute('data-entry', v['dialer-proxy']);
e.entry.value = '';
entryOptions(e.entry);
}
delete v['dialer-proxy']; delete v['dialer-proxy'];
e.proxy = v; e.proxy = v;
e.error = null; e.error = null;
@ -821,7 +607,7 @@ return view.extend({
}); });
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [ var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [ E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
e.name, info, e.entry, e.name, info,
E('button', { 'class': 'btn cbi-button', 'click': function() { E('button', { 'class': 'btn cbi-button', 'click': function() {
e.yaml.style.display = e.yaml.style.display == 'none' ? '' : 'none'; e.yaml.style.display = e.yaml.style.display == 'none' ? '' : 'none';
} }, 'Настройки (YAML)'), } }, 'Настройки (YAML)'),
@ -850,49 +636,6 @@ return view.extend({
srvList.appendChild(el); srvList.appendChild(el);
}; };
S.fromLines(cfg.servers_text).forEach(function(p) { addServer(p); }); S.fromLines(cfg.servers_text).forEach(function(p) { addServer(p); });
// [MY] nodes of the subscriptions (providers <id>-my): the same "Вход" per node
// (MY_NODE_ENTRIES). The names come from the running mihomo; saved entries show
// even when it does not run.
var myNodes = [], myNodeBox = E('div', E('em', 'загружаю ноды [MY] из подписок…'));
var addMyNode = function(provider, name, entry) {
if (myNodes.some(function(n) { return n.provider == provider && n.name == name; }))
return;
var n = { provider: provider, name: name,
entry: E('select', { 'class': 'cbi-input-select', 'data-entry': entry || '' }) };
entryOptions(n.entry);
n.entry.addEventListener('focus', function() { entryOptions(n.entry); });
n.entry.addEventListener('mousedown', function() { entryOptions(n.entry); });
n.entry.addEventListener('change', function() { n.entry.setAttribute('data-entry', n.entry.value); });
myNodes.push(n);
};
String(cfg.my_node_entries || '').split('\n').forEach(function(l) {
var m = /^([^|]*)\|([^|]*)\|(.+)$/.exec(l);
if (m)
addMyNode(m[2], m[3], m[1]);
});
var drawMyNodes = function(note) {
dom.content(myNodeBox, [ note ? E('p', { 'class': 'cbi-value-description' }, note) : '' ].concat(myNodes.length
? myNodes.map(function(n) {
return E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-bottom:.3em' },
[ E('code', n.name), E('span', { 'class': 'cbi-value-description' }, n.provider), n.entry ]);
})
: [ E('em', 'нод [MY] в подписках нет') ]));
};
callApi('/providers/proxies').then(function(r) {
if (r.error)
throw new Error(r.error);
Object.keys(r.providers || {}).sort().forEach(function(pn) {
// <id>-my and <id>-my-via-<entry> (nodes with an entry already); not the chains' <id>-my@<entry>
var m = /^(.+-my)(-via-.+)?$/.exec(pn);
if (!m || pn.indexOf('@') >= 0)
return;
(r.providers[pn].proxies || []).forEach(function(p) { addMyNode(m[1], p.name, ''); });
});
drawMyNodes('');
}).catch(function() {
drawMyNodes('nikki сейчас не работает: видны только ноды, у которых вход уже задан. Запусти профиль, чтобы увидеть все.');
});
// the old settings: hysteria2 by fields (HY2_*) and links (MY_LINKS) become cards, // the old settings: hysteria2 by fields (HY2_*) and links (MY_LINKS) become cards,
// the save writes them as own servers and drops the old keys // the save writes them as own servers and drops the old keys
var moved = 0; var moved = 0;
@ -920,85 +663,20 @@ return view.extend({
moved++; moved++;
}); });
// pools (POOLS): own servers (by name) and subscription nodes (providers + filter) picked // import: share links and/or YAML (or a file) -> cards
// by hand, a card each; group = the name in upper case, a service goes through it
var poolList = E('div');
var poolSubs = [];
(cfg.subs || []).forEach(function(s) {
if (s.id)
poolSubs.push([ s.id, s.id ], [ s.id + '-my', s.id + ' — только [MY]' ]);
});
var boxes = function(all, have, label) {
var list = all.map(function(o) { return { v: o[0], t: o[1] }; });
have.forEach(function(v) {
if (!list.some(function(o) { return o.v == v; }))
list.push({ v: v, t: v + ' (нет в настройках)' });
});
return list.map(function(o) {
o.c = check(have.indexOf(o.v) >= 0);
o.el = E('label', { 'style': 'margin-right:1em;white-space:nowrap;display:inline-block' }, [ o.c, ' ', o.t ]);
return o;
});
};
var addPool = function(v) {
var srvNames = servers.map(function(e) { return e.name.value.trim(); }).filter(Boolean);
var e = {
name: text(v.name || '', 'de'),
type: E('select', { 'class': 'cbi-input-select' }, [
[ 'fallback', 'первый живой' ], [ 'url-test', 'самый быстрый' ], [ 'select', 'вручную (в дашборде / графе)' ]
].map(function(o) { return E('option', { 'value': o[0] }, o[1]); })),
srv: boxes(srvNames.map(function(n) { return [ n, n ]; }),
(v.servers || '').split(';').map(function(x) { return x.trim(); }).filter(Boolean)),
subs: boxes(poolSubs, (v.subs || '').split(/\s+/).filter(Boolean)),
filter: text(v.filter || '', '(?i)🇩🇪|\\bde\\b или \\[WL\\]'),
exclude: text(v.exclude || '', '(?i)torrent'),
uplink: check(v.uplink == '1')
};
e.name.style.width = '9em';
e.type.value = v.type || 'fallback';
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
e.name, e.type,
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить пул', 'click': function() {
poolList.removeChild(el);
pools.splice(pools.indexOf(e), 1);
} }, '✕')
]),
field('Свои серверы', e.srv.length ? e.srv.map(function(o) { return o.el; }) : E('em', 'нет своих серверов'),
'новые серверы появятся здесь после сохранения'),
field('Подписки', e.subs.length ? e.subs.map(function(o) { return o.el; }) : E('em', 'нет подписок'),
'их ноды — по фильтру ниже; «только [MY]» — ноды с [MY] в имени'),
field('Фильтр', e.filter, 'регулярное выражение по имени ноды подписки (filter в mihomo): ' +
'метка своей подписки — \\[WL\\], страна — (?i)🇩🇪|\\bde\\b; пусто — все ноды. К своим серверам не применяется'),
field('Исключить', e.exclude, 'ноды подписки с таким именем не берутся'),
field('В UPLINK', e.uplink, 'предлагать пул в группе UPLINK: если выбрать его там (дашборд, граф), всё ' +
'сначала идёт через пул, а дальше как обычно — для выхода из блокировок. Серверы пула при этом подключаются напрямую')
]);
pools.push(e);
poolList.appendChild(el);
};
(cfg.pools || []).forEach(addPool);
// import: share links, AmneziaVPN keys, YAML or a WireGuard / AmneziaWG .conf (or a
// file) -> cards; a .conf from a file is named after the file
var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 8, 'spellcheck': 'false', var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 8, 'spellcheck': 'false',
'style': 'width:100%;font-family:monospace', 'style': 'width:100%;font-family:monospace',
'placeholder': 'vless://…\ntrojan://…\nhysteria2://…\nvpn://… (ключ AmneziaVPN)\n\nили .conf AmneziaWG / WireGuard ([Interface] … [Peer] …)\n\nили YAML, как в конфиге mihomo / Clash:\n- name: nl-1\n type: hysteria2\n server: vpn.example.com\n port: 443\n password: ...' }); 'placeholder': 'vless://…\ntrojan://…\nhysteria2://…\n\nили YAML, как в конфиге mihomo / Clash:\n- name: nl-1\n type: hysteria2\n server: vpn.example.com\n port: 443\n password: ...' });
var importFile = E('input', { 'type': 'file', 'accept': '.yaml,.yml,.txt,.conf,.vpn' }); var importFile = E('input', { 'type': 'file', 'accept': '.yaml,.yml,.txt,.conf' });
var importName = '';
importFile.addEventListener('change', function() { importFile.addEventListener('change', function() {
readFile(importFile).then(function(t) { readFile(importFile).then(function(t) { importText.value = t; });
importText.value = t;
importName = importFile.files[0] ? importFile.files[0].name.replace(/\.[^.]*$/, '') : '';
});
}); });
importText.addEventListener('input', function() { importName = ''; });
var importBox = E('div', { 'style': 'display:none;margin-bottom:.5em' }, [ var importBox = E('div', { 'style': 'display:none;margin-bottom:.5em' }, [
importText, importText,
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-top:.3em' }, [ E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-top:.3em' }, [
E('span', 'или из файла:'), importFile, E('span', 'или из файла:'), importFile,
E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': function() { E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': function() {
var r = S.parseText(importText.value, importName); var r = S.parseText(importText.value);
r.servers.forEach(function(p) { addServer(p); }); r.servers.forEach(function(p) { addServer(p); });
var msg = [ E('p', r.servers.length ? 'Добавлено серверов: ' + r.servers.length + var msg = [ E('p', r.servers.length ? 'Добавлено серверов: ' + r.servers.length +
'. Проверь имена и нажми «Сохранить и применить».' : 'Серверов не нашёл.') ]; '. Проверь имена и нажми «Сохранить и применить».' : 'Серверов не нашёл.') ];
@ -1021,19 +699,11 @@ return view.extend({
field('x-hwid', f.hwid_id, 'если провайдер уже знает устройство — оставь тот же') field('x-hwid', f.hwid_id, 'если провайдер уже знает устройство — оставь тот же')
]); ]);
dom.content(ovpnBox, [ dom.content(ovpnBox, [
field('Файл .ovpn', f.ovpn, cfg.ovpn_file ? 'загружен; выбери файл, только чтобы заменить' field('Файл .ovpn', f.ovpn, cfg.ovpn_file ? 'загружен; выбери файл, только чтобы заменить' : 'ещё не загружен'),
: 'профиль, который выдал администратор VPN (для OpenVPN Connect или openvpn)'),
field('Логин', f.vpn_username), field('Логин', f.vpn_username),
field('Пароль', f.vpn_password, 'обычный пароль, без одноразового кода'), field('Пароль (без OTP)', f.vpn_password),
field('Сети через VPN', f.ovpn_routes, 'адреса, которые открываются только через VPN, CIDR через пробел. ' + field('TOTP-секрет', f.totp_secret),
'При загрузке .ovpn подставляются его строки route; остальной трафик идёт как обычно'), field('Адрес для проверки', f.ovpn_check_url, 'что открывает ручная проверка туннеля (кнопка «Проверить» в блоке OpenVPN, тест задержки в дашборде; с ядром не из kit — ещё и cron раз в ~10 минут). Сайт видит этот запрос, поэтому лучше страница, которую и так открываешь в браузере')
field('TOTP-секрет', f.totp_secret, 'только если VPN просит одноразовый код из приложения (Google Authenticator и т. п.): ' +
'секрет из QR-кода, строка из букв и цифр (secret=… в ссылке otpauth://). Роутер сам подставляет код при подключении'),
cfg.has_totp ? field('Без кода', f.totp_clear, 'забыть сохранённый секрет: VPN больше не просит код') : '',
field('Как отправлять код', f.pass_format, 'обычно подходит «сам»; если сервер не принимает код — попробуй другие'),
field('Адрес для проверки', f.ovpn_check_url, 'страница за VPN: её открывает кнопка «Проверить» в блоке OpenVPN ' +
'и тест задержки в дашборде (с ядром не из kit — ещё и роутер раз в ~10 минут). Сайт видит этот запрос, ' +
'поэтому лучше страница, которую и так открываешь')
]); ]);
dom.content(tsBox, [ dom.content(tsBox, [
field('Имя ноды', f.ts_hostname), field('Имя ноды', f.ts_hostname),
@ -1064,62 +734,9 @@ return view.extend({
errors.push('OpenVPN: нужен логин'); errors.push('OpenVPN: нужен логин');
if (!cfg.has_vpn_password && !f.vpn_password.value) if (!cfg.has_vpn_password && !f.vpn_password.value)
errors.push('OpenVPN: нужен пароль'); errors.push('OpenVPN: нужен пароль');
if (!f.ovpn_routes.value.trim()) if (!cfg.has_totp && !f.totp_secret.value.trim())
errors.push('OpenVPN: укажи сети, которые идут через VPN'); errors.push('OpenVPN: нужен TOTP-секрет');
f.ovpn_routes.value.split(/\s+/).filter(Boolean).forEach(function(n) {
if (!/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/.test(n))
errors.push('OpenVPN: сеть ' + n + ' — не IPv4-адрес или CIDR');
});
if (f.totp_secret.value.trim() && !/^[A-Za-z2-7=\s-]+$/.test(f.totp_secret.value))
errors.push('OpenVPN: TOTP-секрет — буквы A–Z и цифры 2–7 (base32)');
} }
var poolNames = {}, taken = /^(boot|boot-auto|ru|foreign|torrent|torrent-sel|my|my-exit|main|push|uplink|tailscale|ts-exit|ovpn-exit|csqtt|direct|reject|reject-drop|pass|compatible|global|openvpn)$/;
var poolData = pools.map(function(e) {
return { name: e.name.value.trim().toLowerCase(), type: e.type.value,
servers: e.srv.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join('; '),
subs: e.subs.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join(' '),
filter: e.filter.value.trim(), exclude: e.exclude.value.trim(), uplink: e.uplink.checked ? '1' : '' };
});
poolData.forEach(function(v) {
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
errors.push('Пул «' + v.name + '»: имя — латиница, цифры, _ и -');
else if (poolNames[v.name])
errors.push('Пул «' + v.name + '» повторяется');
else if (taken.test(v.name))
errors.push('Пул «' + v.name + '»: такая группа уже есть, возьми другое имя');
poolNames[v.name] = true;
if (!v.servers && !v.subs)
errors.push('Пул «' + v.name + '»: отметь свои серверы или подписки');
});
var svcNames = {};
var svcData = services.map(function(e) {
return { name: e.name.value.trim().toLowerCase(), via: e.via.value, chain: e.chain.value, geosite: e.geosite.value.trim(),
domains: e.domains.value.trim(), ips: e.ips.value.trim(), hostlist: e.hostlist.value.trim(), server: e.server.value.trim(), provider: e.server.value.trim() ? e.provider.value.trim() : '' };
});
svcData.forEach(function(v) {
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
errors.push('Сервис «' + v.name + '»: имя — латиница, цифры, _ и -');
else if (svcNames[v.name])
errors.push('Сервис «' + v.name + '» повторяется');
else if (taken.test(v.name) || poolNames[v.name])
errors.push('Сервис «' + v.name + '»: такая группа уже есть, возьми другое имя');
svcNames[v.name] = true;
if (!v.geosite && !v.domains && !v.ips && !v.hostlist)
errors.push('Сервис «' + v.name + '»: нужен geosite, домены, IP или список доменов');
var builtin = /^(MY|FOREIGN|RU|DIRECT|MAIN|MY-EXIT)$/;
if (!v.server && !builtin.test(v.via) && !poolNames[v.via.toLowerCase()])
errors.push('Сервис «' + v.name + '»: пула ' + v.via + ' больше нет');
if (v.chain && !builtin.test(v.chain) && !poolNames[v.chain.toLowerCase()])
errors.push('Сервис «' + v.name + '»: пула ' + v.chain + ' (вход) больше нет');
if (v.chain && !v.server && v.via != 'MY' && !poolNames[v.via.toLowerCase()])
errors.push('Сервис «' + v.name + '»: вход — только когда выход через MY или пул');
else if (v.chain && !v.server && v.chain == v.via)
errors.push('Сервис «' + v.name + '»: вход и выход — одно и то же');
});
f.bypass_clients.value.split(/\s+/).filter(Boolean).forEach(function(c) {
if (!/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/.test(c) && !/^[0-9a-f]{2}([:-][0-9a-f]{2}){5}$/i.test(c))
errors.push('Клиенты мимо mihomo: ' + c + ' — не IPv4-адрес, подсеть или MAC');
});
if (f.lite_gomemlimit.value.trim() && !/^[1-9][0-9]*(B|KiB|MiB|GiB)?$/.test(f.lite_gomemlimit.value.trim())) if (f.lite_gomemlimit.value.trim() && !/^[1-9][0-9]*(B|KiB|MiB|GiB)?$/.test(f.lite_gomemlimit.value.trim()))
errors.push('Лимит памяти: число с единицей, например 64MiB'); errors.push('Лимит памяти: число с единицей, например 64MiB');
var names = {}, srvLines = []; var names = {}, srvLines = [];
@ -1134,25 +751,8 @@ return view.extend({
errors.push('Свой сервер ' + n + ': ' + e.error); errors.push('Свой сервер ' + n + ': ' + e.error);
else if (e.proxy.server === undefined || e.proxy.server === null || e.proxy.server === '') else if (e.proxy.server === undefined || e.proxy.server === null || e.proxy.server === '')
errors.push('Свой сервер ' + n + ': пустой server (открой «Настройки (YAML)»)'); errors.push('Свой сервер ' + n + ': пустой server (открой «Настройки (YAML)»)');
// the entry: a pool that exists and does not hold the server itself (a loop)
var en = e.entry.value, ep = poolData.filter(function(v) { return v.name.toUpperCase() == en; })[0];
if (en && !/^(FOREIGN|RU|DIRECT)$/.test(en) && !ep)
errors.push('Свой сервер ' + n + ': вход через пул ' + en + ', а такого пула нет');
else if (ep && ep.servers.split(';').map(function(x) { return x.trim(); }).indexOf(n) >= 0)
errors.push('Свой сервер ' + n + ': вход через пул ' + en + ', в который он сам входит — так нельзя');
srvLines.push(S.toLine(e.get())); srvLines.push(S.toLine(e.get()));
}); });
var nodeLines = [];
myNodes.forEach(function(n) {
var en = n.entry.value, ep = poolData.filter(function(v) { return v.name.toUpperCase() == en; })[0];
if (!en)
return;
if (!/^(FOREIGN|RU|DIRECT)$/.test(en) && !ep)
errors.push('Нода ' + n.name + ': вход через пул ' + en + ', а такого пула нет');
else if (ep && ep.subs.split(/\s+/).indexOf(n.provider) >= 0)
errors.push('Нода ' + n.name + ': вход через пул ' + en + ', который сам берёт ноды ' + n.provider + ' — так нельзя');
nodeLines.push(en + '|' + n.provider + '|' + n.name);
});
if (errors.length) { if (errors.length) {
ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger'); ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger');
return; return;
@ -1172,7 +772,6 @@ return view.extend({
foreign_domains: f.foreign_domains.value.trim(), foreign_domains: f.foreign_domains.value.trim(),
my_domains: f.my_domains.value.trim(), my_domains: f.my_domains.value.trim(),
local_hosts: f.local_hosts.value.trim(), local_hosts: f.local_hosts.value.trim(),
bypass_clients: f.bypass_clients.value.trim(),
my_links: '', my_links: '',
openvpn: f.openvpn.checked, openvpn: f.openvpn.checked,
csqtt: f.csqtt.checked, csqtt: f.csqtt.checked,
@ -1180,9 +779,6 @@ return view.extend({
vpn_username: f.vpn_username.value.trim(), vpn_username: f.vpn_username.value.trim(),
vpn_password: f.vpn_password.value, vpn_password: f.vpn_password.value,
totp_secret: f.totp_secret.value.replace(/\s+/g, ''), totp_secret: f.totp_secret.value.replace(/\s+/g, ''),
totp_clear: f.totp_clear.checked,
pass_format: f.pass_format.value,
ovpn_routes: f.ovpn_routes.value.trim(),
tailscale: f.tailscale.checked, tailscale: f.tailscale.checked,
ts_hostname: f.ts_hostname.value.trim(), ts_hostname: f.ts_hostname.value.trim(),
ts_domains: f.ts_domains.value.trim(), ts_domains: f.ts_domains.value.trim(),
@ -1192,10 +788,7 @@ return view.extend({
lite: f.lite.checked, lite: f.lite.checked,
lite_gomemlimit: f.lite_gomemlimit.value.trim(), lite_gomemlimit: f.lite_gomemlimit.value.trim(),
hy2: [], hy2: [],
services: svcData, servers_text: srvLines.join('\n')
pools: poolData,
servers_text: srvLines.join('\n'),
my_node_entries: nodeLines.join('\n')
}); });
}, this)).then(L.bind(function(r) { }, this)).then(L.bind(function(r) {
if (r.error) { if (r.error) {
@ -1204,16 +797,14 @@ return view.extend({
} }
return this.follow().then(L.bind(function(j) { return this.follow().then(L.bind(function(j) {
if (j && j.rc === 0) if (j && j.rc === 0)
return this.renderSettingsBox(); return this.renderSettingsBox(false);
}, this)); }, this));
}, this)); }, this));
}) })
}, 'Сохранить и применить'); }, 'Сохранить и применить');
var put = L.bind(function(tab, children) { dom.content(this.settingsBox, [
dom.content(this.slots[tab].settings, section('Настройки', children)); E('h3', 'Настройка'),
}, this);
put('subs', [
field('BOOT', f.boot, 'vless-ссылки seed-нод, по одной на строку: группа BOOT берёт первую живую, ' + field('BOOT', f.boot, 'vless-ссылки seed-нод, по одной на строку: группа BOOT берёт первую живую, ' +
'через неё качаются подписки; пусто — без BOOT. Подписки по умолчанию качаются через BOOT-AUTO: ' + 'через неё качаются подписки; пусто — без BOOT. Подписки по умолчанию качаются через BOOT-AUTO: ' +
'BOOT, иначе ноды уже скачанных подписок (FOREIGN), иначе напрямую'), 'BOOT, иначе ноды уже скачанных подписок (FOREIGN), иначе напрямую'),
@ -1222,82 +813,41 @@ return view.extend({
'click': function() { addSub({}); update(); } 'click': function() { addSub({}); update(); }
}, 'Добавить подписку') ], 'Имя провайдера берётся из домена (sub.kittyvpn.com → kittyvpn), ' + }, 'Добавить подписку') ], 'Имя провайдера берётся из домена (sub.kittyvpn.com → kittyvpn), ' +
'настройки привязаны к нему; задать своё: имя=https://…. HWID — для подписок с лимитом устройств.'), 'настройки привязаны к нему; задать своё: имя=https://…. HWID — для подписок с лимитом устройств.'),
hwidBox hwidBox,
]); field('Торренты', f.torrent, 'через TORRENT-SEL (порты 20000-20199)'),
put('ovpn', [ field('Обход для пушей', f.push, 'Apple APNs и Google FCM через группу PUSH (main/foreign — DIRECT, whitelist — MY): ' +
field('Включить OpenVPN', f.openvpn, 'доступ к рабочей или учебной сети по файлу .ovpn, с одноразовыми кодами (TOTP) или без. ' + 'уведомления не рвутся при смене ноды; выключено — пуши идут по общим правилам'),
'Через VPN идут только указанные сети, остальное — как обычно'), field('OpenVPN BMSTU', f.openvpn),
ovpnBox ovpnBox,
]); field('CSQTT', f.csqtt, 'интерфейс csqtt0 от star-panel-csqtt (Службы → star-panel-csqtt). Группа UPLINK в дашборде: ' +
put('csqtt', [
field('Включить CSQTT', f.csqtt, 'интерфейс csqtt0 от star-panel-csqtt (Службы → star-panel-csqtt). Группа UPLINK в дашборде: ' +
'DIRECT — как раньше, CSQTT — ноды подписок, BOOT и свои серверы подключаются через csqtt0 ' + 'DIRECT — как раньше, CSQTT — ноды подписок, BOOT и свои серверы подключаются через csqtt0 ' +
'(выход из белых списков), а MAIN/FOREIGN/MY работают поверх') '(выход из белых списков), а MAIN/FOREIGN/MY работают поверх'),
]); field('Tailscale', f.tailscale),
put('ts', [ tsBox,
field('Включить Tailscale', f.tailscale, 'доступ к своей сети Tailscale (tailnet) со всех устройств за роутером'),
tsBox
]);
put('system', [
field('Облегчённый режим', f.lite, 'для роутеров с 256 МБ памяти: лимит памяти ядра (GOMEMLIMIT), ' + field('Облегчённый режим', f.lite, 'для роутеров с 256 МБ памяти: лимит памяти ядра (GOMEMLIMIT), ' +
'проверки нод раз в 10 минут и только при трафике, сниффер без QUIC, лог nikki — warning, без поиска процессов ' + 'проверки нод раз в 10 минут и только при трафике, сниффер без QUIC, лог nikki — warning, без поиска процессов ' +
'(кроме CSQTT), перехват без TUN (TCP redirect, UDP tproxy). Что ещё ест память, kit напишет в журнале применения'), '(кроме CSQTT), перехват без TUN (TCP redirect, UDP tproxy). Что ещё ест память, kit напишет в журнале применения'),
field('Лимит памяти', f.lite_gomemlimit, 'GOMEMLIMIT для облегчённого режима, по умолчанию 64MiB; ' + field('Лимит памяти', f.lite_gomemlimit, 'GOMEMLIMIT для облегчённого режима, по умолчанию 64MiB; ' +
'слишком низкий — ядро постоянно чистит память и грузит процессор') 'слишком низкий — ядро постоянно чистит память и грузит процессор'),
]); field('Конфиг для телефона', f.mobile, 'FlClash: QR и ссылка появятся на этой странице после сохранения ' +
put('phone', [ '(файл раздаётся роутером внутри LAN по ссылке со случайным токеном)'),
field('Конфиг для телефона', f.mobile, 'тот же обход в приложении на телефоне или компьютере (FlClash, Clash Mi и др.): ' +
'QR и ссылка появятся на этой вкладке после сохранения. Файл раздаёт роутер, только в своей сети')
]);
put('pools', [
E('h4', 'Пулы'),
E('p', { 'class': 'cbi-value-description' }, 'Свои наборы серверов: свои серверы галками и ноды подписок по фильтру. ' +
'У каждого пула своя группа (имя заглавными, например DE); сервис можно пустить через пул — тогда его выход задан ' +
'настройками, одинаково на роутере и телефоне. Пустой пул (серверы переименованы, подписка выключена) закрывает ' +
'свои сервисы (REJECT), а не пускает их мимо.'),
poolList,
E('div', [ E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addPool({}); } }, 'Добавить пул') ]),
E('h4', 'Сервисы'),
E('p', { 'class': 'cbi-value-description' }, 'Сайт или приложение, которое всегда идёт своим путём, что бы ни было выбрано ' +
'в MAIN: своя группа в дашборде (имя заглавными, например CLAUDE), правила выше «Своих правил». Через свои серверы — ' +
'первый живой, а не самый быстрый: выходной IP не скачет между странами, пока сервер жив (в дашборде можно ' +
'выбрать другой). На whitelist и телефоне к своим серверам — через MY-EXIT, как обычно. Есть и в конфиге телефона.'),
svcList,
E('div', [
E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addService({}); } }, 'Добавить сервис'), ' ',
E('button', { 'class': 'btn cbi-button', 'click': function() {
if (!services.some(function(e) { return e.name.value.trim().toLowerCase() == 'claude'; }))
addService({ name: 'claude', geosite: 'anthropic', via: 'MY' });
} }, '+ Claude')
])
]);
put('rules', [
field('Торренты', f.torrent, 'через TORRENT-SEL (порты 20000-20199)'),
field('Обход для пушей', f.push, 'Apple APNs и Google FCM через группу PUSH (main/foreign — DIRECT, whitelist — MY): ' +
'уведомления не рвутся при смене ноды; выключено — пуши идут по общим правилам'),
E('h4', 'Свои правила'), E('h4', 'Свои правила'),
E('p', { 'class': 'cbi-value-description' }, 'Через пробел. Выше торрентов, ru-inside, .ru и MAIN (ниже только ' + E('p', { 'class': 'cbi-value-description' }, 'Через пробел. Выше торрентов, ru-inside, .ru и MAIN (ниже только ' +
'Tailscale, OpenVPN, локальная сеть, пуши и сервисы). Домен действует вместе с поддоменами (example.com = *.example.com), ' + 'Tailscale, OpenVPN, локальная сеть и пуши). Домен действует вместе с поддоменами (example.com = *.example.com), ' +
'IP без маски = /32. Если адрес попал в несколько списков — побеждает MY, затем FOREIGN, затем RU.'), 'IP без маски = /32. Если адрес попал в несколько списков — побеждает MY, затем FOREIGN, затем RU.'),
field('Домены через RU', f.ru_domains, 'на main (свой белый IP) идут напрямую'), field('Домены через RU', f.ru_domains, 'на main (свой белый IP) идут напрямую'),
field('Домены через FOREIGN', f.foreign_domains), field('Домены через FOREIGN', f.foreign_domains),
field('Домены через MY', f.my_domains, 'свои серверы (вкладка «Свои серверы») и [MY] из подписок'), field('Домены через MY', f.my_domains, 'свои серверы: ниже и [MY] из подписок'),
field('Доп. IP через RU', f.ru_ips, 'на main (свой белый IP) идут напрямую'), field('Доп. IP через RU', f.ru_ips, 'на main (свой белый IP) идут напрямую'),
field('Доп. IP через FOREIGN', f.foreign_ips), field('Доп. IP через FOREIGN', f.foreign_ips),
field('Доп. IP через MY', f.my_ips, 'свои серверы (вкладка «Свои серверы») и [MY] из подписок'), field('Доп. IP через MY', f.my_ips, 'свои серверы: ниже и [MY] из подписок'),
field('Локальные адреса', f.local_hosts, 'домен=IP в локальной сети (с поддоменами): роутер и клиенты ' + field('Локальные адреса', f.local_hosts, 'домен=IP в локальной сети (с поддоменами): роутер и клиенты ' +
'ходят к серверу напрямую по LAN, а не через белый IP и обратно. Только для этого роутера (не телефон, ' + 'ходят к серверу напрямую по LAN, а не через белый IP и обратно. Только для этого роутера (не телефон, ' +
'при импорте не переносится)'), 'при импорте не переносится)'),
field('Клиенты мимо mihomo', f.bypass_clients, 'IP-адреса (или подсети) и MAC-адреса устройств в локальной сети ' + E('h4', 'Свои серверы'),
'через пробел: их трафик и DNS идут напрямую, без обхода. Например, второй роутер со своим kit за этим — иначе ' +
'его трафик дважды идёт через прокси. MAC надёжнее: IP может смениться (или закрепи IP в Сеть → DHCP и DNS). ' +
'Только для этого роутера')
]);
put('servers', [
E('p', { 'class': 'cbi-value-description' }, 'Собираются в группу MY (автовыбор самого быстрого, в дашборде можно закрепить один). MY — пункт в MAIN ' + E('p', { 'class': 'cbi-value-description' }, 'Собираются в группу MY (автовыбор самого быстрого, в дашборде можно закрепить один). MY — пункт в MAIN ' +
'рядом с FOREIGN. К самим серверам на whitelist и с телефона — через MY-EXIT, на main — напрямую. Ссылки ' + 'рядом с FOREIGN. К самим серверам на whitelist и с телефона — через MY-EXIT, на main — напрямую. Ссылки ' +
'vless / vmess / trojan / ss / hysteria2 / tuic / anytls и YAML разбираются так же, как в mihomo; ключ ' + 'vless / vmess / trojan / ss / hysteria2 / tuic / anytls и YAML разбираются так же, как в mihomo; серверы ' +
'AmneziaVPN (vpn://) и .conf AmneziaWG / WireGuard становятся сервером wireguard; серверы ' +
'попадают и в конфиг телефона. Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY.'), 'попадают и в конфиг телефона. Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY.'),
moved ? E('p', { 'class': 'alert-message warning' }, 'Перенесено из старых настроек (hysteria2 по полям, ссылки): ' + moved ? E('p', { 'class': 'alert-message warning' }, 'Перенесено из старых настроек (hysteria2 по полям, ссылки): ' +
moved + '. Нажми «Сохранить и применить», чтобы сохранить их в новом виде.') : '', moved + '. Нажми «Сохранить и применить», чтобы сохранить их в новом виде.') : '',
@ -1311,15 +861,8 @@ return view.extend({
addServer({ name: 'new', type: 'hysteria2', server: '', port: 443, password: '' }, true); addServer({ name: 'new', type: 'hysteria2', server: '', port: 443, password: '' }, true);
} }, 'Добавить вручную') } }, 'Добавить вручную')
]), ]),
E('h4', 'Из подписок ([MY])'), E('div', { 'class': 'cbi-page-actions' }, [ save ])
E('p', { 'class': 'cbi-value-description' }, 'Серверы, которые ты держишь в своей подписке с [MY] в имени: их настройки ' +
'приходят из подписки, но вход можно задать здесь — для каждого отдельно, как у своих серверов выше. ' +
'Нода ищется по точному имени: если в подписке её переименуют, вход перестанет действовать.'),
myNodeBox
]); ]);
// one button for every tab: the settings are saved and applied together
dom.content(this.saveBox, E('div', { 'class': 'cbi-page-actions' }, [
E('span', { 'class': 'cbi-value-description', 'style': 'margin-right:1em' }, 'сохраняет настройки всех вкладок'), save ]));
}, },
importBox: function() { importBox: function() {
@ -1439,26 +982,19 @@ return view.extend({
render: function(data) { render: function(data) {
this.busy = false; this.busy = false;
this.buttons = []; this.buttons = [];
// each tab: its live state and buttons (renderBody), then its settings (renderSettings) this.body = E('div');
this.slots = {};
var tabList = [ [ 'overview', 'Обзор' ], [ 'subs', 'Подписки' ], [ 'rules', 'Правила' ], [ 'servers', 'Свои серверы' ],
[ 'pools', 'Пулы и сервисы' ], [ 'ovpn', 'OpenVPN' ], [ 'ts', 'Tailscale' ], [ 'csqtt', 'CSQTT' ],
[ 'phone', 'Телефон' ], [ 'system', 'Система' ] ].map(function(t) {
var slot = this.slots[t[0]] = { status: E('div'), settings: E('div') };
return [ t[0], t[1], E('div', [ slot.status, slot.settings ]) ];
}, this);
this.jobTitle = E('h3'); this.jobTitle = E('h3');
this.jobLink = E('div'); this.jobLink = E('div');
this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' }); this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' });
this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLink, this.jobLog ]); this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLink, this.jobLog ]);
this.saveBox = E('div'); this.settingsBox = E('div', { 'class': 'cbi-section' });
this.renderSettingsBox(); this.renderSettingsBox(!data[0].configured);
this.renderBody(data[0]); this.renderBody(data[0]);
this.showJob(data[1]); this.showJob(data[1]);
if (data[1].running) if (data[1].running)
this.follow(); this.follow();
return E([], [ E('h2', 'mihomo-kit'), tabs(tabList, 'mihomo-kit-tab'), this.saveBox, this.jobBox ]); return E([], [ E('h2', 'mihomo-kit'), this.body, this.settingsBox, this.jobBox ]);
} }
}); });

View File

@ -3,8 +3,8 @@
# #
# status profile, nikki running, which features are on, kit version, # status profile, nikki running, which features are on, kit version,
# mihomo API port/secret (dashboard link) # mihomo API port/secret (dashboard link)
# ovpn_status OpenVPN state (ovpn.sh state: mode, schedule, tunnel from the core, # ovpn_status OpenVPN state (bmstu-otp.sh state: mode, schedule, tunnel from the core,
# no traffic) + the current one-time code (with TOTP) # no traffic) + current OTP
# ovpn_probe delay to OVPN_CHECK_URL through the tunnel (a request the site can log) # ovpn_probe delay to OVPN_CHECK_URL through the tunnel (a request the site can log)
# csqtt_status CSQTT state (mihomo-kit.sh csqtt state: csqtt status + group UPLINK) # csqtt_status CSQTT state (mihomo-kit.sh csqtt state: csqtt status + group UPLINK)
# run start a whitelisted command as the background job # run start a whitelisted command as the background job
@ -15,15 +15,6 @@
# import {data, keep_local}: replace the settings with an export, as the job # import {data, keep_local}: replace the settings with an export, as the job
# config_get settings for the form (secrets: only whether they are set) # config_get settings for the form (secrets: only whether they are set)
# config_set save the form (via "mihomo-kit.sh configure") as the job # config_set save the form (via "mihomo-kit.sh configure") as the job
# graph {profile}: the built profile's YAML for the graph page (default: the running one)
# and the services and pools of the settings (+ servers, subs: what a pool can take;
# hostlists: the zapret lists a service can take)
# api {path}: GET /proxies, /connections or /providers/proxies of the mihomo API
# services_set {services: [{name, geosite, domains, ips, via, chain, server, provider, hostlist}], pools: [{name, type, servers,
# subs, filter, exclude, uplink}]}: replace the services and pools ("mihomo-kit.sh services")
# as the job
# group {group, action, name, url}: select (pick / pin name), unfix (back to automatic),
# delay (test every member against url) - the graph page, through the mihomo API
# #
# rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job. # rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job.
@ -49,7 +40,7 @@ q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; } job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; }
# mihomo API base URL from nikki's mixin settings (as in ovpn.sh) # mihomo API base URL from nikki's mixin settings (as in bmstu-otp.sh)
api_url() { api_url() {
l=$(uci -q get nikki.mixin.api_listen) l=$(uci -q get nikki.mixin.api_listen)
port=${l##*:} host=${l%:*} port=${l##*:} host=${l%:*}
@ -138,9 +129,9 @@ delay_check() {
m_ovpn_status() { m_ovpn_status() {
json_init json_init
# what decides the tunnel now and the next change (ovpn.sh state); only # what decides the tunnel now and the next change (bmstu-otp.sh state); only
# known keys with plain values get through to eval # known keys with plain values get through to eval
eval "$(ovpn.sh state 2>/dev/null | eval "$(bmstu-otp.sh state 2>/dev/null |
sed -En -e 's/^(mode|want|tunnel|link|up_since|up_hm|up_day|retry_hm|retry_why|until|until_hm|until_day|after|why|next|next_to|next_hm|next_day|win|sched|sched_active|timer_max|sched_start|sched_end|sched_days|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p' \ sed -En -e 's/^(mode|want|tunnel|link|up_since|up_hm|up_day|retry_hm|retry_why|until|until_hm|until_day|after|why|next|next_to|next_hm|next_day|win|sched|sched_active|timer_max|sched_start|sched_end|sched_days|jitter)=([A-Za-z0-9:._-]*)$/st_\1=\2/p' \
-e "s/^err='([^'\`\$\\\\]*)'\$/st_err='\\1'/p")" -e "s/^err='([^'\`\$\\\\]*)'\$/st_err='\\1'/p")"
for k in mode tunnel link up_hm up_day retry_hm retry_why err until_hm until_day after why next_to next_hm next_day win sched_start sched_end sched_days; do for k in mode tunnel link up_hm up_day retry_hm retry_why err until_hm until_day after why next_to next_hm next_day win sched_start sched_end sched_days; do
@ -149,7 +140,7 @@ m_ovpn_status() {
for k in want up_since until next sched sched_active timer_max jitter; do for k in want up_since until next sched sched_active timer_max jitter; do
eval "json_add_int $k \"\${st_$k:-0}\"" eval "json_add_int $k \"\${st_$k:-0}\""
done done
json_add_string otp "$(ovpn.sh otp 2>/dev/null)" json_add_string otp "$(bmstu-otp.sh otp 2>/dev/null)"
json_add_int otp_left "$((30 - $(date +%s) % 30))" json_add_int otp_left "$((30 - $(date +%s) % 30))"
json_dump json_dump
} }
@ -174,7 +165,7 @@ m_ovpn_probe() {
prof=$(uci -q get nikki.config.profile) prof=$(uci -q get nikki.config.profile)
prof=${prof#file:} prof=${prof#file:}
group=$(envval OVPN_GROUP "${prof%.yaml}") group=$(envval OVPN_GROUP "${prof%.yaml}")
delay_check "${group:-OPENVPN}" OVPN_CHECK_URL https://www.gstatic.com/generate_204 delay_check "${group:-BMSTU}" OVPN_CHECK_URL https://eu.bmstu.ru
json_dump json_dump
} }
@ -183,14 +174,14 @@ m_run() {
cmd=$(jsonfilter -s "$input" -e '@.cmd' 2>/dev/null) cmd=$(jsonfilter -s "$input" -e '@.cmd' 2>/dev/null)
arg=$(jsonfilter -s "$input" -e '@.arg' 2>/dev/null) arg=$(jsonfilter -s "$input" -e '@.arg' 2>/dev/null)
case "$cmd" in case "$cmd" in
ovpn-on) set -- ovpn.sh on ;; ovpn-on) set -- bmstu-otp.sh on ;;
ovpn-off) set -- ovpn.sh off ;; ovpn-off) set -- bmstu-otp.sh off ;;
ovpn-refresh) set -- ovpn.sh refresh ;; ovpn-refresh) set -- bmstu-otp.sh refresh ;;
ovpn-for | ovpn-extend) ovpn-for | ovpn-extend)
case "$arg" in '' | *[!0-9]* | 0) reply_error "bad minutes" ;; esac case "$arg" in '' | *[!0-9]* | 0) reply_error "bad minutes" ;; esac
set -- ovpn.sh "${cmd#ovpn-}" "$arg" set -- bmstu-otp.sh "${cmd#ovpn-}" "$arg"
;; ;;
ovpn-stop) set -- ovpn.sh stop ;; ovpn-stop) set -- bmstu-otp.sh stop ;;
ovpn-sched) ovpn-sched)
# arg: "off" | "on" | "HH:MM HH:MM [DAYS]" (DAYS: digits 1..7); unquoted below to split # arg: "off" | "on" | "HH:MM HH:MM [DAYS]" (DAYS: digits 1..7); unquoted below to split
case "$arg" in case "$arg" in
@ -200,7 +191,7 @@ m_run() {
;; ;;
*) reply_error "bad schedule" ;; *) reply_error "bad schedule" ;;
esac esac
set -- ovpn.sh sched $arg set -- bmstu-otp.sh sched $arg
;; ;;
use) use)
case "$arg" in '' | *[!A-Za-z0-9_-]*) reply_error "bad profile name" ;; esac case "$arg" in '' | *[!A-Za-z0-9_-]*) reply_error "bad profile name" ;; esac
@ -243,7 +234,7 @@ start_job() {
m_config_get() { m_config_get() {
[ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env" [ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env"
[ -f "$NIKKI_DIR/openvpn.env" ] && . "$NIKKI_DIR/openvpn.env" [ -f "$NIKKI_DIR/bmstu.env" ] && . "$NIKKI_DIR/bmstu.env"
[ -f /etc/openwrt_release ] && . /etc/openwrt_release [ -f /etc/openwrt_release ] && . /etc/openwrt_release
json_init json_init
json_add_boolean configured "$(b test -f "$PROFILES_D/common.env")" json_add_boolean configured "$(b test -f "$PROFILES_D/common.env")"
@ -283,9 +274,8 @@ m_config_get() {
json_add_string hwid_os_ver "${HWID_OS_VER:-${DISTRIB_RELEASE:-}}" json_add_string hwid_os_ver "${HWID_OS_VER:-${DISTRIB_RELEASE:-}}"
json_add_string hwid_model "${HWID_MODEL:-$(cat /tmp/sysinfo/model 2>/dev/null)}" json_add_string hwid_model "${HWID_MODEL:-$(cat /tmp/sysinfo/model 2>/dev/null)}"
json_add_string hwid_id "${HWID_ID:-$(md5sum < /sys/class/net/br-lan/address 2>/dev/null | cut -c1-16)}" json_add_string hwid_id "${HWID_ID:-$(md5sum < /sys/class/net/br-lan/address 2>/dev/null | cut -c1-16)}"
# a new router: torrents and push off, the phone config on json_add_boolean torrent "${TORRENT:-1}"
json_add_boolean torrent "${TORRENT:-0}" json_add_boolean push "${PUSH:-1}"
json_add_boolean push "${PUSH:-0}"
json_add_string ru_ips "${RU_IPS:-}" json_add_string ru_ips "${RU_IPS:-}"
json_add_string foreign_ips "${FOREIGN_IPS:-}" json_add_string foreign_ips "${FOREIGN_IPS:-}"
json_add_string my_ips "${MY_IPS:-}" json_add_string my_ips "${MY_IPS:-}"
@ -293,19 +283,6 @@ m_config_get() {
json_add_string foreign_domains "${FOREIGN_DOMAINS:-}" json_add_string foreign_domains "${FOREIGN_DOMAINS:-}"
json_add_string my_domains "${MY_DOMAINS:-}" json_add_string my_domains "${MY_DOMAINS:-}"
json_add_string local_hosts "${LOCAL_HOSTS:-}" json_add_string local_hosts "${LOCAL_HOSTS:-}"
json_add_string bypass_clients "${BYPASS_CLIENTS:-}"
# [MY] nodes of the subscriptions with an entry of their own: "<ENTRY>|<id>-my|<name>" lines
# (MY_NODE_1, MY_NODE_2, ... in common.env)
json_add_string my_node_entries "$(
_mk=1
while eval "[ -n \"\${MY_NODE_$_mk+x}\" ]"; do
eval "printf '%s\n' \"\$MY_NODE_$_mk\""
_mk=$((_mk + 1))
done
)"
blocks_json services "${SERVICES:-}" SVC geosite domains ips via chain server provider hostlist
blocks_json pools "${POOLS:-}" POOL type servers subs filter exclude uplink
hostlist_files
# own servers: one JSON proxy per line (luci/servers.js); the old hy2 / my_links # own servers: one JSON proxy per line (luci/servers.js); the old hy2 / my_links
# below are moved into it by the page on the next save # below are moved into it by the page on the next save
json_add_string servers_text "$(cat "$NIKKI_DIR/my-servers" 2>/dev/null)" json_add_string servers_text "$(cat "$NIKKI_DIR/my-servers" 2>/dev/null)"
@ -315,23 +292,16 @@ m_config_get() {
set +f set +f
json_add_boolean openvpn "${OPENVPN:-0}" json_add_boolean openvpn "${OPENVPN:-0}"
json_add_boolean csqtt "${CSQTT:-0}" json_add_boolean csqtt "${CSQTT:-0}"
json_add_boolean ovpn_file "$(b test -f "$NIKKI_DIR/openvpn.ovpn")" json_add_boolean ovpn_file "$(b test -f "$NIKKI_DIR/bmstu.ovpn")"
json_add_string ovpn_routes "${OVPN_ROUTES:-}"
json_add_string pass_format "${PASS_FORMAT:-auto}"
json_add_string vpn_username "${VPN_USERNAME:-}" json_add_string vpn_username "${VPN_USERNAME:-}"
json_add_boolean has_vpn_password "$(b test -n "${VPN_PASSWORD:-}")" json_add_boolean has_vpn_password "$(b test -n "${VPN_PASSWORD:-}")"
json_add_boolean has_totp "$(b test -n "${TOTP_SECRET:-}")" json_add_boolean has_totp "$(b test -n "${TOTP_SECRET:-}")"
json_add_boolean tailscale "${TAILSCALE:-0}" json_add_boolean tailscale "${TAILSCALE:-0}"
json_add_string ts_hostname "${TS_HOSTNAME:-$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo}" json_add_string ts_hostname "${TS_HOSTNAME:-$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo}"
json_add_string ts_domains "${TS_DOMAINS:-}" json_add_string ts_domains "${TS_DOMAINS:-}"
json_add_string ovpn_check_url "${OVPN_CHECK_URL:-}" json_add_string ovpn_check_url "${OVPN_CHECK_URL:-https://eu.bmstu.ru}"
json_add_string ts_check_url "${TS_CHECK_URL:-http://100.69.216.50:8080}" json_add_string ts_check_url "${TS_CHECK_URL:-http://100.69.216.50:8080}"
# common.env has MOBILE=1 only when on json_add_boolean mobile "${MOBILE:-0}"
if [ -f "$PROFILES_D/common.env" ]; then
json_add_boolean mobile "${MOBILE:-0}"
else
json_add_boolean mobile 1
fi
json_add_boolean lite "${LITE:-0}" json_add_boolean lite "${LITE:-0}"
json_add_string lite_gomemlimit "${LITE_GOMEMLIMIT:-}" json_add_string lite_gomemlimit "${LITE_GOMEMLIMIT:-}"
json_add_array hy2 json_add_array hy2
@ -351,10 +321,8 @@ m_config_get() {
# {"data": {boot_links (one per line), subs: [{url, via, hwid}], hwid_*, torrent, push, ru_ips, # {"data": {boot_links (one per line), subs: [{url, via, hwid}], hwid_*, torrent, push, ru_ips,
# foreign_ips, my_ips, ru_domains, foreign_domains, my_domains, local_hosts, my_links (one per line), # foreign_ips, my_ips, ru_domains, foreign_domains, my_domains, local_hosts, my_links (one per line),
# services: [{name, geosite, domains, ips, via, chain, server, provider, hostlist}], pools: [{name, type, servers, subs, filter, exclude, uplink}],
# servers_text (own servers, one JSON proxy per line: written to /etc/nikki/my-servers), # servers_text (own servers, one JSON proxy per line: written to /etc/nikki/my-servers),
# openvpn, csqtt, ovpn (file text, optional), vpn_username, vpn_password, totp_secret, # openvpn, csqtt, ovpn (file text, optional), vpn_username, vpn_password, totp_secret,
# totp_clear (1: no codes any more), pass_format, ovpn_routes (only from a page that has it),
# tailscale, ts_hostname, ts_domains, lite, lite_gomemlimit, hy2: [{name, server, port, password, # tailscale, ts_hostname, ts_domains, lite, lite_gomemlimit, hy2: [{name, server, port, password,
# obfs_password, sni, insecure, up, down}]}}; empty OpenVPN secrets keep the saved ones # obfs_password, sni, insecure, up, down}]}}; empty OpenVPN secrets keep the saved ones
m_config_set() { m_config_set() {
@ -363,8 +331,8 @@ m_config_set() {
job_running && reply_error "busy: $(cat "$JOB/cmd")" job_running && reply_error "busy: $(cat "$JOB/cmd")"
for v in boot_links hwid_ua hwid_os hwid_os_ver hwid_model hwid_id torrent push ru_ips foreign_ips my_ips \ for v in boot_links hwid_ua hwid_os hwid_os_ver hwid_model hwid_id torrent push ru_ips foreign_ips my_ips \
ru_domains foreign_domains my_domains local_hosts my_links openvpn csqtt ovpn \ ru_domains foreign_domains my_domains local_hosts my_links openvpn csqtt ovpn \
vpn_username vpn_password totp_secret totp_clear pass_format tailscale ts_hostname ts_domains ovpn_check_url \ vpn_username vpn_password totp_secret tailscale ts_hostname ts_domains ovpn_check_url ts_check_url mobile \
ts_check_url mobile lite lite_gomemlimit; do lite lite_gomemlimit; do
json_get_var "$v" "$v" "" json_get_var "$v" "$v" ""
done done
# own servers: only a page that sends them (an old cached one sends hy2 instead) # own servers: only a page that sends them (an old cached one sends hy2 instead)
@ -380,7 +348,7 @@ m_config_set() {
fi fi
if [ -n "$ovpn" ]; then if [ -n "$ovpn" ]; then
umask 077 umask 077
printf '%s\n' "$ovpn" > "$NIKKI_DIR/openvpn.ovpn.tmp" && mv "$NIKKI_DIR/openvpn.ovpn.tmp" "$NIKKI_DIR/openvpn.ovpn" printf '%s\n' "$ovpn" > "$NIKKI_DIR/bmstu.ovpn.tmp" && mv "$NIKKI_DIR/bmstu.ovpn.tmp" "$NIKKI_DIR/bmstu.ovpn"
fi fi
umask 077 umask 077
env=$(mktemp /tmp/mihomo-kit-form.XXXXXX) || reply_error "mktemp failed" env=$(mktemp /tmp/mihomo-kit-form.XXXXXX) || reply_error "mktemp failed"
@ -425,28 +393,7 @@ m_config_set() {
echo "CSQTT=$(q "${csqtt:-0}")" echo "CSQTT=$(q "${csqtt:-0}")"
echo "VPN_USERNAME=$(q "$vpn_username")" echo "VPN_USERNAME=$(q "$vpn_username")"
[ -n "$vpn_password" ] && echo "VPN_PASSWORD=$(q "$vpn_password")" [ -n "$vpn_password" ] && echo "VPN_PASSWORD=$(q "$vpn_password")"
if [ "$totp_clear" = 1 ]; then [ -n "$totp_secret" ] && echo "TOTP_SECRET=$(q "$totp_secret")"
echo "TOTP_SECRET=''"
elif [ -n "$totp_secret" ]; then
echo "TOTP_SECRET=$(q "$totp_secret")"
fi
case "$pass_format" in auto | scrv1 | otp-last | otp-first) echo "PASS_FORMAT=$pass_format" ;; esac
# an old cached page does not send these: the saved ones stay
json_get_type _bc bypass_clients
if [ -n "$_bc" ]; then
json_get_var bypass_clients bypass_clients ""
echo "BYPASS_CLIENTS=$(q "$(echo $bypass_clients)")"
fi
json_get_type _me my_node_entries
if [ -n "$_me" ]; then
json_get_var my_node_entries my_node_entries ""
echo "MY_NODE_ENTRIES=$(q "$my_node_entries")"
fi
json_get_type _rt ovpn_routes
if [ -n "$_rt" ]; then
json_get_var ovpn_routes ovpn_routes ""
echo "OVPN_ROUTES=$(q "$(echo $ovpn_routes)")"
fi
echo "TAILSCALE=$(q "${tailscale:-0}")" echo "TAILSCALE=$(q "${tailscale:-0}")"
echo "TS_HOSTNAME=$(q "$ts_hostname")" echo "TS_HOSTNAME=$(q "$ts_hostname")"
echo "TS_DOMAINS=$(q "$ts_domains")" echo "TS_DOMAINS=$(q "$ts_domains")"
@ -476,186 +423,11 @@ m_config_set() {
json_select .. json_select ..
fi fi
echo "HY2=$(q "$hy2")" echo "HY2=$(q "$hy2")"
blocks_env services SERVICES SVC geosite domains ips via chain server provider hostlist
blocks_env pools POOLS POOL type servers subs filter exclude uplink
} > "$env" } > "$env"
umask 022 umask 022
start_job mihomo-kit.sh configure "$env" start_job mihomo-kit.sh configure "$env"
} }
# blocks_json <array> <names> <key prefix> <fields...>: SERVICES / POOLS of the sourced
# settings as an array of {name, <field>...} (keys <prefix>_<NAME>_<FIELD>)
blocks_json() {
_arr=$1 _list=$2 _pre=$3
shift 3
json_add_array "$_arr"
for n in $_list; do
k=${_pre}_$(echo "$n" | tr 'a-z-' 'A-Z_')
json_add_object ""
json_add_string name "$n"
for v in "$@"; do
eval "val=\${${k}_$(echo "$v" | tr 'a-z' 'A-Z'):-}"
json_add_string "$v" "$val"
done
json_close_object
done
json_close_array
}
# blocks_env <array> <LIST key> <key prefix> <fields...>: the request's array as env lines
# (<prefix>_<NAME>_<FIELD>=..., then LIST=names); no such array in the request: no lines
blocks_env() {
_arr=$1 _var=$2 _pre=$3
shift 3
json_get_type _t "$_arr"
[ "$_t" = array ] || return 0
_names=
json_select "$_arr"
json_get_keys _keys
for _i in $_keys; do
json_select "$_i"
json_get_var name name ""
name=$(printf '%s' "$name" | tr -d ' \t\r\n')
if [ -n "$name" ]; then
_names="${_names:+$_names }$name"
K=${_pre}_$(echo "$name" | tr 'a-z-' 'A-Z_')
for v in "$@"; do
json_get_var val "$v" ""
[ -n "$val" ] && echo "${K}_$(echo "$v" | tr 'a-z' 'A-Z')=$(q "$val")"
done
fi
json_select ..
done
json_select ..
echo "$_var=$(q "$_names")"
}
# zapret hostlists a service can take (SVC_<NAME>_HOSTLIST): [{path, lines}] - the
# domain lists of zapret2 / zapret (not the exclude lists, not the IP sets)
hostlist_files() {
json_add_array hostlists
for f in /opt/zapret2/ipset/* /opt/zapret/ipset/*; do
[ -f "$f" ] || continue
case "${f##*/}" in *exclude*) continue ;; *host*.txt | *host*.txt.gz | *host*.lst) ;; *) continue ;; esac
json_add_object ""
json_add_string path "$f"
case "$f" in *.gz) n=$(gzip -dc "$f" 2>/dev/null | grep -c '^[^#]') ;; *) n=$(grep -c '^[^#]' "$f") ;; esac
json_add_int lines "${n:-0}"
json_close_object
done
json_close_array
}
# what a pool can take: own servers by name, providers of the subscriptions ("<id>", "<id>-my")
pool_sources() {
# not a pipe: json_add_* must run in this shell
json_add_array servers
grep -v '^[[:space:]]*$' "$NIKKI_DIR/my-servers" > /tmp/mihomo-kit-srv.$$ 2>/dev/null
while IFS= read -r l; do
json_add_string "" "$(jsonfilter -s "$l" -e '@.name')"
done < /tmp/mihomo-kit-srv.$$
rm -f /tmp/mihomo-kit-srv.$$
for n in ${HY2:-}; do json_add_string "" "$n"; done
json_close_array
json_add_array subs
SUBS=${SUBS:-} mihomo-kit.sh sub-ids > /tmp/mihomo-kit-ids.$$
while read -r id w; do
json_add_string "" "$id"
json_add_string "" "$id-my"
done < /tmp/mihomo-kit-ids.$$
rm -f /tmp/mihomo-kit-ids.$$
[ -n "${MY_LINKS:-}" ] && json_add_string "" my-links
json_close_array
}
m_graph() {
json_load "$(cat)"
json_get_var want profile ""
prof=$(uci -q get nikki.config.profile)
prof=${prof#file:}
prof=${prof%.yaml}
case "$want" in '' | *[!A-Za-z0-9_-]*) want=$prof ;; esac
[ -f "$NIKKI_DIR/profiles/$want.yaml" ] || reply_error "нет профиля $want (mihomo-kit.sh build)"
json_init
json_add_string running "$prof"
json_add_boolean active "$(b pidof mihomo)"
json_add_string profile "$want"
json_add_string yaml "$(cat "$NIKKI_DIR/profiles/$want.yaml")"
# the services and pools, as config_get gives them, and what a pool can take: the graph edits these
[ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env"
blocks_json services "${SERVICES:-}" SVC geosite domains ips via chain server provider hostlist
blocks_json pools "${POOLS:-}" POOL type servers subs filter exclude uplink
hostlist_files
pool_sources
json_dump
}
m_services_set() {
json_load "$(cat)"
job_running && reply_error "busy: $(cat "$JOB/cmd")"
umask 077
env=$(mktemp /tmp/mihomo-kit-svc.XXXXXX) || reply_error "mktemp failed"
{
blocks_env services SERVICES SVC geosite domains ips via chain server provider hostlist
blocks_env pools POOLS POOL type servers subs filter exclude uplink
} > "$env"
umask 022
start_job mihomo-kit.sh services "$env"
}
# the API's answer as it is: only these read-only paths
m_api() {
json_load "$(cat)"
json_get_var path path ""
case "$path" in /proxies | /connections | /providers/proxies) ;; *) reply_error "path not allowed" ;; esac
sec=$(uci -q get nikki.mixin.api_secret)
res=$(curl -fsS -m 10 ${sec:+-H "Authorization: Bearer $sec"} "$(api_url)$path" 2>&1) ||
reply_error "mihomo API: $res"
# connections without their metadata (flat, most of the size): the graph needs the
# rule and chains, and ubus has a limit on the answer
[ "$path" = /connections ] && res=$(printf '%s' "$res" | sed 's/"metadata":{[^}]*},//g')
printf '%s\n' "$res"
}
# api_call <curl args...>: the answer of the mihomo API, or reply_error with its message
api_call() {
sec=$(uci -q get nikki.mixin.api_secret)
out=$(curl -sS -m 25 -w '\n%{http_code}' ${sec:+-H "Authorization: Bearer $sec"} "$@" 2>&1) ||
reply_error "mihomo API: $out"
code=$(printf '%s' "$out" | tail -n 1)
body=$(printf '%s' "$out" | sed '$d')
case "$code" in 2??) ;; *) reply_error "mihomo API: $(jsonfilter -s "$body" -e '@.message' 2>/dev/null || echo "HTTP $code")" ;; esac
}
m_group() {
json_load "$(cat)"
json_get_vars group action name url
# the kit's group names; anything else would need escaping in the URL
case "$group" in '' | *[!A-Za-z0-9_.-]*) reply_error "bad group name" ;; esac
case "$action" in
select)
json_init
json_add_string name "$name"
api_call -X PUT -H 'Content-Type: application/json' -d "$(json_dump)" "$(api_url)/proxies/$group"
;;
unfix)
api_call -X DELETE "$(api_url)/proxies/$group"
;;
delay)
api_call -G --data-urlencode "url=${url:-https://www.gstatic.com/generate_204}" \
--data-urlencode timeout=5000 "$(api_url)/group/$group/delay"
# {"name": ms} of the members that answered
[ -n "$body" ] || body='{}'
printf '%s\n' "$body"
return
;;
*) reply_error "bad action" ;;
esac
json_init
json_add_boolean ok 1
json_dump
}
m_ts_check() { m_ts_check() {
json_init json_init
delay_check TAILSCALE TS_CHECK_URL http://100.69.216.50:8080 delay_check TAILSCALE TS_CHECK_URL http://100.69.216.50:8080
@ -708,7 +480,7 @@ m_job() {
case "$1" in case "$1" in
list) list)
echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true},"graph":{"profile":"str"},"api":{"path":"str"},"group":{"group":"str","action":"str","name":"str","url":"str"},"services_set":{"services":[],"pools":[]}}' echo '{"status":{},"ovpn_status":{},"ovpn_probe":{},"csqtt_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{},"export":{},"import":{"data":"str","keep_local":true}}'
;; ;;
call) call)
case "$2" in case "$2" in
@ -724,10 +496,6 @@ case "$1" in
ts_check) m_ts_check ;; ts_check) m_ts_check ;;
export) m_export ;; export) m_export ;;
import) m_import ;; import) m_import ;;
graph) m_graph ;;
api) m_api ;;
group) m_group ;;
services_set) m_services_set ;;
*) reply_error "unknown method" ;; *) reply_error "unknown method" ;;
esac esac
;; ;;

View File

@ -1,6 +1,5 @@
// Own servers of the kit (LuCI "Свои серверы"): share links, YAML, WireGuard / AmneziaWG // Own servers of the kit (LuCI "Свои серверы"): share links and YAML -> mihomo proxy
// .conf and AmneziaVPN keys (vpn://) -> mihomo proxy objects, and one stored line per // objects, and one stored line per server (/etc/nikki/my-servers, see mihomo-kit.sh).
// server (/etc/nikki/my-servers, see mihomo-kit.sh).
// parseLinks is a port of mihomo's common/convert (ConvertsV2Ray) so a link gives the // parseLinks is a port of mihomo's common/convert (ConvertsV2Ray) so a link gives the
// same proxy as in a subscription; tools/test.sh checks it against the Go converter. // same proxy as in a subscription; tools/test.sh checks it against the Go converter.
// Browser: a global "mkServers" (loaded like qrcode.js); node: module.exports. // Browser: a global "mkServers" (loaded like qrcode.js); node: module.exports.
@ -297,10 +296,6 @@
case 'ws': case 'ws':
case 'httpupgrade': case 'httpupgrade':
var ws = { path: query.get('path'), headers: { 'User-Agent': USER_AGENT, Host: query.get('host') } }; var ws = { path: query.get('path'), headers: { 'User-Agent': USER_AGENT, Host: query.get('host') } };
if (network == 'httpupgrade') {
proxy.network = 'ws';
ws['v2ray-http-upgrade'] = true;
}
if (query.get('ed')) { if (query.get('ed')) {
if (!/^[+-]?[0-9]+$/.test(query.get('ed'))) if (!/^[+-]?[0-9]+$/.test(query.get('ed')))
return 'bad WebSocket max early data size'; return 'bad WebSocket max early data size';
@ -599,13 +594,8 @@
var net = q.get('type').toLowerCase(); var net = q.get('type').toLowerCase();
if (net) if (net)
p.network = net; p.network = net;
if (net == 'ws' || net == 'httpupgrade') { if (net == 'ws')
p['ws-opts'] = { path: q.get('path'), headers: { 'User-Agent': USER_AGENT } }; p['ws-opts'] = { path: q.get('path'), headers: { 'User-Agent': USER_AGENT } };
if (net == 'httpupgrade') {
p.network = 'ws';
p['ws-opts']['v2ray-http-upgrade'] = true;
}
}
else if (net == 'grpc') else if (net == 'grpc')
p['grpc-opts'] = { 'grpc-service-name': q.get('serviceName') }; p['grpc-opts'] = { 'grpc-service-name': q.get('serviceName') };
p['client-fingerprint'] = q.get('fp') || 'chrome'; p['client-fingerprint'] = q.get('fp') || 'chrome';
@ -687,10 +677,6 @@
case 'ws': case 'ws':
case 'httpupgrade': case 'httpupgrade':
var wo = { path: '/' }, hd = {}; var wo = { path: '/' }, hd = {};
if (network == 'httpupgrade') {
p.network = 'ws';
wo['v2ray-http-upgrade'] = true;
}
if (host) if (host)
hd.Host = host; hd.Host = host;
if (path) { if (path) {
@ -1321,310 +1307,22 @@
return indent + scalar(v); return indent + scalar(v);
} }
// --- WireGuard / AmneziaWG: .conf files and AmneziaVPN keys (vpn://) -------------
// zlib inflate (RFC 1950/1951) as zlib's puff.c: byte array -> byte array, throws
var LBASE = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
131, 163, 195, 227, 258 ];
var LEXT = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 ];
var DBASE = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ];
var DEXT = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ];
var CLORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
// canonical Huffman code of the code lengths: count of codes per length, symbols in order
function huffman(lengths) {
var count = [], offs = [ 0, 0 ], sym = [], i;
for (i = 0; i < 16; i++)
count[i] = 0;
lengths.forEach(function (l) { count[l]++; });
for (i = 1; i < 15; i++)
offs[i + 1] = offs[i] + count[i];
lengths.forEach(function (l, s) {
if (l)
sym[offs[l]++] = s;
});
return { count: count, sym: sym };
}
function inflate(data) {
if (data.length < 2 || (data[0] & 0x0f) != 8 || ((data[0] << 8) | data[1]) % 31)
throw new Error('not zlib');
var pos = 2, bitbuf = 0, bitcnt = 0, out = [], fixed = null, i;
var bits = function (n) {
var v = bitbuf;
while (bitcnt < n) {
if (pos >= data.length)
throw new Error('truncated');
v |= data[pos++] << bitcnt;
bitcnt += 8;
}
bitbuf = v >>> n;
bitcnt -= n;
return v & ((1 << n) - 1);
};
var decode = function (h) {
for (var len = 1, code = 0, first = 0, index = 0; len < 16; len++) {
code |= bits(1);
if (code - h.count[len] < first)
return h.sym[index + code - first];
index += h.count[len];
first = (first + h.count[len]) << 1;
code <<= 1;
}
throw new Error('bad code');
};
var codes = function (lit, dist) {
for (;;) {
var s = decode(lit);
if (s < 256) {
out.push(s);
continue;
}
if (s == 256)
return;
if ((s -= 257) >= 29)
throw new Error('bad length');
var len = LBASE[s] + bits(LEXT[s]);
if ((s = decode(dist)) >= 30)
throw new Error('bad distance');
var d = DBASE[s] + bits(DEXT[s]);
if (d > out.length)
throw new Error('distance too far');
while (len--)
out.push(out[out.length - d]);
}
};
for (var last = 0; !last;) {
last = bits(1);
var type = bits(2);
if (type == 0) {
bitbuf = bitcnt = 0;
var n = data[pos] | data[pos + 1] << 8;
if (pos + 4 + n > data.length || (n ^ (data[pos + 2] | data[pos + 3] << 8)) != 0xffff)
throw new Error('bad stored block');
for (pos += 4; n--;)
out.push(data[pos++]);
} else if (type == 1) {
if (!fixed) {
var l = [];
for (i = 0; i < 288; i++)
l[i] = i < 144 ? 8 : i < 256 ? 9 : i < 280 ? 7 : 8;
fixed = [ huffman(l), huffman(l.slice(0, 30).map(function () { return 5; })) ];
}
codes(fixed[0], fixed[1]);
} else if (type == 2) {
var nlen = bits(5) + 257, ndist = bits(5) + 1, ncode = bits(4) + 4, lengths = [];
for (i = 0; i < 19; i++)
lengths[i] = 0;
for (i = 0; i < ncode; i++)
lengths[CLORDER[i]] = bits(3);
var lencode = huffman(lengths);
for (lengths = []; lengths.length < nlen + ndist;) {
var sym = decode(lencode), rep, prev = 0;
if (sym < 16) {
lengths.push(sym);
continue;
}
if (sym == 16) {
if (!lengths.length)
throw new Error('repeat with no length');
prev = lengths[lengths.length - 1];
rep = 3 + bits(2);
} else {
rep = sym == 17 ? 3 + bits(3) : 11 + bits(7);
}
while (rep--)
lengths.push(prev);
}
if (lengths.length > nlen + ndist)
throw new Error('too many lengths');
codes(huffman(lengths.slice(0, nlen)), huffman(lengths.slice(nlen)));
} else {
throw new Error('bad block type');
}
}
return out;
}
// AmneziaWG keys of [Interface] (lower case) -> amnezia-wg-option of mihomo
var AWG = { jc: 'jc', jmin: 'jmin', jmax: 'jmax', s1: 's1', s2: 's2', s3: 's3', s4: 's4',
h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', i1: 'i1', i2: 'i2', i3: 'i3', i4: 'i4', i5: 'i5',
j1: 'j1', j2: 'j2', j3: 'j3', itime: 'itime' };
// AmneziaWG 3: mihomo needs "version: 3" with them
var AWG3 = { headerprotectionkey: 'header-protection-key', contentpaddingaddition: 'content-padding-addition',
rekeyaftertime: 'rekey-after-time', rekeytimeout: 'rekey-timeout', rejectaftertime: 'reject-after-time',
keepalivetimeout: 'keepalive-timeout', maxhandshakeattempts: 'max-handshake-attempts',
randomtrailers: 'random-trailers', disablecookies: 'disable-cookies' };
// [Interface] and the first [Peer] (keys in lower case) -> a wireguard proxy in the
// simplified syntax (one peer; AllowedIPs and DNS dropped: routing and DNS are the kit's)
function wgProxy(iface, peer, name) {
var need = function (v, what) {
if (!v)
throw new Error('нет ' + what);
return v;
};
var ep = need(peer.endpoint, 'Endpoint в [Peer]');
var m = /^\[([^\]]+)\]:([0-9]+)$/.exec(ep) || /^([^:\[\]]+):([0-9]+)$/.exec(ep);
if (!m)
throw new Error('Endpoint ' + ep + ': нужно адрес:порт');
var p = { name: name || m[1], type: 'wireguard', server: m[1], port: +m[2] };
need(iface.address, 'Address в [Interface]').split(',').forEach(function (a) {
a = a.trim();
var v6 = a.indexOf(':') >= 0, k = v6 ? 'ipv6' : 'ip';
if (a && !p[k])
p[k] = a.replace(v6 ? /\/128$/ : /\/32$/, '');
});
p['private-key'] = need(iface.privatekey, 'PrivateKey в [Interface]');
p['public-key'] = need(peer.publickey, 'PublicKey в [Peer]');
if (peer.presharedkey)
p['pre-shared-key'] = peer.presharedkey;
if (/^[0-9]+$/.test(iface.mtu || ''))
p.mtu = +iface.mtu;
// AmneziaWG 3 gives a range ("25-35"): mihomo takes one number
m = /^([0-9]+)(-[0-9]+)?$/.exec(peer.persistentkeepalive || '');
if (m && +m[1])
p['persistent-keepalive'] = +m[1];
p.udp = true;
var awg = {}, keys = Object.keys(iface).filter(function (k) { return (AWG[k] || AWG3[k]) && iface[k] !== ''; });
if (keys.some(function (k) { return AWG3[k]; }))
awg.version = 3;
keys.forEach(function (k) {
var v = iface[k];
if (k == 'randomtrailers' || k == 'disablecookies')
v = /^(1|true|on|yes)$/i.test(v);
else if (/^[0-9]+$/.test(v))
v = +v;
awg[AWG[k] || AWG3[k]] = v;
});
if (keys.length)
p['amnezia-wg-option'] = awg;
return p;
}
// a wg-quick / AmneziaWG .conf -> proxy (name: default name), throws
function parseConf(text, name) {
var iface = null, peers = [], sec = null;
String(text).split(/\r?\n/).forEach(function (l) {
l = l.replace(/#.*/, '').trim();
var m = /^\[\s*(\w+)\s*\]$/.exec(l), i = l.indexOf('=');
if (m) {
m = m[1].toLowerCase();
sec = m == 'interface' ? (iface = iface || {}) : m == 'peer' ? (peers[peers.length] = {}) : null;
} else if (sec && i > 0) {
sec[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim();
}
});
if (!iface || !peers.length)
throw new Error('нужны секции [Interface] и [Peer]');
if (peers.length > 1)
throw new Error('несколько [Peer]: поддерживается один');
return wgProxy(iface, peers[0], name);
}
// an AmneziaVPN key: "vpn://" + base64url of qCompress(JSON) (4-byte length + zlib) or
// of the JSON itself; its AmneziaWG / WireGuard containers -> { servers, errors }
function parseAmnezia(line) {
var r = { servers: [], errors: [] }, o = null;
var raw = b64(urlSafe(line.trim().replace(/^vpn:\/\//i, '').replace(/[\s=]/g, '')), URLSAFE, false);
if (raw) {
try {
o = JSON.parse(utf8(inflate(raw.slice(4))));
} catch (e) {
try {
o = JSON.parse(utf8(raw));
} catch (e2) {}
}
}
if (!isObj(o)) {
r.errors.push('vpn://: не похоже на ключ AmneziaVPN');
return r;
}
if (o.api_key || o.auth_data) {
r.errors.push('vpn://: ключ Amnezia Free / Premium — в нём доступ к их API, а не сервер. ' +
'Нужен ключ своего сервера (AmneziaWG) или его .conf');
return r;
}
var other = [];
(Array.isArray(o.containers) ? o.containers : []).forEach(function (c) {
var proto = isObj(c) && (c.awg || c.wireguard), last = null;
if (!isObj(proto)) {
other.push(isObj(c) && c.container || '?');
return;
}
try {
last = JSON.parse(proto.last_config);
} catch (e) {}
if (!isObj(last)) {
r.errors.push('vpn://: ' + c.container + ' без настроек клиента (last_config)');
return;
}
var name = o.description || o.hostName;
try {
var p;
if (last.config) {
p = parseConf(last.config, name);
} else {
// no wg config text: the same from the fields (AWG ones are named as in it)
var iface = { address: last.client_ip, privatekey: last.client_priv_key };
Object.keys(last).forEach(function (k) {
if (AWG[k.toLowerCase()] || AWG3[k.toLowerCase()])
iface[k.toLowerCase()] = String(last[k]);
});
p = wgProxy(iface, { endpoint: (last.hostName || o.hostName) + ':' + (last.port || proto.port),
publickey: last.server_pub_key, presharedkey: last.psk_key,
persistentkeepalive: String(last.persistent_keep_alive || '') }, name);
}
// the client sets MTU from the key, not from the config text
if (!p.mtu && /^[0-9]+$/.test(String(last.mtu || '')))
p.mtu = +last.mtu;
r.servers.push(p);
} catch (e) {
r.errors.push('vpn://: ' + c.container + ': ' + e.message);
}
});
if (!r.servers.length && !r.errors.length)
r.errors.push('vpn://: нет AmneziaWG / WireGuard' + (other.length ? ' (есть: ' + other.join(', ') +
'; для Xray возьми vless://-ссылку)' : ''));
return r;
}
// --- servers of the form --------------------------------------------------------- // --- servers of the form ---------------------------------------------------------
var LINK = /^\s*[A-Za-z][A-Za-z0-9+.-]*:\/\//; var LINK = /^\s*[A-Za-z][A-Za-z0-9+.-]*:\/\//;
var VPN = /^\s*vpn:\/\//i;
var CONF = /^\s*\[\s*Interface\s*\]\s*$/im;
// pasted text: share links, AmneziaVPN keys (vpn://) and/or mihomo YAML (a "proxies:" // pasted text: share links and/or mihomo YAML (a "proxies:" list, a list, one proxy)
// list, a list, one proxy) or WireGuard / AmneziaWG .conf; name: default name of a // -> { servers: [...], errors: [...] }
// .conf (the file name) -> { servers: [...], errors: [...] } function parseText(text) {
function parseText(text, name) { var links = [], rest = [], errors = [];
var links = [], keys = [], rest = [], errors = [];
String(text).split(/\r?\n/).forEach(function (l) { String(text).split(/\r?\n/).forEach(function (l) {
(VPN.test(l) ? keys : LINK.test(l) ? links : rest).push(l); (LINK.test(l) ? links : rest).push(l);
}); });
var servers = links.length ? parseLinks(links.join('\n')) : []; var servers = links.length ? parseLinks(links.join('\n')) : [];
if (links.length && servers.length < links.length) if (links.length && servers.length < links.length)
errors.push('не разобрано ссылок: ' + (links.length - servers.length) + ' из ' + links.length); errors.push('не разобрано ссылок: ' + (links.length - servers.length) + ' из ' + links.length);
keys.forEach(function (l) {
var r = parseAmnezia(l);
servers = servers.concat(r.servers);
errors = errors.concat(r.errors);
});
var y = rest.join('\n'); var y = rest.join('\n');
if (CONF.test(y)) { if (y.trim()) {
// .conf: one per [Interface] (several files pasted one after another)
y.split(/^(?=\s*\[\s*Interface\s*\]\s*$)/im).forEach(function (c) {
if (!CONF.test(c))
return;
try {
servers.push(parseConf(c, name));
} catch (e) {
errors.push('.conf: ' + e.message);
}
});
} else if (y.trim()) {
var doc = null, list = []; var doc = null, list = [];
try { try {
doc = yamlLoad(y); doc = yamlLoad(y);
@ -1654,14 +1352,13 @@
return { servers: servers, errors: errors }; return { servers: servers, errors: errors };
} }
// one stored line: JSON with "name" first (mihomo-kit.sh reads it with sed), a // one stored line: JSON with "name" first (mihomo-kit.sh reads it with sed), no
// dialer-proxy only as the server's own entry (LuCI "Вход"; otherwise the kit sets // dialer-proxy (the kit sets it per profile), "$" as \u0024 (no ${...} for the
// it per profile), "$" as \u0024 (no ${...} for the template engine; JSON and YAML // template engine; JSON and YAML both read \u escapes)
// both read \u escapes)
function toLine(p) { function toLine(p) {
var o = { name: String(p.name) }; var o = { name: String(p.name) };
Object.keys(p).forEach(function (k) { Object.keys(p).forEach(function (k) {
if (k != 'name' && (k != 'dialer-proxy' || p[k])) if (k != 'name' && k != 'dialer-proxy')
o[k] = p[k]; o[k] = p[k];
}); });
return JSON.stringify(o).replace(/\$/g, '\\u0024'); return JSON.stringify(o).replace(/\$/g, '\\u0024');
@ -1702,8 +1399,6 @@
return { return {
parseLinks: parseLinks, parseLinks: parseLinks,
parseText: parseText, parseText: parseText,
parseConf: parseConf,
parseAmnezia: parseAmnezia,
yamlLoad: yamlLoad, yamlLoad: yamlLoad,
yamlDump: yamlDump, yamlDump: yamlDump,
toLine: toLine, toLine: toLine,

View File

@ -1,11 +1,11 @@
#!/bin/sh #!/bin/sh
# OpenVPN (with an optional TOTP second factor) for mihomo / nikki on OpenWrt. # OpenVPN (BMSTU) + TOTP for mihomo / nikki on OpenWrt.
# #
# mihomo has no static-challenge support: the password in the proxy config is # mihomo has no static-challenge support: the password in the proxy config is
# static. This script builds the file proxy-provider from the .ovpn (with a fresh # static. This script builds the file proxy-provider from the .ovpn with a fresh
# OTP baked into the password when TOTP_SECRET is set), reloads the provider via # OTP baked into the password, reloads the provider via the mihomo API and brings
# the mihomo API and brings the tunnel up while the code is still valid. After # the tunnel up while the code is still valid. After that the server's auth-token
# that the server's auth-token keeps rekeys alive without an OTP. With the kit core (auto-connect, as OpenVPN # keeps rekeys alive without an OTP. With the kit core (auto-connect, as OpenVPN
# Connect) the tunnel comes up as soon as the provider loads, reconnects by itself # Connect) the tunnel comes up as soon as the provider loads, reconnects by itself
# with the auth-token, and sends the server EXIT when closed; once the token is # with the auth-token, and sends the server EXIT when closed; once the token is
# rejected it waits for a provider with a fresh OTP (cron check). # rejected it waits for a provider with a fresh OTP (cron check).
@ -17,46 +17,44 @@
# cores report no state: there the cron check probes, rarely and at random moments. # cores report no state: there the cron check probes, rarely and at random moments.
# #
# Usage: # Usage:
# ovpn.sh otp print the current TOTP code # bmstu-otp.sh otp print the current TOTP code
# ovpn.sh authfile print username/password lines (openvpn auth-user-pass file) # bmstu-otp.sh authfile print username/password lines (openvpn auth-user-pass file)
# ovpn.sh refresh regenerate provider with fresh OTP, reload, warm up # bmstu-otp.sh refresh regenerate provider with fresh OTP, reload, warm up
# ovpn.sh up bring the tunnel up if it should be up and does not answer # bmstu-otp.sh up bring the tunnel up if it should be up and does not answer
# ovpn.sh write only regenerate the provider and routes (nikki init, before mihomo starts) # bmstu-otp.sh write only regenerate the provider and routes (nikki init, before mihomo starts)
# ovpn.sh check reconcile to the desired state (timer/manual/schedule) and # bmstu-otp.sh check reconcile to the desired state (timer/manual/schedule) and
# refresh a dead tunnel (cron, once a minute; no traffic with the kit core) # refresh a dead tunnel (cron, once a minute; no traffic with the kit core)
# Three modes, one at a time: on (always), off, schedule. A timer runs over any of them # Three modes, one at a time: on (always), off, schedule. A timer runs over any of them
# and hands back to the mode when it ends. # and hands back to the mode when it ends.
# ovpn.sh on always on: drops the manual off, the schedule and the timer # bmstu-otp.sh on always on: drops the manual off, the schedule and the timer
# ovpn.sh off close the tunnel and keep it closed: drops the schedule and the # bmstu-otp.sh off close the tunnel and keep it closed: drops the schedule and the
# timer (the VPN's addresses go without it); frees the server # timer (BMSTU traffic goes without it); frees the single server
# session (the kit core sends EXIT; other cores leave it until # session (the kit core sends EXIT; other cores leave it until
# ping-restart, ~5 min) # ping-restart, ~5 min)
# ovpn.sh sched on the schedule decides (drops the manual off; the timer stays) # bmstu-otp.sh sched on the schedule decides (drops the manual off; the timer stays)
# ovpn.sh sched off schedule off, the tunnel off (as "off", the timer stays) # bmstu-otp.sh sched off schedule off, the tunnel off (as "off", the timer stays)
# ovpn.sh sched HH:MM HH:MM [DAYS] | days DAYS: only store the work hours # bmstu-otp.sh sched HH:MM HH:MM [DAYS] | days DAYS: only store the work hours
# (router time; DAYS 12345 | weekdays | weekend | all); "sched on" uses them # (MSK; DAYS 12345 | weekdays | weekend | all); "sched on" uses them
# ovpn.sh for N up for N minutes from now over the mode, then back to it # bmstu-otp.sh for N up for N minutes from now over the mode, then back to it
# ovpn.sh extend N N more minutes on the timer (starts one if none runs); a timer # bmstu-otp.sh extend N N more minutes on the timer (starts one if none runs); a timer
# never reaches past TIMER_MAX minutes from now # never reaches past TIMER_MAX minutes from now
# ovpn.sh stop end the timer now, back to the mode # bmstu-otp.sh stop end the timer now, back to the mode
# ovpn.sh status what decides now, the next change, the tunnel state (no traffic) # bmstu-otp.sh status what decides now, the next change, the tunnel state (no traffic)
# ovpn.sh probe open CHECK_URL through the tunnel (a request the site can log) # bmstu-otp.sh probe open CHECK_URL through the tunnel (a request the site can log)
# ovpn.sh state the same as key=value lines (LuCI) # bmstu-otp.sh state the same as key=value lines (LuCI)
# ovpn.sh want exit code: should the tunnel be up now # bmstu-otp.sh want exit code: should the tunnel be up now
# ovpn.sh debug show the real handshake error in the nikki log # bmstu-otp.sh debug show the real handshake error in the nikki log
set -u set -u
# the files of kits before 2026-11 (bmstu.*), until mihomo-kit.sh moves them ENV_FILE="${ENV_FILE:-/etc/nikki/bmstu.env}"
_old() { [ -f "/etc/nikki/$1" ] && [ ! -f "/etc/nikki/$2" ] && echo "/etc/nikki/$1" || echo "/etc/nikki/$2"; }
ENV_FILE="${ENV_FILE:-$(_old bmstu.env openvpn.env)}"
[ -f "$ENV_FILE" ] && . "$ENV_FILE" [ -f "$ENV_FILE" ] && . "$ENV_FILE"
: "${OVPN_FILE:=$(_old bmstu.ovpn openvpn.ovpn)}" : "${OVPN_FILE:=/etc/nikki/bmstu.ovpn}"
: "${PROVIDER_FILE:=/etc/nikki/run/providers/openvpn.yaml}" : "${PROVIDER_FILE:=/etc/nikki/run/providers/bmstu.yaml}"
: "${PROVIDER_NAME:=openvpn}" : "${PROVIDER_NAME:=bmstu}"
: "${PROXY_NAME:=openvpn}" : "${PROXY_NAME:=bmstu-ovpn}"
: "${GROUP_NAME:=OPENVPN}" : "${GROUP_NAME:=BMSTU}"
# API address/secret: from nikki's mixin settings unless set in the env file # API address/secret: from nikki's mixin settings unless set in the env file
uci_get() { uci -q get "$1" 2>/dev/null; } uci_get() { uci -q get "$1" 2>/dev/null; }
# api_listen is host:port; a wildcard/empty host means loopback works # api_listen is host:port; a wildcard/empty host means loopback works
@ -69,16 +67,16 @@ api_from_uci() {
} }
: "${API:=$(api_from_uci)}" : "${API:=$(api_from_uci)}"
: "${API_SECRET:=$(uci_get nikki.mixin.api_secret)}" : "${API_SECRET:=$(uci_get nikki.mixin.api_secret)}"
# while this file exists the tunnel stays off (ovpn.sh off/on); it is the # while this file exists the tunnel stays off (bmstu-otp.sh off/on); it is the
# sticky manual off and wins over the schedule # sticky manual off and wins over the schedule
: "${OFF_FLAG:=$(_old bmstu.off openvpn.off)}" : "${OFF_FLAG:=/etc/nikki/bmstu.off}"
# timer (ovpn.sh for N): holds an epoch; the tunnel stays up until then, # timer (bmstu-otp.sh for N): holds an epoch; the tunnel stays up until then,
# overriding the schedule, then this file is removed and the schedule resumes # overriding the schedule, then this file is removed and the schedule resumes
: "${UNTIL_FLAG:=$(_old bmstu.until openvpn.until)}" : "${UNTIL_FLAG:=/etc/nikki/bmstu.until}"
# the longest a timer (for / extend) reaches from now, minutes # the longest a timer (for / extend) reaches from now, minutes
: "${TIMER_MAX:=720}" : "${TIMER_MAX:=720}"
# schedule: with OVPN_SCHED=1 the tunnel is up only inside [START,END], the # schedule: with OVPN_SCHED=1 the tunnel is up only inside [START,END] local time
# router's local time. A deterministic per-day jitter of up to OVPN_SCHED_JITTER # (the router is MSK). A deterministic per-day jitter of up to OVPN_SCHED_JITTER
# minutes is added to each edge so the on/off moments are not identical every day. # minutes is added to each edge so the on/off moments are not identical every day.
# OVPN_SCHED_DAYS: weekdays the window opens on, digits 1 (Mon) .. 7 (Sun); a window # OVPN_SCHED_DAYS: weekdays the window opens on, digits 1 (Mon) .. 7 (Sun); a window
# past midnight belongs to the day it starts on. # past midnight belongs to the day it starts on.
@ -86,7 +84,7 @@ api_from_uci() {
: "${OVPN_SCHED_DAYS:=1234567}" : "${OVPN_SCHED_DAYS:=1234567}"
# what "probe" opens through the tunnel: OVPN_CHECK_URL of the profiles (LuCI) # what "probe" opens through the tunnel: OVPN_CHECK_URL of the profiles (LuCI)
: "${CHECK_URL:=$(sed -n 's/^OVPN_CHECK_URL=//p' /etc/nikki/profiles.d/common.env 2>/dev/null | tail -n 1 | tr -d "'\"")}" : "${CHECK_URL:=$(sed -n 's/^OVPN_CHECK_URL=//p' /etc/nikki/profiles.d/common.env 2>/dev/null | tail -n 1 | tr -d "'\"")}"
: "${CHECK_URL:=https://www.gstatic.com/generate_204}" : "${CHECK_URL:=https://eu.bmstu.ru}"
# ms, must exceed HANDSHAKE_TIMEOUT (max 32767) # ms, must exceed HANDSHAKE_TIMEOUT (max 32767)
: "${CHECK_TIMEOUT:=25000}" : "${CHECK_TIMEOUT:=25000}"
# cores without the tunnel state: the cron check probes at most every PROBE_EVERY # cores without the tunnel state: the cron check probes at most every PROBE_EVERY
@ -104,13 +102,11 @@ api_from_uci() {
# No fresh OTP during a pause either. # No fresh OTP during a pause either.
: "${OVPN_RECONNECT_PAUSE:=120}" "${OVPN_RECONNECT_JITTER:=30}" : "${OVPN_RECONNECT_PAUSE:=120}" "${OVPN_RECONNECT_JITTER:=30}"
: "${OVPN_KICK_PAUSE:=$OVPN_RECONNECT_PAUSE}" : "${OVPN_KICK_PAUSE:=$OVPN_RECONNECT_PAUSE}"
# with TOTP_SECRET, how the code goes with the password: # scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1" (the BMSTU
# scrv1 - what openvpn / OpenVPN Connect send for "static-challenge ... 1": # profile): SCRV1:b64(pass):b64(otp)
# SCRV1:b64(pass):b64(otp) # otp-last - <password><otp> (the server accepts it too)
# otp-last - <password><otp>
# otp-first - <otp><password> # otp-first - <otp><password>
# auto (default): scrv1 when the .ovpn has static-challenge, else otp-last : "${PASS_FORMAT:=scrv1}"
: "${PASS_FORMAT:=auto}"
# client the server sees (key-method 2 options string and peer-info): # client the server sees (key-method 2 options string and peer-info):
# connect-mac - OpenVPN Connect 3.7.1 (5558) for macOS, as its log shows them # connect-mac - OpenVPN Connect 3.7.1 (5558) for macOS, as its log shows them
# mihomo - what mihomo sends itself (IV_VER=mihomo-openvpn) # mihomo - what mihomo sends itself (IV_VER=mihomo-openvpn)
@ -127,7 +123,7 @@ api_from_uci() {
: "${MIXED_PORT:=$(uci_get nikki.mixin.mixed_port || echo 7890)}" : "${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')")}" : "${MIXED_AUTH:=$(u=$(uci_get 'nikki.@authentication[0].username') && echo "$u:$(uci_get 'nikki.@authentication[0].password')")}"
log() { logger -t openvpn "$*" 2>/dev/null; echo "$*" >&2; } log() { logger -t bmstu-otp "$*" 2>/dev/null; echo "$*" >&2; }
die() { log "error: $*"; exit 1; } die() { log "error: $*"; exit 1; }
# --- TOTP (RFC 6238, HMAC-SHA1) -------------------------------------------- # --- TOTP (RFC 6238, HMAC-SHA1) --------------------------------------------
@ -184,16 +180,9 @@ fresh_totp() {
b64() { printf '%s' "$1" | openssl base64 -A 2>/dev/null || printf '%s' "$1" | base64 | tr -d '\n'; } b64() { printf '%s' "$1" | openssl base64 -A 2>/dev/null || printf '%s' "$1" | base64 | tr -d '\n'; }
# the password the provider carries: as is without TOTP_SECRET
make_password() { make_password() {
[ -n "${TOTP_SECRET:-}" ] || { echo "$VPN_PASSWORD"; return; } otp=$1
otp=$(fresh_totp) || return 1 case "$PASS_FORMAT" in
_pf=$PASS_FORMAT
if [ "$_pf" = auto ]; then
_pf=otp-last
grep -q '^[[:space:]]*static-challenge' "$OVPN_FILE" 2>/dev/null && _pf=scrv1
fi
case "$_pf" in
scrv1) echo "SCRV1:$(b64 "$VPN_PASSWORD"):$(b64 "$otp")" ;; scrv1) echo "SCRV1:$(b64 "$VPN_PASSWORD"):$(b64 "$otp")" ;;
otp-first) echo "$otp$VPN_PASSWORD" ;; otp-first) echo "$otp$VPN_PASSWORD" ;;
otp-last) echo "$VPN_PASSWORD$otp" ;; otp-last) echo "$VPN_PASSWORD$otp" ;;
@ -241,24 +230,21 @@ write_provider() {
[ -f "$OVPN_FILE" ] || die "no $OVPN_FILE" [ -f "$OVPN_FILE" ] || die "no $OVPN_FILE"
[ -n "${VPN_USERNAME:-}" ] || die "VPN_USERNAME is empty" [ -n "${VPN_USERNAME:-}" ] || die "VPN_USERNAME is empty"
[ -n "${VPN_PASSWORD:-}" ] || die "VPN_PASSWORD is empty" [ -n "${VPN_PASSWORD:-}" ] || die "VPN_PASSWORD is empty"
[ -n "${TOTP_SECRET:-}" ] || die "TOTP_SECRET is empty"
# first "remote host port proto" line # first "remote host port proto" line
set -- $(ovpn_opt remote) set -- $(ovpn_opt remote)
host=$1 port=${2:-1194} proto=${3:-udp} host=$1 port=${2:-1194} proto=${3:-udp}
case "$proto" in tcp*) proto=tcp ;; *) proto=udp ;; esac case "$proto" in tcp*) proto=tcp ;; *) proto=udp ;; esac
fallback=$(ovpn_opt data-ciphers-fallback) fallback=$(ovpn_opt data-ciphers-fallback)
# the .ovpn's list (data-ciphers, or the older ncp-ciphers), else the usual AEAD ones
ciphers=$(ovpn_opt data-ciphers)
[ -n "$ciphers" ] || ciphers=$(ovpn_opt ncp-ciphers)
ciphers=$(printf '%s' "${ciphers:-AES-256-GCM:AES-128-GCM}" | sed 's/:/, /g')
pass=$(make_password) || exit 1 pass=$(make_password "$(fresh_totp)") || exit 1
mkdir -p "$(dirname "$PROVIDER_FILE")" mkdir -p "$(dirname "$PROVIDER_FILE")"
# per process: the init hook can write while a cron refresh does # per process: the init hook can write while a cron refresh does
tmp="$PROVIDER_FILE.tmp.$$" tmp="$PROVIDER_FILE.tmp.$$"
{ {
echo "# generated by ovpn.sh at $(date '+%F %T') - do not edit" echo "# generated by bmstu-otp.sh at $(date '+%F %T') - do not edit"
echo "proxies:" echo "proxies:"
echo " - name: $PROXY_NAME" echo " - name: $PROXY_NAME"
echo " type: openvpn" echo " type: openvpn"
@ -268,9 +254,10 @@ write_provider() {
echo " udp: true" echo " udp: true"
echo " username: $(yaml_str "$VPN_USERNAME")" echo " username: $(yaml_str "$VPN_USERNAME")"
echo " password: $(yaml_str "$pass")" echo " password: $(yaml_str "$pass")"
echo " data-ciphers: [$ciphers]" # the server pushes AES-256-GCM
echo " data-ciphers: [AES-256-GCM, AES-128-GCM]"
[ -n "$fallback" ] && echo " data-ciphers-fallback: $fallback" [ -n "$fallback" ] && echo " data-ciphers-fallback: $fallback"
# what servers usually push (and OpenVPN Connect uses); mihomo ignores pushed ping. # what the server pushes (and OpenVPN Connect uses); mihomo ignores pushed ping.
# A dead tunnel is noticed by the cron check sooner than by ping-restart. # A dead tunnel is noticed by the cron check sooner than by ping-restart.
echo " ping: 60" echo " ping: 60"
echo " ping-restart: 300" echo " ping-restart: 300"
@ -364,18 +351,18 @@ tunnel_ok() {
} }
# provider with a single direct proxy: the old tunnel gets closed with the # provider with a single direct proxy: the old tunnel gets closed with the
# outdated proxy, and the VPN's addresses go without it (on whitelist / foreign # outdated proxy, and BMSTU traffic goes without it (public resources still
# the provider's dialer-proxy sends them through OVPN-EXIT) # open; on street the provider's dialer-proxy sends it through OVPN-EXIT)
write_off_provider() { write_off_provider() {
mkdir -p "$(dirname "$PROVIDER_FILE")" mkdir -p "$(dirname "$PROVIDER_FILE")"
printf '# ovpn.sh off\nproxies:\n - name: %s-off\n type: direct\n' "$PROVIDER_NAME" > "$PROVIDER_FILE" printf '# bmstu-otp.sh off\nproxies:\n - name: %s-off\n type: direct\n' "$PROVIDER_NAME" > "$PROVIDER_FILE"
} }
# rule-provider <PROVIDER_NAME>-routes (written by mihomo-kit.sh build): with the # rule-provider <PROVIDER_NAME>-routes (written by mihomo-kit.sh build): with the
# tunnel off it is emptied, so the VPN's addresses follow the normal rules # tunnel off it is emptied, so BMSTU addresses follow the normal rules
ROUTES=${ROUTES:-$(dirname "$PROVIDER_FILE")/$PROVIDER_NAME-routes} ROUTES=${ROUTES:-$(dirname "$PROVIDER_FILE")/$PROVIDER_NAME-routes}
routes_body() { routes_body() {
if [ "$1" = off ] || { [ -f "$ROUTES.all" ] && ! grep -q . "$ROUTES.all"; }; then if [ "$1" = off ]; then
echo 'payload: []' echo 'payload: []'
elif [ -f "$ROUTES.all" ]; then elif [ -f "$ROUTES.all" ]; then
echo 'payload:' echo 'payload:'
@ -423,7 +410,7 @@ refresh() {
# kit core, steady state (cron): it reconnects by itself with the session # kit core, steady state (cron): it reconnects by itself with the session
# token. A fresh OTP is needed once the server rejected the token, or when the # token. A fresh OTP is needed once the server rejected the token, or when the
# tunnel has stayed down for DOWN_GRACE seconds. # tunnel has stayed down for DOWN_GRACE seconds.
DOWN_SINCE=${DOWN_SINCE:-/tmp/openvpn.down} DOWN_SINCE=${DOWN_SINCE:-/tmp/bmstu-otp.down}
watch_core() { watch_core() {
if [ "$_cs_since" -gt 0 ]; then if [ "$_cs_since" -gt 0 ]; then
rm -f "$DOWN_SINCE" rm -f "$DOWN_SINCE"
@ -450,7 +437,7 @@ watch_core() {
# other cores (no tunnel state): probe CHECK_URL, but only every PROBE_EVERY # other cores (no tunnel state): probe CHECK_URL, but only every PROBE_EVERY
# seconds and not on the minute mark, so it does not look like a clock # seconds and not on the minute mark, so it does not look like a clock
PROBE_LAST=${PROBE_LAST:-/tmp/openvpn.probe} PROBE_LAST=${PROBE_LAST:-/tmp/bmstu-otp.probe}
watch_probe() { watch_probe() {
_now=$(date +%s) _now=$(date +%s)
_last=$(cat "$PROBE_LAST" 2>/dev/null) _last=$(cat "$PROBE_LAST" 2>/dev/null)
@ -729,7 +716,7 @@ state() {
echo "jitter=$OVPN_SCHED_JITTER" echo "jitter=$OVPN_SCHED_JITTER"
} }
# persist KEY=value in the env file (openvpn.env) and apply it to this process, # persist KEY=value in the env file (bmstu.env) and apply it to this process,
# so the cron and the init hook that source the file pick the change up # so the cron and the init hook that source the file pick the change up
sched_set() { sched_set() {
eval "$1=\$2" eval "$1=\$2"
@ -782,7 +769,7 @@ reconcile() {
} }
# one state change at a time (cron check, LuCI buttons, use): lock_take <wait s> # one state change at a time (cron check, LuCI buttons, use): lock_take <wait s>
LOCK=${LOCK:-/tmp/openvpn.lock} LOCK=${LOCK:-/tmp/bmstu-otp.lock}
lock_take() { lock_take() {
_w=0 _w=0
until mkdir "$LOCK" 2>/dev/null; do until mkdir "$LOCK" 2>/dev/null; do
@ -800,18 +787,15 @@ lock_take() {
trap 'rm -rf "$LOCK"' EXIT trap 'rm -rf "$LOCK"' EXIT
} }
# a check with two probes and a refresh takes up to ~2 min # a check with two probes and a refresh takes up to ~2 min
lock_wait() { lock_take 150 || die "busy: another ovpn.sh run holds $LOCK"; } lock_wait() { lock_take 150 || die "busy: another bmstu-otp.sh run holds $LOCK"; }
case "${1:-}" in case "${1:-}" in
otp) otp) totp ;;
[ -n "${TOTP_SECRET:-}" ] || die "no TOTP_SECRET: the password goes without a code"
totp
;;
# auth-user-pass file for testing with the real openvpn client # auth-user-pass file for testing with the real openvpn client
authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password)" ;; authfile) printf '%s\n%s\n' "$VPN_USERNAME" "$(make_password "$(fresh_totp)")" ;;
refresh) refresh)
lock_wait lock_wait
want_up || die "OpenVPN is off now ($(base_state | cut -d' ' -f2)): ovpn.sh on, or for <min>" want_up || die "OpenVPN is off now ($(base_state | cut -d' ' -f2)): bmstu-otp.sh on, or for <min>"
routes_set on routes_set on
refresh refresh
;; ;;
@ -858,7 +842,7 @@ case "${1:-}" in
# bring the tunnel up for N minutes, over the manual off and the schedule; # bring the tunnel up for N minutes, over the manual off and the schedule;
# then whatever was in force before holds again (the cron applies it) # then whatever was in force before holds again (the cron applies it)
for | extend) for | extend)
case "${2:-}" in '' | *[!0-9]* | 0) die "usage: ovpn.sh $1 <minutes>" ;; esac case "${2:-}" in '' | *[!0-9]* | 0) die "usage: bmstu-otp.sh $1 <minutes>" ;; esac
lock_wait lock_wait
_now=$(date +%s) _now=$(date +%s)
# extend: from the end of the running timer, from now when none runs # extend: from the end of the running timer, from now when none runs
@ -886,7 +870,7 @@ case "${1:-}" in
case "${2:-}" in case "${2:-}" in
'' | show) '' | show)
if [ "${OVPN_SCHED:-0}" = 1 ]; then if [ "${OVPN_SCHED:-0}" = 1 ]; then
echo "schedule on: $OVPN_SCHED_START-$OVPN_SCHED_END (router time), days $OVPN_SCHED_DAYS, jitter +-$OVPN_SCHED_JITTER min" echo "schedule on: $OVPN_SCHED_START-$OVPN_SCHED_END MSK, days $OVPN_SCHED_DAYS, jitter +-$OVPN_SCHED_JITTER min"
else else
echo "schedule off" echo "schedule off"
fi fi
@ -904,11 +888,11 @@ case "${1:-}" in
sched_set OVPN_SCHED 1 sched_set OVPN_SCHED 1
;; ;;
days) days)
_dz=$(days_norm "${3:-}") && [ -n "$_dz" ] || die "usage: ovpn.sh sched days 12345 | weekdays | weekend | all" _dz=$(days_norm "${3:-}") && [ -n "$_dz" ] || die "usage: bmstu-otp.sh sched days 12345 | weekdays | weekend | all"
sched_set OVPN_SCHED_DAYS "$_dz" sched_set OVPN_SCHED_DAYS "$_dz"
;; ;;
[0-9][0-9]:[0-9][0-9]) [0-9][0-9]:[0-9][0-9])
_a=$(hhmm_to_min "$2") && _b=$(hhmm_to_min "${3:-}") || die "usage: ovpn.sh sched HH:MM HH:MM" _a=$(hhmm_to_min "$2") && _b=$(hhmm_to_min "${3:-}") || die "usage: bmstu-otp.sh sched HH:MM HH:MM"
# the jittered edges must not cross, or the window flips between # the jittered edges must not cross, or the window flips between
# almost the whole day and nothing from day to day # almost the whole day and nothing from day to day
_j=$((${OVPN_SCHED_JITTER:-0} * 2)) _j=$((${OVPN_SCHED_JITTER:-0} * 2))
@ -922,7 +906,7 @@ case "${1:-}" in
sched_set OVPN_SCHED_START "$2" sched_set OVPN_SCHED_START "$2"
sched_set OVPN_SCHED_END "$3" sched_set OVPN_SCHED_END "$3"
;; ;;
*) die "usage: ovpn.sh sched off | on | HH:MM HH:MM [DAYS] | days DAYS" ;; *) die "usage: bmstu-otp.sh sched off | on | HH:MM HH:MM [DAYS] | days DAYS" ;;
esac esac
wait_api wait_api
reconcile reconcile
@ -942,14 +926,14 @@ case "${1:-}" in
eval "$(state)" eval "$(state)"
case "$mode" in case "$mode" in
timer) echo "on by timer until $until_hm $until_day, then $after ($why)" ;; timer) echo "on by timer until $until_hm $until_day, then $after ($why)" ;;
manual) echo "off (manual, until ovpn.sh on)" ;; manual) echo "off (manual, until bmstu-otp.sh on)" ;;
always) echo "on (no schedule)" ;; always) echo "on (no schedule)" ;;
schedule) schedule)
[ "$want" = 1 ] && echo "on by schedule" || echo "off by schedule" [ "$want" = 1 ] && echo "on by schedule" || echo "off by schedule"
;; ;;
esac esac
if [ "$next" -gt 0 ]; then if [ "$next" -gt 0 ]; then
echo "schedule: $sched_start-$sched_end (router time), days $sched_days, today $win (jitter +-$jitter min)" echo "schedule: $sched_start-$sched_end MSK, days $sched_days, today $win (jitter +-$jitter min)"
[ "$mode" = schedule ] && echo "turns $next_to at $next_hm $next_day" [ "$mode" = schedule ] && echo "turns $next_to at $next_hm $next_day"
fi fi
case "$link" in case "$link" in
@ -958,7 +942,7 @@ case "${1:-}" in
connecting) echo "tunnel connecting${err:+ (last error: $err)}" ;; connecting) echo "tunnel connecting${err:+ (last error: $err)}" ;;
rejected) echo "the server rejected the session: the cron check gets a new OTP${retry_hm:+ after the pause, at $retry_hm}" ;; rejected) echo "the server rejected the session: the cron check gets a new OTP${retry_hm:+ after the pause, at $retry_hm}" ;;
held) echo "reconnect pause ($retry_why${err:+: $err}): next attempt at $retry_hm" ;; held) echo "reconnect pause ($retry_why${err:+: $err}): next attempt at $retry_hm" ;;
*) echo "tunnel state unknown: this core does not report it (ovpn.sh probe opens $CHECK_URL)" ;; *) echo "tunnel state unknown: this core does not report it (bmstu-otp.sh probe opens $CHECK_URL)" ;;
esac esac
[ "$want" = 1 ] && [ "$tunnel" = down ] && echo "the cron check brings it up within a minute" [ "$want" = 1 ] && [ "$tunnel" = down ] && echo "the cron check brings it up within a minute"
[ "$want" = 0 ] && [ "$tunnel" = up ] && echo "the cron check takes it down within a minute" [ "$want" = 0 ] && [ "$tunnel" = up ] && echo "the cron check takes it down within a minute"
@ -970,14 +954,14 @@ case "${1:-}" in
HANDSHAKE_TIMEOUT=0 write_provider HANDSHAKE_TIMEOUT=0 write_provider
api PATCH /configs -H 'Content-Type: application/json' -d '{"log-level":"debug"}' >/dev/null 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)" api PUT "/providers/proxies/$PROVIDER_NAME" >/dev/null || die "provider reload failed (API $API)"
echo "password format: ${TOTP_SECRET:+$PASS_FORMAT}${TOTP_SECRET:-no TOTP}, length $(sed -n 's/^ password: "\(.*\)"$/\1/p' "$PROVIDER_FILE" | wc -c)" 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" \ curl -skS -m 25 -o /dev/null -w "request via mihomo: http %{http_code}\n" \
${MIXED_AUTH:+--proxy-user "$MIXED_AUTH"} \ ${MIXED_AUTH:+--proxy-user "$MIXED_AUTH"} \
-x "http://127.0.0.1:$MIXED_PORT" "${DEBUG_URL:-$CHECK_URL}" -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 # let LAN clients trigger a handshake and hit the 5s dial timeout
sleep 20 sleep 20
echo "--- log ---" echo "--- log ---"
{ cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -iE "openvpn" | tail -n 30 { cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -iE "openvpn|bmstu" | tail -n 30
echo "--- handshake errors ---" echo "--- handshake errors ---"
{ cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -E "OpenVPN" | tail -n 5 { cat /var/log/nikki/core.log 2>/dev/null || logread; } | grep -E "OpenVPN" | tail -n 5
;; ;;

View File

@ -1,12 +1,10 @@
# /etc/nikki/openvpn.env on the router, chmod 600 (LuCI / mihomo-kit.sh setup writes it) # /etc/nikki/bmstu.env on the router, chmod 600 (mihomo-kit.sh setup writes it)
VPN_USERNAME="username" VPN_USERNAME="username"
VPN_PASSWORD="your-password" VPN_PASSWORD="your-password"
# only for a VPN that asks for a one-time code: the base32 secret from the TOTP QR # base32 secret from the TOTP QR (otpauth://totp/...?secret=XXXX)
# (otpauth://totp/...?secret=XXXX); without it the password goes as is TOTP_SECRET="XXXXXXXXXXXXXXXX"
#TOTP_SECRET="XXXXXXXXXXXXXXXX" # scrv1 (default, as OpenVPN Connect: SCRV1:b64(pass):b64(otp)) | otp-last | otp-first
# how the code goes: auto (default: scrv1 when the .ovpn has static-challenge, else #PASS_FORMAT=scrv1
# otp-last) | scrv1 (as OpenVPN Connect: SCRV1:b64(pass):b64(otp)) | otp-last | otp-first
#PASS_FORMAT=auto
# connect-mac (default: present as OpenVPN Connect 3.7.1 for macOS) | mihomo # connect-mac (default: present as OpenVPN Connect 3.7.1 for macOS) | mihomo
#OVPN_MIMIC=connect-mac #OVPN_MIMIC=connect-mac
# kit core, pauses before reconnecting (seconds): after a drop or a failed connect # kit core, pauses before reconnecting (seconds): after a drop or a failed connect
@ -21,14 +19,14 @@ VPN_PASSWORD="your-password"
#API_SECRET="" #API_SECRET=""
# something reachable only (or at least) through the VPN # something reachable only (or at least) through the VPN
#CHECK_URL="https://intranet.example.com" #CHECK_URL="https://www.bmstu.ru"
#OVPN_FILE=/etc/nikki/openvpn.ovpn #OVPN_FILE=/etc/nikki/bmstu.ovpn
#PROVIDER_FILE=/etc/nikki/run/providers/openvpn.yaml #PROVIDER_FILE=/etc/nikki/run/providers/bmstu.yaml
# Schedule: with OVPN_SCHED=1 the tunnel is up only inside these local-time (MSK) # Schedule: with OVPN_SCHED=1 the tunnel is up only inside these local-time (MSK)
# hours, with up to OVPN_SCHED_JITTER minutes of deterministic per-day jitter on # hours, with up to OVPN_SCHED_JITTER minutes of deterministic per-day jitter on
# each edge. Managed from LuCI or `ovpn.sh sched ...`; shown here for reference. # each edge. Managed from LuCI or `bmstu-otp.sh sched ...`; shown here for reference.
#OVPN_SCHED=0 #OVPN_SCHED=0
#OVPN_SCHED_START=09:00 #OVPN_SCHED_START=09:00
#OVPN_SCHED_END=17:00 #OVPN_SCHED_END=17:00

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +0,0 @@
untrusted comment: Nikki
RWSrAXyIqregizvXvG9kJI/JoTkaCCPDy6CQrrVQ4IZ8Qgu+iWMql0UW

View File

@ -53,40 +53,11 @@ RU_IPS="194.190.191.112/32"
#MY_DOMAINS="home.example.org" #MY_DOMAINS="home.example.org"
#LOCAL_HOSTS="example.org=192.168.1.10" # own servers in this router's LAN: domain (+ subdomains)=LAN IP #LOCAL_HOSTS="example.org=192.168.1.10" # own servers in this router's LAN: domain (+ subdomains)=LAN IP
# services: a site or app that always takes its own way and has its own group (name in # OpenVPN (BMSTU), needs /etc/nikki/bmstu.env and bmstu-otp.sh
# upper case); rules above the own lists. GEOSITE: lists of MetaCubeX/meta-rules-dat;
# VIA: MY (default; the first alive own server - one exit IP), FOREIGN, RU, DIRECT, MAIN
#SERVICES="claude"
#SVC_CLAUDE_GEOSITE="anthropic"
#SVC_CLAUDE_DOMAINS=""
#SVC_CLAUDE_IPS=""
#SVC_CLAUDE_VIA=MY # or a pool's group: DE
#SVC_CLAUDE_SERVER="my-de" # fixed exit in every profile; empty = group above
#SVC_CLAUDE_PROVIDER="" # empty = own server; or provider ID, e.g. sam_hub-my
#SVC_CLAUDE_CHAIN=WL # entry for VIA = MY / a pool: DIRECT FOREIGN RU MY MY-EXIT or a pool
# pools: own servers and subscription nodes picked by hand, a group each (the name in upper
# case) for the services' VIA. TYPE: fallback (default) | url-test | select; SERVERS: own
# servers by name, ";" between; SUBS: "<id>" (nodes without [MY]) / "<id>-my" (only [MY]);
# FILTER / EXCLUDE: mihomo regex over the subscription nodes' names
#POOLS="de"
#POOL_DE_TYPE=fallback
#POOL_DE_SERVERS="de-1; nl-2"
#POOL_DE_SUBS="sam_hub sam_hub-my"
#POOL_DE_FILTER='(?i)🇩🇪|\bde\b'
#POOL_DE_EXCLUDE='(?i)torrent'
#POOL_DE_UPLINK=1 # offer in UPLINK: everything through the pool first
# [MY] nodes of the subscriptions with an entry of their own (LuCI: «Свои серверы» →
# «Из подписок ([MY])»): "<ENTRY>|<id>-my|<exact node name>", ENTRY FOREIGN, RU, DIRECT or a pool
#MY_NODE_1='FOREIGN|sam_hub-my|[MY] 🇩🇪 de-1'
# OpenVPN by /etc/nikki/openvpn.ovpn, login in /etc/nikki/openvpn.env (ovpn.sh)
OPENVPN=0 OPENVPN=0
#OVPN_ROUTES="10.0.0.0/8 192.168.50.0/24" # what goes through the VPN (LuCI: the .ovpn's route lines) #OVPN_SERVER_HOST=openvpn4.bmstu.ru
#OVPN_SERVER_HOST=vpn.example.com # default: the remote lines of the .ovpn #OVPN_SERVER_IPS="195.19.40.7 195.19.33.86"
#OVPN_SERVER_IPS="203.0.113.10" #OVPN_ROUTES="172.16.0.0/16 172.19.33.0/24 195.19.32.0/19"
#OVPN_CHECK_URL=https://intranet.example.com # a page behind the VPN for the manual check
# weak routers (256 MB RAM): health checks every 10 min and only with traffic, sniffer # weak routers (256 MB RAM): health checks every 10 min and only with traffic, sniffer
# without QUIC, quiet core; on apply also GOMEMLIMIT (LITE_GOMEMLIMIT, default 64MiB) # without QUIC, quiet core; on apply also GOMEMLIMIT (LITE_GOMEMLIMIT, default 64MiB)

View File

@ -1,5 +1,5 @@
# url: what the dashboard's delay test opens through the tunnel; # url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale code) # interval 0: no background checks (they would redial with a stale OTP)
- name: ${OVPN_GROUP} - name: ${OVPN_GROUP}
type: select type: select
use: [${OVPN_PROVIDER}] use: [${OVPN_PROVIDER}]

View File

@ -1,6 +1,6 @@
# what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit): # what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).
# a RU node, for a VPN server in Russia. select, not url-test: switching nodes # select, not url-test: switching nodes would break the tunnel.
# would break the tunnel. Pick one in the dashboard, the choice is remembered. # Pick a concrete RU node in the dashboard, the choice is remembered.
- name: OVPN-EXIT - name: OVPN-EXIT
type: select type: select
use: [${SUB_LIST}] use: [${SUB_LIST}]

View File

@ -1,15 +0,0 @@
# pool ${POOL_NAME} (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: ${POOL_GROUP}
type: ${POOL_TYPE}
empty-fallback: REJECT #@pool_fixed
proxies: [${POOL_PROXIES}] #@pool_proxies
use: [${POOL_USE}] #@pool_use
filter: "${POOL_FILTER}" #@pool_filter
exclude-filter: "${POOL_EXCLUDE}" #@pool_exclude
url: "https://www.gstatic.com/generate_204" #@!pool_select
interval: 300 #@!pool_select,!lite
interval: 600 #@!pool_select,lite
tolerance: 50 #@pool_urltest
lazy: false #@!pool_select,!lite
lazy: true #@!pool_select,lite

View File

@ -1,15 +0,0 @@
# service ${SVC_NAME} (SERVICES, SVC_*): its own way, whatever MAIN is
# through own servers: the first alive one, not the fastest - the exit IP stays the #@svc_my
# same while the server lives (a site that checks the region sees one country); #@svc_my
# pick another in the dashboard, the choice is remembered #@svc_my
- name: ${SVC_GROUP}
type: fallback #@svc_my
proxies: [${OWN_LIST}] #@svc_my,own_srv
use: [${MY_SUB_LIST}] #@svc_my
url: "https://www.gstatic.com/generate_204" #@svc_my
interval: 300 #@svc_my,!lite
interval: 600 #@svc_my,lite
lazy: false #@svc_my,!lite
lazy: true #@svc_my,lite
type: select #@!svc_my
proxies: [${SVC_PROXIES}] #@!svc_my

View File

@ -1,15 +0,0 @@
# ${VG_POOL} through ${VG_ENTRY} (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): its servers and
# nodes, each dialing through ${VG_ENTRY}
- name: "${VG_NAME}"
type: ${VG_TYPE}
empty-fallback: REJECT #@vg_fixed
proxies: [${VG_PROXIES}] #@vg_proxies
use: [${VG_USE}] #@vg_use
filter: "${VG_FILTER}" #@vg_filter
exclude-filter: "${VG_EXCLUDE}" #@vg_exclude
url: "https://www.gstatic.com/generate_204" #@!vg_select
interval: 300 #@!vg_select,!lite
interval: 600 #@!vg_select,lite
tolerance: 50 #@vg_urltest
lazy: false #@!vg_select,!lite
lazy: true #@!vg_select,lite

View File

@ -1,8 +1,7 @@
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect # UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the # through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist); a pool (POOL_<NAME>_UPLINK=1) - through its servers, they themselves # whitelist), then FOREIGN / MY / RU work on top of it as usual.
# direct; then FOREIGN / MY / RU work on top of it as usual.
# On whitelist own servers go MY-EXIT -> node -> UPLINK. # On whitelist own servers go MY-EXIT -> node -> UPLINK.
- name: UPLINK - name: UPLINK
type: select type: select
proxies: [DIRECT${UPLINK_MORE}] proxies: [DIRECT, CSQTT]

View File

@ -5,8 +5,8 @@
interval: 3600 interval: 3600
proxy: ${@SUB_PROXY} proxy: ${@SUB_PROXY}
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]" exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
override: #@uplink override: #@csqtt
dialer-proxy: UPLINK #@uplink dialer-proxy: UPLINK #@csqtt
header: header:
User-Agent: ["${SUB_UA}"] User-Agent: ["${SUB_UA}"]
${@@SUB_HEADERS} ${@@SUB_HEADERS}

View File

@ -3,8 +3,7 @@
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
${SUB_NAME}-my: ${SUB_NAME}-my:
type: file #@router type: file #@router
path: ./providers/${SUB_NAME}.yaml #@router path: ./providers/${SUB_NAME}.yaml #@router
@ -14,11 +13,10 @@
interval: 3600 #@mobile interval: 3600 #@mobile
proxy: ${@SUB_PROXY} #@mobile proxy: ${@SUB_PROXY} #@mobile
filter: "(?i)\\[MY\\]" filter: "(?i)\\[MY\\]"
exclude-filter: "${@@SUB_MY_EXCLUDE}"
override: #@my_exit override: #@my_exit
dialer-proxy: MY-EXIT #@my_exit dialer-proxy: MY-EXIT #@my_exit
override: #@uplink,!my_exit override: #@csqtt,!my_exit
dialer-proxy: UPLINK #@uplink,!my_exit dialer-proxy: UPLINK #@csqtt,!my_exit
header: #@mobile header: #@mobile
User-Agent: ["${SUB_UA}"] #@mobile User-Agent: ["${SUB_UA}"] #@mobile
${@@SUB_HEADERS} #@mobile ${@@SUB_HEADERS} #@mobile

View File

@ -1,24 +0,0 @@
# [MY] nodes of ${SUB_NAME} with an entry of their own (LuCI «Свои серверы» → «Вход»):
# out of ${SUB_NAME}-my, dialing through ${MV_ENTRY} in every profile
${MV_NAME}:
type: file #@router
path: ./providers/${SUB_NAME}.yaml #@router
type: http #@mobile
url: "${SUB_URL}" #@mobile
path: ./providers/${MV_NAME}.yaml #@mobile
interval: 3600 #@mobile
proxy: ${@SUB_PROXY} #@mobile
filter: "${MV_FILTER}"
override:
dialer-proxy: ${MV_ENTRY}
header: #@mobile
User-Agent: ["${SUB_UA}"] #@mobile
${@@SUB_HEADERS} #@mobile
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300 #@!lite
interval: 600 #@lite
timeout: 3000
lazy: false #@!lite
lazy: true #@lite

View File

@ -7,7 +7,7 @@
override: override:
additional-prefix: "[MY] " additional-prefix: "[MY] "
dialer-proxy: MY-EXIT #@my_exit dialer-proxy: MY-EXIT #@my_exit
dialer-proxy: UPLINK #@uplink,!my_exit dialer-proxy: UPLINK #@csqtt,!my_exit
health-check: health-check:
enable: true enable: true
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"

View File

@ -1,26 +0,0 @@
# ${VP_BASE} for the chains through ${VP_ENTRY}: the same nodes, named "... ⟶ ${VP_ENTRY}"
${VP_NAME}:
type: file #@router
path: ${VP_PATH} #@router
type: http #@mobile
url: "${SUB_URL}" #@mobile
path: ./providers/${VP_NAME}.yaml #@mobile
interval: 3600 #@mobile
proxy: ${@SUB_PROXY} #@mobile
filter: "(?i)\\[MY\\]" #@vp_my
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]" #@vp_sub
override:
additional-prefix: "[MY] " #@vp_links
additional-suffix: " ⟶ ${VP_ENTRY}"
dialer-proxy: ${VP_ENTRY} #@!vp_direct
header: #@mobile
User-Agent: ["${SUB_UA}"] #@mobile
${@@SUB_HEADERS} #@mobile
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300 #@!lite
interval: 600 #@lite
timeout: 3000
lazy: false #@!lite
lazy: true #@lite

View File

@ -1,6 +1,6 @@
# OpenVPN: file written on the router by ovpn.sh (with TOTP: a fresh code in the # 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 # password). No health-check here: a dead tunnel would be redialed with a
# stale code; the cron watchdog (ovpn.sh check) handles it. # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
${OVPN_PROVIDER}: ${OVPN_PROVIDER}:
type: file type: file
path: ./providers/${OVPN_PROVIDER}.yaml path: ./providers/${OVPN_PROVIDER}.yaml

View File

@ -12,4 +12,4 @@
reality-opts: reality-opts:
public-key: ${SEED_PBK} public-key: ${SEED_PBK}
short-id: ${SEED_SID} short-id: ${SEED_SID}
dialer-proxy: UPLINK #@uplink dialer-proxy: UPLINK #@csqtt

View File

@ -1,8 +1,6 @@
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile - {"dialer-proxy": "MY-EXIT", ${@@OWN_BODIES} #@my_exit
- {"dialer-proxy": "MY-EXIT", ${@@OWN_PLAIN} #@my_exit - {"dialer-proxy": "UPLINK", ${@@OWN_BODIES} #@csqtt,!my_exit
- {"dialer-proxy": "UPLINK", ${@@OWN_PLAIN} #@uplink,!my_exit - {${@@OWN_BODIES} #@!my_exit,!csqtt
- {${@@OWN_PLAIN} #@!my_exit,!uplink
${@@OWN_ENTRY}

View File

@ -1,3 +0,0 @@
# copies of own servers for the chains (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): the same
# server dialing through another entry, named "<server> ⟶ <entry>" (group "<pool> ⟶ <entry>")
${@@VARIANT_PROXIES}

View File

@ -7,12 +7,3 @@
url: "${RULESET_URL}/ru-inside.mrs" url: "${RULESET_URL}/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "${RULESET_URL}/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400

View File

@ -1,6 +1,6 @@
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and # OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by ovpn.sh off, so with the tunnel off these addresses follow # emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead OpenVPN group # the normal rules instead of a dead BMSTU group
${OVPN_PROVIDER}-routes: ${OVPN_PROVIDER}-routes:
type: file type: file
behavior: ipcidr behavior: ipcidr

View File

@ -1,8 +0,0 @@
# services (SERVICES): geosite list ${GEOSITE_NAME} of MetaCubeX/meta-rules-dat
geosite-${GEOSITE_NAME}:
type: http
behavior: domain
format: mrs
url: "${GEOSITE_URL}/${GEOSITE_NAME}.mrs"
path: ./ruleset/geosite-${GEOSITE_NAME}.mrs
interval: 86400

View File

@ -1,7 +0,0 @@
# service ${SVC_NAME}: domains of its hostlists (SVC_<NAME>_HOSTLIST, e.g. zapret's #@svc_hostlist
# /opt/zapret2/ipset/*.txt), read when the profile is built: rebuild to pick up changes #@svc_hostlist
hostlist-${SVC_NAME}: #@svc_hostlist
type: inline #@svc_hostlist
behavior: domain #@svc_hostlist
payload: #@svc_hostlist
- "${@SVC_HOSTLIST}" #@svc_hostlist

View File

@ -1,8 +1,8 @@
# the OpenVPN server itself (remote lines of the .ovpn) must not go into its own tunnel # OpenVPN server itself must not go into its own tunnel
- IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@!ovpn_exit - IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@!ovpn_exit
- IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@ovpn_exit - IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@ovpn_exit
- DOMAIN,${@OVPN_SERVER_HOST},DIRECT #@!ovpn_exit - DOMAIN,${OVPN_SERVER_HOST},DIRECT #@!ovpn_exit
- DOMAIN,${@OVPN_SERVER_HOST},OVPN-EXIT #@ovpn_exit - DOMAIN,${OVPN_SERVER_HOST},OVPN-EXIT #@ovpn_exit
# the networks that go through the VPN (OVPN_ROUTES; before the private-range DIRECT # networks pushed by the server (before the private-range DIRECT rules);
# rules); a rule-provider so that ovpn.sh off can drop them without a restart # a rule-provider so that bmstu-otp.sh off can drop them without a restart
- RULE-SET,${OVPN_PROVIDER}-routes,${OVPN_GROUP},no-resolve - RULE-SET,${OVPN_PROVIDER}-routes,${OVPN_GROUP},no-resolve

View File

@ -1,5 +0,0 @@
# service ${SVC_NAME}: above the own lists, below the tunnels, LAN and push
- RULE-SET,geosite-${@SVC_GEOSITE},${SVC_GROUP}
- DOMAIN-SUFFIX,${@SVC_DOMAINS},${SVC_GROUP}
- IP-CIDR,${@SVC_IPS},${SVC_GROUP}
- RULE-SET,hostlist-${SVC_NAME},${SVC_GROUP} #@svc_hostlist

View File

@ -1,13 +1,9 @@
- RULE-SET,ru-inside,DIRECT #@!foreign - RULE-SET,ru-inside,DIRECT #@!foreign
# abroad: Russian services through the RU pool too #@foreign # abroad: Russian services through the RU pool too #@foreign
- RULE-SET,ru-inside,RU #@foreign - RULE-SET,ru-inside,RU #@foreign
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,DIRECT #@main
- DOMAIN-SUFFIX,ru,DIRECT #@main - DOMAIN-SUFFIX,ru,DIRECT #@main
- DOMAIN-SUFFIX,su,DIRECT #@main
- DOMAIN-SUFFIX,xn--p1ai,DIRECT #@main - DOMAIN-SUFFIX,xn--p1ai,DIRECT #@main
- RULE-SET,ru-services,RU #@!main
- DOMAIN-SUFFIX,ru,RU #@!main - DOMAIN-SUFFIX,ru,RU #@!main
- DOMAIN-SUFFIX,su,RU #@!main
- DOMAIN-SUFFIX,xn--p1ai,RU #@!main - DOMAIN-SUFFIX,xn--p1ai,RU #@!main
- MATCH,MAIN - MATCH,MAIN

View File

@ -3,11 +3,6 @@ sniffer:
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] #@!lite ports: [80, 8080-8880] #@!lite

View File

@ -1,24 +0,0 @@
[Interface]
Address = 10.8.1.2/32
DNS = 1.1.1.1, 1.0.0.1
PrivateKey = fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=
Jc = 4
Jmin = 10
Jmax = 50
S1 = 98
S2 = 32
S3 = 19
S4 = 7
H1 = 1458367412-1593426716
H2 = 1863071624-1902347825
H3 = 2091548318-2097143921
H4 = 2112573893-2147191025
I1 = <r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>
I2 =
[Peer]
PublicKey = vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=
PresharedKey = 6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = 203.0.113.10:47613
PersistentKeepalive = 25

View File

@ -1,31 +0,0 @@
{
"servers": [
{
"name": "awg2",
"type": "wireguard",
"server": "203.0.113.10",
"port": 47613,
"ip": "10.8.1.2",
"private-key": "fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=",
"public-key": "vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=",
"pre-shared-key": "6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=",
"persistent-keepalive": 25,
"udp": true,
"amnezia-wg-option": {
"jc": 4,
"jmin": 10,
"jmax": 50,
"s1": 98,
"s2": 32,
"s3": 19,
"s4": 7,
"h1": "1458367412-1593426716",
"h2": "1863071624-1902347825",
"h3": "2091548318-2097143921",
"h4": "2112573893-2147191025",
"i1": "<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"
}
}
],
"errors": []
}

View File

@ -1,24 +0,0 @@
# AmneziaWG 3, IPv6 endpoint
[Interface]
PrivateKey = Se+IZIi2AQD3AZjN7AazYfi+j3yqITfYwkTkOzVj1Wo=
Address = 10.8.1.3/32, fd00:8:1::3/128
MTU = 1280
Jc = 3
Jmin = 10
Jmax = 50
S1 = 0
S2 = 0
H1 = 1
H2 = 2
H3 = 3
H4 = 4
HeaderProtectionKey = odnCO5zIam/+bXlGAOclYIK0o4+FVxGscfwiHQIUVcU=
ContentPaddingAddition = 0-32
RekeyAfterTime = 120
RandomTrailers = true
DisableCookies = 1
[Peer]
PublicKey = zUr0LTfErDhhn+GgMPuF7VdeIpQ24pI1kihfwQjfnNg=
Endpoint = [2001:db8::10]:51820 # comment
PersistentKeepalive = 25-35

View File

@ -1,35 +0,0 @@
{
"servers": [
{
"name": "awg3",
"type": "wireguard",
"server": "2001:db8::10",
"port": 51820,
"ip": "10.8.1.3",
"ipv6": "fd00:8:1::3",
"private-key": "Se+IZIi2AQD3AZjN7AazYfi+j3yqITfYwkTkOzVj1Wo=",
"public-key": "zUr0LTfErDhhn+GgMPuF7VdeIpQ24pI1kihfwQjfnNg=",
"mtu": 1280,
"persistent-keepalive": 25,
"udp": true,
"amnezia-wg-option": {
"version": 3,
"jc": 3,
"jmin": 10,
"jmax": 50,
"s1": 0,
"s2": 0,
"h1": 1,
"h2": 2,
"h3": 3,
"h4": 4,
"header-protection-key": "odnCO5zIam/+bXlGAOclYIK0o4+FVxGscfwiHQIUVcU=",
"content-padding-addition": "0-32",
"rekey-after-time": 120,
"random-trailers": true,
"disable-cookies": true
}
}
],
"errors": []
}

View File

@ -1,6 +0,0 @@
[Interface]
Address = 10.0.0.2/32
PrivateKey = 9mpa7dajJsZ00c7XLuNEOM5MYGIlPWQn/WDqg0uGHtc=
[Peer]
PublicKey = 9qAqsbJr88uWikvCYZjXRZZLmRwppEfyxr/s5y9YSP0=

View File

@ -1,6 +0,0 @@
{
"servers": [],
"errors": [
".conf: нет Endpoint в [Peer]"
]
}

View File

@ -1,32 +0,0 @@
{
"servers": [
{
"name": "Амнезия NL",
"type": "wireguard",
"server": "198.51.100.7",
"port": 39125,
"ip": "10.8.1.5",
"private-key": "sJYaurvRLIjIzrNVHIxvzLMewcvxeregrDLiAh3mjxs=",
"public-key": "MkcJxkUHqF5oSmPPP4cKLJHqwk6m7iNQKEGvw9C4rMI=",
"pre-shared-key": "CTu0Yl8/YvvhDkqwszsHTZfEuzCKA83sSxtdn3hwggg=",
"persistent-keepalive": 25,
"udp": true,
"amnezia-wg-option": {
"jc": 4,
"jmin": 10,
"jmax": 50,
"s1": 98,
"s2": 32,
"s3": 19,
"s4": 7,
"h1": "1458367412-1593426716",
"h2": "1863071624-1902347825",
"h3": "2091548318-2097143921",
"h4": "2112573893-2147191025",
"i1": "<r 2><b 0x8580>"
},
"mtu": 1376
}
],
"errors": []
}

View File

@ -1 +0,0 @@
vpn://AAAF9XjalVTbbuM2EP0VYp5lRaQk64L1AkGS1rcYbr1bIBsGhiIxttY2pZCSrNjIN7Q_U3Qf2n9w_2hB0nAXXe9DYECewzlzSA5nZg9pwask50xIiO_3_0GIIdlwtsuTTrJdgAXqG--hLEQFMbgRJj5YUImES7U2L0VRFRBDnZVggUZpsZ43TMi84BADAQvWiazmacGf8gXEsKdgbAoxhfsBr5h4SlL2QCm_zDLBpEQ9hB07tLHtX7iEUn49mak1W_8shG3HdmxMKZ-KvEkqNmIvqIfk8C6pRfPrePB5sBOT3_qDttmNb9k2bVom2EJcj_PLpbv53MoepXyYoh7ylLHJud5S20mLeshX9gyjHopCZRHUQ_okM1cxI2V5qIcCSnlf0bDnh2438DDpYD9yPdINcFc5VSQOu64T4C7xOjhyiOsFIfGVU4kRJ8K-F7o47BAnCrDnRkRdra_0CcbED9wwcjsEewGOsKMjB2rPdwKR9-8ekdOGfui8p5RTyu-njAmVy2n9uM5Tk5nbVTpsVx_7zz_5xWwznU69dDQe9p-3q-4myCe_jG5-brbRlSduBz2dVSaXiWCZib76UDt36_DirmmW16vnrdzJ_odPTzf17mp0Gbpy1lYZd5fbxWKhoi_X62LLssFUvaOjn8q5cCwUxxcqqzc8K4ucVzqPoe1jGzuOHcS6uNTmqnZkxXg1YqxM1nnDVCKUi4JFYVnIapJsmC6fbxW0V1UlBSNmUUjXOePVPC8N-1hUmnl0lSJv5iv2oglvqiAlIplomJiX9eNJ40251keWq1Pwm1KtgjdVba7mBl2jdkrffMVYOdcJ1BRi7j1MNfIM2OT8mJojTlqNfYNnWKMoNIho5BKD3OMTGORpZF6hb8LON4UmGKXzjaEJRvx8c2iC2e98gyjCwJzh_02iXImp0HleSgrxPYVTlWq3LlR4eIXXV-v8cGxF8gIW6L94__2AK-rqsah5puW10IMFGXtK6nV19cNhmzGZiryszOQ8_HH4-_DP4c_DX4cv__6OJmPF4BJDDMdBaBaIXtADEaxTd6jFb3oDXr8CPPbK8w

View File

@ -1,20 +0,0 @@
{
"servers": [
{
"name": "vpn.example.net",
"type": "wireguard",
"server": "vpn.example.net",
"port": 51820,
"ip": "10.9.0.2",
"private-key": "4Wy1vIZv6qyqd2STfzx/wX6a0hdMWghlV6a2DpbkUlM=",
"public-key": "L9Rfyw+PxD7/TW2mkh4C9jAimo8nHK6yRYPkHhZVY6s=",
"persistent-keepalive": 25,
"udp": true,
"mtu": 1420
}
],
"errors": [
"vpn://: ключ Amnezia Free / Premium — в нём доступ к их API, а не сервер. Нужен ключ своего сервера (AmneziaWG) или его .conf",
"vpn://: не похоже на ключ AmneziaVPN"
]
}

View File

@ -1,3 +0,0 @@
vpn://AAABq3jahZBBT8JAEIX_y1ytpWygwiYeDBwwiiGIILimWeiUrm23y3ZbKE3_u7FVSbx4m8m8-fLeq2CXSsOFRJ0BfasuK1DgicSz4NdHoXGfc-2DBZeZVqBSbYBCvzsgDlgQ88x4u1QGYg8UKgZhmpknniADyqBQ0sYTT1SMtkTDwGINgAFtABaDXSxQGk-o5qHr2EPbsUmj_D4pLQovwrIR9FZlt7jfFO6hPPjkeRGcT53jq8ud0J-u9mG8dDkZq230Ek9vG0iGukDtqXz7y3gczoPyeDU7jW86ixVJorA3Gn7ciSQdyMmDW87Xs2gSbpZrN2sZiclbdz3itBlQZyIzX-4iROXxWBRtYtJnUENdv1vgY8Dz2Iz-afenMKB_64L6Eyw7kD4
vpn://AAAAO3jaq1ZKLMiMz06tVLJSqlDSUUrOz0vLTI8vSy0qzszPU7Iy0lHKS8xNVbJScszNS63KTFQIKErNzSzNVaoFAFV2FB8
vpn://not-a-key

View File

@ -1,9 +0,0 @@
[Interface]
Address = 172.16.0.2/32
PrivateKey = SdgDFLQDksOZbdDs+sbQ/z06+65znzFrH5eUCoJUorc=
DNS = 1.1.1.1
[Peer]
PublicKey = b4J5nuV2f5PECf2vFOPNazXHGqkcZtMVZrYSUOD5ZgU=
AllowedIPs = 0.0.0.0/0
Endpoint = wg.example.com:2408

View File

@ -1,15 +0,0 @@
{
"servers": [
{
"name": "plain-wg",
"type": "wireguard",
"server": "wg.example.com",
"port": 2408,
"ip": "172.16.0.2",
"private-key": "SdgDFLQDksOZbdDs+sbQ/z06+65znzFrH5eUCoJUorc=",
"public-key": "b4J5nuV2f5PECf2vFOPNazXHGqkcZtMVZrYSUOD5ZgU=",
"udp": true
}
],
"errors": []
}

View File

@ -16,18 +16,11 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "MY-EXIT", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}} - {"dialer-proxy": "MY-EXIT", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"dialer-proxy": "MY-EXIT", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"} - {"dialer-proxy": "MY-EXIT", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
- {"dialer-proxy": "MY-EXIT", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"} - {"dialer-proxy": "MY-EXIT", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"dialer-proxy": "MY-EXIT", "name":"awg-own","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
- {"dialer-proxy": "MY-EXIT", "name":"m1","type":"hysteria2","server":"m.example.com","port":443,"password":"p","udp":true} - {"dialer-proxy": "MY-EXIT", "name":"m1","type":"hysteria2","server":"m.example.com","port":443,"password":"p","udp":true}
- {"name":"via-foreign","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x","dialer-proxy":"FOREIGN"}
# copies of own servers for the chains (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): the same
# server dialing through another entry, named "<server> ⟶ <entry>" (group "<pool> ⟶ <entry>")
- {"dialer-proxy": "FOREIGN", "name":"m1 ⟶ FOREIGN","type":"hysteria2","server":"m.example.com","port":443,"password":"p","udp":true}
proxy-providers: proxy-providers:
example: example:
@ -73,8 +66,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: http type: http
url: "https://sub.example.com/sub/aaa" url: "https://sub.example.com/sub/aaa"
@ -98,8 +90,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: http type: http
url: "https://sub2.example.com/x?a=1&b=2" url: "https://sub2.example.com/x?a=1&b=2"
@ -118,26 +109,6 @@ proxy-providers:
timeout: 3000 timeout: 3000
lazy: false lazy: false
# example2-my for the chains through FOREIGN: the same nodes, named "... ⟶ FOREIGN"
example2-my@FOREIGN:
type: http
url: "https://sub2.example.com/x?a=1&b=2"
path: ./providers/example2-my@FOREIGN.yaml
interval: 3600
proxy: BOOT-AUTO
filter: "(?i)\\[MY\\]"
override:
additional-suffix: " ⟶ FOREIGN"
dialer-proxy: FOREIGN
header:
User-Agent: ["mihomo"]
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
rule-providers: rule-providers:
# Russian services (geosite ru-inside of russia-only, as .mrs): an ordinary # Russian services (geosite ru-inside of russia-only, as .mrs): an ordinary
# http rule-set, so every client fetches it with the config, no geodata setup # http rule-set, so every client fetches it with the config, no geodata setup
@ -148,35 +119,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
# services (SERVICES): geosite list anthropic of MetaCubeX/meta-rules-dat
geosite-anthropic:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@meta/geo/geosite/anthropic.mrs"
path: ./ruleset/geosite-anthropic.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -250,21 +198,11 @@ proxy-groups:
tolerance: 50 tolerance: 50
lazy: false lazy: false
# pool one (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: ONE
type: fallback
proxies: ["m1"]
use: [example2-my]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of # own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed # the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
- name: MY - name: MY
type: url-test type: url-test
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "awg-own", "via-foreign", "m1"] proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "m1"]
use: [example-my, example2-my] use: [example-my, example2-my]
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"
interval: 300 interval: 300
@ -282,21 +220,6 @@ proxy-groups:
tolerance: 300 tolerance: 300
lazy: false lazy: false
# service claude (SERVICES, SVC_*): its own way, whatever MAIN is
- name: CLAUDE
type: select
proxies: ["ONE ⟶ FOREIGN", ONE, MY, FOREIGN, RU, DIRECT]
# ONE through FOREIGN (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): its servers and
# nodes, each dialing through FOREIGN
- name: "ONE ⟶ FOREIGN"
type: fallback
proxies: ["m1 ⟶ FOREIGN"]
use: [example2-my@FOREIGN]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
- name: MAIN - name: MAIN
type: select type: select
proxies: [FOREIGN, MY, RU, DIRECT] proxies: [FOREIGN, MY, RU, DIRECT]
@ -306,9 +229,6 @@ rules:
- IP-CIDR,10.0.0.0/8,DIRECT,no-resolve - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
- IP-CIDR,172.16.0.0/12,DIRECT,no-resolve - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve
# service claude: above the own lists, below the tunnels, LAN and push
- RULE-SET,geosite-anthropic,CLAUDE
# own lists from the settings: above torrents, ru-inside, .ru and MATCH; below the # own lists from the settings: above torrents, ru-inside, .ru and MATCH; below the
# tunnels, LAN and push. Domains (DOMAIN-SUFFIX: the domain and all subdomains) # tunnels, LAN and push. Domains (DOMAIN-SUFFIX: the domain and all subdomains)
# before IPs; first match wins: MY, then FOREIGN, then RU. # before IPs; first match wins: MY, then FOREIGN, then RU.
@ -316,9 +236,7 @@ rules:
- IP-CIDR,194.190.191.112/32,RU - IP-CIDR,194.190.191.112/32,RU
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -73,8 +73,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -93,8 +92,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -118,26 +116,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -284,9 +268,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -17,14 +17,11 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "UPLINK", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}} - {"dialer-proxy": "UPLINK", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"dialer-proxy": "UPLINK", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"} - {"dialer-proxy": "UPLINK", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
- {"dialer-proxy": "UPLINK", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"} - {"dialer-proxy": "UPLINK", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"dialer-proxy": "UPLINK", "name":"awg-own","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
- {"dialer-proxy": "UPLINK", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true} - {"dialer-proxy": "UPLINK", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
- {"name":"via-foreign","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x","dialer-proxy":"FOREIGN"}
# CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo # CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo
# just sends the connection out of it (the interface does not change routes) # just sends the connection out of it (the interface does not change routes)
@ -81,8 +78,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -101,8 +97,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -126,26 +121,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -234,7 +215,7 @@ proxy-groups:
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed # the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
- name: MY - name: MY
type: url-test type: url-test
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "awg-own", "via-foreign", "nl-1"] proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "nl-1"]
use: [example-my, example2-my] use: [example-my, example2-my]
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"
interval: 300 interval: 300
@ -246,8 +227,7 @@ proxy-groups:
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect # UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the # through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist); a pool (POOL_<NAME>_UPLINK=1) - through its servers, they themselves # whitelist), then FOREIGN / MY / RU work on top of it as usual.
# direct; then FOREIGN / MY / RU work on top of it as usual.
# On whitelist own servers go MY-EXIT -> node -> UPLINK. # On whitelist own servers go MY-EXIT -> node -> UPLINK.
- name: UPLINK - name: UPLINK
type: select type: select
@ -295,9 +275,7 @@ rules:
# abroad: Russian services through the RU pool too # abroad: Russian services through the RU pool too
- RULE-SET,ru-inside,RU - RULE-SET,ru-inside,RU
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -17,13 +17,10 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "MY-EXIT", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}} - {"dialer-proxy": "MY-EXIT", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"dialer-proxy": "MY-EXIT", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"} - {"dialer-proxy": "MY-EXIT", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
- {"dialer-proxy": "MY-EXIT", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"} - {"dialer-proxy": "MY-EXIT", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"dialer-proxy": "MY-EXIT", "name":"awg-own","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
- {"name":"via-foreign","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x","dialer-proxy":"FOREIGN"}
# CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo # CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo
# just sends the connection out of it (the interface does not change routes) # just sends the connection out of it (the interface does not change routes)
@ -80,8 +77,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -100,8 +96,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -125,26 +120,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -236,7 +217,7 @@ proxy-groups:
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed # the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
- name: MY - name: MY
type: url-test type: url-test
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "awg-own", "via-foreign"] proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own"]
use: [example-my, example2-my] use: [example-my, example2-my]
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"
interval: 300 interval: 300
@ -256,8 +237,7 @@ proxy-groups:
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect # UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the # through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist); a pool (POOL_<NAME>_UPLINK=1) - through its servers, they themselves # whitelist), then FOREIGN / MY / RU work on top of it as usual.
# direct; then FOREIGN / MY / RU work on top of it as usual.
# On whitelist own servers go MY-EXIT -> node -> UPLINK. # On whitelist own servers go MY-EXIT -> node -> UPLINK.
- name: UPLINK - name: UPLINK
type: select type: select
@ -303,9 +283,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -27,8 +27,7 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true} - {"name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
proxy-providers: proxy-providers:
@ -75,8 +74,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -93,8 +91,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -106,12 +103,12 @@ proxy-providers:
timeout: 3000 timeout: 3000
lazy: false lazy: false
# OpenVPN: file written on the router by ovpn.sh (with TOTP: a fresh code in the # 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 # password). No health-check here: a dead tunnel would be redialed with a
# stale code; the cron watchdog (ovpn.sh check) handles it. # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
openvpn: bmstu:
type: file type: file
path: ./providers/openvpn.yaml path: ./providers/bmstu.yaml
health-check: health-check:
enable: false enable: false
override: override:
@ -127,34 +124,20 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and # OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by ovpn.sh off, so with the tunnel off these addresses follow # emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead OpenVPN group # the normal rules instead of a dead BMSTU group
openvpn-routes: bmstu-routes:
type: file type: file
behavior: ipcidr behavior: ipcidr
path: ./providers/openvpn-routes.yaml path: ./providers/bmstu-routes.yaml
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -246,16 +229,16 @@ proxy-groups:
lazy: false lazy: false
# url: what the dashboard's delay test opens through the tunnel; # url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale code) # interval 0: no background checks (they would redial with a stale OTP)
- name: OPENVPN - name: BMSTU
type: select type: select
use: [openvpn] use: [bmstu]
url: "https://www.gstatic.com/generate_204" url: "https://eu.bmstu.ru"
interval: 0 interval: 0
# what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit): # what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).
# a RU node, for a VPN server in Russia. select, not url-test: switching nodes # select, not url-test: switching nodes would break the tunnel.
# would break the tunnel. Pick one in the dashboard, the choice is remembered. # Pick a concrete RU node in the dashboard, the choice is remembered.
- name: OVPN-EXIT - name: OVPN-EXIT
type: select type: select
use: [example, example2] use: [example, example2]
@ -300,11 +283,13 @@ rules:
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE - DOMAIN-SUFFIX,ts.net,TAILSCALE
# the OpenVPN server itself (remote lines of the .ovpn) must not go into its own tunnel # OpenVPN server itself must not go into its own tunnel
- IP-CIDR,198.51.100.4/32,OVPN-EXIT,no-resolve - IP-CIDR,195.19.40.7/32,OVPN-EXIT,no-resolve
# the networks that go through the VPN (OVPN_ROUTES; before the private-range DIRECT - IP-CIDR,195.19.33.86/32,OVPN-EXIT,no-resolve
# rules); a rule-provider so that ovpn.sh off can drop them without a restart - DOMAIN,openvpn4.bmstu.ru,OVPN-EXIT
- RULE-SET,openvpn-routes,OPENVPN,no-resolve # networks pushed by the server (before the private-range DIRECT rules);
# a rule-provider so that bmstu-otp.sh off can drop them without a restart
- RULE-SET,bmstu-routes,BMSTU,no-resolve
- IP-CIDR,192.168.0.0/16,DIRECT,no-resolve - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
- IP-CIDR,10.0.0.0/8,DIRECT,no-resolve - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
@ -331,9 +316,7 @@ rules:
# abroad: Russian services through the RU pool too # abroad: Russian services through the RU pool too
- RULE-SET,ru-inside,RU - RULE-SET,ru-inside,RU
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -64,8 +64,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -82,8 +81,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -105,26 +103,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -262,9 +246,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,DIRECT
- DOMAIN-SUFFIX,ru,DIRECT - DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,su,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT - DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN - MATCH,MAIN

View File

@ -82,8 +82,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
kitty-my: kitty-my:
type: file type: file
path: ./providers/kitty.yaml path: ./providers/kitty.yaml
@ -100,8 +99,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
vpn_host-my: vpn_host-my:
type: file type: file
path: ./providers/vpn_host.yaml path: ./providers/vpn_host.yaml
@ -118,8 +116,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
sub3-my: sub3-my:
type: file type: file
path: ./providers/sub3.yaml path: ./providers/sub3.yaml
@ -141,26 +138,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -298,9 +281,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,DIRECT
- DOMAIN-SUFFIX,ru,DIRECT - DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,su,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT - DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN - MATCH,MAIN

View File

@ -77,8 +77,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -97,8 +96,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -122,26 +120,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080] ports: [80, 8080]
@ -242,8 +226,7 @@ proxy-groups:
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect # UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the # through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist); a pool (POOL_<NAME>_UPLINK=1) - through its servers, they themselves # whitelist), then FOREIGN / MY / RU work on top of it as usual.
# direct; then FOREIGN / MY / RU work on top of it as usual.
# On whitelist own servers go MY-EXIT -> node -> UPLINK. # On whitelist own servers go MY-EXIT -> node -> UPLINK.
- name: UPLINK - name: UPLINK
type: select type: select
@ -289,9 +272,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,DIRECT
- DOMAIN-SUFFIX,ru,DIRECT - DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,su,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT - DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN - MATCH,MAIN

View File

@ -24,8 +24,7 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true} - {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
proxy-providers: proxy-providers:
@ -72,8 +71,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -92,8 +90,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -117,26 +114,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080] ports: [80, 8080]
@ -281,9 +264,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -27,14 +27,11 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}} - {"name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"} - {"name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
- {"name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"} - {"name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"name":"awg-own","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
- {"name":"home-hy","type":"hysteria2","server":"1.1.1.1","port":443,"password":"x","udp":true} - {"name":"home-hy","type":"hysteria2","server":"1.1.1.1","port":443,"password":"x","udp":true}
- {"name":"via-foreign","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x","dialer-proxy":"FOREIGN"}
proxy-providers: proxy-providers:
example: example:
@ -80,8 +77,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -98,8 +94,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -111,12 +106,12 @@ proxy-providers:
timeout: 3000 timeout: 3000
lazy: false lazy: false
# OpenVPN: file written on the router by ovpn.sh (with TOTP: a fresh code in the # 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 # password). No health-check here: a dead tunnel would be redialed with a
# stale code; the cron watchdog (ovpn.sh check) handles it. # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
openvpn: bmstu:
type: file type: file
path: ./providers/openvpn.yaml path: ./providers/bmstu.yaml
health-check: health-check:
enable: false enable: false
@ -130,34 +125,20 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and # OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by ovpn.sh off, so with the tunnel off these addresses follow # emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead OpenVPN group # the normal rules instead of a dead BMSTU group
openvpn-routes: bmstu-routes:
type: file type: file
behavior: ipcidr behavior: ipcidr
path: ./providers/openvpn-routes.yaml path: ./providers/bmstu-routes.yaml
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -261,18 +242,18 @@ proxy-groups:
lazy: false lazy: false
# url: what the dashboard's delay test opens through the tunnel; # url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale code) # interval 0: no background checks (they would redial with a stale OTP)
- name: OPENVPN - name: BMSTU
type: select type: select
use: [openvpn] use: [bmstu]
url: "https://www.gstatic.com/generate_204" url: "https://eu.bmstu.ru"
interval: 0 interval: 0
# own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of # own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed # the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
- name: MY - name: MY
type: url-test type: url-test
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "awg-own", "via-foreign", "home-hy"] proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "home-hy"]
use: [example-my, example2-my] use: [example-my, example2-my]
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"
interval: 300 interval: 300
@ -306,12 +287,13 @@ rules:
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE - DOMAIN-SUFFIX,ts.net,TAILSCALE
# the OpenVPN server itself (remote lines of the .ovpn) must not go into its own tunnel # OpenVPN server itself must not go into its own tunnel
- IP-CIDR,203.0.113.10/32,DIRECT,no-resolve - IP-CIDR,195.19.40.7/32,DIRECT,no-resolve
- DOMAIN,vpn.corp.example,DIRECT - IP-CIDR,195.19.33.86/32,DIRECT,no-resolve
# the networks that go through the VPN (OVPN_ROUTES; before the private-range DIRECT - DOMAIN,openvpn4.bmstu.ru,DIRECT
# rules); a rule-provider so that ovpn.sh off can drop them without a restart # networks pushed by the server (before the private-range DIRECT rules);
- RULE-SET,openvpn-routes,OPENVPN,no-resolve # a rule-provider so that bmstu-otp.sh off can drop them without a restart
- RULE-SET,bmstu-routes,BMSTU,no-resolve
- IP-CIDR,192.168.0.0/16,DIRECT,no-resolve - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
- IP-CIDR,10.0.0.0/8,DIRECT,no-resolve - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
@ -350,9 +332,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,DIRECT
- DOMAIN-SUFFIX,ru,DIRECT - DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,su,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT - DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN - MATCH,MAIN

View File

@ -42,8 +42,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -60,8 +59,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -83,26 +81,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -201,9 +185,7 @@ rules:
- IP-CIDR,9.9.9.9/32,FOREIGN - IP-CIDR,9.9.9.9/32,FOREIGN
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,DIRECT
- DOMAIN-SUFFIX,ru,DIRECT - DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,su,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT - DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN - MATCH,MAIN

View File

@ -1,366 +0,0 @@
proxies:
- name: seed
type: vless
server: 1.2.3.4
port: 443
uuid: 00000000-0000-0000-0000-000000000000
network: tcp
udp: true
tls: true
flow: xtls-rprx-vision
servername: eh.vk.ru
client-fingerprint: firefox
reality-opts:
public-key: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
short-id: a1b2
proxy-providers:
example:
type: http
url: "https://sub.example.com/sub/aaa"
path: ./providers/example.yaml
interval: 3600
proxy: BOOT-AUTO
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
header:
User-Agent: ["mihomo"]
# one check per provider: the groups over it (use:) only add their URLs to it,
# so the interval and lazy here are what counts for RU/FOREIGN/TORRENT/MY-EXIT.
# lite: every 10 min and skipped while no traffic used the provider
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
example2:
type: http
url: "https://sub2.example.com/x?a=1&b=2"
path: ./providers/example2.yaml
interval: 3600
proxy: BOOT-AUTO
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
header:
User-Agent: ["mihomo"]
# one check per provider: the groups over it (use:) only add their URLs to it,
# so the interval and lazy here are what counts for RU/FOREIGN/TORRENT/MY-EXIT.
# lite: every 10 min and skipped while no traffic used the provider
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# own servers kept in the subscription, named "[MY] ...", for group MY (the main
# provider leaves them out); a provider of its own because on whitelist and the
# phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
exclude-filter: "^(\\[MY\\] 🇩🇪 de-1 \\(a\\)|\\[MY\\] nl\\.2)$"
override:
dialer-proxy: MY-EXIT
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# own servers kept in the subscription, named "[MY] ...", for group MY (the main
# provider leaves them out); a provider of its own because on whitelist and the
# phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
exclude-filter: "^(\\[MY\\] fi\\x603)$"
override:
dialer-proxy: MY-EXIT
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# [MY] nodes of example with an entry of their own (LuCI «Свои серверы» → «Вход»):
# out of example-my, dialing through FOREIGN in every profile
example-my-via-FOREIGN:
type: file
path: ./providers/example.yaml
filter: "^(\\[MY\\] 🇩🇪 de-1 \\(a\\)|\\[MY\\] nl\\.2)$"
override:
dialer-proxy: FOREIGN
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# [MY] nodes of example2 with an entry of their own (LuCI «Свои серверы» → «Вход»):
# out of example2-my, dialing through DE in every profile
example2-my-via-DE:
type: file
path: ./providers/example2.yaml
filter: "^(\\[MY\\] fi\\x603)$"
override:
dialer-proxy: DE
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# example-my for the chains through RU: the same nodes, named "... ⟶ RU"
example-my@RU:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
override:
additional-suffix: " ⟶ RU"
dialer-proxy: RU
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
rule-providers:
# Russian services (geosite ru-inside of russia-only, as .mrs): an ordinary
# http rule-set, so every client fetches it with the config, no geodata setup
ru-inside:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs
interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff:
HTTP:
ports: [80, 8080-8880]
TLS:
ports: [443, 8443]
# lite: no QUIC (fake-ip already gives the domain; pure-IP QUIC goes by IP)
QUIC:
ports: [443, 8443]
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'
- '+.ru'
- '+.xn--p1ai'
- rule-set:ru-inside
default-nameserver:
- 77.88.8.8
- 1.1.1.1
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
- https://dns.google/dns-query
proxy-groups:
# BOOT: whitelisted entry nodes (BOOT_LINKS), the first alive one
- name: BOOT
type: fallback
proxies: [seed]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# default for downloading subscriptions: BOOT (if set), else the nodes of the
# saved subscriptions (providers are cached on disk), else direct. FOREIGN goes
# before DIRECT: the health check of DIRECT (gstatic) passes in Russia even when
# the subscription site itself is blocked.
- name: BOOT-AUTO
type: fallback
proxies: [BOOT, FOREIGN, DIRECT]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
- name: RU
type: url-test
use: [example, example2]
filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск"
# lite: the provider's URL, so RU nodes are not tested a second time
url: "https://ya.ru"
interval: 300
tolerance: 50
lazy: false
- name: FOREIGN
type: url-test
use: [example, example2]
exclude-filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск"
url: "https://www.gstatic.com/generate_204"
interval: 300
tolerance: 50
lazy: false
- name: TORRENT
type: url-test
use: [example, example2]
filter: "(?i)torrent|\\[tor\\]"
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 6000
tolerance: 500
max-failed-times: 5
lazy: false
# pool de (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: DE
type: fallback
use: [example]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# pool mix (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: MIX
type: fallback
use: [example-my, example-my-via-FOREIGN]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# pool svc-fixed-claude (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: SVC-FIXED-CLAUDE
type: select
empty-fallback: REJECT
use: [example-my, example-my-via-FOREIGN]
filter: "^\\[MY\\] nl\\.2$"
# own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
- name: MY
type: url-test
use: [example-my, example-my-via-FOREIGN, example2-my, example2-my-via-DE]
url: "https://www.gstatic.com/generate_204"
interval: 300
tolerance: 50
lazy: false
# whitelist and mobile (my_exit): what own servers are reached through; switches only when the node is
# clearly worse or dead (each switch breaks everything going through MY)
- name: MY-EXIT
type: url-test
use: [example, example2]
exclude-filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск"
url: "https://www.gstatic.com/generate_204"
interval: 300
tolerance: 300
lazy: false
# service claude (SERVICES, SVC_*): its own way, whatever MAIN is
- name: CLAUDE
type: select
proxies: ["SVC-FIXED-CLAUDE ⟶ RU"]
# SVC-FIXED-CLAUDE through RU (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): its servers and
# nodes, each dialing through RU
- name: "SVC-FIXED-CLAUDE ⟶ RU"
type: select
empty-fallback: REJECT
use: [example-my@RU]
filter: "^\\[MY\\] nl\\.2 ⟶ RU$"
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
# no own servers in the settings: MY may be empty (no [MY] nodes in the subscriptions)
proxies: [FOREIGN, MY, DIRECT]
rules:
- 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
# push notifications (Apple APNs, Google FCM): long-lived connections on a
# stable path - group PUSH (main/foreign: DIRECT, whitelist: MY)
- DOMAIN-SUFFIX,push.apple.com,PUSH
- IP-CIDR,17.249.0.0/16,PUSH,no-resolve
- IP-CIDR,17.252.0.0/16,PUSH,no-resolve
- IP-CIDR,17.57.144.0/22,PUSH,no-resolve
- IP-CIDR,17.188.128.0/18,PUSH,no-resolve
- IP-CIDR,17.188.20.0/23,PUSH,no-resolve
- DOMAIN-REGEX,^(alt[0-9]+-)?mtalk[0-9]*\.google\.com$,PUSH
- DST-PORT,5228-5230,PUSH
# service claude: above the own lists, below the tunnels, LAN and push
- DOMAIN-SUFFIX,claude.ai,CLAUDE
# own lists from the settings: above torrents, ru-inside, .ru and MATCH; below the
# tunnels, LAN and push. Domains (DOMAIN-SUFFIX: the domain and all subdomains)
# before IPs; first match wins: MY, then FOREIGN, then RU.
# RU on main (home, own white IP): reachable directly; whitelist/abroad: through RU
- IP-CIDR,194.190.191.112/32,RU
- SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -13,7 +13,6 @@ proxies:
reality-opts: reality-opts:
public-key: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA public-key: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
short-id: a1b2 short-id: a1b2
dialer-proxy: UPLINK
# Tailscale: userspace node, starts on first use. First login: open the URL # Tailscale: userspace node, starts on first use. First login: open the URL
# from the nikki log ("To start this tsnet server ... go to: ..."), then # from the nikki log ("To start this tsnet server ... go to: ..."), then
@ -32,23 +31,10 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "MY-EXIT", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}} - {"dialer-proxy": "MY-EXIT", "name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"dialer-proxy": "MY-EXIT", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"} - {"dialer-proxy": "MY-EXIT", "name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
- {"dialer-proxy": "MY-EXIT", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"} - {"dialer-proxy": "MY-EXIT", "name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"dialer-proxy": "MY-EXIT", "name":"awg-own","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
- {"name":"via-foreign","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x","dialer-proxy":"FOREIGN"}
# copies of own servers for the chains (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): the same
# server dialing through another entry, named "<server> ⟶ <entry>" (group "<pool> ⟶ <entry>")
- {"dialer-proxy": "WL", "name":"🇩🇪 de 1 ⟶ WL","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"dialer-proxy": "WL", "name":"hy-own ⟶ WL","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"dialer-proxy": "FOREIGN", "name":"🇩🇪 de 1 ⟶ FOREIGN","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
- {"dialer-proxy": "FOREIGN", "name":"tr \"q\" ⟶ FOREIGN","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
- {"dialer-proxy": "FOREIGN", "name":"hy-own ⟶ FOREIGN","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
- {"dialer-proxy": "FOREIGN", "name":"awg-own ⟶ FOREIGN","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
- {"dialer-proxy": "FOREIGN", "name":"via-foreign ⟶ FOREIGN","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x"}
proxy-providers: proxy-providers:
example: example:
@ -58,8 +44,6 @@ proxy-providers:
interval: 3600 interval: 3600
proxy: BOOT-AUTO proxy: BOOT-AUTO
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]" exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
override:
dialer-proxy: UPLINK
header: header:
User-Agent: ["mihomo"] User-Agent: ["mihomo"]
# one check per provider: the groups over it (use:) only add their URLs to it, # one check per provider: the groups over it (use:) only add their URLs to it,
@ -79,8 +63,6 @@ proxy-providers:
interval: 3600 interval: 3600
proxy: BOOT-AUTO proxy: BOOT-AUTO
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]" exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
override:
dialer-proxy: UPLINK
header: header:
User-Agent: ["mihomo"] User-Agent: ["mihomo"]
# one check per provider: the groups over it (use:) only add their URLs to it, # one check per provider: the groups over it (use:) only add their URLs to it,
@ -98,8 +80,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -118,8 +99,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -149,95 +129,6 @@ proxy-providers:
timeout: 3000 timeout: 3000
lazy: false lazy: false
# example for the chains through DIRECT: the same nodes, named "... ⟶ DIRECT"
example@DIRECT:
type: file
path: ./providers/example.yaml
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
override:
additional-suffix: " ⟶ DIRECT"
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# example for the chains through WL: the same nodes, named "... ⟶ WL"
example@WL:
type: file
path: ./providers/example.yaml
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
override:
additional-suffix: " ⟶ WL"
dialer-proxy: WL
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# example2-my for the chains through WL: the same nodes, named "... ⟶ WL"
example2-my@WL:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
additional-suffix: " ⟶ WL"
dialer-proxy: WL
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# example-my for the chains through FOREIGN: the same nodes, named "... ⟶ FOREIGN"
example-my@FOREIGN:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
override:
additional-suffix: " ⟶ FOREIGN"
dialer-proxy: FOREIGN
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# example2-my for the chains through FOREIGN: the same nodes, named "... ⟶ FOREIGN"
example2-my@FOREIGN:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
additional-suffix: " ⟶ FOREIGN"
dialer-proxy: FOREIGN
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# my-links for the chains through FOREIGN: the same nodes, named "... ⟶ FOREIGN"
my-links@FOREIGN:
type: file
path: ./providers/my-links.txt
override:
additional-prefix: "[MY] "
additional-suffix: " ⟶ FOREIGN"
dialer-proxy: FOREIGN
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
rule-providers: rule-providers:
# Russian services (geosite ru-inside of russia-only, as .mrs): an ordinary # Russian services (geosite ru-inside of russia-only, as .mrs): an ordinary
# http rule-set, so every client fetches it with the config, no geodata setup # http rule-set, so every client fetches it with the config, no geodata setup
@ -248,58 +139,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
# services (SERVICES): geosite list anthropic of MetaCubeX/meta-rules-dat
geosite-anthropic:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@meta/geo/geosite/anthropic.mrs"
path: ./ruleset/geosite-anthropic.mrs
interval: 86400
# services (SERVICES): geosite list openai of MetaCubeX/meta-rules-dat
geosite-openai:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@meta/geo/geosite/openai.mrs"
path: ./ruleset/geosite-openai.mrs
interval: 86400
# service yt: domains of its hostlists (SVC_<NAME>_HOSTLIST, e.g. zapret's
# /opt/zapret2/ipset/*.txt), read when the profile is built: rebuild to pick up changes
hostlist-yt:
type: inline
behavior: domain
payload:
- "+.youtube.com"
- "+.youtu.be"
- "+.googlevideo.com"
- "exact.example"
- "+.wild.example"
- "+.dot.example"
- "+.ggpht.com"
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -393,40 +238,11 @@ proxy-groups:
max-failed-times: 5 max-failed-times: 5
lazy: false lazy: false
# pool de (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: DE
type: url-test
proxies: ["🇩🇪 de 1", "hy-own"]
use: [example, example2-my]
filter: "(?i)🇩🇪|\\bde\\b"
exclude-filter: "(?i)tor"
url: "https://www.gstatic.com/generate_204"
interval: 300
tolerance: 50
lazy: false
# pool gone (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: GONE
type: select
proxies: [REJECT]
# pool wl (POOLS, POOL_*): own servers and subscription nodes picked in the settings;
# filter / exclude-filter apply to the subscriptions' nodes only
- name: WL
type: fallback
use: [example]
filter: "\\[WL\\]"
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of # own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of
# the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed # the subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed
- name: MY - name: MY
type: url-test type: url-test
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "awg-own", "via-foreign"] proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own"]
use: [example-my, example2-my, my-links] use: [example-my, example2-my, my-links]
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"
interval: 300 interval: 300
@ -444,54 +260,6 @@ proxy-groups:
tolerance: 300 tolerance: 300
lazy: false lazy: false
# service claude (SERVICES, SVC_*): its own way, whatever MAIN is
- name: CLAUDE
type: select
proxies: ["DE ⟶ WL", DE, MY, FOREIGN, RU, DIRECT]
# service chat (SERVICES, SVC_*): its own way, whatever MAIN is
- name: CHAT
type: select
proxies: ["MY ⟶ FOREIGN", MY, FOREIGN, RU, DIRECT]
# service yt (SERVICES, SVC_*): its own way, whatever MAIN is
- name: YT
type: select
proxies: [RU, MY, FOREIGN, DIRECT]
# WL through DIRECT (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): its servers and
# nodes, each dialing through DIRECT
- name: "WL ⟶ DIRECT"
type: fallback
use: [example@DIRECT]
filter: "\\[WL\\]"
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# DE through WL (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): its servers and
# nodes, each dialing through WL
- name: "DE ⟶ WL"
type: url-test
proxies: ["🇩🇪 de 1 ⟶ WL", "hy-own ⟶ WL"]
use: [example@WL, example2-my@WL]
filter: "(?i)🇩🇪|\\bde\\b"
exclude-filter: "(?i)tor"
url: "https://www.gstatic.com/generate_204"
interval: 300
tolerance: 50
lazy: false
# MY through FOREIGN (SVC_<NAME>_CHAIN, POOL_<NAME>_UPLINK): its servers and
# nodes, each dialing through FOREIGN
- name: "MY ⟶ FOREIGN"
type: fallback
proxies: ["🇩🇪 de 1 ⟶ FOREIGN", "tr \"q\" ⟶ FOREIGN", "hy-own ⟶ FOREIGN", "awg-own ⟶ FOREIGN", "via-foreign ⟶ FOREIGN"]
use: [example-my@FOREIGN, example2-my@FOREIGN, my-links@FOREIGN]
url: "https://www.gstatic.com/generate_204"
interval: 300
lazy: false
# url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test # url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test
- name: TAILSCALE - name: TAILSCALE
type: select type: select
@ -499,15 +267,6 @@ proxy-groups:
url: "http://100.69.216.50:8080" url: "http://100.69.216.50:8080"
interval: 0 interval: 0
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist); a pool (POOL_<NAME>_UPLINK=1) - through its servers, they themselves
# direct; then FOREIGN / MY / RU work on top of it as usual.
# On whitelist own servers go MY-EXIT -> node -> UPLINK.
- name: UPLINK
type: select
proxies: [DIRECT, "WL ⟶ DIRECT"]
- name: MAIN - name: MAIN
type: select type: select
proxies: [FOREIGN, MY, RU, DIRECT] proxies: [FOREIGN, MY, RU, DIRECT]
@ -540,18 +299,6 @@ rules:
- DOMAIN-REGEX,^(alt[0-9]+-)?mtalk[0-9]*\.google\.com$,PUSH - DOMAIN-REGEX,^(alt[0-9]+-)?mtalk[0-9]*\.google\.com$,PUSH
- DST-PORT,5228-5230,PUSH - DST-PORT,5228-5230,PUSH
# service claude: above the own lists, below the tunnels, LAN and push
- RULE-SET,geosite-anthropic,CLAUDE
- DOMAIN-SUFFIX,claude.example,CLAUDE
# service chat: above the own lists, below the tunnels, LAN and push
- RULE-SET,geosite-openai,CHAT
- RULE-SET,geosite-anthropic,CHAT
- IP-CIDR,1.2.3.4/32,CHAT
# service yt: above the own lists, below the tunnels, LAN and push
- RULE-SET,hostlist-yt,YT
# own lists from the settings: above torrents, ru-inside, .ru and MATCH; below the # own lists from the settings: above torrents, ru-inside, .ru and MATCH; below the
# tunnels, LAN and push. Domains (DOMAIN-SUFFIX: the domain and all subdomains) # tunnels, LAN and push. Domains (DOMAIN-SUFFIX: the domain and all subdomains)
# before IPs; first match wins: MY, then FOREIGN, then RU. # before IPs; first match wins: MY, then FOREIGN, then RU.
@ -561,9 +308,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -31,8 +31,7 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true} - {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
- {"dialer-proxy": "MY-EXIT", "name":"de-2","type":"hysteria2","server":"5.6.7.8","port":443,"password":"q","udp":true} - {"dialer-proxy": "MY-EXIT", "name":"de-2","type":"hysteria2","server":"5.6.7.8","port":443,"password":"q","udp":true}
@ -80,8 +79,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -100,8 +98,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -125,26 +122,12 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -308,9 +291,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -28,8 +28,7 @@ proxies:
# own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON # own servers of the settings (LuCI "Свои серверы", /etc/nikki/my-servers): one JSON
# proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in # proxy per line, as mihomo's own config would have it; the kit puts dialer-proxy in
# front: whitelist and the phone through MY-EXIT, else with UPLINK (CSQTT, pools) through it. # front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
# A server with an entry of its own (LuCI "Вход") keeps it in every profile
- {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p\"w\\1","obfs":"salamander","obfs-password":"obfs","sni":"vpn.example.com","up":"50 mbps","down":"100 mbps","udp":true} - {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p\"w\\1","obfs":"salamander","obfs-password":"obfs","sni":"vpn.example.com","up":"50 mbps","down":"100 mbps","udp":true}
- {"dialer-proxy": "MY-EXIT", "name":"de_2","type":"hysteria2","server":"5.6.7.8","port":8443,"password":"x","sni":"www.bing.com","skip-cert-verify":true,"udp":true} - {"dialer-proxy": "MY-EXIT", "name":"de_2","type":"hysteria2","server":"5.6.7.8","port":8443,"password":"x","sni":"www.bing.com","skip-cert-verify":true,"udp":true}
@ -77,8 +76,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example-my: example-my:
type: file type: file
path: ./providers/example.yaml path: ./providers/example.yaml
@ -97,8 +95,7 @@ proxy-providers:
# phone they go through MY-EXIT. Router: not a second download, reads the file the # phone they go through MY-EXIT. Router: not a second download, reads the file the
# main provider saves (mihomo watches it; ./providers exists before the start, # main provider saves (mihomo watches it; ./providers exists before the start,
# ovpn_routes_write). Phone: FlClash moves provider files to paths of its own, # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,
# so the subscription is fetched once more. Nodes with an entry of their own # so the subscription is fetched once more.
# (MY_NODE_ENTRIES) are left out here for <id>-my-via-<entry> (providers/16-myvia).
example2-my: example2-my:
type: file type: file
path: ./providers/example2.yaml path: ./providers/example2.yaml
@ -112,12 +109,12 @@ proxy-providers:
timeout: 3000 timeout: 3000
lazy: false lazy: false
# OpenVPN: file written on the router by ovpn.sh (with TOTP: a fresh code in the # 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 # password). No health-check here: a dead tunnel would be redialed with a
# stale code; the cron watchdog (ovpn.sh check) handles it. # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
openvpn: bmstu:
type: file type: file
path: ./providers/openvpn.yaml path: ./providers/bmstu.yaml
health-check: health-check:
enable: false enable: false
override: override:
@ -133,34 +130,20 @@ rule-providers:
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs" url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-inside.mrs"
path: ./ruleset/ru-inside.mrs path: ./ruleset/ru-inside.mrs
interval: 86400 interval: 86400
# Russian services outside ru-inside and outside .ru/.su/.рф (russia-only ru-services):
# not on the whitelist, so through RU everywhere but main
ru-services:
type: http
behavior: domain
format: mrs
url: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/ru-services.mrs"
path: ./ruleset/ru-services.mrs
interval: 86400
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and # OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by ovpn.sh off, so with the tunnel off these addresses follow # emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead OpenVPN group # the normal rules instead of a dead BMSTU group
openvpn-routes: bmstu-routes:
type: file type: file
behavior: ipcidr behavior: ipcidr
path: ./providers/openvpn-routes.yaml path: ./providers/bmstu-routes.yaml
sniffer: sniffer:
enable: true enable: true
force-dns-mapping: true force-dns-mapping: true
parse-pure-ip: true parse-pure-ip: true
override-destination: false override-destination: false
# ECH: browsers show the outer name cloudflare-ech.com instead of the site behind
# Cloudflare; the sniffed name wins in the rules, so .ru / own lists would miss the
# site. Skipped: the rules see the name from mihomo's DNS (fake-ip / DNS mapping).
skip-domain:
- "+.cloudflare-ech.com"
sniff: sniff:
HTTP: HTTP:
ports: [80, 8080-8880] ports: [80, 8080-8880]
@ -259,16 +242,16 @@ proxy-groups:
lazy: false lazy: false
# url: what the dashboard's delay test opens through the tunnel; # url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale code) # interval 0: no background checks (they would redial with a stale OTP)
- name: OPENVPN - name: BMSTU
type: select type: select
use: [openvpn] use: [bmstu]
url: "https://intranet.corp.example/" url: "https://lks.bmstu.ru/"
interval: 0 interval: 0
# what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit): # what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).
# a RU node, for a VPN server in Russia. select, not url-test: switching nodes # select, not url-test: switching nodes would break the tunnel.
# would break the tunnel. Pick one in the dashboard, the choice is remembered. # Pick a concrete RU node in the dashboard, the choice is remembered.
- name: OVPN-EXIT - name: OVPN-EXIT
type: select type: select
use: [example, example2] use: [example, example2]
@ -330,12 +313,13 @@ rules:
- DOMAIN-SUFFIX,corp.example,TAILSCALE - DOMAIN-SUFFIX,corp.example,TAILSCALE
- DOMAIN-SUFFIX,internal.example,TAILSCALE - DOMAIN-SUFFIX,internal.example,TAILSCALE
# the OpenVPN server itself (remote lines of the .ovpn) must not go into its own tunnel # OpenVPN server itself must not go into its own tunnel
- DOMAIN,vpn1.corp.example,OVPN-EXIT - IP-CIDR,195.19.40.7/32,OVPN-EXIT,no-resolve
- DOMAIN,vpn2.corp.example,OVPN-EXIT - IP-CIDR,195.19.33.86/32,OVPN-EXIT,no-resolve
# the networks that go through the VPN (OVPN_ROUTES; before the private-range DIRECT - DOMAIN,openvpn4.bmstu.ru,OVPN-EXIT
# rules); a rule-provider so that ovpn.sh off can drop them without a restart # networks pushed by the server (before the private-range DIRECT rules);
- RULE-SET,openvpn-routes,OPENVPN,no-resolve # a rule-provider so that bmstu-otp.sh off can drop them without a restart
- RULE-SET,bmstu-routes,BMSTU,no-resolve
- IP-CIDR,192.168.0.0/16,DIRECT,no-resolve - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve
- IP-CIDR,10.0.0.0/8,DIRECT,no-resolve - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve
@ -363,9 +347,7 @@ rules:
- SRC-PORT,20000-20199,TORRENT-SEL - SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT - RULE-SET,ru-inside,DIRECT
# main (home, own white IP): ru-services and .ru/.su/.рф directly; elsewhere through RU # main (home, own white IP): .ru/.рф directly; elsewhere through RU
- RULE-SET,ru-services,RU
- DOMAIN-SUFFIX,ru,RU - DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,su,RU
- DOMAIN-SUFFIX,xn--p1ai,RU - DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN - MATCH,MAIN

View File

@ -6,10 +6,3 @@ HY2_M1_PASSWORD=p
LOCAL_HOSTS="sub2.example.com=192.168.64.20" LOCAL_HOSTS="sub2.example.com=192.168.64.20"
MY_LINKS='ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#ss1' MY_LINKS='ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#ss1'
MY_SERVERS_FILE=tests/fixtures/own.servers MY_SERVERS_FILE=tests/fixtures/own.servers
SERVICES=claude
SVC_CLAUDE_GEOSITE=anthropic
POOLS=one
POOL_ONE_SERVERS='m1'
POOL_ONE_SUBS="example2-my"
SVC_CLAUDE_VIA=ONE
SVC_CLAUDE_CHAIN=FOREIGN

View File

@ -1,9 +0,0 @@
# a client profile as servers hand it out: two remotes, pushed and own routes
client
dev tun
remote vpn.corp.example 1194 udp
remote 203.0.113.10 443 tcp
data-ciphers AES-256-GCM:CHACHA20-POLY1305
route 10.20.0.0 255.255.0.0
route 192.0.2.7
static-challenge "Code" 1

View File

@ -1,5 +1,3 @@
{"name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}} {"name":"🇩🇪 de 1","type":"vless","server":"x.example.com","port":"443","uuid":"00000000-0000-0000-0000-000000000001","udp":true,"tls":true,"client-fingerprint":"chrome","servername":"www.example.com","reality-opts":{"public-key":"Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns","short-id":"ab"},"xudp":true,"network":"xhttp","xhttp-opts":{"path":"/x"}}
{"name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"} {"name":"tr \"q\"","type":"trojan","server":"t.example.org","port":"443","password":"p\u0024w","udp":true,"skip-cert-verify":false,"sni":"t.example.org","network":"grpc","grpc-opts":{"grpc-service-name":"g"},"client-fingerprint":"chrome"}
{"name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"} {"name":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
{"name":"awg-own","type":"wireguard","server":"203.0.113.10","port":47613,"ip":"10.8.1.2","private-key":"fTo2df+b5vCuulh7pOXMWiWJY2VwSe2Kuup2nA34tfI=","public-key":"vGYpG72gCXPNfYzr/0iNfSoL83vbrVSGUC+v+MKRVyE=","pre-shared-key":"6ut/J6EuaJ97RMFcZuiJkzIo7a5uxR98htK5NdWJW6E=","persistent-keepalive":25,"udp":true,"amnezia-wg-option":{"jc":4,"jmin":10,"jmax":50,"s1":98,"s2":32,"s3":19,"s4":7,"h1":"1458367412-1593426716","h2":"1863071624-1902347825","h3":"2091548318-2097143921","h4":"2112573893-2147191025","i1":"<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>"}}
{"name":"via-foreign","type":"ss","server":"f.example.com","port":8388,"cipher":"aes-256-gcm","password":"x","dialer-proxy":"FOREIGN"}

View File

@ -1,8 +1,6 @@
TARGET=router TARGET=router
LOCATION=foreign LOCATION=foreign
OPENVPN=1 OPENVPN=1
OVPN_SERVER_IPS="198.51.100.4"
OVPN_ROUTES="10.30.0.0/16"
TAILSCALE=1 TAILSCALE=1
HY2=nl-1 HY2=nl-1
HY2_NL_1_SERVER=vpn.example.com HY2_NL_1_SERVER=vpn.example.com

View File

@ -1,7 +1,5 @@
LOCATION=main LOCATION=main
OPENVPN=1 OPENVPN=1
OVPN_FILE=tests/fixtures/openvpn.ovpn
OVPN_ROUTES="10.20.0.0/16 192.0.2.7/32"
TAILSCALE=1 TAILSCALE=1
HY2=home-hy HY2=home-hy
HY2_HOME_HY_SERVER=1.1.1.1 HY2_HOME_HY_SERVER=1.1.1.1

View File

@ -1,13 +0,0 @@
LOCATION=whitelist
# [MY] nodes with an entry of their own (LuCI: «Свои серверы» → «Вход»)
MY_NODE_1='FOREIGN|example-my|[MY] 🇩🇪 de-1 (a)'
MY_NODE_2='FOREIGN|example-my|[MY] nl.2'
MY_NODE_3='DE|example2-my|[MY] fi`3'
POOLS='de mix'
POOL_DE_SUBS='example'
POOL_MIX_SUBS='example-my'
SERVICES='claude'
SVC_CLAUDE_DOMAINS='claude.ai'
SVC_CLAUDE_SERVER='[MY] nl.2'
SVC_CLAUDE_PROVIDER='example-my'
SVC_CLAUDE_CHAIN='RU'

View File

@ -3,24 +3,3 @@ LOCATION=whitelist
TAILSCALE=1 TAILSCALE=1
MY_LINKS='vless://00000000-0000-0000-0000-000000000001@x.example.com:443?security=reality&sni=www.example.com&pbk=Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns&sid=ab&type=xhttp&path=%2Fx#de%201 trojan://pw@t.example.org:443?sni=t.example.org#tr' MY_LINKS='vless://00000000-0000-0000-0000-000000000001@x.example.com:443?security=reality&sni=www.example.com&pbk=Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns&sid=ab&type=xhttp&path=%2Fx#de%201 trojan://pw@t.example.org:443?sni=t.example.org#tr'
MY_SERVERS_FILE=tests/fixtures/own.servers MY_SERVERS_FILE=tests/fixtures/own.servers
SERVICES="claude chat yt"
SVC_CLAUDE_GEOSITE=anthropic
SVC_CLAUDE_VIA=DE
SVC_CLAUDE_CHAIN=WL
SVC_CLAUDE_DOMAINS="*.claude.example"
SVC_CHAT_GEOSITE="openai anthropic"
SVC_CHAT_IPS="1.2.3.4"
SVC_CHAT_VIA=MY
SVC_CHAT_CHAIN=FOREIGN
SVC_YT_HOSTLIST="tests/hostlists/youtube.txt tests/hostlists/extra.txt.gz tests/hostlists/missing.txt"
SVC_YT_VIA=RU
POOLS="de gone wl"
POOL_DE_TYPE=url-test
POOL_DE_SERVERS='🇩🇪 de 1; hy-own; renamed-server'
POOL_DE_SUBS="example example2-my no-such"
POOL_DE_FILTER='(?i)🇩🇪|\bde\b'
POOL_DE_EXCLUDE='(?i)tor'
POOL_GONE_SERVERS='renamed-server'
POOL_WL_SUBS="example"
POOL_WL_FILTER='\[WL\]'
POOL_WL_UPLINK=1

View File

@ -1,7 +1,5 @@
LOCATION=whitelist LOCATION=whitelist
OPENVPN=1 OPENVPN=1
OVPN_SERVER_HOST="vpn1.corp.example vpn2.corp.example"
OVPN_ROUTES="10.20.0.0/16 172.16.5.0/24"
TAILSCALE=1 TAILSCALE=1
TS_EXIT=1 TS_EXIT=1
TS_DOMAINS="corp.example internal.example" TS_DOMAINS="corp.example internal.example"
@ -19,6 +17,6 @@ HY2_DE_2_PASSWORD=x
HY2_DE_2_SNI=www.bing.com HY2_DE_2_SNI=www.bing.com
HY2_DE_2_INSECURE=1 HY2_DE_2_INSECURE=1
TS_CHECK_URL=http://100.69.216.50:8080/ TS_CHECK_URL=http://100.69.216.50:8080/
OVPN_CHECK_URL=https://intranet.corp.example/ OVPN_CHECK_URL=https://lks.bmstu.ru/
RU_DOMAINS="*.example.com" RU_DOMAINS="*.example.com"
MY_IPS="10.8.0.0/24" MY_IPS="10.8.0.0/24"

Binary file not shown.

View File

@ -1,11 +0,0 @@
# zapret hostlist
youtube.com
YouTu.be
googlevideo.com # video
^exact.example
*.wild.example
.dot.example
youtube.com
bad domain!
1.2.3.4

View File

@ -233,7 +233,7 @@
}, },
{ {
"name": "hu", "name": "hu",
"network": "ws", "network": "httpupgrade",
"port": "443", "port": "443",
"server": "example.com", "server": "example.com",
"type": "vless", "type": "vless",
@ -246,7 +246,6 @@
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36" "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
}, },
"path": "/u", "path": "/u",
"v2ray-http-upgrade": true,
"v2ray-http-upgrade-fast-open": true "v2ray-http-upgrade-fast-open": true
}, },
"xudp": true "xudp": true
@ -456,7 +455,7 @@
"alterId": 0, "alterId": 0,
"cipher": "auto", "cipher": "auto",
"name": "hu-01", "name": "hu-01",
"network": "ws", "network": "httpupgrade",
"port": "443", "port": "443",
"server": "v.example.com", "server": "v.example.com",
"skip-cert-verify": false, "skip-cert-verify": false,
@ -468,7 +467,6 @@
"early-data-header-name": "X", "early-data-header-name": "X",
"headers": {}, "headers": {},
"path": "/u?eh=X", "path": "/u?eh=X",
"v2ray-http-upgrade": true,
"v2ray-http-upgrade-fast-open": true "v2ray-http-upgrade-fast-open": true
}, },
"xudp": true "xudp": true
@ -530,24 +528,6 @@
"path": "/ws" "path": "/ws"
} }
}, },
{
"client-fingerprint": "chrome",
"name": "tr-hu",
"network": "ws",
"password": "pw",
"port": "443",
"server": "t.example.org",
"skip-cert-verify": false,
"type": "trojan",
"udp": true,
"ws-opts": {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36"
},
"path": "/hu",
"v2ray-http-upgrade": true
}
},
{ {
"client-fingerprint": "chrome", "client-fingerprint": "chrome",
"name": "tr-badbool", "name": "tr-badbool",

View File

@ -28,7 +28,6 @@ vmess://eyJ2IjoiMiIsImFkZCI6Im5vbmFtZS5leGFtcGxlLmNvbSIsInBvcnQiOiI0NDMiLCJpZCI6
vmess://uuid@aead.example.com:443?encryption=aes-128-gcm&type=ws&path=%2Fa&host=h&security=tls#aead vmess://uuid@aead.example.com:443?encryption=aes-128-gcm&type=ws&path=%2Fa&host=h&security=tls#aead
trojan://pw@t.example.org:443?sni=t.example.org&type=grpc&serviceName=g&allowInsecure=1&alpn=h2#tr trojan://pw@t.example.org:443?sni=t.example.org&type=grpc&serviceName=g&allowInsecure=1&alpn=h2#tr
trojan://p%40w@t.example.org:443?type=ws&path=%2Fws&fp=safari&pcs=deadbeef#tr-ws trojan://p%40w@t.example.org:443?type=ws&path=%2Fws&fp=safari&pcs=deadbeef#tr-ws
trojan://pw@t.example.org:443?type=httpupgrade&path=%2Fhu#tr-hu
trojan://pw@t.example.org:443?allowInsecure=yes#tr-badbool trojan://pw@t.example.org:443?allowInsecure=yes#tr-badbool
ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#ss1 ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#ss1
ss://YWVzLTI1Ni1nY206cGFzcw==@1.2.3.4:8389#ss-padded ss://YWVzLTI1Ni1nY206cGFzcw==@1.2.3.4:8389#ss-padded

View File

@ -1,196 +0,0 @@
diff --git a/adapter/outbound/reality.go b/adapter/outbound/reality.go
index 70c7bc7a..2796c9bc 100644
--- a/adapter/outbound/reality.go
+++ b/adapter/outbound/reality.go
@@ -6,6 +6,8 @@ import (
"encoding/hex"
"errors"
"fmt"
+ "strconv"
+ "strings"
tlsC "github.com/metacubex/mihomo/component/tls"
)
@@ -15,12 +17,28 @@ type RealityOptions struct {
ShortID string `proxy:"short-id,omitempty"`
SupportX25519MLKEM768 bool `proxy:"support-x25519mlkem768,omitempty"`
+
+ // Xray version reported to the server, "x.y.z" (default tlsC.RealityDefaultClientVersion)
+ ClientVersion string `proxy:"client-version,omitempty"`
}
func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
if o.PublicKey != "" {
config := new(tlsC.RealityConfig)
config.SupportX25519MLKEM768 = o.SupportX25519MLKEM768
+ if o.ClientVersion != "" {
+ parts := strings.Split(o.ClientVersion, ".")
+ if len(parts) != 3 {
+ return nil, errors.New("invalid REALITY client-version, want x.y.z")
+ }
+ for i, part := range parts {
+ n, err := strconv.ParseUint(part, 10, 8)
+ if err != nil {
+ return nil, errors.New("invalid REALITY client-version, want x.y.z (each 0-255)")
+ }
+ config.ClientVersion[i] = byte(n)
+ }
+ }
const x25519ScalarSize = 32
publicKey, err := base64.RawURLEncoding.DecodeString(o.PublicKey)
diff --git a/adapter/outbound/reality_version_test.go b/adapter/outbound/reality_version_test.go
new file mode 100644
index 00000000..444e50c7
--- /dev/null
+++ b/adapter/outbound/reality_version_test.go
@@ -0,0 +1,22 @@
+package outbound
+
+import "testing"
+
+func TestRealityClientVersion(t *testing.T) {
+ base := RealityOptions{PublicKey: "Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns", ShortID: "ab"}
+ c, err := base.Parse()
+ if err != nil || c.ClientVersion != [3]byte{} {
+ t.Fatalf("no client-version: %v %v", c, err)
+ }
+ o := base
+ o.ClientVersion = "25.3.6"
+ if c, err = o.Parse(); err != nil || c.ClientVersion != [3]byte{25, 3, 6} {
+ t.Fatalf("25.3.6: %v %v", c, err)
+ }
+ for _, bad := range []string{"1.8", "1.8.2.4", "a.b.c", "256.0.0", "-1.0.0"} {
+ o.ClientVersion = bad
+ if _, err = o.Parse(); err == nil {
+ t.Fatalf("%q accepted", bad)
+ }
+ }
+}
diff --git a/component/tls/reality.go b/component/tls/reality.go
index ff6a0a3d..d2bc3b3b 100644
--- a/component/tls/reality.go
+++ b/component/tls/reality.go
@@ -28,11 +28,19 @@ import (
const RealityMaxShortIDLen = 8
+// RealityDefaultClientVersion is the Xray version a REALITY client reports in the
+// session ID. Upstream sends 1.8.2; servers with minClientVer above it (set by some
+// panels) reject that while Xray clients pass, so report a current Xray release.
+var RealityDefaultClientVersion = [3]byte{26, 10, 21}
+
type RealityConfig struct {
PublicKey *ecdh.PublicKey
ShortID [RealityMaxShortIDLen]byte
SupportX25519MLKEM768 bool
+
+ // ClientVersion: x.y.z reported to the server; zero = RealityDefaultClientVersion
+ ClientVersion [3]byte
}
func GetRealityConn(ctx context.Context, conn net.Conn, fingerprint UClientHelloID, serverName string, realityConfig *RealityConfig) (net.Conn, error) {
@@ -71,9 +79,11 @@ func GetRealityConn(ctx context.Context, conn net.Conn, fingerprint UClientHello
binary.BigEndian.PutUint64(hello.SessionId, uint64(ntp.Now().Unix()))
copy(hello.SessionId[8:], realityConfig.ShortID[:])
- hello.SessionId[0] = 1
- hello.SessionId[1] = 8
- hello.SessionId[2] = 2
+ version := realityConfig.ClientVersion
+ if version == [3]byte{} {
+ version = RealityDefaultClientVersion
+ }
+ copy(hello.SessionId[:3], version[:])
//log.Debugln("REALITY hello.sessionId[:16]: %v", hello.SessionId[:16])
diff --git a/component/tls/reality_version_test.go b/component/tls/reality_version_test.go
new file mode 100644
index 00000000..31389118
--- /dev/null
+++ b/component/tls/reality_version_test.go
@@ -0,0 +1,81 @@
+package tls
+
+import (
+ "context"
+ "crypto/ecdh"
+ "crypto/rand"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ utls "github.com/metacubex/utls"
+)
+
+func TestRealityDefaultClientVersion(t *testing.T) {
+ if RealityDefaultClientVersion == [3]byte{} || RealityDefaultClientVersion == [3]byte{1, 8, 2} {
+ t.Fatal("the default must be a current Xray version, not upstream's 1.8.2")
+ }
+}
+
+// a REALITY server with minClientVer (as some panels set it): the reported client
+// version decides whether the handshake authenticates
+func TestRealityMinClientVer(t *testing.T) {
+ key, err := ecdh.X25519().GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // the "dest" site REALITY mirrors (and relays failed probes to)
+ dest := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ defer dest.Close()
+ var shortID [8]byte
+ copy(shortID[:], []byte{0x52, 0x97})
+ server := &utls.RealityConfig{
+ Type: "tcp",
+ Dest: dest.Listener.Addr().String(),
+ ServerNames: map[string]bool{"www.example.com": true},
+ PrivateKey: key.Bytes(),
+ ShortIds: map[[8]byte]bool{shortID: true},
+ DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, network, address)
+ },
+ Log: t.Logf,
+ MinClientVer: []byte{25, 0, 0},
+ }
+ server.SessionTicketsDisabled = true
+ fp, _ := GetFingerprint("chrome")
+
+ try := func(version [3]byte) error {
+ c, s := net.Pipe()
+ defer c.Close()
+ defer s.Close()
+ go func() {
+ if conn, err := utls.RealityServer(context.Background(), s, server); err == nil {
+ conn.Write([]byte("ok"))
+ }
+ s.Close()
+ }()
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ conn, err := GetRealityConn(ctx, c, fp, "www.example.com", &RealityConfig{
+ PublicKey: key.PublicKey(), ShortID: shortID, ClientVersion: version,
+ })
+ if err != nil {
+ return err
+ }
+ buf := make([]byte, 2)
+ _, err = conn.Read(buf)
+ return err
+ }
+
+ if err := try([3]byte{1, 8, 2}); err == nil {
+ t.Fatal("version 1.8.2 (upstream mihomo) passed a server with minClientVer 25.0.0")
+ }
+ if err := try([3]byte{}); err != nil {
+ t.Fatalf("the default version: %v", err)
+ }
+ if err := try([3]byte{25, 3, 6}); err != nil {
+ t.Fatalf("client-version 25.3.6: %v", err)
+ }
+}

View File

@ -1,140 +0,0 @@
<!doctype html>
<!-- The config graph (luci/graph.js) without the router: open this file from the repo,
pick or drop any mihomo config. Live state: the router's mihomo API address and secret
(LuCI → mihomo-kit, the dashboard link has both); mihomo allows any origin by default. -->
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mihomo graph</title>
<style>
:root { color-scheme: light dark; --bg: #fff; --fg: #1f2328; --mute: #6b7280; --b: #c9ced6; }
@media (prefers-color-scheme: dark) { :root { --bg: #16181d; --fg: #e6e8eb; --mute: #9aa1ab; --b: #454c57; } }
body { margin: 0; padding: 12px 16px; background: var(--bg); color: var(--fg); font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; }
h1 { font-size: 16px; margin: 0 0 8px; }
.top { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; margin-bottom: 8px; }
.top input[type=text], .top input[type=password] { width: 14em; padding: 3px 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--b); border-radius: 4px; }
button { padding: 3px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--b); border-radius: 4px; cursor: pointer; }
.hint { color: var(--mute); }
#drop { border: 2px dashed var(--b); border-radius: 6px; padding: 24px; text-align: center; color: var(--mute); }
#drop.over { border-color: #4c7cf0; }
textarea { width: 100%; box-sizing: border-box; font: 12px monospace; background: var(--bg); color: var(--fg); border: 1px solid var(--b); border-radius: 4px; }
#err { color: #e03131; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Граф конфига mihomo</h1>
<div class="top">
<input type="file" id="file" accept=".yaml,.yml,.txt">
<button id="paste">Вставить текст</button>
<span class="hint">API:</span>
<input type="text" id="api" placeholder="http://192.168.1.1:9090">
<input type="password" id="secret" placeholder="secret">
<button id="connect">Подключить</button>
<span id="apiState" class="hint"></span>
</div>
<div id="pasteBox" style="display:none;margin-bottom:8px">
<textarea id="text" rows="10" placeholder="proxies: …"></textarea>
<button id="show">Показать</button>
</div>
<div id="drop">Перетащи сюда конфиг mihomo (.yaml) или выбери файл</div>
<div id="err"></div>
<div id="graph"></div>
<script src="../luci/servers.js"></script>
<script src="../luci/graph.js"></script>
<script>
(function() {
var $ = function(id) { return document.getElementById(id); };
var g = null, timer = null;
var store = function(k, v) {
try {
if (v === undefined)
return localStorage.getItem('mkg-' + k) || '';
localStorage.setItem('mkg-' + k, v);
} catch (e) {
return '';
}
};
$('api').value = store('api');
var show = function(text) {
$('err').textContent = '';
try {
var cfg = mkServers.yamlLoad(text);
if (!cfg || typeof cfg != 'object' || !cfg.rules && !cfg['proxy-groups'])
throw new Error('не похоже на конфиг mihomo: нет rules и proxy-groups');
if (!g)
g = mkGraph.view($('graph'), act);
g.show(cfg);
$('drop').style.display = 'none';
} catch (e) {
$('err').textContent = 'Не разобрал: ' + e.message;
}
};
var read = function(f) {
var r = new FileReader();
r.onload = function() { show(r.result); };
r.readAsText(f);
};
$('file').addEventListener('change', function() { if (this.files[0]) read(this.files[0]); });
$('paste').addEventListener('click', function() {
$('pasteBox').style.display = $('pasteBox').style.display == 'none' ? '' : 'none';
});
$('show').addEventListener('click', function() { show($('text').value); });
var drop = $('drop');
document.addEventListener('dragover', function(e) { e.preventDefault(); drop.classList.add('over'); });
document.addEventListener('dragleave', function() { drop.classList.remove('over'); });
document.addEventListener('drop', function(e) {
e.preventDefault();
drop.classList.remove('over');
if (e.dataTransfer.files[0])
read(e.dataTransfer.files[0]);
});
// live: /proxies and /providers/proxies every 10 s, /connections every 2 s
var api = function(path, method, body) {
var base = $('api').value.trim().replace(/\/+$/, ''), sec = $('secret').value, h = {};
if (sec)
h.Authorization = 'Bearer ' + sec;
if (body)
h['Content-Type'] = 'application/json';
return fetch(base + path, { method: method || 'GET', headers: h, body: body ? JSON.stringify(body) : undefined }).then(function(r) {
if (!r.ok)
return r.json().catch(function() { return {}; }).then(function(j) {
throw new Error(j.message || path + ': HTTP ' + r.status);
});
return r.status == 204 ? {} : r.json();
});
};
// the choice in the groups, once connected to the API
var act = {
select: function(g, name) { return api('/proxies/' + encodeURIComponent(g), 'PUT', { name: name }); },
unfix: function(g) { return api('/proxies/' + encodeURIComponent(g), 'DELETE'); },
delay: function(g, url) {
return api('/group/' + encodeURIComponent(g) + '/delay?timeout=5000&url=' +
encodeURIComponent(url || 'https://www.gstatic.com/generate_204'));
},
refresh: function() { return Promise.resolve(); }
};
$('connect').addEventListener('click', function() {
store('api', $('api').value.trim());
if (timer)
clearTimeout(timer);
if (!g)
return ($('apiState').textContent = 'сначала конфиг');
var tick = 0;
var loop = function() {
var full = tick++ % 5 == 0;
Promise.all([ full ? api('/proxies') : null, api('/connections'), full ? api('/providers/proxies') : null ]).then(function(r) {
g.live(r[0] && r[0].proxies, r[1].connections || [], r[2] && r[2].providers);
$('apiState').textContent = 'подключено';
}).catch(function(e) {
$('apiState').textContent = 'ошибка: ' + e.message;
}).then(function() { timer = setTimeout(loop, 2000); });
};
loop();
});
})();
</script>
</body>
</html>

View File

@ -1,103 +0,0 @@
#!/bin/sh
# Mirror an OpenWrt-nikki release into the kit repo's releases: the router installs
# nikki from there (router/mihomo-kit.sh nikki_feed), GitHub is often unreachable.
# GITEA_TOKEN=... tools/nikki-mirror.sh [v1.26.2|latest] [arch...]
# Each nikki_<arch>-openwrt-24.10.tar.gz is a signed opkg feed; it is repacked without
# mihomo-alpha and the zh translations (less RAM on the router, Packages and its
# signature unchanged) and uploaded to the release nikki-<version>, made if missing.
# No arch = all of the release. Assets already there are skipped.
# Then set NIKKI_VERSION in router/mihomo-kit.sh and push the kit.
# Needs curl, jq, tar, gzip.
set -eu
ver=${1:-latest}
[ $# -gt 0 ] && shift
: "${GITEA_TOKEN:?set GITEA_TOKEN (Settings -> Applications, scope write:repository)}"
GITEA=${GITEA:-https://git.sam-hub.net}
REPO=${REPO:-sam/mihomo-kit}
UPSTREAM=nikkinikki-org/OpenWrt-nikki
BRANCH=openwrt-24.10
cd "$(dirname "$0")"
work=$(pwd)/nikki-work
rm -rf "$work"
mkdir -p "$work"
trap 'rm -rf "$work"' EXIT
if [ "$ver" = latest ]; then
api=https://api.github.com/repos/$UPSTREAM/releases/latest
else
api=https://api.github.com/repos/$UPSTREAM/releases/tags/$ver
fi
curl -fsSL "$api" > "$work/upstream.json"
ver=$(jq -r .tag_name "$work/upstream.json")
tag=nikki-$ver
echo "upstream $ver -> $GITEA/$REPO release $tag"
# the token through a config file, not argv (ps); timeouts: an upload may stall
umask 077
printf 'header = "Authorization: token %s"\n' "$GITEA_TOKEN" > "$work/curlrc"
gitea() { curl -K "$work/curlrc" -fsS --connect-timeout 20 "$@"; }
api=$GITEA/api/v1/repos/$REPO
if ! gitea -m 60 "$api/releases/tags/$tag" > "$work/release.json" 2>/dev/null; then
jq -n --arg t "$tag" --arg v "$ver" '{tag_name: $t, name: $t, target_commitish: "main",
body: ("Зеркало https://github.com/nikkinikki-org/OpenWrt-nikki/releases/tag/" + $v +
" для установки nikki на роутер (без mihomo-alpha и переводов zh).")}' |
gitea -m 60 -X POST -H 'Content-Type: application/json' -d @- \
"$api/releases" > "$work/release.json"
echo "created release $tag"
fi
id=$(jq -r .id "$work/release.json")
have=$(jq -r '.assets[]?.name' "$work/release.json")
jq -r --arg b "$BRANCH" '.assets[] | select(.name | endswith("-" + $b + ".tar.gz")) |
"\(.name) \(.browser_download_url)"' "$work/upstream.json" > "$work/list"
if [ $# -gt 0 ]; then
for a in "$@"; do grep "^nikki_$a-$BRANCH.tar.gz " "$work/list" || echo "warning: no bundle for $a" >&2; done \
> "$work/list.sel"
mv "$work/list.sel" "$work/list"
fi
[ -s "$work/list" ] || { echo "nothing to mirror" >&2; exit 1; }
while read -r name url; do
if printf '%s\n' "$have" | grep -qx "$name"; then
echo "$name: already there"
continue
fi
echo "$name: downloading"
d=$work/b
rm -rf "$d"
mkdir -p "$d"
curl -fSL --connect-timeout 20 -m 600 --retry 3 --progress-bar "$url" | tar xzf - -C "$d"
[ -f "$d/Packages.gz" ] && [ -f "$d/Packages.sig" ] || { echo "$name: not a feed" >&2; exit 1; }
rm -f "$d"/mihomo-alpha_*.ipk "$d"/luci-i18n-nikki-zh-*.ipk
# ustar, no owner names: busybox tar on the router
(cd "$d" && tar --format ustar --owner 0 --group 0 -cf - .) | gzip -9 > "$work/$name"
size=$(wc -c < "$work/$name")
ok=
for try in 1 2 3; do
echo "$name: uploading $(du -h "$work/$name" | cut -f1) (try $try)"
# progress bar on the terminal, then the average speed
curl -K "$work/curlrc" -fS --connect-timeout 20 -m 600 --progress-bar -o /dev/null \
-w '%{time_total} %{speed_upload}\n' \
-X POST -F "attachment=@$work/$name" "$api/releases/$id/assets?name=$name" |
awk -v n="$name" '{printf "%s: sent in %ds, %.2f MB/s\n", n, $1, $2 / 1048576}' || true
# what the server has now: right size = done, anything else = remove and retry
gitea -m 60 "$api/releases/$id/assets" > "$work/assets.json" || continue
jq -r --arg n "$name" --argjson s "$size" '.[] | select(.name == $n) |
"\(.id) \(if .size == $s then "ok" else "bad" end)"' "$work/assets.json" > "$work/same"
if grep -q ' ok$' "$work/same"; then
# a stalled try may have landed too: keep one copy
grep ' ok$' "$work/same" | tail -n +2 | while read -r a _; do
gitea -m 60 -X DELETE "$api/releases/$id/assets/$a"; done
ok=1
break
fi
while read -r a _; do gitea -m 60 -X DELETE "$api/releases/$id/assets/$a"; done < "$work/same"
done
rm -f "$work/$name"
[ -n "$ok" ] || { echo "$name: upload failed 3 times, run again later" >&2; exit 1; }
done < "$work/list"
echo "done: $GITEA/$REPO/releases/tag/$tag"
grep -q "^NIKKI_VERSION=$ver\$" ../router/mihomo-kit.sh ||
echo "now set NIKKI_VERSION=$ver in router/mihomo-kit.sh and push the kit"

View File

@ -1,83 +0,0 @@
#!/usr/bin/env node
// Fixed exits must survive profile changes, preserve provider identity and chain
// suffixes, and fail closed if a node/source disappears. Render actual shell code.
const fs = require('fs'), os = require('os'), path = require('path');
const { spawnSync } = require('child_process');
const assert = require('assert');
const S = require('../luci/servers.js'), G = require('../luci/graph.js');
const root = path.resolve(__dirname, '..');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'kit-fixed-'));
const q = v => "'" + String(v).replace(/'/g, "'\\''") + "'";
function render(values, ok = true) {
const env = path.join(tmp, 'profile.env');
fs.writeFileSync(env, Object.entries(values).map(([k,v])=>k+'='+q(v)).join('\n')+'\n');
const r = spawnSync('sh', ['router/mihomo-kit.sh','render','tests/fixtures/common.env',env], {cwd:root,encoding:'utf8'});
if (!ok) { assert.notEqual(r.status,0,'invalid settings accepted'); return; }
assert.equal(r.status,0,r.stderr);
const cfg = S.yamlLoad(r.stdout);
assert.deepEqual(G.model(cfg).warnings,[]);
if (process.env.MIHOMO) {
// The renderer's config is real YAML; validate the fixed groups with the actual
// core as well. Avoid unrelated remote rule sets/geodata in this small config.
const config = path.join(tmp,'core.yaml');
fs.writeFileSync(config,JSON.stringify({proxies:cfg.proxies,'proxy-groups':cfg['proxy-groups'],'proxy-providers':cfg['proxy-providers'],rules:['MATCH,DIRECT']}));
const t=spawnSync(process.env.MIHOMO,['-t','-d',tmp,'-f',config],{encoding:'utf8'});
assert.equal(t.status,0,t.stdout+'\n'+t.stderr);
}
return cfg;
}
const nodeName = '[MY] 🇨🇭 one (a).+$ [x] `q`';
const group = (cfg,n) => cfg['proxy-groups'].find(g=>g.name===n);
const defaults = {
MY_SERVERS_FILE:'tests/fixtures/own.servers',
SERVICES:'fixed sub chain gone normal',
SVC_FIXED_DOMAINS:'fixed.example', SVC_FIXED_SERVER:'tr "q"',
SVC_SUB_DOMAINS:'subfixed.example', SVC_SUB_SERVER:nodeName, SVC_SUB_PROVIDER:'example-my',
SVC_CHAIN_DOMAINS:'chain.example', SVC_CHAIN_SERVER:nodeName, SVC_CHAIN_PROVIDER:'example-my', SVC_CHAIN_CHAIN:'FOREIGN',
SVC_GONE_DOMAINS:'gone.example', SVC_GONE_SERVER:'server removed',
SVC_NORMAL_DOMAINS:'normal.example', SVC_NORMAL_VIA:'MY'
};
try {
for (const [TARGET,LOCATION] of [['router','main'],['router','whitelist'],['router','foreign'],['mobile','main']]) {
const c=render({...defaults,TARGET,LOCATION});
assert.deepEqual(group(c,'FIXED').proxies,['SVC-FIXED-FIXED']);
assert.deepEqual(group(c,'SVC-FIXED-FIXED').proxies,['tr "q"']);
assert.equal(group(c,'NORMAL').type,'fallback');
assert.deepEqual(group(c,'SVC-FIXED-GONE').proxies,['REJECT']);
const pg=group(c,'SVC-FIXED-SUB');
assert.deepEqual(pg.use,['example-my']);
assert.equal(pg['empty-fallback'],'REJECT');
const regex = new RegExp(pg.filter);
assert(regex.test(nodeName));
assert(!regex.test(nodeName+' copy'));
assert(!regex.test('copy '+nodeName));
assert(!regex.test(nodeName.replace('.','X')));
const cg=group(c,'SVC-FIXED-CHAIN ⟶ FOREIGN');
assert.deepEqual(group(c,'CHAIN').proxies,[cg.name]);
assert.deepEqual(cg.use,['example-my@FOREIGN']);
assert.equal(cg['empty-fallback'],'REJECT');
assert(new RegExp(cg.filter).test(nodeName+' ⟶ FOREIGN'));
assert(!new RegExp(cg.filter).test(nodeName+' copy ⟶ FOREIGN'));
const own=c.proxies.find(p=>p.name==='tr "q"');
assert.equal(own['dialer-proxy'], TARGET==='mobile'||LOCATION==='whitelist'?'MY-EXIT':undefined);
console.log('ok fixed service '+TARGET+'/'+LOCATION);
}
const c=render({...defaults,SUB_EXAMPLE_DISABLED:'1'});
assert.deepEqual(group(c,'SVC-FIXED-SUB').proxies,['REJECT']);
assert.deepEqual(group(c,'SVC-FIXED-CHAIN ⟶ FOREIGN').proxies,['REJECT']);
const ownChain=render({...defaults,CSQTT:'1',SVC_FIXED_CHAIN:'DIRECT'});
const og=group(ownChain,'SVC-FIXED-FIXED ⟶ DIRECT');
assert.deepEqual(og.proxies,['tr "q" ⟶ DIRECT']);
assert.equal(ownChain.proxies.find(p=>p.name==='tr "q" ⟶ DIRECT')['dialer-proxy'],undefined);
render({...defaults,SVC_SUB_PROVIDER:'bad|source'},false);
render({...defaults,SVC_SUB_SERVER:''},false);
render({...defaults,POOLS:'svc_fixed_fixed',POOL_SVC_FIXED_FIXED_SERVERS:'hy-own'},false);
// Shell metacharacters remain data; they must not be evaluated by generated keys.
const injection='$(touch '+path.join(tmp,'injected')+') "quote"';
const missing=render({...defaults,SVC_FIXED_SERVER:injection});
assert(!fs.existsSync(path.join(tmp,'injected')));
assert.deepEqual(group(missing,'SVC-FIXED-FIXED').proxies,['REJECT']);
console.log('ok fixed service missing source, explicit entry, invalid settings and shell quoting');
} finally {
fs.rmSync(tmp,{recursive:true,force:true});
}

View File

@ -1,95 +0,0 @@
#!/usr/bin/env node
// luci/graph.js on the rendered profiles (tests/expected/*.yaml): every name resolves,
// the layout has no overlaps and runs left to right, and live() follows a connection
// through the groups' choice and the dialer-proxy chain.
const fs = require("fs");
const path = require("path");
const S = require("../luci/servers.js");
const G = require("../luci/graph.js");
let fail = 0;
const check = (name, ok, msg) => {
if (ok)
return;
fail = 1;
console.log("FAIL " + name + ": " + msg);
};
const dir = path.join(__dirname, "..", "tests", "expected");
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) {
const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, f), "utf8"));
const m = G.model(cfg);
check(f, !m.warnings.length, m.warnings.join("; "));
check(f, m.list.filter((n) => n.kind == "rule").length > 0, "no rule nodes");
const lay = G.layout(m);
const cols = {};
for (const n of m.list) {
const b = lay.nodes[n.id];
check(f, b && [b.x, b.y, b.w, b.h].every(Number.isFinite), "no position for " + n.id);
(cols[b.x] = cols[b.x] || []).push(b);
}
for (const x in cols) {
const c = cols[x].sort((a, b) => a.y - b.y);
for (let i = 1; i < c.length; i++)
check(f, c[i].y >= c[i - 1].y + c[i - 1].h - 0.01, "nodes overlap in column x=" + x);
}
const lastX = Math.max(...m.list.map((n) => lay.nodes[n.id].x));
for (const n of m.list) {
const b = lay.nodes[n.id];
if (n.exit)
check(f, b.x == lastX, n.id + " is an exit but not in the last column");
if (b.aux)
check(f, lay.lane != null && b.y > lay.lane, n.id + " is not under the lane");
// every proxy and subscription goes somewhere: through a dialer or directly
if ((n.kind == "proxy" && !n.exit) || n.kind == "provider")
check(f, m.dialerOf[n.id], n.id + " has no way out");
}
if (cfg["proxy-groups"].some((g) => g.name == "BOOT-AUTO"))
check(f, lay.nodes["g:BOOT-AUTO"].aux, "BOOT-AUTO is not in the lane");
for (const le of lay.edges)
if (le.pts)
for (let i = 1; i < le.pts.length; i++)
check(f, le.pts[i].x > le.pts[i - 1].x, "edge runs right to left: " + le.e.from + " -> " + le.e.to);
if (!fail)
console.log("ok graph " + f + " (" + m.list.length + " nodes, " + lay.ranks + " columns)");
}
// live: a connection by MATCH through MAIN -> FOREIGN -> a node of "example", which dials
// through UPLINK -> CSQTT (router-csqtt: subscription nodes with dialer-proxy UPLINK)
{
const cfg = S.yamlLoad(fs.readFileSync(path.join(dir, "router-csqtt.yaml"), "utf8"));
const m = G.model(cfg);
// /proxies: groups and the config's proxies; the subscriptions' nodes only in /providers/proxies
const proxies = {
MAIN: { type: "Selector", now: "FOREIGN", all: ["FOREIGN", "DIRECT"] },
FOREIGN: { type: "URLTest", now: "nl-1", all: ["nl-1", "de-1"], fixed: "nl-1" },
UPLINK: { type: "Selector", now: "CSQTT" }, CSQTT: { history: [] },
};
const providers = {
example: { proxies: [{ name: "nl-1", alive: true, history: [{ delay: 42 }] }, { name: "de-1", alive: false }] },
example2: { proxies: [{ name: "nl-1", alive: true }] },
default: { proxies: [{ name: "MAIN" }] },
};
const conns = [
{ id: "c1", rule: "Match", rulePayload: "", chains: ["nl-1", "FOREIGN", "MAIN"], upload: 10, download: 20 },
{ id: "c2", rule: "", rulePayload: "", chains: ["DIRECT"] },
{ id: "c3", rule: "RuleSet", rulePayload: "ru-inside", chains: ["DIRECT"] },
];
const L = G.live(m, proxies, conns, null, providers);
const match = m.ruleIndex["match|"];
const want = [match, "g:MAIN", "g:FOREIGN", "v:example", "g:UPLINK", "p:CSQTT"];
const got = Object.keys(L.nodes);
check("live", want.every((id) => L.nodes[id] && L.nodes[id].n == 1), "path " + JSON.stringify(got) + ", want " + JSON.stringify(want));
check("live", Object.keys(L.edges).length == want.length - 1, "edges on the path: " + Object.keys(L.edges).length);
check("live", L.nodes["b:DIRECT"] && L.nodes["b:DIRECT"].byRule == 1, "rule straight to DIRECT counted at DIRECT");
check("live", L.groups["g:FOREIGN"].fixed == "nl-1", "fixed of FOREIGN");
const mem = L.members("g:FOREIGN");
check("live", mem.length == 2 && mem[0].delay == 42 && mem[1].alive === false, "members of FOREIGN: " + JSON.stringify(mem));
check("live", L.provider["v:example"] && L.provider["v:example"].alive == 1 && L.provider["v:example"].n == 2, "alive nodes of example");
check("live", L.nowProv["g:FOREIGN"] == "v:example", "FOREIGN's choice comes from example: " + L.nowProv["g:FOREIGN"]);
check("live", L.internal == 1 && L.unmatched == 0, "internal " + L.internal + ", unmatched " + JSON.stringify(L.unmatchedRules));
check("live", L.delay["g:FOREIGN"] == 42, "delay of FOREIGN's choice");
if (!fail)
console.log("ok graph live");
}
process.exit(fail);

View File

@ -34,19 +34,9 @@ for (const f of fs.readdirSync(path.join(root, "yaml"))) {
// the editor shows yamlDump; it must read back the same // the editor shows yamlDump; it must read back the same
check("yaml/" + f + " (dump)", want, s.yamlLoad(s.yamlDump(got))); check("yaml/" + f + " (dump)", want, s.yamlLoad(s.yamlDump(got)));
} }
// WireGuard / AmneziaWG .conf and AmneziaVPN keys (vpn://): parseText with the file name // a stored line reads back the same, without dialer-proxy, with no "$" left
// as the default name; tests/amnezia/<x>.expected.json is checked by hand and with
// `mihomo -t` (key.vpn and keys.txt: qCompress'd JSON as the AmneziaVPN client makes it)
for (const f of fs.readdirSync(path.join(root, "amnezia"))) {
if (f.endsWith(".expected.json"))
continue;
const exp = path.join(root, "amnezia", f.replace(/\.[^.]+$/, ".expected.json"));
check("amnezia/" + f, JSON.parse(fs.readFileSync(exp, "utf8")),
s.parseText(fs.readFileSync(path.join(root, "amnezia", f), "utf8"), f.replace(/\.[^.]+$/, "")));
}
// a stored line reads back the same (dialer-proxy: the server's own entry), with no "$" left
const p = { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}", "dialer-proxy": "Z" }; const p = { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}", "dialer-proxy": "Z" };
const line = s.toLine(p); const line = s.toLine(p);
check("toLine", { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}", "dialer-proxy": "Z" }, check("toLine", { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}" },
line.includes("$") || !line.startsWith('{"name":') ? null : JSON.parse(line)); line.includes("$") || !line.startsWith('{"name":') ? null : JSON.parse(line));
process.exit(fail); process.exit(fail);

View File

@ -1,8 +1,7 @@
#!/bin/sh #!/bin/sh
# Render every fixture with router/mihomo-kit.sh and compare with tests/expected/, # Render every fixture with router/mihomo-kit.sh and compare with tests/expected/,
# validate with `mihomo -t` when MIHOMO points to a mihomo binary, check # validate with `mihomo -t` when MIHOMO points to a mihomo binary, and check
# luci/servers.js (share links, YAML) against the outputs of mihomo's own Go code, # luci/servers.js (share links, YAML) against the outputs of mihomo's own Go code.
# and luci/graph.js (the config graph) on the rendered profiles.
# tools/test.sh # tools/test.sh
# UPDATE=1 tools/test.sh rewrite tests/expected/ (review the diff) # UPDATE=1 tools/test.sh rewrite tests/expected/ (review the diff)
# MIHOMO=/path/to/mihomo tools/test.sh # MIHOMO=/path/to/mihomo tools/test.sh
@ -11,12 +10,10 @@ cd "$(dirname "$0")/.."
out=$(mktemp -d) out=$(mktemp -d)
fail=0 fail=0
if [ -n "${MIHOMO:-}" ]; then if [ -n "${MIHOMO:-}" ]; then
# rule-sets are fetched over http: put a local copy of each in place for an offline check # rule-sets are fetched over http: put a local copy in place for an offline check
mkdir -p "$out/home/ruleset" mkdir -p "$out/home/ruleset"
echo '+.example.ru' > "$out/domains.txt" echo '+.example.ru' > "$out/ru-inside.txt"
for r in $(sed -n 's|^ *path: \./ruleset/\(.*\.mrs\)$|\1|p' tests/expected/*.yaml | sort -u); do "$MIHOMO" convert-ruleset domain text "$out/ru-inside.txt" "$out/home/ruleset/ru-inside.mrs" >/dev/null
"$MIHOMO" convert-ruleset domain text "$out/domains.txt" "$out/home/ruleset/$r" >/dev/null
done
fi fi
mkdir -p tests/expected mkdir -p tests/expected
for f in tests/fixtures/*.env; do for f in tests/fixtures/*.env; do
@ -40,8 +37,6 @@ for f in tests/fixtures/*.env; do
done done
if command -v node >/dev/null 2>&1; then if command -v node >/dev/null 2>&1; then
node tools/test-servers.js || fail=1 node tools/test-servers.js || fail=1
node tools/test-graph.js || fail=1
node tools/test-fixed-services.js || fail=1
else else
echo "skip luci/servers.js: no node" echo "skip luci/servers.js: no node"
fi fi