From d03040779bc24b5c8287641bf7b5f50d68f33fbb Mon Sep 17 00:00:00 2001 From: Sam Latsin Date: Mon, 26 Oct 2026 15:52:40 +0300 Subject: [PATCH] Improved custom servers features --- README.md | 74 +- luci/mihomo-kit.js | 340 ++--- luci/rpcd.sh | 15 + luci/servers.js | 1410 ++++++++++++++++++++ router/mihomo-kit.sh | 96 +- templates/groups/45-sub.yaml | 6 +- templates/proxies/30-hy2.each.yaml | 14 - templates/proxies/30-own_srv.yaml | 6 + tests/expected/mobile.yaml | 242 ++++ tests/expected/router-boots.yaml | 274 ++++ tests/expected/router-csqtt-foreign.yaml | 281 ++++ tests/expected/router-csqtt.yaml | 289 ++++ tests/expected/router-foreign.yaml | 322 +++++ tests/expected/router-hwid.yaml | 252 ++++ tests/expected/router-ids.yaml | 287 ++++ tests/expected/router-lite-csqtt.yaml | 278 ++++ tests/expected/router-lite.yaml | 270 ++++ tests/expected/router-main.yaml | 338 +++++ tests/expected/router-minimal.yaml | 191 +++ tests/expected/router-whitelist-ts-my.yaml | 314 +++++ tests/expected/router-whitelist-ts.yaml | 297 +++++ tests/expected/router-whitelist.yaml | 353 +++++ tests/fixtures/mobile.env | 1 + tests/fixtures/own.servers | 3 + tests/fixtures/router-boots.env | 4 +- tests/fixtures/router-csqtt-foreign.env | 1 + tests/fixtures/router-csqtt.env | 1 + tests/fixtures/router-main.env | 1 + tests/fixtures/router-whitelist-ts-my.env | 1 + tests/links/links-edge.expected.json | 178 +++ tests/links/links-edge.txt | 20 + tests/links/links.expected.json | 773 +++++++++++ tests/links/links.txt | 53 + tests/links/sub.b64 | 1 + tests/links/sub.expected.json | 28 + tests/yaml/clash.expected.json | 1 + tests/yaml/clash.yaml | 61 + tests/yaml/list.expected.json | 1 + tests/yaml/list.yaml | 29 + tests/yaml/one.expected.json | 1 + tests/yaml/one.yaml | 5 + tools/build-web.py | 21 - tools/render.js | 22 - tools/test-servers.js | 42 + tools/test.sh | 25 +- web/engine.js | 358 ----- web/index.html | 785 ----------- web/index.src.html | 392 ------ 48 files changed, 6878 insertions(+), 1879 deletions(-) create mode 100644 luci/servers.js delete mode 100644 templates/proxies/30-hy2.each.yaml create mode 100644 templates/proxies/30-own_srv.yaml create mode 100644 tests/expected/mobile.yaml create mode 100644 tests/expected/router-boots.yaml create mode 100644 tests/expected/router-csqtt-foreign.yaml create mode 100644 tests/expected/router-csqtt.yaml create mode 100644 tests/expected/router-foreign.yaml create mode 100644 tests/expected/router-hwid.yaml create mode 100644 tests/expected/router-ids.yaml create mode 100644 tests/expected/router-lite-csqtt.yaml create mode 100644 tests/expected/router-lite.yaml create mode 100644 tests/expected/router-main.yaml create mode 100644 tests/expected/router-minimal.yaml create mode 100644 tests/expected/router-whitelist-ts-my.yaml create mode 100644 tests/expected/router-whitelist-ts.yaml create mode 100644 tests/expected/router-whitelist.yaml create mode 100644 tests/fixtures/own.servers create mode 100644 tests/links/links-edge.expected.json create mode 100644 tests/links/links-edge.txt create mode 100644 tests/links/links.expected.json create mode 100644 tests/links/links.txt create mode 100644 tests/links/sub.b64 create mode 100644 tests/links/sub.expected.json create mode 100644 tests/yaml/clash.expected.json create mode 100644 tests/yaml/clash.yaml create mode 100644 tests/yaml/list.expected.json create mode 100644 tests/yaml/list.yaml create mode 100644 tests/yaml/one.expected.json create mode 100644 tests/yaml/one.yaml delete mode 100755 tools/build-web.py delete mode 100755 tools/render.js create mode 100755 tools/test-servers.js delete mode 100644 web/engine.js delete mode 100644 web/index.html delete mode 100644 web/index.src.html diff --git a/README.md b/README.md index 18edb54..eb31b7f 100644 --- a/README.md +++ b/README.md @@ -207,25 +207,33 @@ BOOT — whitelisted seed-ноды для скачивания подписок: Пуши (Apple `*.push.apple.com` и подсети 17.x, Google FCM `mtalk.google.com`, порты 5228–5230) идут через группу `PUSH`: на `main` по умолчанию `DIRECT`, на `whitelist` — `MY` -(без своих hysteria2 — `FOREIGN`); переключается в дашборде. Долгое соединение пушей +(без своих серверов — `FOREIGN`); переключается в дашборде. Долгое соединение пушей рвётся, когда меняется нода под ним, — отсюда пропадающие уведомления. Отключается галочкой «Обход для пушей» (`PUSH=0` в `common.env`) — тогда пуши идут по общим правилам. -Свои серверы hysteria2 — LuCI → Настройка → «Свои серверы» (или `HY2="имя1 имя2"` и -`HY2_<ИМЯ>_SERVER/_PORT/_PASSWORD/_OBFS_PASSWORD/_SNI/_INSECURE/_UP/_DOWN` в -`common.env`). Они собираются в группу `MY` (url-test: самый быстрый живой; в дашборде -можно закрепить конкретный). `MY` — пункт в `MAIN` рядом с `FOREIGN` (переключать -вручную). К самим серверам на `whitelist` подключение через группу `MY-EXIT` (те же ноды, -что в `FOREIGN`, но с `tolerance: 300`: меняет ноду, только если текущая заметно хуже или -умерла — каждая смена рвёт всё, что идёт через `MY`), на `main` — напрямую. +Свои серверы — LuCI → Настройка → «Свои серверы». Каждый сервер — карточка: имя (так он +виден в дашборде), тип и адрес, «Настройки (YAML)» — весь сервер в формате mihomo, правится +на месте. «Добавить из ссылки / YAML» принимает сразу несколько: ссылки `vless://`, `vmess://`, +`trojan://`, `ss://`, `hysteria2://`, `tuic://`, `anytls://` (и `socks5://`, `http(s)://`, +`ssr://`, `hysteria://`, `mierus://`), подписку в base64 или YAML из конфига mihomo / Clash +(список `proxies:`, просто список или один сервер). Ссылки страница разбирает так же, как +mihomo разбирает подписку (`luci/servers.js` — перенос его `common/convert`, `tools/test.sh` +сверяет с ним): reality, xhttp, ws, grpc и прочее — как в приложении. «Скопировать» отдаёт +сервер как YAML для другого роутера. -Свои серверы других протоколов — там же, поле «Ссылки» (или `MY_LINKS` в `common.env`, через -пробел): ссылки `vless://`, `vmess://`, `trojan://`, `ss://`, `hysteria2://`, `tuic://`, -`anytls://` как из приложения. Разбирает их само ядро, как подписку (reality, xhttp, ws, -grpc и т. д.): kit при сборке пишет их в `run/providers/my-links.txt` (права 600), его читает -file-провайдер `my-links` в группе `MY`, ноды называются `[MY] <имя из ссылки>`. Пробелы в имени -после `#` форма заменяет на `%20`. Как и hysteria2, на `whitelist` они идут через `MY-EXIT`. -Только на роутере: в конфиг телефона ссылки не попадают (на телефоне — `[MY]`-ноды подписки). +Серверы хранятся в `/etc/nikki/my-servers` (права 600, по одному JSON-объекту прокси на +строку) и переносятся экспортом настроек. Сборка вписывает их в `proxies:` профилей роутера +и в конфиг телефона и собирает в группу `MY` (url-test: самый быстрый живой; в дашборде +можно закрепить конкретный). `MY` — пункт в `MAIN` рядом с `FOREIGN` (переключать +вручную). К самим серверам на `whitelist` и с телефона подключение через группу `MY-EXIT` +(те же ноды, что в `FOREIGN`, но с `tolerance: 300`: меняет ноду, только если текущая +заметно хуже или умерла — каждая смена рвёт всё, что идёт через `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] 🇩🇪 de-1`, регистр не важен), из любой подписки сами попадают в `MY`, а не в `RU` / @@ -236,7 +244,7 @@ file-провайдер `my-links` в группе `MY`, ноды называю только их (на телефоне FlClash переносит файлы провайдеров к себе, поэтому там `<имя>-my` качает ту же ссылку ещё раз) — свой провайдер нужен, чтобы на `whitelist` и телефоне ходить к ним через `MY-EXIT`. Группа `MY` теперь есть -всегда; без hysteria2, ссылок и `[MY]`-нод она пустая, и `PUSH` на `whitelist` тогда по +всегда; без своих серверов и `[MY]`-нод она пустая, и `PUSH` на `whitelist` тогда по умолчанию `FOREIGN`. CSQTT ([star-panel-csqtt](https://github.com/starkugz/csqtt-openwrt)) — резервный выход из белых @@ -326,12 +334,6 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво содержит ссылки подписок — токен и есть секрет; «Новая ссылка» (`mihomo-kit.sh mobile new`) отзывает старую. -Без роутера — веб-конструктор: - -Открыть [web/index.html](web/index.html) (из репозитория или со своего хостинга) → -«Телефон» → подписки и vless-ссылка BOOT → «Скачать» → FlClash: Профили → + → Файл. -Страница всё считает в браузере и никуда ничего не отправляет. - ## Профили | | роутер `main` | роутер `whitelist` | роутер `foreign` | телефон | @@ -345,7 +347,7 @@ RU-адреса, без OpenVPN, Tailscale, торрентов и `PUSH`; сво | всё остальное (`MAIN`) | `FOREIGN` | `FOREIGN` | напрямую (можно `MY`) | `FOREIGN` | | торренты (порты 20000–20199) | ✓ | ✓ | ✓ | — | | OpenVPN | напрямую | через `OVPN-EXIT` (RU-нода) | через `OVPN-EXIT` (RU-нода) | — | -| Tailscale | напрямую | через `MY` (свои hysteria2 и `[MY]`-ноды подписки), без них напрямую* | напрямую | — | +| Tailscale | напрямую | через `MY` (свои серверы и `[MY]`-ноды подписки), без них напрямую* | напрямую | — | | свои серверы | напрямую | через `MY-EXIT` | напрямую | через `MY-EXIT` | | пуши (`PUSH`, отключаемо) | `DIRECT` | `MY` | `DIRECT` | — | @@ -449,30 +451,32 @@ opkg сравнивает полный размер новых пакетов с ``` install.sh загрузчик: кит в /etc/nikki/kit + mihomo-kit.sh setup -templates/ фрагменты конфига (общие для скрипта и страницы) +templates/ фрагменты конфига presets/ профили, которые setup кладёт в profiles.d router/ mihomo-kit.sh сборка, setup-мастер, use/update/fix bmstu-otp.sh OpenVPN BMSTU: TOTP в пароле, cron-сторож, on/off -luci/ страница LuCI «Службы → mihomo-kit»: rpcd.sh (бэкенд), view, ACL, меню -web/ страница-конструктор: engine.js + index.src.html → index.html -tools/ push.sh, test.sh, build-web.py, render.js -tests/fixtures/ профили для test.sh (фиктивные секреты) +luci/ страница LuCI «Службы → mihomo-kit»: rpcd.sh (бэкенд), view, ACL, меню, + servers.js (ссылки и YAML своих серверов), qrcode.js +tools/ push.sh, test.sh, test-servers.js, core/ (ядро kit) +tests/fixtures/ профили для test.sh (фиктивные секреты), own.servers +tests/expected/ эталонный YAML каждого профиля +tests/links/, yaml/ ссылки и YAML с выводом Go-кода mihomo для luci/servers.js ``` Шаблоны: `templates/<секция>/NN-<модуль>[.<тег>...][.each].yaml`; секции собираются в порядке head, proxies, providers, sniffer, dns, groups, rules, файлы — по имени. - файл включается, если активны модуль и все теги; `.each` — по разу на элемент модуля - (`sub` — подписка: `${SUB_NAME}`, `${SUB_URL}`; `hy2` — свой сервер: `${HY2_NAME}`, ...); + (`sub` — подписка: `${SUB_NAME}`, `${SUB_URL}`; `boot` — seed-нода: `${SEED_NAME}`, ...); - `${@@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`, -`openvpn`, `tailscale`, `ts_exit`, `hy2`, `my_links`, `local_hosts`, `csqtt`, `lite`. Значения по умолчанию — `set_defaults` в -`router/mihomo-kit.sh` и `DEFAULTS` в `web/engine.js` (держать одинаковыми). +Теги: `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`, `my_links`, `local_hosts`, `csqtt`, `lite`. Значения по умолчанию — `set_defaults` в +`router/mihomo-kit.sh`. ### Ядро kit @@ -494,9 +498,9 @@ tests/fixtures/ профили для test.sh (фиктивные секре Новая версия mihomo или новая правка — следующий суффикс (`ts6`) в шагах 1–3. Патчи применяются по алфавиту; если не накладываются, поправить их на новом теге. -После правки шаблонов или движка: +После правки шаблонов, скрипта или `luci/servers.js`: ```sh -MIHOMO=/path/to/mihomo tools/test.sh # sh и JS дают одинаковый YAML, mihomo -t проходит -tools/build-web.py # пересобрать web/index.html +MIHOMO=/path/to/mihomo tools/test.sh # профили = tests/expected/, mihomo -t проходит, servers.js = Go +UPDATE=1 tools/test.sh # переписать tests/expected/ (изменения — проверить в diff) ``` diff --git a/luci/mihomo-kit.js b/luci/mihomo-kit.js index b528745..20ab2ca 100644 --- a/luci/mihomo-kit.js +++ b/luci/mihomo-kit.js @@ -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" function loadQr() { if (window.qrcode) @@ -197,22 +110,17 @@ function loadQr() { }); } -// one hysteria2 server from the form -> mihomo proxy YAML (parseHy2 reads it back) -function hy2Yaml(d) { - var q = function(v) { return '"' + String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'; }; - var y = [ '- name: ' + d.name, ' type: hysteria2', ' server: ' + d.server, ' port: ' + d.port, - ' password: ' + q(d.password) ]; - if (d.obfs_password) - y.push(' obfs: salamander', ' obfs-password: ' + q(d.obfs_password)); - if (d.sni) - y.push(' sni: ' + d.sni); - if (d.insecure) - 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'; +// own servers: luci/servers.js (links and YAML -> proxies), a global "mkServers" +function loadServers() { + if (window.mkServers) + return Promise.resolve(window.mkServers); + return new Promise(function(resolve, reject) { + var s = document.createElement('script'); + s.src = L.resource('mihomo-kit/servers.js'); + s.onload = function() { resolve(window.mkServers); }; + s.onerror = function() { reject(new Error('servers.js not loaded')); }; + document.head.appendChild(s); + }); } // 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) renderSettingsBox: function(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', { 'class': 'btn cbi-button cbi-button-action', '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'), my_domains: text(cfg.my_domains, 'example.com *.example.org'), 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), csqtt: check(cfg.csqtt), ovpn: E('input', { 'type': 'file', 'accept': '.ovpn,.conf' }), @@ -651,60 +559,114 @@ return view.extend({ }; (cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub); - // own hysteria2 servers: one block of fields each - var hy2List = E('div'), hy2 = []; - var addHy2 = function(h) { - var e = { - name: text(h.name, 'nl-1'), - server: text(h.server, 'vpn.example.com'), - port: text(h.port || '443'), - password: text(h.password, '', 'password'), - obfs_password: text(h.obfs_password, 'пусто — без obfs', 'password'), - sni: text(h.sni, 'пусто — как server'), - insecure: check(h.insecure == '1'), - up: text(h.up, '50 mbps'), - down: text(h.down, '100 mbps') + // own servers (luci/servers.js): a card each - the name, type and address, the + // proxy as YAML to edit; share links / YAML pasted below become cards + var S = window.mkServers; + var srvList = E('div'), servers = []; + var taken = function() { + var t = {}; + servers.forEach(function(e) { t[e.name.value.trim()] = true; }); + return t; + }; + var addServer = function(p, open) { + var e = { proxy: {}, error: null }; + Object.keys(p).forEach(function(k) { + 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' }, [ - field('Имя', e.name, 'буквы, цифры, _ - ; так сервер виден в дашборде'), - field('Сервер', e.server), - field('Порт', e.port), - field('Пароль', e.password, 'auth.password на сервере'), - field('Obfs-пароль', e.obfs_password, 'salamander; пусто — без obfs'), - field('SNI', e.sni), - field('Не проверять сертификат', e.insecure, 'для самоподписанного сертификата (SNI чужого сайта)'), - field('Up / Down', [ e.up, e.down ], 'реальный потолок канала клиента; пусто — без ограничения'), - E('div', [ + E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [ + e.name, info, + E('button', { 'class': 'btn cbi-button', 'click': function() { + e.yaml.style.display = e.yaml.style.display == 'none' ? '' : 'none'; + } }, 'Настройки (YAML)'), 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(), - 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() }); + var yaml = S.yamlDump([ e.get() ]) + '\n'; copyText(yaml).then(function(ok) { if (ok) - return ui.addNotification(null, E('p', 'Конфиг ' + e.name.value.trim() + - ' скопирован: на другом роутере — «Импорт из YAML / ссылки». В нём пароли, не публикуй.'), 'info'); - ui.showModal('Конфиг ' + e.name.value.trim(), [ + return ui.addNotification(null, E('p', 'Сервер ' + e.name.value.trim() + + ' скопирован: на другом роутере — «Добавить из ссылки / YAML». В нём пароли, не публикуй.'), 'info'); + ui.showModal('Сервер ' + e.name.value.trim(), [ E('p', 'Скопировать автоматически не вышло — выдели и скопируй:'), E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'readonly': 'readonly', '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('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() { - hy2List.removeChild(el); - hy2.splice(hy2.indexOf(e), 1); - } }, 'Удалить сервер') - ]) + } }, 'Скопировать'), + E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить сервер', 'click': function() { + srvList.removeChild(el); + servers.splice(servers.indexOf(e), 1); + } }, '✕') + ]), + e.yaml, err ]); - hy2.push(e); - hy2List.appendChild(el); + servers.push(e); + 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 - var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 10, 'style': 'width:100%;font-family:monospace', - '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' }); + // import: share links and/or YAML (or a file) -> cards + var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 8, 'spellcheck': 'false', + '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' }); importFile.addEventListener('change', function() { 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('span', 'или из файла:'), importFile, E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': function() { - var found = parseHy2(importText.value); - if (!found.length) { - ui.addNotification(null, E('p', 'Не нашёл серверов hysteria2: нужны хотя бы server и password'), 'warning'); - return; + var r = S.parseText(importText.value); + r.servers.forEach(function(p) { addServer(p); }); + var msg = [ E('p', r.servers.length ? 'Добавлено серверов: ' + r.servers.length + + '. Проверь имена и нажми «Сохранить и применить».' : 'Серверов не нашёл.') ]; + 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())) errors.push('Лимит памяти: число с единицей, например 64MiB'); - var names = {}; - var hy2Data = hy2.map(function(e) { - var d = {}; - Object.keys(e).forEach(function(k) { - d[k] = k == 'insecure' ? e[k].checked : (k == 'password' || k == 'obfs_password' ? e[k].value : e[k].value.trim()); - }); - if (!/^[A-Za-z0-9_-]+$/.test(d.name)) - errors.push('Свой сервер: имя «' + d.name + '» — только буквы, цифры, _ -'); - else if (names[d.name.toUpperCase().replace(/-/g, '_')]) - errors.push('Свой сервер: имя ' + d.name + ' повторяется'); - names[d.name.toUpperCase().replace(/-/g, '_')] = true; - if (!d.server || !/^[0-9]+$/.test(d.port) || !d.password) - errors.push('Свой сервер ' + (d.name || '?') + ': нужны сервер, порт и пароль'); - return d; + var names = {}, srvLines = []; + servers.forEach(function(e) { + var n = e.name.value.trim(); + if (!n) + errors.push('Свой сервер: пустое имя'); + else if (names[n]) + errors.push('Свой сервер: имя «' + n + '» повторяется'); + names[n] = true; + if (e.error) + errors.push('Свой сервер ' + n + ': ' + e.error); + else if (e.proxy.server === undefined || e.proxy.server === null || e.proxy.server === '') + errors.push('Свой сервер ' + n + ': пустой server (открой «Настройки (YAML)»)'); + srvLines.push(S.toLine(e.get())); }); if (errors.length) { 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(), my_domains: f.my_domains.value.trim(), local_hosts: f.local_hosts.value.trim(), - my_links: f.my_links.value.trim(), + my_links: '', openvpn: f.openvpn.checked, csqtt: f.csqtt.checked, ovpn: ovpn, @@ -841,7 +787,8 @@ return view.extend({ mobile: f.mobile.checked, lite: f.lite.checked, lite_gomemlimit: f.lite_gomemlimit.value.trim(), - hy2: hy2Data + hy2: [], + servers_text: srvLines.join('\n') }); }, this)).then(L.bind(function(r) { if (r.error) { @@ -899,19 +846,20 @@ return view.extend({ 'при импорте не переносится)'), E('h4', 'Свои серверы'), E('p', { 'class': 'cbi-value-description' }, 'Собираются в группу MY (автовыбор самого быстрого, в дашборде можно закрепить один). MY — пункт в MAIN ' + - 'рядом с FOREIGN. К самим серверам на whitelist — через MY-EXIT, на main — напрямую. ' + - 'Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY, а не в FOREIGN/RU.'), - field('Ссылки', f.my_links, 'vless / vmess / trojan / ss / hysteria2 / tuic / anytls — как в приложении ' + - '(reality, xhttp, ws, grpc разбирает само ядро); в MY как «[MY] имя». Только на этом роутере, в конфиг ' + - 'телефона не попадают'), - E('h5', 'hysteria2 по полям'), - hy2List, + 'рядом с FOREIGN. К самим серверам на whitelist и с телефона — через MY-EXIT, на main — напрямую. Ссылки ' + + 'vless / vmess / trojan / ss / hysteria2 / tuic / anytls и YAML разбираются так же, как в mihomo; серверы ' + + 'попадают и в конфиг телефона. Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY.'), + moved ? E('p', { 'class': 'alert-message warning' }, 'Перенесено из старых настроек (hysteria2 по полям, ссылки): ' + + moved + '. Нажми «Сохранить и применить», чтобы сохранить их в новом виде.') : '', + srvList, importBox, E('div', [ - E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addHy2({}); } }, 'Добавить сервер'), ' ', - E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() { + E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { 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 ]) ]); diff --git a/luci/rpcd.sh b/luci/rpcd.sh index 0f923c0..0b44b65 100644 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -283,6 +283,9 @@ m_config_get() { json_add_string foreign_domains "${FOREIGN_DOMAINS:-}" json_add_string my_domains "${MY_DOMAINS:-}" 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 set -f 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, # 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, # 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 @@ -331,6 +335,17 @@ m_config_set() { lite lite_gomemlimit; do json_get_var "$v" "$v" "" 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 umask 077 printf '%s\n' "$ovpn" > "$NIKKI_DIR/bmstu.ovpn.tmp" && mv "$NIKKI_DIR/bmstu.ovpn.tmp" "$NIKKI_DIR/bmstu.ovpn" diff --git a/luci/servers.js b/luci/servers.js new file mode 100644 index 0000000..1b639c2 --- /dev/null +++ b/luci/servers.js @@ -0,0 +1,1410 @@ +// Own servers of the kit (LuCI "Свои серверы"): share links and YAML -> mihomo proxy +// objects, and one stored line per server (/etc/nikki/my-servers, see mihomo-kit.sh). +// parseLinks is a port of mihomo's common/convert (ConvertsV2Ray) so a link gives the +// same proxy as in a subscription; tools/test.sh checks it against the Go converter. +// Browser: a global "mkServers" (loaded like qrcode.js); node: module.exports. +(function (root, factory) { + var api = factory(); + if (typeof module === 'object' && module.exports) + module.exports = api; + else + root.mkServers = api; +})(this, function () { + 'use strict'; + + // mihomo puts a random browser User-Agent into ws headers; a fixed one here + var 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'; + + // --- base64 as Go's encoding/base64 (strict alphabets, \r \n skipped) ------------- + + var STD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var URLSAFE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; + + // -> byte array or null; padded: '=' required to a multiple of 4, else forbidden + function b64(s, alphabet, padded) { + s = String(s).replace(/[\r\n]/g, ''); + var body = s; + if (padded) { + if (s.length % 4) + return null; + var p = s.indexOf('='); + if (p >= 0) { + if (!/^={1,2}$/.test(s.slice(p)) || s.length - p > 2) + return null; + body = s.slice(0, p); + if ((body.length + (s.length - p)) % 4) + return null; + } + } else if (s.indexOf('=') >= 0) { + return null; + } + if (body.length % 4 == 1) + return null; + var out = [], bits = 0, acc = 0; + for (var i = 0; i < body.length; i++) { + var v = alphabet.indexOf(body.charAt(i)); + if (v < 0) + return null; + acc = (acc << 6) | v; + bits += 6; + if (bits >= 8) { + bits -= 8; + out.push((acc >> bits) & 0xff); + } + } + // Go rejects non-zero trailing bits + if (bits && (acc & ((1 << bits) - 1))) + return null; + return out; + } + + function utf8(bytes) { + var s = ''; + for (var i = 0; i < bytes.length; i++) + s += '%' + ('0' + bytes[i].toString(16)).slice(-2); + try { + return decodeURIComponent(s); + } catch (e) { + // invalid UTF-8: one char per byte (Go keeps the bytes, a string can't) + return bytes.map(function (b) { return String.fromCharCode(b); }).join(''); + } + } + + // tryDecodeBase64: RawStdEncoding, then StdEncoding + function tryDecodeBase64(s) { + var r = b64(s, STD, false); + if (r === null) + r = b64(s, STD, true); + return r === null ? null : utf8(r); + } + + function decodeBase64(s) { + var r = tryDecodeBase64(s); + return r === null ? s : r; + } + + // TryDecodeBase64 (util.go): by length, std then url-safe + function tryDecodeBase64Str(s) { + var r = s.length % 4 == 0 ? (b64(s, STD, true) || b64(s, URLSAFE, true)) + : (b64(s, STD, false) || b64(s, URLSAFE, false)); + return r === null ? null : utf8(r); + } + + function decodeUrlSafe(s) { + var r = b64(s, URLSAFE, false); + return r === null ? '' : utf8(r); + } + + function urlSafe(s) { + return s.replace(/\+/g, '-').replace(/\//g, '_'); + } + + // --- net/url as in Go ------------------------------------------------------------ + + // unescape: '+' -> ' ' only in query mode; a bad %-escape -> null + function unescape(s, query) { + if (/%(?![0-9A-Fa-f]{2})/.test(s)) + return null; + if (query) + s = s.replace(/\+/g, ' '); + try { + return decodeURIComponent(s); + } catch (e) { + // valid escapes but not UTF-8: per byte + return s.replace(/%([0-9A-Fa-f]{2})/g, function (_, h) { return String.fromCharCode(parseInt(h, 16)); }); + } + } + + // escaping of userinfo as Go's url.User(...).String() (encodeUserPassword): letters, + // digits, - _ . ~ and $ & + , ; = stay, the rest is %XX of the UTF-8 bytes + function escapeUser(s) { + return encodeURIComponent(s) + .replace(/%(24|26|2B|2C|3B|3D)/g, function (_, h) { return String.fromCharCode(parseInt(h, 16)); }) + .replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); + } + + // ParseQuery: '&'-separated; pairs with ';' or a bad escape are dropped (Go errors + // on them and url.Query() ignores the error) + function parseQuery(raw) { + var q = {}; + String(raw || '').split('&').forEach(function (kv) { + if (!kv || kv.indexOf(';') >= 0) + return; + var i = kv.indexOf('='), k = i < 0 ? kv : kv.slice(0, i), v = i < 0 ? '' : kv.slice(i + 1); + k = unescape(k, true); + v = unescape(v, true); + if (k === null || v === null) + return; + (q[k] = q[k] || []).push(v); + }); + return { + get: function (k) { return q[k] ? q[k][0] : ''; }, + all: function (k) { return q[k] || []; }, + has: function (k) { return !!q[k]; } + }; + } + + // url.Parse for scheme://[userinfo@]host[:port][/path][?query][#fragment]; null on error + function parseURL(s) { + var u = { fragment: '', rawQuery: '', path: '', user: null, host: '' }; + // Go: "invalid control character in URL" + if (/[\x00-\x1f\x7f]/.test(s)) + return null; + var h = s.indexOf('#'); + if (h >= 0) { + u.fragment = unescape(s.slice(h + 1), false); + if (u.fragment === null) + return null; + s = s.slice(0, h); + } + var q = s.indexOf('?'); + if (q >= 0) { + u.rawQuery = s.slice(q + 1); + s = s.slice(0, q); + } + var m = s.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/(.*)$/); + if (!m) + return null; + u.scheme = m[1].toLowerCase(); + var rest = m[2], slash = rest.indexOf('/'); + var auth = slash < 0 ? rest : rest.slice(0, slash); + u.path = slash < 0 ? '' : rest.slice(slash); + var at = auth.lastIndexOf('@'); + if (at >= 0) { + var ui = auth.slice(0, at), c = ui.indexOf(':'); + // Go's validUserinfo + if (!/^[A-Za-z0-9\-._:~!$&'()*+,;=%@]*$/.test(ui)) + return null; + var name = unescape(c < 0 ? ui : ui.slice(0, c), false); + var pass = c < 0 ? null : unescape(ui.slice(c + 1), false); + if (name === null || (c >= 0 && pass === null)) + return null; + u.user = { username: name, password: pass }; + auth = auth.slice(at + 1); + } + // Go's host check: ASCII only letters, digits and -_.~!$&'()*+,;=:[]<>"% + if (/[\x00-\x7f]/.test(auth) && !/^(?:[A-Za-z0-9\-_.~!$&'()*+,;=:\[\]<>"%]|[^\x00-\x7f])*$/.test(auth)) + return null; + // host[:port] or [v6][:port]; the port must be digits + var hm = auth.match(/^(\[[^\]]*\]|[^:]*)(?::(.*))?$/); + if (!hm || (hm[2] !== undefined && !/^[0-9]*$/.test(hm[2]))) + return null; + if (auth.indexOf(':') >= 0 && auth.charAt(0) != '[' && auth.indexOf(':') != auth.lastIndexOf(':')) + return null; + u.host = unescape(auth, false); + if (u.host === null) + return null; + u.hostname = hm[1].replace(/^\[|\]$/g, ''); + u.port = hm[2] || ''; + u.query = parseQuery(u.rawQuery); + u.userString = function () { + if (!u.user) + return ''; + return escapeUser(u.user.username) + (u.user.password === null ? '' : ':' + escapeUser(u.user.password)); + }; + return u; + } + + // strconv.ParseBool, error -> false + function parseBool(s) { + return /^(1|t|T|TRUE|true|True)$/.test(s); + } + + function splitList(s) { + return s.split(','); + } + + // shadowsocks methods mihomo accepts (stand-in for VerifyMethod) + var SS_METHODS = /^(none|plain|dummy|rc4-md5|aes-(128|192|256)-(gcm|cfb|ctr)|chacha20(-ietf)?(-poly1305)?|xchacha20(-ietf-poly1305)?|aes-(128|256)-ccm|2022-blake3-(aes-128-gcm|aes-256-gcm|chacha20-poly1305)|aegis-(128l|256)|lea-(128|192|256)-gcm|rabbit128-poly1305)$/; + + function uniqueName(names, name) { + if (Object.prototype.hasOwnProperty.call(names, name)) { + names[name]++; + var i = names[name]; + return name + '-' + (i < 10 ? '0' + i : i); + } + names[name] = 0; + return name; + } + + function handleVShareLink(names, url, scheme, proxy) { + var query = url.query; + proxy.name = uniqueName(names, url.fragment); + if (url.hostname === '') + return 'url.Hostname() is empty'; + if (url.port === '') + return 'url.Port() is empty'; + proxy.type = scheme; + proxy.server = url.hostname; + proxy.port = url.port; + proxy.uuid = url.user ? url.user.username : ''; + proxy.udp = true; + var tls = query.get('security').toLowerCase(); + if (/tls$/.test(tls) || tls == 'reality') { + proxy.tls = true; + proxy['client-fingerprint'] = query.get('fp') || 'chrome'; + if (query.get('alpn')) + proxy.alpn = splitList(query.get('alpn')); + if (query.get('pcs')) + proxy.fingerprint = query.get('pcs'); + } + if (query.get('sni')) + proxy.servername = query.get('sni'); + if (query.get('pbk')) { + var reality = { 'public-key': query.get('pbk'), 'short-id': query.get('sid') }; + var ml = query.get('support-x25519mlkem768'); + if (ml && /^(1|t|T|TRUE|true|True|0|f|F|FALSE|false|False)$/.test(ml)) + reality['support-x25519mlkem768'] = parseBool(ml); + proxy['reality-opts'] = reality; + } + + switch (query.get('packetEncoding')) { + case 'none': + break; + case 'packet': + proxy['packet-addr'] = true; + break; + default: + proxy.xudp = true; + } + + var network = query.get('type').toLowerCase() || 'tcp'; + var fakeType = query.get('headerType').toLowerCase(); + if (network == 'tcp' && fakeType == 'http') + network = 'http'; + else if (network == 'http') + network = 'h2'; + proxy.network = network; + switch (network) { + case 'http': + var headers = {}, httpOpts = { path: [ '/' ] }; + if (query.get('host')) + headers.Host = [ query.get('host') ]; + if (query.get('method')) + httpOpts.method = query.get('method'); + if (query.get('path')) + httpOpts.path = [ query.get('path') ]; + httpOpts.headers = headers; + proxy['http-opts'] = httpOpts; + break; + case 'h2': + var h2 = { path: query.get('path') || '/' }; + if (query.get('host')) + h2.host = [ query.get('host') ]; + proxy['h2-opts'] = h2; + break; + case 'ws': + case 'httpupgrade': + var ws = { path: query.get('path'), headers: { 'User-Agent': USER_AGENT, Host: query.get('host') } }; + if (query.get('ed')) { + if (!/^[+-]?[0-9]+$/.test(query.get('ed'))) + return 'bad WebSocket max early data size'; + if (network == 'ws') { + ws['max-early-data'] = parseInt(query.get('ed'), 10); + ws['early-data-header-name'] = 'Sec-WebSocket-Protocol'; + } else { + ws['v2ray-http-upgrade-fast-open'] = true; + } + } + if (query.get('eh')) + ws['early-data-header-name'] = query.get('eh'); + proxy['ws-opts'] = ws; + break; + case 'grpc': + proxy['grpc-opts'] = { 'grpc-service-name': query.get('serviceName') }; + break; + case 'xhttp': + var x = {}; + if (query.get('path')) + x.path = query.get('path'); + if (query.get('host')) + x.host = query.get('host'); + if (query.get('mode')) + x.mode = query.get('mode'); + if (query.get('extra')) { + var extra = null; + try { extra = JSON.parse(query.get('extra')); } catch (e) {} + if (extra && typeof extra == 'object' && !Array.isArray(extra)) + parseXHTTPExtra(extra, x); + } + proxy['xhttp-opts'] = x; + break; + } + return null; + } + + var isStr = function (v) { return typeof v == 'string'; }; + var isNum = function (v) { return typeof v == 'number'; }; + var isObj = function (v) { return v && typeof v == 'object' && !Array.isArray(v); }; + var trunc = function (v) { return v < 0 ? Math.ceil(v) : Math.floor(v); }; + + function parseXHTTPExtra(extra, opts) { + var xmuxToReuse = function (xmux) { + var reuse = {}; + var set = function (src, dst) { + var v = xmux[src]; + if (isStr(v) && v !== '') + reuse[dst] = v; + else if (isNum(v)) + reuse[dst] = String(trunc(v)); + }; + set('maxConnections', 'max-connections'); + set('maxConcurrency', 'max-concurrency'); + set('cMaxReuseTimes', 'c-max-reuse-times'); + set('hMaxRequestTimes', 'h-max-request-times'); + set('hMaxReusableSecs', 'h-max-reusable-secs'); + if (isNum(xmux.hKeepAlivePeriod)) + reuse['h-keep-alive-period'] = trunc(xmux.hKeepAlivePeriod); + return reuse; + }; + var str = function (src, dst) { + if (isStr(extra[src]) && extra[src] !== '') { + opts[dst] = extra[src]; + return true; + } + return false; + }; + var int = function (src, dst) { + if (isNum(extra[src])) + opts[dst] = trunc(extra[src]); + }; + + if (isObj(extra.headers) && Object.keys(extra.headers).length) + opts.headers = extra.headers; + if (extra.noGRPCHeader === true) + opts['no-grpc-header'] = true; + str('xPaddingBytes', 'x-padding-bytes'); + if (typeof extra.xPaddingObfsMode == 'boolean') + opts['x-padding-obfs-mode'] = extra.xPaddingObfsMode; + str('xPaddingKey', 'x-padding-key'); + str('xPaddingHeader', 'x-padding-header'); + str('xPaddingPlacement', 'x-padding-placement'); + str('xPaddingMethod', 'x-padding-method'); + str('uplinkHTTPMethod', 'uplink-http-method'); + str('sessionIDPlacement', 'session-placement') || str('sessionPlacement', 'session-placement'); + str('sessionIDKey', 'session-key') || str('sessionKey', 'session-key'); + str('sessionIDTable', 'session-table'); + if (!str('sessionIDLength', 'session-length') && isNum(extra.sessionIDLength)) + opts['session-length'] = String(trunc(extra.sessionIDLength)); + str('seqPlacement', 'seq-placement'); + str('seqKey', 'seq-key'); + str('uplinkDataPlacement', 'uplink-data-placement'); + str('uplinkDataKey', 'uplink-data-key'); + int('uplinkChunkSize', 'uplink-chunk-size'); + int('scMaxEachPostBytes', 'sc-max-each-post-bytes'); + int('scMinPostsIntervalMs', 'sc-min-posts-interval-ms'); + + if (isObj(extra.xmux) && Object.keys(extra.xmux).length) { + var reuse = xmuxToReuse(extra.xmux); + if (Object.keys(reuse).length) + opts['reuse-settings'] = reuse; + } + + if (isObj(extra.downloadSettings)) { + var dsAny = extra.downloadSettings, ds = {}; + if (isStr(dsAny.address) && dsAny.address !== '') + ds.server = dsAny.address; + if (isNum(dsAny.port)) + ds.port = trunc(dsAny.port); + var sec = isStr(dsAny.security) ? dsAny.security.toLowerCase() : ''; + if (sec == 'tls' || sec == 'reality') { + ds.tls = true; + var t = dsAny.tlsSettings; + if (isObj(t)) { + if (isStr(t.serverName) && t.serverName !== '') + ds.servername = t.serverName; + if (isStr(t.fingerprint) && t.fingerprint !== '') + ds['client-fingerprint'] = t.fingerprint; + if (Array.isArray(t.alpn) && t.alpn.length) { + var alpn = t.alpn.filter(isStr); + if (alpn.length) + ds.alpn = alpn; + } + if (t.allowInsecure === true) + ds['skip-cert-verify'] = true; + } + if (sec == 'reality' && isObj(dsAny.realitySettings)) { + var r = dsAny.realitySettings, ro = {}; + if (isStr(r.publicKey) && r.publicKey !== '') + ro['public-key'] = r.publicKey; + if (isStr(r.shortId) && r.shortId !== '') + ro['short-id'] = r.shortId; + if (Object.keys(ro).length) + ds['reality-opts'] = ro; + } + } + var xs = dsAny.xhttpSettings; + if (isObj(xs)) { + if (isStr(xs.path) && xs.path !== '') + ds.path = xs.path; + if (isStr(xs.host) && xs.host !== '') + ds.host = xs.host; + if (isObj(xs.headers) && Object.keys(xs.headers).length) + ds.headers = xs.headers; + if (isObj(xs.extra) && isObj(xs.extra.xmux) && Object.keys(xs.extra.xmux).length) { + var dr = xmuxToReuse(xs.extra.xmux); + if (Object.keys(dr).length) + ds['reuse-settings'] = dr; + } + } + if (Object.keys(ds).length) + opts['download-settings'] = ds; + } + } + + function buildRealmOpts(serverURL, token, realmID, stun) { + var o = { enable: true, 'server-url': serverURL }; + if (token) + o.token = token; + if (realmID) + o['realm-id'] = realmID; + if (stun.length) + o['stun-servers'] = stun; + return o; + } + + function splitHysteria2Ports(line) { + var i = line.indexOf('://'); + if (i < 0) + return [ line, '' ]; + var head = line.slice(0, i + 3), rest = line.slice(i + 3), auth = rest, tail = ''; + var j = rest.search(/[\/?#]/); + if (j >= 0) { + auth = rest.slice(0, j); + tail = rest.slice(j); + } + var userinfo = '', at = auth.lastIndexOf('@'); + if (at >= 0) { + userinfo = auth.slice(0, at + 1); + auth = auth.slice(at + 1); + } + if (auth.indexOf(']') >= 0) + return [ line, '' ]; + var colon = auth.lastIndexOf(':'); + if (colon < 0) + return [ line, '' ]; + var host = auth.slice(0, colon), ports = auth.slice(colon + 1); + if (!/[,-]/.test(ports)) + return [ line, '' ]; + var first = ports.slice(0, ports.search(/[,-]/)); + if (first === '') + return [ line, '' ]; + return [ head + userinfo + host + ':' + first + tail, ports ]; + } + + // ConvertsV2Ray: share links (or a base64 subscription of them) -> proxy objects + function parseLinks(text) { + var data = decodeBase64(String(text)); + var proxies = [], names = {}; + + data.split('\n').forEach(function (raw) { + var line = raw.replace(/[ \r]+$/, ''); + if (!line) + return; + var cut = line.indexOf('://'); + if (cut < 0) + return; + var scheme = line.slice(0, cut).toLowerCase(), body = line.slice(cut + 3); + var u, q, p; + + switch (scheme) { + case 'hysteria': + if (!(u = parseURL(line))) + return; + q = u.query; + p = { name: uniqueName(names, u.fragment), type: scheme, server: u.hostname, port: u.port, + sni: q.get('peer'), obfs: q.get('obfs') }; + if (q.get('alpn')) + p.alpn = splitList(q.get('alpn')); + p.auth_str = q.get('auth'); + p.protocol = q.get('protocol'); + p.down = q.get('down') || q.get('downmbps'); + p.up = q.get('up') || q.get('upmbps'); + p['skip-cert-verify'] = parseBool(q.get('insecure')); + proxies.push(p); + return; + + case 'hysteria2': + case 'hy2': + case 'hysteria2+realm': + case 'hy2+realm': + var realm = /\+realm$/.test(scheme), hop = splitHysteria2Ports(line); + if (!(u = parseURL(hop[0]))) + return; + q = u.query; + p = { name: uniqueName(names, u.fragment), type: 'hysteria2', server: u.hostname, port: u.port || '443' }; + if (hop[1]) + p.ports = hop[1]; + p.obfs = q.get('obfs'); + p['obfs-password'] = q.get('obfs-password'); + p.sni = q.get('sni'); + p['skip-cert-verify'] = parseBool(q.get('insecure')); + if (q.get('alpn')) + p.alpn = splitList(q.get('alpn')); + p.fingerprint = q.get('pinSHA256'); + p.down = q.get('down'); + p.up = q.get('up'); + if (realm) { + var token = unescape(u.userString(), false) || ''; + var realmID = unescape(u.path.replace(/^\//, ''), false) || ''; + p['realm-opts'] = buildRealmOpts('https://' + u.host, token, realmID, q.all('stun')); + if (q.get('auth')) + p.password = q.get('auth'); + } else if (u.userString()) { + p.password = u.userString(); + } + proxies.push(p); + return; + + case 'tuic': + if (!(u = parseURL(line))) + return; + q = u.query; + p = { name: uniqueName(names, u.fragment), type: scheme, server: u.hostname, port: u.port, udp: true }; + if (u.user && u.user.password !== null) { + p.uuid = u.user.username; + p.password = u.user.password; + } else { + p.token = u.user ? u.user.username : ''; + } + if (q.get('congestion_control')) + p['congestion-controller'] = q.get('congestion_control'); + if (q.get('alpn')) + p.alpn = splitList(q.get('alpn')); + if (q.get('sni')) + p.sni = q.get('sni'); + if (q.get('disable_sni') == '1') + p['disable-sni'] = true; + if (q.get('udp_relay_mode')) + p['udp-relay-mode'] = q.get('udp_relay_mode'); + proxies.push(p); + return; + + case 'trojan': + if (!(u = parseURL(line))) + return; + q = u.query; + p = { name: uniqueName(names, u.fragment), type: scheme, server: u.hostname, port: u.port, + password: u.user ? u.user.username : '', udp: true, + 'skip-cert-verify': parseBool(q.get('allowInsecure')) }; + if (q.get('sni')) + p.sni = q.get('sni'); + if (q.get('alpn')) + p.alpn = splitList(q.get('alpn')); + var net = q.get('type').toLowerCase(); + if (net) + p.network = net; + if (net == 'ws') + p['ws-opts'] = { path: q.get('path'), headers: { 'User-Agent': USER_AGENT } }; + else if (net == 'grpc') + p['grpc-opts'] = { 'grpc-service-name': q.get('serviceName') }; + p['client-fingerprint'] = q.get('fp') || 'chrome'; + if (q.get('pcs')) + p.fingerprint = q.get('pcs'); + proxies.push(p); + return; + + case 'vless': + if (!(u = parseURL(line))) + return; + var dh = tryDecodeBase64(u.host); + if (dh !== null) { + // Go re-reads hostname/port from the decoded host + u.host = dh; + var dm = dh.match(/^(\[[^\]]*\]|[^:]*)(?::(.*))?$/); + u.hostname = dm ? dm[1].replace(/^\[|\]$/g, '') : dh; + u.port = dm && dm[2] && /^[0-9]+$/.test(dm[2]) ? dm[2] : ''; + } + p = {}; + if (handleVShareLink(names, u, scheme, p)) + return; + if (u.query.get('flow')) + p.flow = u.query.get('flow').toLowerCase(); + if (u.query.get('encryption')) + p.encryption = u.query.get('encryption'); + proxies.push(p); + return; + + case 'vmess': + var dc = tryDecodeBase64(body); + if (dc === null) { + // Xray VMessAEAD share link + if (!(u = parseURL(line))) + return; + p = {}; + if (handleVShareLink(names, u, scheme, p)) + return; + p.alterId = 0; + p.cipher = u.query.get('encryption') || 'auto'; + proxies.push(p); + return; + } + var v; + try { v = JSON.parse(dc); } catch (e) { return; } + if (!isObj(v) || !isStr(v.ps)) + return; + p = { name: uniqueName(names, v.ps), type: scheme, server: v.add, port: v.port, uuid: v.id, + alterId: 'aid' in v ? v.aid : 0, udp: true, xudp: true, tls: false, 'skip-cert-verify': false, + cipher: isStr(v.scy) && v.scy !== '' ? v.scy : 'auto' }; + if (isStr(v.sni) && v.sni !== '') + p.servername = v.sni; + var network = ''; + if (isStr(v.net)) { + network = v.net.toLowerCase(); + if (v.type === 'http') + network = 'http'; + else if (network == 'http') + network = 'h2'; + p.network = network; + } + if (isStr(v.tls)) { + if (/tls$/.test(v.tls.toLowerCase())) + p.tls = true; + if (isStr(v.alpn)) + p.alpn = splitList(v.alpn); + } + var host = isStr(v.host) && v.host !== '' ? v.host : ''; + var path = isStr(v.path) && v.path !== '' ? v.path : ''; + switch (network) { + case 'http': + p['http-opts'] = { path: [ path || '/' ], headers: host ? { Host: [ host ] } : {} }; + break; + case 'h2': + p['h2-opts'] = { path: path || '/' }; + if (host) + p['h2-opts'].host = [ host ]; + break; + case 'ws': + case 'httpupgrade': + var wo = { path: '/' }, hd = {}; + if (host) + hd.Host = host; + if (path) { + var pu = parseURL('x://h' + (path.charAt(0) == '/' ? '' : '/') + path); + var pq = pu && pu.rawQuery !== '' ? pu.query : null; + if (pu && pq && pq.get('ed') && /^[+-]?[0-9]+$/.test(pq.get('ed'))) { + if (network == 'ws') { + wo['max-early-data'] = parseInt(pq.get('ed'), 10); + wo['early-data-header-name'] = 'Sec-WebSocket-Protocol'; + } else { + wo['v2ray-http-upgrade-fast-open'] = true; + } + path = vmessPathWithoutEd(path); + } + if (pu && pq && pq.get('eh')) + wo['early-data-header-name'] = pq.get('eh'); + wo.path = path; + } + wo.headers = hd; + p['ws-opts'] = wo; + break; + case 'grpc': + p['grpc-opts'] = { 'grpc-service-name': v.path }; + break; + } + proxies.push(p); + return; + + case 'ss': + if (!(u = parseURL(line))) + return; + var ssName = uniqueName(names, u.fragment); + if (u.port === '') { + var hb = b64(u.host, STD, false); + if (hb === null || !(u = parseURL('ss://' + utf8(hb)))) + return; + } + var cipherRaw = u.user ? u.user.username : '', cipher = cipherRaw, password; + if (u.user && u.user.password !== null) { + password = u.user.password; + } else { + var bb = b64(cipherRaw, URLSAFE, false) || b64(cipherRaw, STD, true) || []; + var cp = utf8(bb), ci = cp.indexOf(':'); + if (ci < 0) + return; + cipher = cp.slice(0, ci); + password = cp.slice(ci + 1); + if (!SS_METHODS.test(cipher)) { + cp = utf8(b64(cipherRaw, STD, false) || []); + ci = cp.indexOf(':'); + cipher = ci < 0 ? cp : cp.slice(0, ci); + password = ci < 0 ? '' : cp.slice(ci + 1); + } + } + q = u.query; + p = { name: ssName, type: scheme, server: u.hostname, port: u.port, cipher: cipher, password: password, udp: true }; + if (q.get('udp-over-tcp') == 'true' || q.get('uot') == '1') + p['udp-over-tcp'] = true; + var plugin = q.get('plugin'); + if (plugin.indexOf(';') >= 0) { + var pi = parseQuery('pluginName=' + plugin.replace(/;/g, '&')); + var pn = pi.get('pluginName'); + if (pn.indexOf('obfs') >= 0) { + p.plugin = 'obfs'; + p['plugin-opts'] = { mode: pi.get('obfs'), host: pi.get('obfs-host') }; + } else if (pn.indexOf('v2ray-plugin') >= 0) { + p.plugin = 'v2ray-plugin'; + p['plugin-opts'] = { mode: pi.get('mode') || pi.get('obfs'), host: pi.get('host') || pi.get('obfs-host'), + path: pi.get('path'), tls: plugin.indexOf('tls') >= 0 }; + } + } + proxies.push(p); + return; + + case 'ssr': + var sd = tryDecodeBase64Str(body); + if (sd === null) + return; + var qi = sd.indexOf('/?'); + if (qi < 0) + return; + var before = sd.slice(0, qi).split(':'); + if (before.length != 6) + return; + var sq = parseQuery(urlSafe(sd.slice(qi + 2))); + p = { name: uniqueName(names, decodeUrlSafe(sq.get('remarks'))), type: scheme, server: before[0], + port: before[1], cipher: before[3], password: decodeUrlSafe(urlSafe(before[5])), + obfs: before[4], protocol: before[2], udp: true }; + if (decodeUrlSafe(sq.get('obfsparam'))) + p['obfs-param'] = decodeUrlSafe(sq.get('obfsparam')); + if (decodeUrlSafe(sq.get('protoparam'))) + p['protocol-param'] = decodeUrlSafe(sq.get('protoparam')); + proxies.push(p); + return; + + case 'socks': + case 'socks5': + case 'socks5h': + case 'http': + case 'https': + if (!(u = parseURL(line)) || !u.hostname || !u.port) + return; + var user = '', pw = '', enc = u.userString(); + if (enc) { + var parts = decodeBase64(enc).split(':'); + user = parts[0]; + if (parts.length == 2) + pw = parts[1]; + } + p = { name: uniqueName(names, u.fragment || u.hostname + ':' + u.port), + type: /^socks/.test(scheme) ? 'socks5' : 'http', server: u.hostname, port: u.port, + username: user, password: pw, 'skip-cert-verify': true }; + if (scheme == 'https') + p.tls = true; + proxies.push(p); + return; + + case 'anytls': + if (!(u = parseURL(line)) || !u.hostname || !u.port) + return; + var au = u.user ? u.user.username : ''; + var ap = u.user && u.user.password !== null ? u.user.password : au; + q = u.query; + proxies.push({ name: uniqueName(names, u.fragment || u.hostname + ':' + u.port), type: 'anytls', + server: u.hostname, port: u.port, username: au, password: ap, sni: q.get('sni'), + fingerprint: q.get('hpkp'), 'skip-cert-verify': q.get('insecure') == '1', udp: true }); + return; + + case 'mierus': + if (!(u = parseURL(line)) || !u.hostname) + return; + q = u.query; + var base = u.fragment || q.get('profile') || u.hostname; + var ports = q.all('port'), protos = q.all('protocol'); + if (!ports.length || ports.length != protos.length) + return; + ports.forEach(function (port, i) { + var m = { name: uniqueName(names, base + ':' + port + '/' + protos[i]), type: 'mieru', + server: u.hostname, transport: protos[i], udp: true, + username: u.user ? u.user.username : '', password: u.user && u.user.password !== null ? u.user.password : '' }; + if (port.indexOf('-') >= 0) + m['port-range'] = port; + else if (/^[+-]?[0-9]+$/.test(port)) + m.port = parseInt(port, 10); + else + return; + if (q.get('multiplexing')) + m.multiplexing = q.get('multiplexing'); + if (q.get('handshake-mode')) + m['handshake-mode'] = q.get('handshake-mode'); + if (q.get('traffic-pattern')) + m['traffic-pattern'] = q.get('traffic-pattern'); + proxies.push(m); + }); + return; + } + }); + return proxies; + } + + // vmess ws path: the "ed" parameter dropped, the rest re-encoded like Go's + // query.Encode() (keys sorted) + function vmessPathWithoutEd(path) { + var qi = path.indexOf('?'); + var base = path.slice(0, qi), raw = path.slice(qi + 1), h = raw.indexOf('#'), frag = ''; + if (h >= 0) { + frag = raw.slice(h); + raw = raw.slice(0, h); + } + var pairs = []; + raw.split('&').forEach(function (kv) { + if (!kv || kv.indexOf(';') >= 0) + return; + var i = kv.indexOf('='), k = unescape(i < 0 ? kv : kv.slice(0, i), true), v = unescape(i < 0 ? '' : kv.slice(i + 1), true); + if (k !== null && v !== null && k != 'ed') + pairs.push([ k, v ]); + }); + var esc = function (s) { + return encodeURIComponent(s).replace(/%20/g, '+').replace(/[!'()*]/g, function (c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase(); + }); + }; + pairs.sort(function (a, b) { return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0; }); + var enc = pairs.map(function (kv) { return esc(kv[0]) + '=' + esc(kv[1]); }).join('&'); + return base + (enc ? '?' + enc : '') + frag; + } + + // --- YAML: the subset proxy configs use ---------------------------------------- + // Block mappings and sequences, flow {..} and [..] (also over several lines), + // plain / 'single' / "double" scalars, comments, | and > blocks. Scalars resolve as + // go-yaml v3 does for the common cases (bool, null, int, float, else string). + // No anchors, aliases, tags or multiple documents. + + function yamlError(msg, line) { + var e = new Error((line ? 'строка ' + line + ': ' : '') + msg); + e.yaml = true; + return e; + } + + function resolvePlain(s) { + if (/^(null|Null|NULL|~|)$/.test(s)) + return null; + if (/^(true|True|TRUE)$/.test(s)) + return true; + if (/^(false|False|FALSE)$/.test(s)) + return false; + if (/^[-+]?[0-9]+$/.test(s) && Math.abs(Number(s)) <= Number.MAX_SAFE_INTEGER) + return parseInt(s, 10); + if (/^0x[0-9a-fA-F]+$/.test(s)) + return parseInt(s.slice(2), 16); + if (/^0o[0-7]+$/.test(s)) + return parseInt(s.slice(2), 8); + if (/^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$/.test(s)) + return parseFloat(s); + if (/^[-+]?\.(inf|Inf|INF)$/.test(s)) + return s.charAt(0) == '-' ? -Infinity : Infinity; + if (/^\.(nan|NaN|NAN)$/.test(s)) + return NaN; + return s; + } + + var DQ_ESC = { '0': '\0', 'a': '\x07', 'b': '\b', 't': '\t', '\t': '\t', 'n': '\n', 'v': '\x0b', 'f': '\f', + 'r': '\r', 'e': '\x1b', ' ': ' ', '"': '"', '/': '/', '\\': '\\', 'N': '\x85', '_': '\xa0', + 'L': '\u2028', 'P': '\u2029' }; + + // a scanner over one (possibly joined) text: quoted scalars and flow collections + function Scanner(text, line) { + this.s = text; + this.i = 0; + this.line = line; + } + Scanner.prototype = { + ws: function () { + while (this.i < this.s.length && /[ \t\n]/.test(this.s.charAt(this.i))) + this.i++; + // a comment runs to the end of its line + if (this.s.charAt(this.i) == '#' && (this.i == 0 || /[ \t\n]/.test(this.s.charAt(this.i - 1)))) { + while (this.i < this.s.length && this.s.charAt(this.i) != '\n') + this.i++; + this.ws(); + } + }, + peek: function () { return this.s.charAt(this.i); }, + fail: function (msg) { throw yamlError(msg, this.line); }, + quoted: function () { + // escapes go in as placeholders: line folding applies to the source breaks only + var q = this.s.charAt(this.i++), out = '', esc = []; + var put = function (c) { + out += String.fromCharCode(0xe000 + esc.length); + esc.push(c); + }; + var done = function () { + return foldQuoted(out).replace(/[\ue000-\uf8ff]/g, function (c) { return esc[c.charCodeAt(0) - 0xe000]; }); + }; + for (;;) { + if (this.i >= this.s.length) + this.fail('незакрытая кавычка'); + var c = this.s.charAt(this.i++); + if (q == "'") { + if (c == "'") { + if (this.s.charAt(this.i) == "'") { + put("'"); + this.i++; + continue; + } + return done(); + } + out += c; + continue; + } + if (c == '"') + return done(); + if (c != '\\') { + out += c; + continue; + } + var e = this.s.charAt(this.i++), n; + if (e == '\n') { + // escaped line break: joined without a space + while (/[ \t]/.test(this.s.charAt(this.i))) + this.i++; + out += '\u0001'; + continue; + } + if (DQ_ESC.hasOwnProperty(e)) { + put(DQ_ESC[e]); + continue; + } + n = { x: 2, u: 4, U: 8 }[e]; + if (!n || !/^[0-9a-fA-F]+$/.test(this.s.substr(this.i, n)) || this.s.substr(this.i, n).length != n) + this.fail('неверное экранирование \\' + e); + put(String.fromCodePoint(parseInt(this.s.substr(this.i, n), 16))); + this.i += n; + } + }, + // a plain scalar in flow context: up to , ] } or ": " + plain: function () { + var start = this.i; + while (this.i < this.s.length) { + var c = this.s.charAt(this.i); + if (c == ',' || c == ']' || c == '}' || c == '\n') + break; + // ":" ends a key (and a value) only before a space, , ] } or the end + if (c == ':' && (this.i + 1 == this.s.length || /[ ,\]}\n]/.test(this.s.charAt(this.i + 1)))) + break; + if (c == '#' && /[ \t]/.test(this.s.charAt(this.i - 1))) + break; + this.i++; + } + return this.s.slice(start, this.i).trim(); + }, + node: function () { + this.ws(); + var c = this.peek(); + if (c == '{') + return this.map(); + if (c == '[') + return this.seq(); + if (c == '"' || c == "'") + return this.quoted(); + if (c == '&' || c == '*' || c == '!') + this.fail('якоря, ссылки и теги не поддерживаются'); + return resolvePlain(this.plain()); + }, + key: function () { + this.ws(); + var c = this.peek(); + if (c == '"' || c == "'") + return this.quoted(); + return this.plain(); + }, + map: function () { + var o = {}; + this.i++; + for (;;) { + this.ws(); + if (this.peek() == '}') { + this.i++; + return o; + } + var k = this.key(); + this.ws(); + var v = null; + if (this.peek() == ':') { + this.i++; + this.ws(); + if (this.peek() != ',' && this.peek() != '}') + v = this.node(); + } + o[String(k)] = v; + this.ws(); + if (this.peek() == ',') + this.i++; + else if (this.peek() != '}') + this.fail('ожидалась , или }'); + } + }, + seq: function () { + var a = []; + this.i++; + for (;;) { + this.ws(); + if (this.peek() == ']') { + this.i++; + return a; + } + a.push(this.node()); + this.ws(); + if (this.peek() == ',') + this.i++; + else if (this.peek() != ']') + this.fail('ожидалась , или ]'); + } + } + }; + + // line folding of a quoted scalar over several lines: a break -> space, empty lines -> \n + function foldQuoted(s) { + if (s.indexOf('\n') < 0) + return s.replace(/\u0001/g, ''); + var parts = s.split('\n'), out = parts[0].replace(/[ \t]+$/, ''); + for (var i = 1; i < parts.length; i++) { + var p = parts[i].replace(/^[ \t]+/, ''); + if (i < parts.length - 1) + p = p.replace(/[ \t]+$/, ''); + if (p === '' && i < parts.length - 1) + out += '\n'; + else + out += (/\n$/.test(out) || /\u0001$/.test(out) ? '' : ' ') + p; + } + return out.replace(/\u0001/g, ''); + } + + function yamlLoad(text) { + var src = String(text).replace(/\r\n?/g, '\n').replace(/^\ufeff/, '').split('\n'); + var lines = []; + src.forEach(function (raw, n) { + if (/^\t/.test(raw)) + throw yamlError('табуляция в отступе', n + 1); + var t = raw.replace(/^ +/, ''); + if (t === '' || t.charAt(0) == '#' || /^(---|\.\.\.)(\s|$)/.test(t)) + return lines.push({ indent: -1, text: '', n: n + 1, raw: raw }); + lines.push({ indent: raw.length - t.length, text: t.replace(/[ \t]+$/, ''), n: n + 1, raw: raw }); + }); + var pos = 0; + var skip = function () { + while (pos < lines.length && lines[pos].indent < 0) + pos++; + }; + var cur = function () { + skip(); + return pos < lines.length ? lines[pos] : null; + }; + + // "key: rest" of a block mapping line -> [key, rest] or null + var splitKey = function (t, n) { + var key, rest; + if (t.charAt(0) == '"' || t.charAt(0) == "'") { + var sc = new Scanner(t, n); + key = sc.quoted(); + rest = t.slice(sc.i); + if (!/^:( |$)/.test(rest)) + return null; + return [ key, rest.slice(1).replace(/^ +/, '') ]; + } + if (/^[\[{&*!|>%@`]/.test(t)) + return null; + var m = t.match(/^([^#]*?)\s*:(?: +(.*)|$)/); + if (!m || / #/.test(m[1])) + return null; + return [ m[1], m[2] === undefined ? '' : m[2] ]; + }; + + // an inline value (after "key: " or "- "): flow, quoted, block scalar or plain; + // a flow / quoted value may continue on the following lines + var inline = function (rest, line, parentIndent) { + var c = rest.charAt(0); + if (c == '|' || c == '>') { + var m = rest.match(/^([|>])([+-]?)\s*(#.*)?$/); + if (!m) + throw yamlError('неподдерживаемый блочный скаляр', line.n); + return blockScalar(m[1], m[2], parentIndent); + } + if (c == '{' || c == '[' || c == '"' || c == "'") { + var text = rest, sc; + for (;;) { + sc = new Scanner(text, line.n); + try { + var v = sc.node(); + sc.ws(); + if (sc.i < sc.s.length) + throw yamlError('лишнее после значения: ' + sc.s.slice(sc.i, sc.i + 20), line.n); + return v; + } catch (e) { + // unbalanced: take the next line in + var nx = pos < lines.length ? lines[pos] : null; + if (!nx || !/незакрыт|ожидалась/.test(e.message) || sc.i < sc.s.length) + throw e; + text += '\n' + (nx.indent < 0 ? '' : nx.raw); + pos++; + } + } + } + if (c == '&' || c == '*' || c == '!') + throw yamlError('якоря, ссылки и теги не поддерживаются', line.n); + var plain = rest.replace(/\s+#.*$/, ''); + // a plain scalar may continue on more indented lines + for (;;) { + var nl = cur(); + if (!nl || nl.indent <= parentIndent || /^- |^-$/.test(nl.text) || splitKey(nl.text, nl.n)) + break; + plain += ' ' + nl.text.replace(/\s+#.*$/, ''); + pos++; + } + return resolvePlain(plain); + }; + + var blockScalar = function (style, chomp, parentIndent) { + var body = [], ind = -1; + while (pos < lines.length) { + var l = lines[pos], lead = l.raw.length - l.raw.replace(/^ +/, '').length; + if (l.raw.trim() !== '' && lead <= parentIndent) + break; + if (l.raw.trim() !== '' && ind < 0) + ind = lead; + body.push(l.raw); + pos++; + } + body = body.map(function (r) { return ind < 0 ? '' : r.slice(ind); }); + var trail = 0; + while (body.length && body[body.length - 1].trim() === '') { + body.pop(); + trail++; + } + var s; + if (style == '|') + s = body.join('\n'); + else { + // folding: a break between two plain lines -> space, n empty lines -> n + // breaks; around more indented lines the breaks stay + s = ''; + var empty = 0, prev = null; + body.forEach(function (r) { + if (r === '') { + empty++; + return; + } + if (prev !== null) { + var keep = /^\s/.test(r) || /^\s/.test(prev); + s += empty ? new Array(empty + (keep ? 2 : 1)).join('\n') : keep ? '\n' : ' '; + } + s += r; + prev = r; + empty = 0; + }); + } + if (chomp == '-' || !body.length) + return s; + return s + (chomp == '+' ? new Array(trail + 2).join('\n') : '\n'); + }; + + var node = function (indent) { + var l = cur(); + if (!l || l.indent < indent) + return null; + if (/^-( |$)/.test(l.text)) + return seq(l.indent); + if (splitKey(l.text, l.n)) + return map(l.indent); + pos++; + return inline(l.text, l, l.indent - 1); + }; + + var seq = function (indent) { + var a = []; + for (;;) { + var l = cur(); + if (!l || l.indent != indent || !/^-( |$)/.test(l.text)) + return a; + var rest = l.text.replace(/^- */, ''); + if (rest === '') { + pos++; + var nx = cur(); + a.push(nx && nx.indent > indent ? node(nx.indent) : null); + continue; + } + // "- key: v" / "- - x": the rest is a node at the column after "- " + var col = indent + (l.text.length - rest.length); + if (/^-( |$)/.test(rest) || splitKey(rest, l.n)) { + lines[pos] = { indent: col, text: rest, n: l.n, raw: new Array(col + 1).join(' ') + rest }; + a.push(node(col)); + continue; + } + pos++; + a.push(inline(rest, l, indent)); + } + }; + + var map = function (indent) { + var o = {}; + for (;;) { + var l = cur(); + if (!l || l.indent != indent) + return o; + var kv = splitKey(l.text, l.n); + if (!kv) + throw yamlError('ожидалось «ключ: значение»: ' + l.text.slice(0, 30), l.n); + pos++; + var v; + if (kv[1] === '' || /^#/.test(kv[1])) { + var nx = cur(); + if (nx && nx.indent > indent) + v = node(nx.indent); + else if (nx && nx.indent == indent && /^-( |$)/.test(nx.text)) + v = seq(indent); + else + v = null; + } else { + v = inline(kv[1], l, indent); + } + o[String(kv[0])] = v; + } + }; + + var l0 = cur(); + if (!l0) + return null; + var doc = node(l0.indent); + var extra = cur(); + if (extra) + throw yamlError('не разобрано: ' + extra.text.slice(0, 30), extra.n); + return doc; + } + + // block YAML of a proxy (for editing); strings quoted only where needed + function yamlDump(v, indent) { + indent = indent || ''; + var scalar = function (x) { + if (x === null || x === undefined) + return 'null'; + if (typeof x == 'boolean' || typeof x == 'number') + return String(x); + x = String(x); + if (x === '' || resolvePlain(x) !== x || /^[\s\-?:,\[\]{}#&*!|>'"%@`]|[\s:]$|: | #|[\x00-\x1f"\\]/.test(x)) + return JSON.stringify(x); + return x; + }; + if (Array.isArray(v)) { + if (!v.length) + return '[]'; + return v.map(function (x) { + if (isObj(x) && Object.keys(x).length) + return indent + '- ' + yamlDump(x, indent + ' ').replace(/^\s+/, ''); + return indent + '- ' + (Array.isArray(x) || isObj(x) ? yamlDump(x, indent + ' ').trim() : scalar(x)); + }).join('\n'); + } + if (isObj(v)) { + var keys = Object.keys(v); + if (!keys.length) + return '{}'; + return keys.map(function (k) { + var x = v[k], kk = scalar(k); + if ((Array.isArray(x) && x.length) || (isObj(x) && Object.keys(x).length)) + return indent + kk + ':\n' + yamlDump(x, indent + ' '); + return indent + kk + ': ' + (Array.isArray(x) ? '[]' : isObj(x) ? '{}' : scalar(x)); + }).join('\n'); + } + return indent + scalar(v); + } + + // --- servers of the form --------------------------------------------------------- + + var LINK = /^\s*[A-Za-z][A-Za-z0-9+.-]*:\/\//; + + // pasted text: share links and/or mihomo YAML (a "proxies:" list, a list, one proxy) + // -> { servers: [...], errors: [...] } + function parseText(text) { + var links = [], rest = [], errors = []; + String(text).split(/\r?\n/).forEach(function (l) { + (LINK.test(l) ? links : rest).push(l); + }); + var servers = links.length ? parseLinks(links.join('\n')) : []; + if (links.length && servers.length < links.length) + errors.push('не разобрано ссылок: ' + (links.length - servers.length) + ' из ' + links.length); + var y = rest.join('\n'); + if (y.trim()) { + var doc = null, list = []; + try { + doc = yamlLoad(y); + } catch (e) { + // one base64 subscription blob + var fromB64 = /^[A-Za-z0-9+\/=_\-\s]+$/.test(y.trim()) ? parseLinks(y.trim()) : []; + if (fromB64.length) + servers = servers.concat(fromB64); + else + errors.push('YAML: ' + (e.message || e).split('\n')[0]); + } + if (Array.isArray(doc)) + list = doc; + else if (isObj(doc) && Array.isArray(doc.proxies)) + list = doc.proxies; + else if (isObj(doc) && doc.type) + list = [ doc ]; + else if (doc !== null && doc !== undefined) + errors.push('YAML: нет списка proxies и не похоже на один сервер'); + list.forEach(function (p) { + if (isObj(p) && isStr(p.type) && p.server !== undefined) + servers.push(p); + else + errors.push('YAML: пропущен элемент без type/server'); + }); + } + return { servers: servers, errors: errors }; + } + + // one stored line: JSON with "name" first (mihomo-kit.sh reads it with sed), no + // dialer-proxy (the kit sets it per profile), "$" as \u0024 (no ${...} for the + // template engine; JSON and YAML both read \u escapes) + function toLine(p) { + var o = { name: String(p.name) }; + Object.keys(p).forEach(function (k) { + if (k != 'name' && k != 'dialer-proxy') + o[k] = p[k]; + }); + return JSON.stringify(o).replace(/\$/g, '\\u0024'); + } + + function fromLines(text) { + var out = []; + String(text || '').split('\n').forEach(function (l) { + if (!l.trim()) + return; + try { + var o = JSON.parse(l); + if (isObj(o)) + out.push(o); + } catch (e) {} + }); + return out; + } + + // "vless · host:port" + function summary(p) { + var host = p.server === undefined ? '?' : String(p.server); + if (host.indexOf(':') >= 0) + host = '[' + host + ']'; + return (p.type || '?') + ' · ' + host + (p.port !== undefined ? ':' + p.port : p['port-range'] ? ':' + p['port-range'] : ''); + } + + // a name not in "taken" (an object): "de", "de-2", "de-3", ... + function freeName(name, taken) { + name = String(name || '').trim() || 'server'; + if (!taken[name]) + return name; + for (var i = 2; ; i++) + if (!taken[name + '-' + i]) + return name + '-' + i; + } + + return { + parseLinks: parseLinks, + parseText: parseText, + yamlLoad: yamlLoad, + yamlDump: yamlDump, + toLine: toLine, + fromLines: fromLines, + summary: summary, + freeName: freeName, + USER_AGENT: USER_AGENT + }; +}); diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh index 98dc36a..e02de84 100755 --- a/router/mihomo-kit.sh +++ b/router/mihomo-kit.sh @@ -73,10 +73,10 @@ log() { echo "$*" >&2; } die() { log "error: $*"; exit 1; } # --- rendering -------------------------------------------------------------- -# Template syntax (same in web/engine.js): +# Template syntax: # file NN-[....][.each].yaml included if module and tags are active; # .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 ... ${@VAR} ... repeated for every word 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}" : "${SUBS:=}" "${RU_IPS:=}" "${HY2:=}" : "${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}" : "${BOOT_LINKS:=}" : "${BOOT_SERVER:=}" "${BOOT_PORT:=443}" "${BOOT_UUID:=}" "${BOOT_SNI:=}" "${BOOT_PBK:=}" "${BOOT_SID:=}" @@ -135,14 +135,10 @@ compute_tags() { fi _i=$((_i + 1)) done - # own hysteria2 servers: HY2_LIST "a, b" (group MY) - HY2_LIST="" - for _n in $HY2; do - HY2_LIST="${HY2_LIST:+$HY2_LIST, }$_n" - 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 "*) + # own servers of the settings (own_servers_vars): proxies in the profile and in group MY + [ -n "$OWN_BODIES" ] && TAGS="$TAGS own_srv " + # MY has servers for sure: own ones or links (not only maybe [MY] nodes) + case "$TAGS" in *" own_srv "* | *" my_links "*) TAGS="$TAGS own " ;; esac @@ -151,7 +147,7 @@ compute_tags() { case "$TAGS" in *" router "*" whitelist "* | *" router "*" foreign "*) TAGS="$TAGS ovpn_exit " ;; esac # own servers through MY-EXIT: whitelist and the phone (often on whitelists) 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 @@ -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_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() { SEED_ITEMS="" SEED_LIST="" _k=1 if [ -n "$BOOT_LINKS" ]; then @@ -208,7 +204,7 @@ seed_vars() { # Subscription ids (provider names, keys SUB__*). A SUBS word is "url" or # "name=url"; without a name the id comes from the domain: # 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() { _h=${1#*://} _h=${_h%%[/?#]*} @@ -349,24 +345,43 @@ sub_vars() { export SUB_NAME SUB_URL SUB_PROXY SUB_UA SUB_HEADERS } -# variables for templates/proxies/*-hy2.each.yaml: hy2_vars -# HY2__SERVER, _PORT, _PASSWORD required -# HY2__OBFS_PASSWORD salamander obfs (empty = none) -# HY2__SNI, _INSECURE=1 (skip-cert-verify), _UP, _DOWN ("50 mbps") -hy2_vars() { +# hy2_json : an old own hysteria2 server of the settings (HY2__SERVER, _PORT, +# _PASSWORD; _OBFS_PASSWORD = salamander; _SNI, _INSECURE=1, _UP, _DOWN) as a stored +# line of own servers (see own_servers_vars) +hy2_json() { _k=$(hy2_key "$1") - eval "HY2_SERVER=\${${_k}_SERVER} HY2_PORT=\${${_k}_PORT} _pw=\${${_k}_PASSWORD} - _ob=\${${_k}_OBFS_PASSWORD:-} HY2_SNI=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0} - _up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}" - HY2_NAME=$1 - HY2_PASSWORD=$(yq "$_pw") - HY2_OBFS="" HY2_OBFS_PASSWORD="" - [ -n "$_ob" ] && HY2_OBFS=salamander HY2_OBFS_PASSWORD=$(yq "$_ob") - HY2_INSECURE=false - [ "$_in" = 1 ] && HY2_INSECURE=true - HY2_UP=$(yq "$_up") HY2_DOWN=$(yq "$_dn") - export HY2_NAME HY2_SERVER HY2_PORT HY2_PASSWORD HY2_OBFS HY2_OBFS_PASSWORD HY2_SNI \ - HY2_INSECURE HY2_UP HY2_DOWN + eval "_sv=\${${_k}_SERVER} _po=\${${_k}_PORT} _pw=\${${_k}_PASSWORD} _ob=\${${_k}_OBFS_PASSWORD:-} + _sn=\${${_k}_SNI:-} _in=\${${_k}_INSECURE:-0} _up=\${${_k}_UP:-} _dn=\${${_k}_DOWN:-}" + case "$_po" in '' | *[!0-9]*) _po="\"$(yq "$_po")\"" ;; esac + printf '{"name":"%s","type":"hysteria2","server":"%s","port":%s,"password":"%s"' \ + "$(yq "$1")" "$(yq "$_sv")" "$_po" "$(yq "$_pw")" + [ -n "$_ob" ] && printf ',"obfs":"salamander","obfs-password":"%s"' "$(yq "$_ob")" + [ -n "$_sn" ] && printf ',"sni":"%s"' "$(yq "$_sn")" + [ "$_in" = 1 ] && printf ',"skip-cert-verify":true' + [ -n "$_up" ] && printf ',"up":"%s"' "$(yq "$_up")" + [ -n "$_dn" ] && printf ',"down":"%s"' "$(yq "$_dn")" + printf ',"udp":true}\n' +} + +# 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() { @@ -444,14 +459,6 @@ render_section() { _part=$(render_file "$f") [ -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" done elif [ "$EACH" = 1 ]; then @@ -532,6 +539,7 @@ render() { sub_pairs boot_seeds check_vars + own_servers_vars compute_tags 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 @@ -539,7 +547,8 @@ render() { 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 \ 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 for s in head proxies:proxies providers:proxy-providers rule-providers:rule-providers sniffer dns \ 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=$_changed 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 _v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8) @@ -1709,7 +1719,7 @@ cmd_apply() { EXPORT_HEAD='# mihomo-kit export v1' cmd_export() { 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 echo "#%% file ${_f#"$NIKKI_DIR"/}" 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" for _f in $_files; do 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" ;; esac case "${_f#profiles.d/}" in */* | *[!A-Za-z0-9_.-]*) die "bad file name: $_f" ;; esac @@ -1749,7 +1759,7 @@ cmd_import() { umask 077 rm -f "$PROFILES_D"/*.env 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" done if [ "${2:-}" = --keep-local ]; then diff --git a/templates/groups/45-sub.yaml b/templates/groups/45-sub.yaml index 499d83a..59433fd 100644 --- a/templates/groups/45-sub.yaml +++ b/templates/groups/45-sub.yaml @@ -1,8 +1,8 @@ - # own servers: hysteria2 from the settings (HY2) and the "[MY] ..." nodes of the - # subscriptions (providers -my); the fastest alive one; pin one in the dashboard if needed + # own servers: those of the settings (proxies/30-own_srv) and the "[MY] ..." nodes of + # the subscriptions (providers -my); the fastest alive one; pin one in the dashboard if needed - name: MY type: url-test - proxies: [${HY2_LIST}] #@hy2 + proxies: [${OWN_LIST}] #@own_srv use: [${MY_SUB_LIST}] url: "https://www.gstatic.com/generate_204" interval: 300 #@!lite diff --git a/templates/proxies/30-hy2.each.yaml b/templates/proxies/30-hy2.each.yaml deleted file mode 100644 index 1eb726e..0000000 --- a/templates/proxies/30-hy2.each.yaml +++ /dev/null @@ -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 diff --git a/templates/proxies/30-own_srv.yaml b/templates/proxies/30-own_srv.yaml new file mode 100644 index 0000000..41dcd58 --- /dev/null +++ b/templates/proxies/30-own_srv.yaml @@ -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 diff --git a/tests/expected/mobile.yaml b/tests/expected/mobile.yaml new file mode 100644 index 0000000..dc5ec71 --- /dev/null +++ b/tests/expected/mobile.yaml @@ -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 -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 diff --git a/tests/expected/router-boots.yaml b/tests/expected/router-boots.yaml new file mode 100644 index 0000000..9b2aaef --- /dev/null +++ b/tests/expected/router-boots.yaml @@ -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 -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 diff --git a/tests/expected/router-csqtt-foreign.yaml b/tests/expected/router-csqtt-foreign.yaml new file mode 100644 index 0000000..e62ca84 --- /dev/null +++ b/tests/expected/router-csqtt-foreign.yaml @@ -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 -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 diff --git a/tests/expected/router-csqtt.yaml b/tests/expected/router-csqtt.yaml new file mode 100644 index 0000000..126e124 --- /dev/null +++ b/tests/expected/router-csqtt.yaml @@ -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 -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 diff --git a/tests/expected/router-foreign.yaml b/tests/expected/router-foreign.yaml new file mode 100644 index 0000000..561e8db --- /dev/null +++ b/tests/expected/router-foreign.yaml @@ -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 -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 diff --git a/tests/expected/router-hwid.yaml b/tests/expected/router-hwid.yaml new file mode 100644 index 0000000..879829e --- /dev/null +++ b/tests/expected/router-hwid.yaml @@ -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 -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 diff --git a/tests/expected/router-ids.yaml b/tests/expected/router-ids.yaml new file mode 100644 index 0000000..7a09a2c --- /dev/null +++ b/tests/expected/router-ids.yaml @@ -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 -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 diff --git a/tests/expected/router-lite-csqtt.yaml b/tests/expected/router-lite-csqtt.yaml new file mode 100644 index 0000000..a0b0d2f --- /dev/null +++ b/tests/expected/router-lite-csqtt.yaml @@ -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 -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 diff --git a/tests/expected/router-lite.yaml b/tests/expected/router-lite.yaml new file mode 100644 index 0000000..a51421c --- /dev/null +++ b/tests/expected/router-lite.yaml @@ -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 -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 diff --git a/tests/expected/router-main.yaml b/tests/expected/router-main.yaml new file mode 100644 index 0000000..06b507a --- /dev/null +++ b/tests/expected/router-main.yaml @@ -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 -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 diff --git a/tests/expected/router-minimal.yaml b/tests/expected/router-minimal.yaml new file mode 100644 index 0000000..85f9233 --- /dev/null +++ b/tests/expected/router-minimal.yaml @@ -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 -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 diff --git a/tests/expected/router-whitelist-ts-my.yaml b/tests/expected/router-whitelist-ts-my.yaml new file mode 100644 index 0000000..cc9617e --- /dev/null +++ b/tests/expected/router-whitelist-ts-my.yaml @@ -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 -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 diff --git a/tests/expected/router-whitelist-ts.yaml b/tests/expected/router-whitelist-ts.yaml new file mode 100644 index 0000000..b226bc5 --- /dev/null +++ b/tests/expected/router-whitelist-ts.yaml @@ -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 -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 diff --git a/tests/expected/router-whitelist.yaml b/tests/expected/router-whitelist.yaml new file mode 100644 index 0000000..f042785 --- /dev/null +++ b/tests/expected/router-whitelist.yaml @@ -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 -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 diff --git a/tests/fixtures/mobile.env b/tests/fixtures/mobile.env index d2b8ed6..c75c912 100644 --- a/tests/fixtures/mobile.env +++ b/tests/fixtures/mobile.env @@ -5,3 +5,4 @@ HY2_M1_PORT=443 HY2_M1_PASSWORD=p LOCAL_HOSTS="sub2.example.com=192.168.64.20" MY_LINKS='ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#ss1' +MY_SERVERS_FILE=tests/fixtures/own.servers diff --git a/tests/fixtures/own.servers b/tests/fixtures/own.servers new file mode 100644 index 0000000..81b0a7d --- /dev/null +++ b/tests/fixtures/own.servers @@ -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"} diff --git a/tests/fixtures/router-boots.env b/tests/fixtures/router-boots.env index e8edb36..fd426f0 100644 --- a/tests/fixtures/router-boots.env +++ b/tests/fixtures/router-boots.env @@ -1,5 +1,5 @@ TARGET=router 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 -vless://22222222-2222-2222-2222-222222222222@seed2.example.com:8443?security=reality&sni=ya.ru&pbk=PBK2&sid=b2" +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=ppQ9FwLrLIa0AOrp1WvcyiaQ37vg2WSy_CD4bIdiTUw&sid=b2" SUB_EXAMPLE_PROXY=BOOT diff --git a/tests/fixtures/router-csqtt-foreign.env b/tests/fixtures/router-csqtt-foreign.env index 2096e0a..3a9b055 100644 --- a/tests/fixtures/router-csqtt-foreign.env +++ b/tests/fixtures/router-csqtt-foreign.env @@ -5,3 +5,4 @@ HY2=nl-1 HY2_NL_1_SERVER=vpn.example.com HY2_NL_1_PORT=443 HY2_NL_1_PASSWORD=p +MY_SERVERS_FILE=tests/fixtures/own.servers diff --git a/tests/fixtures/router-csqtt.env b/tests/fixtures/router-csqtt.env index 474a8cc..ec0a34d 100644 --- a/tests/fixtures/router-csqtt.env +++ b/tests/fixtures/router-csqtt.env @@ -1,3 +1,4 @@ TARGET=router LOCATION=whitelist CSQTT=1 +MY_SERVERS_FILE=tests/fixtures/own.servers diff --git a/tests/fixtures/router-main.env b/tests/fixtures/router-main.env index f572974..a172d20 100644 --- a/tests/fixtures/router-main.env +++ b/tests/fixtures/router-main.env @@ -12,3 +12,4 @@ RU_DOMAINS="*.example.com +.gosuslugi.example .bank.example plain.example" FOREIGN_DOMAINS="api.example.com" MY_DOMAINS="*.home.example" LOCAL_HOSTS="sub2.example.com=192.168.64.20 *.lan-srv.example=10.0.0.5" +MY_SERVERS_FILE=tests/fixtures/own.servers diff --git a/tests/fixtures/router-whitelist-ts-my.env b/tests/fixtures/router-whitelist-ts-my.env index 065b2d9..90e8d30 100644 --- a/tests/fixtures/router-whitelist-ts-my.env +++ b/tests/fixtures/router-whitelist-ts-my.env @@ -2,3 +2,4 @@ TARGET=router LOCATION=whitelist 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_SERVERS_FILE=tests/fixtures/own.servers diff --git a/tests/links/links-edge.expected.json b/tests/links/links-edge.expected.json new file mode 100644 index 0000000..d7290eb --- /dev/null +++ b/tests/links/links-edge.expected.json @@ -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 + } +] diff --git a/tests/links/links-edge.txt b/tests/links/links-edge.txt new file mode 100644 index 0000000..809ee34 --- /dev/null +++ b/tests/links/links-edge.txt @@ -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== diff --git a/tests/links/links.expected.json b/tests/links/links.expected.json new file mode 100644 index 0000000..a7da7d7 --- /dev/null +++ b/tests/links/links.expected.json @@ -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 + } +] diff --git a/tests/links/links.txt b/tests/links/links.txt new file mode 100644 index 0000000..703c68e --- /dev/null +++ b/tests/links/links.txt @@ -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 diff --git a/tests/links/sub.b64 b/tests/links/sub.b64 new file mode 100644 index 0000000..4b44f98 --- /dev/null +++ b/tests/links/sub.b64 @@ -0,0 +1 @@ +dmxlc3M6Ly91dWlkQHMxLmV4YW1wbGU6NDQzP3NlY3VyaXR5PXJlYWxpdHkmcGJrPUsmc2lkPTEjczEKdHJvamFuOi8vcHdAczIuZXhhbXBsZTo0NDMjczI= \ No newline at end of file diff --git a/tests/links/sub.expected.json b/tests/links/sub.expected.json new file mode 100644 index 0000000..2c9a2f6 --- /dev/null +++ b/tests/links/sub.expected.json @@ -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 + } +] diff --git a/tests/yaml/clash.expected.json b/tests/yaml/clash.expected.json new file mode 100644 index 0000000..f732d25 --- /dev/null +++ b/tests/yaml/clash.expected.json @@ -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"}]} diff --git a/tests/yaml/clash.yaml b/tests/yaml/clash.yaml new file mode 100644 index 0000000..7e27e68 --- /dev/null +++ b/tests/yaml/clash.yaml @@ -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 diff --git a/tests/yaml/list.expected.json b/tests/yaml/list.expected.json new file mode 100644 index 0000000..6d7f950 --- /dev/null +++ b/tests/yaml/list.expected.json @@ -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"}] diff --git a/tests/yaml/list.yaml b/tests/yaml/list.yaml new file mode 100644 index 0000000..e7ce09f --- /dev/null +++ b/tests/yaml/list.yaml @@ -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: "-" diff --git a/tests/yaml/one.expected.json b/tests/yaml/one.expected.json new file mode 100644 index 0000000..e4a0a37 --- /dev/null +++ b/tests/yaml/one.expected.json @@ -0,0 +1 @@ +{"name":"single","password":"pw","port":443,"server":"an.example","type":"anytls"} diff --git a/tests/yaml/one.yaml b/tests/yaml/one.yaml new file mode 100644 index 0000000..0d8da38 --- /dev/null +++ b/tests/yaml/one.yaml @@ -0,0 +1,5 @@ +name: single +type: anytls +server: an.example +port: 443 +password: "pw" diff --git a/tools/build-web.py b/tools/build-web.py deleted file mode 100755 index f56d15a..0000000 --- a/tools/build-web.py +++ /dev/null @@ -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(".expected.json is +// common/convert.ConvertsV2Ray of (ws User-Agent set to servers.js's fixed one), +// tests/yaml/.expected.json is go.yaml.in/yaml/v3 of .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); diff --git a/tools/test.sh b/tools/test.sh index 3f3b16e..b0ce1f3 100755 --- a/tools/test.sh +++ b/tools/test.sh @@ -1,7 +1,9 @@ #!/bin/sh -# Render every fixture with router/mihomo-kit.sh and web/engine.js, diff them, -# and (if MIHOMO points to a mihomo binary) validate with `mihomo -t`. -# tools/test.sh parity only +# Render every fixture with router/mihomo-kit.sh and compare with tests/expected/, +# validate with `mihomo -t` when MIHOMO points to a mihomo binary, and check +# luci/servers.js (share links, YAML) against the outputs of mihomo's own Go code. +# tools/test.sh +# UPDATE=1 tools/test.sh rewrite tests/expected/ (review the diff) # MIHOMO=/path/to/mihomo tools/test.sh set -u cd "$(dirname "$0")/.." @@ -13,23 +15,30 @@ if [ -n "${MIHOMO:-}" ]; then echo '+.example.ru' > "$out/ru-inside.txt" "$MIHOMO" convert-ruleset domain text "$out/ru-inside.txt" "$out/home/ruleset/ru-inside.mrs" >/dev/null fi +mkdir -p tests/expected for f in tests/fixtures/*.env; do n=$(basename "$f" .env) [ "$n" = common ] && continue - sh router/mihomo-kit.sh render tests/fixtures/common.env "$f" > "$out/$n.sh.yaml" || { echo "FAIL $n: sh render"; fail=1; continue; } - sh -c 'set -a; . tests/fixtures/common.env; . "$1"; node tools/render.js' _ "$f" > "$out/$n.js.yaml" || { echo "FAIL $n: js render"; fail=1; continue; } - if ! diff -u "$out/$n.sh.yaml" "$out/$n.js.yaml"; then - echo "FAIL $n: sh and js differ" + sh router/mihomo-kit.sh render tests/fixtures/common.env "$f" > "$out/$n.yaml" || { echo "FAIL $n: render"; fail=1; continue; } + if [ "${UPDATE:-0}" = 1 ]; then + cp "$out/$n.yaml" "tests/expected/$n.yaml" + 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 continue fi 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 echo "FAIL $n: mihomo -t"; tail -3 "$out/$n.log"; fail=1; continue fi fi echo "ok $n" 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" exit $fail diff --git a/web/engine.js b/web/engine.js deleted file mode 100644 index 83a22d7..0000000 --- a/web/engine.js +++ /dev/null @@ -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-[....][.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__*), 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__, else the old SUB_ - const subGet = (v, i, id, key) => v[`SUB_${id.toUpperCase()}_${key}`] || v[`SUB${i}_${key}`] || ""; - // SUB__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_ 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__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"); - } - - // "....[.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); diff --git a/web/index.html b/web/index.html deleted file mode 100644 index bf29060..0000000 --- a/web/index.html +++ /dev/null @@ -1,785 +0,0 @@ - - - - - -mihomo-kit - - - -
-
-

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

-

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

-
- -
-
-
- Куда -
-
- - -
-
- - - -
-
-

Обычный — дома в России или за рубежом. Белые списки: OpenVPN через выбранную RU-ноду (группа OVPN-EXIT), свои серверы через MY-EXIT.

- - -
- -
- Подписки -
- -

«Через»: откуда качать подписку. Авто = BOOT-AUTO: BOOT (если включён), иначе ноды сохранённых подписок, иначе напрямую. - HWID — для подписок с лимитом устройств (x-hwid, x-device-os, …).

- - - - - - - - -
- -
- BOOT - -
- - -
-
-
-
- -
-
-
-
- -
-
- -
- HWID -

Общий для всех подписок с галкой HWID. Если провайдер уже знает устройство — тот же x-hwid.

- -
-
-
-
- - -
- -
- Модули роутера - - - - - - -
- параметры OpenVPN - - - -
- - -
- - - -
-
-
- -
-
-
- - - -
-
- - -
-
- -

-      

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

-
-
-
- - - - - diff --git a/web/index.src.html b/web/index.src.html deleted file mode 100644 index ba14675..0000000 --- a/web/index.src.html +++ /dev/null @@ -1,392 +0,0 @@ - - - - - -mihomo-kit - - - -
-
-

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

-

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

-
- -
-
-
- Куда -
-
- - -
-
- - - -
-
-

Обычный — дома в России или за рубежом. Белые списки: OpenVPN через выбранную RU-ноду (группа OVPN-EXIT), свои серверы через MY-EXIT.

- - -
- -
- Подписки -
- -

«Через»: откуда качать подписку. Авто = BOOT-AUTO: BOOT (если включён), иначе ноды сохранённых подписок, иначе напрямую. - HWID — для подписок с лимитом устройств (x-hwid, x-device-os, …).

- - - - - - - - -
- -
- BOOT - -
- - -
-
-
-
- -
-
-
-
- -
-
- -
- HWID -

Общий для всех подписок с галкой HWID. Если провайдер уже знает устройство — тот же x-hwid.

- -
-
-
-
- - -
- -
- Модули роутера - - - - - - -
- параметры OpenVPN - - - -
- - -
- - - -
-
-
- -
-
-
- - - -
-
- - -
-
- -

-      

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

-
-
-
- - - - -