Compare commits
7
Commits
v122-r2
...
87ac016293
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87ac016293 | ||
|
|
05972f8c24 | ||
|
|
d482ed97c4 | ||
|
|
9b7a89257b | ||
|
|
9dead7741d | ||
|
|
ce763dd1be | ||
|
|
9c8def5e5c |
No files matched your search
@@ -143,6 +143,8 @@ jobs:
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y qemu-system-x86 openssh-client
|
||||
- name: Test with the real OpenWrt package manager and BusyBox ash
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
python3 scripts/test-openwrt-package-vm.py \
|
||||
--release '${{ matrix.version }}' --package-dir artifacts \
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# FORK.md — изменения форка (cyril/luci-app-owrt-remote)
|
||||
|
||||
Форк `kzolotarev95/luci-app-owrt-remote`. Зеркало upstream: `~/mirrors/luci-app-owrt-remote.git` (GitHub origin), push-копия в Gitea `11.11.11.106:3000/cyril/luci-app-owrt-remote` (pull-зеркало отключено; ресинк вручную, наши коммиты — поверх upstream main).
|
||||
|
||||
## Наш коммит: REALITY для hops роутер↔хаб
|
||||
|
||||
`VLESS+Reality` вместо `security=none` (см. `docs/REALITY_TRANSPORT.md`):
|
||||
|
||||
- `vps/owrt-remote-hub.py`
|
||||
- профиль транспорта `STATE_DIR/transport.json` (x25519-пара через бинарь xray, shortId, dest/SNI, fingerprint); env `OWRT_REMOTE_TRANSPORT` (`reality` по умолчанию, `none` — как upstream), `OWRT_REMOTE_REALITY_DEST`, `OWRT_REMOTE_REALITY_FINGERPRINT`, `OWRT_REMOTE_XRAY_BINARY`;
|
||||
- reality streamSettings в `make_server_xray_config()` и `make_router_xray_config()`;
|
||||
- uci-строки `security`, `reality_public_key`, `reality_server_name`, `reality_fingerprint` в генерируемом конфиге роутера;
|
||||
- блок `transport` в heartbeat `hub_update`;
|
||||
- `reload_vps_xray` пишет конфиг в candidate-файл, гоняет `xray -test` и только потом подменяет — кривой конфиг не убьёт живой туннель.
|
||||
- `files/usr/sbin/owrt-remote` — те же поля uci + валидация + reality streamSettings в `render_client_config`, compat-probe по security, возрастная проверка ядра для reality (< 24.2.14 — заменить).
|
||||
- `files/etc/config/owrtremote`, поля формы в `files/www/cgi-bin/owrt-remote`, `PKG_RELEASE:=3`.
|
||||
|
||||
## Известные проблемы upstream, на которые наткнулись
|
||||
|
||||
- **XTLS/Xray-core#7259**: REALITY-серверы >= 26.9.8 отвергают client hello («received real certificate (potential MITM or redirection)»), работает на 26.7.28. Хабы держим на **xray-core 26.7.28**, пока upstream не починит. Проверка матрицы версий — в `docs/REALITY_TRANSPORT.md`.
|
||||
|
||||
## Как ресинкать с upstream
|
||||
|
||||
```
|
||||
git -C ~/mirrors/luci-app-owrt-remote.git fetch origin
|
||||
git -C ~/mirrors/luci-app-owrt-remote.git merge --ff-only origin/main # или rebase нашей ветки
|
||||
# конфликты вероятны в owrt-remote-hub.py (make_server/client configs) — сверять с docs/REALITY_TRANSPORT.md
|
||||
git -C ~/forks/luci-app-owrt-remote fetch && git -C ~/forks/luci-app-owrt-remote rebase main
|
||||
```
|
||||
@@ -38,27 +38,6 @@
|
||||
Роутер сам подключается к VPS изнутри сети, а ты заходишь в Hub-панель и открываешь нужный роутер, LuCI или SSH Web Terminal.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b>Remote управление Xray:</b> запуск, остановка и перезапуск Xray выбранного роутера
|
||||
через Heartbeat, с проверкой результата и журналом действий. Работает при остановленном
|
||||
Xray и недоступном SSH-туннеле, если агент продолжает связываться с Hub.
|
||||
Нужны обновлённые Hub и агент. <a href="docs/xray-control.md">Описание и проверка</a>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b>Журналы VPS:</b> ежедневная ротация в 03:20, ограничение journald,
|
||||
фильтрация успешных частых HTTP-запросов и проверка заполнения диска.
|
||||
Устанавливается также через кнопку «Обновление панели».
|
||||
<a href="docs/VPS_LOG_MAINTENANCE.md">Установка, проверка и откат</a>.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<b>Tachyon:</b> автоматическое обнаружение пакета на каждом роутере,
|
||||
версия и Online/Offline, открытие отдельного веб-интерфейса или старого LuCI
|
||||
через авторизованный туннель Hub.
|
||||
<a href="docs/TACHYON_INTEGRATION.md">Локальная установка, проверка и откат</a>.
|
||||
</p>
|
||||
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# REALITY-транспорт hops роутер↔хаб (наш форк)
|
||||
|
||||
## Суть
|
||||
|
||||
Upstream: один VLESS-inbound хаба на `:8443` c `network=tcp, security=none`.
|
||||
Роутер дIAL-OUTит к хабу; reverse-порталы (LuCI/SSH) живут за тем же conn.
|
||||
Без TLS: весь трафик и логин-данные в панели — открытым текстом внутри hops.
|
||||
|
||||
Форк: тот же единственный inbound, но `security=reality` — полноценное TLS-рукопожатие,
|
||||
замаскированное под handshake публичного сайта-прикрытия (`dest`), без CA-сертификатов
|
||||
и продлений. Аутентификация по-прежнему per-router UUID (LuCI + SSH = два UUID).
|
||||
|
||||
## Где что генерируется
|
||||
|
||||
- Хаб: `transport.json` в `STATE_DIR` (`/var/lib/owrt-remote/`), создаётся лениво
|
||||
(`xray x25519` → приват/публик, `shortId` = 8 hex, `dest`=SNI из env).
|
||||
- Серверный inbound: `privateKey`, `serverNames=[SNI]`, `shortIds=[shortId]`,
|
||||
`dest=<SNI>:443`, `xver=0`.
|
||||
- Клиент (роутер): `publicKey`, `serverName`, `fingerprint` (chrome). shortId клиенту
|
||||
не нужен (сервер кодирует его в «фейковом» сертификате).
|
||||
- Конфиг роутера хаб отдаёт готовыми `uci set owrtremote.main.security/reality_*`
|
||||
(карточка роутера / print-openwrt-config / панельный «Xray настройки» на роутере).
|
||||
- Heartbeat остаётся отдельным HTTPS-каналом (через панель/Pangolin), к xray не относится.
|
||||
|
||||
## Пин версии xray на хабе (важно!)
|
||||
|
||||
Upstream-регрессия **XTLS/Xray-core#7259**: REALITY-сервер 26.9.8+ не принимает
|
||||
рукопожатия клиентов (клиент: `received real certificate (potential MITM or redirection)`).
|
||||
Практика 22.11.2026: связка 26.11.9↔26.11.9 не работает, ~~26.7.28~~ (см. таблицу матрицы
|
||||
в коммите форка/заметку хаба) — хаб держим на **26.7.28**, пока upstream не выпустит фикс.
|
||||
|
||||
Обновление хаба на новую версию core — только после повторного прогона e2e-матрицы
|
||||
(hub-generators → две локации xray → reverse-туннель через reality).
|
||||
|
||||
## Смена camouflage-домена
|
||||
|
||||
env хаба: `OWRT_REMOTE_REALITY_DEST=download.windowsupdate.com`, рестарт `owrt-remote`,
|
||||
затем пересоздать конфиги роутеров (карточка → новая команда uci; shortId/pk те же, если
|
||||
не трогать transport.json). Удаление `transport.json` = новая x25519-пара и новый shortId
|
||||
⇒ всем роутерам нужны новые конфиги.
|
||||
|
||||
## Совместимость / откат
|
||||
|
||||
`OWRT_REMOTE_TRANSPORT=none` + рестарт = ровно upstream-поведение (но генератор конфига
|
||||
роутера продолжит писать `security=none`, роутер-агент умеет оба).
|
||||
Старые агенты (без полей security) не работают с reality-hub — роутер нужно обновить
|
||||
(установить ipk/файлы этого форка).
|
||||
|
||||
|
||||
## 22.11.2026: reverse + REALITY is broken on modern cores — `security=tls` is now the default
|
||||
|
||||
Bisect matrix (xray 26.7.28 / 26.11.9, all four pairs, loopback e2e):
|
||||
|
||||
* the REALITY hop itself authenticates and tunnels user traffic fine
|
||||
(shortId MUST be present in the client `realitySettings`; camo dest
|
||||
`www.microsoft.com` is dead because Microsoft now serves post-quantum
|
||||
cert chains — use `www.cloudflare.com`);
|
||||
* BUT the tag-form VLESS reverse (Rvs control channel, PR #5101) never
|
||||
registers when the bridge transport is REALITY: portal logs the reality
|
||||
handshake (`hs.c.conn == conn: true`) and then silence — no
|
||||
`v1.rvs.cool` request is ever dispatched. Upstream reports of the same
|
||||
family: XTLS/Xray-core #6242 / #6248 ("reverse broken since 26.5,
|
||||
works on 26.4.25"). Our repro: relay hex-dump shows the bridge's Rvs
|
||||
request on the wire, portal never responds. xray 26.4.25 was also pulled
|
||||
(ghcr layers, /tmp/xraybin264) and tested: the tag-form fails there too
|
||||
(26.4.25<->26.4.25 and cross-version) — upstream's "works on 26.4.25"
|
||||
refers to the legacy domain-form reverse config, not PR #5101 tags.)
|
||||
|
||||
Working alternative shipped as `OWRT_REMOTE_TRANSPORT=tls` (default):
|
||||
self-signed hub cert (hub generates it with openssl) + `pinnedPeerCertSha256`
|
||||
on the router (xray removed `allowInsecure`), ALPN `h2,http/1.1`, uTLS
|
||||
`fingerprint: chrome`. Verified end-to-end through hub-generated configs:
|
||||
portal `entry-*` -> reverse mux -> router `router-admin` freedom redirect
|
||||
= HTTP 200 on 26.11.9<->26.11.9 and 26.11.9<->26.7.28.
|
||||
|
||||
Pitfalls discovered along the way:
|
||||
|
||||
* freedom outbounds behind the reverse bridge need explicit
|
||||
`finalRules: [{action: allow, network: tcp, port: ...}]` — newer cores
|
||||
blackhole reverse egress by default (see also 3x-ui 6f6c7fc);
|
||||
* the Rvs bridge registers ~2 s after the router xray starts (monitor
|
||||
interval), healthcheck scripts must wait, or they see
|
||||
`non existing outTag`;
|
||||
* legacy `reverse.bridges/portals` config objects were REMOVED in 26.x —
|
||||
only the tag form works.
|
||||
|
||||
REALITY stays selectable (`OWRT_REMOTE_TRANSPORT=reality`) for the hub
|
||||
panel hop style until upstream fixes reverse-over-REALITY.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Раскрытие данных карточек роутеров
|
||||
|
||||
На ПК и телефоне карточки открываются кнопками «Открыть данные» и «Скрыть данные».
|
||||
На ПК подробности раскрываются поверх сетки. Место компактной карточки сохраняется,
|
||||
поэтому соседние карточки, следующие ряды и высота страницы не меняются.
|
||||
Одновременно открыта одна карточка. Закрыть её можно кнопкой, Escape или нажатием
|
||||
снаружи. Длинное содержимое прокручивается внутри раскрытой карточки.
|
||||
|
||||
Раскрытие занимает 230 мс. В облегчённом дизайне и при системной настройке уменьшения
|
||||
анимации переход выполняется сразу. На мобильном сохраняется раскрытие внутри
|
||||
страницы. Обновление статусов сохраняет открытые данные и их прокрутку.
|
||||
|
||||
## Локальная установка на VPS
|
||||
|
||||
Из PowerShell Windows 11:
|
||||
|
||||
```powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-router-card-details.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@YOUR_VPS_IP -Action Install
|
||||
```
|
||||
|
||||
Скрипт проверяет Python, сохраняет исходный Hub в
|
||||
`/root/owrt-remote-backup-before-router-card-details-v122/hub.py`, атомарно заменяет
|
||||
файл, перезапускает Hub и проверяет SHA256 работающего процесса через `/health`.
|
||||
При ошибке восстанавливает файл, который был установлен до текущей попытки.
|
||||
После установки обновите страницу панели через Ctrl+F5.
|
||||
|
||||
Откат к сохранённой копии:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@YOUR_VPS_IP -Action Rollback
|
||||
```
|
||||
|
||||
## Проверка интерфейса
|
||||
|
||||
`tests/test_router_card_details.cjs` использует настоящий HTML/JS панели и
|
||||
Playwright с установленным Chrome. Проверяет координаты сетки во время анимации,
|
||||
раскрытие/закрытие, границы экрана, быстрые повторные клики, обновление статусов,
|
||||
прокрутку, фокус клавиатуры и переход с ПК на мобильный размер. Сценарии включают
|
||||
три дизайна, уменьшенную анимацию, две колонки и обе ориентации телефона.
|
||||
@@ -17,6 +17,12 @@ config remote 'main'
|
||||
option vless_uuid ''
|
||||
option vless_encryption 'none'
|
||||
option vless_flow ''
|
||||
option security 'none'
|
||||
option reality_public_key ''
|
||||
option reality_server_name ''
|
||||
option reality_fingerprint 'chrome'
|
||||
option tls_sni ''
|
||||
option tls_pin ''
|
||||
option reverse_tag 'reverse-in'
|
||||
option ssh_vless_uuid ''
|
||||
option ssh_reverse_tag 'reverse-in-ssh'
|
||||
|
||||
@@ -622,7 +622,18 @@ validate_xray_config() {
|
||||
xray_requires_legacy_replacement() {
|
||||
local version
|
||||
# Keep an existing working core. Replace a known incompatible core only
|
||||
# for the transport generated here (VLESS encryption=none, security=none).
|
||||
# for the transport generated here.
|
||||
if [ "$(uci_get security none)" = reality ]; then
|
||||
# Reality needs a core with X25519/Reality support; replace only old builds.
|
||||
version="$("$1" version 2>/dev/null | sed -n '1s/^Xray \([0-9][0-9.]*\) .*/\1/p')"
|
||||
[ -n "$version" ] || return 1
|
||||
LC_ALL=C awk -v version="$version" 'BEGIN {
|
||||
n=split(version, v, ".")
|
||||
exit !(n==3 && (v[1]*10000 + v[2]*100 + v[3]) < 240214)
|
||||
}'
|
||||
return $?
|
||||
fi
|
||||
# (VLESS encryption=none, security=none path, upstream rule)
|
||||
[ "$(uci_get vless_encryption none)" = none ] || return 1
|
||||
version="$("$1" version 2>/dev/null | sed -n '1s/^Xray \([0-9][0-9.]*\) .*/\1/p')"
|
||||
[ -n "$version" ] || return 1
|
||||
@@ -640,15 +651,21 @@ xray_validate_transport_binary() (
|
||||
trap 'rm -rf "$probe"' EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
umask 077
|
||||
if [ "$(uci_get security none)" = reality ]; then
|
||||
cat >"$probe/config.json" <<'EOF'
|
||||
{"log":{"loglevel":"none"},"outbounds":[{"tag":"vps-interconn","protocol":"vless","settings":{"address":"example.com","port":8443,"id":"11111111-1111-4111-8111-111111111111","encryption":"none","reverse":{"tag":"compat-reverse"}},"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"show":false,"fingerprint":"chrome","serverName":"www.microsoft.com","publicKey":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}}]}
|
||||
EOF
|
||||
else
|
||||
cat >"$probe/config.json" <<'EOF'
|
||||
{"log":{"loglevel":"none"},"outbounds":[{"tag":"vps-interconn","protocol":"vless","settings":{"address":"example.com","port":8443,"id":"11111111-1111-4111-8111-111111111111","encryption":"none","reverse":{"tag":"compat-reverse"}},"streamSettings":{"network":"tcp","security":"none"}}]}
|
||||
EOF
|
||||
fi
|
||||
if "$binary" -test -config "$probe/config.json" >"$probe/result" 2>&1; then
|
||||
return 0
|
||||
else
|
||||
rc=$?
|
||||
head -c 8192 "$probe/result" >&2
|
||||
log "ОШИБКА: пакет Xray несовместим с текущим VLESS reverse без TLS (rc=$rc). Нужна сборка с поддержкой текущего транспорта; рабочий бинарник и кэш сохранены"
|
||||
log "ОШИБКА: пакет Xray несовместим с текущим транспортом VLESS reverse (security=$(uci_get security none), rc=$rc). Нужна сборка с поддержкой текущего транспорта; рабочий бинарник и кэш сохранены"
|
||||
return "$rc"
|
||||
fi
|
||||
)
|
||||
@@ -683,6 +700,13 @@ render_client_config() (
|
||||
ssh_uuid="$(uci_get ssh_vless_uuid '')"
|
||||
encryption="$(uci_get vless_encryption none)"
|
||||
flow="$(uci_get vless_flow '')"
|
||||
security="$(uci_get security none)"
|
||||
reality_pk="$(uci_get reality_public_key '')"
|
||||
reality_sid="$(uci_get reality_short_id '')"
|
||||
reality_sni="$(uci_get reality_server_name '')"
|
||||
reality_fp="$(uci_get reality_fingerprint chrome)"
|
||||
tls_sni="$(uci_get tls_sni '')"
|
||||
tls_pin="$(uci_get tls_pin '')"
|
||||
reverse_tag="$(uci_get reverse_tag reverse-in)"
|
||||
ssh_reverse_tag="$(uci_get ssh_reverse_tag "${reverse_tag}-ssh")"
|
||||
admin_host="$(uci_get admin_host 127.0.0.1)"
|
||||
@@ -707,6 +731,30 @@ render_client_config() (
|
||||
fi
|
||||
done
|
||||
case "$vps_host" in *://*|*/*) die "vps_host должен содержать IP или домен без http(s):// и пути" ;; esac
|
||||
case "$security" in none|reality|tls) ;; *) die "security: ожидается none, reality или tls" ;; esac
|
||||
if [ "$security" = tls ]; then
|
||||
case "$tls_sni" in ''|*://*) die "tls_sni: SNI-домен хаба без схемы и путей" ;; esac
|
||||
if [ "$(printf '%s' "$tls_sni" | LC_ALL=C tr -d '\001-\040\177')" != "$tls_sni" ]; then
|
||||
die "tls_sni: содержит пробел или управляющий символ"
|
||||
fi
|
||||
case "$tls_pin" in *[!0-9a-fA-F]*|'') die "tls_pin: 64-символьный hex SHA256 сертификата хаба из карточки роутера на VPS" ;; esac
|
||||
[ "${#tls_pin}" -eq 64 ] || die "tls_pin: длина SHA256 должна быть 64 hex-символа"
|
||||
transport_stream='"security": "tls",
|
||||
"tlsSettings": {"serverName": "'"$(json_escape "$tls_sni")"'", "pinnedPeerCertSha256": "'"$(json_escape "$tls_pin")"'", "alpn": ["h2", "http/1.1"], "fingerprint": "'"$(json_escape "$reality_fp")"'"}'
|
||||
elif [ "$security" = reality ]; then
|
||||
case "$reality_pk" in ''|*[!A-Za-z0-9_-]*) die "reality_public_key: ожидается 43-символьный base64url-ключ X25519 из карточки роутера на VPS" ;; esac
|
||||
[ "${#reality_pk}" -eq 43 ] || die "reality_public_key: длина ключа X25519 должна быть 43 символа"
|
||||
case "$reality_sni" in ''|*://*) die "reality_server_name: укажите camouflage-домен без схемы и путей (например www.microsoft.com)" ;; esac
|
||||
if [ "$(printf '%s' "$reality_sni" | LC_ALL=C tr -d '\001-\040\177')" != "$reality_sni" ]; then
|
||||
die "reality_server_name: содержит пробел или управляющий символ"
|
||||
fi
|
||||
case "$reality_fp" in ''|*[!a-zA-Z0-9_-]*) die "reality_fingerprint: ожидается отпечаток без пробелов (chrome, firefox, safari, ios, android)" ;; esac
|
||||
case "$reality_sid" in *[!0-9a-fA-F]*) die "reality_short_id: ожидается hex (0-9a-f)" ;; esac
|
||||
transport_stream='"security": "reality",
|
||||
"realitySettings": {"show": false, "fingerprint": "'"$(json_escape "$reality_fp")"'", "serverName": "'"$(json_escape "$reality_sni")"'", "publicKey": "'"$(json_escape "$reality_pk")"'", "shortId": "'"$(json_escape "$reality_sid")"'"}'
|
||||
else
|
||||
transport_stream='"security": "none"'
|
||||
fi
|
||||
|
||||
if [ "$stdout" = "1" ]; then
|
||||
xray_config_dir="${TMPDIR:-/tmp}"
|
||||
@@ -761,7 +809,7 @@ render_client_config() (
|
||||
},
|
||||
"streamSettings": {
|
||||
"network": "tcp",
|
||||
"security": "none"$wan_sockopt
|
||||
$transport_stream$wan_sockopt
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -779,7 +827,7 @@ render_client_config() (
|
||||
},
|
||||
"streamSettings": {
|
||||
"network": "tcp",
|
||||
"security": "none"$wan_sockopt
|
||||
$transport_stream$wan_sockopt
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -192,7 +192,7 @@ save_config() {
|
||||
fi
|
||||
uci_set enabled "$enabled"
|
||||
|
||||
for field in router_id router_name role hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port public_url; do
|
||||
for field in router_id router_name role hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow security reality_public_key reality_short_id reality_server_name reality_fingerprint tls_sni tls_pin reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port public_url; do
|
||||
uci_set "$field" "$(param "$field")"
|
||||
done
|
||||
if has_param vps_host_auto; then uci_set vps_host_mode auto; else uci_set vps_host_mode manual; fi
|
||||
@@ -208,7 +208,7 @@ save_config() {
|
||||
|
||||
clear_config() {
|
||||
local field
|
||||
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_host_mode wan_direct wan_interface wan_dns vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
|
||||
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_host_mode wan_direct wan_interface wan_dns vps_port vless_uuid vless_encryption vless_flow security reality_public_key reality_short_id reality_server_name reality_fingerprint tls_sni tls_pin reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
|
||||
uci -q delete "owrtremote.main.$field"
|
||||
done
|
||||
uci commit owrtremote
|
||||
@@ -715,6 +715,13 @@ EOF
|
||||
field vless_uuid "VLESS UUID" text "Уникальный UUID роутера. Бери из карточки роутера на VPS или из команды print-openwrt-config."
|
||||
field vless_encryption "VLESS encryption" text "Для этой схемы оставь none. Меняй только если сам меняешь Xray-конфиг на VPS."
|
||||
field vless_flow "VLESS flow" text "Обычно оставь пустым. Нужно только для специальных режимов Xray."
|
||||
field security "Транспорт (security)" text "tls (рекомендуется), reality или none. Остальные значения — из карточки роутера на VPS."
|
||||
field reality_short_id "Reality shortId" text "8 hex-символов. Только для security=reality."
|
||||
field tls_sni "TLS SNI" text "SNI/CN сертификата хаба. Только для security=tls."
|
||||
field tls_pin "TLS pin" text "64 hex-символа SHA256 сертификата хаба. Только для security=tls."
|
||||
field reality_public_key "Reality public key" text "43-символьный публичный ключ X25519 хаба. Только для security=reality."
|
||||
field reality_server_name "Reality SNI" text "Camouflage-домен хаба, например www.microsoft.com. Только для security=reality."
|
||||
field reality_fingerprint "Reality fingerprint" text "Отпечаток клиента: chrome, firefox, safari, ios или android."
|
||||
field reverse_tag "Reverse tag" text "Метка reverse-туннеля внутри Xray. Обычно оставь reverse-in, если на VPS не задавал другое."
|
||||
field ssh_vless_uuid "SSH VLESS UUID" text "UUID отдельного SSH reverse-туннеля. Бери из OpenWrt config на VPS для этого роутера."
|
||||
field ssh_reverse_tag "SSH reverse tag" text "Метка reverse-туннеля для SSH. Обычно reverse-in-ssh."
|
||||
|
||||
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-owrt-remote
|
||||
PKG_VERSION:=122
|
||||
PKG_RELEASE:=2
|
||||
PKG_RELEASE:=4
|
||||
PKG_LICENSE:=MIT
|
||||
PKG_MAINTAINER:=kzolotarev95
|
||||
PKGARCH:=all
|
||||
|
||||
@@ -65,6 +65,33 @@ def release_tag():
|
||||
return 'v' + version + (('-r' + revision) if revision != '1' else '')
|
||||
|
||||
|
||||
def release_asset(tag, filename):
|
||||
"""Resolve the official prior package even if its SHA256SUMS was removed."""
|
||||
repository = 'https://github.com/kzolotarev95/luci-app-owrt-remote'
|
||||
api = 'https://api.github.com/repos/kzolotarev95/luci-app-owrt-remote/releases/tags/'
|
||||
if not re.fullmatch(r'v[0-9]+(?:-r[0-9]+)?', tag) or not re.fullmatch(r'[A-Za-z0-9_.+-]+', filename):
|
||||
raise ValueError('invalid previous release identifier')
|
||||
headers = {'User-Agent': 'OpenWrt-Remote-package-builder', 'Accept': 'application/vnd.github+json'}
|
||||
token = os.environ.get('GITHUB_TOKEN')
|
||||
if token:
|
||||
headers['Authorization'] = 'Bearer ' + token
|
||||
with urllib.request.urlopen(urllib.request.Request(api + tag, headers=headers), timeout=45) as response:
|
||||
data = response.read(4 * 1024 * 1024 + 1)
|
||||
if len(data) > 4 * 1024 * 1024:
|
||||
raise ValueError('oversized previous Release metadata')
|
||||
assets = [asset for asset in json.loads(data).get('assets', []) if asset.get('name') == filename]
|
||||
if len(assets) != 1:
|
||||
raise ValueError('previous Release package missing or ambiguous: ' + filename)
|
||||
asset = assets[0]
|
||||
expected_url = repository + '/releases/download/' + tag + '/' + filename
|
||||
digest = asset.get('digest') or ''
|
||||
if asset.get('browser_download_url') != expected_url or not re.fullmatch(r'sha256:[0-9a-f]{64}', digest):
|
||||
raise ValueError('previous Release package has no official SHA256: ' + filename)
|
||||
if not 0 < int(asset.get('size') or 0) <= 16 * 1024 * 1024:
|
||||
raise ValueError('invalid previous Release package size')
|
||||
return expected_url, digest.removeprefix('sha256:')
|
||||
|
||||
|
||||
def latest_release(series, html):
|
||||
candidates = [link.rstrip("/") for link in Links(html).links
|
||||
if re.fullmatch(re.escape(series) + r"\.[0-9]+/", link)]
|
||||
|
||||
@@ -64,10 +64,9 @@ def main():
|
||||
tag = 'v' + version + (('-r' + previous) if previous != '1' else '')
|
||||
series = '.'.join(args.release.split('.')[:2])
|
||||
name = f'{package.PACKAGE}_{version}-r{previous}_openwrt-{series}_{"noarch" if apk else "all"}{candidate.suffix}'
|
||||
origin = 'https://github.com/kzolotarev95/luci-app-owrt-remote/releases/download/' + tag + '/'
|
||||
expected = package.checksum(package.get_text(origin + 'SHA256SUMS'), name)
|
||||
url, expected = package.release_asset(tag, name)
|
||||
baseline = source / 'test-fixtures' / ('previous-release' + candidate.suffix)
|
||||
package.download(origin + name, baseline, expected)
|
||||
package.download(url, baseline, expected)
|
||||
output = Path(args.output).resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
port = free_port()
|
||||
|
||||
@@ -73,9 +73,9 @@ const eventFor = (selector, node) => ({target: {closest(wanted) { return wanted
|
||||
expandedActionPanels: new Set(), expandedCardDetails: new Set(),
|
||||
expandedGroupPickers: new Set(), openRouterGroups: new Set(['__ungrouped__']),
|
||||
mobileCardsMq: {matches: false}, authIsOwner: () => true, groupPickerButtonsHtml: empty,
|
||||
renderModelMetric: empty, modelGetsLegendBadge: () => false, metric: empty,
|
||||
renderModelMetric: empty, modelGetsLegendBadge: () => false, metric: empty, renderTachyon: empty,
|
||||
statusRu: identity, ago: empty, metricHtml: empty, formatMemoryHtml: empty,
|
||||
memoryClass: empty, formatFlashHtml: empty, flashClass: empty,
|
||||
memoryClass: empty, formatFlashHtml: empty, flashClass: empty, syncCardDetails: empty,
|
||||
formatTemperatureHtml: empty, tempClass: empty, syncActionToggleStates: empty,
|
||||
});
|
||||
vm.runInContext(source.slice(renderBegin, renderEnd), context);
|
||||
|
||||
@@ -89,6 +89,18 @@ class PackageTests(unittest.TestCase):
|
||||
with self.subTest(values=values), mock.patch.object(p,'versions',return_value=values):
|
||||
self.assertEqual(p.release_tag(), expected)
|
||||
|
||||
def test_previous_package_uses_official_api_digest_without_checksum_asset(self):
|
||||
filename = 'luci-app-owrt-remote_122-r1_openwrt-25.12_noarch.apk'
|
||||
url = 'https://github.com/kzolotarev95/luci-app-owrt-remote/releases/download/v122/' + filename
|
||||
asset = {'name':filename,'browser_download_url':url,'digest':'sha256:'+'a'*64,'size':83000}
|
||||
data = p.json.dumps({'assets':[asset]}).encode()
|
||||
with mock.patch.object(p.urllib.request,'urlopen',return_value=io.BytesIO(data)):
|
||||
self.assertEqual(p.release_asset('v122',filename),(url,'a'*64))
|
||||
for change in ({'digest':None},{'browser_download_url':'https://other.example/package.apk'}):
|
||||
invalid = dict(asset,**change)
|
||||
with mock.patch.object(p.urllib.request,'urlopen',return_value=io.BytesIO(p.json.dumps({'assets':[invalid]}).encode())):
|
||||
with self.assertRaises(ValueError):p.release_asset('v122',filename)
|
||||
|
||||
def test_package_scripts_defer_procd_lifecycle_to_openwrt_for_apk_and_ipk(self):
|
||||
script = p.package_hook("postinst")
|
||||
self.assertNotIn("configure ]", script)
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// Run with Playwright available in NODE_PATH. Uses the actual dashboard HTML/JS.
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const {execFileSync} = require('node:child_process');
|
||||
const {chromium} = require('playwright');
|
||||
const output = path.resolve('.test-output/card-details');
|
||||
fs.mkdirSync(output, {recursive:true});
|
||||
execFileSync(process.env.TEST_PYTHON || 'python', ['-c', String.raw`
|
||||
import importlib.util, os, sys, tempfile
|
||||
from pathlib import Path
|
||||
with tempfile.TemporaryDirectory(prefix='card-details-preview-') as state:
|
||||
os.environ['OWRT_REMOTE_STATE_DIR'] = state
|
||||
spec = importlib.util.spec_from_file_location('card_details_hub', 'vps/owrt-remote-hub.py')
|
||||
hub = importlib.util.module_from_spec(spec); sys.modules[spec.name] = hub; spec.loader.exec_module(hub)
|
||||
routers = [{
|
||||
'id': 'node-' + str(i), 'name': 'Router ' + str(i), 'online': i != 8,
|
||||
'role': 'node', 'group_id': '', 'last_seen_iso': '2026-11-22T00:00:00Z',
|
||||
'status': {'model': 'Xiaomi Mi Router AX3000T (OpenWrt U-Boot layout)',
|
||||
'release': 'OpenWrt 25.12.5', 'xray': 'running', 'ssh': 'running',
|
||||
'memory': '64 MB free / 234 MB', 'flash': '30 MB free / 60 MB',
|
||||
'uptime': '1000', 'load': '0.1 0.2 0.3', 'temperature': '55'},
|
||||
'permissions': {p: True for p in ('owner','manage','admin','ssh','config','delete','logs')},
|
||||
'ssh_entry_port': 19180 + i, 'admin_url': '/r/node-' + str(i) + '/',
|
||||
'ssh_url': '/ssh/node-' + str(i) + '/', 'config_url': '/config/node-' + str(i),
|
||||
'tachyon': {'installed': True, 'online': True, 'version': '2.0.0-beta.15', 'url': '/tachyon/node-' + str(i) + '/'}
|
||||
} for i in range(1,10)]
|
||||
page = hub.dashboard_html(routers, 'owner', auth_bootstrap={'username':'owner','is_owner':True})
|
||||
Path('.test-output/card-details/dashboard.html').write_text(page, encoding='utf-8')
|
||||
`], {cwd:path.resolve(__dirname, '..')});
|
||||
const html = fs.readFileSync(path.join(output, 'dashboard.html'), 'utf8');
|
||||
const routers = JSON.parse(html.match(/window\.ROUTERS = (\[.*\]);/)[1]);
|
||||
const geometry = page => page.locator('.routerCardSlot').evaluateAll(slots => slots.map(el => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return {x:r.x,y:r.y,width:r.width,height:r.height};
|
||||
}));
|
||||
function sameGrid(before, after, label) {
|
||||
assert.equal(after.length, before.length);
|
||||
for (let i=0; i<before.length; i++) for (const k of ['x','y','width','height']) {
|
||||
assert(Math.abs(before[i][k]-after[i][k])<1, `${label}: slot ${i} ${k} moved`);
|
||||
}
|
||||
}
|
||||
const settled = page => page.waitForFunction(() => cardDetailsAnimations.size === 0);
|
||||
async function fitsViewport(page) {
|
||||
const r = await page.locator('.isFloating>.card').evaluate(el => {
|
||||
const r=el.getBoundingClientRect();
|
||||
return {left:r.left,right:r.right,top:r.top,bottom:r.bottom,w:innerWidth,h:innerHeight};
|
||||
});
|
||||
assert(r.left>=11 && r.right<=r.w-11 && r.top>=11 && r.bottom<=r.h-11, JSON.stringify(r));
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth<=innerWidth));
|
||||
}
|
||||
(async () => {
|
||||
const browser = await chromium.launch({headless:true, channel:'chrome'});
|
||||
let count=0;
|
||||
try {
|
||||
for (const scenario of [
|
||||
{name:'desktop', width:1280,height:900},
|
||||
{name:'two-columns',width:900,height:700},
|
||||
{name:'winter',width:1280,height:900,design:'winter'},
|
||||
{name:'lite',width:1280,height:900,design:'lite',noMotion:true},
|
||||
{name:'reduced-motion',width:1280,height:900,reducedMotion:'reduce',noMotion:true},
|
||||
{name:'portrait',width:390,height:844,mobile:true},
|
||||
{name:'landscape',width:844,height:390,mobile:true},
|
||||
]) {
|
||||
const context=await browser.newContext({viewport:{width:scenario.width,height:scenario.height},
|
||||
hasTouch:!!scenario.mobile,isMobile:!!scenario.mobile,reducedMotion:scenario.reducedMotion || 'no-preference'});
|
||||
try {
|
||||
await context.addInitScript(design => {
|
||||
localStorage.setItem('owrtRemote:hubDesign',design);
|
||||
localStorage.setItem('owrtRemote:seasonEffectMode','off');
|
||||
},scenario.design || 'default');
|
||||
await context.route('**/*', async route => {
|
||||
const u=new URL(route.request().url());
|
||||
if (u.pathname === '/') return route.fulfill({contentType:'text/html; charset=utf-8',body:html});
|
||||
if (u.pathname === '/api/routers') return route.fulfill({json:{routers}});
|
||||
if (u.pathname === '/api/auth/meta') return route.fulfill({json:{ok:true,auth:{username:'owner',is_owner:true}}});
|
||||
if (u.pathname === '/api/notifications/wait') return route.abort();
|
||||
if (u.pathname.startsWith('/api/')) return route.fulfill({json:{ok:true,groups:[],notifications:[]}});
|
||||
return route.abort();
|
||||
});
|
||||
const page=await context.newPage();
|
||||
const errors=[];page.on('pageerror', e=>errors.push(e.message));
|
||||
await page.goto('http://hub.test/',{waitUntil:'domcontentloaded'});
|
||||
await page.locator('.routerCardSlot').nth(8).waitFor();
|
||||
const toggles=page.locator('[data-card-toggle]');
|
||||
assert.equal(await toggles.count(),9,scenario.name);
|
||||
assert.equal(await page.locator('.cardBody:visible').count(),0,'compact at entry');
|
||||
await toggles.first().scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(50);
|
||||
const before=await geometry(page);
|
||||
const docHeight=await page.evaluate(()=>document.documentElement.scrollHeight);
|
||||
await toggles.first().click();
|
||||
assert.equal(await toggles.first().getAttribute('aria-expanded'),'true');
|
||||
if (!scenario.mobile) {
|
||||
assert.equal(await page.locator('.isFloating').count(),1);
|
||||
assert.equal(await page.evaluate(()=>cardDetailsAnimations.size>0),!scenario.noMotion,scenario.name+' animation policy');
|
||||
sameGrid(before,await geometry(page),scenario.name+' during animation');
|
||||
await settled(page);
|
||||
sameGrid(before,await geometry(page),scenario.name+' open');
|
||||
if (scenario.height-before[0].y-12>=400) {
|
||||
assert(Math.abs((await page.locator('.isFloating>.card').boundingBox()).y-before[0].y)<1,'expansion stays anchored when there is room');
|
||||
}
|
||||
assert.equal(await page.evaluate(()=>document.documentElement.scrollHeight),docHeight,'page height stable');
|
||||
await fitsViewport(page);
|
||||
const body=page.locator('.isFloating .cardBody');
|
||||
const scrolled=await body.evaluate(el=>{el.scrollTop=80;return el.scrollTop;});
|
||||
await page.evaluate(()=>loadRouters());
|
||||
await page.waitForTimeout(60);
|
||||
assert.equal(await page.locator('.isFloating .cardBody').evaluate(el=>el.scrollTop),scrolled,'poll preserves scroll');
|
||||
sameGrid(before,await geometry(page),scenario.name+' polling');
|
||||
await toggles.first().focus();
|
||||
await page.evaluate(()=>loadRouters());
|
||||
assert.equal(await toggles.first().evaluate(el=>el===document.activeElement),true,'poll preserves keyboard focus');
|
||||
await toggles.nth(1).click();
|
||||
await settled(page);
|
||||
assert.equal(await page.locator('.isFloating').count(),1,'one desktop expansion');
|
||||
assert.equal(await toggles.first().getAttribute('aria-expanded'),'false');
|
||||
sameGrid(before,await geometry(page),scenario.name+' switch');
|
||||
await page.screenshot({path:path.join(output,scenario.name+'.png'),fullPage:false});
|
||||
await page.keyboard.press('Escape');
|
||||
await settled(page);
|
||||
assert.equal(await page.locator('.isFloating').count(),0,'Escape closes');
|
||||
sameGrid(before,await geometry(page),scenario.name+' close');
|
||||
await toggles.last().scrollIntoViewIfNeeded();
|
||||
await toggles.last().click();await settled(page);await fitsViewport(page);
|
||||
await page.locator('#routerStats').evaluate(el=>el.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true})));
|
||||
await settled(page);
|
||||
assert.equal(await page.locator('.isFloating').count(),0,'outside pointer closes');
|
||||
await page.evaluate(()=>{
|
||||
const toggle=document.querySelector('[data-card-toggle]');
|
||||
toggle.click();toggle.click();toggle.click();
|
||||
});
|
||||
await settled(page);
|
||||
assert.equal(await toggles.first().getAttribute('aria-expanded'),'true','rapid clicks finish open');
|
||||
await toggles.first().click();await settled(page);
|
||||
assert.equal(await page.locator('.isFloating').count(),0,'toggle closes');
|
||||
await toggles.first().scrollIntoViewIfNeeded();
|
||||
await toggles.first().click();await settled(page);
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.waitForFunction(()=>mobileCardsMq.matches && !document.querySelector('.isFloating'));
|
||||
assert.equal(await toggles.first().getAttribute('aria-expanded'),'true','resizing to mobile keeps data open');
|
||||
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'resize has no overflow');
|
||||
} else {
|
||||
assert.equal(await page.locator('.isFloating').count(),0,'mobile stays inline');
|
||||
assert.equal(await page.locator('.cardBody:visible').count(),1);
|
||||
await page.evaluate(()=>loadRouters());
|
||||
assert.equal(await toggles.first().getAttribute('aria-expanded'),'true','mobile poll preserves state');
|
||||
await page.screenshot({path:path.join(output,scenario.name+'.png'),fullPage:false});
|
||||
await toggles.first().click();
|
||||
assert.equal(await page.locator('.cardBody:visible').count(),0);
|
||||
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
||||
}
|
||||
assert.deepEqual(errors,[],scenario.name+' browser errors');
|
||||
count++;console.log('CARD_DETAILS_OK',scenario.name);
|
||||
} finally {await context.close();}
|
||||
}
|
||||
} finally {await browser.close();}
|
||||
console.log('CARD_DETAILS_BROWSER_OK:',count,'scenarios');
|
||||
})().catch(e=>{console.error(e);process.exitCode=1;});
|
||||
@@ -18,7 +18,8 @@ assert(html.includes('Online'));
|
||||
assert(html.includes('href="/tachyon/a/"'));
|
||||
assert(html.includes('tachyonMeta'));
|
||||
assert(html.includes('tachyonAction'));
|
||||
assert(context.renderTachyon({permissions:{admin:true}, tachyon:{installed:true, online:true, url:'/tachyon/a/'}}).includes('Tachyon</strong>'));
|
||||
const withoutVersion = context.renderTachyon({permissions:{admin:true}, tachyon:{installed:true, online:true, url:'/tachyon/a/'}});
|
||||
assert.match(withoutVersion.replace(/<[^>]*>/g, ''), /Tachyon\s*Online/);
|
||||
router.tachyon.online = false;
|
||||
assert(context.renderTachyon(router).includes('Offline'));
|
||||
router.permissions.admin = false;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
& (Join-Path $PSScriptRoot 'deploy-tachyon.ps1') -Vps $Vps -Action $Action `
|
||||
-BackupName donate-ui -BackupVersion v122 -PrepareOnly:$PrepareOnly
|
||||
if (-not $PrepareOnly) { Write-Host "Donate UI $Action finished successfully." }
|
||||
@@ -0,0 +1,12 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# The shared VPS installer validates the source, keeps an independent backup,
|
||||
# replaces Hub atomically and verifies the running source revision after restart.
|
||||
& (Join-Path $PSScriptRoot 'deploy-tachyon.ps1') -Vps $Vps -Action $Action `
|
||||
-BackupName router-card-details -BackupVersion v122 -PrepareOnly:$PrepareOnly
|
||||
if (-not $PrepareOnly) { Write-Host "Router card details $Action finished successfully." }
|
||||
@@ -2,7 +2,7 @@ param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[ValidateSet('tachyon-integration', 'tachyon-layout', 'tachyon-detection')][string]$BackupName = 'tachyon-integration',
|
||||
[ValidateSet('tachyon-integration', 'tachyon-layout', 'tachyon-detection', 'router-card-details', 'donate-ui')][string]$BackupName = 'tachyon-integration',
|
||||
[ValidateSet('v121', 'v122')][string]$BackupVersion = 'v121',
|
||||
[ValidateRange(1, 65535)][int]$Port = 22,
|
||||
[string]$JumpHost = '',
|
||||
|
||||
+480
-27
@@ -114,6 +114,31 @@ ACME_WEBROOT = STATE_DIR / "acme-webroot"
|
||||
# take longer than the old 75-second window while the reverse tunnel remains usable.
|
||||
ONLINE_AFTER_SECONDS = max(75, int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "180")))
|
||||
DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443"))
|
||||
# Fork change (reality-transport): upstream ships the router<->hub hop as plain
|
||||
# VLESS (network=tcp, security=none) — UUID-authenticated but not encrypted, so
|
||||
# LuCI credentials and logs travel in cleartext inside that hop. This fork wraps
|
||||
# it in VLESS+Reality: a real TLS handshake camouflaged against a public dest,
|
||||
# no CA-issued certificates, no renewal. Per-router UUIDs still authenticate.
|
||||
# OWRT_REMOTE_TRANSPORT: tls (default) | reality | none.
|
||||
# tls - self-signed hub cert + pinnedPeerCertSha256 on the router.
|
||||
# Works with the modern tag-form VLESS reverse on xray >= 26.5.
|
||||
# reality - REALITY camouflage. NOTE: tag-form reverse (Rvs control channel)
|
||||
# does NOT register over REALITY on xray 26.7.28/26.11.9
|
||||
# (XTLS/Xray-core #6242/#6248 family); verified broken in e2e
|
||||
# 22.11.2026. The hop itself authenticates fine, so keep this
|
||||
# switch ready for when upstream fixes reverse-over-REALITY.
|
||||
# none - upstream behavior (cleartext hop).
|
||||
TRANSPORT_MODE = os.environ.get("OWRT_REMOTE_TRANSPORT", "tls").strip().lower()
|
||||
TLS_SNI = os.environ.get("OWRT_REMOTE_TLS_SNI", "www.microsoft.com").strip()
|
||||
# NOTE: do NOT default to www.microsoft.com — Microsoft now serves post-quantum
|
||||
# (ML-DSA) cert chains and REALITY cannot re-sign them; the handshake silently
|
||||
# falls back to passthrough ("received real certificate"). Verified working
|
||||
# 22.11.2026 (xray 26.7.28 + 26.11.9, any direction): www.cloudflare.com,
|
||||
# www.apple.com, www.google.com, download.windowsupdate.com, www.jetbrains.com.
|
||||
REALITY_DEST = os.environ.get("OWRT_REMOTE_REALITY_DEST", "www.cloudflare.com").strip()
|
||||
REALITY_FINGERPRINT = os.environ.get("OWRT_REMOTE_REALITY_FINGERPRINT", "chrome").strip()
|
||||
TRANSPORT_FILE = STATE_DIR / "transport.json"
|
||||
XRAY_BINARY = os.environ.get("OWRT_REMOTE_XRAY_BINARY", "/usr/local/bin/xray")
|
||||
REQUEST_QUEUE_SIZE = int(os.environ.get("OWRT_REMOTE_REQUEST_QUEUE_SIZE", "128"))
|
||||
ROUTER_PROXY_LIMIT = max(1, int(os.environ.get("OWRT_REMOTE_ROUTER_PROXY_LIMIT", "4")))
|
||||
PROXY_TIMEOUT = float(os.environ.get("OWRT_REMOTE_PROXY_TIMEOUT", "25"))
|
||||
@@ -4118,6 +4143,7 @@ def router_current_hub_bundle(router, app_public_url="", request_origin="", fall
|
||||
"hub_url": hub_url,
|
||||
"public_url": public_url,
|
||||
"vps_host": config_vps_host,
|
||||
"transport": transport_public_summary(),
|
||||
}
|
||||
return hub_update, hub_url, config_vps_host
|
||||
|
||||
@@ -4621,6 +4647,169 @@ def delete_router_note_entry(conn, router_id, note_id):
|
||||
return get_router(conn, router_id)
|
||||
|
||||
|
||||
def generate_reality_profile():
|
||||
# X25519 keypair via the local xray binary (stdlib has no X25519). Labels
|
||||
# follow `xray x25519` output of the deployed core.
|
||||
binary = XRAY_BINARY if Path(XRAY_BINARY).exists() else (shutil.which("xray") or "")
|
||||
if not binary:
|
||||
raise RuntimeError(f"xray binary not found for Reality keypair generation: {XRAY_BINARY}")
|
||||
result = subprocess.run(
|
||||
[binary, "x25519"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20, check=False,
|
||||
)
|
||||
out = result.stdout or ""
|
||||
private = re.search(r"PrivateKey:\s*(\S+)", out)
|
||||
public = re.search(r"Password \(PublicKey\):\s*(\S+)", out) or re.search(r"Password \(b64\):\s*(\S+)", out)
|
||||
if not private or not public:
|
||||
detail = (result.stderr or out or "").strip()
|
||||
raise RuntimeError(f"`{binary} x25519` returned no keypair: {detail}")
|
||||
return {
|
||||
"mode": "reality",
|
||||
"privateKey": private.group(1),
|
||||
"publicKey": public.group(1),
|
||||
"shortId": secrets.token_hex(4),
|
||||
"serverName": REALITY_DEST,
|
||||
"dest": f"{REALITY_DEST}:443",
|
||||
"fingerprint": REALITY_FINGERPRINT or "chrome",
|
||||
}
|
||||
|
||||
|
||||
def generate_tls_profile():
|
||||
# Self-signed cert via the openssl CLI (stdlib cannot sign). The router
|
||||
# pins the leaf certificate hash (pinnedPeerCertSha256); allowInsecure
|
||||
# was removed from xray >= 26.x, pinning is the supported replacement.
|
||||
import hashlib
|
||||
binary = shutil.which("openssl") or ""
|
||||
if not binary:
|
||||
raise RuntimeError("openssl not found for TLS transport generation")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
crt = os.path.join(tmp, "hub.crt")
|
||||
key = os.path.join(tmp, "hub.key")
|
||||
result = subprocess.run(
|
||||
[binary, "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "3650",
|
||||
"-subj", f"/CN={TLS_SNI}", "-addext", f"subjectAltName=DNS:{TLS_SNI}",
|
||||
"-keyout", key, "-out", crt],
|
||||
text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60, check=False,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"openssl cert generation failed: {(result.stderr or '').strip()[:300]}")
|
||||
cert_pem = open(crt, encoding="utf-8").read()
|
||||
key_pem = open(key, encoding="utf-8").read()
|
||||
der = subprocess.run(
|
||||
[binary, "x509", "-in", crt, "-outform", "der"],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=True,
|
||||
).stdout
|
||||
return {
|
||||
"mode": "tls",
|
||||
"serverName": TLS_SNI,
|
||||
"certificate": cert_pem,
|
||||
"key": key_pem,
|
||||
"pin": hashlib.sha256(der).hexdigest(),
|
||||
"fingerprint": "chrome",
|
||||
}
|
||||
|
||||
|
||||
def transport_profile():
|
||||
if TRANSPORT_MODE not in ("reality", "tls"):
|
||||
return {"mode": "none"}
|
||||
if TRANSPORT_FILE.exists():
|
||||
try:
|
||||
data = json.loads(TRANSPORT_FILE.read_text(encoding="utf-8"))
|
||||
if data.get("mode") == "reality" and data.get("privateKey") and data.get("publicKey"):
|
||||
if TRANSPORT_MODE == "reality":
|
||||
return data
|
||||
if data.get("mode") == "tls" and data.get("certificate") and data.get("key") and data.get("pin"):
|
||||
if TRANSPORT_MODE == "tls":
|
||||
return data
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
data = generate_tls_profile() if TRANSPORT_MODE == "tls" else generate_reality_profile()
|
||||
TRANSPORT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
atomic_write_text(TRANSPORT_FILE, json.dumps(data, ensure_ascii=False, indent=2) + "\n", mode=0o600)
|
||||
try:
|
||||
os.chmod(TRANSPORT_FILE, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
return data
|
||||
|
||||
|
||||
def transport_public_summary():
|
||||
profile = transport_profile()
|
||||
if profile.get("mode") == "tls":
|
||||
return {
|
||||
"mode": "tls",
|
||||
"serverName": profile["serverName"],
|
||||
"pin": profile["pin"],
|
||||
"fingerprint": profile.get("fingerprint", "chrome"),
|
||||
}
|
||||
if profile.get("mode") != "reality":
|
||||
return {"mode": "none"}
|
||||
return {
|
||||
"mode": "reality",
|
||||
"publicKey": profile["publicKey"],
|
||||
"shortId": profile["shortId"],
|
||||
"serverName": profile["serverName"],
|
||||
"fingerprint": profile.get("fingerprint", "chrome"),
|
||||
}
|
||||
|
||||
|
||||
def transport_server_stream():
|
||||
profile = transport_profile()
|
||||
if profile.get("mode") == "tls":
|
||||
return {
|
||||
"network": "tcp",
|
||||
"security": "tls",
|
||||
"tlsSettings": {
|
||||
"certificates": [{
|
||||
"certificate": [profile["certificate"]],
|
||||
"key": [profile["key"]],
|
||||
}],
|
||||
"alpn": ["h2", "http/1.1"],
|
||||
},
|
||||
}
|
||||
if profile.get("mode") != "reality":
|
||||
return {"network": "tcp", "security": "none"}
|
||||
return {
|
||||
"network": "tcp",
|
||||
"security": "reality",
|
||||
"realitySettings": {
|
||||
"show": False,
|
||||
"dest": profile["dest"],
|
||||
"xver": 0,
|
||||
"serverNames": [profile["serverName"]],
|
||||
"shortIds": [profile["shortId"]],
|
||||
"privateKey": profile["privateKey"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def transport_client_stream():
|
||||
profile = transport_profile()
|
||||
if profile.get("mode") == "tls":
|
||||
return {
|
||||
"network": "tcp",
|
||||
"security": "tls",
|
||||
"tlsSettings": {
|
||||
"serverName": profile["serverName"],
|
||||
"pinnedPeerCertSha256": profile["pin"],
|
||||
"alpn": ["h2", "http/1.1"],
|
||||
"fingerprint": profile.get("fingerprint", "chrome"),
|
||||
},
|
||||
}
|
||||
if profile.get("mode") != "reality":
|
||||
return {"network": "tcp", "security": "none"}
|
||||
return {
|
||||
"network": "tcp",
|
||||
"security": "reality",
|
||||
"realitySettings": {
|
||||
"show": False,
|
||||
"fingerprint": profile.get("fingerprint", "chrome"),
|
||||
"serverName": profile["serverName"],
|
||||
"publicKey": profile["publicKey"],
|
||||
"shortId": profile["shortId"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLESS_PORT, decryption="none"):
|
||||
clients = []
|
||||
inbounds = [
|
||||
@@ -4633,10 +4822,7 @@ def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLE
|
||||
"clients": clients,
|
||||
"decryption": decryption,
|
||||
},
|
||||
"streamSettings": {
|
||||
"network": "tcp",
|
||||
"security": "none",
|
||||
},
|
||||
"streamSettings": transport_server_stream(),
|
||||
}
|
||||
]
|
||||
rules = []
|
||||
@@ -4777,7 +4963,7 @@ def make_router_xray_config(row):
|
||||
"flow": row["vless_flow"],
|
||||
"reverse": {"tag": bridge_tag},
|
||||
},
|
||||
"streamSettings": {"network": "tcp", "security": "none"},
|
||||
"streamSettings": transport_client_stream(),
|
||||
},
|
||||
{
|
||||
"tag": "vps-ssh-interconn",
|
||||
@@ -4790,7 +4976,7 @@ def make_router_xray_config(row):
|
||||
"flow": row["vless_flow"],
|
||||
"reverse": {"tag": ssh_bridge_tag},
|
||||
},
|
||||
"streamSettings": {"network": "tcp", "security": "none"},
|
||||
"streamSettings": transport_client_stream(),
|
||||
},
|
||||
],
|
||||
"routing": {
|
||||
@@ -4826,11 +5012,33 @@ def reload_vps_xray(db_path=DB_PATH):
|
||||
init_db(conn)
|
||||
rows = list_router_rows(conn)
|
||||
config = make_server_xray_config(rows)
|
||||
atomic_write_text(out, json.dumps(config, ensure_ascii=False, indent=2) + "\n", mode=0o600)
|
||||
config_text = json.dumps(config, ensure_ascii=False, indent=2) + "\n"
|
||||
# Never replace a live tunnel config with an invalid one: render to a
|
||||
# candidate, let the deployed xray validate it, then swap atomically.
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
candidate = out.parent / (out.name + ".candidate")
|
||||
atomic_write_text(candidate, config_text, mode=0o600)
|
||||
try:
|
||||
os.chmod(candidate, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
binary = XRAY_BINARY if Path(XRAY_BINARY).exists() else (shutil.which("xray") or "")
|
||||
if binary:
|
||||
test = subprocess.run(
|
||||
[binary, "-test", "-config", str(candidate)],
|
||||
text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=False,
|
||||
)
|
||||
if test.returncode != 0:
|
||||
candidate.unlink(missing_ok=True)
|
||||
detail = (test.stderr or test.stdout or "").strip()
|
||||
raise RuntimeError(f"xray -test rejected generated config: {detail}")
|
||||
os.replace(candidate, out)
|
||||
try:
|
||||
os.chmod(out, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
candidate.rename(out)
|
||||
result = subprocess.run(
|
||||
["systemctl", "restart", service],
|
||||
text=True,
|
||||
@@ -4937,6 +5145,18 @@ def build_openwrt_config_payload(row, hub_url, vps_host_override="", public_url_
|
||||
),
|
||||
"public_url": effective_public_url,
|
||||
}
|
||||
profile = transport_profile()
|
||||
if profile.get("mode") == "tls":
|
||||
payload["security"] = "tls"
|
||||
payload["tls_sni"] = profile["serverName"]
|
||||
payload["tls_pin"] = profile["pin"]
|
||||
payload["reality_fingerprint"] = profile.get("fingerprint", "chrome")
|
||||
if profile.get("mode") == "reality":
|
||||
payload["security"] = "reality"
|
||||
payload["reality_public_key"] = profile["publicKey"]
|
||||
payload["reality_short_id"] = profile["shortId"]
|
||||
payload["reality_server_name"] = profile["serverName"]
|
||||
payload["reality_fingerprint"] = profile.get("fingerprint", "chrome")
|
||||
return payload
|
||||
|
||||
|
||||
@@ -4972,6 +5192,13 @@ def build_openwrt_config_lines(payload, mode="manual"):
|
||||
f"uci set owrtremote.main.ssh_host='{sh_quote(payload['ssh_host'])}'",
|
||||
f"uci set owrtremote.main.ssh_port='{payload['ssh_port']}'",
|
||||
f"uci set owrtremote.main.public_url='{sh_quote(payload['public_url'])}'",
|
||||
f"uci set owrtremote.main.security='{sh_quote(payload.get('security', 'none'))}'",
|
||||
f"uci set owrtremote.main.reality_public_key='{sh_quote(payload.get('reality_public_key', ''))}'",
|
||||
f"uci set owrtremote.main.reality_short_id='{sh_quote(payload.get('reality_short_id', ''))}'",
|
||||
f"uci set owrtremote.main.reality_server_name='{sh_quote(payload.get('reality_server_name', ''))}'",
|
||||
f"uci set owrtremote.main.reality_fingerprint='{sh_quote(payload.get('reality_fingerprint', ''))}'",
|
||||
f"uci set owrtremote.main.tls_sni='{sh_quote(payload.get('tls_sni', ''))}'",
|
||||
f"uci set owrtremote.main.tls_pin='{sh_quote(payload.get('tls_pin', ''))}'",
|
||||
"uci commit owrtremote",
|
||||
"owrt-remote render-client",
|
||||
"/etc/init.d/owrt-remote enable",
|
||||
@@ -6372,6 +6599,76 @@ def inject_hub_appearance(path, body, content_type):
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
def donate_payment_logos_html():
|
||||
# Small inline vector marks keep the thank-you page self-contained.
|
||||
return '''<div class="donatePaymentBlock">
|
||||
<div class="donatePaymentBrands" role="img" aria-label="Логотипы: СБП, Сбер, Альфа-Банк, ВТБ, Т-Банк">
|
||||
<span class="donatePaymentBrand paymentSbp"><svg width="23" height="24" viewBox="0 0 24 26" aria-hidden="true" focusable="false"><path fill="#5b57a2" d="M1 1l7 4v8L1 17z"/><path fill="#0d90cd" d="M1 1l7 12H1z"/><path fill="#e5234e" d="M8 5l7 4-7 4z"/><path fill="#f9b229" d="M15 9l8 4-8 4-7-4z"/><path fill="#72b22c" d="M8 13l7 4-7 4z"/><path fill="#00743e" d="M1 17l7-4v8l-7 4z"/><path fill="#0d90cd" d="M8 21l7-4v4l-7 4z"/></svg><span>СБП</span></span>
|
||||
<span class="donatePaymentBrand paymentSber"><svg width="21" height="21" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20.8 10a9 9 0 1 1-6.4-6.7" fill="none" stroke="#21a038" stroke-width="2.5" stroke-linecap="round"/><path d="M7 10.5l4.2 3.2L21 6.2" fill="none" stroke="#21a038" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg><span>СБЕР</span></span>
|
||||
<span class="donatePaymentBrand paymentAlfa"><svg width="21" height="21" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect width="24" height="24" rx="2" fill="#ef3124"/><path fill="#fff" d="M10.3 4h3.4l4.5 13h-3.5l-.8-2.6h-4L9.1 17H5.8zm.4 7.8h2.4L12 7.5zM6 19h12v2H6z"/></svg><span>Альфа Банк</span></span>
|
||||
<span class="donatePaymentBrand paymentVtb"><svg width="21" height="20" viewBox="0 0 24 20" aria-hidden="true" focusable="false"><path fill="#3980d9" d="M6 2h18l-2 4H4zM3 8h18l-2 4H1zM2 14h15l-2 4H0z"/></svg><span>ВТБ</span></span>
|
||||
<span class="donatePaymentBrand paymentTbank"><svg width="21" height="21" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect width="24" height="24" rx="3" fill="#ffdd2d"/><path fill="#1b1b1b" d="M5 5h14v5h-4.5v10h-5V10H5z"/></svg><span>Т-БАНК</span></span>
|
||||
</div>
|
||||
</div>'''
|
||||
|
||||
|
||||
def donate_html():
|
||||
return f"""<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Сказать спасибо — OpenWrt Remote Hub</title>
|
||||
{branding_head_tags()}
|
||||
<style>
|
||||
:root{{--bg:#140d21;--panel:#21192e;--panel2:#30243e;--text:#f7f2ff;--muted:#c4b5d5;--line:rgba(180,150,220,.25);--cyan:#67e8f9;--blue:#7c3aed}}
|
||||
*{{box-sizing:border-box}}
|
||||
body{{margin:0;min-height:100vh;min-height:100svh;display:grid;place-items:center;padding:24px;color:var(--text);background:radial-gradient(ellipse at 0 0,#4b2766,transparent 65%),radial-gradient(ellipse at 100% 100%,#222451,transparent 60%),var(--bg);font:14px/1.65 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}}
|
||||
.donateCard{{position:relative;z-index:1;width:min(100%,560px);padding:30px;border:1px solid var(--line);border-radius:22px;background:var(--panel);box-shadow:0 20px 60px #0004;text-align:center}}
|
||||
.donateHeading{{margin-bottom:22px;text-align:center}}
|
||||
.donateEyebrow{{color:var(--muted);font-size:12px;font-weight:700;letter-spacing:.04em}}
|
||||
h1{{margin:6px 0 0;font-size:26px;line-height:1.3}}
|
||||
.donateTitleTail{{display:inline-block;white-space:nowrap}}
|
||||
.donateLinks{{display:grid;gap:10px;margin-bottom:22px}}
|
||||
.donateLinkCard{{display:grid;justify-items:center;gap:3px;padding:13px 16px;border:1px solid var(--line);border-radius:12px;background:var(--panel2);color:var(--text);text-decoration:none;overflow-wrap:anywhere;text-align:center;transition:border-color .15s ease,background .15s ease}}
|
||||
.donateLinkCard:hover{{border-color:var(--cyan)}}
|
||||
.donateLinkCard:focus-visible,.donateBack:focus-visible{{outline:2px solid var(--cyan);outline-offset:3px}}
|
||||
.donateLinkCard strong{{font-size:13px}}
|
||||
.donateLinkCard span{{color:var(--muted);font-size:13px}}
|
||||
.donateMessage p{{margin:0 0 12px}}
|
||||
.donateMessage p:last-child{{margin-bottom:0}}
|
||||
.donatePaymentBlock{{margin-top:22px;padding-top:18px;border-top:1px solid var(--line)}}
|
||||
.donatePaymentBrands{{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:12px}}
|
||||
.donatePaymentBrand{{display:inline-flex;align-items:center;justify-content:center;gap:5px;min-height:26px;color:var(--text);font-size:11px;font-weight:800;line-height:1.2;white-space:nowrap}}
|
||||
.donatePaymentBrand svg{{display:block;flex:none}}
|
||||
.paymentSber{{color:#36b65c}}.paymentAlfa{{color:#ef5045;font-size:10px}}
|
||||
.paymentVtb,.paymentTbank{{font-weight:900}}
|
||||
@media(max-width:400px){{.donatePaymentBrands{{gap:9px}}.donatePaymentBrand{{gap:4px;font-size:10px}}.paymentAlfa{{font-size:9px}}}}
|
||||
.donateFooter{{margin-top:24px;padding-top:16px;border-top:1px solid var(--line);text-align:center}}
|
||||
.donateBack{{color:var(--muted);font-size:13px;text-underline-offset:4px}}
|
||||
@media(max-width:600px){{body{{padding:12px}}.donateCard{{padding:22px 18px;border-radius:18px}}h1{{font-size:23px}}}}
|
||||
</style>
|
||||
{hub_design_head()}
|
||||
</head>
|
||||
<body>
|
||||
<main class="panel donateCard" aria-labelledby="donateTitle">
|
||||
<header class="donateHeading"><div class="donateEyebrow">OpenWrt Remote Hub</div><h1 id="donateTitle">Сказать спасибо ❤️ <span class="donateTitleTail">Donate 💲</span></h1></header>
|
||||
<div class="donateLinks">
|
||||
<a class="donateLinkCard" href="https://donate.zks95.ugnss.ru" target="_blank" rel="noopener noreferrer"><strong>Основная ссылка:</strong><span>https://donate.zks95.ugnss.ru</span></a>
|
||||
<a class="donateLinkCard" href="https://donate.zks95.ugnss.ru:8443" target="_blank" rel="noopener noreferrer"><strong>Резервная ссылка:</strong><span>https://donate.zks95.ugnss.ru:8443</span></a>
|
||||
</div>
|
||||
<div class="donateMessage">
|
||||
<p><strong>Буду искренне благодарен за любой донат!</strong></p>
|
||||
<p>Совершенно не важно, какая сумма - важна ваша поддержка. Даже небольшой вклад помогает развивать проект и двигаться дальше.</p>
|
||||
<p>Спасибо каждому, кто рядом! Всех обнял! 🤝🚀</p>
|
||||
</div>
|
||||
{donate_payment_logos_html()}
|
||||
<footer class="donateFooter"><a class="donateBack" href="/">Вернуться в Hub</a></footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def dashboard_html(routers, username, sessions=None, notifications=None, auth_bootstrap=None, vps_resources=None):
|
||||
routers_json = json.dumps(routers, ensure_ascii=False)
|
||||
sessions_json = json.dumps(sessions or [], ensure_ascii=False)
|
||||
@@ -6432,6 +6729,19 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{body{{font-size:13px;background-attachment:scroll}}.wrap{{padding:10px}}.top{{gap:12px;padding:14px 0;align-items:flex-start}}.brand,.brand>div{{width:100%}}h1{{font-size:22px;line-height:1.18}}.appBanner{{width:auto;max-width:100%;justify-content:center;min-height:36px;padding:8px 12px}}.links,.headerActions,.summary,.mobileOwnerTools{{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));width:100%;gap:8px;max-width:none}}.links{{margin-top:10px}}.links a,.badge,.headerActions .btn,.mobileOwnerTools .btn,.mobileOwnerTools .badge,.miniStat{{width:100%;min-width:0;padding:9px 10px;font-size:12px}}.headerStack{{margin-top:0;width:100%;min-width:0}}.headerStack .badge{{width:100%;min-width:0}}.authMenu{{position:fixed;left:10px;right:10px;top:74px;width:auto;max-height:calc(100svh - 90px);overflow:auto}}.authMenuHead{{min-height:40px;padding:0 104px 8px 0}}.authMenu h2{{margin:2px 104px 0 0;line-height:1.2}}.authMenuClose{{display:inline-flex;top:0;right:0;min-height:32px;padding:6px 12px}}.cards,.routerGroupCards,.toolbar,.authGrid{{grid-template-columns:1fr}}.authRow{{grid-template-columns:1fr;gap:7px;padding:8px}}.authRowTitle{{font-size:13px}}.authRowMeta{{font-size:11px;line-height:1.3}}.authRouterFlags{{justify-content:flex-start;gap:6px}}.authFlagPill{{min-height:25px;padding:3px 7px;gap:5px}}.authFlagPill input{{width:12px;height:12px;flex-basis:12px}}.authFlagPill span{{font-size:10px}}.routerStats{{grid-template-columns:repeat(3,minmax(0,1fr));gap:5px;margin-bottom:7px}}.statCard{{min-height:52px;padding:7px 6px}}.statCard span{{font-size:8px;letter-spacing:.015em}}.statCard strong{{font-size:20px}}.statCard em{{display:none}}.statCardHead{{min-height:16px}}.statValueRow,.offlineStatRow{{min-height:20px;margin-top:4px}}.offlineMoreBtn{{right:2px;min-height:16px;padding:0 5px;font-size:7px}}.offlinePopover{{right:3px;width:min(230px,calc(100vw - 20px));padding:8px}}.offlineItem{{padding:6px 7px}}.offlineName{{font-size:10px}}.toolbar{{padding:10px;margin:12px 0}}.card.main{{grid-column:span 1}}.card{{padding:12px;min-height:0}}.card>.metaLine,.card>.tagRow{{display:none}}.nameRow{{gap:6px;margin-top:10px}}.nameRow::before{{flex-basis:26px;width:26px;height:26px}}.name{{font-size:12px;max-width:190px}}.nameEditBtn{{flex-basis:26px;width:26px;height:26px}}.mobilePanelToggle,.routerFormToggle{{display:inline-flex}}.routerSearchDock{{width:100%}}.seasonDock{{width:100%}}#mobileSeasonDock{{width:100%;min-width:0;max-width:none;padding:0;border:0;background:none;box-shadow:none;backdrop-filter:none}}.routerSearchToggle,.seasonToggle{{width:100%}}.routerSearchPanel,.seasonPanel{{position:static;width:100%;margin-top:8px}}.routerSearchCard,.seasonCard{{width:100%;min-height:0;padding:10px 11px;border-radius:16px}}.routerSearchTitle{{font-size:11px}}.routerSearchField{{min-height:36px}}.routerSearchMeta{{text-align:center}}.metrics{{grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}}.metric{{padding:8px}}.diagnosticPanel{{padding:12px}}.diagnosticTop{{gap:8px}}.diagnosticTop h2{{font-size:17px}}.diagnosticLead{{font-size:11px}}.diagnosticGrid{{grid-template-columns:1fr;gap:10px}}.diagnosticGrid label{{font-size:13px}}.diagnosticGrid textarea{{min-height:118px;padding:12px 13px;font-size:15px;line-height:1.35}}.diagBlock{{padding:11px}}.actions{{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}}.actions .btn,.actions button{{width:100%;min-width:0;padding:9px 8px;font-size:12px}}.wolControls,.trafficControls{{grid-template-columns:1fr}}.wolField span,.wolMeta{{text-align:center}}.wolControls .btn,.wolControls button,.trafficControls .btn,.trafficControls button{{width:100%}}.trafficSummary{{justify-content:center}}.trafficViewport{{max-height:360px;padding-right:0}}.trafficRowTop{{grid-template-columns:1fr}}.trafficTotalBadge{{min-width:0;text-align:left}}}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{.desktopHeader{{display:none}}#hubMenuPanelHost{{display:block;width:100%}}#hubMenuPanelHost:empty{{display:none}}.mobileOwnerTools{{display:grid;margin:0 0 8px}}.mobileOwnerTools[hidden]{{display:none!important}}.top{{padding:6px 0 0;gap:0}}.mobileSearchDock{{display:block;margin:0}}.mobilePanelToggle,.routerFormToggle,.actionToggle{{width:100%;min-height:38px;margin:7px 0;padding:9px 12px;border-radius:999px;font-size:12px;line-height:1}}.actionToggle{{display:inline-flex}}body.preload-mobile-panels .headerActions,body.preload-mobile-panels .routerFormWrap,body.preload-mobile-panels .mobileOwnerTools{{display:none!important}}.card .actions.mobileCollapsed:not(.open){{display:none}}.cardTop{{gap:0}}}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{.headerActions .badge,.headerActions .btn,.mobileOwnerTools .badge,.mobileOwnerTools .btn{{width:100%;min-width:0;max-width:none}}}}
|
||||
.routerCardSlot{{position:relative;min-width:0;align-self:start}}
|
||||
.routerCardSlot>.card{{min-height:0;width:100%}}
|
||||
.cardDetailsToggle{{display:flex;align-items:center;justify-content:center;gap:9px;width:100%;min-height:36px;margin-top:12px;padding:9px 12px;color:var(--text);border:1px solid var(--line);background:rgba(255,255,255,.08)}}
|
||||
.cardDetailsToggle::after{{content:"";width:7px;height:7px;border-right:2px solid currentColor;border-bottom:2px solid currentColor;transform:translateY(-2px) rotate(45deg);transition:transform .2s ease}}
|
||||
.cardDetailsToggle[aria-expanded="true"]::after{{transform:translateY(2px) rotate(225deg)}}
|
||||
.cardDetailsToggle:focus-visible{{outline:2px solid var(--cyan);outline-offset:3px}}
|
||||
.cardBody{{margin-top:10px;min-width:0}}
|
||||
.routerCardSlot.isFloating{{z-index:45}}
|
||||
.routerCardSlot.isFloating>.card{{position:fixed;display:flex;flex-direction:column;max-height:calc(100vh - 24px);max-height:calc(100dvh - 24px);margin:0;overflow:hidden;background:var(--panel);box-shadow:0 24px 64px rgba(0,0,0,.45)}}
|
||||
.routerCardSlot.isFloating>.card>.cardTop,.routerCardSlot.isFloating>.card>.nameRow,.routerCardSlot.isFloating>.card>.routerCardGroup,.routerCardSlot.isFloating>.card>.cardDetailsToggle{{flex-shrink:0}}
|
||||
.routerCardSlot.isFloating>.card>.nameRow{{align-self:center}}
|
||||
.routerCardSlot.isFloating .cardBody{{min-height:0;overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-gutter:stable;padding:0 3px 3px}}
|
||||
@media(prefers-reduced-motion:reduce){{.cardDetailsToggle::after{{transition:none}}}}
|
||||
@media(max-width:420px){{.links,.headerActions,.summary,.actions,.mobileOwnerTools{{grid-template-columns:1fr}}.metrics{{grid-template-columns:1fr}}.metric.span2{{grid-column:span 1}}}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{.desktopHeader{{width:100%}}.summary{{justify-content:center}}}}
|
||||
@media(min-width:681px){{.trafficPanel{{width:min(100%,332px);justify-self:center;padding:9px 9px 8px;border-radius:10px;gap:9px}}.trafficControls{{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:6px}}.trafficPanel .wolField{{gap:4px;font-size:11px}}.trafficPanel .wolField span{{text-align:center}}.trafficPanel .wolField input{{min-height:32px;padding:0 9px;font-size:13px}}.trafficStatusField .wolMeta{{min-height:32px;font-size:11px;line-height:1.18;text-align:center}}.trafficPanel .btn{{min-height:32px;padding:6px 7px;font-size:11px}}.trafficSummary{{justify-content:center}}.trafficSummaryChip{{min-height:20px;padding:0 7px;font-size:9.5px}}.trafficViewport{{max-height:min(42svh,350px)}}.trafficList{{gap:6px}}.trafficRow{{gap:6px;padding:8px}}.trafficRowTop{{grid-template-columns:1fr;gap:7px}}.trafficIdentity{{text-align:center!important}}.trafficName{{display:block;width:100%;font-size:13px;text-align:center!important}}.trafficMetaLine{{font-size:10px;line-height:1.32;text-align:center!important}}.trafficTotalBadge{{display:grid;width:fit-content;min-width:136px;max-width:186px;justify-self:center!important;margin:0 auto;place-self:center;padding:6px 10px;text-align:center!important}}.trafficTotalBadge span{{font-size:9px}}.trafficTotalBadge strong{{font-size:12px}}.trafficStat{{padding:6px 5px}}.trafficStat span{{font-size:9px}}.trafficStat strong{{font-size:11px}}}}
|
||||
@@ -6501,6 +6811,11 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
.hubUpdateConfirmActions{{gap:8px;margin-top:14px}}
|
||||
.hubUpdateConfirmActions button{{min-height:44px;padding:9px 8px;font-size:12px}}
|
||||
}}
|
||||
.desktopHeader .links .donateLink{{grid-column:1/span 2;min-width:0;max-width:none;min-height:36px;padding:8px 14px;font-size:13px;font-weight:800;line-height:1;white-space:normal;text-align:center}}
|
||||
.links a.appBanner{{border-color:rgba(34,211,238,.38);background:linear-gradient(110deg,rgba(34,211,238,.14),rgba(124,58,237,.24),rgba(236,72,153,.14));box-shadow:0 10px 24px rgba(124,58,237,.16),inset 0 1px 0 rgba(255,255,255,.10)}}
|
||||
.headerActions .donateLinkMobile{{display:none}}
|
||||
@media(min-width:681px) and (max-width:1100px){{.desktopHeaderBottom{{width:100%;grid-template-columns:repeat(4,minmax(0,1fr))}}.desktopHeader .links{{grid-column:1/-1;grid-template-columns:repeat(4,minmax(0,1fr))}}.desktopHeader .links .nethavenTop{{grid-column:3/span 2}}.desktopHeaderBottom>.headerActions{{grid-column:1/-1;grid-template-columns:repeat(5,minmax(0,1fr))}}}}
|
||||
@media(max-width:680px),(max-width:1024px) and (orientation:landscape) and (pointer:coarse){{.headerActions .donateLinkMobile{{display:flex;grid-column:1/-1;min-height:36px;padding:8px 12px;font-size:13px;font-weight:800;line-height:1}}}}
|
||||
</style>
|
||||
{hub_design_head()}
|
||||
</head>
|
||||
@@ -6573,14 +6888,14 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
</div>
|
||||
<div class="desktopHeaderBottom">
|
||||
<div class="links">
|
||||
<a href="https://t.me/kzolotarev95" target="_blank" rel="noopener noreferrer">Telegram</a>
|
||||
<a href="https://github.com/kzolotarev95" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<a class="appBanner donateLink" href="/donate/" target="_blank" rel="noopener noreferrer"><span>Сказать спасибо ❤️ Donate 💲</span></a>
|
||||
<a class="nethavenTop" href="https://t.me/+LZDsQJhUfcNhYWEy" target="_blank" rel="noopener noreferrer">NetHaven VPN</a>
|
||||
</div>
|
||||
<div class="headerActions">
|
||||
<a class="badge" id="vpsTerminalLink" href="/vps-terminal/" target="_blank" rel="noopener noreferrer" {'hidden' if not is_owner else ''}>Терминал VPS</a>
|
||||
<button class="badge" id="xrayReload" type="button" {'hidden' if not is_owner else ''}>Обновить Xray CFG</button>
|
||||
<button class="badge" id="xrayRestart" type="button" {'hidden' if not is_owner else ''}>Рестарт Xray VPS</button>
|
||||
<a class="badge donateLinkMobile" href="/donate/" target="_blank" rel="noopener noreferrer">Сказать спасибо ❤️ Donate 💲</a>
|
||||
<button class="badge authToggle" id="authToggle" type="button">{safe_username}</button>
|
||||
<a class="btn" href="/logout">Выйти</a>
|
||||
<div class="authMenu" id="authMenu" hidden>
|
||||
@@ -7034,6 +7349,8 @@ const diagnosticSummary = document.getElementById('diagnosticSummary');
|
||||
const diagnosticBlocks = document.getElementById('diagnosticBlocks');
|
||||
const expandedActionPanels = new Set();
|
||||
const expandedCardDetails = new Set();
|
||||
const cardDetailsAnimations = new Map();
|
||||
let cardDetailsPositionFrame = 0;
|
||||
const expandedGroupPickers = new Set();
|
||||
const diagnosticDrafts = new Map();
|
||||
const noteStateByRouter = new Map();
|
||||
@@ -7204,6 +7521,128 @@ function syncActionToggleStates(root = cards) {{
|
||||
}});
|
||||
}}
|
||||
|
||||
function positionCardDetails(card) {{
|
||||
const slot = card.parentElement;
|
||||
if (!slot.classList.contains('isFloating')) return;
|
||||
const rect = slot.getBoundingClientRect();
|
||||
const gap = 12;
|
||||
card.style.width = Math.min(rect.width, window.innerWidth - gap * 2) + 'px';
|
||||
card.style.left = Math.max(gap, Math.min(rect.left, window.innerWidth - card.offsetWidth - gap)) + 'px';
|
||||
const roomBelow = window.innerHeight - gap - Math.max(gap, rect.top);
|
||||
const minimum = Math.min(400, window.innerHeight - gap * 2);
|
||||
const maximum = Math.min(720, window.innerHeight - gap * 2);
|
||||
// Grow down from the card when there is room; lift it only at the viewport edge.
|
||||
card.style.maxHeight = (roomBelow >= minimum ? Math.min(maximum, roomBelow) : maximum) + 'px';
|
||||
const height = card.getBoundingClientRect().height;
|
||||
card.style.top = Math.max(gap, Math.min(rect.top, window.innerHeight - height - gap)) + 'px';
|
||||
}}
|
||||
|
||||
function resetCardDetailsPosition(card) {{
|
||||
card.parentElement.classList.remove('isFloating');
|
||||
card.parentElement.style.height = '';
|
||||
card.style.removeProperty('width');
|
||||
card.style.removeProperty('left');
|
||||
card.style.removeProperty('top');
|
||||
card.style.removeProperty('max-height');
|
||||
}}
|
||||
|
||||
function setCardDetailsExpanded(body, open, animate = true) {{
|
||||
const card = body.closest('.card');
|
||||
const slot = card.parentElement;
|
||||
const toggle = card.querySelector('[data-card-toggle]');
|
||||
const previousAnimation = cardDetailsAnimations.get(body.id);
|
||||
const before = card.getBoundingClientRect();
|
||||
if (previousAnimation) {{
|
||||
cardDetailsAnimations.delete(body.id);
|
||||
previousAnimation.cancel();
|
||||
}}
|
||||
if (open && !mobileCardsMq.matches) {{
|
||||
cards.querySelectorAll('.routerCardSlot.isFloating .cardBody').forEach(other => {{
|
||||
if (other !== body) setCardDetailsExpanded(other, false, false);
|
||||
}});
|
||||
}}
|
||||
if (open) expandedCardDetails.add(body.id);
|
||||
else expandedCardDetails.delete(body.id);
|
||||
toggle.setAttribute('aria-expanded', String(open));
|
||||
toggle.textContent = open ? 'Скрыть данные' : 'Открыть данные';
|
||||
body.inert = !open;
|
||||
const finishClose = () => {{
|
||||
body.hidden = true;
|
||||
resetCardDetailsPosition(card);
|
||||
}};
|
||||
const motion = animate && !mobileCardsMq.matches && typeof card.animate === 'function'
|
||||
&& document.documentElement.dataset.hubDesign !== 'lite'
|
||||
&& !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
let after;
|
||||
if (open) {{
|
||||
// Measure the compact card before taking its expanded copy out of the grid.
|
||||
body.hidden = true;
|
||||
resetCardDetailsPosition(card);
|
||||
if (!mobileCardsMq.matches) {{
|
||||
slot.style.height = card.getBoundingClientRect().height + 'px';
|
||||
slot.classList.add('isFloating');
|
||||
}}
|
||||
body.hidden = false;
|
||||
positionCardDetails(card);
|
||||
after = card.getBoundingClientRect();
|
||||
}} else if (slot.classList.contains('isFloating') && motion) {{
|
||||
after = slot.getBoundingClientRect();
|
||||
}} else {{
|
||||
finishClose();
|
||||
return;
|
||||
}}
|
||||
if (!motion) return;
|
||||
const animation = card.animate([
|
||||
{{height: before.height + 'px', transform: open ? `translateY(${{before.top - after.top}}px)` : 'none'}},
|
||||
{{height: after.height + 'px', transform: open ? 'none' : `translateY(${{after.top - before.top}}px)`}}
|
||||
], {{duration: 230, easing: 'cubic-bezier(.2,.8,.2,1)'}});
|
||||
cardDetailsAnimations.set(body.id, animation);
|
||||
animation.finished.then(() => {{
|
||||
if (cardDetailsAnimations.get(body.id) !== animation) return;
|
||||
cardDetailsAnimations.delete(body.id);
|
||||
if (!open) finishClose();
|
||||
flushDeferredRouterRender();
|
||||
}}).catch(() => {{}});
|
||||
}}
|
||||
|
||||
function syncCardDetails() {{
|
||||
cardDetailsAnimations.forEach(animation => animation.cancel());
|
||||
cardDetailsAnimations.clear();
|
||||
cards.querySelectorAll('.cardBody').forEach(body => {{
|
||||
setCardDetailsExpanded(body, expandedCardDetails.has(body.id), false);
|
||||
}});
|
||||
}}
|
||||
|
||||
function closeDesktopCardDetails(restoreFocus = false) {{
|
||||
if (mobileCardsMq.matches) return;
|
||||
cards.querySelectorAll('.routerCardSlot.isFloating .cardBody').forEach(body => {{
|
||||
if (!expandedCardDetails.has(body.id)) return;
|
||||
if (restoreFocus) body.closest('.card').querySelector('[data-card-toggle]').focus({{preventScroll: true}});
|
||||
setCardDetailsExpanded(body, false);
|
||||
}});
|
||||
}}
|
||||
|
||||
document.addEventListener('pointerdown', ev => {{
|
||||
if (!ev.target.closest('.routerCardSlot.isFloating')) closeDesktopCardDetails();
|
||||
}});
|
||||
document.addEventListener('keydown', ev => {{
|
||||
if (ev.key === 'Escape' && !ev.defaultPrevented) closeDesktopCardDetails(true);
|
||||
}});
|
||||
function scheduleCardDetailsPosition() {{
|
||||
if (cardDetailsPositionFrame || mobileCardsMq.matches) return;
|
||||
cardDetailsPositionFrame = window.requestAnimationFrame(() => {{
|
||||
cardDetailsPositionFrame = 0;
|
||||
cards.querySelectorAll('.routerCardSlot.isFloating>.card').forEach(card => {{
|
||||
const rect = card.parentElement.getBoundingClientRect();
|
||||
if (rect.bottom < 0 || rect.top > window.innerHeight) {{
|
||||
setCardDetailsExpanded(card.querySelector('.cardBody'), false, false);
|
||||
}} else positionCardDetails(card);
|
||||
}});
|
||||
}});
|
||||
}}
|
||||
window.addEventListener('scroll', scheduleCardDetailsPosition, {{passive: true}});
|
||||
window.addEventListener('resize', scheduleCardDetailsPosition, {{passive: true}});
|
||||
|
||||
function getDiagnosticDraft(routerId) {{
|
||||
const key = String(routerId || '');
|
||||
if (!diagnosticDrafts.has(key)) {{
|
||||
@@ -7273,7 +7712,7 @@ function activeWolInteractiveField() {{
|
||||
}}
|
||||
|
||||
function shouldDeferRouterRender() {{
|
||||
return Boolean(activeWolInteractiveField());
|
||||
return Boolean(activeWolInteractiveField() || cardDetailsAnimations.size);
|
||||
}}
|
||||
|
||||
function clearPendingWolBlurFlush() {{
|
||||
@@ -8461,7 +8900,8 @@ function renderTachyon(router) {{
|
||||
const button = (router.permissions || {{}}).admin
|
||||
? `<a class="btn" href="${{escapeAttr(t.url)}}" target="_blank" rel="noopener noreferrer">Открыть Tachyon</a>`
|
||||
: '<span class="btn disabled">Открыть Tachyon</span>';
|
||||
return `<div class="tachyonIntegration" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:10px;margin-top:10px;border:1px solid var(--line,rgba(180,150,220,.25));border-radius:12px"><div class="tachyonMeta" style="display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px;min-height:24px;max-width:100%"><strong style="min-width:0;max-width:100%;overflow-wrap:anywhere;text-align:center">Tachyon${{t.version ? ' ' + escapeHtml(t.version) : ''}}</strong><span style="color:${{t.online ? '#74e3ac' : '#f2bc6b'}}">${{label}}</span></div><div class="tachyonAction">${{button}}</div></div>`;
|
||||
const crown = '<svg class="tachyonCrown" width="18" height="16" viewBox="0 0 24 20" style="flex:0 0 18px;color:#fbbf24" aria-hidden="true" focusable="false"><path fill="currentColor" d="M3 5l4.5 4L12 2l4.5 7L21 5l-2 10H5z"/><path fill="#f59e0b" d="M5 16h14v3H5z"/><g fill="#fde68a"><circle cx="3" cy="4" r="1.5"/><circle cx="12" cy="2" r="1.5"/><circle cx="21" cy="4" r="1.5"/></g></svg>';
|
||||
return `<div class="tachyonIntegration" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:10px;margin-top:10px;border:1px solid var(--line,rgba(180,150,220,.25));border-radius:12px"><div class="tachyonMeta" style="display:flex;align-items:center;justify-content:center;gap:8px;min-height:40px;max-width:100%"><strong class="tachyonName" style="display:inline-flex;align-items:center;justify-content:center;gap:5px;min-width:0;max-width:100%;text-align:center">${{crown}}<span style="min-width:0;overflow-wrap:anywhere">Tachyon${{t.version ? ' ' + escapeHtml(t.version) : ''}}</span></strong><span class="status tachyonStatus${{t.online ? '' : ' off'}}" style="flex-shrink:0"><i aria-hidden="true"></i>${{label}}</span></div><div class="tachyonAction">${{button}}</div></div>`;
|
||||
}}
|
||||
|
||||
function render(list) {{
|
||||
@@ -8516,7 +8956,7 @@ function render(list) {{
|
||||
const actionsId = actionPanelId(r.id);
|
||||
const actionsOpen = expandedActionPanels.has(actionsId);
|
||||
const detailsId = 'router-details-' + String(r.id).replace(/[^a-zA-Z0-9_-]/g, '-');
|
||||
const collapseCards = mobileCardsMq.matches && !expandedCardDetails.has(detailsId);
|
||||
const collapseCards = !expandedCardDetails.has(detailsId);
|
||||
const groupHeading = idx === 0 || groupName(groupedList[idx - 1].group_id) !== groupName(r.group_id)
|
||||
? `<div class="routerGroupHeading"><span>${{escapeHtml(groupName(r.group_id))}}</span><em>${{groupedList.filter((item) => groupName(item.group_id) === groupName(r.group_id)).length}} роутера</em></div>`
|
||||
: '';
|
||||
@@ -8532,13 +8972,13 @@ function render(list) {{
|
||||
metricHtml('Температура', formatTemperatureHtml(temperature), tempClass(temperature)),
|
||||
metric('Нагрузка', load, 'span2')
|
||||
].join('');
|
||||
return `${{groupHeading}}<article class="card ${{isMain ? 'main' : ''}} ${{online ? 'online' : 'off'}}">
|
||||
return `${{groupHeading}}<div class="routerCardSlot"><article class="card ${{isMain ? 'main' : ''}} ${{online ? 'online' : 'off'}}">
|
||||
<div class="cardTop">
|
||||
<div class="status ${{stateClass}}"><i></i>${{stateText}}</div>
|
||||
</div>
|
||||
<div class="nameRow"><div class="name">${{escapeHtml(r.name)}}</div>${{renameButton}}</div>
|
||||
${{mobileCardsMq.matches ? `<button class="mobileToggle" type="button" data-card-toggle="${{escapeAttr(detailsId)}}" aria-expanded="${{collapseCards ? 'false' : 'true'}}">${{collapseCards ? 'Открыть данные' : 'Скрыть данные'}}</button>` : ''}}
|
||||
<div class="cardBody" id="${{escapeAttr(detailsId)}}"${{collapseCards ? ' hidden' : ''}}>
|
||||
<button class="mobileToggle cardDetailsToggle" type="button" data-card-toggle="${{escapeAttr(detailsId)}}" aria-controls="${{escapeAttr(detailsId)}}" aria-expanded="${{collapseCards ? 'false' : 'true'}}">${{collapseCards ? 'Открыть данные' : 'Скрыть данные'}}</button>
|
||||
<div class="cardBody" id="${{escapeAttr(detailsId)}}" role="region" aria-label="${{escapeAttr('Данные роутера ' + (r.name || r.id))}}"${{collapseCards ? ' hidden' : ''}}>
|
||||
<div class="metrics">
|
||||
${{metricsHtml}}
|
||||
</div>
|
||||
@@ -8555,9 +8995,10 @@ function render(list) {{
|
||||
</div>
|
||||
${{wolReady ? renderWolPanelResponsive(r) : ''}}
|
||||
</div>
|
||||
</article>`;
|
||||
</article></div>`;
|
||||
}}).join('');
|
||||
syncActionToggleStates();
|
||||
syncCardDetails();
|
||||
}}
|
||||
|
||||
function escapeHtml(s) {{
|
||||
@@ -8724,7 +9165,7 @@ render = function(list) {{
|
||||
const actionsId = actionPanelId(r.id);
|
||||
const actionsOpen = expandedActionPanels.has(actionsId);
|
||||
const detailsId = 'router-details-' + String(r.id).replace(/[^a-zA-Z0-9_-]/g, '-');
|
||||
const collapseCards = mobileCardsMq.matches && !expandedCardDetails.has(detailsId);
|
||||
const collapseCards = !expandedCardDetails.has(detailsId);
|
||||
const routerKey = String(r.id || '');
|
||||
const groupPickerOpen = expandedGroupPickers.has(routerKey);
|
||||
const selectedGroupName = groupName(r.group_id);
|
||||
@@ -8755,14 +9196,14 @@ render = function(list) {{
|
||||
metricHtml('Температура', formatTemperatureHtml(temperature), tempClass(temperature)),
|
||||
metric('Нагрузка', load, 'span2')
|
||||
].join('');
|
||||
return `${{groupStart}}<article class="card ${{isMain ? 'main' : ''}} ${{online ? 'online' : 'off'}}">
|
||||
return `${{groupStart}}<div class="routerCardSlot"><article class="card ${{isMain ? 'main' : ''}} ${{online ? 'online' : 'off'}}">
|
||||
<div class="cardTop">
|
||||
<div class="status ${{stateClass}}"><i></i>${{stateText}}</div>
|
||||
</div>
|
||||
<div class="nameRow"><div class="name">${{escapeHtml(r.name)}}</div>${{renameButton}}</div>
|
||||
${{groupSelectHtml}}
|
||||
${{mobileCardsMq.matches ? `<button class="mobileToggle" type="button" data-card-toggle="${{escapeAttr(detailsId)}}" aria-expanded="${{collapseCards ? 'false' : 'true'}}">${{collapseCards ? 'Открыть данные' : 'Скрыть данные'}}</button>` : ''}}
|
||||
<div class="cardBody" id="${{escapeAttr(detailsId)}}"${{collapseCards ? ' hidden' : ''}}>
|
||||
<button class="mobileToggle cardDetailsToggle" type="button" data-card-toggle="${{escapeAttr(detailsId)}}" aria-controls="${{escapeAttr(detailsId)}}" aria-expanded="${{collapseCards ? 'false' : 'true'}}">${{collapseCards ? 'Открыть данные' : 'Скрыть данные'}}</button>
|
||||
<div class="cardBody" id="${{escapeAttr(detailsId)}}" role="region" aria-label="${{escapeAttr('Данные роутера ' + (r.name || r.id))}}"${{collapseCards ? ' hidden' : ''}}>
|
||||
${{notesPreview ? `<div class="notesPreview"><strong>Заметки:</strong> <span>${{escapeHtml(notesPreview)}}</span></div>` : ''}}
|
||||
<div class="metrics">
|
||||
${{metricsHtml}}
|
||||
@@ -8781,14 +9222,18 @@ render = function(list) {{
|
||||
</div>
|
||||
${{wolReady ? renderWolPanelResponsive(r) : ''}}
|
||||
</div>
|
||||
</article>${{groupEnd}}`;
|
||||
</article></div>${{groupEnd}}`;
|
||||
}}).join('');
|
||||
syncActionToggleStates();
|
||||
syncCardDetails();
|
||||
}};
|
||||
|
||||
function renderRouterView() {{
|
||||
const pageScrollX = window.scrollX || window.pageXOffset || 0;
|
||||
const pageScrollY = window.scrollY || window.pageYOffset || 0;
|
||||
const cardDetailsScrollTops = new Map();
|
||||
cards.querySelectorAll('.cardBody').forEach(body => cardDetailsScrollTops.set(body.id, body.scrollTop));
|
||||
const focusedCardToggle = document.activeElement?.dataset?.cardToggle;
|
||||
const wolPickerScrollTops = new Map();
|
||||
document.querySelectorAll('[data-wol-picker-list]').forEach((list) => {{
|
||||
const routerId = String(list.dataset.wolPickerList || '');
|
||||
@@ -8805,6 +9250,14 @@ function renderRouterView() {{
|
||||
return;
|
||||
}}
|
||||
render(visibleRouters);
|
||||
cardDetailsScrollTops.forEach((scrollTop, id) => {{
|
||||
const body = document.getElementById(id);
|
||||
if (body) body.scrollTop = scrollTop;
|
||||
}});
|
||||
if (focusedCardToggle) {{
|
||||
const body = document.getElementById(focusedCardToggle);
|
||||
body?.closest('.card').querySelector('[data-card-toggle]')?.focus({{preventScroll: true}});
|
||||
}}
|
||||
if (pendingRouterViewRestore) {{
|
||||
window.cancelAnimationFrame(pendingRouterViewRestore);
|
||||
pendingRouterViewRestore = 0;
|
||||
@@ -8816,6 +9269,7 @@ function renderRouterView() {{
|
||||
if (list) list.scrollTop = scrollTop;
|
||||
}});
|
||||
pendingRouterViewRestore = 0;
|
||||
scheduleCardDetailsPosition();
|
||||
}});
|
||||
}}
|
||||
|
||||
@@ -9608,15 +10062,11 @@ cards.addEventListener('click', async (ev) => {{
|
||||
ev.stopPropagation();
|
||||
return;
|
||||
}}
|
||||
const toggleId = ev.target?.dataset?.cardToggle;
|
||||
const toggleId = ev.target.closest('[data-card-toggle]')?.dataset.cardToggle;
|
||||
if (toggleId) {{
|
||||
const body = document.getElementById(toggleId);
|
||||
if (!body) return;
|
||||
body.hidden = !body.hidden;
|
||||
if (body.hidden) expandedCardDetails.delete(toggleId);
|
||||
else expandedCardDetails.add(toggleId);
|
||||
ev.target.setAttribute('aria-expanded', body.hidden ? 'false' : 'true');
|
||||
ev.target.textContent = body.hidden ? 'Открыть данные' : 'Скрыть данные';
|
||||
setCardDetailsExpanded(body, !expandedCardDetails.has(toggleId));
|
||||
return;
|
||||
}}
|
||||
const actionsToggleId = ev.target?.dataset?.actionsToggle;
|
||||
@@ -19907,6 +20357,9 @@ exit 127
|
||||
if path == "/ssh-key-manual/":
|
||||
self.send_bytes(200, ssh_key_manual_html().encode("utf-8"), "text/html; charset=utf-8")
|
||||
return
|
||||
if path in ("/donate", "/donate/"):
|
||||
self.send_bytes(200, donate_html().encode("utf-8"), "text/html; charset=utf-8")
|
||||
return
|
||||
if path == "/logout":
|
||||
revoke_hub_session(token=self.current_session_token())
|
||||
self.redirect("/login", [("Set-Cookie", self.clear_session_cookie())])
|
||||
|
||||
Reference in new issue
Block a user