8 Commits
Author SHA1 Message Date
cyril 87ac016293 fork: docs — xray 26.4.25 tested too: tag-form reverse over REALITY fails there as well (only legacy domain-form reverse works on pre-26.5 cores) 2026-11-22 12:47:41 +03:00
cyril 05972f8c24 fork: security=tls (self-signed + pinnedPeerCertSha256) becomes the default hop transport
reverse-over-REALITY is broken on xray >= 26.7 (Rvs control channel never
registers; XTLS/Xray-core #6242/#6248 family). Verified loopback e2e with
hub-generated configs on 26.11.9<->26.11.9 and 26.11.9<->26.7.28: portal
entry-* -> reverse mux -> router-admin redirect = HTTP 200 over pinned TLS.

- hub: OWRT_REMOTE_TRANSPORT=tls|reality|none (default tls); generates
  self-signed cert (openssl) + exposes pin; serves tls streamSettings.
- agent: uci tls_sni/tls_pin, validation, tls branch in render_client_config.
- CGI: reality_short_id/tls_sni/tls_pin fields; uci config lines extended.
- docs: REALITY_TRANSPORT.md extended with the bisect results and pitfalls
  (freedom finalRules for reverse egress, bridge registers ~2s late,
  legacy reverse objects removed).
2026-11-22 12:28:43 +03:00
cyril d482ed97c4 fork: REALITY client must carry shortId; default camo moved off www.microsoft.com
Verified 22.11.2026 (xray 26.7.28 + 26.11.9, matrix of 4 version pairs):
- REALITY authenticates fine both directions ONLY when the client
  realitySettings includes "shortId"; without it the server silently
  falls back to passthrough ("received real certificate").
- dest www.microsoft.com is broken for REALITY MITM (Microsoft now
  serves post-quantum cert chains); www.cloudflare.com / www.apple.com /
  www.google.com / download.windowsupdate.com / www.jetbrains.com all work.
- hub transport: expose shortId in summary/payload/uci line; agent reads
  uci reality_short_id and emits "shortId" in realitySettings.

NOTE: new tag-form VLESS reverse (Rvs, PR #5101) does NOT register its
control connection when the bridge transport is REALITY on xray >= 26.7
(portal logs show handshake auth OK but no v1.rvs.cool request;
security=none works). See XTLS/Xray-core #6242 #6248. Reverse-over-REALITY
e2e therefore blocked pending core-version bisect (26.4.25) or upstream fix.
2026-11-22 12:15:22 +03:00
cyril-fork 9b7a89257b fork: REALITY transport for the router<->hub VLESS hop
Upstream ships the router<->hub hop as plain VLESS (tcp, security=none):
UUID-authenticated but cleartext — LuCI credentials and logs inside the
hop are readable by anyone on-path. This fork wraps the hop in
VLESS+Reality (TLS handshake camouflaged against a public dest, no CA
certs, no renewal):

- vps/owrt-remote-hub.py: transport profile (STATE_DIR/transport.json,
  x25519 keypair via the xray binary), reality streamSettings in the
  server inbound and in make_router_xray_config(), uci transport lines
  in the generated OpenWrt config, transport block in heartbeat
  hub_update, and xray -test gate before swapping /etc/xray config.
- files/usr/sbin/owrt-remote: security/reality_* uci options,
  validation, reality streamSettings in render_client_config,
  security-aware compat probe and core-compat checks.
- files/etc/config/owrtremote, cgi form fields, PKG_RELEASE bump.

Env on the hub: OWRT_REMOTE_TRANSPORT=reality|none,
OWRT_REMOTE_REALITY_DEST/FINGERPRINT, OWRT_REMOTE_XRAY_BINARY.

NOTE: xray-core >= 26.9.8 REALITY servers reject client hellos
(XTLS/Xray-core#7259) — pin the hub core to 26.7.28 until upstream fixes it.
2026-11-22 11:22:49 +03:00
kzolotarev95 9dead7741d Update README.md 2026-11-22 02:38:21 +04:00
kzolotarev95 ce763dd1be Improve Hub card expansion, Tachyon badges and donation page 2026-11-22 02:35:28 +04:00
kzolotarev95 9c8def5e5c Verify previous release packages using GitHub asset digests 2026-11-22 00:13:16 +04:00
kzolotarev95 927aec8ffe Fix Tachyon APK discovery and release package revision 122-r2
OpenWrt IPK and APK / Validate source and resolve stable SDKs (push) Waiting to run
2026-11-22 00:07:08 +04:00
28 changed files with 1420 additions and 97 deletions

No files matched your search

+4 -2
View File
@@ -51,10 +51,10 @@ jobs:
import os, subprocess, sys
sys.path.insert(0, 'scripts')
import openwrt_package as p
expected = 'v' + p.versions()[0]
expected = p.release_tag()
tag = os.environ['RELEASE_TAG'] or expected
if os.environ['PUBLISH_REQUESTED'] == 'true' and tag != expected:
raise SystemExit('Release tag must match PKG_VERSION in package/luci-app-owrt-remote/Makefile')
raise SystemExit('Release tag must match PKG_VERSION and PKG_RELEASE (vVERSION or vVERSION-rREVISION)')
if os.environ['MANUAL_PUBLISH'] == 'true':
# Retry corrected build tooling without moving an existing tag.
# Runtime files must match; packaging tools/metadata may be fixed.
@@ -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 \
+29
View File
@@ -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
```
+1 -21
View File
@@ -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>
@@ -205,6 +184,7 @@ owrt-remote status
IPK для OpenWrt 23.05/24.10 и APK для 25.12. Пакеты
архитектурно независимые (`all`/`noarch`): содержат тот же агент и LuCI-файлы,
что и `install.sh`, сохраняют `/etc/config/owrtremote` и существующий Xray.
Версия интерфейса — v122, исправленная пакетная ревизия — 122-r2.
GitHub Actions проверяет SDK разных архитектур, установку/обновление/удаление
в OpenWrt VM и при выпуске тега `v*` прикладывает пакеты к GitHub Release.
Для APK в штатной LuCI нужен доверенный ключ подписи; неподписанный локальный
+7 -3
View File
@@ -144,13 +144,17 @@ Workflow `.github/workflows/openwrt-packages.yml` запускается на т
публикации Release, изменениях пакета в pull request и вручную. В PR и при
обычном ручном запуске он только собирает и тестирует. Для повторной публикации
после исправления сборочного инструмента доступен ручной запуск с
`publish_release=true` и существующим `release_tag`, например `v122`.
`publish_release=true` и существующим `release_tag`, например `v122-r2`.
Он не перемещает тег и проверяет, что содержимое `files/` и установочные
помощники совпадают с этим тегом. Рецепт и инструменты сборки могут содержать
исправления; точный commit сборки записывается в отчёте. После проверок
пакеты прикладываются к Release.
Тег должен совпадать с `PKG_VERSION`: текущий пример — `v122`.
Следующий выпуск должен получить новую версию или пакетную ревизию в Makefile.
Первая пакетная ревизия версии использует тег `vVERSION`, следующие —
`vVERSION-rREVISION`. Например, `PKG_VERSION=122`, `PKG_RELEASE=2` соответствуют
тегу `v122-r2`; версия интерфейса остаётся v122. Старый тег v122 и его пакеты
122-r1 сохраняются. Для новой версии интерфейса пакетная ревизия начинается с 1.
При выпуске ревизии CI дополнительно скачивает предыдущий опубликованный пакет,
проверяет его SHA256 и проверяет настоящее обновление с него на новый пакет.
На каждом запуске выбирается последняя стабильная patch-версия веток
23.05, 24.10 и 25.12. Матрица `package/openwrt-targets.json` содержит 10 SDK
+88
View File
@@ -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.
+40
View File
@@ -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. Проверяет координаты сетки во время анимации,
раскрытие/закрытие, границы экрана, быстрые повторные клики, обновление статусов,
прокрутку, фокус клавиатуры и переход с ПК на мобильный размер. Сценарии включают
три дизайна, уменьшенную анимацию, две колонки и обе ориентации телефона.
+68
View File
@@ -3,6 +3,74 @@
Интеграция включена в Remote Hub v122. Обновить нужно Hub на VPS и агент
на роутере; Tachyon устанавливается отдельно и автоматически не загружается.
## Исправление APK 3.0.5 в пакетах 122-r2
На node-12 с OpenWrt 25.12.5 команда `apk info -v tachyon` вернула описание,
а не версию. Прежний парсер ожидал `tachyon-VERSION`, получил пустую строку
и выбрал старую LuCI-страницу вместо самостоятельной панели на порту 1680.
Поэтому в карточке исчезла версия, а кнопка открывала LuCI с внешней ссылкой.
Теперь версия читается через `apk list --installed --manifest`, с резервным
структурированным `apk query`. Наличие самостоятельного интерфейса подтверждает
локальный read-only API `/api/agent/v1/health`; старый номер пакета не мешает
обнаружить работающий современный интерфейс. HTTP 403 страницы LuCI сам по себе
не означает, что неизвестный Tachyon работает. Версия работающего приложения
по-прежнему берётся из его OpenAPI, если он доступен.
Блок карточки имеет две строки: название/версия/состояние и ниже кнопка.
Отсутствие версии больше не переносит кнопку в верхнюю строку и не меняет высоту
обычного блока. Проверены ПК, мобильная вертикальная и горизонтальная ориентация.
Установить исправление интерфейса VPS из локальных исходников:
```powershell
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-tachyon-detection-fix.ps1'
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Install
```
Установить агент на удалённый node-12 через существующий SSH-туннель VPS:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -RouterId node-12 -Action Install
```
SSH отдельно запрашивает пароль VPS и пароль выбранного роутера; они могут
отличаться. Скрипт читает `ssh_entry_port` выбранного роутера из базы в режиме
read-only и подключается через ProxyJump. Туннель не публикуется наружу.
Перезапуск выполняет отдельный procd worker после завершения записи файлов,
чтобы не оборвать установку вместе с SSH. После него VPS ждёт свежий Heartbeat
и проверяет настоящий Tachyon API через обратный маршрут выбранного роутера.
При отсутствии подтверждения выводится ошибка, успех не подставляется.
Проверить node-12 отдельно, без переустановки и без изменения файлов:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -RouterId node-12 -Action Status
```
Ожидается `TACHYON_CHECK_OK: node-12`. Команда показывает версию, режим, порт,
состояние Xray, возраст Heartbeat и результат запроса к API через туннель.
Страница LuCI вместо JSON Tachyon не считается успешной проверкой.
Для обычного локального SSH:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router root@192.168.2.1 -Action Install
```
Отдельная резервная копия на каждом устройстве:
`/root/owrt-remote-backup-before-tachyon-detection-v122`.
Откат удалённого роутера и затем VPS:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -RouterId node-12 -Action Rollback
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Rollback
```
В рамках исправления не меняются настройки и пакет самого Tachyon.
Исправленные пакеты выпускаются с тегом v122-r2. Прежние IPK/APK 122-r1
и тег v122 сохраняются.
## Обнаружение
Агент проверяет установленные пакеты tachyon и luci-app-tachyon через
+6
View File
@@ -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'
+33 -22
View File
@@ -9,7 +9,7 @@ tachyon_inventory_failed() {
}
tachyon_json() (
local dir package version package_version mode port service available api code pkg rc now last admin_port
local dir package version package_version mode port service available api code pkg rc now last admin_port candidate_port probe
umask 077
ulimit -f 64
mkdir -p "$TACHYON_RUNTIME" || { printf '{"checked":false}'; return; }
@@ -29,7 +29,14 @@ tachyon_json() (
for pkg in tachyon luci-app-tachyon; do
grep -qx "$pkg" "$dir/package" || continue
package="$pkg"
version="$(apk info -v "$pkg" 2>/dev/null | sed -n "s/^$pkg-//p" | head -n 1 | awk '{print $1}')"
# apk info -v prints the package description on OpenWrt 25.12.
# The installed version is available through the manifest.
version="$(apk list --installed --manifest "$pkg" 2>/dev/null | awk -v wanted="$pkg" '
$1 == wanted && $2 != "" {print $2; exit}
$1 ~ ("^" wanted "-") {sub("^" wanted "-", "", $1); print $1; exit}
')"
[ -n "$version" ] || version="$(apk query --installed --from system --fields name,version --format json "$pkg" 2>/dev/null |
jsonfilter -e '@[0].version' 2>/dev/null)"
break
done
elif command -v opkg >/dev/null 2>&1; then
@@ -43,24 +50,33 @@ tachyon_json() (
else
tachyon_inventory_failed; return
fi
case "$version" in ''|*[!0-9a-zA-Z.+~_-]*) version='' ;; esac
[ "${#version}" -le 80 ] || version=''
case "$package" in tachyon|luci-app-tachyon) ;; *) package='' ;; esac
if [ -z "$package" ]; then
printf '{"checked":true,"installed":false}\n' >"$dir/json"
else
package_version="$version"
port=0
mode=luci
# Older Tachyon can use listen_port for a proxy, not its web UI.
case "$version" in 2.*|[3-9].*)
mode=standalone
port="$(uci -q get tachyon.settings.listen_port 2>/dev/null)"
port=0; mode=luci; api=''
candidate_port="$(uci -q get tachyon.settings.listen_port 2>/dev/null)"
case "$candidate_port" in ''|*[!0-9]*) candidate_port=1680 ;; esac
[ "${#candidate_port}" -le 5 ] || candidate_port=1680
[ "$candidate_port" -ge 1024 ] && [ "$candidate_port" -le 65535 ] || candidate_port=1680
candidate_port="$(printf '%s' "$candidate_port" | awk '{printf "%d", $1}')"
# Older versions can use this port for a proxy. A real read-only
# Tachyon API response confirms the standalone UI, even if package
# metadata is missing or stale. An open port alone proves nothing.
probe="$(curl -q -fsS --noproxy '*' --connect-timeout 1 --max-time 2 --max-filesize 65536 \
"http://127.0.0.1:$candidate_port/api/agent/v1/health" 2>/dev/null |
jsonfilter -e '@.core_running' 2>/dev/null)"
case "$probe" in
true|false) mode=standalone; port="$candidate_port"; api='/api/agent/v1' ;;
*)
# Keep v2 routed to its own port when it is temporarily down;
# never substitute an available LuCI page for an offline UI.
case "$version" in 2.*|[3-9].*) mode=standalone; port="$candidate_port" ;; esac
;;
esac
case "$port" in ''|*[!0-9]*) port=0 ;; esac
[ "${#port}" -le 5 ] || port=0
[ "$port" -ge 1024 ] && [ "$port" -le 65535 ] || port=0
port="$(printf '%s' "$port" | awk '{printf "%d", $1}')"
[ "$mode" != standalone ] || [ "$port" != 0 ] || port=1680
service=unknown
for pkg in tachyon tachyon-core; do
rc="$(ubus call service list "{\"name\":\"$pkg\"}" 2>/dev/null |
@@ -68,7 +84,7 @@ tachyon_json() (
if printf '%s\n' "$rc" | grep -qx true; then service=running; break; fi
[ -z "$rc" ] || service=stopped
done
available=false; api=''
available=false
if [ "$mode" = standalone ]; then
code="$(curl -q -s --noproxy '*' --connect-timeout 1 --max-time 2 -o /dev/null \
-w '%{http_code}' "http://127.0.0.1:$port/" 2>/dev/null)"
@@ -81,16 +97,11 @@ tachyon_json() (
-w '%{http_code}' "http://127.0.0.1:$admin_port/cgi-bin/luci/admin/services/tachyon" 2>/dev/null)"
fi
case "$code" in 2??|3??|401|403) [ "$service" = stopped ] || available=true ;; esac
if [ "$mode" = standalone ] && [ "$available" = true ]; then
rc="$(curl -q -fsS --noproxy '*' --max-time 1 "http://127.0.0.1:$port/api/agent/v1/health" 2>/dev/null |
jsonfilter -e '@.core_running' 2>/dev/null)"
case "$rc" in true|false)
api='/api/agent/v1'
rc="$(curl -q -fsS --noproxy '*' --max-time 1 --max-filesize 65536 \
[ -n "$version" ] || [ "$mode" = standalone ] || available=false
if [ "$mode" = standalone ] && [ "$available" = true ] && [ "$api" = /api/agent/v1 ]; then
rc="$(curl -q -fsS --noproxy '*' --connect-timeout 1 --max-time 1 --max-filesize 65536 \
"http://127.0.0.1:$port/api/agent/v1/openapi.json" 2>/dev/null | jsonfilter -e '@.info.version' 2>/dev/null)"
case "$rc" in ''|*[!a-zA-Z0-9.+~_-]*) ;; *) [ "${#rc}" -gt 80 ] || version="$rc" ;; esac
;;
esac
fi
for pkg in tachyon-api tachyon-agent; do
[ -z "$api" ] || break
+52 -4
View File
@@ -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
}
}
],
+9 -2
View File
@@ -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."
+1 -1
View File
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-owrt-remote
PKG_VERSION:=122
PKG_RELEASE:=1
PKG_RELEASE:=4
PKG_LICENSE:=MIT
PKG_MAINTAINER:=kzolotarev95
PKGARCH:=all
+32
View File
@@ -60,6 +60,38 @@ def versions():
return version, release
def release_tag():
version, revision = versions()
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)]
+23
View File
@@ -3,6 +3,7 @@
import argparse
import contextlib
import functools
import hashlib
import http.server
import os
from pathlib import Path
@@ -54,6 +55,18 @@ def main():
parser.error("one main package and one real upgrade fixture are required")
candidate, fixture = candidates[0], fixtures[0]
apk = candidate.suffix == ".apk"
# Verify upgrades from the previously published package as well as the
# synthetic next revision. Old Release assets/tags remain immutable.
version, revision = package.versions()
baseline = None
if int(revision) > 1:
previous = str(int(revision) - 1)
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}'
url, expected = package.release_asset(tag, name)
baseline = source / 'test-fixtures' / ('previous-release' + candidate.suffix)
package.download(url, baseline, expected)
output = Path(args.output).resolve()
output.mkdir(parents=True, exist_ok=True)
port = free_port()
@@ -141,6 +154,16 @@ def main():
print("Testing remove, preserved state, and migration from unowned overlay files", flush=True)
remote(remove + " " + package.PACKAGE, timeout=180)
remote("set -e; test ! -e /usr/sbin/owrt-remote; test ! -e /www/cgi-bin/owrt-remote; test ! -e /etc/init.d/owrt-remote; sha256sum -c /tmp/remote-before.sha256")
if baseline:
print('Testing upgrade from the previous published Release', flush=True)
remote('wget -qO /tmp/remote-previous' + candidate.suffix + ' ' + shlex.quote(origin + 'test-fixtures/' + baseline.name))
baseline_install = 'apk add --allow-untrusted' if apk else 'opkg install'
remote(baseline_install + ' /tmp/remote-previous' + candidate.suffix, timeout=300)
remote(install + ' /tmp/remote-package' + candidate.suffix, timeout=300)
helper = 'usr/lib/owrt-remote/tachyon.sh'
digest = hashlib.sha256(package.payload()[helper][0]).hexdigest()
remote('set -e; sha256sum -c /tmp/remote-before.sha256; test "$(sha256sum /' + helper + ' | cut -d\" \" -f1)" = ' + digest)
remote(remove + ' ' + package.PACKAGE, timeout=180)
# Configuration left by install.sh is unowned by a package manager.
# A fresh package install must preserve it just like an upgrade.
remote(install + " /tmp/remote-package" + candidate.suffix, timeout=300)
+4
View File
@@ -1,5 +1,9 @@
# Версия v122
Исправления Tachyon для APK 3.0.5 выпускаются как пакетная ревизия 122-r2
с тегом v122-r2. Номер интерфейсов остаётся v122; исходный тег v122 и пакеты
122-r1 сохраняются.
Выпуск использует main и отдельный тег v122. GitHub Actions собирает IPK/APK,
проверяет их и прикладывает к Releases → v122 после успешного завершения сборок
и установки/обновления/удаления в OpenWrt VM. Выпущенная v121 сохраняется.
+2 -2
View File
@@ -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);
+17
View File
@@ -84,6 +84,23 @@ class PackageTests(unittest.TestCase):
text = (ROOT / "files" / name).read_text(encoding="utf-8")
self.assertIn("OpenWrt Remote Hub v" + version, text)
def test_package_revision_has_its_own_tag_without_renaming_the_panel(self):
for values, expected in [(('122','1'),'v122'), (('122','2'),'v122-r2'), (('123','1'),'v123')]:
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)
+159
View File
@@ -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;});
+41 -3
View File
@@ -137,7 +137,7 @@ curl() {
[ "$TEST_HTTP" != fail ] || return 7
for last do :; done
case "$last" in
*/api/agent/v1/health) printf '{"core_running":false}' ;;
*/api/agent/v1/health) [ "${TEST_API:-1}" = 1 ] || return 22; printf '{"core_running":false}' ;;
*/api/agent/v1/openapi.json) printf '{"info":{"version":"2.0.0-beta.14"}}' ;;
*) printf '%s' "$TEST_HTTP" ;;
esac
@@ -180,17 +180,55 @@ print(str(value).lower() if isinstance(value,bool) else value)' "$@"
def test_apk_discovery_and_legacy_luci(self):
code = r'''
apk() { if [ "$2" = -v ]; then echo tachyon-2.0.0-r1; else printf 'base-files\ntachyon\n'; fi; }
apk() {
case "$1" in
info) printf 'base-files\ntachyon\n' ;;
list) printf 'tachyon 2.0.0-r1\n' ;;
*) return 1 ;;
esac
}
tachyon_json force
'''
result = self.run_shell(code)
self.assertEqual(json.loads(result.stdout)['package_version'], '2.0.0-r1')
with (self.root / 'uci').open('a') as config:
config.write('tachyon.settings.listen_port=1602\n')
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='1.3.13', TEST_HTTP='403', TEST_SERVICE='true')
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='1.3.13', TEST_HTTP='403', TEST_SERVICE='true', TEST_API='0')
self.assertEqual(json.loads(result.stdout)['mode'], 'luci')
self.assertEqual(json.loads(result.stdout)['port'], 0)
def test_apk_305_description_is_not_a_version_and_manifest_selects_standalone(self):
result = self.run_shell(r'''
apk() {
case "$1:$2" in
info:) printf 'base-files\ntachyon\n' ;;
info:-v) printf 'tachyon: Pure-Rust routing orchestrator and web panel for OpenWrt (aarch64)\ntachyon: https://github.com/Dushnilin/tachyon\ntachyon: 7136 KiB\n' ;;
list:--installed) printf 'tachyon 2.0.0~beta.15-r1\n' ;;
*) return 1 ;;
esac
}
tachyon_json force
''')
status = json.loads(result.stdout)
self.assertEqual(status['mode'], 'standalone')
self.assertEqual(status['port'], 1680)
self.assertEqual(status['package_version'], '2.0.0~beta.15-r1')
self.assertTrue(status['available'])
def test_actual_api_recovers_missing_or_stale_package_version(self):
for version in ('', '1.3.13'):
result = self.harness.run_shell(self.mocks + 'tachyon_json force',
TEST_VERSION=version, TEST_HTTP='200', TEST_SERVICE='true')
status = json.loads(result.stdout)
self.assertEqual(status['mode'], 'standalone')
self.assertEqual(status['port'], 1680)
self.assertEqual(status['version'], '2.0.0-beta.14')
def test_luci_login_response_is_not_proof_of_an_unknown_tachyon_ui(self):
result = self.harness.run_shell(self.mocks + 'tachyon_json force',
TEST_VERSION='', TEST_API='0', TEST_HTTP='403', TEST_SERVICE='true')
self.assertFalse(json.loads(result.stdout)['available'])
def test_custom_web_port_and_no_reconfigure_when_manually_stopped(self):
with (self.root / 'uci').open('a') as config:
config.write('tachyon.settings.listen_port=1800\n')
+37
View File
@@ -0,0 +1,37 @@
// Browser regression: an absent version must not move the action into the header.
const {chromium} = require('playwright');
const fs = require('node:fs');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const source = fs.readFileSync('vps/owrt-remote-hub.py', 'utf8');
const start = source.indexOf('function renderTachyon(router) {{');
const end = source.indexOf('\nfunction render(list)', start);
const escape = s => String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const context = {escapeHtml:escape, escapeAttr:escape};
vm.createContext(context);
vm.runInContext(source.slice(start,end).replaceAll('{{','{').replaceAll('}}','}'), context);
(async () => {
const browser = await chromium.launch({headless:true, ...(process.env.OWRT_TEST_BROWSER_BIN ? {executablePath:process.env.OWRT_TEST_BROWSER_BIN} : {})});
try {
for (const [width,height] of [[1280,900],[390,844],[844,390]]) {
const page = await browser.newPage({viewport:{width,height}});
const cards = ['2.0.0-beta.15','', '2.0.0~beta.15-r1'].map(version =>
'<section class="card">'+context.renderTachyon({permissions:{admin:true},tachyon:{installed:true,online:true,version,url:'/tachyon/test/'}})+'</section>').join('');
await page.setContent('<style>*{box-sizing:border-box}body{margin:12px;font:13px Arial;background:#21192e;color:#fff}.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.card{min-width:0}.btn{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:8px 12px;border:1px solid #736387;border-radius:7px;background:#3b3049;color:white;text-decoration:none;font-weight:bold}@media(max-width:600px){.cards{grid-template-columns:1fr}}</style><div class="cards">'+cards+'</div>');
const boxes = await page.locator('.tachyonIntegration').evaluateAll(items => items.map(el => {
const box=el.getBoundingClientRect(), meta=el.querySelector('.tachyonMeta').getBoundingClientRect(), action=el.querySelector('.tachyonAction').getBoundingClientRect();
return {height:box.height,actionTop:action.top-box.top,metaBottom:meta.bottom-box.top,overflow:el.scrollWidth>el.clientWidth,center:Math.abs((action.left+action.width/2)-(box.left+box.width/2))};
}));
for (const box of boxes) {
assert(!box.overflow,`${width}: overflowing card`);
assert(box.actionTop>=box.metaBottom+7,`${width}: action must be below metadata`);
assert(box.center<1,`${width}: centered button`);
assert(Math.abs(box.actionTop-boxes[0].actionTop)<1,`${width}: version changed action placement`);
assert(Math.abs(box.height-boxes[0].height)<1,`${width}: version changed block height`);
}
if (process.env.OWRT_TEST_SCREENSHOT_DIR) await page.screenshot({path:process.env.OWRT_TEST_SCREENSHOT_DIR+`/tachyon-cards-${width}.png`,fullPage:true});
await page.close();
}
console.log('TACHYON_CARD_LAYOUT_OK: desktop, portrait and landscape');
} finally { await browser.close(); }
})().catch(error => {console.error(error);process.exitCode=1;});
+20 -2
View File
@@ -5,6 +5,7 @@ import shlex
import shutil
import subprocess
import tempfile
import sys
import unittest
from test_host_policy import ROOT, SH
@@ -17,6 +18,7 @@ class DeployTests(unittest.TestCase):
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.env = dict(os.environ)
self.env['TEST_PYTHON'] = Path(sys.executable).as_posix()
if os.name == 'nt':
self.env['PATH'] = str(Path(SH).parent) + os.pathsep + self.env['PATH']
self.targets = {name: self.root / name for name in ('agent', 'tachyon.sh')}
@@ -29,8 +31,14 @@ class DeployTests(unittest.TestCase):
original = {'agent': '/usr/sbin/owrt-remote', 'tachyon.sh': '/usr/lib/owrt-remote/tachyon.sh'}[name]
self.script = self.script.replace('echo ' + original, 'echo ' + shlex.quote(target.as_posix()))
self.script = self.script.replace('/etc/init.d/owrt-remote restart', 'test_restart')
self.script = self.script.replace('/usr/sbin/owrt-remote tachyon-status', "printf '{\"checked\":true}'")
mocks = '''
ubus() { printf '{}'; }
ubus() {
case "$1:$2:$3" in
call:service:add) "$TEST_PYTHON" -c 'import json,sys; data=json.loads(sys.argv[1]); assert data["instances"]["once"]["command"][0]=="/bin/sh"' "$4" ;;
*) printf '{}' ;;
esac
}
jsonfilter() { printf true; }
timeout() { return 0; }
busybox() { return 127; }
@@ -39,7 +47,7 @@ sleep() { :; }
'''
self.script = mocks + self.script.replace('test -r /usr/lib/owrt-remote/control.sh', 'true')
def deploy(self, action='Install', bad=False, fail=False, no_timeout=False):
def deploy(self, action='Install', bad=False, fail=False, no_timeout=False, deferred=False):
stage = self.root / 'stage'
stage.mkdir()
for name, source in {'agent': 'files/usr/sbin/owrt-remote', 'tachyon.sh': 'files/usr/lib/owrt-remote/tachyon.sh'}.items():
@@ -47,6 +55,7 @@ sleep() { :; }
stage.joinpath(name).write_text(text, encoding='utf-8', newline='\n')
script = self.script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(stage.as_posix()))
script = script.replace('__UPLOAD_NAME__', 'sandbox').replace('__KIND__', 'Router').replace('__ACTION__', action)
script = script.replace('__DEFER_RESTART__', '1' if deferred else '0')
if no_timeout:
# Model the optional applet missing from both PATH and BusyBox.
script = script.replace('command -v timeout >/dev/null 2>&1', 'false')
@@ -97,6 +106,15 @@ sleep() { :; }
self.assertNotIn('restoring files', result.stderr)
self.assert_original()
def test_reverse_ssh_install_queues_independent_restart_after_file_checks(self):
# A direct restart would close the SSH connection carrying deployment.
# The old restart mock intentionally fails; deferred mode must skip it.
result = self.deploy(deferred=True, fail=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('TACHYON_RESTART_QUEUED', result.stdout)
self.assertNotIn('TACHYON_INTEGRATION_Router_Install_OK', result.stdout)
self.assertNotIn('restoring files', result.stderr)
if __name__ == '__main__':
unittest.main()
+92
View File
@@ -0,0 +1,92 @@
"""Reverse SSH verification must validate the actual router API, not the badge."""
from contextlib import closing, redirect_stdout
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
from pathlib import Path
import sqlite3
import tempfile
import threading
import time
import unittest
class DetectionVerificationTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.db = Path(self.temp.name) / 'hub.db'
self.body = b'{"core_running":false}'
owner = self
class Backend(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200); self.end_headers(); self.wfile.write(owner.body)
def log_message(self, *args): pass
self.server = ThreadingHTTPServer(('127.0.0.1', 0), Backend)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start(); self.addCleanup(self.close)
with closing(sqlite3.connect(self.db)) as db, db:
db.execute('create table routers(id text,last_seen real,status_json text,tachyon_entry_port integer,deleted_at integer default 0)')
db.execute('insert into routers(id,last_seen,status_json,tachyon_entry_port) values(?,?,?,?)', ('node-12', time.time(), json.dumps({
'xray':'running', 'tachyon':{'mode':'standalone','available':True,'version':'2.0.0-beta.15'}}), self.server.server_port))
def close(self):
self.server.shutdown(); self.server.server_close(); self.thread.join(timeout=3)
def verify(self, action='Install'):
source = (Path(__file__).resolve().parents[1] / 'vps/deploy-tachyon-detection-fix.ps1').read_text(encoding='utf-8')
code = source.split("$Verify = @'\n",1)[1].split("\n'@",1)[0]
code = code.replace('/var/lib/owrt-remote/hub.db',self.db.as_posix()).replace('__ROUTER_ID__','node-12')
code = code.replace('__SINCE__',str(int(time.time())-10)).replace('__ACTION__',action)
code = code.replace('range(40)','range(1)').replace('time.sleep(2)','time.sleep(0)')
output = io.StringIO()
with redirect_stdout(output): exec(compile(code,'verification','exec'),{})
return output.getvalue()
def status(self):
source = (Path(__file__).resolve().parents[1] / 'vps/deploy-tachyon-detection-fix.ps1').read_text(encoding='utf-8')
code = source.split("$Status = @'\n",1)[1].split("\n'@",1)[0]
code = code.replace('/var/lib/owrt-remote/hub.db',self.db.as_posix()).replace('__ROUTER_ID__','node-12')
output = io.StringIO()
try:
with redirect_stdout(output): exec(compile(code,'status','exec'),{})
except SystemExit as result:
return result.code, output.getvalue()
raise AssertionError('Status must explicitly report its return code')
def test_standalone_route_with_stopped_core_is_still_a_working_web_api(self):
self.assertIn('TACHYON_DETECTION_Router_Install_OK',self.verify())
def test_luci_html_instead_of_tachyon_is_rejected(self):
self.body = b'<html>LuCI login</html>'
with self.assertRaisesRegex(SystemExit,'Result not confirmed'): self.verify()
def test_wrong_api_field_type_is_rejected(self):
self.body = b'{"core_running":"false"}'
with self.assertRaisesRegex(SystemExit,'Result not confirmed'): self.verify()
def test_stale_heartbeat_cannot_confirm_deployment(self):
with closing(sqlite3.connect(self.db)) as db, db: db.execute('update routers set last_seen=0')
with self.assertRaisesRegex(SystemExit,'Result not confirmed'): self.verify()
def test_rollback_can_restore_legacy_detection(self):
with closing(sqlite3.connect(self.db)) as db, db:
db.execute('update routers set status_json=?',(json.dumps({'xray':'running','tachyon':{'mode':'luci'}}),))
self.assertIn('TACHYON_DETECTION_Router_Rollback_OK',self.verify('Rollback'))
def test_status_checks_the_selected_router_without_changing_database(self):
before = self.db.read_bytes()
rc, output = self.status()
self.assertEqual(rc, 0, output)
self.assertIn('TACHYON_CHECK_OK: node-12', output)
self.assertIn('2.0.0-beta.15', output)
self.assertEqual(self.db.read_bytes(), before)
def test_status_rejects_luci_html_and_reports_failure(self):
self.body = b'<html>LuCI</html>'
rc, output = self.status()
self.assertEqual(rc, 1, output)
self.assertIn('TACHYON_CHECK_FAILED: node-12', output)
if __name__ == '__main__': unittest.main()
+4
View File
@@ -16,6 +16,10 @@ assert(html.includes('Открыть Tachyon'));
assert(html.includes('target="_blank"'));
assert(html.includes('Online'));
assert(html.includes('href="/tachyon/a/"'));
assert(html.includes('tachyonMeta'));
assert(html.includes('tachyonAction'));
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;
+10
View File
@@ -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." }
+12
View File
@@ -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." }
+113
View File
@@ -0,0 +1,113 @@
[CmdletBinding(DefaultParameterSetName = 'Router')]
param(
[Parameter(ParameterSetName = 'Router')][string]$Router = 'root@192.168.2.1',
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
[Parameter(ParameterSetName = 'Vps')][ValidatePattern('^[A-Za-z0-9_.-]+$')][string]$RouterId,
[ValidateSet('Install', 'Rollback', 'Status')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$Deploy = Join-Path $PSScriptRoot 'deploy-tachyon.ps1'
if ($Action -eq 'Status') {
if (-not $Vps -or -not $RouterId) { throw 'Status requires -Vps and -RouterId, for example node-12.' }
$Status = @'
import json, sqlite3, time, urllib.request
from contextlib import closing
with closing(sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro', uri=True)) as db:
row = db.execute('select last_seen,status_json,tachyon_entry_port from routers where id=? and coalesce(deleted_at,0)=0', ('__ROUTER_ID__',)).fetchone()
if not row:
raise SystemExit('Router __ROUTER_ID__ not found in Hub')
status = json.loads(row[1] or '{}')
tachyon = status.get('tachyon') or {}
age = max(0, int(time.time() - float(row[0] or 0)))
api_ok = False
reason = 'standalone route unavailable'
if tachyon.get('mode') == 'standalone' and row[2]:
try:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open('http://127.0.0.1:' + str(int(row[2])) + '/api/agent/v1/health', timeout=4) as response:
health = json.loads(response.read(65536))
api_ok = type(health.get('core_running')) is bool
reason = 'Tachyon API confirmed through the reverse tunnel' if api_ok else 'Unexpected API response'
except Exception as error:
reason = 'Reverse route: ' + type(error).__name__
print(json.dumps({'router':'__ROUTER_ID__', 'version':tachyon.get('version') or '',
'package_version':tachyon.get('package_version') or '', 'mode':tachyon.get('mode') or 'unknown',
'port':tachyon.get('port'), 'xray':status.get('xray'), 'heartbeat_age_seconds':age,
'api_ok':api_ok, 'reason':reason}, ensure_ascii=True, indent=2))
ok = age <= 120 and status.get('xray') == 'running' and tachyon.get('available') and api_ok
print('TACHYON_CHECK_OK: __ROUTER_ID__' if ok else 'TACHYON_CHECK_FAILED: __ROUTER_ID__')
raise SystemExit(0 if ok else 1)
'@
$Status = $Status.Replace('__ROUTER_ID__', $RouterId)
$Status.Replace("`r`n", "`n") | & ssh -T -o ConnectTimeout=20 $Vps 'python3 -'
if ($LASTEXITCODE -ne 0) { throw 'Router check failed. See mode, version and API result above. No files were changed.' }
return
}
$Options = @{ Action = $Action; BackupName = 'tachyon-detection'; BackupVersion = 'v122'; PrepareOnly = $PrepareOnly }
if ($PSCmdlet.ParameterSetName -eq 'Router') {
& $Deploy -Router $Router @Options
} elseif (-not $RouterId) {
& $Deploy -Vps $Vps @Options
} else {
# Query only this router's loopback SSH listener. RouterId cannot contain
# shell/SQL quoting characters, and the database is opened read-only.
$Query = @'
import sqlite3, time
from contextlib import closing
with closing(sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro', uri=True)) as db:
row = db.execute('select ssh_entry_port from routers where id=? and coalesce(deleted_at,0)=0', ('__ROUTER_ID__',)).fetchone()
if not row or not isinstance(row[0], int) or not 1024 <= row[0] <= 65535:
raise SystemExit('Router has no valid loopback SSH entry in Hub')
print('TACHYON_SSH_PORT=' + str(row[0]))
print('TACHYON_MIN_SEEN=' + str(int(time.time())))
'@
$Query = $Query.Replace('__ROUTER_ID__', $RouterId)
$Output = $Query.Replace("`r`n", "`n") | & ssh -T -o ConnectTimeout=20 $Vps 'python3 -'
if ($LASTEXITCODE -ne 0) { throw 'Cannot read the selected router SSH port. Router was not changed.' }
$PortLine = @($Output | Where-Object { $_ -match '^TACHYON_SSH_PORT=([0-9]+)$' })
if ($PortLine.Count -ne 1) { throw 'Hub did not return one SSH port. Router was not changed.' }
$RouterPort = [int]($PortLine[0] -replace '^TACHYON_SSH_PORT=', '')
if ($RouterPort -lt 1024 -or $RouterPort -gt 65535) { throw 'Invalid SSH listener port.' }
Write-Host "Selected router: $RouterId; SSH via $Vps and loopback port $RouterPort"
$SinceLine = @($Output | Where-Object { $_ -match '^TACHYON_MIN_SEEN=([0-9]+)$' })
if ($SinceLine.Count -ne 1) { throw 'Hub did not return a verification timestamp.' }
$Since = [long]($SinceLine[0] -replace '^TACHYON_MIN_SEEN=', '')
& $Deploy -Router root@127.0.0.1 -Port $RouterPort -JumpHost $Vps -DeferRestart @Options
if ($PrepareOnly) { return }
# Verification uses the VPS, so a reconnecting reverse SSH tunnel does
# not interrupt it. It also verifies the real route, not just a green card.
$Verify = @'
import json, sqlite3, time, urllib.request
from contextlib import closing
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
last = 'Waiting for a fresh Heartbeat and the standalone route'
for attempt in range(40):
with closing(sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro', uri=True)) as db:
row = db.execute('select last_seen,status_json,tachyon_entry_port from routers where id=?', ('__ROUTER_ID__',)).fetchone()
try:
status = json.loads(row[1] or '{}') if row else {}
tachyon = status.get('tachyon') or {}
fresh = row and float(row[0] or 0) >= __SINCE__
if fresh and status.get('xray') == 'running':
if '__ACTION__' == 'Rollback':
print('TACHYON_DETECTION_Router_Rollback_OK: fresh Heartbeat; Xray running')
break
if tachyon.get('mode') == 'standalone' and tachyon.get('available') and tachyon.get('version') and row[2]:
with opener.open('http://127.0.0.1:' + str(int(row[2])) + '/api/agent/v1/health', timeout=3) as response:
health = json.loads(response.read(65536))
if type(health.get('core_running')) is bool:
print('TACHYON_DETECTION_Router_Install_OK: ' + str(tachyon.get('version')) + '; standalone API verified through the router tunnel')
break
last = 'Waiting for router __ROUTER_ID__: mode=' + str(tachyon.get('mode')) + '; Xray=' + str(status.get('xray'))
except Exception as error:
last = 'Reverse route not ready: ' + type(error).__name__
time.sleep(2)
else:
raise SystemExit('Result not confirmed: ' + last + '; backup retained at /root/owrt-remote-backup-before-tachyon-detection-v122')
'@
$Verify = $Verify.Replace('__ROUTER_ID__', $RouterId).Replace('__SINCE__', [string]$Since).Replace('__ACTION__', $Action)
$Verify.Replace("`r`n", "`n") | & ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Vps 'python3 -'
if ($LASTEXITCODE -ne 0) { throw 'Router result not confirmed. See diagnostic above; retained backup is available for Rollback.' }
}
+36 -8
View File
@@ -2,7 +2,11 @@ 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')][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 = '',
[switch]$DeferRestart,
[switch]$PrepareOnly
)
@@ -13,6 +17,7 @@ $StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$TargetKind = $PSCmdlet.ParameterSetName
$Destination = if ($TargetKind -eq 'Vps') { $Vps } else { $Router }
if ($DeferRestart -and $TargetKind -ne 'Router') { throw 'Deferred restart requires a router target.' }
$RemoteScript = @'
#!/bin/sh
@@ -23,6 +28,7 @@ action=__ACTION__
backup=/root/owrt-remote-backup-before-__BACKUP_NAME__-v121
changed=0
step=preflight
defer_restart=__DEFER_RESTART__
if [ "$kind" = Vps ]; then
names=hub.py
@@ -155,8 +161,15 @@ snapshot "$stage/previous"
changed=1
step=apply-files
apply_files "$source_dir"
if [ "$kind" = Router ] && [ "$action" = Install ]; then
step=refresh-discovery
# Refresh the bounded RAM cache before rendering Xray, so an old LuCI
# classification cannot keep the standalone route absent for another beat.
/usr/sbin/owrt-remote tachyon-status >"$stage/tachyon-status"
cat "$stage/tachyon-status"
fi
step=restart
restart
if [ "$defer_restart" != 1 ]; then restart; fi
step=verify-health
if [ "$kind" = Vps ]; then
@@ -190,12 +203,21 @@ for name in $names; do
path="$(target "$name")"
if [ -e "$source_dir/$name.absent" ]; then test ! -e "$path"; else cmp "$source_dir/$name" "$path"; fi
done
printf '\nBackup: %s\nTACHYON_INTEGRATION_%s_%s_OK\n' "$backup" "$kind" "$action"
if [ "$defer_restart" = 1 ]; then
step=queue-restart
# An SSH connection through Xray must finish before Xray stops. This
# bounded procd worker is independent of the service being restarted.
ubus call service add '{"name":"owrt-remote-tachyon-refresh","instances":{"once":{"command":["/bin/sh","-c","sleep 3; /etc/init.d/owrt-remote restart","__UPLOAD_NAME__"],"stdout":true,"stderr":true}}}' >/dev/null
printf '\nBackup: %s\nTACHYON_RESTART_QUEUED\n' "$backup"
else
printf '\nBackup: %s\nTACHYON_INTEGRATION_%s_%s_OK\n' "$backup" "$kind" "$action"
fi
'@
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__KIND__', $TargetKind).Replace('__ACTION__', $Action).Replace('__BACKUP_NAME__', $BackupName)
if ($BackupVersion -eq 'v122') { $RemoteScript = $RemoteScript.Replace('-__BACKUP_NAME__-v121', '-__BACKUP_NAME__-v122') }
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__KIND__', $TargetKind).Replace('__ACTION__', $Action).Replace('__BACKUP_NAME__', $BackupName).Replace('__DEFER_RESTART__', $(if ($DeferRestart) { '1' } else { '0' }))
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
$Sources = if ($TargetKind -eq 'Vps') {
@@ -209,11 +231,17 @@ try {
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -o ConnectTimeout=20 -r -- $StageRoot "${Destination}:/tmp/"
$JumpOptions = if ($JumpHost) { @('-o', "ProxyJump=$JumpHost") } else { @() }
& scp -O -P $Port @JumpOptions -o ConnectTimeout=20 -r -- $StageRoot "${Destination}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
& ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Destination "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. Success was not confirmed; see output above." }
Write-Host "Tachyon integration $TargetKind $Action finished successfully."
$RemoteOutput = & ssh -T -p $Port @JumpOptions -o ConnectTimeout=20 -o ServerAliveInterval=15 $Destination "sh /tmp/$UploadName/run.sh"
$RemoteCode = $LASTEXITCODE
$RemoteOutput | Write-Output
if ($RemoteCode -ne 0 -and -not ($DeferRestart -and $RemoteCode -eq 255 -and @($RemoteOutput) -contains 'TACHYON_RESTART_QUEUED')) {
throw "$Action failed. Success was not confirmed; see output above."
}
if ($DeferRestart) { Write-Host 'Files applied; restart queued. Runtime verification follows.' }
else { Write-Host "Tachyon integration $TargetKind $Action finished successfully." }
} finally {
if (-not $PrepareOnly -and (Test-Path -LiteralPath $StageRoot)) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
+480 -27
View File
@@ -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-wrap:wrap;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"><strong>Tachyon ${{escapeHtml(t.version || '')}}</strong><span style="color:${{t.online ? '#74e3ac' : '#f2bc6b'}}">${{label}}</span>${{button}}</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())])