diff --git a/README.md b/README.md index a297df5..538f0bd 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,14 @@ x-device-os, x-ver-os, x-device-model, x-hwid). Порядок подписок включён) и выбираются вручную в дашборде — в автовыборе не участвуют. На профиле `street` к ним идут через ноду `FOREIGN` (`dialer-proxy`), на `home` — напрямую. +Проверка туннелей: у групп `BMSTU` и `TAILSCALE` свой адрес проверки — LuCI → Настройка +(«Адрес для проверки» в блоках OpenVPN и Tailscale) или `OVPN_CHECK_URL` (по умолчанию +`https://eu.bmstu.ru`) / `TS_CHECK_URL` (HTTP-сервис на ноде тейлнета, по умолчанию +`http://100.69.216.50:8080`) в `common.env`. +Кнопка проверки задержки этих групп в дашборде открывает его через туннель (если дашборд +берёт адрес из группы); сами по таймеру они не проверяются. Tailscale ещё проверяется +кнопкой «Проверить» на странице mihomo-kit. + Новый профиль = новый файл в `profiles.d/` (например `LOCATION=home` + `OPENVPN=0`), затем `mihomo-kit.sh build && mihomo-kit.sh use <имя>`. Все опции — в [router/profile.env.example](router/profile.env.example). diff --git a/luci/acl.json b/luci/acl.json index 3379738..31163e7 100644 --- a/luci/acl.json +++ b/luci/acl.json @@ -3,7 +3,7 @@ "description": "mihomo-kit: profiles, OpenVPN, Tailscale", "read": { "ubus": { - "mihomo-kit": [ "status", "ovpn_status", "job", "update_check" ] + "mihomo-kit": [ "status", "ovpn_status", "job", "update_check", "ts_check" ] } }, "write": { diff --git a/luci/mihomo-kit.js b/luci/mihomo-kit.js index fb96373..6aa0657 100644 --- a/luci/mihomo-kit.js +++ b/luci/mihomo-kit.js @@ -11,6 +11,7 @@ var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', expect: { '': {} } }); var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } }); var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } }); +var callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', expect: { '': {} } }); var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', expect: { '': {} } }); var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } }); var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], expect: { '': {} } }); @@ -233,16 +234,34 @@ return view.extend({ ])); } - if (st.tailscale) + if (st.tailscale) { + var tsState = E('span', '—'); + var tsCheck = function() { + dom.content(tsState, E('em', 'проверяю…')); + return callTsCheck().then(function(r) { + dom.content(tsState, { + up: E('strong', { 'style': 'color:green' }, 'отвечает, ' + r.delay + ' мс'), + down: [ E('strong', { 'style': 'color:#c00' }, 'не отвечает'), ' ' + (r.message || '') ], + nourl: 'адрес для проверки не задан (Настройка → Tailscale)' + }[r.state] || r.state); + if (r.url) + tsState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', r.url ])); + }).catch(function(e) { dom.content(tsState, String(e)); }); + }; + if (st.ts_logged_in) + tsCheck(); sections.push(section('Tailscale', [ E('table', { 'class': 'table' }, [ - row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла')) + row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла')), + row('Связь', [ tsState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action', + 'click': ui.createHandlerFn(this, tsCheck) }, 'Проверить') ]) ]), E('div', { 'class': 'cbi-page-actions' }, st.ts_logged_in ? [ this.button('Войти заново', 'negative', 'ts-relogin', null, 'Удалить ключ ноды и войти заново? Нода получит новый адрес 100.x.') ] : [ this.button('Получить ссылку для входа', 'positive', 'ts-login') ]) ])); + } sections.push(section('Обслуживание', [ E('table', { 'class': 'table' }, [ @@ -288,7 +307,9 @@ return view.extend({ totp_secret: text('', cfg.has_totp ? 'сохранён — пусто, чтобы не менять' : 'base32 из QR', 'password'), tailscale: check(cfg.tailscale), ts_hostname: text(cfg.ts_hostname), - ts_domains: text(cfg.ts_domains, 'corp.example.com') + ts_domains: text(cfg.ts_domains, 'corp.example.com'), + ovpn_check_url: text(cfg.ovpn_check_url, 'https://eu.bmstu.ru'), + ts_check_url: text(cfg.ts_check_url, 'http://100.69.216.50:8080') }; var update = function() { @@ -409,11 +430,13 @@ return view.extend({ field('Файл .ovpn', f.ovpn, cfg.ovpn_file ? 'загружен; выбери файл, только чтобы заменить' : 'ещё не загружен'), field('Логин', f.vpn_username), field('Пароль (без OTP)', f.vpn_password), - field('TOTP-секрет', f.totp_secret) + field('TOTP-секрет', f.totp_secret), + field('Адрес для проверки', f.ovpn_check_url, 'что открывает проверка туннеля в дашборде (группа BMSTU); лучше внутренний ресурс') ]); dom.content(tsBox, [ field('Имя ноды', f.ts_hostname), - field('Split-DNS домены', f.ts_domains, 'домены тейлнета кроме *.ts.net, через пробел') + field('Split-DNS домены', f.ts_domains, 'домены тейлнета кроме *.ts.net, через пробел'), + field('Адрес для проверки', f.ts_check_url, 'HTTP-сервис на ноде тейлнета: проверка в дашборде (группа TAILSCALE) и кнопка «Проверить»') ]); f.openvpn.addEventListener('change', update); f.tailscale.addEventListener('change', update); @@ -475,6 +498,8 @@ return view.extend({ tailscale: f.tailscale.checked, ts_hostname: f.ts_hostname.value.trim(), ts_domains: f.ts_domains.value.trim(), + ovpn_check_url: f.ovpn_check_url.value.trim(), + ts_check_url: f.ts_check_url.value.trim(), hy2: hy2Data }); }, this)).then(L.bind(function(r) { diff --git a/luci/rpcd.sh b/luci/rpcd.sh index c36c8e7..bf798d6 100644 --- a/luci/rpcd.sh +++ b/luci/rpcd.sh @@ -7,6 +7,7 @@ # run start a whitelisted command as the background job # job the job's command, state, exit code and output # update_check latest kit commit on the git server vs the installed one +# ts_check Tailscale delay test to TS_CHECK_URL through the mihomo API # config_get settings for the form (secrets: only whether they are set) # config_set save the form (via "mihomo-kit.sh configure") as the job # @@ -34,6 +35,15 @@ q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; } job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; } +# mihomo API base URL from nikki's mixin settings (as in bmstu-otp.sh) +api_url() { + l=$(uci -q get nikki.mixin.api_listen) + port=${l##*:} host=${l%:*} + case "$port" in '' | *[!0-9]*) port=9090 ;; esac + case "$host" in '' | 0.0.0.0 | '[::]' | '::' | '*' | "$l") host=127.0.0.1 ;; esac + echo "http://$host:$port" +} + reply_error() { json_init json_add_string error "$1" @@ -164,6 +174,8 @@ m_config_get() { json_add_boolean tailscale "${TAILSCALE:-0}" json_add_string ts_hostname "${TS_HOSTNAME:-$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo}" json_add_string ts_domains "${TS_DOMAINS:-}" + json_add_string ovpn_check_url "${OVPN_CHECK_URL:-https://eu.bmstu.ru}" + json_add_string ts_check_url "${TS_CHECK_URL:-http://100.69.216.50:8080}" json_add_array hy2 for n in ${HY2:-}; do k=HY2_$(echo "$n" | tr 'a-z-' 'A-Z_') @@ -188,7 +200,7 @@ m_config_set() { json_select data || reply_error "no data" job_running && reply_error "busy: $(cat "$JOB/cmd")" for v in boot_link hwid_ua hwid_os hwid_os_ver hwid_model hwid_id torrent ru_ips openvpn ovpn \ - vpn_username vpn_password totp_secret tailscale ts_hostname ts_domains; do + vpn_username vpn_password totp_secret tailscale ts_hostname ts_domains ovpn_check_url ts_check_url; do json_get_var "$v" "$v" "" done if [ -n "$ovpn" ]; then @@ -231,7 +243,9 @@ m_config_set() { echo "TAILSCALE=$(q "${tailscale:-0}")" echo "TS_HOSTNAME=$(q "$ts_hostname")" echo "TS_DOMAINS=$(q "$ts_domains")" - echo "HY2_SET=1" + echo "FORM=1" + echo "OVPN_CHECK_URL=$(q "$ovpn_check_url")" + echo "TS_CHECK_URL=$(q "$ts_check_url")" hy2= if json_select hy2; then json_get_keys keys @@ -257,6 +271,35 @@ m_config_set() { start_job mihomo-kit.sh configure "$env" } +m_ts_check() { + prof=$(uci -q get nikki.config.profile) + prof=${prof#file:} + prof=${prof%.yaml} + url=$(envval TS_CHECK_URL "$prof") + # same default as set_defaults in mihomo-kit.sh + [ -n "$url" ] || url=http://100.69.216.50:8080 + json_init + if [ -z "$url" ]; then + json_add_string state nourl + json_dump + return + fi + json_add_string url "$url" + sec=$(uci -q get nikki.mixin.api_secret) + res=$(curl -sS -m 12 ${sec:+-H "Authorization: Bearer $sec"} -G \ + --data-urlencode "url=$url" --data-urlencode timeout=8000 \ + "$(api_url)/proxies/TAILSCALE/delay" 2>&1) + delay=$(jsonfilter -s "$res" -e '@.delay' 2>/dev/null) + if [ -n "$delay" ]; then + json_add_string state up + json_add_int delay "$delay" + else + json_add_string state down + json_add_string message "$(jsonfilter -s "$res" -e '@.message' 2>/dev/null || echo "$res")" + fi + json_dump +} + m_update_check() { out=$(mihomo-kit.sh check-update 2>&1) || reply_error "$(echo "$out" | tail -n 1)" json_init @@ -279,7 +322,7 @@ m_job() { case "$1" in list) - echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{}}' + echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}},"update_check":{},"ts_check":{}}' ;; call) case "$2" in @@ -290,6 +333,7 @@ case "$1" in config_get) m_config_get ;; config_set) m_config_set ;; update_check) m_update_check ;; + ts_check) m_ts_check ;; *) reply_error "unknown method" ;; esac ;; diff --git a/router/mihomo-kit.sh b/router/mihomo-kit.sh index e527d29..8aee96d 100755 --- a/router/mihomo-kit.sh +++ b/router/mihomo-kit.sh @@ -61,6 +61,7 @@ set_defaults() { : "${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}" } compute_tags() { @@ -333,7 +334,7 @@ render() { compute_tags export TARGET LOCATION GEOIP_URL GEOSITE_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \ BOOT_PBK BOOT_SID TS_HOSTNAME TS_DOMAINS OVPN_PROVIDER OVPN_GROUP OVPN_SERVER_HOST \ - OVPN_SERVER_IPS OVPN_ROUTES RU_IPS + OVPN_SERVER_IPS OVPN_ROUTES RU_IPS OVPN_CHECK_URL TS_CHECK_URL _first=1 for s in head proxies:proxies providers:proxy-providers sniffer dns groups:proxy-groups rules:rules; do _dir=${s%%:*} @@ -550,11 +551,14 @@ install_files() { install_luci } -# LuCI page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view +# LuCI page "Services -> mihomo-kit" (luci/): rpcd plugin, ACL, menu, view. +# The view goes to view/mihomo-kit/v.js and the menu points there: LuCI +# loads views by script with a ?v= of its own version, which neither a kit +# update nor a hard reload changes, so a fixed name stays cached in the browser. install_luci() { src=$KIT_DIR/luci [ -d "$src" ] && [ -d /www/luci-static/resources ] || return 0 - _changed=0 + _changed=0 _rpcd=0 # put ; uhttpd answers 403 for files that are not world-readable, # and a run from LuCI inherits rpcd's umask 077 put() { @@ -567,11 +571,23 @@ install_luci() { } put "$src/rpcd.sh" /usr/libexec/rpcd/mihomo-kit 755 put "$src/acl.json" /usr/share/rpcd/acl.d/luci-app-mihomo-kit.json 644 - put "$src/menu.json" /usr/share/luci/menu.d/luci-app-mihomo-kit.json 644 - put "$src/mihomo-kit.js" /www/luci-static/resources/view/mihomo-kit.js 644 + # rpcd needs a restart only for its plugin and ACL (it drops LuCI sessions) + _rpcd=$_changed + + _views=/www/luci-static/resources/view + _v=v$(md5sum < "$src/mihomo-kit.js" | cut -c1-8) + put "$src/mihomo-kit.js" "$_views/mihomo-kit/$_v.js" 644 + for _f in "$_views/mihomo-kit.js" "$_views"/mihomo-kit/*.js; do + [ -f "$_f" ] && [ "$_f" != "$_views/mihomo-kit/$_v.js" ] && rm -f "$_f" && _changed=1 + done + sed "s|\"path\": \"mihomo-kit\"|\"path\": \"mihomo-kit/$_v\"|" "$src/menu.json" > /tmp/mihomo-kit-menu.json + put /tmp/mihomo-kit-menu.json /usr/share/luci/menu.d/luci-app-mihomo-kit.json 644 + rm -f /tmp/mihomo-kit-menu.json + [ "$_changed" = 1 ] || return 0 rm -rf /tmp/luci-indexcache* /tmp/luci-modulecache log "LuCI page installed: Services -> mihomo-kit" + [ "$_rpcd" = 1 ] || return 0 # rpcd loads plugins only on start; delayed so a job started from LuCI # (kit update) gets to finish first (sleep 5; /etc/init.d/rpcd restart) < /dev/null > /dev/null 2>&1 & @@ -765,12 +781,12 @@ common_other_keys() { # common.env (+ bmstu.env) from the variables the wizard / configure set; # per-subscription values come as SUB_PROXY/HWID (index in SUBS). -# Own hysteria2 servers (HY2, HY2__*) are rewritten only with HY2_SET=1 -# (LuCI form); the terminal wizard does not ask for them and keeps them. +# Keys only the LuCI form sets (own hysteria2 servers HY2, HY2__*, check +# URLs) are rewritten only with FORM=1; the terminal wizard keeps them. write_config() { umask 077 _any_hwid=0 - [ "${HY2_SET:-0}" = 1 ] && COMMON_KEYS="$COMMON_KEYS|HY2|HY2_[A-Z0-9_]+" + [ "${FORM:-0}" = 1 ] && COMMON_KEYS="$COMMON_KEYS|HY2|HY2_[A-Z0-9_]+|OVPN_CHECK_URL|TS_CHECK_URL" _others=$(common_other_keys) sub_pairs { @@ -802,7 +818,9 @@ write_config() { echo "OPENVPN=$OPENVPN" echo "TAILSCALE=$TAILSCALE" [ "$TAILSCALE" = 1 ] && echo "TS_HOSTNAME=$(q "$TS_HOSTNAME")" && echo "TS_DOMAINS=$(q "$TS_DOMAINS")" - if [ "${HY2_SET:-0}" = 1 ]; then + if [ "${FORM:-0}" = 1 ]; then + [ -n "${OVPN_CHECK_URL:-}" ] && echo "OVPN_CHECK_URL=$(q "$OVPN_CHECK_URL")" + [ -n "${TS_CHECK_URL:-}" ] && echo "TS_CHECK_URL=$(q "$TS_CHECK_URL")" echo "HY2=$(q "$HY2")" for _n in $HY2; do _k=$(hy2_key "$_n") @@ -848,7 +866,7 @@ cmd_sub_ids() { # Settings from the LuCI form: holds BOOT_LINK, SUBS, SUB_PROXY/HWID, # HWID_*, TORRENT, RU_IPS, OPENVPN, VPN_* (empty secrets = keep), TAILSCALE, TS_*, -# HY2_SET=1 + HY2 + HY2__*. +# FORM=1, OVPN_CHECK_URL, TS_CHECK_URL, HY2 + HY2__*. # Validates, writes common.env/bmstu.env, builds and restarts the current profile. cmd_configure() { [ -f "${1:-}" ] || die "usage: configure " diff --git a/templates/groups/40-openvpn.yaml b/templates/groups/40-openvpn.yaml index 2527694..eb85935 100644 --- a/templates/groups/40-openvpn.yaml +++ b/templates/groups/40-openvpn.yaml @@ -1,3 +1,7 @@ + # url: what the dashboard's delay test opens through the tunnel; + # interval 0: no background checks (they would redial with a stale OTP) - name: ${OVPN_GROUP} type: select use: [${OVPN_PROVIDER}] + url: "${OVPN_CHECK_URL}" + interval: 0 diff --git a/templates/groups/50-tailscale.yaml b/templates/groups/50-tailscale.yaml index c7111e8..e2cd118 100644 --- a/templates/groups/50-tailscale.yaml +++ b/templates/groups/50-tailscale.yaml @@ -1,3 +1,6 @@ + # url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test - name: TAILSCALE type: select proxies: [tailscale] + url: "${@TS_CHECK_URL}" + interval: 0 diff --git a/tests/fixtures/router-street.env b/tests/fixtures/router-street.env index 1a12371..4e19a5c 100644 --- a/tests/fixtures/router-street.env +++ b/tests/fixtures/router-street.env @@ -16,3 +16,5 @@ HY2_DE_2_PORT=8443 HY2_DE_2_PASSWORD=x HY2_DE_2_SNI=www.bing.com HY2_DE_2_INSECURE=1 +TS_CHECK_URL=http://100.69.216.50:8080/ +OVPN_CHECK_URL=https://lks.bmstu.ru/ diff --git a/web/engine.js b/web/engine.js index 30fb28d..ba4fa07 100644 --- a/web/engine.js +++ b/web/engine.js @@ -23,6 +23,7 @@ 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", }; const SECTIONS = [ diff --git a/web/index.html b/web/index.html index f1d5f0d..16e5c66 100644 --- a/web/index.html +++ b/web/index.html @@ -211,6 +211,7 @@ 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", }; const SECTIONS = [ @@ -435,9 +436,9 @@ const TEMPLATES = { "groups/10-boot.yaml": " - name: BOOT\n type: select\n proxies: [seed]\n", "groups/20-sub.yaml": " - name: RU\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://ya.ru\"\n interval: 300\n tolerance: 50\n lazy: false\n\n - name: FOREIGN\n type: url-test\n use: [${SUB_LIST}]\n exclude-filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n tolerance: 50\n lazy: false\n", "groups/30-torrent.yaml": " - name: TORRENT\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)torrent|\\\\[tor\\\\]\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 6000\n tolerance: 500\n max-failed-times: 5\n lazy: false\n", - "groups/40-openvpn.yaml": " - name: ${OVPN_GROUP}\n type: select\n use: [${OVPN_PROVIDER}]\n", + "groups/40-openvpn.yaml": " # url: what the dashboard's delay test opens through the tunnel;\n # interval 0: no background checks (they would redial with a stale OTP)\n - name: ${OVPN_GROUP}\n type: select\n use: [${OVPN_PROVIDER}]\n url: \"${OVPN_CHECK_URL}\"\n interval: 0\n", "groups/41-openvpn.street.yaml": " # what the OpenVPN tunnel itself goes through on a whitelisted network.\n # select, not url-test: switching nodes would break the tunnel.\n # Pick a concrete RU node in the dashboard, the choice is remembered.\n - name: OVPN-EXIT\n type: select\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n", - "groups/50-tailscale.yaml": " - name: TAILSCALE\n type: select\n proxies: [tailscale]\n", + "groups/50-tailscale.yaml": " # url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test\n - name: TAILSCALE\n type: select\n proxies: [tailscale]\n url: \"${@TS_CHECK_URL}\"\n interval: 0\n", "groups/51-tailscale.ts_exit.yaml": " # Tailscale needs full-cone UDP from its dialer-proxy: vless/vmess/trojan\n # cannot do it in mihomo, so only ss / hysteria2 / tuic / socks5 nodes here.\n - name: TS-EXIT\n type: select\n proxies: [${HY2_LIST}] #@hy2\n use: [${SUB_LIST}]\n exclude-type: \"vless|vmess|trojan\"\n", "groups/90-base.yaml": " - name: MAIN\n type: select\n proxies: [FOREIGN, ${HY2_MAIN}RU, DIRECT]\n", "groups/91-torrent.yaml": " - name: TORRENT-SEL\n type: select\n proxies: [TORRENT, FOREIGN, DIRECT]\n",