Improved custom servers features

This commit is contained in:
Sam Latsin 2026-10-26 15:52:40 +03:00
parent 59f8d43aa0
commit d03040779b
48 changed files with 6878 additions and 1879 deletions

View File

@ -207,25 +207,33 @@ BOOT — whitelisted seed-ноды для скачивания подписок:
Пуши (Apple `*.push.apple.com` и подсети 17.x, Google FCM `mtalk.google.com`, порты Пуши (Apple `*.push.apple.com` и подсети 17.x, Google FCM `mtalk.google.com`, порты
5228–5230) идут через группу `PUSH`: на `main` по умолчанию `DIRECT`, на `whitelist` — `MY` 5228–5230) идут через группу `PUSH`: на `main` по умолчанию `DIRECT`, на `whitelist` — `MY`
(без своих hysteria2 — `FOREIGN`); переключается в дашборде. Долгое соединение пушей (без своих серверов — `FOREIGN`); переключается в дашборде. Долгое соединение пушей
рвётся, когда меняется нода под ним, — отсюда пропадающие уведомления. Отключается рвётся, когда меняется нода под ним, — отсюда пропадающие уведомления. Отключается
галочкой «Обход для пушей» (`PUSH=0` в `common.env`) — тогда пуши идут по общим правилам. галочкой «Обход для пушей» (`PUSH=0` в `common.env`) — тогда пуши идут по общим правилам.
Свои серверы hysteria2 — LuCI → Настройка → «Свои серверы» (или `HY2="имя1 имя2"` и Свои серверы — LuCI → Настройка → «Свои серверы». Каждый сервер — карточка: имя (так он
`HY2_<ИМЯ>_SERVER/_PORT/_PASSWORD/_OBFS_PASSWORD/_SNI/_INSECURE/_UP/_DOWN` в виден в дашборде), тип и адрес, «Настройки (YAML)» — весь сервер в формате mihomo, правится
`common.env`). Они собираются в группу `MY` (url-test: самый быстрый живой; в дашборде на месте. «Добавить из ссылки / YAML» принимает сразу несколько: ссылки `vless://`, `vmess://`,
можно закрепить конкретный). `MY` — пункт в `MAIN` рядом с `FOREIGN` (переключать `trojan://`, `ss://`, `hysteria2://`, `tuic://`, `anytls://` (и `socks5://`, `http(s)://`,
вручную). К самим серверам на `whitelist` подключение через группу `MY-EXIT` (те же ноды, `ssr://`, `hysteria://`, `mierus://`), подписку в base64 или YAML из конфига mihomo / Clash
что в `FOREIGN`, но с `tolerance: 300`: меняет ноду, только если текущая заметно хуже или (список `proxies:`, просто список или один сервер). Ссылки страница разбирает так же, как
умерла — каждая смена рвёт всё, что идёт через `MY`), на `main` — напрямую. mihomo разбирает подписку (`luci/servers.js` — перенос его `common/convert`, `tools/test.sh`
сверяет с ним): reality, xhttp, ws, grpc и прочее — как в приложении. «Скопировать» отдаёт
сервер как YAML для другого роутера.
Свои серверы других протоколов — там же, поле «Ссылки» (или `MY_LINKS` в `common.env`, через Серверы хранятся в `/etc/nikki/my-servers` (права 600, по одному JSON-объекту прокси на
пробел): ссылки `vless://`, `vmess://`, `trojan://`, `ss://`, `hysteria2://`, `tuic://`, строку) и переносятся экспортом настроек. Сборка вписывает их в `proxies:` профилей роутера
`anytls://` как из приложения. Разбирает их само ядро, как подписку (reality, xhttp, ws, и в конфиг телефона и собирает в группу `MY` (url-test: самый быстрый живой; в дашборде
grpc и т. д.): kit при сборке пишет их в `run/providers/my-links.txt` (права 600), его читает можно закрепить конкретный). `MY` — пункт в `MAIN` рядом с `FOREIGN` (переключать
file-провайдер `my-links` в группе `MY`, ноды называются `[MY] <имя из ссылки>`. Пробелы в имени вручную). К самим серверам на `whitelist` и с телефона подключение через группу `MY-EXIT`
после `#` форма заменяет на `%20`. Как и hysteria2, на `whitelist` они идут через `MY-EXIT`. (те же ноды, что в `FOREIGN`, но с `tolerance: 300`: меняет ноду, только если текущая
Только на роутере: в конфиг телефона ссылки не попадают (на телефоне — `[MY]`-ноды подписки). заметно хуже или умерла — каждая смена рвёт всё, что идёт через `MY`), на `main` —
напрямую, с CSQTT — через `UPLINK`. `dialer-proxy` из YAML сервера отбрасывается: его ставит kit.
Старые настройки по-прежнему собираются: hysteria2 по полям (`HY2="имя1 имя2"` и
`HY2_<ИМЯ>_SERVER/_PORT/_PASSWORD/_OBFS_PASSWORD/_SNI/_INSECURE/_UP/_DOWN` в `common.env`) и
ссылки `MY_LINKS` (только роутер, провайдер `my-links`). Страница показывает их карточками и
при сохранении переносит в `my-servers`.
Свои серверы можно держать и в своей подписке: ноды, в имени которых есть `[MY]` Свои серверы можно держать и в своей подписке: ноды, в имени которых есть `[MY]`
(`[MY] 🇩🇪 de-1`, регистр не важен), из любой подписки сами попадают в `MY`, а не в `RU` / (`[MY] 🇩🇪 de-1`, регистр не важен), из любой подписки сами попадают в `MY`, а не в `RU` /
@ -236,7 +244,7 @@ file-провайдер `my-links` в группе `MY`, ноды называю
только их (на телефоне FlClash переносит файлы провайдеров к себе, поэтому там `<имя>-my` только их (на телефоне FlClash переносит файлы провайдеров к себе, поэтому там `<имя>-my`
качает ту же ссылку ещё раз) — свой провайдер нужен, чтобы на `whitelist` и телефоне ходить к ним через качает ту же ссылку ещё раз) — свой провайдер нужен, чтобы на `whitelist` и телефоне ходить к ним через
`MY-EXIT`. Группа `MY` теперь есть `MY-EXIT`. Группа `MY` теперь есть
всегда; без hysteria2, ссылок и `[MY]`-нод она пустая, и `PUSH` на `whitelist` тогда по всегда; без своих серверов и `[MY]`-нод она пустая, и `PUSH` на `whitelist` тогда по
умолчанию `FOREIGN`. умолчанию `FOREIGN`.
CSQTT ([star-panel-csqtt](https://github.com/starkugz/csqtt-openwrt)) — резервный выход из белых CSQTT ([star-panel-csqtt](https://github.com/starkugz/csqtt-openwrt)) — резервный выход из белых
@ -326,12 +334,6 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво
содержит ссылки подписок — токен и есть секрет; «Новая ссылка» (`mihomo-kit.sh mobile new`) содержит ссылки подписок — токен и есть секрет; «Новая ссылка» (`mihomo-kit.sh mobile new`)
отзывает старую. отзывает старую.
Без роутера — веб-конструктор:
Открыть [web/index.html](web/index.html) (из репозитория или со своего хостинга) →
«Телефон» → подписки и vless-ссылка BOOT → «Скачать» → FlClash: Профили → + → Файл.
Страница всё считает в браузере и никуда ничего не отправляет.
## Профили ## Профили
| | роутер `main` | роутер `whitelist` | роутер `foreign` | телефон | | | роутер `main` | роутер `whitelist` | роутер `foreign` | телефон |
@ -345,7 +347,7 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво
| всё остальное (`MAIN`) | `FOREIGN` | `FOREIGN` | напрямую (можно `MY`) | `FOREIGN` | | всё остальное (`MAIN`) | `FOREIGN` | `FOREIGN` | напрямую (можно `MY`) | `FOREIGN` |
| торренты (порты 20000–20199) | ✓ | ✓ | ✓ | — | | торренты (порты 20000–20199) | ✓ | ✓ | ✓ | — |
| OpenVPN | напрямую | через `OVPN-EXIT` (RU-нода) | через `OVPN-EXIT` (RU-нода) | — | | OpenVPN | напрямую | через `OVPN-EXIT` (RU-нода) | через `OVPN-EXIT` (RU-нода) | — |
| Tailscale | напрямую | через `MY` (свои hysteria2 и `[MY]`-ноды подписки), без них напрямую* | напрямую | — | | Tailscale | напрямую | через `MY` (свои серверы и `[MY]`-ноды подписки), без них напрямую* | напрямую | — |
| свои серверы | напрямую | через `MY-EXIT` | напрямую | через `MY-EXIT` | | свои серверы | напрямую | через `MY-EXIT` | напрямую | через `MY-EXIT` |
| пуши (`PUSH`, отключаемо) | `DIRECT` | `MY` | `DIRECT` | — | | пуши (`PUSH`, отключаемо) | `DIRECT` | `MY` | `DIRECT` | — |
@ -449,30 +451,32 @@ opkg сравнивает полный размер новых пакетов с
``` ```
install.sh загрузчик: кит в /etc/nikki/kit + mihomo-kit.sh setup install.sh загрузчик: кит в /etc/nikki/kit + mihomo-kit.sh setup
templates/ фрагменты конфига (общие для скрипта и страницы) 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
bmstu-otp.sh OpenVPN BMSTU: 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, меню,
web/ страница-конструктор: engine.js + index.src.html → index.html servers.js (ссылки и YAML своих серверов), qrcode.js
tools/ push.sh, test.sh, build-web.py, render.js tools/ push.sh, test.sh, test-servers.js, core/ (ядро kit)
tests/fixtures/ профили для test.sh (фиктивные секреты) tests/fixtures/ профили для test.sh (фиктивные секреты), own.servers
tests/expected/ эталонный YAML каждого профиля
tests/links/, yaml/ ссылки и YAML с выводом Go-кода mihomo для luci/servers.js
``` ```
Шаблоны: `templates/<секция>/NN-<модуль>[.<тег>...][.each].yaml`; секции собираются в Шаблоны: `templates/<секция>/NN-<модуль>[.<тег>...][.each].yaml`; секции собираются в
порядке head, proxies, providers, sniffer, dns, groups, rules, файлы — по имени. порядке head, proxies, providers, sniffer, dns, groups, rules, файлы — по имени.
- файл включается, если активны модуль и все теги; `.each` — по разу на элемент модуля - файл включается, если активны модуль и все теги; `.each` — по разу на элемент модуля
(`sub` — подписка: `${SUB_NAME}`, `${SUB_URL}`; `hy2` — свой сервер: `${HY2_NAME}`, ...); (`sub` — подписка: `${SUB_NAME}`, `${SUB_URL}`; `boot` — seed-нода: `${SEED_NAME}`, ...);
- `${@@VAR}` — строка повторяется для каждой строки `VAR` (пустая `VAR` — строки нет); - `${@@VAR}` — строка повторяется для каждой строки `VAR` (пустая `VAR` — строки нет);
- `строка #@тег[,!тег]` — строка остаётся, только если условия выполнены; - `строка #@тег[,!тег]` — строка остаётся, только если условия выполнены;
- `${@VAR}` — строка повторяется для каждого слова из `VAR`; - `${@VAR}` — строка повторяется для каждого слова из `VAR`;
- `${VAR}` — подстановка. - `${VAR}` — подстановка.
Теги: `base`, `sub`, `router`|`mobile`, `main`|`whitelist`|`foreign` (роутер), служебные `ovpn_exit` (whitelist, foreign), `my_exit` (whitelist, телефон), `own` (`hy2` или `my_links`), `boot`, `torrent`, `push`, Теги: `base`, `sub`, `router`|`mobile`, `main`|`whitelist`|`foreign` (роутер), служебные `ovpn_exit` (whitelist, foreign), `my_exit` (whitelist, телефон), `own_srv` (есть свои серверы), `own` (`own_srv` или `my_links`), `boot`, `torrent`, `push`,
`openvpn`, `tailscale`, `ts_exit`, `hy2`, `my_links`, `local_hosts`, `csqtt`, `lite`. Значения по умолчанию — `set_defaults` в `openvpn`, `tailscale`, `ts_exit`, `my_links`, `local_hosts`, `csqtt`, `lite`. Значения по умолчанию — `set_defaults` в
`router/mihomo-kit.sh` и `DEFAULTS` в `web/engine.js` (держать одинаковыми). `router/mihomo-kit.sh`.
### Ядро kit ### Ядро kit
@ -494,9 +498,9 @@ tests/fixtures/ профили для test.sh (фиктивные секре
Новая версия mihomo или новая правка — следующий суффикс (`ts6`) в шагах 1–3. Патчи Новая версия mihomo или новая правка — следующий суффикс (`ts6`) в шагах 1–3. Патчи
применяются по алфавиту; если не накладываются, поправить их на новом теге. применяются по алфавиту; если не накладываются, поправить их на новом теге.
После правки шаблонов или движка: После правки шаблонов, скрипта или `luci/servers.js`:
```sh ```sh
MIHOMO=/path/to/mihomo tools/test.sh # sh и JS дают одинаковый YAML, mihomo -t проходит MIHOMO=/path/to/mihomo tools/test.sh # профили = tests/expected/, mihomo -t проходит, servers.js = Go
tools/build-web.py # пересобрать web/index.html UPDATE=1 tools/test.sh # переписать tests/expected/ (изменения — проверить в diff)
``` ```

View File

@ -97,93 +97,6 @@ function field(title, el, desc) {
]); ]);
} }
// hysteria2 servers from pasted text: mihomo proxy YAML (block or {flow} items,
// with or without "proxies:") and/or hysteria2:// links -> form values.
// dialer-proxy and other keys are ignored: the kit sets them itself.
function parseHy2(text) {
var unquote = function(v) {
v = v.trim();
var m = v.match(/^"((?:[^"\\]|\\.)*)"/);
if (m)
return m[1].replace(/\\(.)/g, '$1');
m = v.match(/^'((?:[^']|'')*)'/);
if (m)
return m[1].replace(/''/g, "'");
return v.replace(/\s+#.*$/, '').trim();
};
var fromMap = function(o) {
if (o.type && !/^(hysteria2|hy2)$/i.test(o.type))
return null;
if (!o.server || !o.password)
return null;
return {
name: o.name || '', server: o.server, port: o.port || '443', password: o.password,
obfs_password: o['obfs-password'] || '', sni: o.sni || '',
insecure: /^(true|1|yes)$/i.test(o['skip-cert-verify'] || '') ? '1' : '0',
up: o.up || '', down: o.down || ''
};
};
var out = [], cur = null;
var flush = function() {
var h = cur && fromMap(cur);
if (h)
out.push(h);
cur = null;
};
String(text).split(/\r?\n/).forEach(function(line) {
var t = line.trim(), m;
if (!t || t.charAt(0) == '#')
return;
// hysteria2://password@host:port/?sni=..&obfs=salamander&obfs-password=..&insecure=1#name
if ((m = t.match(/^(?:hysteria2|hy2):\/\/([^@]*)@([^:\/?#]+|\[[^\]]+\]):?(\d*)[^?#]*(?:\?([^#]*))?(?:#(.*))?$/i))) {
flush();
var q = {};
(m[4] || '').split('&').forEach(function(kv) {
var i = kv.indexOf('=');
if (i > 0)
q[decodeURIComponent(kv.slice(0, i))] = decodeURIComponent(kv.slice(i + 1));
});
var h = fromMap({ name: decodeURIComponent(m[5] || ''), server: m[2].replace(/^\[|\]$/g, ''),
port: m[3], password: decodeURIComponent(m[1]), 'obfs-password': q['obfs-password'] || '',
sni: q.sni || q.peer || '', 'skip-cert-verify': q.insecure || '' });
if (h)
out.push(h);
return;
}
// - {name: a, type: hysteria2, ...}
if ((m = t.match(/^-?\s*\{(.*)\}$/))) {
flush();
cur = {};
m[1].split(',').forEach(function(kv) {
var i = kv.indexOf(':');
if (i > 0)
cur[kv.slice(0, i).trim()] = unquote(kv.slice(i + 1));
});
flush();
return;
}
// "- key: value" starts a new item, "key: value" continues it
if ((m = t.match(/^(-\s+)?([A-Za-z0-9_-]+)\s*:\s*(.*)$/))) {
if (m[1] || !cur) {
flush();
cur = {};
}
if (m[3] !== '')
cur[m[2]] = unquote(m[3]);
}
});
flush();
return out.map(function(h) {
h.name = (h.name || h.server.split('.')[0]).replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'hy2';
return h;
});
}
// 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) if (window.qrcode)
@ -197,22 +110,17 @@ function loadQr() {
}); });
} }
// one hysteria2 server from the form -> mihomo proxy YAML (parseHy2 reads it back) // own servers: luci/servers.js (links and YAML -> proxies), a global "mkServers"
function hy2Yaml(d) { function loadServers() {
var q = function(v) { return '"' + String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'; }; if (window.mkServers)
var y = [ '- name: ' + d.name, ' type: hysteria2', ' server: ' + d.server, ' port: ' + d.port, return Promise.resolve(window.mkServers);
' password: ' + q(d.password) ]; return new Promise(function(resolve, reject) {
if (d.obfs_password) var s = document.createElement('script');
y.push(' obfs: salamander', ' obfs-password: ' + q(d.obfs_password)); s.src = L.resource('mihomo-kit/servers.js');
if (d.sni) s.onload = function() { resolve(window.mkServers); };
y.push(' sni: ' + d.sni); s.onerror = function() { reject(new Error('servers.js not loaded')); };
if (d.insecure) document.head.appendChild(s);
y.push(' skip-cert-verify: true'); });
if (d.up)
y.push(' up: ' + q(d.up));
if (d.down)
y.push(' down: ' + q(d.down));
return y.join('\n') + '\n';
} }
// clipboard: navigator.clipboard needs https, LuCI is usually plain http; // clipboard: navigator.clipboard needs https, LuCI is usually plain http;
@ -573,7 +481,9 @@ return view.extend({
// collapsed: a button; open: the form (always open until configured) // collapsed: a button; open: the form (always open until configured)
renderSettingsBox: function(open) { renderSettingsBox: function(open) {
if (open) if (open)
return callConfigGet().then(L.bind(this.renderSettings, this)); return Promise.all([ callConfigGet(), loadServers() ]).then(L.bind(function(r) {
return this.renderSettings(r[0]);
}, this));
dom.content(this.settingsBox, [ E('h3', 'Настройка'), E('button', { dom.content(this.settingsBox, [ E('h3', 'Настройка'), E('button', {
'class': 'btn cbi-button cbi-button-action', 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function() { return this.renderSettingsBox(true); }) 'click': ui.createHandlerFn(this, function() { return this.renderSettingsBox(true); })
@ -599,8 +509,6 @@ 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'),
my_links: E('textarea', { 'class': 'cbi-input-textarea', 'rows': 3, 'style': 'width:100%;font-family:monospace',
'placeholder': 'vless://…\ntrojan://…\nss://… (по одной на строку)' }, cfg.my_links || ''),
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' }),
@ -651,60 +559,114 @@ return view.extend({
}; };
(cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub); (cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub);
// own hysteria2 servers: one block of fields each // own servers (luci/servers.js): a card each - the name, type and address, the
var hy2List = E('div'), hy2 = []; // proxy as YAML to edit; share links / YAML pasted below become cards
var addHy2 = function(h) { var S = window.mkServers;
var e = { var srvList = E('div'), servers = [];
name: text(h.name, 'nl-1'), var taken = function() {
server: text(h.server, 'vpn.example.com'), var t = {};
port: text(h.port || '443'), servers.forEach(function(e) { t[e.name.value.trim()] = true; });
password: text(h.password, '', 'password'), return t;
obfs_password: text(h.obfs_password, 'пусто — без obfs', 'password'), };
sni: text(h.sni, 'пусто — как server'), var addServer = function(p, open) {
insecure: check(h.insecure == '1'), var e = { proxy: {}, error: null };
up: text(h.up, '50 mbps'), Object.keys(p).forEach(function(k) {
down: text(h.down, '100 mbps') if (k != 'name' && k != 'dialer-proxy')
e.proxy[k] = p[k];
});
e.name = text(S.freeName(p.name, taken()), 'имя в дашборде');
e.name.style.width = '16em';
e.get = function() {
var o = { name: e.name.value.trim() };
Object.keys(e.proxy).forEach(function(k) { o[k] = e.proxy[k]; });
return o;
}; };
var info = E('code', {}, S.summary(e.proxy));
var err = E('div', { 'style': 'color:#c33;display:none' });
e.yaml = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'spellcheck': 'false',
'style': 'width:100%;font-family:monospace;margin-top:.3em' + (open ? '' : ';display:none') }, S.yamlDump(e.proxy));
// the YAML is read as it is typed: an error shows and blocks the save
e.yaml.addEventListener('input', function() {
try {
var v = S.yamlLoad(e.yaml.value);
if (!v || typeof v != 'object' || Array.isArray(v))
throw new Error('нужен один сервер в виде «ключ: значение»');
if (!v.type || v.server === undefined || v.server === null || v.server === '')
throw new Error('нужны type и server');
delete v.name;
delete v['dialer-proxy'];
e.proxy = v;
e.error = null;
info.textContent = S.summary(v);
err.style.display = 'none';
} catch (x) {
e.error = x.message;
err.textContent = 'YAML: ' + x.message;
err.style.display = '';
}
});
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' }, [
field('Имя', e.name, 'буквы, цифры, _ - ; так сервер виден в дашборде'), E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
field('Сервер', e.server), e.name, info,
field('Порт', e.port), E('button', { 'class': 'btn cbi-button', 'click': function() {
field('Пароль', e.password, 'auth.password на сервере'), e.yaml.style.display = e.yaml.style.display == 'none' ? '' : 'none';
field('Obfs-пароль', e.obfs_password, 'salamander; пусто — без obfs'), } }, 'Настройки (YAML)'),
field('SNI', e.sni),
field('Не проверять сертификат', e.insecure, 'для самоподписанного сертификата (SNI чужого сайта)'),
field('Up / Down', [ e.up, e.down ], 'реальный потолок канала клиента; пусто — без ограничения'),
E('div', [
E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() { E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() {
var yaml = hy2Yaml({ name: e.name.value.trim(), server: e.server.value.trim(), port: e.port.value.trim(), var yaml = S.yamlDump([ e.get() ]) + '\n';
password: e.password.value, obfs_password: e.obfs_password.value, sni: e.sni.value.trim(),
insecure: e.insecure.checked, up: e.up.value.trim(), down: e.down.value.trim() });
copyText(yaml).then(function(ok) { copyText(yaml).then(function(ok) {
if (ok) if (ok)
return ui.addNotification(null, E('p', 'Конфиг ' + e.name.value.trim() + return ui.addNotification(null, E('p', 'Сервер ' + e.name.value.trim() +
' скопирован: на другом роутере — «Импорт из YAML / ссылки». В нём пароли, не публикуй.'), 'info'); ' скопирован: на другом роутере — «Добавить из ссылки / YAML». В нём пароли, не публикуй.'), 'info');
ui.showModal('Конфиг ' + e.name.value.trim(), [ ui.showModal('Сервер ' + e.name.value.trim(), [
E('p', 'Скопировать автоматически не вышло — выдели и скопируй:'), E('p', 'Скопировать автоматически не вышло — выдели и скопируй:'),
E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'readonly': 'readonly', E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'readonly': 'readonly',
'style': 'width:100%;font-family:monospace', 'click': function(ev) { ev.target.select(); } }, yaml), 'style': 'width:100%;font-family:monospace', 'click': function(ev) { ev.target.select(); } }, yaml),
E('div', { 'class': 'right' }, E('button', { 'class': 'btn', 'click': ui.hideModal }, 'Закрыть')) E('div', { 'class': 'right' }, E('button', { 'class': 'btn', 'click': ui.hideModal }, 'Закрыть'))
]); ]);
}); });
} }, 'Скопировать в буфер'), ' ', } }, 'Скопировать'),
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() { E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить сервер', 'click': function() {
hy2List.removeChild(el); srvList.removeChild(el);
hy2.splice(hy2.indexOf(e), 1); servers.splice(servers.indexOf(e), 1);
} }, 'Удалить сервер') } }, '✕')
]) ]),
e.yaml, err
]); ]);
hy2.push(e); servers.push(e);
hy2List.appendChild(el); srvList.appendChild(el);
}; };
(cfg.hy2 || []).forEach(addHy2); S.fromLines(cfg.servers_text).forEach(function(p) { addServer(p); });
// 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
var moved = 0;
(cfg.hy2 || []).forEach(function(h) {
var o = { name: h.name, type: 'hysteria2', server: h.server,
port: /^[0-9]+$/.test(h.port) ? +h.port : h.port, password: h.password };
if (h.obfs_password) {
o.obfs = 'salamander';
o['obfs-password'] = h.obfs_password;
}
if (h.sni)
o.sni = h.sni;
if (h.insecure == '1')
o['skip-cert-verify'] = true;
if (h.up)
o.up = h.up;
if (h.down)
o.down = h.down;
o.udp = true;
addServer(o);
moved++;
});
S.parseLinks(cfg.my_links || '').forEach(function(p) {
addServer(p);
moved++;
});
// import: paste YAML / hysteria2:// links (or load a file) -> fields // import: share links and/or YAML (or a file) -> cards
var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 10, 'style': 'width:100%;font-family:monospace', var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 8, 'spellcheck': 'false',
'placeholder': '- name: nl-1\n type: hysteria2\n server: vpn.example.com\n port: 443\n password: ...\n\nили hysteria2://пароль@host:443/?sni=...#nl-1' }); 'style': 'width:100%;font-family:monospace',
'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' }); var importFile = E('input', { 'type': 'file', 'accept': '.yaml,.yml,.txt,.conf' });
importFile.addEventListener('change', function() { importFile.addEventListener('change', function() {
readFile(importFile).then(function(t) { importText.value = t; }); readFile(importFile).then(function(t) { importText.value = t; });
@ -714,31 +676,16 @@ return view.extend({
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 found = parseHy2(importText.value); var r = S.parseText(importText.value);
if (!found.length) { r.servers.forEach(function(p) { addServer(p); });
ui.addNotification(null, E('p', 'Не нашёл серверов hysteria2: нужны хотя бы server и password'), 'warning'); var msg = [ E('p', r.servers.length ? 'Добавлено серверов: ' + r.servers.length +
return; '. Проверь имена и нажми «Сохранить и применить».' : 'Серверов не нашёл.') ];
r.errors.forEach(function(x) { msg.push(E('p', x)); });
ui.addNotification(null, msg, r.servers.length && !r.errors.length ? 'info' : 'warning');
if (r.servers.length) {
importText.value = '';
importBox.style.display = 'none';
} }
var added = 0, updated = 0;
found.forEach(function(h) {
var e = hy2.filter(function(x) { return x.name.value.trim() == h.name; })[0];
if (!e) {
addHy2(h);
added++;
return;
}
Object.keys(h).forEach(function(k) {
if (k == 'insecure')
e[k].checked = h[k] == '1';
else
e[k].value = h[k];
});
updated++;
});
importText.value = '';
importBox.style.display = 'none';
ui.addNotification(null, E('p', 'Импорт: добавлено ' + added + ', обновлено ' + updated +
'. Проверь поля и нажми «Сохранить и применить».'), 'info');
} }, 'Разобрать') } }, 'Разобрать')
]) ])
]); ]);
@ -792,20 +739,19 @@ return view.extend({
} }
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 = {}; var names = {}, srvLines = [];
var hy2Data = hy2.map(function(e) { servers.forEach(function(e) {
var d = {}; var n = e.name.value.trim();
Object.keys(e).forEach(function(k) { if (!n)
d[k] = k == 'insecure' ? e[k].checked : (k == 'password' || k == 'obfs_password' ? e[k].value : e[k].value.trim()); errors.push('Свой сервер: пустое имя');
}); else if (names[n])
if (!/^[A-Za-z0-9_-]+$/.test(d.name)) errors.push('Свой сервер: имя «' + n + '» повторяется');
errors.push('Свой сервер: имя «' + d.name + '» — только буквы, цифры, _ -'); names[n] = true;
else if (names[d.name.toUpperCase().replace(/-/g, '_')]) if (e.error)
errors.push('Свой сервер: имя ' + d.name + ' повторяется'); errors.push('Свой сервер ' + n + ': ' + e.error);
names[d.name.toUpperCase().replace(/-/g, '_')] = true; else if (e.proxy.server === undefined || e.proxy.server === null || e.proxy.server === '')
if (!d.server || !/^[0-9]+$/.test(d.port) || !d.password) errors.push('Свой сервер ' + n + ': пустой server (открой «Настройки (YAML)»)');
errors.push('Свой сервер ' + (d.name || '?') + ': нужны сервер, порт и пароль'); srvLines.push(S.toLine(e.get()));
return d;
}); });
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');
@ -826,7 +772,7 @@ 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(),
my_links: f.my_links.value.trim(), my_links: '',
openvpn: f.openvpn.checked, openvpn: f.openvpn.checked,
csqtt: f.csqtt.checked, csqtt: f.csqtt.checked,
ovpn: ovpn, ovpn: ovpn,
@ -841,7 +787,8 @@ return view.extend({
mobile: f.mobile.checked, mobile: f.mobile.checked,
lite: f.lite.checked, lite: f.lite.checked,
lite_gomemlimit: f.lite_gomemlimit.value.trim(), lite_gomemlimit: f.lite_gomemlimit.value.trim(),
hy2: hy2Data hy2: [],
servers_text: srvLines.join('\n')
}); });
}, this)).then(L.bind(function(r) { }, this)).then(L.bind(function(r) {
if (r.error) { if (r.error) {
@ -899,19 +846,20 @@ return view.extend({
'при импорте не переносится)'), 'при импорте не переносится)'),
E('h4', 'Свои серверы'), E('h4', 'Свои серверы'),
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 — напрямую. Ссылки ' +
'Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY, а не в FOREIGN/RU.'), 'vless / vmess / trojan / ss / hysteria2 / tuic / anytls и YAML разбираются так же, как в mihomo; серверы ' +
field('Ссылки', f.my_links, 'vless / vmess / trojan / ss / hysteria2 / tuic / anytls — как в приложении ' + 'попадают и в конфиг телефона. Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY.'),
'(reality, xhttp, ws, grpc разбирает само ядро); в MY как «[MY] имя». Только на этом роутере, в конфиг ' + moved ? E('p', { 'class': 'alert-message warning' }, 'Перенесено из старых настроек (hysteria2 по полям, ссылки): ' +
'телефона не попадают'), moved + '. Нажми «Сохранить и применить», чтобы сохранить их в новом виде.') : '',
E('h5', 'hysteria2 по полям'), srvList,
hy2List,
importBox, importBox,
E('div', [ E('div', [
E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addHy2({}); } }, 'Добавить сервер'), ' ', E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() {
E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() {
importBox.style.display = importBox.style.display == 'none' ? '' : 'none'; importBox.style.display = importBox.style.display == 'none' ? '' : 'none';
} }, 'Импорт из YAML / ссылки') } }, 'Добавить из ссылки / YAML'), ' ',
E('button', { 'class': 'btn cbi-button', 'click': function() {
addServer({ name: 'new', type: 'hysteria2', server: '', port: 443, password: '' }, true);
} }, 'Добавить вручную')
]), ]),
E('div', { 'class': 'cbi-page-actions' }, [ save ]) E('div', { 'class': 'cbi-page-actions' }, [ save ])
]); ]);

View File

@ -283,6 +283,9 @@ 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:-}"
# 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
json_add_string servers_text "$(cat "$NIKKI_DIR/my-servers" 2>/dev/null)"
# own servers as links: one per line in the form # own servers as links: one per line in the form
set -f set -f
json_add_string my_links "$(printf '%s\n' ${MY_LINKS:-})" json_add_string my_links "$(printf '%s\n' ${MY_LINKS:-})"
@ -318,6 +321,7 @@ 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),
# 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,
# 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
@ -331,6 +335,17 @@ m_config_set() {
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)
json_get_type _st servers_text
if [ -n "$_st" ]; then
json_get_var servers_text servers_text ""
umask 077
if [ -n "$servers_text" ]; then
printf '%s\n' "$servers_text" > "$NIKKI_DIR/my-servers.tmp" && mv "$NIKKI_DIR/my-servers.tmp" "$NIKKI_DIR/my-servers"
else
rm -f "$NIKKI_DIR/my-servers"
fi
fi
if [ -n "$ovpn" ]; then if [ -n "$ovpn" ]; then
umask 077 umask 077
printf '%s\n' "$ovpn" > "$NIKKI_DIR/bmstu.ovpn.tmp" && mv "$NIKKI_DIR/bmstu.ovpn.tmp" "$NIKKI_DIR/bmstu.ovpn" printf '%s\n' "$ovpn" > "$NIKKI_DIR/bmstu.ovpn.tmp" && mv "$NIKKI_DIR/bmstu.ovpn.tmp" "$NIKKI_DIR/bmstu.ovpn"

1410
luci/servers.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -73,10 +73,10 @@ log() { echo "$*" >&2; }
die() { log "error: $*"; exit 1; } die() { log "error: $*"; exit 1; }
# --- rendering -------------------------------------------------------------- # --- rendering --------------------------------------------------------------
# Template syntax (same in web/engine.js): # Template syntax:
# file NN-<module>[.<tag>...][.each].yaml included if module and tags are active; # file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
# .each = once per item of the module: # .each = once per item of the module:
# sub - subscription, hy2 - own server # sub - subscription, boot - seed node
# line ... #@tag[,!tag] kept only if the conditions hold # line ... #@tag[,!tag] kept only if the conditions hold
# line ... ${@VAR} ... repeated for every word of VAR # line ... ${@VAR} ... repeated for every word of VAR
# line ... ${@@VAR} ... repeated for every line of VAR # line ... ${@@VAR} ... repeated for every line of VAR
@ -89,7 +89,7 @@ set_defaults() {
: "${BOOT:=1}" "${TORRENT:=1}" "${PUSH:=1}" "${OPENVPN:=0}" "${TAILSCALE:=0}" "${TS_EXIT:=0}" : "${BOOT:=1}" "${TORRENT:=1}" "${PUSH:=1}" "${OPENVPN:=0}" "${TAILSCALE:=0}" "${TS_EXIT:=0}"
: "${SUBS:=}" "${RU_IPS:=}" "${HY2:=}" : "${SUBS:=}" "${RU_IPS:=}" "${HY2:=}"
: "${FOREIGN_IPS:=}" "${MY_IPS:=}" "${RU_DOMAINS:=}" "${FOREIGN_DOMAINS:=}" "${MY_DOMAINS:=}" : "${FOREIGN_IPS:=}" "${MY_IPS:=}" "${RU_DOMAINS:=}" "${FOREIGN_DOMAINS:=}" "${MY_DOMAINS:=}"
: "${LOCAL_HOSTS:=}" "${MY_LINKS:=}" : "${LOCAL_HOSTS:=}" "${MY_LINKS:=}" "${MY_SERVERS_FILE:=$NIKKI_DIR/my-servers}"
: "${RULESET_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release}" : "${RULESET_URL:=https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release}"
: "${BOOT_LINKS:=}" : "${BOOT_LINKS:=}"
: "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}" : "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}"
@ -135,14 +135,10 @@ compute_tags() {
fi fi
_i=$((_i + 1)) _i=$((_i + 1))
done done
# own hysteria2 servers: HY2_LIST "a, b" (group MY) # own servers of the settings (own_servers_vars): proxies in the profile and in group MY
HY2_LIST="" [ -n "$OWN_BODIES" ] && TAGS="$TAGS own_srv "
for _n in $HY2; do # MY has servers for sure: own ones or links (not only maybe [MY] nodes)
HY2_LIST="${HY2_LIST:+$HY2_LIST, }$_n" case "$TAGS" in *" own_srv "* | *" my_links "*)
done
[ -n "$HY2" ] && TAGS="$TAGS hy2 "
# MY has servers for sure: hysteria2 from the settings or links (not only maybe [MY] nodes)
case "$TAGS" in *" hy2 "* | *" my_links "*)
TAGS="$TAGS own " TAGS="$TAGS own "
;; ;;
esac esac
@ -151,7 +147,7 @@ compute_tags() {
case "$TAGS" in *" router "*" whitelist "* | *" router "*" foreign "*) TAGS="$TAGS ovpn_exit " ;; esac case "$TAGS" in *" router "*" whitelist "* | *" router "*" foreign "*) TAGS="$TAGS ovpn_exit " ;; esac
# own servers through MY-EXIT: whitelist and the phone (often on whitelists) # own servers through MY-EXIT: whitelist and the phone (often on whitelists)
case "$TAGS" in *" whitelist "* | *" mobile "*) TAGS="$TAGS my_exit " ;; esac case "$TAGS" in *" whitelist "* | *" mobile "*) TAGS="$TAGS my_exit " ;; esac
export SUB_LIST MY_SUB_LIST HY2_LIST CSQTT_MAIN export SUB_LIST MY_SUB_LIST CSQTT_MAIN
} }
# vless_parse <vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name> # vless_parse <vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name>
@ -172,7 +168,7 @@ vless_qv() { _v=${_q#*&$1=}; [ "$_v" = "$_q" ] || echo "${_v%%&*}"; }
# BOOT seeds: BOOT_LINKS (vless links, space/newline separated) or the old single # BOOT seeds: BOOT_LINKS (vless links, space/newline separated) or the old single
# BOOT_SERVER/PORT/UUID/SNI/PBK/SID -> SEED_ITEMS "name|server|port|uuid|sni|pbk|sid ...", # BOOT_SERVER/PORT/UUID/SNI/PBK/SID -> SEED_ITEMS "name|server|port|uuid|sni|pbk|sid ...",
# SEED_LIST "seed, seed2". Same as bootSeeds() in web/engine.js. # SEED_LIST "seed, seed2".
boot_seeds() { boot_seeds() {
SEED_ITEMS="" SEED_LIST="" _k=1 SEED_ITEMS="" SEED_LIST="" _k=1
if [ -n "$BOOT_LINKS" ]; then if [ -n "$BOOT_LINKS" ]; then
@ -208,7 +204,7 @@ seed_vars() {
# Subscription ids (provider names, keys SUB_<ID>_*). A SUBS word is "url" or # Subscription ids (provider names, keys SUB_<ID>_*). A SUBS word is "url" or
# "name=url"; without a name the id comes from the domain: # "name=url"; without a name the id comes from the domain:
# https://sub.kittyvpn.com/x -> kittyvpn, https://a.b.co.uk/ -> b # https://sub.kittyvpn.com/x -> kittyvpn, https://a.b.co.uk/ -> b
# Repeats get 2, 3, ... Same algorithm as subPairs() in web/engine.js. # Repeats get 2, 3, ...
sub_auto_id() { sub_auto_id() {
_h=${1#*://} _h=${1#*://}
_h=${_h%%[/?#]*} _h=${_h%%[/?#]*}
@ -349,24 +345,43 @@ sub_vars() {
export SUB_NAME SUB_URL SUB_PROXY SUB_UA SUB_HEADERS export SUB_NAME SUB_URL SUB_PROXY SUB_UA SUB_HEADERS
} }
# variables for templates/proxies/*-hy2.each.yaml: hy2_vars <name> # hy2_json <name>: an old own hysteria2 server of the settings (HY2_<NAME>_SERVER, _PORT,
# HY2_<NAME>_SERVER, _PORT, _PASSWORD required # _PASSWORD; _OBFS_PASSWORD = salamander; _SNI, _INSECURE=1, _UP, _DOWN) as a stored
# HY2_<NAME>_OBFS_PASSWORD salamander obfs (empty = none) # line of own servers (see own_servers_vars)
# HY2_<NAME>_SNI, _INSECURE=1 (skip-cert-verify), _UP, _DOWN ("50 mbps") hy2_json() {
hy2_vars() {
_k=$(hy2_key "$1") _k=$(hy2_key "$1")
eval "HY2_SERVER=\${${_k}_SERVER} HY2_PORT=\${${_k}_PORT} _pw=\${${_k}_PASSWORD} eval "_sv=\${${_k}_SERVER} _po=\${${_k}_PORT} _pw=\${${_k}_PASSWORD} _ob=\${${_k}_OBFS_PASSWORD:-}
_ob=\${${_k}_OBFS_PASSWORD:-} HY2_SNI=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0} _sn=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0} _up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}"
_up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}" case "$_po" in '' | *[!0-9]*) _po="\"$(yq "$_po")\"" ;; esac
HY2_NAME=$1 printf '{"name":"%s","type":"hysteria2","server":"%s","port":%s,"password":"%s"' \
HY2_PASSWORD=$(yq "$_pw") "$(yq "$1")" "$(yq "$_sv")" "$_po" "$(yq "$_pw")"
HY2_OBFS="" HY2_OBFS_PASSWORD="" [ -n "$_ob" ] && printf ',"obfs":"salamander","obfs-password":"%s"' "$(yq "$_ob")"
[ -n "$_ob" ] && HY2_OBFS=salamander HY2_OBFS_PASSWORD=$(yq "$_ob") [ -n "$_sn" ] && printf ',"sni":"%s"' "$(yq "$_sn")"
HY2_INSECURE=false [ "$_in" = 1 ] && printf ',"skip-cert-verify":true'
[ "$_in" = 1 ] && HY2_INSECURE=true [ -n "$_up" ] && printf ',"up":"%s"' "$(yq "$_up")"
HY2_UP=$(yq "$_up") HY2_DOWN=$(yq "$_dn") [ -n "$_dn" ] && printf ',"down":"%s"' "$(yq "$_dn")"
export HY2_NAME HY2_SERVER HY2_PORT HY2_PASSWORD HY2_OBFS HY2_OBFS_PASSWORD HY2_SNI \ printf ',"udp":true}\n'
HY2_INSECURE HY2_UP HY2_DOWN }
# Own servers (LuCI "Свои серверы"): MY_SERVERS_FILE holds one JSON proxy per line
# with "name" first (luci/servers.js), plus the old HY2_* keys -> OWN_BODIES, the
# lines without the leading "{" (templates/proxies puts dialer-proxy in front), and
# OWN_LIST '"a", "b"' for group MY. "$" becomes \u0024: the template engine would read
# ${...} in a password, JSON and YAML both read the escape.
own_servers_vars() {
OWN_BODIES="" OWN_LIST=""
_lines=$(
[ -f "$MY_SERVERS_FILE" ] && grep -v '^[[:space:]]*$' "$MY_SERVERS_FILE"
for _n in $HY2; do hy2_json "$_n"; done
)
[ -n "$_lines" ] || return 0
_names=$(printf '%s\n' "$_lines" | sed -nE 's/^\{"name":("([^"\\]|\\.)*"),.*/\1/p')
[ "$(printf '%s\n' "$_names" | grep -c .)" = "$(printf '%s\n' "$_lines" | grep -c .)" ] ||
die "$MY_SERVERS_FILE: a line is not {\"name\":...} (save the servers in LuCI again)"
_dup=$(printf '%s\n' "$_names" | sort | uniq -d | head -n 1)
[ -z "$_dup" ] || die "own servers: the name $_dup repeats"
OWN_BODIES=$(printf '%s\n' "$_lines" | sed 's/^{//; s/\$/\\u0024/g')
OWN_LIST=$(printf '%s\n' "$_names" | sed 's/\$/\\u0024/g' | awk '{ printf "%s%s", (NR > 1 ? ", " : ""), $0 }')
} }
render_file() { render_file() {
@ -444,14 +459,6 @@ render_section() {
_part=$(render_file "$f") _part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out [ -n "$_part" ] && _out="${_out:+$_out
}$_part"
done
elif [ "$EACH" = 1 ] && [ "$_mod" = hy2 ]; then
for _n in $HY2; do
hy2_vars "$_n"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
}$_part" }$_part"
done done
elif [ "$EACH" = 1 ]; then elif [ "$EACH" = 1 ]; then
@ -532,6 +539,7 @@ render() {
sub_pairs sub_pairs
boot_seeds boot_seeds
check_vars check_vars
own_servers_vars
compute_tags compute_tags
for _l in RU_IPS FOREIGN_IPS MY_IPS; do eval "$_l=\$(norm_list ip \"\$$_l\")"; done for _l in RU_IPS FOREIGN_IPS MY_IPS; do eval "$_l=\$(norm_list ip \"\$$_l\")"; done
for _l in RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS; do eval "$_l=\$(norm_list dom \"\$$_l\")"; done for _l in RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS; do eval "$_l=\$(norm_list dom \"\$$_l\")"; done
@ -539,7 +547,8 @@ render() {
export TARGET LOCATION RULESET_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \ export TARGET LOCATION RULESET_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \
BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \ BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \
OVPN_SERVER_IPS OVPN_ROUTES OVPN_CHECK_URL TS_CHECK_URL CSQTT_IFACE CSQTT_PROCESS \ OVPN_SERVER_IPS OVPN_ROUTES OVPN_CHECK_URL TS_CHECK_URL CSQTT_IFACE CSQTT_PROCESS \
RU_IPS FOREIGN_IPS MY_IPS RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS LOCAL_DOMAINS LOCAL_HOSTS_YAML RU_IPS FOREIGN_IPS MY_IPS RU_DOMAINS FOREIGN_DOMAINS MY_DOMAINS LOCAL_DOMAINS LOCAL_HOSTS_YAML \
OWN_BODIES OWN_LIST
_first=1 _first=1
for s in head proxies:proxies providers:proxy-providers rule-providers:rule-providers sniffer dns \ for s in head proxies:proxies providers:proxy-providers rule-providers:rule-providers sniffer dns \
groups:proxy-groups rules:rules; do groups:proxy-groups rules:rules; do
@ -1288,6 +1297,7 @@ install_luci() {
# rpcd needs a restart only for its plugin and ACL (it drops LuCI sessions) # rpcd needs a restart only for its plugin and ACL (it drops LuCI sessions)
_rpcd=$_changed _rpcd=$_changed
put "$src/qrcode.js" /www/luci-static/resources/mihomo-kit/qrcode.js 644 put "$src/qrcode.js" /www/luci-static/resources/mihomo-kit/qrcode.js 644
put "$src/servers.js" /www/luci-static/resources/mihomo-kit/servers.js 644
_views=/www/luci-static/resources/view _views=/www/luci-static/resources/view
_v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8) _v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8)
@ -1709,7 +1719,7 @@ cmd_apply() {
EXPORT_HEAD='# mihomo-kit export v1' EXPORT_HEAD='# mihomo-kit export v1'
cmd_export() { cmd_export() {
echo "$EXPORT_HEAD $(uci -q get 'system.@system[0].hostname') $(date '+%Y-%m-%d %H:%M')" echo "$EXPORT_HEAD $(uci -q get 'system.@system[0].hostname') $(date '+%Y-%m-%d %H:%M')"
for _f in "$PROFILES_D"/*.env "$NIKKI_DIR/bmstu.env" "$NIKKI_DIR/bmstu.ovpn"; do for _f in "$PROFILES_D"/*.env "$NIKKI_DIR/bmstu.env" "$NIKKI_DIR/bmstu.ovpn" "$NIKKI_DIR/my-servers"; do
[ -f "$_f" ] || continue [ -f "$_f" ] || continue
echo "#%% file ${_f#"$NIKKI_DIR"/}" echo "#%% file ${_f#"$NIKKI_DIR"/}"
cat "$_f" cat "$_f"
@ -1727,7 +1737,7 @@ cmd_import() {
echo "$_files" | grep -q '^profiles.d/common.env$' || die "no profiles.d/common.env in the export" echo "$_files" | grep -q '^profiles.d/common.env$' || die "no profiles.d/common.env in the export"
for _f in $_files; do for _f in $_files; do
case "$_f" in case "$_f" in
profiles.d/*.env | bmstu.env | bmstu.ovpn) ;; profiles.d/*.env | bmstu.env | bmstu.ovpn | my-servers) ;;
*) die "unexpected file in the export: $_f" ;; *) die "unexpected file in the export: $_f" ;;
esac esac
case "${_f#profiles.d/}" in */* | *[!A-Za-z0-9_.-]*) die "bad file name: $_f" ;; esac case "${_f#profiles.d/}" in */* | *[!A-Za-z0-9_.-]*) die "bad file name: $_f" ;; esac
@ -1749,7 +1759,7 @@ cmd_import() {
umask 077 umask 077
rm -f "$PROFILES_D"/*.env rm -f "$PROFILES_D"/*.env
cp "$_tmp"/profiles.d/*.env "$PROFILES_D/" cp "$_tmp"/profiles.d/*.env "$PROFILES_D/"
for _f in bmstu.env bmstu.ovpn; do for _f in bmstu.env bmstu.ovpn my-servers; do
[ -f "$_tmp/$_f" ] && cp "$_tmp/$_f" "$NIKKI_DIR/$_f" [ -f "$_tmp/$_f" ] && cp "$_tmp/$_f" "$NIKKI_DIR/$_f"
done done
if [ "${2:-}" = --keep-local ]; then if [ "${2:-}" = --keep-local ]; then

View File

@ -1,8 +1,8 @@
# own servers: hysteria2 from the settings (HY2) and the "[MY] ..." nodes of the # own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of
# 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: [${HY2_LIST}] #@hy2 proxies: [${OWN_LIST}] #@own_srv
use: [${MY_SUB_LIST}] use: [${MY_SUB_LIST}]
url: "https://www.gstatic.com/generate_204" url: "https://www.gstatic.com/generate_204"
interval: 300 #@!lite interval: 300 #@!lite

View File

@ -1,14 +0,0 @@
- name: ${HY2_NAME}
type: hysteria2
server: ${HY2_SERVER}
port: ${HY2_PORT}
password: "${HY2_PASSWORD}"
obfs: ${@HY2_OBFS}
obfs-password: "${@@HY2_OBFS_PASSWORD}"
sni: ${@HY2_SNI}
skip-cert-verify: ${HY2_INSECURE}
up: "${@@HY2_UP}"
down: "${@@HY2_DOWN}"
udp: true
dialer-proxy: MY-EXIT #@my_exit
dialer-proxy: UPLINK #@csqtt,!my_exit

View File

@ -0,0 +1,6 @@
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"dialer-proxy": "MY-EXIT", ${@@OWN_BODIES} #@my_exit
- {"dialer-proxy": "UPLINK", ${@@OWN_BODIES} #@csqtt,!my_exit
- {${@@OWN_BODIES} #@!my_exit,!csqtt

242
tests/expected/mobile.yaml Normal file
View File

@ -0,0 +1,242 @@
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
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"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":"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":"m1","type":"hysteria2","server":"m.example.com","port":443,"password":"p","udp":true}
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.
example-my:
type: http
url: "https://sub.example.com/sub/aaa"
path: ./providers/example-my.yaml
interval: 3600
proxy: BOOT-AUTO
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
header:
User-Agent: ["mihomo"]
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.
example2-my:
type: http
url: "https://sub2.example.com/x?a=1&b=2"
path: ./providers/example2-my.yaml
interval: 3600
proxy: BOOT-AUTO
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
header:
User-Agent: ["mihomo"]
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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'
- '+.ru'
default-nameserver:
- 77.88.8.8
- 223.5.5.5
proxy-server-nameserver:
- https://77.88.8.8/dns-query
direct-nameserver:
- 77.88.8.8
- 77.88.8.1
nameserver:
- https://dns.google/dns-query
- https://1.1.1.1/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
# 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
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "m1"]
use: [example-my, example2-my]
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
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, 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
# 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
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,274 @@
proxies:
- name: seed
type: vless
server: 1.2.3.4
port: 443
uuid: 11111111-1111-1111-1111-111111111111
network: tcp
udp: true
tls: true
flow: xtls-rprx-vision
servername: eh.vk.ru
client-fingerprint: firefox
reality-opts:
public-key: Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns
short-id: a1
- name: seed2
type: vless
server: seed2.example.com
port: 8443
uuid: 22222222-2222-2222-2222-222222222222
network: tcp
udp: true
tls: true
flow: xtls-rprx-vision
servername: ya.ru
client-fingerprint: firefox
reality-opts:
public-key: ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw
short-id: b2
proxy-providers:
example:
type: http
url: "https://sub.example.com/sub/aaa"
path: ./providers/example.yaml
interval: 3600
proxy: BOOT
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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, seed2]
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
# 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, example2-my]
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
- 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
# 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/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,281 @@
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
dialer-proxy: UPLINK
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"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":"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":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
# CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo
# just sends the connection out of it (the interface does not change routes)
- name: CSQTT
type: direct
interface-name: csqtt0
udp: true
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\\]"
override:
dialer-proxy: UPLINK
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\\]"
override:
dialer-proxy: UPLINK
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: UPLINK
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: UPLINK
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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'
default-nameserver:
- 77.88.8.8
- 1.1.1.1
proxy-server-nameserver:
- https://77.88.8.8/dns-query
direct-nameserver:
- 1.1.1.1
- 8.8.8.8
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
# 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
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "nl-1"]
use: [example-my, example2-my]
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)
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist), 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, CSQTT]
- name: MAIN
type: select
# abroad: direct by default, own servers / pools by hand
proxies: [DIRECT, MY, FOREIGN, RU, CSQTT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [DIRECT, MY, FOREIGN]
rules:
# the CSQTT client's own connections (peer, VK TURN) must not go into its tunnel
- PROCESS-NAME,csqtt,DIRECT
- 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
# 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
# abroad: Russian services through the RU pool too
- RULE-SET,ru-inside,RU
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,289 @@
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
dialer-proxy: UPLINK
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"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":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
# CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo
# just sends the connection out of it (the interface does not change routes)
- name: CSQTT
type: direct
interface-name: csqtt0
udp: true
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\\]"
override:
dialer-proxy: UPLINK
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\\]"
override:
dialer-proxy: UPLINK
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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
# 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
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own"]
use: [example-my, example2-my]
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
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist), 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, CSQTT]
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT, CSQTT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [MY, FOREIGN, DIRECT]
rules:
# the CSQTT client's own connections (peer, VK TURN) must not go into its tunnel
- PROCESS-NAME,csqtt,DIRECT
- 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
# 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/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,322 @@
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
# Tailscale: userspace node, starts on first use. First login: open the URL
# from the nikki log ("To start this tsnet server ... go to: ..."), then
# disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the
# mihomo environment (mihomo-kit.sh fix).
- name: tailscale
type: tailscale
hostname: test-mihomo
state-dir: ./tailscale
udp: true
accept-routes: true
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the
# password). No health-check here: a dead tunnel would be redialed with a
# stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
bmstu:
type: file
path: ./providers/bmstu.yaml
health-check:
enable: false
override:
dialer-proxy: OVPN-EXIT
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
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead BMSTU group
bmstu-routes:
type: file
behavior: ipcidr
path: ./providers/bmstu-routes.yaml
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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'
# tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below)
- '+.ts.net'
default-nameserver:
- 77.88.8.8
- 1.1.1.1
proxy-server-nameserver:
- https://77.88.8.8/dns-query
direct-nameserver:
- 1.1.1.1
- 8.8.8.8
nameserver:
- https://1.1.1.1/dns-query
- https://dns.google/dns-query
# MagicDNS of the embedded Tailscale (the proxy named "tailscale")
nameserver-policy:
'+.ts.net': tailscale://tailscale
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
# url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale OTP)
- name: BMSTU
type: select
use: [bmstu]
url: "https://eu.bmstu.ru"
interval: 0
# what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).
# select, not url-test: switching nodes would break the tunnel.
# Pick a concrete RU node in the dashboard, the choice is remembered.
- name: OVPN-EXIT
type: select
use: [example, example2]
filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск"
# 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
proxies: ["nl-1"]
use: [example-my, example2-my]
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)
# url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test
- name: TAILSCALE
type: select
proxies: [tailscale]
url: "http://100.69.216.50:8080"
interval: 0
- name: MAIN
type: select
# abroad: direct by default, own servers / pools by hand
proxies: [DIRECT, MY, FOREIGN, RU]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [DIRECT, MY, FOREIGN]
rules:
# Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE
# OpenVPN server itself must not go into its own tunnel
- IP-CIDR,195.19.40.7/32,OVPN-EXIT,no-resolve
- IP-CIDR,195.19.33.86/32,OVPN-EXIT,no-resolve
- DOMAIN,openvpn4.bmstu.ru,OVPN-EXIT
# 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,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
# 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
# abroad: Russian services through the RU pool too
- RULE-SET,ru-inside,RU
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,252 @@
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: ["my \"ua\" \\x"]
x-a: ["1"]
x-b: ["two words"]
# 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: DIRECT
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
header:
User-Agent: ["v2rayN/9.99"]
x-device-os: ["OpenWrt"]
x-ver-os: ["24.10.3"]
x-device-model: ["Huasifei WH3000 Pro"]
x-hwid: ["123"]
# 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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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
# 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, example2-my]
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: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [DIRECT, MY, FOREIGN]
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
# 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,DIRECT
- SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN

View File

@ -0,0 +1,287 @@
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:
kitty:
type: http
url: "https://a.example.com/x"
path: ./providers/kitty.yaml
interval: 3600
proxy: BOOT-AUTO
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
header:
User-Agent: ["v2rayN/9.99"]
x-device-os: ["OpenWrt"]
x-ver-os: ["24.10.3"]
x-device-model: ["Huasifei WH3000 Pro"]
x-hwid: ["123"]
# 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
vpn_host:
type: http
url: "https://sub.vpn-host.co.uk/y?t=1"
path: ./providers/vpn_host.yaml
interval: 3600
proxy: DIRECT
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
sub3:
type: http
url: "https://1.2.3.4:8443/s"
path: ./providers/sub3.yaml
interval: 3600
proxy: FOREIGN
exclude-filter: "(?i)app not supported|приложение не|свяжитесь|\\[MY\\]"
header:
User-Agent: ["mihomo"]
x-a: ["1"]
# 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.
kitty-my:
type: file
path: ./providers/kitty.yaml
filter: "(?i)\\[MY\\]"
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.
vpn_host-my:
type: file
path: ./providers/vpn_host.yaml
filter: "(?i)\\[MY\\]"
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.
sub3-my:
type: file
path: ./providers/sub3.yaml
filter: "(?i)\\[MY\\]"
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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: [kitty, vpn_host, sub3]
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: [kitty, vpn_host, sub3]
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: [kitty, vpn_host, sub3]
filter: "(?i)torrent|\\[tor\\]"
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 6000
tolerance: 500
max-failed-times: 5
lazy: false
# 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: [kitty-my, vpn_host-my, sub3-my]
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: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [DIRECT, MY, FOREIGN]
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
# 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,DIRECT
- SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN

View File

@ -0,0 +1,278 @@
# LITE=1 (weak routers). nikki's mixin overrides keys whose uci options are set
# (mihomo-kit.sh puts log_level / match_process there); these cover the rest
log-level: warning
tcp-concurrent: false
unified-delay: false
geo-auto-update: false
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
dialer-proxy: UPLINK
# CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo
# just sends the connection out of it (the interface does not change routes)
- name: CSQTT
type: direct
interface-name: csqtt0
udp: true
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\\]"
override:
dialer-proxy: UPLINK
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: 600
timeout: 3000
lazy: true
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\\]"
override:
dialer-proxy: UPLINK
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: 600
timeout: 3000
lazy: true
# 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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: UPLINK
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 600
timeout: 3000
lazy: true
# 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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: UPLINK
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 600
timeout: 3000
lazy: true
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
sniff:
HTTP:
ports: [80, 8080]
TLS:
ports: [443, 8443]
# lite: no QUIC (fake-ip already gives the domain; pure-IP QUIC goes by IP)
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://www.gstatic.com/generate_204"
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
# 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, example2-my]
url: "https://www.gstatic.com/generate_204"
interval: 600
tolerance: 50
lazy: true
# 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)
# UPLINK: what the subscription nodes, BOOT seeds and own servers connect
# through. DIRECT - as before; CSQTT - through csqtt0 first (out of the
# whitelist), 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, CSQTT]
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT, CSQTT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [DIRECT, MY, FOREIGN]
rules:
# the CSQTT client's own connections (peer, VK TURN) must not go into its tunnel
- PROCESS-NAME,csqtt,DIRECT
- 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
# 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,DIRECT
- SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN

View File

@ -0,0 +1,270 @@
# LITE=1 (weak routers). nikki's mixin overrides keys whose uci options are set
# (mihomo-kit.sh puts log_level / match_process there); these cover the rest
log-level: warning
find-process-mode: off
tcp-concurrent: false
unified-delay: false
geo-auto-update: false
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
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"dialer-proxy": "MY-EXIT", "name":"nl-1","type":"hysteria2","server":"vpn.example.com","port":443,"password":"p","udp":true}
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: 600
timeout: 3000
lazy: true
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: 600
timeout: 3000
lazy: true
# 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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 600
timeout: 3000
lazy: true
# 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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 600
timeout: 3000
lazy: true
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
sniff:
HTTP:
ports: [80, 8080]
TLS:
ports: [443, 8443]
# lite: no QUIC (fake-ip already gives the domain; pure-IP QUIC goes by IP)
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://www.gstatic.com/generate_204"
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
# 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
proxies: ["nl-1"]
use: [example-my, example2-my]
url: "https://www.gstatic.com/generate_204"
interval: 600
tolerance: 50
lazy: true
# 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
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [MY, FOREIGN, 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
# 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/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,338 @@
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
# Tailscale: userspace node, starts on first use. First login: open the URL
# from the nikki log ("To start this tsnet server ... go to: ..."), then
# disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the
# mihomo environment (mihomo-kit.sh fix).
- name: tailscale
type: tailscale
hostname: test-mihomo
state-dir: ./tailscale
udp: true
accept-routes: true
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through 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"}}
- {"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":"home-hy","type":"hysteria2","server":"1.1.1.1","port":443,"password":"x","udp":true}
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: DIRECT
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the
# password). No health-check here: a dead tunnel would be redialed with a
# stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
bmstu:
type: file
path: ./providers/bmstu.yaml
health-check:
enable: 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
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead BMSTU group
bmstu-routes:
type: file
behavior: ipcidr
path: ./providers/bmstu-routes.yaml
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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
# tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below)
- '+.ts.net'
# own servers in the LAN (LOCAL_HOSTS): clients get the real LAN address
- '+.sub2.example.com'
- '+.lan-srv.example'
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
# MagicDNS of the embedded Tailscale (the proxy named "tailscale")
nameserver-policy:
'+.ts.net': tailscale://tailscale
# LOCAL_HOSTS: own domains -> LAN addresses (dns.use-hosts is on by default), so neither
# the core nor the clients go out to the white IP and back into the router itself
hosts:
'+.sub2.example.com': 192.168.64.20
'+.lan-srv.example': 10.0.0.5
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
# url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale OTP)
- name: BMSTU
type: select
use: [bmstu]
url: "https://eu.bmstu.ru"
interval: 0
# 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
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own", "home-hy"]
use: [example-my, example2-my]
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)
# url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test
- name: TAILSCALE
type: select
proxies: [tailscale]
url: "http://100.69.216.50:8080"
interval: 0
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [DIRECT, MY, FOREIGN]
rules:
# Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE
# OpenVPN server itself must not go into its own tunnel
- IP-CIDR,195.19.40.7/32,DIRECT,no-resolve
- IP-CIDR,195.19.33.86/32,DIRECT,no-resolve
- DOMAIN,openvpn4.bmstu.ru,DIRECT
# 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,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
# 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
# LOCAL_HOSTS: own servers in the LAN, before everything else
- DOMAIN-SUFFIX,sub2.example.com,DIRECT
- DOMAIN-SUFFIX,lan-srv.example,DIRECT
- DOMAIN-SUFFIX,home.example,MY
- DOMAIN-SUFFIX,api.example.com,FOREIGN
- DOMAIN-SUFFIX,example.com,DIRECT
- DOMAIN-SUFFIX,gosuslugi.example,DIRECT
- DOMAIN-SUFFIX,bank.example,DIRECT
- DOMAIN-SUFFIX,plain.example,DIRECT
- IP-CIDR,10.8.0.0/24,MY
- IP-CIDR,9.9.9.0/24,FOREIGN
- IP-CIDR,2001:db8::1/128,FOREIGN
- IP-CIDR,194.190.191.112/32,DIRECT
- IP-CIDR,5.6.7.8/32,DIRECT
- SRC-PORT,20000-20199,TORRENT-SEL
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN

View File

@ -0,0 +1,191 @@
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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:
# 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: [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
# 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, example2-my]
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: MAIN
type: select
proxies: [FOREIGN, MY, RU, 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
# 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
- DOMAIN-SUFFIX,home.example,MY
- IP-CIDR,9.9.9.9/32,FOREIGN
- RULE-SET,ru-inside,DIRECT
# main (home, own white IP): .ru/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,DIRECT
- DOMAIN-SUFFIX,xn--p1ai,DIRECT
- MATCH,MAIN

View File

@ -0,0 +1,314 @@
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
# Tailscale: userspace node, starts on first use. First login: open the URL
# from the nikki log ("To start this tsnet server ... go to: ..."), then
# disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the
# mihomo environment (mihomo-kit.sh fix).
- name: tailscale
type: tailscale
hostname: test-mihomo
state-dir: ./tailscale
udp: true
accept-routes: true
# whitelist: control and DERP over TCP through own servers (MY -> own node -> MY-EXIT);
# MY holds hysteria2 from the settings and "[MY]" nodes of the subscriptions; empty MY is direct
# needs the kit's core (v1.19.32-ts1, tools/core/*.patch, MetaCubeX/mihomo#3142)
dialer-proxy: MY
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"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":"hy-own","type":"hysteria2","server":"h.example.net","port":8443,"password":"a\u0024b","obfs":"salamander","obfs-password":"o","up":"50 mbps"}
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# own servers as links (MY_LINKS, LuCI "Свои серверы (ссылки)"): kit writes them to
# this file on build, mihomo parses vless/vmess/trojan/ss/hysteria2/tuic/anytls links
# like a subscription; group MY, named "[MY] ..." like the [MY] nodes of the subscriptions
my-links:
type: file
path: ./providers/my-links.txt
override:
additional-prefix: "[MY] "
dialer-proxy: MY-EXIT
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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
# tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below)
- '+.ts.net'
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
# MagicDNS of the embedded Tailscale (the proxy named "tailscale")
nameserver-policy:
'+.ts.net': tailscale://tailscale
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
# 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
proxies: ["🇩🇪 de 1", "tr \"q\"", "hy-own"]
use: [example-my, example2-my, my-links]
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
# url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test
- name: TAILSCALE
type: select
proxies: [tailscale]
url: "http://100.69.216.50:8080"
interval: 0
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [MY, FOREIGN, DIRECT]
rules:
# Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE
- 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
# 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/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,297 @@
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
# Tailscale: userspace node, starts on first use. First login: open the URL
# from the nikki log ("To start this tsnet server ... go to: ..."), then
# disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the
# mihomo environment (mihomo-kit.sh fix).
- name: tailscale
type: tailscale
hostname: test-mihomo
state-dir: ./tailscale
udp: true
accept-routes: true
# whitelist: control and DERP over TCP through own servers (MY -> own node -> MY-EXIT);
# MY holds hysteria2 from the settings and "[MY]" nodes of the subscriptions; empty MY is direct
# needs the kit's core (v1.19.32-ts1, tools/core/*.patch, MetaCubeX/mihomo#3142)
dialer-proxy: MY
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"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}
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
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
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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
# tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below)
- '+.ts.net'
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
# MagicDNS of the embedded Tailscale (the proxy named "tailscale")
nameserver-policy:
'+.ts.net': tailscale://tailscale
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
# 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
proxies: ["nl-1", "de-2"]
use: [example-my, example2-my]
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
# url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test
- name: TAILSCALE
type: select
proxies: [tailscale]
url: "http://100.69.216.50:8080"
interval: 0
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [MY, FOREIGN, DIRECT]
rules:
# Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE
- 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
# 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/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -0,0 +1,353 @@
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
# Tailscale: userspace node, starts on first use. First login: open the URL
# from the nikki log ("To start this tsnet server ... go to: ..."), then
# disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the
# mihomo environment (mihomo-kit.sh fix).
- name: tailscale
type: tailscale
hostname: test-mihomo
state-dir: ./tailscale
udp: true
accept-routes: true
dialer-proxy: TS-EXIT
# 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
# front: whitelist and the phone through MY-EXIT, with CSQTT through UPLINK
- {"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}
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.
example-my:
type: file
path: ./providers/example.yaml
filter: "(?i)\\[MY\\]"
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.
example2-my:
type: file
path: ./providers/example2.yaml
filter: "(?i)\\[MY\\]"
override:
dialer-proxy: MY-EXIT
health-check:
enable: true
url: "https://www.gstatic.com/generate_204"
interval: 300
timeout: 3000
lazy: false
# OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the
# password). No health-check here: a dead tunnel would be redialed with a
# stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.
bmstu:
type: file
path: ./providers/bmstu.yaml
health-check:
enable: false
override:
dialer-proxy: OVPN-EXIT
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
# OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and
# emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow
# the normal rules instead of a dead BMSTU group
bmstu-routes:
type: file
behavior: ipcidr
path: ./providers/bmstu-routes.yaml
sniffer:
enable: true
force-dns-mapping: true
parse-pure-ip: true
override-destination: false
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
# tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below)
- '+.ts.net'
- '+.corp.example'
- '+.internal.example'
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
# MagicDNS of the embedded Tailscale (the proxy named "tailscale")
nameserver-policy:
'+.ts.net': tailscale://tailscale
'+.corp.example': tailscale://tailscale
'+.internal.example': tailscale://tailscale
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
# url: what the dashboard's delay test opens through the tunnel;
# interval 0: no background checks (they would redial with a stale OTP)
- name: BMSTU
type: select
use: [bmstu]
url: "https://lks.bmstu.ru/"
interval: 0
# what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).
# select, not url-test: switching nodes would break the tunnel.
# Pick a concrete RU node in the dashboard, the choice is remembered.
- name: OVPN-EXIT
type: select
use: [example, example2]
filter: "(?i)🇷🇺|\\bru\\b|russia|росси|моск"
# 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
proxies: ["nl-1", "de_2"]
use: [example-my, example2-my]
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
# url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test
- name: TAILSCALE
type: select
proxies: [tailscale]
url: "http://100.69.216.50:8080/"
interval: 0
# Tailscale needs full-cone UDP from its dialer-proxy: vless/vmess/trojan
# cannot do it in mihomo, so only ss / hysteria2 / tuic / socks5 nodes here.
- name: TS-EXIT
type: select
proxies: [MY]
use: [example, example2]
exclude-type: "vless|vmess|trojan"
- name: MAIN
type: select
proxies: [FOREIGN, MY, RU, DIRECT]
- name: TORRENT-SEL
type: select
proxies: [TORRENT, FOREIGN, DIRECT]
- name: PUSH
type: select
proxies: [MY, FOREIGN, DIRECT]
rules:
# Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)
- IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve
- DOMAIN-SUFFIX,ts.net,TAILSCALE
- DOMAIN-SUFFIX,corp.example,TAILSCALE
- DOMAIN-SUFFIX,internal.example,TAILSCALE
# OpenVPN server itself must not go into its own tunnel
- IP-CIDR,195.19.40.7/32,OVPN-EXIT,no-resolve
- IP-CIDR,195.19.33.86/32,OVPN-EXIT,no-resolve
- DOMAIN,openvpn4.bmstu.ru,OVPN-EXIT
# 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,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
# 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
- DOMAIN-SUFFIX,example.com,RU
- IP-CIDR,10.8.0.0/24,MY
- 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/.рф directly; elsewhere through RU
- DOMAIN-SUFFIX,ru,RU
- DOMAIN-SUFFIX,xn--p1ai,RU
- MATCH,MAIN

View File

@ -5,3 +5,4 @@ HY2_M1_PORT=443
HY2_M1_PASSWORD=p 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

3
tests/fixtures/own.servers vendored Normal file
View File

@ -0,0 +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":"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"}

View File

@ -1,5 +1,5 @@
TARGET=router TARGET=router
LOCATION=whitelist LOCATION=whitelist
BOOT_LINKS="vless://11111111-1111-1111-1111-111111111111@1.2.3.4:443?type=tcp&security=reality&sni=eh.vk.ru&pbk=PBK1&sid=a1&flow=xtls-rprx-vision#one BOOT_LINKS="vless://11111111-1111-1111-1111-111111111111@1.2.3.4:443?type=tcp&security=reality&sni=eh.vk.ru&pbk=Nc9ZSDuQMwHN4M6TeDHjfJhgZ6SBTBbfMwx5iHQZ1ns&sid=a1&flow=xtls-rprx-vision#one
vless://22222222-2222-2222-2222-222222222222@seed2.example.com:8443?security=reality&sni=ya.ru&pbk=PBK2&sid=b2" vless://22222222-2222-2222-2222-222222222222@seed2.example.com:8443?security=reality&sni=ya.ru&pbk=ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw&sid=b2"
SUB_EXAMPLE_PROXY=BOOT SUB_EXAMPLE_PROXY=BOOT

View File

@ -5,3 +5,4 @@ HY2=nl-1
HY2_NL_1_SERVER=vpn.example.com HY2_NL_1_SERVER=vpn.example.com
HY2_NL_1_PORT=443 HY2_NL_1_PORT=443
HY2_NL_1_PASSWORD=p HY2_NL_1_PASSWORD=p
MY_SERVERS_FILE=tests/fixtures/own.servers

View File

@ -1,3 +1,4 @@
TARGET=router TARGET=router
LOCATION=whitelist LOCATION=whitelist
CSQTT=1 CSQTT=1
MY_SERVERS_FILE=tests/fixtures/own.servers

View File

@ -12,3 +12,4 @@ RU_DOMAINS="*.example.com +.gosuslugi.example .bank.example plain.example"
FOREIGN_DOMAINS="api.example.com" FOREIGN_DOMAINS="api.example.com"
MY_DOMAINS="*.home.example" MY_DOMAINS="*.home.example"
LOCAL_HOSTS="sub2.example.com=192.168.64.20 *.lan-srv.example=10.0.0.5" LOCAL_HOSTS="sub2.example.com=192.168.64.20 *.lan-srv.example=10.0.0.5"
MY_SERVERS_FILE=tests/fixtures/own.servers

View File

@ -2,3 +2,4 @@ TARGET=router
LOCATION=whitelist 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

View File

@ -0,0 +1,178 @@
[
{
"client-fingerprint": "chrome",
"name": "upper",
"network": "ws",
"port": "443",
"server": "Upper.Example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"ws-opts": {
"headers": {
"Host": "",
"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": "/w"
},
"xudp": true
},
{
"client-fingerprint": "chrome",
"name": "plus",
"password": "a+b+c",
"port": "443",
"server": "t.example",
"skip-cert-verify": false,
"sni": "a b",
"type": "trojan",
"udp": true
},
{
"client-fingerprint": "chrome",
"name": "two-at",
"password": "us@er",
"port": "443",
"server": "t.example",
"skip-cert-verify": false,
"type": "trojan",
"udp": true
},
{
"client-fingerprint": "chrome",
"name": "noport-trojan",
"password": "pw",
"port": "",
"server": "t.example",
"skip-cert-verify": false,
"type": "trojan",
"udp": true
},
{
"down": "",
"fingerprint": "",
"name": "colon-pass",
"obfs": "",
"obfs-password": "",
"password": "user:pa%3Ass",
"port": "443",
"server": "h.example",
"skip-cert-verify": false,
"sni": "",
"type": "hysteria2",
"up": ""
},
{
"cipher": "aes-128-gcm",
"name": "ss-legacy-padded",
"password": "pw",
"port": "8388",
"server": "1.1.1.1",
"type": "ss",
"udp": true
},
{
"cipher": "chacha20-ietf-poly1305",
"name": "plugin-no-semicolon",
"password": "pass",
"port": "8388",
"server": "h.example",
"type": "ss",
"udp": true
},
{
"client-fingerprint": "chrome",
"name": "empty-values",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"http-opts": {
"headers": {},
"path": [
"/"
]
},
"name": "tcp-http-upper",
"network": "http",
"port": "443",
"server": "example.com",
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"name": "empty-pass",
"password": "",
"port": "443",
"server": "tu.example",
"type": "tuic",
"udp": true,
"uuid": "uuid"
},
{
"name": "4.4.4.4:1080",
"password": "",
"port": "1080",
"server": "4.4.4.4",
"skip-cert-verify": true,
"type": "socks5",
"username": ""
},
{
"name": "escaped-user",
"network": "tcp",
"port": "443",
"server": "example.com",
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"down": "",
"fingerprint": "",
"name": "plus-in-query",
"obfs": "salamander",
"obfs-password": "a+b c",
"password": "pw",
"port": "443",
"server": "h.example",
"skip-cert-verify": false,
"sni": "",
"type": "hysteria2",
"up": ""
},
{
"alpn": [
"h2",
"http/1.1"
],
"alterId": 0,
"cipher": "auto",
"h2-opts": {
"host": [
"h"
],
"path": "/p"
},
"name": "h2 path",
"network": "h2",
"port": "443",
"server": "x.example",
"skip-cert-verify": false,
"tls": true,
"type": "vmess",
"udp": true,
"uuid": "i",
"xudp": true
}
]

View File

@ -0,0 +1,20 @@
VLESS://uuid@Upper.Example.com:443?security=TLS&type=WS&path=%2Fw#upper
trojan://a+b%2Bc@t.example:443?sni=a+b#plus
trojan://us@er@t.example:443#two-at
trojan://pw@t.example:44x3#badport
trojan://pw@t.example#noport-trojan
hy2://user:pa:ss@h.example:443#colon-pass
hy2://pass word@h.example:443#space
ss://YWVzLTEyOC1nY206cHdAMS4xLjEuMTo4Mzg4#ss-legacy-padded
ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpwYXNz@h.example:8388/?plugin=simple-obfs#plugin-no-semicolon
vmess://eyJ2IjoiMiIsInBzIjo1LCJhZGQiOiJ4IiwicG9ydCI6IjEiLCJpZCI6ImkifQ==
vmess://bm90IGpzb24=
vless://uuid@example.com:443?security=tls&sni=&alpn=#empty-values
vless://uuid@example.com:443?type=tcp&headerType=HTTP#tcp-http-upper
anytls://pw@:443#nohost
tuic://uuid:@tu.example:443#empty-pass
socks://@4.4.4.4:1080
vless://%75uid@example.com:443#escaped-user
hy2://pw@h.example:443/?obfs=salamander&obfs-password=a%2Bb+c#plus-in-query
vless://uuid@lead.example:443#leading-space
vmess://eyJ2IjoiMiIsInBzIjoiaDIgcGF0aCIsImFkZCI6InguZXhhbXBsZSIsInBvcnQiOiI0NDMiLCJpZCI6ImkiLCJuZXQiOiJodHRwIiwiaG9zdCI6ImgiLCJwYXRoIjoiL3AiLCJ0bHMiOiJ0bHMiLCJhbHBuIjoiaDIsaHR0cC8xLjEifQ==

View File

@ -0,0 +1,773 @@
[
{
"alpn": [
"h3",
"h4"
],
"down": "514",
"fingerprint": "65b3acd7db555768304a16abb6f4366c1a0c0bb5cec81429617f0150d7d66726",
"name": "hy2test",
"obfs": "salamander",
"obfs-password": "gawrgura",
"password": "letmein",
"port": "8443",
"server": "example.com",
"skip-cert-verify": true,
"sni": "real.example.com",
"type": "hysteria2",
"up": "114"
},
{
"down": "",
"fingerprint": "",
"name": "hop",
"obfs": "",
"obfs-password": "",
"password": "letmein",
"port": "443",
"ports": "443,5000-6000",
"server": "example.com",
"skip-cert-verify": false,
"sni": "example.com",
"type": "hysteria2",
"up": ""
},
{
"down": "",
"fingerprint": "",
"name": "realm",
"obfs": "",
"obfs-password": "",
"password": "letmein",
"port": "8443",
"realm-opts": {
"enable": true,
"realm-id": "rid42",
"server-url": "https://rendezvous.example.com:8443",
"stun-servers": [
"stun1:3478",
"stun2:3478"
],
"token": "tok3n"
},
"server": "rendezvous.example.com",
"skip-cert-verify": false,
"sni": "example.com",
"type": "hysteria2",
"up": ""
},
{
"down": "",
"fingerprint": "",
"name": "v6 hy2",
"obfs": "",
"obfs-password": "",
"password": "p%40ss%3Aw0rd",
"port": "8443",
"server": "2001:db8::1",
"skip-cert-verify": false,
"sni": "x.example",
"type": "hysteria2",
"up": ""
},
{
"down": "",
"fingerprint": "",
"name": "noport",
"obfs": "",
"obfs-password": "",
"password": "pw",
"port": "443",
"server": "h.example",
"skip-cert-verify": false,
"sni": "",
"type": "hysteria2",
"up": ""
},
{
"handshake-mode": "HANDSHAKE_NO_WAIT",
"multiplexing": "MULTIPLEXING_HIGH",
"name": "default:6666/TCP",
"password": "pass",
"port": 6666,
"server": "1.2.3.4",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
"transport": "TCP",
"type": "mieru",
"udp": true,
"username": "user"
},
{
"handshake-mode": "HANDSHAKE_NO_WAIT",
"multiplexing": "MULTIPLEXING_HIGH",
"name": "default:9998-9999/TCP",
"password": "pass",
"port-range": "9998-9999",
"server": "1.2.3.4",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
"transport": "TCP",
"type": "mieru",
"udp": true,
"username": "user"
},
{
"handshake-mode": "HANDSHAKE_NO_WAIT",
"multiplexing": "MULTIPLEXING_HIGH",
"name": "default:6489/UDP",
"password": "pass",
"port": 6489,
"server": "1.2.3.4",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
"transport": "UDP",
"type": "mieru",
"udp": true,
"username": "user"
},
{
"handshake-mode": "HANDSHAKE_NO_WAIT",
"multiplexing": "MULTIPLEXING_HIGH",
"name": "default:4896/UDP",
"password": "pass",
"port": 4896,
"server": "1.2.3.4",
"traffic-pattern": "CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3",
"transport": "UDP",
"type": "mieru",
"udp": true,
"username": "user"
},
{
"name": "simple:443/TCP",
"password": "pass",
"port": 443,
"server": "example.com",
"transport": "TCP",
"type": "mieru",
"udp": true,
"username": "user"
},
{
"client-fingerprint": "chrome",
"encryption": "none",
"flow": "xtls-rprx-vision",
"name": "My-VLESS-Reality-Vision",
"network": "tcp",
"port": "34888",
"reality-opts": {
"public-key": "ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw",
"short-id": "6ba85179f3a2b4c5"
},
"server": "142.98.76.54",
"servername": "github.io",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "a1b2c3d4-eacc-4433-981b-7e5f9a8b",
"xudp": true
},
{
"client-fingerprint": "chrome",
"http-opts": {
"headers": {
"Host": [
"cdn.example.com"
]
},
"method": "POST",
"path": [
"/edge"
]
},
"name": "vless-http",
"network": "http",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"client-fingerprint": "chrome",
"h2-opts": {
"host": [
"cdn.example.com"
],
"path": "/grpc"
},
"name": "vless-h2",
"network": "h2",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"alpn": [
"h2",
"http/1.1"
],
"client-fingerprint": "chrome",
"name": "ws ed",
"network": "ws",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"ws-opts": {
"early-data-header-name": "Sec-WebSocket-Protocol",
"headers": {
"Host": "cdn.example.com",
"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"
},
"max-early-data": 2048,
"path": "/ws?ed=2048"
},
"xudp": true
},
{
"name": "hu",
"network": "httpupgrade",
"port": "443",
"server": "example.com",
"type": "vless",
"udp": true,
"uuid": "uuid",
"ws-opts": {
"early-data-header-name": "X-Ed",
"headers": {
"Host": "h",
"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",
"v2ray-http-upgrade-fast-open": true
},
"xudp": true
},
{
"client-fingerprint": "chrome",
"grpc-opts": {
"grpc-service-name": "svc"
},
"name": "grpc",
"network": "grpc",
"packet-addr": true,
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid"
},
{
"client-fingerprint": "chrome",
"name": "xhttp extra",
"network": "xhttp",
"port": "443",
"reality-opts": {
"public-key": "K",
"short-id": "ab",
"support-x25519mlkem768": true
},
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xhttp-opts": {
"download-settings": {
"path": "/d",
"port": 443,
"reality-opts": {
"public-key": "P",
"short-id": "s"
},
"server": "d.example",
"tls": true
},
"host": "x.example",
"mode": "packet-up",
"no-grpc-header": true,
"path": "/x",
"reuse-settings": {
"h-keep-alive-period": 30,
"max-concurrency": "16-32"
},
"x-padding-bytes": "100-1000"
},
"xudp": true
},
{
"client-fingerprint": "firefox",
"fingerprint": "abc",
"flow": "xtls-rprx-vision",
"name": "flow",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid"
},
{
"client-fingerprint": "chrome",
"name": "b64host",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"name": "semicolon",
"network": "tcp",
"port": "443",
"server": "example.com",
"servername": "s",
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"name": "badesc",
"network": "tcp",
"port": "443",
"server": "example.com",
"servername": "a b",
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"alterId": "0",
"cipher": "auto",
"h2-opts": {
"host": [
"cdn.example.com"
],
"path": "/grpc"
},
"name": "demo",
"network": "h2",
"port": "443",
"server": "server.example.com",
"skip-cert-verify": false,
"tls": true,
"type": "vmess",
"udp": true,
"uuid": "b831381d-6324-4d53-ad4f-8cda48b30811",
"xudp": true
},
{
"alpn": [
"h2"
],
"alterId": 0,
"cipher": "auto",
"name": "ws ed-01",
"network": "ws",
"port": 443,
"server": "v.example.com",
"servername": "s.example",
"skip-cert-verify": false,
"tls": true,
"type": "vmess",
"udp": true,
"uuid": "id",
"ws-opts": {
"early-data-header-name": "Sec-WebSocket-Protocol",
"headers": {
"Host": "v.example.com"
},
"max-early-data": 2048,
"path": "/w?a=1&b=2"
},
"xudp": true
},
{
"alterId": 0,
"cipher": "auto",
"http-opts": {
"headers": {
"Host": [
"hh"
]
},
"path": [
"/p"
]
},
"name": "http",
"network": "http",
"port": "80",
"server": "v.example.com",
"skip-cert-verify": false,
"tls": false,
"type": "vmess",
"udp": true,
"uuid": "id",
"xudp": true
},
{
"alterId": 0,
"cipher": "aes-128-gcm",
"grpc-opts": {
"grpc-service-name": "svc"
},
"name": "grpc-01",
"network": "grpc",
"port": "443",
"server": "v.example.com",
"skip-cert-verify": false,
"tls": true,
"type": "vmess",
"udp": true,
"uuid": "id",
"xudp": true
},
{
"alterId": 0,
"cipher": "auto",
"name": "demo-01",
"network": "tcp",
"port": "443",
"server": "dup.example.com",
"skip-cert-verify": false,
"tls": false,
"type": "vmess",
"udp": true,
"uuid": "id",
"xudp": true
},
{
"alterId": 0,
"cipher": "auto",
"name": "hu-01",
"network": "httpupgrade",
"port": "443",
"server": "v.example.com",
"skip-cert-verify": false,
"tls": false,
"type": "vmess",
"udp": true,
"uuid": "id",
"ws-opts": {
"early-data-header-name": "X",
"headers": {},
"path": "/u?eh=X",
"v2ray-http-upgrade-fast-open": true
},
"xudp": true
},
{
"alterId": 0,
"cipher": "aes-128-gcm",
"client-fingerprint": "chrome",
"name": "aead",
"network": "ws",
"port": "443",
"server": "aead.example.com",
"tls": true,
"type": "vmess",
"udp": true,
"uuid": "uuid",
"ws-opts": {
"headers": {
"Host": "h",
"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": "/a"
},
"xudp": true
},
{
"alpn": [
"h2"
],
"client-fingerprint": "chrome",
"grpc-opts": {
"grpc-service-name": "g"
},
"name": "tr",
"network": "grpc",
"password": "pw",
"port": "443",
"server": "t.example.org",
"skip-cert-verify": true,
"sni": "t.example.org",
"type": "trojan",
"udp": true
},
{
"client-fingerprint": "safari",
"fingerprint": "deadbeef",
"name": "tr-ws",
"network": "ws",
"password": "p@w",
"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": "/ws"
}
},
{
"client-fingerprint": "chrome",
"name": "tr-badbool",
"password": "pw",
"port": "443",
"server": "t.example.org",
"skip-cert-verify": false,
"type": "trojan",
"udp": true
},
{
"cipher": "aes-256-gcm",
"name": "ss1",
"password": "pass",
"port": "8388",
"server": "1.2.3.4",
"type": "ss",
"udp": true
},
{
"cipher": "aes-256-gcm",
"name": "ss-padded",
"password": "pass",
"port": "8389",
"server": "1.2.3.4",
"type": "ss",
"udp": true
},
{
"cipher": "chacha20-ietf-poly1305",
"name": "ss-sip002-old",
"password": "secret",
"port": "9000",
"server": "5.6.7.8",
"type": "ss",
"udp": true
},
{
"cipher": "2022-blake3-aes-128-gcm",
"name": "ss2022",
"password": "YWJjZGVmZ2hpamtsbW5vcA==",
"port": "443",
"server": "9.9.9.9",
"type": "ss",
"udp": true,
"udp-over-tcp": true
},
{
"cipher": "aes-128-gcm",
"name": "ss-obfs",
"password": "pw",
"plugin": "obfs",
"plugin-opts": {
"host": "bing.com",
"mode": "http"
},
"port": "443",
"server": "h.example",
"type": "ss",
"udp": true
},
{
"cipher": "aes-128-gcm",
"name": "ss-v2ray",
"password": "pw",
"plugin": "v2ray-plugin",
"plugin-opts": {
"host": "h.example",
"mode": "websocket",
"path": "/v",
"tls": true
},
"port": "443",
"server": "h.example",
"type": "ss",
"udp": true
},
{
"alpn": [
"h3"
],
"congestion-controller": "bbr",
"disable-sni": true,
"name": "tuic5",
"password": "pass",
"port": "443",
"server": "tu.example",
"sni": "tu.example",
"type": "tuic",
"udp": true,
"udp-relay-mode": "native",
"uuid": "uuid"
},
{
"name": "tuic4",
"port": "443",
"server": "tu.example",
"token": "token",
"type": "tuic",
"udp": true
},
{
"fingerprint": "xx",
"name": "any",
"password": "pw",
"port": "443",
"server": "an.example",
"skip-cert-verify": true,
"sni": "an.example",
"type": "anytls",
"udp": true,
"username": "pw"
},
{
"fingerprint": "",
"name": "an.example:8443",
"password": "pw",
"port": "8443",
"server": "an.example",
"skip-cert-verify": false,
"sni": "",
"type": "anytls",
"udp": true,
"username": "user"
},
{
"name": "sk",
"password": "pass",
"port": "1080",
"server": "1.1.1.1",
"skip-cert-verify": true,
"type": "socks5",
"username": "user"
},
{
"name": "2.2.2.2:3128",
"password": "",
"port": "3128",
"server": "2.2.2.2",
"skip-cert-verify": true,
"type": "http",
"username": ""
},
{
"name": "tlsproxy",
"password": "pass",
"port": "443",
"server": "3.3.3.3",
"skip-cert-verify": true,
"tls": true,
"type": "http",
"username": "user"
},
{
"cipher": "aes-256-cfb",
"name": "ssr name",
"obfs": "plain",
"obfs-param": "op",
"password": "pwd",
"port": "443",
"protocol": "origin",
"server": "1.2.3.4",
"type": "ssr",
"udp": true
},
{
"alpn": [
"h3"
],
"auth_str": "a",
"down": "50",
"name": "hy1",
"obfs": "xplus",
"port": "443",
"protocol": "udp",
"server": "h1.example",
"skip-cert-verify": true,
"sni": "sni.example",
"type": "hysteria",
"up": "10"
},
{
"client-fingerprint": "chrome",
"name": "v6vless",
"network": "tcp",
"port": "443",
"server": "2001:db8::2",
"servername": "v6.example",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"client-fingerprint": "chrome",
"name": "✓ emoji 🇩🇪",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"client-fingerprint": "chrome",
"name": "dup",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"client-fingerprint": "chrome",
"name": "dup-01",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"client-fingerprint": "chrome",
"name": "dup-02",
"network": "tcp",
"port": "443",
"server": "example.com",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
}
]

53
tests/links/links.txt Normal file
View File

@ -0,0 +1,53 @@
hysteria2://letmein@example.com:8443/?insecure=1&obfs=salamander&obfs-password=gawrgura&pinSHA256=65b3acd7db555768304a16abb6f4366c1a0c0bb5cec81429617f0150d7d66726&sni=real.example.com&up=114&down=514&alpn=h3,h4#hy2test
hysteria2://letmein@example.com:443,5000-6000/?sni=example.com#hop
hysteria2+realm://tok3n@rendezvous.example.com:8443/rid42?auth=letmein&stun=stun1:3478&stun=stun2:3478&sni=example.com#realm
hy2://p%40ss%3Aw0rd@[2001:db8::1]:8443?sni=x.example#v6%20hy2
hy2://pw@h.example#noport
mierus://user:pass@1.2.3.4?handshake-mode=HANDSHAKE_NO_WAIT&mtu=1400&multiplexing=MULTIPLEXING_HIGH&port=6666&port=9998-9999&port=6489&port=4896&profile=default&protocol=TCP&protocol=TCP&protocol=UDP&protocol=UDP&traffic-pattern=CCoQARoECAEQCiIYCAMQASoIMDAwMTAyMDMqCDA0MDUwNjA3
mierus://user:pass@example.com?port=443&protocol=TCP&profile=simple
vless://a1b2c3d4-eacc-4433-981b-7e5f9a8b@142.98.76.54:34888?encryption=none&security=reality&type=tcp&sni=github.io&fp=chrome&pbk=ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw&sid=6ba85179f3a2b4c5&flow=xtls-rprx-vision#My-VLESS-Reality-Vision
vless://uuid@example.com:443?security=tls&type=tcp&headerType=http&host=cdn.example.com&path=%2Fedge&method=POST#vless-http
vless://uuid@example.com:443?security=tls&type=http&host=cdn.example.com&path=%2Fgrpc#vless-h2
vless://uuid@example.com:443?security=tls&type=ws&host=cdn.example.com&path=%2Fws%3Fed%3D2048&ed=2048&alpn=h2,http/1.1#ws%20ed
vless://uuid@example.com:443?security=none&type=httpupgrade&host=h&path=%2Fu&ed=1024&eh=X-Ed#hu
vless://uuid@example.com:443?security=tls&type=grpc&serviceName=svc&packetEncoding=packet#grpc
vless://uuid@example.com:443?security=reality&type=xhttp&pbk=K&sid=ab&mode=packet-up&host=x.example&path=%2Fx&support-x25519mlkem768=true&extra=%7B%22xPaddingBytes%22%3A%22100-1000%22%2C%22noGRPCHeader%22%3Atrue%2C%22xmux%22%3A%7B%22maxConcurrency%22%3A%2216-32%22%2C%22hKeepAlivePeriod%22%3A30%7D%2C%22downloadSettings%22%3A%7B%22address%22%3A%22d.example%22%2C%22port%22%3A443%2C%22security%22%3A%22reality%22%2C%22realitySettings%22%3A%7B%22publicKey%22%3A%22P%22%2C%22shortId%22%3A%22s%22%7D%2C%22xhttpSettings%22%3A%7B%22path%22%3A%22%2Fd%22%7D%7D%7D#xhttp%20extra
vless://uuid@example.com:443?packetEncoding=none&flow=XTLS-RPRX-VISION&fp=firefox&security=tls&pcs=abc#flow
vless://uuid@example.com?security=tls#noport
vless://uuid@ZXhhbXBsZS5jb206NDQz?security=tls#b64host
vless://uuid@example.com:443?type=ws&ed=abc#bad-ed
vless://uuid@example.com:443?a=b;c=d&sni=s#semicolon
vless://uuid@example.com:443?sni=a+b&path=%zz#badesc
vmess://eyJ2IjoiMiIsInBzIjoiZGVtbyIsImFkZCI6InNlcnZlci5leGFtcGxlLmNvbSIsInBvcnQiOiI0NDMiLCJpZCI6ImI4MzEzODFkLTYzMjQtNGQ1My1hZDRmLThjZGE0OGIzMDgxMSIsImFpZCI6IjAiLCJzY3kiOiJhdXRvIiwibmV0IjoiaDIiLCJ0eXBlIjoibm9uZSIsImhvc3QiOiJjZG4uZXhhbXBsZS5jb20iLCJwYXRoIjoiL2dycGMiLCJ0bHMiOiJ0bHMifQ==
vmess://eyJ2IjoiMiIsInBzIjoid3MgZWQiLCJhZGQiOiJ2LmV4YW1wbGUuY29tIiwicG9ydCI6NDQzLCJpZCI6ImlkIiwiYWlkIjowLCJuZXQiOiJ3cyIsImhvc3QiOiJ2LmV4YW1wbGUuY29tIiwicGF0aCI6Ii93P2VkPTIwNDgmYj0yJmE9MSIsInRscyI6InRscyIsInNuaSI6InMuZXhhbXBsZSIsImFscG4iOiJoMiJ9
vmess://eyJ2IjoiMiIsInBzIjoiaHR0cCIsImFkZCI6InYuZXhhbXBsZS5jb20iLCJwb3J0IjoiODAiLCJpZCI6ImlkIiwibmV0IjoidGNwIiwidHlwZSI6Imh0dHAiLCJob3N0IjoiaGgiLCJwYXRoIjoiL3AifQ==
vmess://eyJ2IjoiMiIsInBzIjoiZ3JwYyIsImFkZCI6InYuZXhhbXBsZS5jb20iLCJwb3J0IjoiNDQzIiwiaWQiOiJpZCIsIm5ldCI6ImdycGMiLCJwYXRoIjoic3ZjIiwidGxzIjoiVExTIiwic2N5IjoiYWVzLTEyOC1nY20ifQ==
vmess://eyJ2IjoiMiIsInBzIjoiZGVtbyIsImFkZCI6ImR1cC5leGFtcGxlLmNvbSIsInBvcnQiOiI0NDMiLCJpZCI6ImlkIiwibmV0IjoidGNwIn0=
vmess://eyJ2IjoiMiIsInBzIjoiaHUiLCJhZGQiOiJ2LmV4YW1wbGUuY29tIiwicG9ydCI6IjQ0MyIsImlkIjoiaWQiLCJuZXQiOiJodHRwdXBncmFkZSIsInBhdGgiOiIvdT9lZD0xMDI0JmVoPVgifQ==
vmess://eyJ2IjoiMiIsImFkZCI6Im5vbmFtZS5leGFtcGxlLmNvbSIsInBvcnQiOiI0NDMiLCJpZCI6ImlkIn0=
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://p%40w@t.example.org:443?type=ws&path=%2Fws&fp=safari&pcs=deadbeef#tr-ws
trojan://pw@t.example.org:443?allowInsecure=yes#tr-badbool
ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#ss1
ss://YWVzLTI1Ni1nY206cGFzcw==@1.2.3.4:8389#ss-padded
ss://Y2hhY2hhMjAtaWV0Zi1wb2x5MTMwNTpzZWNyZXRANS42LjcuODo5MDAw#ss-sip002-old
ss://2022-blake3-aes-128-gcm:YWJjZGVmZ2hpamtsbW5vcA%3D%3D@9.9.9.9:443?uot=1#ss2022
ss://YWVzLTEyOC1nY206cHc@h.example:443?plugin=obfs-local%3Bobfs%3Dhttp%3Bobfs-host%3Dbing.com#ss-obfs
ss://YWVzLTEyOC1nY206cHc@h.example:443?plugin=v2ray-plugin%3Bmode%3Dwebsocket%3Bhost%3Dh.example%3Bpath%3D%2Fv%3Btls#ss-v2ray
tuic://uuid:pass@tu.example:443?congestion_control=bbr&alpn=h3&sni=tu.example&udp_relay_mode=native&disable_sni=1#tuic5
tuic://token@tu.example:443#tuic4
anytls://pw@an.example:443?sni=an.example&insecure=1&hpkp=xx#any
anytls://user:pw@an.example:8443
socks5://dXNlcjpwYXNz@1.1.1.1:1080#sk
http://2.2.2.2:3128
https://dXNlcjpwYXNz@3.3.3.3:443#tlsproxy
ssr://MS4yLjMuNDo0NDM6b3JpZ2luOmFlcy0yNTYtY2ZiOnBsYWluOmNIZGsvP3JlbWFya3M9YzNOeUlHNWhiV1Umb2Jmc3BhcmFtPWIzQQ
hysteria://h1.example:443?peer=sni.example&auth=a&upmbps=10&downmbps=50&obfs=xplus&alpn=h3&protocol=udp&insecure=true#hy1
unknown://foo@bar:1
just text
vless://uuid@[2001:db8::2]:443?security=tls&sni=v6.example#v6vless
vless://uuid@example.com:443?security=tls#%E2%9C%93%20emoji%20%F0%9F%87%A9%F0%9F%87%AA
vless://uuid@example.com:443?security=tls#dup
vless://uuid@example.com:443?security=tls#dup
vless://uuid@example.com:443?security=tls#dup

1
tests/links/sub.b64 Normal file
View File

@ -0,0 +1 @@
dmxlc3M6Ly91dWlkQHMxLmV4YW1wbGU6NDQzP3NlY3VyaXR5PXJlYWxpdHkmcGJrPUsmc2lkPTEjczEKdHJvamFuOi8vcHdAczIuZXhhbXBsZTo0NDMjczI=

View File

@ -0,0 +1,28 @@
[
{
"client-fingerprint": "chrome",
"name": "s1",
"network": "tcp",
"port": "443",
"reality-opts": {
"public-key": "K",
"short-id": "1"
},
"server": "s1.example",
"tls": true,
"type": "vless",
"udp": true,
"uuid": "uuid",
"xudp": true
},
{
"client-fingerprint": "chrome",
"name": "s2",
"password": "pw",
"port": "443",
"server": "s2.example",
"skip-cert-verify": false,
"type": "trojan",
"udp": true
}
]

View File

@ -0,0 +1 @@
{"port":7890,"proxies":[{"alpn":["h2","http/1.1"],"client-fingerprint":"chrome","name":"🇩🇪 de-1 | vless","network":"xhttp","port":443,"reality-opts":{"public-key":"K-_kk","short-id":"ab"},"server":"x.example","servername":"www.example.com","tls":true,"type":"vless","udp":true,"uuid":"0b1c2d3e-0000-4000-8000-000000000001","xhttp-opts":{"headers":{"X-Forwarded-For":"1.2.3.4"},"mode":"packet-up","path":"/x"}},{"name":"b","password":"p#w","port":443,"server":"t:x","sni":"t.example","type":"trojan","udp":true},{"down":"100 mbps","name":"c","obfs":"salamander","obfs-password":"a\"b\\cé","password":"it's","ports":"2000-3000","server":"h.example","skip-cert-verify":true,"type":"hysteria2","up":"50 mbps"},{"cipher":"aes-256-gcm","name":"d","password":123456,"plugin":"obfs","plugin-opts":{"host":"bing.com","mode":"tls"},"port":8388,"server":"1.2.3.4","type":"ss"},{"alterId":0,"cipher":"auto","name":"e","port":"443","server":"v.example","smux":{"enabled":false,"padding":null},"type":"vmess","uuid":"x","ws-opts":{"headers":{"Host":"v.example"},"path":"/w?ed=2048"}}],"proxy-groups":[{"name":"G","proxies":["b","c"],"type":"select"}]}

61
tests/yaml/clash.yaml Normal file
View File

@ -0,0 +1,61 @@
# a typical subscription / Clash config
port: 7890
proxies:
- name: "🇩🇪 de-1 | vless" # a comment
type: vless
server: x.example
port: 443
uuid: 0b1c2d3e-0000-4000-8000-000000000001
network: xhttp
tls: true
udp: true
servername: www.example.com
client-fingerprint: chrome
alpn: [h2, "http/1.1"]
reality-opts: {public-key: K-_kk, short-id: ab}
xhttp-opts:
path: /x
mode: packet-up
headers:
X-Forwarded-For: 1.2.3.4
- {name: b, type: trojan, server: "t:x", port: 443, password: "p#w", udp: true, sni: t.example}
- name: c
type: hysteria2
server: h.example
ports: 2000-3000
password: 'it''s'
up: 50 mbps
down: "100 mbps"
obfs: salamander
obfs-password: "a\"b\\cé"
skip-cert-verify: True
- name: d
type: ss
server: 1.2.3.4
port: 8388
cipher: aes-256-gcm
password: 123456
plugin: obfs
plugin-opts:
mode: tls
host: bing.com
-
name: e
type: vmess
server: v.example
port: "443"
uuid: x
alterId: 0
cipher: auto
ws-opts:
path: "/w?ed=2048"
headers: {Host: v.example}
smux:
enabled: false
padding: ~
proxy-groups:
- name: G
type: select
proxies:
- b
- c

View File

@ -0,0 +1 @@
[{"colon-in":"http://a.example:8080/p","dash":"-","empty":null,"float":1.5,"folded":"word one word two\npara","hash-in":"a#b","hex":31,"multi":["a","b","c"],"name":"one","neg":-3,"nested":[[1,2],{"k":"v","k2":["a",{"x":1}]}],"port":1080,"quoted":"two lines","server":"s.example","str-num":"443","text":"line 1\nline 2\n","type":"socks5"}]

29
tests/yaml/list.yaml Normal file
View File

@ -0,0 +1,29 @@
- name: one
type: socks5
server: s.example
port: 1080
empty:
nested:
- - 1
- 2
- k: v
k2: [a, {x: 1}]
multi: [a,
b, c]
text: |
line 1
line 2
folded: >-
word one
word two
para
quoted: "two
lines"
float: 1.5
hex: 0x1F
neg: -3
str-num: "443"
colon-in: http://a.example:8080/p
hash-in: a#b
dash: "-"

View File

@ -0,0 +1 @@
{"name":"single","password":"pw","port":443,"server":"an.example","type":"anytls"}

5
tests/yaml/one.yaml Normal file
View File

@ -0,0 +1,5 @@
name: single
type: anytls
server: an.example
port: 443
password: "pw"

View File

@ -1,21 +0,0 @@
#!/usr/bin/env python3
"""Build web/index.html: web/index.src.html + web/engine.js + templates/ inlined.
The result is one self-contained file: open it from disk or put it on any
static host. Run after changing templates/ or web/.
"""
import json
import pathlib
root = pathlib.Path(__file__).resolve().parent.parent
templates = {
f"{p.parent.name}/{p.name}": p.read_text(encoding="utf-8")
for p in sorted((root / "templates").glob("*/*.yaml"))
}
engine = (root / "web" / "engine.js").read_text(encoding="utf-8")
page = (root / "web" / "index.src.html").read_text(encoding="utf-8")
tpl_json = json.dumps(templates, ensure_ascii=False, indent=1).replace("</", "<\\/")
page = page.replace("/*__ENGINE__*/", engine).replace("/*__TEMPLATES__*/", tpl_json)
(root / "web" / "index.html").write_text(page, encoding="utf-8")
print(f"web/index.html: {len(templates)} templates")

View File

@ -1,22 +0,0 @@
#!/usr/bin/env node
// Render a profile with web/engine.js. Variables come from the environment:
// sh -c 'set -a; . common.env; . home.env; node tools/render.js'
const fs = require("fs");
const path = require("path");
const { render, DEFAULTS } = require("../web/engine.js");
const tplDir = path.join(__dirname, "..", "templates");
const templates = {};
for (const dir of fs.readdirSync(tplDir)) {
const full = path.join(tplDir, dir);
if (!fs.statSync(full).isDirectory()) continue;
for (const f of fs.readdirSync(full)) templates[`${dir}/${f}`] = fs.readFileSync(path.join(full, f), "utf8");
}
const vars = {};
for (const [k, val] of Object.entries(process.env)) if (k in DEFAULTS || /^(SUB[0-9]*|HY2)_/.test(k)) vars[k] = val;
try {
process.stdout.write(render(templates, vars));
} catch (e) {
console.error("error: " + e.message);
process.exit(1);
}

42
tools/test-servers.js Executable file
View File

@ -0,0 +1,42 @@
#!/usr/bin/env node
// luci/servers.js against mihomo's own Go code: tests/links/<x>.expected.json is
// common/convert.ConvertsV2Ray of <x> (ws User-Agent set to servers.js's fixed one),
// tests/yaml/<x>.expected.json is go.yaml.in/yaml/v3 of <x>.yaml.
const fs = require("fs");
const path = require("path");
const s = require("../luci/servers.js");
const root = path.join(__dirname, "..", "tests");
const canon = (v) => Array.isArray(v) ? v.map(canon)
: v && typeof v == "object" ? Object.keys(v).sort().reduce((o, k) => (o[k] = canon(v[k]), o), {}) : v;
let fail = 0;
const check = (name, want, got) => {
const a = JSON.stringify(canon(want)), b = JSON.stringify(canon(got));
if (a === b)
return console.log("ok " + name);
fail = 1;
console.log("FAIL " + name + "\n want " + a + "\n got " + b);
};
for (const f of fs.readdirSync(path.join(root, "links"))) {
if (f.endsWith(".expected.json"))
continue;
const exp = path.join(root, "links", f.replace(/\.[^.]+$/, ".expected.json"));
check("links/" + f, JSON.parse(fs.readFileSync(exp, "utf8")),
s.parseLinks(fs.readFileSync(path.join(root, "links", f), "utf8")));
}
for (const f of fs.readdirSync(path.join(root, "yaml"))) {
if (!f.endsWith(".yaml"))
continue;
const want = JSON.parse(fs.readFileSync(path.join(root, "yaml", f.replace(/\.yaml$/, ".expected.json")), "utf8"));
const got = s.yamlLoad(fs.readFileSync(path.join(root, "yaml", f), "utf8"));
check("yaml/" + f, want, got);
// the editor shows yamlDump; it must read back the same
check("yaml/" + f + " (dump)", want, s.yamlLoad(s.yamlDump(got)));
}
// a stored line reads back the same, without dialer-proxy, with no "$" left
const p = { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}", "dialer-proxy": "Z" };
const line = s.toLine(p);
check("toLine", { name: "a$b", type: "ss", server: "h", port: 1, password: "x${Y}" },
line.includes("$") || !line.startsWith('{"name":') ? null : JSON.parse(line));
process.exit(fail);

View File

@ -1,7 +1,9 @@
#!/bin/sh #!/bin/sh
# Render every fixture with router/mihomo-kit.sh and web/engine.js, diff them, # Render every fixture with router/mihomo-kit.sh and compare with tests/expected/,
# and (if MIHOMO points to a mihomo binary) validate with `mihomo -t`. # validate with `mihomo -t` when MIHOMO points to a mihomo binary, and check
# tools/test.sh parity only # luci/servers.js (share links, YAML) against the outputs of mihomo's own Go code.
# tools/test.sh
# 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
set -u set -u
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
@ -13,23 +15,30 @@ if [ -n "${MIHOMO:-}" ]; then
echo '+.example.ru' > "$out/ru-inside.txt" echo '+.example.ru' > "$out/ru-inside.txt"
"$MIHOMO" convert-ruleset domain text "$out/ru-inside.txt" "$out/home/ruleset/ru-inside.mrs" >/dev/null "$MIHOMO" convert-ruleset domain text "$out/ru-inside.txt" "$out/home/ruleset/ru-inside.mrs" >/dev/null
fi fi
mkdir -p tests/expected
for f in tests/fixtures/*.env; do for f in tests/fixtures/*.env; do
n=$(basename "$f" .env) n=$(basename "$f" .env)
[ "$n" = common ] && continue [ "$n" = common ] && continue
sh router/mihomo-kit.sh render tests/fixtures/common.env "$f" > "$out/$n.sh.yaml" || { echo "FAIL $n: sh render"; fail=1; continue; } sh router/mihomo-kit.sh render tests/fixtures/common.env "$f" > "$out/$n.yaml" || { echo "FAIL $n: render"; fail=1; continue; }
sh -c 'set -a; . tests/fixtures/common.env; . "$1"; node tools/render.js' _ "$f" > "$out/$n.js.yaml" || { echo "FAIL $n: js render"; fail=1; continue; } if [ "${UPDATE:-0}" = 1 ]; then
if ! diff -u "$out/$n.sh.yaml" "$out/$n.js.yaml"; then cp "$out/$n.yaml" "tests/expected/$n.yaml"
echo "FAIL $n: sh and js differ" elif ! diff -u "tests/expected/$n.yaml" "$out/$n.yaml"; then
echo "FAIL $n: differs from tests/expected/$n.yaml (UPDATE=1 if intended)"
fail=1 fail=1
continue continue
fi fi
if [ -n "${MIHOMO:-}" ]; then if [ -n "${MIHOMO:-}" ]; then
cp "$out/$n.sh.yaml" "$out/home/$n.yaml" cp "$out/$n.yaml" "$out/home/$n.yaml"
if ! "$MIHOMO" -t -d "$out/home" -f "$out/home/$n.yaml" >"$out/$n.log" 2>&1; then if ! "$MIHOMO" -t -d "$out/home" -f "$out/home/$n.yaml" >"$out/$n.log" 2>&1; then
echo "FAIL $n: mihomo -t"; tail -3 "$out/$n.log"; fail=1; continue echo "FAIL $n: mihomo -t"; tail -3 "$out/$n.log"; fail=1; continue
fi fi
fi fi
echo "ok $n" echo "ok $n"
done done
if command -v node >/dev/null 2>&1; then
node tools/test-servers.js || fail=1
else
echo "skip luci/servers.js: no node"
fi
rm -rf "$out" rm -rf "$out"
exit $fail exit $fail

View File

@ -1,358 +0,0 @@
// mihomo-kit renderer, the browser twin of render() in router/mihomo-kit.sh.
// Keep both in sync: tools/test.sh renders the fixtures with both and diffs.
//
// Template syntax:
// file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
// .each = once per item of the module:
// sub - subscription, hy2 - own server
// line ... #@tag[,!tag] kept only if the conditions hold
// line ... ${@VAR} ... repeated for every word of VAR
// line ... ${@@VAR} ... repeated for every line of VAR
// text ${VAR} replaced with the variable
(function (root) {
const DEFAULTS = {
TARGET: "router", LOCATION: "main",
BOOT: "1", TORRENT: "1", PUSH: "1", OPENVPN: "0", TAILSCALE: "0", TS_EXIT: "0",
SUBS: "", RU_IPS: "", HY2: "",
FOREIGN_IPS: "", MY_IPS: "", RU_DOMAINS: "", FOREIGN_DOMAINS: "", MY_DOMAINS: "",
LOCAL_HOSTS: "", MY_LINKS: "",
RULESET_URL: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release",
BOOT_LINKS: "",
BOOT_SERVER: "", BOOT_PORT: "443", BOOT_UUID: "", BOOT_SNI: "", BOOT_PBK: "", BOOT_SID: "",
TS_HOSTNAME: "mihomo", TS_DOMAINS: "",
HWID_UA: "v2rayN/9.99", HWID_OS: "", HWID_OS_VER: "", HWID_MODEL: "", HWID_ID: "",
OVPN_PROVIDER: "bmstu", OVPN_GROUP: "BMSTU", OVPN_SERVER_HOST: "openvpn4.bmstu.ru",
OVPN_SERVER_IPS: "195.19.40.7 195.19.33.86",
OVPN_ROUTES: "172.16.0.0/16 172.19.33.0/24 195.19.32.0/19",
OVPN_CHECK_URL: "https://eu.bmstu.ru", TS_CHECK_URL: "http://100.69.216.50:8080",
CSQTT: "0", CSQTT_IFACE: "csqtt0", CSQTT_PROCESS: "csqtt", LITE: "0",
};
const SECTIONS = [
["head", ""], ["proxies", "proxies:"], ["providers", "proxy-providers:"], ["rule-providers", "rule-providers:"],
["sniffer", ""], ["dns", ""], ["groups", "proxy-groups:"], ["rules", "rules:"],
];
const words = (s) => (s || "").split(/\s+/).filter(Boolean);
function withDefaults(input) {
const v = { ...DEFAULTS };
for (const [k, val] of Object.entries(input || {})) {
if (val !== undefined && val !== null && val !== "") v[k] = String(val);
}
// old names of the profiles (see set_defaults)
v.LOCATION = { home: "main", street: "whitelist" }[v.LOCATION] || v.LOCATION;
return v;
}
// Subscription ids (provider names, keys SUB_<ID>_*), see sub_pairs in
// mihomo-kit.sh: a SUBS word is "url" or "name=url"; without a name the id
// comes from the domain (sub.kittyvpn.com -> kittyvpn); repeats get 2, 3, ...
function autoId(url) {
let h = url.replace(/^.*?:\/\//, "").replace(/[/?#].*$/, "").replace(/^.*@/, "");
h = h.replace(/:[^:]*$/, "").replace(/[A-Z]/g, (c) => c.toLowerCase());
if (h.includes(".")) h = h.replace(/\.[^.]*$/, "");
while (/\.(co|com|net|org|gov|edu|ac)$/.test(h)) h = h.replace(/\.[^.]*$/, "");
const id = h.slice(h.lastIndexOf(".") + 1).replace(/[^a-z0-9_]/g, "_");
return !id ? "sub" : /^[0-9]/.test(id) ? "sub" + id : id;
}
function subPairs(subs) {
const seen = new Set();
return words(subs).map((w) => {
const eq = w.indexOf("=");
let name = "", url = w;
if (eq > 0 && /^[A-Za-z0-9_-]+$/.test(w.slice(0, eq))) {
name = w.slice(0, eq);
url = w.slice(eq + 1);
} else name = autoId(w);
name = name.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/-/g, "_");
let id = name;
for (let k = 2; seen.has(id); k++) id = name + k;
seen.add(id);
return { id, url, word: w };
});
}
// SUB_<ID>_<key>, else the old SUB<index>_<key>
const subGet = (v, i, id, key) => v[`SUB_${id.toUpperCase()}_${key}`] || v[`SUB${i}_${key}`] || "";
// SUB_<ID>_DISABLED=1: kept (id, settings) but left out of the profile
const subOff = (v, i, id) => subGet(v, i, id, "DISABLED") === "1";
// vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name (see vless_parse in mihomo-kit.sh)
function parseVless(link) {
const l = link.replace(/^vless:\/\//, "").replace(/#.*$/, "");
const at = l.indexOf("@");
let hp = (at < 0 ? l : l.slice(at + 1)).replace(/\?.*$/, "");
const c = hp.lastIndexOf(":");
const server = c < 0 ? hp : hp.slice(0, c);
let port = c < 0 ? hp : hp.slice(c + 1);
if (!/^[0-9]+$/.test(port)) port = "443";
const qm = l.indexOf("?");
const q = "&" + (qm < 0 ? l : l.slice(qm + 1)) + "&";
const qv = (k) => {
const i = q.indexOf("&" + k + "=");
if (i < 0) return "";
const rest = q.slice(i + k.length + 2);
return rest.slice(0, rest.indexOf("&"));
};
return { server, port, uuid: at < 0 ? l : l.slice(0, at), sni: qv("sni"), pbk: qv("pbk"), sid: qv("sid") };
}
// BOOT seeds: BOOT_LINKS or the old single BOOT_* (see boot_seeds)
function bootSeeds(v) {
if (words(v.BOOT_LINKS).length)
return words(v.BOOT_LINKS).map((l, i) => ({ name: i ? `seed${i + 1}` : "seed", ...parseVless(l) }));
if (v.BOOT_SERVER)
return [{ name: "seed", server: v.BOOT_SERVER, port: v.BOOT_PORT, uuid: v.BOOT_UUID,
sni: v.BOOT_SNI, pbk: v.BOOT_PBK, sid: v.BOOT_SID }];
return [];
}
const seedVars = (s) => ({ SEED_NAME: s.name, SEED_SERVER: s.server, SEED_PORT: s.port, SEED_UUID: s.uuid,
SEED_SNI: s.sni, SEED_PBK: s.pbk, SEED_SID: s.sid });
// HY2_<NAME> prefix of an own hysteria2 server's keys (see hy2_key)
const hy2Key = (name) => "HY2_" + name.replace(/[a-z]/g, (c) => c.toUpperCase()).replace(/-/g, "_");
// variables for templates/proxies/*-hy2.each.yaml (see hy2_vars in mihomo-kit.sh)
function hy2Vars(v, name) {
const k = (key) => v[`${hy2Key(name)}_${key}`] || "";
const obfs = k("OBFS_PASSWORD");
return {
HY2_NAME: name, HY2_SERVER: k("SERVER"), HY2_PORT: k("PORT"), HY2_PASSWORD: yq(k("PASSWORD")),
HY2_OBFS: obfs ? "salamander" : "", HY2_OBFS_PASSWORD: obfs ? yq(obfs) : "",
HY2_SNI: k("SNI"), HY2_INSECURE: k("INSECURE") === "1" ? "true" : "false",
HY2_UP: yq(k("UP")), HY2_DOWN: yq(k("DOWN")),
};
}
// own lists of the settings (see norm_list): domains without "*." / "+." / "."
// (DOMAIN-SUFFIX covers subdomains), IPs without a mask get /32 (/128)
const normList = (kind, s) => words(s).map((w) => {
if (kind === "dom") return w.replace(/^\*/, "").replace(/^\+/, "").replace(/^\./, "");
return w.includes("/") ? w : w + (w.includes(":") ? "/128" : "/32");
}).filter(Boolean).join(" ");
// LOCAL_HOSTS "a.com=192.168.1.10 ..." -> LOCAL_DOMAINS, LOCAL_HOSTS_YAML (see local_hosts_vars)
function localHostsVars(v, tags) {
v.LOCAL_DOMAINS = "";
v.LOCAL_HOSTS_YAML = "";
if (!tags.has("local_hosts")) return;
const doms = [], lines = [];
for (const w of words(v.LOCAL_HOSTS)) {
const eq = w.indexOf("=");
const d = (eq < 0 ? w : w.slice(0, eq)).replace(/^\*/, "").replace(/^\+/, "").replace(/^\./, "");
const a = eq < 0 ? "" : w.slice(eq + 1);
if (eq < 0) throw new Error(`LOCAL_HOSTS: '${w}' is not domain=address`);
if (!/^[A-Za-z0-9.-]+$/.test(d)) throw new Error(`LOCAL_HOSTS: bad domain in '${w}'`);
if (!/^[0-9A-Fa-f.:]+$/.test(a)) throw new Error(`LOCAL_HOSTS: bad address in '${w}'`);
doms.push(d);
lines.push(`'+.${d}': ${a}`);
}
v.LOCAL_DOMAINS = doms.join(" ");
v.LOCAL_HOSTS_YAML = lines.join("\n");
}
// the URL's host is one of LOCAL_DOMAINS or under one (see is_local_url)
function isLocalUrl(v, url) {
let h = url.replace(/^[^:]*:\/\//, "").split("/")[0].split("?")[0];
h = h.slice(h.lastIndexOf("@") + 1).replace(/:[^:]*$/, "");
return words(v.LOCAL_DOMAINS).some((d) => h === d || h.endsWith("." + d));
}
function check(v) {
if (!words(v.SUBS).length) throw new Error("SUBS is empty (subscription URLs)");
if (!["router", "mobile"].includes(v.TARGET)) throw new Error("TARGET must be router or mobile");
if (!["main", "whitelist", "foreign"].includes(v.LOCATION)) throw new Error("LOCATION must be main, whitelist or foreign");
for (const l of words(v.MY_LINKS)) {
if (!/^(vless|vmess|trojan|ss|hysteria2|hy2|tuic|anytls):\/\/./.test(l))
throw new Error(`MY_LINKS: '${l.split("?")[0]}' is not a vless/vmess/trojan/ss/hysteria2/tuic/anytls link`);
}
if (v.BOOT === "1") {
const seeds = bootSeeds(v);
if (!seeds.length) throw new Error("BOOT=1 but no BOOT_LINKS (vless links of the seed nodes)");
for (const s of seeds) {
for (const k of ["server", "uuid", "sni", "pbk", "sid"]) {
if (!s[k]) throw new Error(`BOOT ${s.name}: ${k.toUpperCase()} is empty (vless link needs host, uuid, sni, pbk, sid)`);
}
}
}
let on = 0;
subPairs(v.SUBS).forEach(({ id }, i) => {
if (subOff(v, i, id)) return;
on++;
if (subGet(v, i, id, "PROXY") === "BOOT" && v.BOOT !== "1") throw new Error(`subscription ${id}: PROXY=BOOT but BOOT=0`);
if (subGet(v, i, id, "HWID") === "1") {
for (const k of ["HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) {
if (!v[k]) throw new Error(`${k} is empty (subscription ${id} has HWID=1)`);
}
}
});
if (!on) throw new Error("all subscriptions are disabled (SUB_<ID>_DISABLED=1)");
for (const name of words(v.HY2)) {
if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(`HY2: bad server name ${name} (letters, digits, _ -)`);
for (const key of ["SERVER", "PORT", "PASSWORD"]) {
if (!v[`${hy2Key(name)}_${key}`]) throw new Error(`${hy2Key(name)}_${key} is empty (hysteria2 server ${name})`);
}
}
}
// YAML double-quoted string body
const yq = (s) => String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
// per-subscription variables for the .each templates (see sub_vars in mihomo-kit.sh)
function subVars(v, i, id, url) {
let proxy = subGet(v, i, id, "PROXY") || "BOOT-AUTO";
if (proxy === "none") proxy = "";
// a subscription on an own server in the LAN: no proxy reaches it
if (isLocalUrl(v, url)) proxy = "DIRECT";
let ua = subGet(v, i, id, "UA");
let h = subGet(v, i, id, "HEADERS");
if (subGet(v, i, id, "HWID") === "1") {
ua = ua || v.HWID_UA;
h = `x-device-os=${v.HWID_OS};x-ver-os=${v.HWID_OS_VER};x-device-model=${v.HWID_MODEL};x-hwid=${v.HWID_ID}` + (h ? ";" + h : "");
}
const headers = h.split(";").map((x) => x.trim()).filter(Boolean).map((item) => {
const eq = item.indexOf("=");
const key = (eq < 0 ? item : item.slice(0, eq)).replace(/\s+$/, "");
const val = eq < 0 ? item : item.slice(eq + 1).replace(/^\s+/, "");
return `${key}: ["${yq(val)}"]`;
});
return {
SUB_NAME: id, SUB_URL: url, SUB_PROXY: proxy,
SUB_UA: yq(ua || "mihomo"), SUB_HEADERS: headers.join("\n"),
};
}
function computeTags(v) {
const t = new Set(["base", "sub", v.TARGET]);
if (v.BOOT === "1") t.add("boot");
if (words(v.HY2).length) t.add("hy2");
if (v.TARGET === "router") {
t.add(v.LOCATION);
if (v.TORRENT === "1") t.add("torrent");
if (v.PUSH === "1") t.add("push");
if (v.OPENVPN === "1") t.add("openvpn");
if (v.TAILSCALE === "1") {
t.add("tailscale");
if (v.TS_EXIT === "1") t.add("ts_exit");
}
if (v.CSQTT === "1") t.add("csqtt");
if (v.LITE === "1") t.add("lite");
// own servers in the LAN (LOCAL_HOSTS): only the router is always at home
if (words(v.LOCAL_HOSTS).length) t.add("local_hosts");
// own servers as links (MY_LINKS): a file on the router, the phone cannot read it
if (words(v.MY_LINKS).length) t.add("my_links");
}
// MY has servers for sure: hysteria2 from the settings or links (see compute_tags)
if (t.has("hy2") || t.has("my_links")) t.add("own");
// OpenVPN through OVPN-EXIT: whitelist and abroad (see compute_tags)
if (t.has("router") && (t.has("whitelist") || t.has("foreign"))) t.add("ovpn_exit");
// own servers through MY-EXIT: whitelist and the phone (see compute_tags)
if (t.has("whitelist") || t.has("mobile")) t.add("my_exit");
return t;
}
function subst(s, v) {
return s.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_, name) => v[name] ?? "");
}
function renderText(text, v, tags) {
const out = [];
for (let line of text.replace(/\n$/, "").split("\n")) {
const p = line.indexOf("#@");
if (p >= 0) {
const conds = line.slice(p + 2).split(",");
line = line.slice(0, p).replace(/[ \t]+$/, "");
const ok = conds.every((c) => (c.startsWith("!") ? !tags.has(c.slice(1)) : tags.has(c)));
if (!ok) continue;
}
const m = line.match(/\$\{(@@?)([A-Za-z0-9_]+)\}/);
if (m) {
const pre = line.slice(0, m.index);
const post = line.slice(m.index + m[0].length);
const items = m[1] === "@@" ? (v[m[2]] || "").split("\n").filter(Boolean) : words(v[m[2]]);
for (const w of items) out.push(subst(pre + w + post, v));
continue;
}
out.push(subst(line, v));
}
// like $(...) in sh: drop trailing empty lines
while (out.length && out[out.length - 1] === "") out.pop();
return out.join("\n");
}
// "<module>.<tag>...[.each]" -> {active, each}
function fragmentInfo(spec, tags) {
const [mod, ...rest] = spec.split(".");
let each = false;
if (!tags.has(mod)) return { active: false, each, mod };
for (const t of rest) {
if (t === "each") { each = true; continue; }
if (!tags.has(t)) return { active: false, each, mod };
}
return { active: true, each, mod };
}
function render(templates, input) {
const v = withDefaults(input);
check(v);
const tags = computeTags(v);
for (const k of ["RU_IPS", "FOREIGN_IPS", "MY_IPS"]) v[k] = normList("ip", v[k]);
for (const k of ["RU_DOMAINS", "FOREIGN_DOMAINS", "MY_DOMAINS"]) v[k] = normList("dom", v[k]);
localHostsVars(v, tags);
const subs = subPairs(v.SUBS);
v.SUB_LIST = subs.filter((s, i) => !subOff(v, i, s.id)).map((s) => s.id).join(", ");
// providers of the "[MY] ..." nodes (group MY)
v.MY_SUB_LIST = subs.filter((s, i) => !subOff(v, i, s.id)).map((s) => s.id + "-my")
.concat(tags.has("my_links") ? ["my-links"] : []).join(", ");
const seeds = bootSeeds(v);
v.SEED_LIST = seeds.map((s) => s.name).join(", ");
const hy2 = words(v.HY2);
v.HY2_LIST = hy2.join(", ");
// CSQTT tunnel (star-panel-csqtt): last in MAIN (plain exit through its server)
v.CSQTT_MAIN = tags.has("csqtt") ? ", CSQTT" : "";
const sections = [];
for (const [dir, header] of SECTIONS) {
const files = Object.keys(templates)
.filter((p) => p.startsWith(dir + "/") && p.endsWith(".yaml"))
.sort();
const parts = [];
for (const path of files) {
const name = path.slice(dir.length + 1, -".yaml".length);
const info = fragmentInfo(name.slice(name.indexOf("-") + 1), tags);
if (!info.active) continue;
if (info.each && info.mod === "boot") {
for (const s of seeds) {
const part = renderText(templates[path], { ...v, ...seedVars(s) }, tags);
if (part) parts.push(part);
}
} else if (info.each && info.mod === "hy2") {
for (const name of hy2) {
const part = renderText(templates[path], { ...v, ...hy2Vars(v, name) }, tags);
if (part) parts.push(part);
}
} else if (info.each) {
subs.forEach((s, i) => {
if (subOff(v, i, s.id)) return;
const part = renderText(templates[path], { ...v, ...subVars(v, i, s.id, s.url) }, tags);
if (part) parts.push(part);
});
} else {
const part = renderText(templates[path], v, tags);
if (part) parts.push(part);
}
}
if (!parts.length) continue;
sections.push((header ? header + "\n" : "") + parts.join("\n\n"));
}
return sections.join("\n\n") + "\n";
}
const api = { render, subPairs, DEFAULTS };
if (typeof module !== "undefined" && module.exports) module.exports = api;
else root.MihomoKit = api;
})(typeof window !== "undefined" ? window : globalThis);

View File

@ -1,785 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mihomo-kit</title>
<style>
:root {
--bg: #f6f6f3; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e2e1dc;
--accent: #2f6f4f; --accent-soft: #e4efe8; --err: #b3261e; --code-bg: #f1f0ec;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
}
.wrap { max-width: 1280px; margin: 0 auto; padding: 24px 16px 48px; }
header h1 { font-size: 20px; margin: 0 0 4px; }
header p { margin: 0 0 20px; color: var(--muted); }
.grid { display: grid; grid-template-columns: minmax(0, 420px) minmax(0, 1fr); gap: 20px; align-items: start; }
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
fieldset { border: 0; border-top: 1px solid var(--line); margin: 0; padding: 14px 0 4px; }
fieldset:first-child { border-top: 0; padding-top: 0; }
legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
label { display: block; margin: 8px 0 4px; color: var(--muted); font-size: 13px; }
input[type=text], textarea {
width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--text); font: 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
textarea { min-height: 64px; resize: vertical; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
.seg label { margin: 0; padding: 6px 12px; cursor: pointer; color: var(--text); font-size: 13px; }
.seg input { display: none; }
.seg label:has(input:checked) { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.check { display: flex; gap: 8px; align-items: center; margin: 6px 0; color: var(--text); font-size: 14px; }
.check input { margin: 0; }
.hint { color: var(--muted); font-size: 12px; margin: 4px 0 0; }
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; }
details summary { cursor: pointer; color: var(--muted); font-size: 13px; margin-top: 8px; }
.tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 10px; }
.tabs button, .actions button {
border: 1px solid var(--line); background: var(--panel); color: var(--text);
padding: 6px 12px; border-radius: 6px; cursor: pointer; font: inherit; font-size: 13px;
}
.tabs button[aria-selected=true] { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); font-weight: 600; }
.actions { display: flex; gap: 6px; margin-left: auto; }
.out-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
pre {
margin: 0; padding: 14px; background: var(--code-bg); border: 1px solid var(--line); border-radius: 8px;
overflow: auto; max-height: 78vh; font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre;
}
.error { color: var(--err); margin: 0 0 10px; font-weight: 600; }
.note { color: var(--muted); font-size: 12px; margin-top: 10px; }
.sub { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px 6px; margin-top: 8px; }
.sub-head { display: flex; gap: 8px; align-items: center; }
.sub-head .name { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); min-width: 34px; }
.sub-head input { flex: 1; min-width: 0; }
.sub-opts { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-top: 6px; font-size: 13px; }
.sub-opts select { padding: 4px 6px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--text); font: inherit; }
.sub-opts .check { margin: 0; font-size: 13px; }
.link-btn { border: 0; background: none; color: var(--accent); cursor: pointer; font: inherit; font-size: 13px; padding: 6px 0 0; }
.x-btn { border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 16px; line-height: 1; padding: 2px 4px; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>mihomo-kit — конструктор конфига</h1>
<p>Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у <code>mihomo-kit.sh</code> на роутере.</p>
</header>
<div class="grid">
<form class="panel" id="form" autocomplete="off">
<fieldset>
<legend>Куда</legend>
<div class="row">
<div class="seg">
<label><input type="radio" name="TARGET" value="router" checked>Роутер (nikki)</label>
<label><input type="radio" name="TARGET" value="mobile">Телефон (FlClash)</label>
</div>
<div class="seg" data-router>
<label><input type="radio" name="LOCATION" value="main" checked>Обычный</label>
<label><input type="radio" name="LOCATION" value="whitelist">Белые списки</label>
<label><input type="radio" name="LOCATION" value="foreign">За рубежом</label>
</div>
</div>
<p class="hint" data-router>Обычный — дома в России или за рубежом. Белые списки: OpenVPN через выбранную RU-ноду (группа OVPN-EXIT), свои серверы через MY-EXIT.</p>
<label for="PROFILE_NAME" data-router>Имя профиля на роутере</label>
<input type="text" id="PROFILE_NAME" value="main" data-router>
</fieldset>
<fieldset>
<legend>Подписки</legend>
<div id="subs"></div>
<button type="button" class="link-btn" id="add-sub">+ подписка</button>
<p class="hint">«Через»: откуда качать подписку. Авто = BOOT-AUTO: BOOT (если включён), иначе ноды сохранённых подписок, иначе напрямую.
HWID — для подписок с лимитом устройств (x-hwid, x-device-os, …).</p>
<label for="RU_IPS">Доп. IP через RU (CIDR через пробел)</label>
<input type="text" id="RU_IPS" value="194.190.191.112/32">
<label for="FOREIGN_IPS">Доп. IP через FOREIGN (CIDR через пробел)</label>
<input type="text" id="FOREIGN_IPS">
<label for="RU_DOMAINS">Доп. домены через RU (через пробел, вместе с поддоменами)</label>
<input type="text" id="RU_DOMAINS" placeholder="example.ru *.example.com">
<label for="FOREIGN_DOMAINS">Доп. домены через FOREIGN (через пробел, вместе с поддоменами)</label>
<input type="text" id="FOREIGN_DOMAINS" placeholder="example.com *.example.org">
</fieldset>
<fieldset>
<legend>BOOT</legend>
<label class="check"><input type="checkbox" id="BOOT" checked>Качать подписки через BOOT (seed)</label>
<div data-boot>
<label for="vless">Вставить vless:// ссылку — поля заполнятся сами</label>
<input type="text" id="vless" placeholder="vless://uuid@host:443?security=reality&sni=…&pbk=…&sid=…">
<div class="two">
<div><label for="BOOT_SERVER">server</label><input type="text" id="BOOT_SERVER"></div>
<div><label for="BOOT_PORT">port</label><input type="text" id="BOOT_PORT" value="443"></div>
</div>
<label for="BOOT_UUID">uuid</label><input type="text" id="BOOT_UUID">
<div class="two">
<div><label for="BOOT_SNI">servername (SNI)</label><input type="text" id="BOOT_SNI" value="eh.vk.ru"></div>
<div><label for="BOOT_SID">short-id</label><input type="text" id="BOOT_SID"></div>
</div>
<label for="BOOT_PBK">public-key</label><input type="text" id="BOOT_PBK">
</div>
</fieldset>
<fieldset data-hwid>
<legend>HWID</legend>
<p class="hint">Общий для всех подписок с галкой HWID. Если провайдер уже знает устройство — тот же x-hwid.</p>
<label for="HWID_UA">User-Agent</label><input type="text" id="HWID_UA" value="v2rayN/9.99">
<div class="two">
<div><label for="HWID_OS">x-device-os</label><input type="text" id="HWID_OS" value="OpenWrt"></div>
<div><label for="HWID_OS_VER">x-ver-os</label><input type="text" id="HWID_OS_VER" placeholder="24.10.3"></div>
</div>
<label for="HWID_MODEL">x-device-model</label><input type="text" id="HWID_MODEL" placeholder="Huasifei WH3000 Pro">
<label for="HWID_ID">x-hwid</label><input type="text" id="HWID_ID">
</fieldset>
<fieldset data-router>
<legend>Модули роутера</legend>
<label class="check"><input type="checkbox" id="TORRENT" checked>Торренты (порты 20000–20199 → TORRENT-SEL)</label>
<label class="check"><input type="checkbox" id="PUSH" checked>Обход для пушей (APNs, FCM → группа PUSH)</label>
<label class="check"><input type="checkbox" id="CSQTT">CSQTT (интерфейс csqtt0 от star-panel-csqtt → группа UPLINK)</label>
<label class="check"><input type="checkbox" id="LITE">Облегчённый режим (256 МБ RAM: реже проверки нод, сниффер без QUIC)</label>
<label class="check"><input type="checkbox" id="OPENVPN">OpenVPN (BMSTU, OTP через bmstu-otp.sh)</label>
<details data-openvpn>
<summary>параметры OpenVPN</summary>
<label for="OVPN_SERVER_HOST">сервер</label><input type="text" id="OVPN_SERVER_HOST">
<label for="OVPN_SERVER_IPS">IP сервера (не пускать в туннель)</label><input type="text" id="OVPN_SERVER_IPS">
<label for="OVPN_ROUTES">сети через туннель</label><input type="text" id="OVPN_ROUTES">
</details>
<label class="check"><input type="checkbox" id="TAILSCALE">Tailscale</label>
<div data-tailscale>
<label for="TS_HOSTNAME">hostname ноды</label><input type="text" id="TS_HOSTNAME" value="fudy-mihomo">
<label for="TS_DOMAINS">split-DNS домены тейлнета, кроме *.ts.net</label><input type="text" id="TS_DOMAINS">
<label class="check"><input type="checkbox" id="TS_EXIT">Через TS-EXIT (только ss/hysteria2/tuic ноды)</label>
</div>
</fieldset>
</form>
<section class="panel">
<div class="out-head">
<div class="tabs" role="tablist">
<button type="button" data-tab="yaml" aria-selected="true">config.yaml</button>
<button type="button" data-tab="env" aria-selected="false" data-router>profile .env</button>
<button type="button" data-tab="steps" aria-selected="false">Что дальше</button>
</div>
<div class="actions">
<button type="button" id="copy">Копировать</button>
<button type="button" id="download">Скачать</button>
</div>
</div>
<p class="error" id="error" hidden></p>
<pre id="out"></pre>
<p class="note">На роутере удобнее держать <code>.env</code> и собирать там: <code>mihomo-kit.sh build</code>. YAML отсюда — для телефона или разовой проверки.</p>
</section>
</div>
</div>
<script>
// mihomo-kit renderer, the browser twin of render() in router/mihomo-kit.sh.
// Keep both in sync: tools/test.sh renders the fixtures with both and diffs.
//
// Template syntax:
// file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
// .each = once per item of the module:
// sub - subscription, hy2 - own server
// line ... #@tag[,!tag] kept only if the conditions hold
// line ... ${@VAR} ... repeated for every word of VAR
// line ... ${@@VAR} ... repeated for every line of VAR
// text ${VAR} replaced with the variable
(function (root) {
const DEFAULTS = {
TARGET: "router", LOCATION: "main",
BOOT: "1", TORRENT: "1", PUSH: "1", OPENVPN: "0", TAILSCALE: "0", TS_EXIT: "0",
SUBS: "", RU_IPS: "", HY2: "",
FOREIGN_IPS: "", MY_IPS: "", RU_DOMAINS: "", FOREIGN_DOMAINS: "", MY_DOMAINS: "",
LOCAL_HOSTS: "", MY_LINKS: "",
RULESET_URL: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release",
BOOT_LINKS: "",
BOOT_SERVER: "", BOOT_PORT: "443", BOOT_UUID: "", BOOT_SNI: "", BOOT_PBK: "", BOOT_SID: "",
TS_HOSTNAME: "mihomo", TS_DOMAINS: "",
HWID_UA: "v2rayN/9.99", HWID_OS: "", HWID_OS_VER: "", HWID_MODEL: "", HWID_ID: "",
OVPN_PROVIDER: "bmstu", OVPN_GROUP: "BMSTU", OVPN_SERVER_HOST: "openvpn4.bmstu.ru",
OVPN_SERVER_IPS: "195.19.40.7 195.19.33.86",
OVPN_ROUTES: "172.16.0.0/16 172.19.33.0/24 195.19.32.0/19",
OVPN_CHECK_URL: "https://eu.bmstu.ru", TS_CHECK_URL: "http://100.69.216.50:8080",
CSQTT: "0", CSQTT_IFACE: "csqtt0", CSQTT_PROCESS: "csqtt", LITE: "0",
};
const SECTIONS = [
["head", ""], ["proxies", "proxies:"], ["providers", "proxy-providers:"], ["rule-providers", "rule-providers:"],
["sniffer", ""], ["dns", ""], ["groups", "proxy-groups:"], ["rules", "rules:"],
];
const words = (s) => (s || "").split(/\s+/).filter(Boolean);
function withDefaults(input) {
const v = { ...DEFAULTS };
for (const [k, val] of Object.entries(input || {})) {
if (val !== undefined && val !== null && val !== "") v[k] = String(val);
}
// old names of the profiles (see set_defaults)
v.LOCATION = { home: "main", street: "whitelist" }[v.LOCATION] || v.LOCATION;
return v;
}
// Subscription ids (provider names, keys SUB_<ID>_*), see sub_pairs in
// mihomo-kit.sh: a SUBS word is "url" or "name=url"; without a name the id
// comes from the domain (sub.kittyvpn.com -> kittyvpn); repeats get 2, 3, ...
function autoId(url) {
let h = url.replace(/^.*?:\/\//, "").replace(/[/?#].*$/, "").replace(/^.*@/, "");
h = h.replace(/:[^:]*$/, "").replace(/[A-Z]/g, (c) => c.toLowerCase());
if (h.includes(".")) h = h.replace(/\.[^.]*$/, "");
while (/\.(co|com|net|org|gov|edu|ac)$/.test(h)) h = h.replace(/\.[^.]*$/, "");
const id = h.slice(h.lastIndexOf(".") + 1).replace(/[^a-z0-9_]/g, "_");
return !id ? "sub" : /^[0-9]/.test(id) ? "sub" + id : id;
}
function subPairs(subs) {
const seen = new Set();
return words(subs).map((w) => {
const eq = w.indexOf("=");
let name = "", url = w;
if (eq > 0 && /^[A-Za-z0-9_-]+$/.test(w.slice(0, eq))) {
name = w.slice(0, eq);
url = w.slice(eq + 1);
} else name = autoId(w);
name = name.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/-/g, "_");
let id = name;
for (let k = 2; seen.has(id); k++) id = name + k;
seen.add(id);
return { id, url, word: w };
});
}
// SUB_<ID>_<key>, else the old SUB<index>_<key>
const subGet = (v, i, id, key) => v[`SUB_${id.toUpperCase()}_${key}`] || v[`SUB${i}_${key}`] || "";
// SUB_<ID>_DISABLED=1: kept (id, settings) but left out of the profile
const subOff = (v, i, id) => subGet(v, i, id, "DISABLED") === "1";
// vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name (see vless_parse in mihomo-kit.sh)
function parseVless(link) {
const l = link.replace(/^vless:\/\//, "").replace(/#.*$/, "");
const at = l.indexOf("@");
let hp = (at < 0 ? l : l.slice(at + 1)).replace(/\?.*$/, "");
const c = hp.lastIndexOf(":");
const server = c < 0 ? hp : hp.slice(0, c);
let port = c < 0 ? hp : hp.slice(c + 1);
if (!/^[0-9]+$/.test(port)) port = "443";
const qm = l.indexOf("?");
const q = "&" + (qm < 0 ? l : l.slice(qm + 1)) + "&";
const qv = (k) => {
const i = q.indexOf("&" + k + "=");
if (i < 0) return "";
const rest = q.slice(i + k.length + 2);
return rest.slice(0, rest.indexOf("&"));
};
return { server, port, uuid: at < 0 ? l : l.slice(0, at), sni: qv("sni"), pbk: qv("pbk"), sid: qv("sid") };
}
// BOOT seeds: BOOT_LINKS or the old single BOOT_* (see boot_seeds)
function bootSeeds(v) {
if (words(v.BOOT_LINKS).length)
return words(v.BOOT_LINKS).map((l, i) => ({ name: i ? `seed${i + 1}` : "seed", ...parseVless(l) }));
if (v.BOOT_SERVER)
return [{ name: "seed", server: v.BOOT_SERVER, port: v.BOOT_PORT, uuid: v.BOOT_UUID,
sni: v.BOOT_SNI, pbk: v.BOOT_PBK, sid: v.BOOT_SID }];
return [];
}
const seedVars = (s) => ({ SEED_NAME: s.name, SEED_SERVER: s.server, SEED_PORT: s.port, SEED_UUID: s.uuid,
SEED_SNI: s.sni, SEED_PBK: s.pbk, SEED_SID: s.sid });
// HY2_<NAME> prefix of an own hysteria2 server's keys (see hy2_key)
const hy2Key = (name) => "HY2_" + name.replace(/[a-z]/g, (c) => c.toUpperCase()).replace(/-/g, "_");
// variables for templates/proxies/*-hy2.each.yaml (see hy2_vars in mihomo-kit.sh)
function hy2Vars(v, name) {
const k = (key) => v[`${hy2Key(name)}_${key}`] || "";
const obfs = k("OBFS_PASSWORD");
return {
HY2_NAME: name, HY2_SERVER: k("SERVER"), HY2_PORT: k("PORT"), HY2_PASSWORD: yq(k("PASSWORD")),
HY2_OBFS: obfs ? "salamander" : "", HY2_OBFS_PASSWORD: obfs ? yq(obfs) : "",
HY2_SNI: k("SNI"), HY2_INSECURE: k("INSECURE") === "1" ? "true" : "false",
HY2_UP: yq(k("UP")), HY2_DOWN: yq(k("DOWN")),
};
}
// own lists of the settings (see norm_list): domains without "*." / "+." / "."
// (DOMAIN-SUFFIX covers subdomains), IPs without a mask get /32 (/128)
const normList = (kind, s) => words(s).map((w) => {
if (kind === "dom") return w.replace(/^\*/, "").replace(/^\+/, "").replace(/^\./, "");
return w.includes("/") ? w : w + (w.includes(":") ? "/128" : "/32");
}).filter(Boolean).join(" ");
// LOCAL_HOSTS "a.com=192.168.1.10 ..." -> LOCAL_DOMAINS, LOCAL_HOSTS_YAML (see local_hosts_vars)
function localHostsVars(v, tags) {
v.LOCAL_DOMAINS = "";
v.LOCAL_HOSTS_YAML = "";
if (!tags.has("local_hosts")) return;
const doms = [], lines = [];
for (const w of words(v.LOCAL_HOSTS)) {
const eq = w.indexOf("=");
const d = (eq < 0 ? w : w.slice(0, eq)).replace(/^\*/, "").replace(/^\+/, "").replace(/^\./, "");
const a = eq < 0 ? "" : w.slice(eq + 1);
if (eq < 0) throw new Error(`LOCAL_HOSTS: '${w}' is not domain=address`);
if (!/^[A-Za-z0-9.-]+$/.test(d)) throw new Error(`LOCAL_HOSTS: bad domain in '${w}'`);
if (!/^[0-9A-Fa-f.:]+$/.test(a)) throw new Error(`LOCAL_HOSTS: bad address in '${w}'`);
doms.push(d);
lines.push(`'+.${d}': ${a}`);
}
v.LOCAL_DOMAINS = doms.join(" ");
v.LOCAL_HOSTS_YAML = lines.join("\n");
}
// the URL's host is one of LOCAL_DOMAINS or under one (see is_local_url)
function isLocalUrl(v, url) {
let h = url.replace(/^[^:]*:\/\//, "").split("/")[0].split("?")[0];
h = h.slice(h.lastIndexOf("@") + 1).replace(/:[^:]*$/, "");
return words(v.LOCAL_DOMAINS).some((d) => h === d || h.endsWith("." + d));
}
function check(v) {
if (!words(v.SUBS).length) throw new Error("SUBS is empty (subscription URLs)");
if (!["router", "mobile"].includes(v.TARGET)) throw new Error("TARGET must be router or mobile");
if (!["main", "whitelist", "foreign"].includes(v.LOCATION)) throw new Error("LOCATION must be main, whitelist or foreign");
for (const l of words(v.MY_LINKS)) {
if (!/^(vless|vmess|trojan|ss|hysteria2|hy2|tuic|anytls):\/\/./.test(l))
throw new Error(`MY_LINKS: '${l.split("?")[0]}' is not a vless/vmess/trojan/ss/hysteria2/tuic/anytls link`);
}
if (v.BOOT === "1") {
const seeds = bootSeeds(v);
if (!seeds.length) throw new Error("BOOT=1 but no BOOT_LINKS (vless links of the seed nodes)");
for (const s of seeds) {
for (const k of ["server", "uuid", "sni", "pbk", "sid"]) {
if (!s[k]) throw new Error(`BOOT ${s.name}: ${k.toUpperCase()} is empty (vless link needs host, uuid, sni, pbk, sid)`);
}
}
}
let on = 0;
subPairs(v.SUBS).forEach(({ id }, i) => {
if (subOff(v, i, id)) return;
on++;
if (subGet(v, i, id, "PROXY") === "BOOT" && v.BOOT !== "1") throw new Error(`subscription ${id}: PROXY=BOOT but BOOT=0`);
if (subGet(v, i, id, "HWID") === "1") {
for (const k of ["HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) {
if (!v[k]) throw new Error(`${k} is empty (subscription ${id} has HWID=1)`);
}
}
});
if (!on) throw new Error("all subscriptions are disabled (SUB_<ID>_DISABLED=1)");
for (const name of words(v.HY2)) {
if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(`HY2: bad server name ${name} (letters, digits, _ -)`);
for (const key of ["SERVER", "PORT", "PASSWORD"]) {
if (!v[`${hy2Key(name)}_${key}`]) throw new Error(`${hy2Key(name)}_${key} is empty (hysteria2 server ${name})`);
}
}
}
// YAML double-quoted string body
const yq = (s) => String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
// per-subscription variables for the .each templates (see sub_vars in mihomo-kit.sh)
function subVars(v, i, id, url) {
let proxy = subGet(v, i, id, "PROXY") || "BOOT-AUTO";
if (proxy === "none") proxy = "";
// a subscription on an own server in the LAN: no proxy reaches it
if (isLocalUrl(v, url)) proxy = "DIRECT";
let ua = subGet(v, i, id, "UA");
let h = subGet(v, i, id, "HEADERS");
if (subGet(v, i, id, "HWID") === "1") {
ua = ua || v.HWID_UA;
h = `x-device-os=${v.HWID_OS};x-ver-os=${v.HWID_OS_VER};x-device-model=${v.HWID_MODEL};x-hwid=${v.HWID_ID}` + (h ? ";" + h : "");
}
const headers = h.split(";").map((x) => x.trim()).filter(Boolean).map((item) => {
const eq = item.indexOf("=");
const key = (eq < 0 ? item : item.slice(0, eq)).replace(/\s+$/, "");
const val = eq < 0 ? item : item.slice(eq + 1).replace(/^\s+/, "");
return `${key}: ["${yq(val)}"]`;
});
return {
SUB_NAME: id, SUB_URL: url, SUB_PROXY: proxy,
SUB_UA: yq(ua || "mihomo"), SUB_HEADERS: headers.join("\n"),
};
}
function computeTags(v) {
const t = new Set(["base", "sub", v.TARGET]);
if (v.BOOT === "1") t.add("boot");
if (words(v.HY2).length) t.add("hy2");
if (v.TARGET === "router") {
t.add(v.LOCATION);
if (v.TORRENT === "1") t.add("torrent");
if (v.PUSH === "1") t.add("push");
if (v.OPENVPN === "1") t.add("openvpn");
if (v.TAILSCALE === "1") {
t.add("tailscale");
if (v.TS_EXIT === "1") t.add("ts_exit");
}
if (v.CSQTT === "1") t.add("csqtt");
if (v.LITE === "1") t.add("lite");
// own servers in the LAN (LOCAL_HOSTS): only the router is always at home
if (words(v.LOCAL_HOSTS).length) t.add("local_hosts");
// own servers as links (MY_LINKS): a file on the router, the phone cannot read it
if (words(v.MY_LINKS).length) t.add("my_links");
}
// MY has servers for sure: hysteria2 from the settings or links (see compute_tags)
if (t.has("hy2") || t.has("my_links")) t.add("own");
// OpenVPN through OVPN-EXIT: whitelist and abroad (see compute_tags)
if (t.has("router") && (t.has("whitelist") || t.has("foreign"))) t.add("ovpn_exit");
// own servers through MY-EXIT: whitelist and the phone (see compute_tags)
if (t.has("whitelist") || t.has("mobile")) t.add("my_exit");
return t;
}
function subst(s, v) {
return s.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_, name) => v[name] ?? "");
}
function renderText(text, v, tags) {
const out = [];
for (let line of text.replace(/\n$/, "").split("\n")) {
const p = line.indexOf("#@");
if (p >= 0) {
const conds = line.slice(p + 2).split(",");
line = line.slice(0, p).replace(/[ \t]+$/, "");
const ok = conds.every((c) => (c.startsWith("!") ? !tags.has(c.slice(1)) : tags.has(c)));
if (!ok) continue;
}
const m = line.match(/\$\{(@@?)([A-Za-z0-9_]+)\}/);
if (m) {
const pre = line.slice(0, m.index);
const post = line.slice(m.index + m[0].length);
const items = m[1] === "@@" ? (v[m[2]] || "").split("\n").filter(Boolean) : words(v[m[2]]);
for (const w of items) out.push(subst(pre + w + post, v));
continue;
}
out.push(subst(line, v));
}
// like $(...) in sh: drop trailing empty lines
while (out.length && out[out.length - 1] === "") out.pop();
return out.join("\n");
}
// "<module>.<tag>...[.each]" -> {active, each}
function fragmentInfo(spec, tags) {
const [mod, ...rest] = spec.split(".");
let each = false;
if (!tags.has(mod)) return { active: false, each, mod };
for (const t of rest) {
if (t === "each") { each = true; continue; }
if (!tags.has(t)) return { active: false, each, mod };
}
return { active: true, each, mod };
}
function render(templates, input) {
const v = withDefaults(input);
check(v);
const tags = computeTags(v);
for (const k of ["RU_IPS", "FOREIGN_IPS", "MY_IPS"]) v[k] = normList("ip", v[k]);
for (const k of ["RU_DOMAINS", "FOREIGN_DOMAINS", "MY_DOMAINS"]) v[k] = normList("dom", v[k]);
localHostsVars(v, tags);
const subs = subPairs(v.SUBS);
v.SUB_LIST = subs.filter((s, i) => !subOff(v, i, s.id)).map((s) => s.id).join(", ");
// providers of the "[MY] ..." nodes (group MY)
v.MY_SUB_LIST = subs.filter((s, i) => !subOff(v, i, s.id)).map((s) => s.id + "-my")
.concat(tags.has("my_links") ? ["my-links"] : []).join(", ");
const seeds = bootSeeds(v);
v.SEED_LIST = seeds.map((s) => s.name).join(", ");
const hy2 = words(v.HY2);
v.HY2_LIST = hy2.join(", ");
// CSQTT tunnel (star-panel-csqtt): last in MAIN (plain exit through its server)
v.CSQTT_MAIN = tags.has("csqtt") ? ", CSQTT" : "";
const sections = [];
for (const [dir, header] of SECTIONS) {
const files = Object.keys(templates)
.filter((p) => p.startsWith(dir + "/") && p.endsWith(".yaml"))
.sort();
const parts = [];
for (const path of files) {
const name = path.slice(dir.length + 1, -".yaml".length);
const info = fragmentInfo(name.slice(name.indexOf("-") + 1), tags);
if (!info.active) continue;
if (info.each && info.mod === "boot") {
for (const s of seeds) {
const part = renderText(templates[path], { ...v, ...seedVars(s) }, tags);
if (part) parts.push(part);
}
} else if (info.each && info.mod === "hy2") {
for (const name of hy2) {
const part = renderText(templates[path], { ...v, ...hy2Vars(v, name) }, tags);
if (part) parts.push(part);
}
} else if (info.each) {
subs.forEach((s, i) => {
if (subOff(v, i, s.id)) return;
const part = renderText(templates[path], { ...v, ...subVars(v, i, s.id, s.url) }, tags);
if (part) parts.push(part);
});
} else {
const part = renderText(templates[path], v, tags);
if (part) parts.push(part);
}
}
if (!parts.length) continue;
sections.push((header ? header + "\n" : "") + parts.join("\n\n"));
}
return sections.join("\n\n") + "\n";
}
const api = { render, subPairs, DEFAULTS };
if (typeof module !== "undefined" && module.exports) module.exports = api;
else root.MihomoKit = api;
})(typeof window !== "undefined" ? window : globalThis);
</script>
<script>
const TEMPLATES = {
"dns/10-base.yaml": "dns:\n enable: true\n ipv6: false\n respect-rules: true\n enhanced-mode: fake-ip\n fake-ip-range: 198.18.0.1/16\n fake-ip-filter:\n - '*.lan'\n - '*.local' #@router\n - '+.ru' #@!foreign\n - '+.xn--p1ai' #@router,!foreign\n - rule-set:ru-inside #@router,!foreign\n # tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below) #@tailscale\n - '+.ts.net' #@tailscale\n - '+.${@TS_DOMAINS}' #@tailscale\n # own servers in the LAN (LOCAL_HOSTS): clients get the real LAN address #@local_hosts\n - '+.${@LOCAL_DOMAINS}' #@local_hosts\n\n default-nameserver:\n - 77.88.8.8\n - 1.1.1.1 #@router\n - 223.5.5.5 #@mobile\n\n proxy-server-nameserver:\n - https://77.88.8.8/dns-query\n\n direct-nameserver:\n - 77.88.8.8 #@!foreign\n - 77.88.8.1 #@!foreign\n - 1.1.1.1 #@foreign\n - 8.8.8.8 #@foreign\n\n nameserver:\n - https://1.1.1.1/dns-query #@router\n - https://dns.google/dns-query\n - https://1.1.1.1/dns-query #@mobile\n\n # MagicDNS of the embedded Tailscale (the proxy named \"tailscale\") #@tailscale\n nameserver-policy: #@tailscale\n '+.ts.net': tailscale://tailscale #@tailscale\n '+.${@TS_DOMAINS}': tailscale://tailscale #@tailscale\n\n# LOCAL_HOSTS: own domains -> LAN addresses (dns.use-hosts is on by default), so neither #@local_hosts\n# the core nor the clients go out to the white IP and back into the router itself #@local_hosts\nhosts: #@local_hosts\n ${@@LOCAL_HOSTS_YAML} #@local_hosts\n",
"groups/10-boot.yaml": " # BOOT: whitelisted entry nodes (BOOT_LINKS), the first alive one\n - name: BOOT\n type: fallback\n proxies: [${SEED_LIST}]\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n lazy: false\n",
"groups/15-sub.yaml": " # default for downloading subscriptions: BOOT (if set), else the nodes of the\n # saved subscriptions (providers are cached on disk), else direct. FOREIGN goes\n # before DIRECT: the health check of DIRECT (gstatic) passes in Russia even when\n # the subscription site itself is blocked.\n - name: BOOT-AUTO\n type: fallback\n proxies: [BOOT, FOREIGN, DIRECT] #@boot\n proxies: [FOREIGN, DIRECT] #@!boot\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n lazy: false\n",
"groups/20-sub.yaml": " - name: RU\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n # lite: the provider's URL, so RU nodes are not tested a second time\n url: \"https://ya.ru\" #@!lite\n url: \"https://www.gstatic.com/generate_204\" #@lite\n interval: 300\n tolerance: 50\n lazy: false\n\n - name: FOREIGN\n type: url-test\n use: [${SUB_LIST}]\n exclude-filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n tolerance: 50\n lazy: false\n",
"groups/30-torrent.yaml": " - name: TORRENT\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)torrent|\\\\[tor\\\\]\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 6000\n tolerance: 500\n max-failed-times: 5\n lazy: false\n",
"groups/40-openvpn.yaml": " # url: what the dashboard's delay test opens through the tunnel;\n # interval 0: no background checks (they would redial with a stale OTP)\n - name: ${OVPN_GROUP}\n type: select\n use: [${OVPN_PROVIDER}]\n url: \"${OVPN_CHECK_URL}\"\n interval: 0\n",
"groups/41-openvpn.ovpn_exit.yaml": " # what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).\n # select, not url-test: switching nodes would break the tunnel.\n # Pick a concrete RU node in the dashboard, the choice is remembered.\n - name: OVPN-EXIT\n type: select\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n",
"groups/45-sub.yaml": " # own servers: hysteria2 from the settings (HY2) and the \"[MY] ...\" nodes of the\n # subscriptions (providers <id>-my); the fastest alive one; pin one in the dashboard if needed\n - name: MY\n type: url-test\n proxies: [${HY2_LIST}] #@hy2\n use: [${MY_SUB_LIST}]\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300 #@!lite\n interval: 600 #@lite\n tolerance: 50\n lazy: false #@!lite\n lazy: true #@lite\n\n # whitelist and mobile (my_exit): what own servers are reached through; switches only when the node is\n # clearly worse or dead (each switch breaks everything going through MY)\n - name: MY-EXIT #@my_exit\n type: url-test #@my_exit\n use: [${SUB_LIST}] #@my_exit\n exclude-filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\" #@my_exit\n url: \"https://www.gstatic.com/generate_204\" #@my_exit\n interval: 300 #@my_exit\n tolerance: 300 #@my_exit\n lazy: false #@my_exit\n",
"groups/50-tailscale.yaml": " # url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test\n - name: TAILSCALE\n type: select\n proxies: [tailscale]\n url: \"${@TS_CHECK_URL}\"\n interval: 0\n",
"groups/51-tailscale.ts_exit.yaml": " # Tailscale needs full-cone UDP from its dialer-proxy: vless/vmess/trojan\n # cannot do it in mihomo, so only ss / hysteria2 / tuic / socks5 nodes here.\n - name: TS-EXIT\n type: select\n proxies: [MY] #@own\n use: [${SUB_LIST}]\n exclude-type: \"vless|vmess|trojan\"\n",
"groups/60-csqtt.yaml": " # UPLINK: what the subscription nodes, BOOT seeds and own servers connect\n # through. DIRECT - as before; CSQTT - through csqtt0 first (out of the\n # whitelist), then FOREIGN / MY / RU work on top of it as usual.\n # On whitelist own servers go MY-EXIT -> node -> UPLINK.\n - name: UPLINK\n type: select\n proxies: [DIRECT, CSQTT]\n",
"groups/90-base.yaml": " - name: MAIN\n type: select\n proxies: [FOREIGN, MY, RU, DIRECT${CSQTT_MAIN}] #@!foreign\n # abroad: direct by default, own servers / pools by hand #@foreign\n proxies: [DIRECT, MY, FOREIGN, RU${CSQTT_MAIN}] #@foreign\n",
"groups/91-torrent.yaml": " - name: TORRENT-SEL\n type: select\n proxies: [TORRENT, FOREIGN, DIRECT]\n",
"groups/92-push.yaml": " - name: PUSH\n type: select\n proxies: [DIRECT, MY, FOREIGN] #@!whitelist\n proxies: [MY, FOREIGN, DIRECT] #@whitelist,own\n # no own servers in the settings: MY may be empty (no [MY] nodes in the subscriptions) #@whitelist,!own\n proxies: [FOREIGN, MY, DIRECT] #@whitelist,!own\n",
"head/10-lite.yaml": "# LITE=1 (weak routers). nikki's mixin overrides keys whose uci options are set\n# (mihomo-kit.sh puts log_level / match_process there); these cover the rest\nlog-level: warning\nfind-process-mode: off #@!csqtt\ntcp-concurrent: false\nunified-delay: false\ngeo-auto-update: false\n",
"providers/10-sub.each.yaml": " ${SUB_NAME}:\n type: http\n url: \"${SUB_URL}\"\n path: ./providers/${SUB_NAME}.yaml\n interval: 3600\n proxy: ${@SUB_PROXY}\n exclude-filter: \"(?i)app not supported|приложение не|свяжитесь|\\\\[MY\\\\]\"\n override: #@csqtt\n dialer-proxy: UPLINK #@csqtt\n header:\n User-Agent: [\"${SUB_UA}\"]\n ${@@SUB_HEADERS}\n # one check per provider: the groups over it (use:) only add their URLs to it,\n # so the interval and lazy here are what counts for RU/FOREIGN/TORRENT/MY-EXIT.\n # lite: every 10 min and skipped while no traffic used the provider\n health-check:\n enable: true\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300 #@!lite\n interval: 600 #@lite\n timeout: 3000\n lazy: false #@!lite\n lazy: true #@lite\n",
"providers/15-sub.each.yaml": " # own servers kept in the subscription, named \"[MY] ...\", for group MY (the main\n # provider leaves them out); a provider of its own because on whitelist and the\n # phone they go through MY-EXIT. Router: not a second download, reads the file the\n # main provider saves (mihomo watches it; ./providers exists before the start,\n # ovpn_routes_write). Phone: FlClash moves provider files to paths of its own,\n # so the subscription is fetched once more.\n ${SUB_NAME}-my:\n type: file #@router\n path: ./providers/${SUB_NAME}.yaml #@router\n type: http #@mobile\n url: \"${SUB_URL}\" #@mobile\n path: ./providers/${SUB_NAME}-my.yaml #@mobile\n interval: 3600 #@mobile\n proxy: ${@SUB_PROXY} #@mobile\n filter: \"(?i)\\\\[MY\\\\]\"\n override: #@my_exit\n dialer-proxy: MY-EXIT #@my_exit\n override: #@csqtt,!my_exit\n dialer-proxy: UPLINK #@csqtt,!my_exit\n header: #@mobile\n User-Agent: [\"${SUB_UA}\"] #@mobile\n ${@@SUB_HEADERS} #@mobile\n health-check:\n enable: true\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300 #@!lite\n interval: 600 #@lite\n timeout: 3000\n lazy: false #@!lite\n lazy: true #@lite\n",
"providers/17-my_links.yaml": " # own servers as links (MY_LINKS, LuCI \"Свои серверы (ссылки)\"): kit writes them to\n # this file on build, mihomo parses vless/vmess/trojan/ss/hysteria2/tuic/anytls links\n # like a subscription; group MY, named \"[MY] ...\" like the [MY] nodes of the subscriptions\n my-links:\n type: file\n path: ./providers/my-links.txt\n override:\n additional-prefix: \"[MY] \"\n dialer-proxy: MY-EXIT #@my_exit\n dialer-proxy: UPLINK #@csqtt,!my_exit\n health-check:\n enable: true\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300 #@!lite\n interval: 600 #@lite\n timeout: 3000\n lazy: false #@!lite\n lazy: true #@lite\n",
"providers/20-openvpn.yaml": " # OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the\n # password). No health-check here: a dead tunnel would be redialed with a\n # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.\n ${OVPN_PROVIDER}:\n type: file\n path: ./providers/${OVPN_PROVIDER}.yaml\n health-check:\n enable: false\n override: #@ovpn_exit\n dialer-proxy: OVPN-EXIT #@ovpn_exit\n",
"proxies/10-boot.each.yaml": " - name: ${SEED_NAME}\n type: vless\n server: ${SEED_SERVER}\n port: ${SEED_PORT}\n uuid: ${SEED_UUID}\n network: tcp\n udp: true\n tls: true\n flow: xtls-rprx-vision\n servername: ${SEED_SNI}\n client-fingerprint: firefox\n reality-opts:\n public-key: ${SEED_PBK}\n short-id: ${SEED_SID}\n dialer-proxy: UPLINK #@csqtt\n",
"proxies/20-tailscale.yaml": " # Tailscale: userspace node, starts on first use. First login: open the URL\n # from the nikki log (\"To start this tsnet server ... go to: ...\"), then\n # disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the\n # mihomo environment (mihomo-kit.sh fix).\n - name: tailscale\n type: tailscale\n hostname: ${TS_HOSTNAME}\n state-dir: ./tailscale\n udp: true\n accept-routes: true\n dialer-proxy: TS-EXIT #@ts_exit\n # whitelist: control and DERP over TCP through own servers (MY -> own node -> MY-EXIT); #@whitelist,!ts_exit\n # MY holds hysteria2 from the settings and \"[MY]\" nodes of the subscriptions; empty MY is direct #@whitelist,!ts_exit\n # needs the kit's core (v1.19.32-ts1, tools/core/*.patch, MetaCubeX/mihomo#3142) #@whitelist,!ts_exit\n dialer-proxy: MY #@whitelist,!ts_exit\n",
"proxies/30-hy2.each.yaml": " - name: ${HY2_NAME}\n type: hysteria2\n server: ${HY2_SERVER}\n port: ${HY2_PORT}\n password: \"${HY2_PASSWORD}\"\n obfs: ${@HY2_OBFS}\n obfs-password: \"${@@HY2_OBFS_PASSWORD}\"\n sni: ${@HY2_SNI}\n skip-cert-verify: ${HY2_INSECURE}\n up: \"${@@HY2_UP}\"\n down: \"${@@HY2_DOWN}\"\n udp: true\n dialer-proxy: MY-EXIT #@my_exit\n dialer-proxy: UPLINK #@csqtt,!my_exit\n",
"proxies/40-csqtt.yaml": " # CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo\n # just sends the connection out of it (the interface does not change routes)\n - name: CSQTT\n type: direct\n interface-name: ${CSQTT_IFACE}\n udp: true\n",
"rule-providers/10-base.yaml": " # Russian services (geosite ru-inside of russia-only, as .mrs): an ordinary\n # http rule-set, so every client fetches it with the config, no geodata setup\n ru-inside:\n type: http\n behavior: domain\n format: mrs\n url: \"${RULESET_URL}/ru-inside.mrs\"\n path: ./ruleset/ru-inside.mrs\n interval: 86400\n",
"rule-providers/20-openvpn.yaml": " # OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and\n # emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow\n # the normal rules instead of a dead BMSTU group\n ${OVPN_PROVIDER}-routes:\n type: file\n behavior: ipcidr\n path: ./providers/${OVPN_PROVIDER}-routes.yaml\n",
"rules/05-csqtt.yaml": " # the CSQTT client's own connections (peer, VK TURN) must not go into its tunnel\n - PROCESS-NAME,${@CSQTT_PROCESS},DIRECT\n",
"rules/10-tailscale.yaml": " # Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)\n - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve\n - DOMAIN-SUFFIX,ts.net,TAILSCALE\n - DOMAIN-SUFFIX,${@TS_DOMAINS},TAILSCALE\n",
"rules/20-openvpn.yaml": " # OpenVPN server itself must not go into its own tunnel\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@!ovpn_exit\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@ovpn_exit\n - DOMAIN,${OVPN_SERVER_HOST},DIRECT #@!ovpn_exit\n - DOMAIN,${OVPN_SERVER_HOST},OVPN-EXIT #@ovpn_exit\n # networks pushed by the server (before the private-range DIRECT rules);\n # a rule-provider so that bmstu-otp.sh off can drop them without a restart\n - RULE-SET,${OVPN_PROVIDER}-routes,${OVPN_GROUP},no-resolve\n",
"rules/30-base.yaml": " - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve\n - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve\n - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve\n",
"rules/35-push.yaml": " # push notifications (Apple APNs, Google FCM): long-lived connections on a\n # stable path - group PUSH (main/foreign: DIRECT, whitelist: MY)\n - DOMAIN-SUFFIX,push.apple.com,PUSH\n - IP-CIDR,17.249.0.0/16,PUSH,no-resolve\n - IP-CIDR,17.252.0.0/16,PUSH,no-resolve\n - IP-CIDR,17.57.144.0/22,PUSH,no-resolve\n - IP-CIDR,17.188.128.0/18,PUSH,no-resolve\n - IP-CIDR,17.188.20.0/23,PUSH,no-resolve\n - DOMAIN-REGEX,^(alt[0-9]+-)?mtalk[0-9]*\\.google\\.com$,PUSH\n - DST-PORT,5228-5230,PUSH\n",
"rules/40-base.yaml": " # own lists from the settings: above torrents, ru-inside, .ru and MATCH; below the\n # tunnels, LAN and push. Domains (DOMAIN-SUFFIX: the domain and all subdomains)\n # before IPs; first match wins: MY, then FOREIGN, then RU.\n # RU on main (home, own white IP): reachable directly; whitelist/abroad: through RU\n # LOCAL_HOSTS: own servers in the LAN, before everything else #@local_hosts\n - DOMAIN-SUFFIX,${@LOCAL_DOMAINS},DIRECT\n - DOMAIN-SUFFIX,${@MY_DOMAINS},MY\n - DOMAIN-SUFFIX,${@FOREIGN_DOMAINS},FOREIGN\n - DOMAIN-SUFFIX,${@RU_DOMAINS},DIRECT #@main\n - DOMAIN-SUFFIX,${@RU_DOMAINS},RU #@!main\n - IP-CIDR,${@MY_IPS},MY\n - IP-CIDR,${@FOREIGN_IPS},FOREIGN\n - IP-CIDR,${@RU_IPS},DIRECT #@main\n - IP-CIDR,${@RU_IPS},RU #@!main\n",
"rules/50-torrent.yaml": " - SRC-PORT,20000-20199,TORRENT-SEL\n",
"rules/90-base.yaml": " - RULE-SET,ru-inside,DIRECT #@!foreign\n # abroad: Russian services through the RU pool too #@foreign\n - RULE-SET,ru-inside,RU #@foreign\n # main (home, own white IP): .ru/.рф directly; elsewhere through RU\n - DOMAIN-SUFFIX,ru,DIRECT #@main\n - DOMAIN-SUFFIX,xn--p1ai,DIRECT #@main\n - DOMAIN-SUFFIX,ru,RU #@!main\n - DOMAIN-SUFFIX,xn--p1ai,RU #@!main\n - MATCH,MAIN\n",
"sniffer/10-base.yaml": "sniffer:\n enable: true\n force-dns-mapping: true\n parse-pure-ip: true\n override-destination: false\n sniff:\n HTTP:\n ports: [80, 8080-8880] #@!lite\n ports: [80, 8080] #@lite\n TLS:\n ports: [443, 8443]\n # lite: no QUIC (fake-ip already gives the domain; pure-IP QUIC goes by IP)\n QUIC: #@!lite\n ports: [443, 8443] #@!lite\n"
};
const D = MihomoKit.DEFAULTS;
const $ = (id) => document.getElementById(id);
const form = $("form");
let tab = "yaml";
let current = { yaml: "", env: "", steps: "" };
for (const k of ["OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) $(k).value = D[k];
function addSub() {
const row = document.createElement("div");
row.className = "sub";
row.innerHTML = `
<div class="sub-head"><span class="name"></span>
<input type="text" data-k="url" placeholder="https://sub.example.com/sub/xxxx или имя=https://…">
<button type="button" class="x-btn" title="убрать">×</button></div>
<div class="sub-opts">
<label>через <select data-k="proxy"><option value="">авто</option><option>BOOT-AUTO</option><option>BOOT</option><option>DIRECT</option><option>FOREIGN</option></select></label>
<label class="check"><input type="checkbox" data-k="hwid">HWID</label>
</div>
<details><summary>User-Agent и заголовки</summary>
<label>User-Agent (пусто = mihomo, с HWID — из блока HWID)</label><input type="text" data-k="ua">
<label>доп. заголовки: key=value; key2=value 2</label><input type="text" data-k="headers">
</details>`;
row.querySelector(".x-btn").addEventListener("click", () => {
if (document.querySelectorAll("#subs .sub").length > 1) row.remove();
update();
});
$("subs").appendChild(row);
update();
}
$("add-sub").addEventListener("click", addSub);
// rows with a URL, in order; id = provider name from the domain (or "name=url")
function readSubs() {
const rows = [...document.querySelectorAll("#subs .sub")];
const filled = rows.filter((row) => row.querySelector("[data-k=url]").value.trim());
const ids = MihomoKit.subPairs(filled.map((row) => row.querySelector("[data-k=url]").value.trim()).join(" "));
rows.forEach((row) => (row.querySelector(".name").textContent = ""));
return filled.map((row, n) => {
const get = (k) => row.querySelector(`[data-k=${k}]`);
row.querySelector(".name").textContent = ids[n].id;
return { id: ids[n].id, url: ids[n].word, proxy: get("proxy").value, hwid: get("hwid").checked,
ua: get("ua").value.trim(), headers: get("headers").value.trim() };
});
}
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
function flag(id) { return $(id).checked ? "1" : "0"; }
function readVars() {
const v = {
TARGET: radio("TARGET"), LOCATION: radio("LOCATION"),
SUBS: "",
RU_IPS: $("RU_IPS").value.trim(), FOREIGN_IPS: $("FOREIGN_IPS").value.trim(),
RU_DOMAINS: $("RU_DOMAINS").value.trim(), FOREIGN_DOMAINS: $("FOREIGN_DOMAINS").value.trim(),
BOOT: flag("BOOT"), TORRENT: flag("TORRENT"), PUSH: flag("PUSH"), OPENVPN: flag("OPENVPN"),
TAILSCALE: flag("TAILSCALE"), TS_EXIT: flag("TS_EXIT"), CSQTT: flag("CSQTT"), LITE: flag("LITE"),
};
for (const k of ["BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID",
"TS_HOSTNAME", "TS_DOMAINS", "OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) {
v[k] = $(k).value.trim();
}
const subs = readSubs();
v.SUBS = subs.map((x) => x.url).join(" ");
v._HWID = subs.some((x) => x.hwid);
for (const x of subs) {
const p = `SUB_${x.id.toUpperCase()}_`;
if (x.proxy) v[p + "PROXY"] = x.proxy;
if (x.hwid) v[p + "HWID"] = "1";
if (x.ua) v[p + "UA"] = x.ua;
if (x.headers) v[p + "HEADERS"] = x.headers;
}
for (const k of ["HWID_UA", "HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) v[k] = $(k).value.trim();
return v;
}
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
function envFile(v) {
const keys = ["TARGET", "LOCATION", "SUBS"];
keys.push(...Object.keys(v).filter((k) => /^SUB_/.test(k) && k !== "SUB_LIST"));
if (v._HWID) keys.push("HWID_UA", "HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID");
keys.push("BOOT");
if (v.BOOT === "1") keys.push("BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID");
keys.push("TORRENT", "PUSH", "RU_IPS", "FOREIGN_IPS", "RU_DOMAINS", "FOREIGN_DOMAINS", "OPENVPN");
if (v.OPENVPN === "1") keys.push("OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES");
keys.push("CSQTT", "LITE", "TAILSCALE");
if (v.TAILSCALE === "1") keys.push("TS_HOSTNAME", "TS_DOMAINS", "TS_EXIT");
return "# mihomo-kit profile (secrets inside: chmod 600)\n" +
keys.map((k) => `${k}=${q(v[k] ?? "")}`).join("\n") + "\n";
}
function steps(v) {
const name = $("PROFILE_NAME").value.trim() || "main";
if (v.TARGET === "mobile") {
return [
"Телефон (FlClash):",
"1. Скачай config.yaml (кнопка «Скачать»).",
"2. FlClash → Профили → + → Файл → выбери config.yaml.",
"3. Включи профиль; геобазы скачаются при первом запуске.",
].join("\n");
}
const s = [
"Роутер (nikki). Один раз на новом роутере — см. README, раздел «Новый роутер».",
"",
`1. Сохрани profile .env как /etc/nikki/profiles.d/${name}.env`,
` (общие секреты можно вынести в /etc/nikki/profiles.d/common.env)`,
` chmod 600 /etc/nikki/profiles.d/*.env`,
"2. Собери и включи:",
` mihomo-kit.sh build ${name}`,
` mihomo-kit.sh use ${name}`,
];
if (v.OPENVPN === "1") s.push("", "OpenVPN: заполни /etc/nikki/bmstu.env, положи .ovpn в /etc/nikki/bmstu.ovpn,",
" cron (bmstu-otp.sh check) ставит mihomo-kit.sh install.",
v.LOCATION === "whitelist" ? " На белых списках выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
if (v.TAILSCALE === "1") s.push("", "Tailscale: ссылка для входа — LuCI → Службы → mihomo-kit или",
" mihomo-kit.sh ts-login",
" Потом в админке Tailscale: Disable key expiry для " + (v.TS_HOSTNAME || "ноды") + ".");
return s.join("\n");
}
function update() {
const v = readVars();
const router = v.TARGET === "router";
document.querySelectorAll("[data-router]").forEach((el) => (el.hidden = !router));
document.querySelectorAll("[data-boot]").forEach((el) => (el.hidden = v.BOOT !== "1"));
document.querySelectorAll("[data-openvpn]").forEach((el) => (el.hidden = v.OPENVPN !== "1"));
document.querySelectorAll("[data-tailscale]").forEach((el) => (el.hidden = v.TAILSCALE !== "1"));
document.querySelectorAll("[data-hwid]").forEach((el) => (el.hidden = !v._HWID));
if (!router && tab === "env") setTab("yaml");
const err = $("error");
try {
current.yaml = MihomoKit.render(TEMPLATES, v);
err.hidden = true;
} catch (e) {
current.yaml = "";
err.textContent = e.message;
err.hidden = false;
}
current.env = envFile(v);
current.steps = steps(v);
$("out").textContent = current[tab];
}
function setTab(t) {
tab = t;
document.querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tab === t)));
$("out").textContent = current[t];
}
function parseVless(link) {
try {
const u = new URL(link.trim());
if (u.protocol !== "vless:") return;
const p = u.searchParams;
$("BOOT_UUID").value = decodeURIComponent(u.username);
$("BOOT_SERVER").value = u.hostname.replace(/^\[|\]$/g, "");
$("BOOT_PORT").value = u.port || "443";
if (p.get("sni")) $("BOOT_SNI").value = p.get("sni");
if (p.get("pbk")) $("BOOT_PBK").value = p.get("pbk");
if (p.get("sid")) $("BOOT_SID").value = p.get("sid");
} catch (_) { /* not a full link yet */ }
}
form.addEventListener("change", update);
form.addEventListener("input", (e) => {
if (e.target.id === "vless") parseVless(e.target.value);
update();
});
document.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => setTab(b.dataset.tab)));
$("copy").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(current[tab]); $("copy").textContent = "Скопировано"; }
catch (_) { $("copy").textContent = "Не вышло"; }
setTimeout(() => ($("copy").textContent = "Копировать"), 1200);
});
$("download").addEventListener("click", () => {
const name = tab === "env" ? `${$("PROFILE_NAME").value.trim() || "main"}.env`
: tab === "yaml" ? (radio("TARGET") === "mobile" ? "flclash.yaml" : `${$("PROFILE_NAME").value.trim() || "main"}.yaml`)
: "steps.txt";
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([current[tab]], { type: "text/plain" }));
a.download = name;
a.click();
URL.revokeObjectURL(a.href);
});
addSub();
</script>
</body>
</html>

View File

@ -1,392 +0,0 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mihomo-kit</title>
<style>
:root {
--bg: #f6f6f3; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e2e1dc;
--accent: #2f6f4f; --accent-soft: #e4efe8; --err: #b3261e; --code-bg: #f1f0ec;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
}
.wrap { max-width: 1280px; margin: 0 auto; padding: 24px 16px 48px; }
header h1 { font-size: 20px; margin: 0 0 4px; }
header p { margin: 0 0 20px; color: var(--muted); }
.grid { display: grid; grid-template-columns: minmax(0, 420px) minmax(0, 1fr); gap: 20px; align-items: start; }
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
fieldset { border: 0; border-top: 1px solid var(--line); margin: 0; padding: 14px 0 4px; }
fieldset:first-child { border-top: 0; padding-top: 0; }
legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
label { display: block; margin: 8px 0 4px; color: var(--muted); font-size: 13px; }
input[type=text], textarea {
width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--text); font: 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
textarea { min-height: 64px; resize: vertical; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
.seg label { margin: 0; padding: 6px 12px; cursor: pointer; color: var(--text); font-size: 13px; }
.seg input { display: none; }
.seg label:has(input:checked) { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.check { display: flex; gap: 8px; align-items: center; margin: 6px 0; color: var(--text); font-size: 14px; }
.check input { margin: 0; }
.hint { color: var(--muted); font-size: 12px; margin: 4px 0 0; }
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; }
details summary { cursor: pointer; color: var(--muted); font-size: 13px; margin-top: 8px; }
.tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 10px; }
.tabs button, .actions button {
border: 1px solid var(--line); background: var(--panel); color: var(--text);
padding: 6px 12px; border-radius: 6px; cursor: pointer; font: inherit; font-size: 13px;
}
.tabs button[aria-selected=true] { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); font-weight: 600; }
.actions { display: flex; gap: 6px; margin-left: auto; }
.out-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
pre {
margin: 0; padding: 14px; background: var(--code-bg); border: 1px solid var(--line); border-radius: 8px;
overflow: auto; max-height: 78vh; font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre;
}
.error { color: var(--err); margin: 0 0 10px; font-weight: 600; }
.note { color: var(--muted); font-size: 12px; margin-top: 10px; }
.sub { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px 6px; margin-top: 8px; }
.sub-head { display: flex; gap: 8px; align-items: center; }
.sub-head .name { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); min-width: 34px; }
.sub-head input { flex: 1; min-width: 0; }
.sub-opts { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-top: 6px; font-size: 13px; }
.sub-opts select { padding: 4px 6px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--text); font: inherit; }
.sub-opts .check { margin: 0; font-size: 13px; }
.link-btn { border: 0; background: none; color: var(--accent); cursor: pointer; font: inherit; font-size: 13px; padding: 6px 0 0; }
.x-btn { border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 16px; line-height: 1; padding: 2px 4px; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>mihomo-kit — конструктор конфига</h1>
<p>Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у <code>mihomo-kit.sh</code> на роутере.</p>
</header>
<div class="grid">
<form class="panel" id="form" autocomplete="off">
<fieldset>
<legend>Куда</legend>
<div class="row">
<div class="seg">
<label><input type="radio" name="TARGET" value="router" checked>Роутер (nikki)</label>
<label><input type="radio" name="TARGET" value="mobile">Телефон (FlClash)</label>
</div>
<div class="seg" data-router>
<label><input type="radio" name="LOCATION" value="main" checked>Обычный</label>
<label><input type="radio" name="LOCATION" value="whitelist">Белые списки</label>
<label><input type="radio" name="LOCATION" value="foreign">За рубежом</label>
</div>
</div>
<p class="hint" data-router>Обычный — дома в России или за рубежом. Белые списки: OpenVPN через выбранную RU-ноду (группа OVPN-EXIT), свои серверы через MY-EXIT.</p>
<label for="PROFILE_NAME" data-router>Имя профиля на роутере</label>
<input type="text" id="PROFILE_NAME" value="main" data-router>
</fieldset>
<fieldset>
<legend>Подписки</legend>
<div id="subs"></div>
<button type="button" class="link-btn" id="add-sub">+ подписка</button>
<p class="hint">«Через»: откуда качать подписку. Авто = BOOT-AUTO: BOOT (если включён), иначе ноды сохранённых подписок, иначе напрямую.
HWID — для подписок с лимитом устройств (x-hwid, x-device-os, …).</p>
<label for="RU_IPS">Доп. IP через RU (CIDR через пробел)</label>
<input type="text" id="RU_IPS" value="194.190.191.112/32">
<label for="FOREIGN_IPS">Доп. IP через FOREIGN (CIDR через пробел)</label>
<input type="text" id="FOREIGN_IPS">
<label for="RU_DOMAINS">Доп. домены через RU (через пробел, вместе с поддоменами)</label>
<input type="text" id="RU_DOMAINS" placeholder="example.ru *.example.com">
<label for="FOREIGN_DOMAINS">Доп. домены через FOREIGN (через пробел, вместе с поддоменами)</label>
<input type="text" id="FOREIGN_DOMAINS" placeholder="example.com *.example.org">
</fieldset>
<fieldset>
<legend>BOOT</legend>
<label class="check"><input type="checkbox" id="BOOT" checked>Качать подписки через BOOT (seed)</label>
<div data-boot>
<label for="vless">Вставить vless:// ссылку — поля заполнятся сами</label>
<input type="text" id="vless" placeholder="vless://uuid@host:443?security=reality&sni=…&pbk=…&sid=…">
<div class="two">
<div><label for="BOOT_SERVER">server</label><input type="text" id="BOOT_SERVER"></div>
<div><label for="BOOT_PORT">port</label><input type="text" id="BOOT_PORT" value="443"></div>
</div>
<label for="BOOT_UUID">uuid</label><input type="text" id="BOOT_UUID">
<div class="two">
<div><label for="BOOT_SNI">servername (SNI)</label><input type="text" id="BOOT_SNI" value="eh.vk.ru"></div>
<div><label for="BOOT_SID">short-id</label><input type="text" id="BOOT_SID"></div>
</div>
<label for="BOOT_PBK">public-key</label><input type="text" id="BOOT_PBK">
</div>
</fieldset>
<fieldset data-hwid>
<legend>HWID</legend>
<p class="hint">Общий для всех подписок с галкой HWID. Если провайдер уже знает устройство — тот же x-hwid.</p>
<label for="HWID_UA">User-Agent</label><input type="text" id="HWID_UA" value="v2rayN/9.99">
<div class="two">
<div><label for="HWID_OS">x-device-os</label><input type="text" id="HWID_OS" value="OpenWrt"></div>
<div><label for="HWID_OS_VER">x-ver-os</label><input type="text" id="HWID_OS_VER" placeholder="24.10.3"></div>
</div>
<label for="HWID_MODEL">x-device-model</label><input type="text" id="HWID_MODEL" placeholder="Huasifei WH3000 Pro">
<label for="HWID_ID">x-hwid</label><input type="text" id="HWID_ID">
</fieldset>
<fieldset data-router>
<legend>Модули роутера</legend>
<label class="check"><input type="checkbox" id="TORRENT" checked>Торренты (порты 20000–20199 → TORRENT-SEL)</label>
<label class="check"><input type="checkbox" id="PUSH" checked>Обход для пушей (APNs, FCM → группа PUSH)</label>
<label class="check"><input type="checkbox" id="CSQTT">CSQTT (интерфейс csqtt0 от star-panel-csqtt → группа UPLINK)</label>
<label class="check"><input type="checkbox" id="LITE">Облегчённый режим (256 МБ RAM: реже проверки нод, сниффер без QUIC)</label>
<label class="check"><input type="checkbox" id="OPENVPN">OpenVPN (BMSTU, OTP через bmstu-otp.sh)</label>
<details data-openvpn>
<summary>параметры OpenVPN</summary>
<label for="OVPN_SERVER_HOST">сервер</label><input type="text" id="OVPN_SERVER_HOST">
<label for="OVPN_SERVER_IPS">IP сервера (не пускать в туннель)</label><input type="text" id="OVPN_SERVER_IPS">
<label for="OVPN_ROUTES">сети через туннель</label><input type="text" id="OVPN_ROUTES">
</details>
<label class="check"><input type="checkbox" id="TAILSCALE">Tailscale</label>
<div data-tailscale>
<label for="TS_HOSTNAME">hostname ноды</label><input type="text" id="TS_HOSTNAME" value="fudy-mihomo">
<label for="TS_DOMAINS">split-DNS домены тейлнета, кроме *.ts.net</label><input type="text" id="TS_DOMAINS">
<label class="check"><input type="checkbox" id="TS_EXIT">Через TS-EXIT (только ss/hysteria2/tuic ноды)</label>
</div>
</fieldset>
</form>
<section class="panel">
<div class="out-head">
<div class="tabs" role="tablist">
<button type="button" data-tab="yaml" aria-selected="true">config.yaml</button>
<button type="button" data-tab="env" aria-selected="false" data-router>profile .env</button>
<button type="button" data-tab="steps" aria-selected="false">Что дальше</button>
</div>
<div class="actions">
<button type="button" id="copy">Копировать</button>
<button type="button" id="download">Скачать</button>
</div>
</div>
<p class="error" id="error" hidden></p>
<pre id="out"></pre>
<p class="note">На роутере удобнее держать <code>.env</code> и собирать там: <code>mihomo-kit.sh build</code>. YAML отсюда — для телефона или разовой проверки.</p>
</section>
</div>
</div>
<script>
/*__ENGINE__*/
</script>
<script>
const TEMPLATES = /*__TEMPLATES__*/;
const D = MihomoKit.DEFAULTS;
const $ = (id) => document.getElementById(id);
const form = $("form");
let tab = "yaml";
let current = { yaml: "", env: "", steps: "" };
for (const k of ["OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) $(k).value = D[k];
function addSub() {
const row = document.createElement("div");
row.className = "sub";
row.innerHTML = `
<div class="sub-head"><span class="name"></span>
<input type="text" data-k="url" placeholder="https://sub.example.com/sub/xxxx или имя=https://…">
<button type="button" class="x-btn" title="убрать">×</button></div>
<div class="sub-opts">
<label>через <select data-k="proxy"><option value="">авто</option><option>BOOT-AUTO</option><option>BOOT</option><option>DIRECT</option><option>FOREIGN</option></select></label>
<label class="check"><input type="checkbox" data-k="hwid">HWID</label>
</div>
<details><summary>User-Agent и заголовки</summary>
<label>User-Agent (пусто = mihomo, с HWID — из блока HWID)</label><input type="text" data-k="ua">
<label>доп. заголовки: key=value; key2=value 2</label><input type="text" data-k="headers">
</details>`;
row.querySelector(".x-btn").addEventListener("click", () => {
if (document.querySelectorAll("#subs .sub").length > 1) row.remove();
update();
});
$("subs").appendChild(row);
update();
}
$("add-sub").addEventListener("click", addSub);
// rows with a URL, in order; id = provider name from the domain (or "name=url")
function readSubs() {
const rows = [...document.querySelectorAll("#subs .sub")];
const filled = rows.filter((row) => row.querySelector("[data-k=url]").value.trim());
const ids = MihomoKit.subPairs(filled.map((row) => row.querySelector("[data-k=url]").value.trim()).join(" "));
rows.forEach((row) => (row.querySelector(".name").textContent = ""));
return filled.map((row, n) => {
const get = (k) => row.querySelector(`[data-k=${k}]`);
row.querySelector(".name").textContent = ids[n].id;
return { id: ids[n].id, url: ids[n].word, proxy: get("proxy").value, hwid: get("hwid").checked,
ua: get("ua").value.trim(), headers: get("headers").value.trim() };
});
}
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
function flag(id) { return $(id).checked ? "1" : "0"; }
function readVars() {
const v = {
TARGET: radio("TARGET"), LOCATION: radio("LOCATION"),
SUBS: "",
RU_IPS: $("RU_IPS").value.trim(), FOREIGN_IPS: $("FOREIGN_IPS").value.trim(),
RU_DOMAINS: $("RU_DOMAINS").value.trim(), FOREIGN_DOMAINS: $("FOREIGN_DOMAINS").value.trim(),
BOOT: flag("BOOT"), TORRENT: flag("TORRENT"), PUSH: flag("PUSH"), OPENVPN: flag("OPENVPN"),
TAILSCALE: flag("TAILSCALE"), TS_EXIT: flag("TS_EXIT"), CSQTT: flag("CSQTT"), LITE: flag("LITE"),
};
for (const k of ["BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID",
"TS_HOSTNAME", "TS_DOMAINS", "OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) {
v[k] = $(k).value.trim();
}
const subs = readSubs();
v.SUBS = subs.map((x) => x.url).join(" ");
v._HWID = subs.some((x) => x.hwid);
for (const x of subs) {
const p = `SUB_${x.id.toUpperCase()}_`;
if (x.proxy) v[p + "PROXY"] = x.proxy;
if (x.hwid) v[p + "HWID"] = "1";
if (x.ua) v[p + "UA"] = x.ua;
if (x.headers) v[p + "HEADERS"] = x.headers;
}
for (const k of ["HWID_UA", "HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) v[k] = $(k).value.trim();
return v;
}
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
function envFile(v) {
const keys = ["TARGET", "LOCATION", "SUBS"];
keys.push(...Object.keys(v).filter((k) => /^SUB_/.test(k) && k !== "SUB_LIST"));
if (v._HWID) keys.push("HWID_UA", "HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID");
keys.push("BOOT");
if (v.BOOT === "1") keys.push("BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID");
keys.push("TORRENT", "PUSH", "RU_IPS", "FOREIGN_IPS", "RU_DOMAINS", "FOREIGN_DOMAINS", "OPENVPN");
if (v.OPENVPN === "1") keys.push("OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES");
keys.push("CSQTT", "LITE", "TAILSCALE");
if (v.TAILSCALE === "1") keys.push("TS_HOSTNAME", "TS_DOMAINS", "TS_EXIT");
return "# mihomo-kit profile (secrets inside: chmod 600)\n" +
keys.map((k) => `${k}=${q(v[k] ?? "")}`).join("\n") + "\n";
}
function steps(v) {
const name = $("PROFILE_NAME").value.trim() || "main";
if (v.TARGET === "mobile") {
return [
"Телефон (FlClash):",
"1. Скачай config.yaml (кнопка «Скачать»).",
"2. FlClash → Профили → + → Файл → выбери config.yaml.",
"3. Включи профиль; геобазы скачаются при первом запуске.",
].join("\n");
}
const s = [
"Роутер (nikki). Один раз на новом роутере — см. README, раздел «Новый роутер».",
"",
`1. Сохрани profile .env как /etc/nikki/profiles.d/${name}.env`,
` (общие секреты можно вынести в /etc/nikki/profiles.d/common.env)`,
` chmod 600 /etc/nikki/profiles.d/*.env`,
"2. Собери и включи:",
` mihomo-kit.sh build ${name}`,
` mihomo-kit.sh use ${name}`,
];
if (v.OPENVPN === "1") s.push("", "OpenVPN: заполни /etc/nikki/bmstu.env, положи .ovpn в /etc/nikki/bmstu.ovpn,",
" cron (bmstu-otp.sh check) ставит mihomo-kit.sh install.",
v.LOCATION === "whitelist" ? " На белых списках выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
if (v.TAILSCALE === "1") s.push("", "Tailscale: ссылка для входа — LuCI → Службы → mihomo-kit или",
" mihomo-kit.sh ts-login",
" Потом в админке Tailscale: Disable key expiry для " + (v.TS_HOSTNAME || "ноды") + ".");
return s.join("\n");
}
function update() {
const v = readVars();
const router = v.TARGET === "router";
document.querySelectorAll("[data-router]").forEach((el) => (el.hidden = !router));
document.querySelectorAll("[data-boot]").forEach((el) => (el.hidden = v.BOOT !== "1"));
document.querySelectorAll("[data-openvpn]").forEach((el) => (el.hidden = v.OPENVPN !== "1"));
document.querySelectorAll("[data-tailscale]").forEach((el) => (el.hidden = v.TAILSCALE !== "1"));
document.querySelectorAll("[data-hwid]").forEach((el) => (el.hidden = !v._HWID));
if (!router && tab === "env") setTab("yaml");
const err = $("error");
try {
current.yaml = MihomoKit.render(TEMPLATES, v);
err.hidden = true;
} catch (e) {
current.yaml = "";
err.textContent = e.message;
err.hidden = false;
}
current.env = envFile(v);
current.steps = steps(v);
$("out").textContent = current[tab];
}
function setTab(t) {
tab = t;
document.querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tab === t)));
$("out").textContent = current[t];
}
function parseVless(link) {
try {
const u = new URL(link.trim());
if (u.protocol !== "vless:") return;
const p = u.searchParams;
$("BOOT_UUID").value = decodeURIComponent(u.username);
$("BOOT_SERVER").value = u.hostname.replace(/^\[|\]$/g, "");
$("BOOT_PORT").value = u.port || "443";
if (p.get("sni")) $("BOOT_SNI").value = p.get("sni");
if (p.get("pbk")) $("BOOT_PBK").value = p.get("pbk");
if (p.get("sid")) $("BOOT_SID").value = p.get("sid");
} catch (_) { /* not a full link yet */ }
}
form.addEventListener("change", update);
form.addEventListener("input", (e) => {
if (e.target.id === "vless") parseVless(e.target.value);
update();
});
document.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => setTab(b.dataset.tab)));
$("copy").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(current[tab]); $("copy").textContent = "Скопировано"; }
catch (_) { $("copy").textContent = "Не вышло"; }
setTimeout(() => ($("copy").textContent = "Копировать"), 1200);
});
$("download").addEventListener("click", () => {
const name = tab === "env" ? `${$("PROFILE_NAME").value.trim() || "main"}.env`
: tab === "yaml" ? (radio("TARGET") === "mobile" ? "flclash.yaml" : `${$("PROFILE_NAME").value.trim() || "main"}.yaml`)
: "steps.txt";
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([current[tab]], { type: "text/plain" }));
a.download = name;
a.click();
URL.revokeObjectURL(a.href);
});
addSub();
</script>
</body>
</html>