Compare commits
10
Commits
780d036a9c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87ac016293 | ||
|
|
05972f8c24 | ||
|
|
d482ed97c4 | ||
|
|
9b7a89257b | ||
|
|
9dead7741d | ||
|
|
ce763dd1be | ||
|
|
9c8def5e5c | ||
|
|
927aec8ffe | ||
|
|
70a4705e67 | ||
|
|
f4ccbf82f3 |
No files matched your search
@@ -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 \
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# FORK.md — изменения форка (cyril/luci-app-owrt-remote)
|
||||
|
||||
Форк `kzolotarev95/luci-app-owrt-remote`. Зеркало upstream: `~/mirrors/luci-app-owrt-remote.git` (GitHub origin), push-копия в Gitea `11.11.11.106:3000/cyril/luci-app-owrt-remote` (pull-зеркало отключено; ресинк вручную, наши коммиты — поверх upstream main).
|
||||
|
||||
## Наш коммит: REALITY для hops роутер↔хаб
|
||||
|
||||
`VLESS+Reality` вместо `security=none` (см. `docs/REALITY_TRANSPORT.md`):
|
||||
|
||||
- `vps/owrt-remote-hub.py`
|
||||
- профиль транспорта `STATE_DIR/transport.json` (x25519-пара через бинарь xray, shortId, dest/SNI, fingerprint); env `OWRT_REMOTE_TRANSPORT` (`reality` по умолчанию, `none` — как upstream), `OWRT_REMOTE_REALITY_DEST`, `OWRT_REMOTE_REALITY_FINGERPRINT`, `OWRT_REMOTE_XRAY_BINARY`;
|
||||
- reality streamSettings в `make_server_xray_config()` и `make_router_xray_config()`;
|
||||
- uci-строки `security`, `reality_public_key`, `reality_server_name`, `reality_fingerprint` в генерируемом конфиге роутера;
|
||||
- блок `transport` в heartbeat `hub_update`;
|
||||
- `reload_vps_xray` пишет конфиг в candidate-файл, гоняет `xray -test` и только потом подменяет — кривой конфиг не убьёт живой туннель.
|
||||
- `files/usr/sbin/owrt-remote` — те же поля uci + валидация + reality streamSettings в `render_client_config`, compat-probe по security, возрастная проверка ядра для reality (< 24.2.14 — заменить).
|
||||
- `files/etc/config/owrtremote`, поля формы в `files/www/cgi-bin/owrt-remote`, `PKG_RELEASE:=3`.
|
||||
|
||||
## Известные проблемы upstream, на которые наткнулись
|
||||
|
||||
- **XTLS/Xray-core#7259**: REALITY-серверы >= 26.9.8 отвергают client hello («received real certificate (potential MITM or redirection)»), работает на 26.7.28. Хабы держим на **xray-core 26.7.28**, пока upstream не починит. Проверка матрицы версий — в `docs/REALITY_TRANSPORT.md`.
|
||||
|
||||
## Как ресинкать с upstream
|
||||
|
||||
```
|
||||
git -C ~/mirrors/luci-app-owrt-remote.git fetch origin
|
||||
git -C ~/mirrors/luci-app-owrt-remote.git merge --ff-only origin/main # или rebase нашей ветки
|
||||
# конфликты вероятны в owrt-remote-hub.py (make_server/client configs) — сверять с docs/REALITY_TRANSPORT.md
|
||||
git -C ~/forks/luci-app-owrt-remote fetch && git -C ~/forks/luci-app-owrt-remote rebase main
|
||||
```
|
||||
@@ -38,20 +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>
|
||||
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
@@ -189,11 +175,16 @@ owrt-remote doctor
|
||||
owrt-remote status
|
||||
```
|
||||
|
||||
Если загрузка Xray прерывается: общий загрузчик с переключением клиентов,
|
||||
диагностика DNS/TLS/HTTP, локальная установка исправления и откат описаны в
|
||||
[docs/XRAY_DOWNLOAD_RECOVERY.md](docs/XRAY_DOWNLOAD_RECOVERY.md).
|
||||
|
||||
<h3> Готовые пакеты для OpenWrt</h3>
|
||||
|
||||
OpenWrt 23.05/24.10 и APK для 25.12. Пакеты
|
||||
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 нужен доверенный ключ подписи; неподписанный локальный
|
||||
|
||||
@@ -144,13 +144,17 @@ Workflow `.github/workflows/openwrt-packages.yml` запускается на т
|
||||
публикации Release, изменениях пакета в pull request и вручную. В PR и при
|
||||
обычном ручном запуске он только собирает и тестирует. Для повторной публикации
|
||||
после исправления сборочного инструмента доступен ручной запуск с
|
||||
`publish_release=true` и существующим `release_tag`, например `v121`.
|
||||
`publish_release=true` и существующим `release_tag`, например `v122-r2`.
|
||||
Он не перемещает тег и проверяет, что содержимое `files/` и установочные
|
||||
помощники совпадают с этим тегом. Рецепт и инструменты сборки могут содержать
|
||||
исправления; точный commit сборки записывается в отчёте. После проверок
|
||||
пакеты прикладываются к Release.
|
||||
Тег должен совпадать с `PKG_VERSION`: текущий пример — `v121`.
|
||||
Следующий выпуск должен получить новую версию или пакетную ревизию в 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
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# REALITY-транспорт hops роутер↔хаб (наш форк)
|
||||
|
||||
## Суть
|
||||
|
||||
Upstream: один VLESS-inbound хаба на `:8443` c `network=tcp, security=none`.
|
||||
Роутер дIAL-OUTит к хабу; reverse-порталы (LuCI/SSH) живут за тем же conn.
|
||||
Без TLS: весь трафик и логин-данные в панели — открытым текстом внутри hops.
|
||||
|
||||
Форк: тот же единственный inbound, но `security=reality` — полноценное TLS-рукопожатие,
|
||||
замаскированное под handshake публичного сайта-прикрытия (`dest`), без CA-сертификатов
|
||||
и продлений. Аутентификация по-прежнему per-router UUID (LuCI + SSH = два UUID).
|
||||
|
||||
## Где что генерируется
|
||||
|
||||
- Хаб: `transport.json` в `STATE_DIR` (`/var/lib/owrt-remote/`), создаётся лениво
|
||||
(`xray x25519` → приват/публик, `shortId` = 8 hex, `dest`=SNI из env).
|
||||
- Серверный inbound: `privateKey`, `serverNames=[SNI]`, `shortIds=[shortId]`,
|
||||
`dest=<SNI>:443`, `xver=0`.
|
||||
- Клиент (роутер): `publicKey`, `serverName`, `fingerprint` (chrome). shortId клиенту
|
||||
не нужен (сервер кодирует его в «фейковом» сертификате).
|
||||
- Конфиг роутера хаб отдаёт готовыми `uci set owrtremote.main.security/reality_*`
|
||||
(карточка роутера / print-openwrt-config / панельный «Xray настройки» на роутере).
|
||||
- Heartbeat остаётся отдельным HTTPS-каналом (через панель/Pangolin), к xray не относится.
|
||||
|
||||
## Пин версии xray на хабе (важно!)
|
||||
|
||||
Upstream-регрессия **XTLS/Xray-core#7259**: REALITY-сервер 26.9.8+ не принимает
|
||||
рукопожатия клиентов (клиент: `received real certificate (potential MITM or redirection)`).
|
||||
Практика 22.11.2026: связка 26.11.9↔26.11.9 не работает, ~~26.7.28~~ (см. таблицу матрицы
|
||||
в коммите форка/заметку хаба) — хаб держим на **26.7.28**, пока upstream не выпустит фикс.
|
||||
|
||||
Обновление хаба на новую версию core — только после повторного прогона e2e-матрицы
|
||||
(hub-generators → две локации xray → reverse-туннель через reality).
|
||||
|
||||
## Смена camouflage-домена
|
||||
|
||||
env хаба: `OWRT_REMOTE_REALITY_DEST=download.windowsupdate.com`, рестарт `owrt-remote`,
|
||||
затем пересоздать конфиги роутеров (карточка → новая команда uci; shortId/pk те же, если
|
||||
не трогать transport.json). Удаление `transport.json` = новая x25519-пара и новый shortId
|
||||
⇒ всем роутерам нужны новые конфиги.
|
||||
|
||||
## Совместимость / откат
|
||||
|
||||
`OWRT_REMOTE_TRANSPORT=none` + рестарт = ровно upstream-поведение (но генератор конфига
|
||||
роутера продолжит писать `security=none`, роутер-агент умеет оба).
|
||||
Старые агенты (без полей security) не работают с reality-hub — роутер нужно обновить
|
||||
(установить ipk/файлы этого форка).
|
||||
|
||||
|
||||
## 22.11.2026: reverse + REALITY is broken on modern cores — `security=tls` is now the default
|
||||
|
||||
Bisect matrix (xray 26.7.28 / 26.11.9, all four pairs, loopback e2e):
|
||||
|
||||
* the REALITY hop itself authenticates and tunnels user traffic fine
|
||||
(shortId MUST be present in the client `realitySettings`; camo dest
|
||||
`www.microsoft.com` is dead because Microsoft now serves post-quantum
|
||||
cert chains — use `www.cloudflare.com`);
|
||||
* BUT the tag-form VLESS reverse (Rvs control channel, PR #5101) never
|
||||
registers when the bridge transport is REALITY: portal logs the reality
|
||||
handshake (`hs.c.conn == conn: true`) and then silence — no
|
||||
`v1.rvs.cool` request is ever dispatched. Upstream reports of the same
|
||||
family: XTLS/Xray-core #6242 / #6248 ("reverse broken since 26.5,
|
||||
works on 26.4.25"). Our repro: relay hex-dump shows the bridge's Rvs
|
||||
request on the wire, portal never responds. xray 26.4.25 was also pulled
|
||||
(ghcr layers, /tmp/xraybin264) and tested: the tag-form fails there too
|
||||
(26.4.25<->26.4.25 and cross-version) — upstream's "works on 26.4.25"
|
||||
refers to the legacy domain-form reverse config, not PR #5101 tags.)
|
||||
|
||||
Working alternative shipped as `OWRT_REMOTE_TRANSPORT=tls` (default):
|
||||
self-signed hub cert (hub generates it with openssl) + `pinnedPeerCertSha256`
|
||||
on the router (xray removed `allowInsecure`), ALPN `h2,http/1.1`, uTLS
|
||||
`fingerprint: chrome`. Verified end-to-end through hub-generated configs:
|
||||
portal `entry-*` -> reverse mux -> router `router-admin` freedom redirect
|
||||
= HTTP 200 on 26.11.9<->26.11.9 and 26.11.9<->26.7.28.
|
||||
|
||||
Pitfalls discovered along the way:
|
||||
|
||||
* freedom outbounds behind the reverse bridge need explicit
|
||||
`finalRules: [{action: allow, network: tcp, port: ...}]` — newer cores
|
||||
blackhole reverse egress by default (see also 3x-ui 6f6c7fc);
|
||||
* the Rvs bridge registers ~2 s after the router xray starts (monitor
|
||||
interval), healthcheck scripts must wait, or they see
|
||||
`non existing outTag`;
|
||||
* legacy `reverse.bridges/portals` config objects were REMOVED in 26.x —
|
||||
only the tag form works.
|
||||
|
||||
REALITY stays selectable (`OWRT_REMOTE_TRANSPORT=reality`) for the hub
|
||||
panel hop style until upstream fixes reverse-over-REALITY.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Раскрытие данных карточек роутеров
|
||||
|
||||
На ПК и телефоне карточки открываются кнопками «Открыть данные» и «Скрыть данные».
|
||||
На ПК подробности раскрываются поверх сетки. Место компактной карточки сохраняется,
|
||||
поэтому соседние карточки, следующие ряды и высота страницы не меняются.
|
||||
Одновременно открыта одна карточка. Закрыть её можно кнопкой, Escape или нажатием
|
||||
снаружи. Длинное содержимое прокручивается внутри раскрытой карточки.
|
||||
|
||||
Раскрытие занимает 230 мс. В облегчённом дизайне и при системной настройке уменьшения
|
||||
анимации переход выполняется сразу. На мобильном сохраняется раскрытие внутри
|
||||
страницы. Обновление статусов сохраняет открытые данные и их прокрутку.
|
||||
|
||||
## Локальная установка на VPS
|
||||
|
||||
Из PowerShell Windows 11:
|
||||
|
||||
```powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-router-card-details.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@YOUR_VPS_IP -Action Install
|
||||
```
|
||||
|
||||
Скрипт проверяет Python, сохраняет исходный Hub в
|
||||
`/root/owrt-remote-backup-before-router-card-details-v122/hub.py`, атомарно заменяет
|
||||
файл, перезапускает Hub и проверяет SHA256 работающего процесса через `/health`.
|
||||
При ошибке восстанавливает файл, который был установлен до текущей попытки.
|
||||
После установки обновите страницу панели через Ctrl+F5.
|
||||
|
||||
Откат к сохранённой копии:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@YOUR_VPS_IP -Action Rollback
|
||||
```
|
||||
|
||||
## Проверка интерфейса
|
||||
|
||||
`tests/test_router_card_details.cjs` использует настоящий HTML/JS панели и
|
||||
Playwright с установленным Chrome. Проверяет координаты сетки во время анимации,
|
||||
раскрытие/закрытие, границы экрана, быстрые повторные клики, обновление статусов,
|
||||
прокрутку, фокус клавиатуры и переход с ПК на мобильный размер. Сценарии включают
|
||||
три дизайна, уменьшенную анимацию, две колонки и обе ориентации телефона.
|
||||
@@ -0,0 +1,309 @@
|
||||
# Tachyon в карточке роутера
|
||||
|
||||
Интеграция включена в 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 через
|
||||
действующий менеджер пакетов: APK либо opkg. Проверка не обращается к репозиториям
|
||||
и не устанавливает зависимости. Открытый порт без установленного пакета
|
||||
не создаёт интеграцию.
|
||||
|
||||
Короткая проверка procd и HTTP различает наличие пакета и доступность интерфейса.
|
||||
Для ветки 2.x порт берётся из tachyon.settings.listen_port, по умолчанию 1680.
|
||||
Для старых версий используется LuCI через существующий вход Админки. В старой
|
||||
ветке listen_port может относиться к прокси, поэтому этот параметр не принимается
|
||||
за порт веб-интерфейса.
|
||||
|
||||
Результат включается в защищённый Heartbeat. Кэш обнаружения находится только
|
||||
в /tmp/owrt-remote-tachyon, обновляется не реже раза в 30 секунд и не содержит
|
||||
конфигураций или секретов. Временные файлы удаляются; размер файла ограничен.
|
||||
Неудачная проверка пакетов не считается удалением Tachyon. Hub сохраняет
|
||||
последний подтверждённый факт установки, но показывает Offline.
|
||||
|
||||
У каждого роутера отдельное состояние. После успешной проверки отсутствующего
|
||||
пакета блок исчезает. После новой установки он появляется автоматически. Смена
|
||||
только состояния службы не перезапускает серверный Xray.
|
||||
|
||||
## Удалённый доступ
|
||||
|
||||
Кнопка открывает /tachyon/ROUTER_ID/ в отдельной вкладке. Проверяется вход
|
||||
в Hub и право Админки A именно на выбранный роутер. Изменяющие запросы
|
||||
дополнительно проверяют Origin/Referer. Пароли и токены не добавляются в URL.
|
||||
|
||||
Для отдельного веб-сервера Hub выделяет свободный вход Xray, доступный только
|
||||
на 127.0.0.1 VPS. Он использует уже существующий аутентифицированный reverse
|
||||
канал Админки. В клиенте добавляется правило только для обнаруженного TCP-порта
|
||||
127.0.0.1:PORT и соответствующего reverse-тега. Остальной HTTP и SSH идут
|
||||
по прежним правилам. Адрес назначения фиксирован; HTTP-запрос не может выбрать
|
||||
другой хост или порт.
|
||||
|
||||
При установке, удалении или смене порта Tachyon агент обновляет конфигурацию
|
||||
только своего Xray. Возможен короткий разрыв обратного туннеля. Heartbeat
|
||||
продолжает работать; ручная остановка Xray через Remote сохраняется. Автоматическая
|
||||
операция использует общую блокировку с Remote управлением Xray.
|
||||
Настройки Tachyon, WAN, DNS, Podkop, firewall и policy routing не меняются.
|
||||
|
||||
HTML, LuCI-ресурсы, fetch/XHR и REST-пути переписываются с префиксом выбранного
|
||||
роутера. Cookies Tachyon получают собственный путь; сессионные cookies Hub
|
||||
не отправляются на роутер. Старый Tachyon открывается через существующий
|
||||
авторизованный прокси LuCI.
|
||||
|
||||
Online означает свежий Heartbeat, запущенный процесс Xray и доступность
|
||||
интерфейса по локальной проверке агента. Это не заменяет фактическую проверку
|
||||
открытия страницы: внешняя проблема туннеля может проявиться при переходе.
|
||||
Offline сохраняет кнопку, чтобы не путать недоступность с удалением пакета.
|
||||
|
||||
## Реальные интерфейсы Tachyon
|
||||
|
||||
Изучены [main](https://github.com/Dushnilin/tachyon) и исходники установленной
|
||||
у пользователя версии
|
||||
[v2.0.0-beta.8](https://github.com/Dushnilin/tachyon/tree/v2.0.0-beta.8) и
|
||||
[v2.0.0-beta.14](https://github.com/Dushnilin/tachyon/tree/v2.0.0-beta.14).
|
||||
Архитектура этих веток различается, поэтому одного README недостаточно.
|
||||
|
||||
В beta.8 Rust HTTP-сервер отдаёт LuCI SPA и ubus-мост на 1680. REST API находится
|
||||
в /api/agent/v1, включая health и openapi.json; CGI-подобный alias
|
||||
/cgi-bin/tachyon-agent обслуживается этим же Rust-сервером. Он не означает,
|
||||
что такой CGI-файл есть у uhttpd на 80. API проверяет сессию, Bearer token либо
|
||||
доверенный локальный адрес. Интеграция не извлекает и не сохраняет API-токены:
|
||||
открытие происходит через авторизованный Hub, а оригинальная авторизация
|
||||
Tachyon сохраняется.
|
||||
|
||||
В другой изученной ветке CGI /cgi-bin/tachyon-agent относится к uhttpd.
|
||||
Агент проверяет существование файла и успешный read-only health-ответ перед
|
||||
передачей метаданных API. Для Rust API на обнаруженном порту проверяется
|
||||
типизированное поле core_running; остановленное ядро не приравнивается
|
||||
к отсутствию REST API. Если OpenAPI сообщает версию работающей программы,
|
||||
она отображается в карточке; версия пакета сохраняется отдельно в package_version.
|
||||
Управление Tachyon через отдельные Hub-команды
|
||||
в эту реализацию не входит.
|
||||
|
||||
## Локальная установка и откат
|
||||
|
||||
Сначала обновить VPS, затем агент роутера:
|
||||
|
||||
~~~powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-tachyon.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Install
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router root@192.168.2.1 -Action Install
|
||||
~~~
|
||||
|
||||
Пароль вводится в SSH, не передаётся в аргументах. Скрипт проверяет синтаксис,
|
||||
создаёт резервную копию, сверяет установленные файлы и проверяет запуск
|
||||
Heartbeat либо ревизию работающего Hub. База и конфиг owrtremote сохраняются.
|
||||
Миграция базы добавляет один совместимый столбец для внутреннего порта.
|
||||
|
||||
Откат в обратном порядке:
|
||||
|
||||
~~~powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router root@192.168.2.1 -Action Rollback
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Rollback
|
||||
~~~
|
||||
|
||||
Копия на каждом устройстве: /root/owrt-remote-backup-before-tachyon-integration-v121.
|
||||
При откате VPS прежний генератор пересоздаёт конфигурацию Xray без нового входа.
|
||||
Дополнительный столбец базы безвреден для прежнего Hub и не удаляется.
|
||||
|
||||
Проверка после установки:
|
||||
|
||||
~~~powershell
|
||||
ssh root@192.168.2.1 'owrt-remote tachyon-status'
|
||||
~~~
|
||||
|
||||
Дождаться одного Heartbeat и обновить страницу Hub через Ctrl+F5. При обычном
|
||||
интервале обнаружение занимает до 30–60 секунд. Для проверки локального кода
|
||||
использовать этот скрипт, поскольку опубликованная сборка GitHub пока другая.
|
||||
|
||||
## Проверки
|
||||
|
||||
По предоставленному пользователем выводу реального роутера: пакет
|
||||
tachyon 2.0.0~beta.8-1, служба tachyon запущена, uhttpd на 80,
|
||||
tachyon.settings.listen_port=1680, HTTP 200 на loopback и LAN:1680,
|
||||
старый LuCI URL возвращает 403. CGI REST на uhttpd не найден.
|
||||
Дополнительные GET-запросы с компьютера подтвердили HTTP 200 для корневой
|
||||
страницы, /api/agent/v1/health и /api/agent/v1/openapi.json на порту 1680.
|
||||
Health сообщил core_running=true; OpenAPI и заголовок страницы сообщили
|
||||
2.0.0-beta.14, хотя пакетный менеджер показывает beta.8. Эти версии намеренно
|
||||
не смешиваются. Переустановка или обновление Tachyon не выполнялись.
|
||||
|
||||
Локальные тесты проверяют opkg/APK, старый LuCI, собственный порт, остановку,
|
||||
ошибку инвентаризации, удаление/переустановку, независимость роутеров,
|
||||
потерю/восстановление Heartbeat, запрещённые адреса/порты и ручную остановку Xray.
|
||||
HTTP-тесты проверяют 401/403, выбор роутера, изоляцию cookies, REST POST/PUT/DELETE
|
||||
и защиту Origin. Node проверяет появление/исчезновение блока, Offline,
|
||||
экранирование и обе реализации карточек.
|
||||
|
||||
Настоящие Xray 26.6.27 (клиент) и 26.10.21 (сервер) успешно провели одновременно
|
||||
HTTP Админки, SSH и отдельный HTTP Tachyon с разными ответами. Проверены оба
|
||||
генератора конфигурации. Это стенд на loopback, не реальный удалённый роутер.
|
||||
Дополнительно прошли 41 регрессия WAN/Heartbeat, 22 проверки пакетов и проверки
|
||||
Remote управления Xray. Установку/удаление и остановку Tachyon на рабочем
|
||||
роутере ради теста не выполняли; установка локальной интеграции на него
|
||||
и проверка через рабочую VPS ещё предстоят.
|
||||
Четыре сценария обнаружения и генерации выполнены в Linux на BusyBox ash 1.36.1.
|
||||
Пять сценариев установщика проверяют повторную установку, откат с удалением
|
||||
ранее отсутствовавшего helper, ошибки preflight и восстановление после отказа
|
||||
перезапуска. Дополнительные команды пакетов на рабочем роутере не выполнялись.
|
||||
В отдельной Ubuntu 24.04 выполнены установка нового Hub и откат этим же
|
||||
PowerShell-скриптом: работающая ревизия подтверждена в обоих случаях.
|
||||
Проверено также переписывание настоящего HTML интерфейса с роутера и синтаксис
|
||||
встроенных скриптов после переписывания.
|
||||
|
||||
Изменённые и добавленные файлы: files/usr/sbin/owrt-remote,
|
||||
files/usr/lib/owrt-remote/tachyon.sh, install.sh, uninstall.sh, vps/owrt-remote-hub.py,
|
||||
vps/deploy-tachyon.ps1, vps/diagnose-tachyon.ps1, tests/test_tachyon.py,
|
||||
tests/test_tachyon_ui.cjs, tests/test_tachyon_deploy.py, tests/test_xray_reverse_transport.py,
|
||||
README.md и этот документ.
|
||||
|
||||
## Исправление для VPS с Xray 26.3.27
|
||||
|
||||
На рабочем сервере подтверждён Xray 26.3.27. Этот выпуск принимает имя
|
||||
протокола tunnel, но использует исходные настройки network/address/port,
|
||||
игнорируя новые allowedNetwork/rewriteAddress/rewritePort. Поэтому в reverse
|
||||
передавался порт входа VPS вместо 1680, правило клиента не совпадало и запрос
|
||||
получал обычную Админку. Это объясняет переход на /cgi-bin/luci/.
|
||||
|
||||
Генератор Hub теперь выдаёт оба набора полей с одинаковыми значениями.
|
||||
На настоящем Xray 26.3.27 ошибка воспроизведена до исправления: отдельный вход
|
||||
Tachyon возвращал ответ HTTP-стенда Админки. После исправления он возвращает
|
||||
ответ именно Tachyon; HTTP Админки и SSH продолжают работать.
|
||||
|
||||
Для уже установленной локальной интеграции нужно применить исправление на VPS:
|
||||
|
||||
~~~powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-tachyon-route-fix.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Install
|
||||
~~~
|
||||
|
||||
Скрипт сохраняет текущие файлы Hub и Xray, дополняет только настройки
|
||||
управляемых Remote входов, проверяет JSON установленным Xray, затем применяет
|
||||
изменения и перезапускает Hub и серверный Xray. Остальные параметры JSON,
|
||||
включая порт VLESS, клиентов и посторонние службы, сохраняются.
|
||||
На время перезапуска возможен короткий разрыв туннелей. Бинарники Xray
|
||||
и файлы роутера не меняются.
|
||||
|
||||
Откат именно этого исправления:
|
||||
|
||||
~~~powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Rollback
|
||||
~~~
|
||||
|
||||
Оба файла восстанавливаются из
|
||||
/root/owrt-remote-backup-before-tachyon-route-fix-v121. Неудачная проверка Xray
|
||||
останавливает установку до замены файлов; отказ перезапуска вызывает
|
||||
восстановление копии текущей попытки.
|
||||
|
||||
Дополнительно добавлены vps/deploy-tachyon-route-fix.ps1,
|
||||
vps/diagnose-tachyon-vps.ps1 и tests/test_tachyon_route_deploy.py.
|
||||
Диагностика VPS передаёт код в base64, чтобы Windows PowerShell не повреждал
|
||||
завершение Python heredoc. По первоначальному выводу данные были собраны
|
||||
полностью; завершающий NameError: PY относится к передаче скрипта, а не к Xray.
|
||||
|
||||
## Пустое место над интерфейсом
|
||||
|
||||
Общий обработчик оформления Hub первоначально исключал /access/, но не новый
|
||||
маршрут /tachyon/. В страницу Tachyon попадало правило общих эффектов,
|
||||
устанавливающее position:relative для прямых дочерних элементов body.
|
||||
Оно переопределяло position:fixed у .tachyon-bg-layer. Фон становился обычным
|
||||
блоком и сдвигал панель ниже первого экрана; в браузере воспроизведён отступ 720 px.
|
||||
|
||||
Обработка /tachyon/ теперь сохраняет собственные CSS и JavaScript Tachyon.
|
||||
Переписывание URL для удалённого доступа продолжает работать.
|
||||
Принудительная прокрутка и дополнительные отступы не добавляются.
|
||||
|
||||
Для уже установленной интеграции:
|
||||
|
||||
~~~powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-tachyon-layout.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Install
|
||||
~~~
|
||||
|
||||
Откат:
|
||||
|
||||
~~~powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps root@132.243.19.232 -Action Rollback
|
||||
~~~
|
||||
|
||||
Установка меняет только файл Hub и перезапускает его веб-службу. Копия:
|
||||
/root/owrt-remote-backup-before-tachyon-layout-v121. Файлы роутера и конфигурация
|
||||
Xray при установке этого исправления не меняются.
|
||||
|
||||
Проверки: два теста общих тем, два HTTP-теста прокси и 18 браузерных сочетаний
|
||||
1280x900 / 390x844 / 844x390 с сохранёнными режимами default / winter / lite.
|
||||
В браузере проверены самостоятельный пример и настоящий HTML Tachyon beta.14:
|
||||
фон имеет position:fixed, верх maincontent находится на 0 px, прокрутка равна
|
||||
нулю, дополнительный canvas Hub отсутствует. Загрузка RPC в этой проверке
|
||||
отключена, поэтому параметры роутера не изменяются.
|
||||
|
||||
Дополнительно добавлены vps/deploy-tachyon-layout.ps1 и tests/test_tachyon_layout.cjs;
|
||||
обновлены tests/test_hub_design_global.py и tests/test_tachyon.py.
|
||||
@@ -101,6 +101,14 @@ journald, ротация и активность таймера. Успех по
|
||||
API роутеров продолжают работать. Нестандартная конфигурация вызывает ошибку
|
||||
с причиной и откат, а не ложное сообщение об успехе.
|
||||
|
||||
Установка обслуживания при первом переходе запускается через отдельную службу
|
||||
`owrt-remote-log-maintenance-<id>` у системного systemd. Ограничение
|
||||
`CapabilityBoundingSet=CAP_NET_BIND_SERVICE` у веб-службы Hub сохраняется:
|
||||
проверка Nginx и ротация выполняются с системными правами в отдельной задаче.
|
||||
Права и владельцы `/var/log/nginx/*.log` не меняются ради обхода ошибок доступа.
|
||||
Предупреждение Nginx `protocol options redefined` само по себе не означает
|
||||
отказ; итог определяется кодом возврата команды и её сообщением об ошибке.
|
||||
|
||||
Если после нажатия кнопки страница продолжает показывать прежнюю сборку,
|
||||
обновить её через Ctrl+F5. Номер версии остаётся v121; новая сборка определяется
|
||||
по SHA256. Отдельные команды установки выше сохраняются для ручного применения.
|
||||
@@ -233,6 +241,14 @@ Python `invalid escape sequence '\s'` в другом HTML-шаблоне Hub н
|
||||
новых настроек: копия текущего обновления успешно вернула исходные файлы,
|
||||
Hub продолжил работать, а результат обновления содержит причину отказа.
|
||||
|
||||
Отдельно воспроизведён `Permission denied` у `nginx -T` при ограничении
|
||||
`CapabilityBoundingSet=CAP_NET_BIND_SERVICE`, используемом штатной службой Hub.
|
||||
С этим же ограничением первый переход со старой сборки через кнопку успешно
|
||||
установил обслуживание в отдельной задаче systemd. Ограничение Hub, владелец
|
||||
и режим `www-data:adm 0640` журнала Nginx, ключи/настройки и целостность SQLite
|
||||
сохранены. Проверены 9 регрессий установки компонентов, 19 проверок обновления
|
||||
и 6 проверок локального тестового обновления.
|
||||
|
||||
Разработчикам: после изменения `vps/log-maintenance.py` выполнить
|
||||
`python scripts/embed-log-maintenance.py`; команда с `--check` и тесты проверяют,
|
||||
что встроенный скрипт совпадает с исходником. Внутренний параметр `--backup`
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# Автоматическая установка и загрузка Xray
|
||||
|
||||
Исправление общее для OpenWrt с opkg/IPK и apk/APK. Версия интерфейса — v122.
|
||||
Изменения включены в v122 и используются установщиком и агентом из GitHub.
|
||||
|
||||
## Что было неправильно
|
||||
|
||||
Наличие curl считалось достаточным: при его ошибке другие клиенты не запускались.
|
||||
Без curl выбирался только один из uclient-fetch/wget. При этом wget часто является
|
||||
ссылкой на uclient-fetch. Отказ предварительного HEAD исключал даже доступный
|
||||
через GET пакет. Ошибка сети запускала перебор старых релизов и могла закончиться
|
||||
сообщением об отсутствии совместимого Xray.
|
||||
|
||||
Лог GL-MT6000 подтверждает сбой загрузки, но не устанавливает его сетевую причину.
|
||||
DNS, TLS, HTTP и сбой самого клиента различаются новой диагностикой на устройстве.
|
||||
|
||||
## Что изменено
|
||||
|
||||
- До замены файлов установщик проверяет curl, CA и jsonfilter. Недостающие пакеты
|
||||
устанавливаются через обнаруженный менеджер. Ошибка зависимостей останавливает
|
||||
установку отдельным этапом, до подготовки Xray.
|
||||
- Установщик и агент используют один загрузчик, встроенный в оба файла. Исходник —
|
||||
`scripts/router-download.sh`; обновление встроенных копий —
|
||||
`python scripts/embed-router-download.py`, проверка — та же команда с `--check`.
|
||||
- curl → uclient-fetch → wget: переход происходит после ошибки, ссылки на один
|
||||
исполняемый файл не повторяются. Частичные ответы удаляются. Секреты, URL с
|
||||
параметрами, подписанные адреса перенаправлений и сырые заголовки не печатаются.
|
||||
- Для Xray выполняется GET без обязательного HEAD. Один файл имеет общий бюджет
|
||||
до 120 секунд на все клиенты и источники, подготовка Xray — до 300 секунд.
|
||||
Завершение процессов и уборка временных данных могут занять ещё несколько секунд.
|
||||
- DNS/TLS/тайм-аут/403 останавливают перебор пакетов. Подтверждённый 404/410 позволяет
|
||||
проверить следующий опубликованный asset. Ошибки совместимости проверяют следующие
|
||||
кандидаты в пределах общего бюджета.
|
||||
- Список релизов, имена файлов, размеры и SHA256 берутся из официального GitHub API.
|
||||
Сохраняются проверки формата, точной архитектуры/ABI, зависимостей целевой системы,
|
||||
версии и фактической поддержки VLESS reverse. Фиксированной версии пакета нет.
|
||||
- Существующий исправный Xray используется повторно. Проверенная постоянная сжатая
|
||||
копия создаётся до замены бинарника; восстановление из неё не требует GitHub.
|
||||
- Без настроек Hub установка возвращает успех и сообщает:
|
||||
«Установлено. Добавьте OpenWrt config из Hub для запуска туннеля».
|
||||
Существующие UCI и ключ веб-панели сохраняются.
|
||||
|
||||
В диагностике `http=000` означает, что клиент не сообщил HTTP-статус. Это не ответ
|
||||
HTTP 000. Например, DNS-сбой curl показывает `tool=curl; http=000; rc=6; reason=DNS`.
|
||||
`client_context` сохраняет отдельную причину ошибки контекста uclient: она сама по
|
||||
себе не доказывает проблему TLS или нехватку RAM.
|
||||
|
||||
curl сохраняет разрешение DNS и привязку каждого перенаправления к выбранному WAN.
|
||||
Резервные минимальные клиенты используют системный DNS, о чём агент сообщает при
|
||||
WAN direct. Скрипты не меняют WAN/DNS/маршруты/Podkop/Xray transport.
|
||||
|
||||
## Зеркало
|
||||
|
||||
Готового доверенного зеркала проекта сейчас нет. По умолчанию используются только
|
||||
официальные GitHub API/Assets; случайные публичные прокси не подключаются.
|
||||
Полная недоступность GitHub без исправного локального Xray/кэша остаётся явной
|
||||
ошибкой загрузки. Смена клиента не гарантирует обход сетевой блокировки.
|
||||
|
||||
Для будущего собственного HTTPS-зеркала предусмотрены `XRAY_PACKAGE_MIRROR`
|
||||
в окружении или `owrtremote.main.xray_package_mirror` в UCI. Формат адресов:
|
||||
`https://YOUR-MIRROR/xray/vVERSION/PUBLISHED_ASSET_NAME`. Адрес не должен содержать
|
||||
пароль, query или fragment. Ожидаемая SHA256 всё равно берётся из официального API;
|
||||
метаданные зеркало не подменяет. При включённом зеркале первая половина бюджета
|
||||
файла отведена официальному источнику, вторая остаётся для зеркала.
|
||||
|
||||
## Локальная проверка на роутере
|
||||
|
||||
PowerShell Windows 11; отдельная установка исправления на существующий клиент:
|
||||
|
||||
```powershell
|
||||
$Fix = Join-Path $env:USERPROFILE 'Documents\openwrt overlay\vps\deploy-xray-download-fix.ps1'
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router root@192.168.2.1 -Action Install
|
||||
```
|
||||
|
||||
Скрипт сохраняет агент в
|
||||
`/root/owrt-remote-backup-before-xray-download-v121`, устанавливает новый агент и
|
||||
выполняет `prepare-xray`. При ошибке автоматически восстанавливает прежний агент.
|
||||
Рабочий Xray, проверенный кэш и настройки не удаляются. Действующий туннель
|
||||
скрипт не перезапускает. Если первая установка прервалась до создания web.key,
|
||||
ключ создаётся только при его отсутствии.
|
||||
|
||||
Откат кода агента, с сохранением исправного бинарника и кэша:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router root@192.168.2.1 -Action Rollback
|
||||
```
|
||||
|
||||
Для первичной установки из локальных исходников установщик также можно запускать
|
||||
на роутере из копии проекта. Публичная однострочная команда не меняется:
|
||||
|
||||
```sh
|
||||
wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/install.sh?v=$(date +%s)" | sh
|
||||
```
|
||||
|
||||
Диагностический режим установки включается переменной
|
||||
`OWRT_REMOTE_INSTALL_DIAGNOSTIC=1` у процесса `sh`, исполняющего установщик. Он
|
||||
показывает stdout/stderr этапов и коды возврата, без `set -x` и дампа UCI.
|
||||
|
||||
## Проверки
|
||||
|
||||
Регрессионные сценарии: отказ curl с успешным резервным клиентом; дедупликация
|
||||
wget/uclient-fetch; сохранение исходного rc; DNS/TLS/ошибка записи; отсутствие HEAD;
|
||||
остановка перебора при сетевой ошибке; 404; общий бюджет; зависший дочерний процесс;
|
||||
официальная SHA256 при использовании зеркала; повреждённый пакет; сохранение
|
||||
рабочего Xray и загрузочного кэша; установка и откат локального исправления.
|
||||
|
||||
Матрица выбора assets проверяет IPK/APK и точные имена aarch64, ARM, MIPS/MIPSel,
|
||||
MIPS64, i386 и x86_64. Она не означает, что upstream публикует пакет для каждого
|
||||
теоретического имени CPU. Если соответствующего asset нет, чужая архитектура
|
||||
не подставляется. Прогоны BusyBox ash и реальные роутеры отмечаются отдельно;
|
||||
полный физический прогон на всех CPU не заявляется.
|
||||
|
||||
Результаты локального прогона 21.11.2026:
|
||||
|
||||
- Linux BusyBox ash 1.36.1: 38 проверок успешны, включая 22 комбинации
|
||||
точных архитектур и форматов в одной проверке матрицы.
|
||||
- Windows POSIX shell: в основном прогоне bootstrap/выбора релизов/установщика
|
||||
55 тестов прошли, 2 требуют Linux; дополнительные проверки упаковки и локального
|
||||
развёртывания также успешны.
|
||||
- Реальная HTTPS-загрузка официального release asset размером 12 243 318 байт
|
||||
через новый код прошла с HTTP 200; SHA256 совпала с GitHub API. Этот файл
|
||||
использован только для проверки скачивания, на роутер он не устанавливался.
|
||||
- Установка на проблемный физический GL-MT6000 / OpenWrt 25.12.6 ещё не выполнена.
|
||||
@@ -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'
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/bin/sh
|
||||
# Discovery only: never starts/stops Tachyon or changes its UCI/network settings.
|
||||
TACHYON_RUNTIME="${OWRT_REMOTE_TACHYON_RUNTIME:-${TMPDIR:-/tmp}/owrt-remote-tachyon}"
|
||||
|
||||
tachyon_inventory_failed() {
|
||||
if [ -s "$TACHYON_RUNTIME/status" ]; then
|
||||
sed 's/"checked":true/"checked":false/;s/"available":true/"available":false/' "$TACHYON_RUNTIME/status"
|
||||
else printf '{"checked":false}'; fi
|
||||
}
|
||||
|
||||
tachyon_json() (
|
||||
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; }
|
||||
if [ "${1:-}" != force ] && [ -s "$TACHYON_RUNTIME/status" ]; then
|
||||
now="$(cut -d. -f1 /proc/uptime)"
|
||||
last="$(cat "$TACHYON_RUNTIME/updated" 2>/dev/null)"
|
||||
case "$last" in ''|*[!0-9]*) ;; *)
|
||||
if [ "$now" -ge "$last" ] && [ $((now-last)) -lt 30 ]; then cat "$TACHYON_RUNTIME/status"; return; fi ;;
|
||||
esac
|
||||
fi
|
||||
dir="$(mktemp -d "$TACHYON_RUNTIME/probe.XXXXXX")" || { printf '{"checked":false}'; return; }
|
||||
trap 'rm -f "$dir/package" "$dir/json"; rmdir "$dir" 2>/dev/null || true' EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
package=''; version=''
|
||||
if command -v apk >/dev/null 2>&1; then
|
||||
apk info >"$dir/package" 2>/dev/null || { tachyon_inventory_failed; return; }
|
||||
for pkg in tachyon luci-app-tachyon; do
|
||||
grep -qx "$pkg" "$dir/package" || continue
|
||||
package="$pkg"
|
||||
# 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
|
||||
for pkg in tachyon luci-app-tachyon; do
|
||||
opkg status "$pkg" >"$dir/package" 2>/dev/null || { tachyon_inventory_failed; return; }
|
||||
package="$(awk '/^Package:/{p=$2} /^Status:.* installed$/{print p;exit}' "$dir/package")"
|
||||
[ -n "$package" ] || continue
|
||||
version="$(awk -v wanted="$package" '/^Package:/{p=$2} p==wanted && /^Version:/{print $2;exit}' "$dir/package")"
|
||||
break
|
||||
done
|
||||
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; 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
|
||||
service=unknown
|
||||
for pkg in tachyon tachyon-core; do
|
||||
rc="$(ubus call service list "{\"name\":\"$pkg\"}" 2>/dev/null |
|
||||
jsonfilter -e "@[\"$pkg\"].instances.*.running" 2>/dev/null)"
|
||||
if printf '%s\n' "$rc" | grep -qx true; then service=running; break; fi
|
||||
[ -z "$rc" ] || service=stopped
|
||||
done
|
||||
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)"
|
||||
else
|
||||
port=0
|
||||
admin_port="$(uci_get admin_port 80)"
|
||||
case "$admin_port" in ''|*[!0-9]*) admin_port=80 ;; esac
|
||||
[ "$admin_port" -gt 0 ] && [ "$admin_port" -le 65535 ] || admin_port=80
|
||||
code="$(curl -q -s --noproxy '*' --connect-timeout 1 --max-time 2 -o /dev/null \
|
||||
-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
|
||||
[ -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
|
||||
fi
|
||||
for pkg in tachyon-api tachyon-agent; do
|
||||
[ -z "$api" ] || break
|
||||
[ -e "/www/cgi-bin/$pkg" ] || continue
|
||||
rc="$(curl -q -fsS --noproxy '*' --max-time 1 \
|
||||
"http://127.0.0.1/cgi-bin/$pkg/health" 2>/dev/null |
|
||||
jsonfilter -e '@.success' 2>/dev/null)"
|
||||
[ "$rc" != true ] || { api="/cgi-bin/$pkg"; break; }
|
||||
done
|
||||
printf '{"checked":true,"installed":true,"version":%s,"package_version":%s,"mode":"%s","port":%s,"service":"%s","available":%s,"api":%s}\n' \
|
||||
"$(json_string "$(printf '%s' "$version" | head -c 80)")" "$(json_string "$(printf '%s' "$package_version" | head -c 80)")" \
|
||||
"$mode" "$port" "$service" "$available" "$(json_string "$api")" >"$dir/json"
|
||||
fi
|
||||
cat "$dir/json"
|
||||
mv -f "$dir/json" "$TACHYON_RUNTIME/status"
|
||||
cut -d. -f1 /proc/uptime >"$TACHYON_RUNTIME/updated"
|
||||
)
|
||||
|
||||
tachyon_tunnel_port() {
|
||||
local state port
|
||||
state="$(tachyon_json)"
|
||||
[ "$(printf '%s' "$state" | jsonfilter -e '@.installed' 2>/dev/null)" = true ] || { printf 0; return; }
|
||||
[ "$(printf '%s' "$state" | jsonfilter -e '@.mode' 2>/dev/null)" = standalone ] || { printf 0; return; }
|
||||
port="$(printf '%s' "$state" | jsonfilter -e '@.port' 2>/dev/null)"
|
||||
case "$port" in ''|*[!0-9]*) port=0 ;; esac
|
||||
[ "$port" -ge 1024 ] && [ "$port" -le 65535 ] || port=0
|
||||
printf '%s' "$port"
|
||||
}
|
||||
|
||||
tachyon_reconcile_xray() {
|
||||
local desired current config slot
|
||||
truthy "$(uci_get enabled 0)" || return 0
|
||||
xray_control_stopped && return 0
|
||||
xray_running || return 0
|
||||
[ "$(tachyon_json | jsonfilter -e '@.checked' 2>/dev/null)" = true ] || return 0
|
||||
desired="$(tachyon_tunnel_port)"
|
||||
config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
|
||||
current="$(jsonfilter -i "$config" -e '@.outbounds[@.tag="router-tachyon"].settings.redirect' 2>/dev/null)"
|
||||
[ "$desired" != 0 ] || desired=''
|
||||
[ -z "$desired" ] || desired="127.0.0.1:$desired"
|
||||
[ "$current" != "$desired" ] || return 0
|
||||
slot="$(cut -d. -f1 /proc/uptime)"; slot=$((slot/120))
|
||||
ubus call service add "{\"name\":\"owrt-remote\",\"instances\":{\"tachyon-reconfigure\":{\"command\":[\"/usr/sbin/owrt-remote\",\"tachyon-reconfigure\",\"$desired\",\"$slot\"],\"stdout\":true,\"stderr\":true}}}" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
tachyon_reconfigure() (
|
||||
xray_control_lock "$CONTROL_RUNTIME/worker-lock" || return 0
|
||||
trap 'rm -f "$CONTROL_RUNTIME/worker-lock/pid"; rmdir "$CONTROL_RUNTIME/worker-lock" 2>/dev/null || true' EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
xray_control_stopped && return 0
|
||||
truthy "$(uci_get enabled 0)" || return 0
|
||||
log 'Tachyon: обновление локального маршрута в обратном туннеле'
|
||||
xray_control_execute restart
|
||||
)
|
||||
+287
-84
@@ -38,6 +38,7 @@ usage() {
|
||||
owrt-remote heartbeat
|
||||
owrt-remote heartbeat-loop
|
||||
owrt-remote heartbeat-diagnostics
|
||||
owrt-remote tachyon-status
|
||||
owrt-remote logs-sync
|
||||
owrt-remote network-diagnostics
|
||||
|
||||
@@ -149,6 +150,14 @@ else
|
||||
xray_control_result_json() { printf null; }
|
||||
xray_control_dispatch() { return 0; }
|
||||
fi
|
||||
TACHYON_HELPER="${OWRT_REMOTE_TACHYON_HELPER:-/usr/lib/owrt-remote/tachyon.sh}"
|
||||
if [ -r "$TACHYON_HELPER" ]; then
|
||||
. "$TACHYON_HELPER"
|
||||
else
|
||||
tachyon_json() { printf '{"checked":false}'; }
|
||||
tachyon_tunnel_port() { printf 0; }
|
||||
tachyon_reconcile_xray() { :; }
|
||||
fi
|
||||
|
||||
host_model() {
|
||||
if [ -r /tmp/sysinfo/model ]; then
|
||||
@@ -447,8 +456,8 @@ xray_discover_releases() (
|
||||
# Older pages are fetched on demand after candidates fail validation.
|
||||
page="${3:-1}"
|
||||
while [ "$page" -le 10 ]; do
|
||||
fetch_file "$XRAY_RELEASE_API_URL?per_page=20&page=$page" "$work/releases.json" || {
|
||||
log 'ERROR: GitHub API unavailable; existing Xray preserved'; return 1;
|
||||
DOWNLOAD_STAGE=xray-releases fetch_file "$XRAY_RELEASE_API_URL?per_page=20&page=$page" "$work/releases.json" || {
|
||||
rc=$?; log "ERROR: GitHub API unavailable (rc=$rc); existing Xray preserved"; return "$rc";
|
||||
}
|
||||
[ "$(wc -c <"$work/releases.json")" -le 2097152 ] || return 1
|
||||
# Validate JSON, including an empty array. API error objects fail closed.
|
||||
@@ -613,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
|
||||
@@ -631,20 +651,28 @@ 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
|
||||
)
|
||||
|
||||
render_client_config() (
|
||||
local tachyon_port
|
||||
tachyon_port="$(tachyon_tunnel_port)"
|
||||
local temp_dir rc xray_host out stdout router_id vps_host vps_port uuid ssh_uuid encryption flow reverse_tag ssh_reverse_tag admin_host admin_port ssh_host ssh_port xray_config xray_config_dir
|
||||
temp_dir=""
|
||||
out=""
|
||||
@@ -672,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)"
|
||||
@@ -696,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}"
|
||||
@@ -718,6 +777,7 @@ render_client_config() (
|
||||
},
|
||||
"inbounds": [],
|
||||
"outbounds": [
|
||||
$([ "$tachyon_port" = 0 ] || printf '{"tag":"router-tachyon","protocol":"freedom","settings":{"redirect":"127.0.0.1:%s","finalRules":[{"action":"allow","network":"tcp","port":%s}]}},' "$tachyon_port" "$tachyon_port")
|
||||
{
|
||||
"tag": "router-admin",
|
||||
"protocol": "freedom",
|
||||
@@ -749,7 +809,7 @@ render_client_config() (
|
||||
},
|
||||
"streamSettings": {
|
||||
"network": "tcp",
|
||||
"security": "none"$wan_sockopt
|
||||
$transport_stream$wan_sockopt
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -767,12 +827,13 @@ render_client_config() (
|
||||
},
|
||||
"streamSettings": {
|
||||
"network": "tcp",
|
||||
"security": "none"$wan_sockopt
|
||||
$transport_stream$wan_sockopt
|
||||
}
|
||||
}
|
||||
],
|
||||
"routing": {
|
||||
"rules": [
|
||||
$([ "$tachyon_port" = 0 ] || printf '{"type":"field","inboundTag":["%s"],"ip":["127.0.0.1"],"port":%s,"outboundTag":"router-tachyon"},' "$(json_escape "$reverse_tag")" "$tachyon_port")
|
||||
{
|
||||
"type": "field",
|
||||
"inboundTag": [
|
||||
@@ -862,6 +923,7 @@ heartbeat_json() {
|
||||
"xray_control": $([ -r "$CONTROL_HELPER" ] && printf 1 || printf 0),
|
||||
"xray_control_result": $(xray_control_result_json || printf null),
|
||||
"ssh": $(json_string "$ssh_state"),
|
||||
"tachyon": $(tachyon_json),
|
||||
"event": $(json_string "$event"),
|
||||
"service": $(json_string "$service_state")
|
||||
}
|
||||
@@ -1289,6 +1351,7 @@ send_heartbeat() {
|
||||
mv -f "$dir/last" "${TMPDIR:-/tmp}/owrt-remote-heartbeat-last"
|
||||
cat "$response"
|
||||
xray_control_dispatch "$response" || log 'Remote Xray: команда не принята; повторная доставка при следующем Heartbeat'
|
||||
tachyon_reconcile_xray || log 'Tachyon: обновление маршрута отложено'
|
||||
log "Heartbeat: OK; Hub=$safe_endpoint; WAN_direct=$(uci_get wan_direct 0); WAN_active=$(cat "$WAN_STATE/active-interface" 2>/dev/null)"
|
||||
return 0
|
||||
fi
|
||||
@@ -1703,77 +1766,184 @@ xray_cache_restore() (
|
||||
return 1
|
||||
)
|
||||
|
||||
# Keep a finite wait even without BusyBox's optional timeout applet. The
|
||||
# foreground poll avoids a racing/orphaned watchdog when downloads finish fast.
|
||||
xray_native_fetch() (
|
||||
dst="$1"; shift
|
||||
client=''
|
||||
trap 'result=$?; [ -z "$client" ] || { kill -KILL "$client" 2>/dev/null || true; wait "$client" 2>/dev/null || true; }; [ "$result" = 0 ] || rm -f "$dst"' EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
# Shells report file blocks in 512 or 1024 bytes: either limit stays <=32 MiB.
|
||||
ulimit -f 32768 || return 1
|
||||
"$@" & client=$!
|
||||
ticks=0
|
||||
while kill -0 "$client" 2>/dev/null; do
|
||||
if [ "$ticks" -ge 120 ]; then
|
||||
kill -KILL "$client" 2>/dev/null || true
|
||||
wait "$client" 2>/dev/null || true
|
||||
client=''; return 28
|
||||
# BEGIN SHARED ROUTER DOWNLOADER
|
||||
# Shared, embedded in install.sh and the router agent by embed-router-download.py.
|
||||
# No dependency on curl/jsonfilter/timeout is needed to bootstrap curl itself.
|
||||
download_clock() {
|
||||
if [ -r /proc/uptime ]; then cut -d. -f1 /proc/uptime; else date +%s; fi
|
||||
}
|
||||
download_note() {
|
||||
if command -v log >/dev/null 2>&1; then log "$*"; else printf '%s\n' "$*" >&2; fi
|
||||
}
|
||||
download_origin() {
|
||||
local authority
|
||||
case "$1" in https://?*) ;; *) return 3 ;; esac
|
||||
authority="${1#https://}"; authority="${authority%%/*}"
|
||||
case "$authority" in ''|*[@\?\#\ ]*|*[!A-Za-z0-9.:-]*) return 3 ;; esac
|
||||
case "$authority" in *:*) ;; *) authority="$authority:443" ;; esac
|
||||
printf 'https://%s' "$authority"
|
||||
}
|
||||
download_signal_tree() {
|
||||
local child
|
||||
# Kill descendants first: a timed-out shell function may own a DNS client.
|
||||
if [ -r "/proc/$1/task/$1/children" ]; then
|
||||
for child in $(cat "/proc/$1/task/$1/children"); do download_signal_tree "$child" "$2"; done
|
||||
fi
|
||||
kill -"$2" "$1" 2>/dev/null || true
|
||||
}
|
||||
download_kill_tree() {
|
||||
local ticks
|
||||
download_signal_tree "$1" TERM
|
||||
# Allow shell EXIT traps to release locks and staging files first.
|
||||
ticks=0
|
||||
while kill -0 "$1" 2>/dev/null && [ "$ticks" -lt 2 ]; do sleep 1; ticks=$((ticks+1)); done
|
||||
download_signal_tree "$1" KILL
|
||||
}
|
||||
download_run() (
|
||||
seconds="$1"; shift; child=''
|
||||
trap 'result=$?; [ -z "$child" ] || { download_kill_tree "$child"; wait "$child" 2>/dev/null || true; }; exit "$result"' EXIT
|
||||
trap 'exit 28' INT TERM
|
||||
"$@" & child=$!
|
||||
ticks=0
|
||||
while kill -0 "$child" 2>/dev/null; do
|
||||
[ "$ticks" -lt "$seconds" ] || return 28
|
||||
sleep 1; ticks=$((ticks+1))
|
||||
done
|
||||
rc=0; wait "$client" || rc=$?; client=''
|
||||
return "$rc"
|
||||
rc=0; wait "$child" || rc=$?; child=''; return "$rc"
|
||||
)
|
||||
|
||||
# Bound one complete download, including redirects. In WAN mode use the
|
||||
# selected resolver on every HTTPS hop, retaining hostname verification/SNI.
|
||||
fetch_file() (
|
||||
url="$1"; dst="$2"; method="${3:-GET}"; rm -f "$dst"
|
||||
stats=''
|
||||
trap 'result=$?; rm -f "$stats"; [ "$result" = 0 ] || rm -f "$dst"' EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
stats="$(mktemp "${TMPDIR:-/tmp}/owrt-xray-http.XXXXXX")" || return 1
|
||||
started="$(remote_clock_ms)"; hop=0; rc=1
|
||||
download_curl() (
|
||||
url="$1"; dst="$2"; stats="$3"; method="$4"; deadline="$5"; hop=0
|
||||
while [ "$hop" -le 5 ]; do
|
||||
origin="$(remote_url_origin "$url")" || return 3
|
||||
case "$origin" in https://*) ;; *) log 'Xray: отклонена загрузка без HTTPS'; return 3 ;; esac
|
||||
origin="$(download_origin "$url")" || return 3
|
||||
set -- -q -fsS --connect-timeout 10 --noproxy '*' --proto '=https' --max-filesize 33554432
|
||||
[ "$method" != HEAD ] || set -- "$@" -I
|
||||
if truthy "$(uci_get wan_direct 0)"; then
|
||||
host="${origin#https://}"; port="${host##*:}"; host="${host%:*}"
|
||||
device="$(wan_device)" || return 1
|
||||
ip="$(wan_resolve_host "$host")" || return 6
|
||||
set -- "$@" --interface "$device" --resolve "$host:$port:$ip"
|
||||
fi
|
||||
remaining=$((120000 - $(remote_clock_ms) + started))
|
||||
DL_DEVICE=''; DL_RESOLVE=''
|
||||
# The agent resolves every redirect through its selected WAN. The
|
||||
# installer has no routing hook and uses the router's system resolver.
|
||||
if command -v download_route >/dev/null 2>&1; then download_route "$origin" || return $?; fi
|
||||
[ -z "$DL_DEVICE" ] || set -- "$@" --interface "$DL_DEVICE"
|
||||
[ -z "$DL_RESOLVE" ] || set -- "$@" --resolve "$DL_RESOLVE"
|
||||
remaining=$((deadline - $(download_clock)))
|
||||
[ "$remaining" -gt 0 ] || return 28
|
||||
remaining="$(LC_ALL=C awk -v ms="$remaining" 'BEGIN { printf "%.3f", ms/1000 }')"
|
||||
rc=0
|
||||
curl "$@" --max-time "$remaining" -o "$dst" -w '%{http_code} %{redirect_url}\n' "$url" >"$stats" || rc=$?
|
||||
curl "$@" --max-time "$remaining.000" -o "$dst" -w '%{http_code} %{redirect_url}\n' "$url" >"$stats" || rc=$?
|
||||
[ "$rc" = 0 ] || return "$rc"
|
||||
code=''; redirect=''; read -r code redirect <"$stats" || true
|
||||
case "$code" in
|
||||
301|302|303|307|308) rc=47; [ -n "$redirect" ] || return 47; url="$redirect"; hop=$((hop+1)) ;;
|
||||
200) [ -s "$dst" ] || { rc=1; return 1; }; return 0 ;;
|
||||
*) rc=22; return 22 ;;
|
||||
301|302|303|307|308) [ -n "$redirect" ] || return 47; url="$redirect"; hop=$((hop+1)) ;;
|
||||
200) [ -s "$dst" ] || return 52; return 0 ;;
|
||||
*) return 22 ;;
|
||||
esac
|
||||
done
|
||||
return 47
|
||||
)
|
||||
download_reason() {
|
||||
case "$1" in
|
||||
3) printf invalid_https_url; return ;; 6) printf DNS; return ;;
|
||||
23|27) printf write; return ;; 28|124|137) printf timeout; return ;;
|
||||
35|51|58|60|77|80|82|83|90|91) printf TLS; return ;;
|
||||
esac
|
||||
if LC_ALL=C grep -Eqi 'no space|permission denied|read-only|write error|file too large' "$2"; then printf write
|
||||
elif LC_ALL=C grep -Eqi 'resolv|bad address|name or service|DNS' "$2"; then printf DNS
|
||||
elif LC_ALL=C grep -qi 'uclient context' "$2"; then printf client_context
|
||||
elif LC_ALL=C grep -Eqi 'TLS|SSL|certificate' "$2"; then printf TLS
|
||||
elif LC_ALL=C grep -Eqi 'timed out|timeout' "$2"; then printf timeout
|
||||
elif [ "$3" != 000 ]; then printf HTTP
|
||||
else printf network; fi
|
||||
}
|
||||
download_tools() {
|
||||
local tool path identity seen
|
||||
seen='|'
|
||||
for tool in curl uclient-fetch wget; do
|
||||
path="$(command -v "$tool" 2>/dev/null)" || continue
|
||||
identity="$(readlink -f "$path" 2>/dev/null)"; identity="${identity:-$path}"
|
||||
case "$seen" in *"|$identity|"*) continue ;; esac
|
||||
seen="$seen$identity|"; printf '%s\n' "$tool"
|
||||
done
|
||||
}
|
||||
remote_download() (
|
||||
url="$1"; dst="$2"; method="${3:-GET}"
|
||||
work="$(mktemp -d "${TMPDIR:-/tmp}/owrt-download.XXXXXX")" || return 23
|
||||
trap 'result=$?; rm -rf "$work"; [ "$result" = 0 ] || rm -f "$dst"; exit "$result"' EXIT
|
||||
trap 'exit 28' INT TERM
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY
|
||||
# Also bound native clients and their error/response files on small RAM.
|
||||
ulimit -f 32768 || return 23
|
||||
deadline=$(( $(download_clock) + 120 ))
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || : >"$DOWNLOAD_RESULT_FILE"
|
||||
for outer in "${XRAY_PREPARE_DEADLINE:-}" "${XRAY_FILE_DEADLINE:-}" "${DOWNLOAD_SOURCE_DEADLINE:-}"; do
|
||||
[ -z "$outer" ] || [ "$outer" -ge "$deadline" ] || deadline="$outer"
|
||||
done
|
||||
origin="$(download_origin "$url")" || { download_note 'Download: reason=invalid_https_url; rc=3'; return 3; }
|
||||
tools="$(download_tools)"; set -- $tools; left="$#"; rc=127
|
||||
[ "$left" -gt 0 ] || download_note 'Download: stage=tools; reason=no_http_client; rc=127'
|
||||
for tool in $tools; do
|
||||
remaining=$((deadline - $(download_clock)))
|
||||
[ "$remaining" -gt 0 ] || { rc=28; reason=timeout; break; }
|
||||
# Reserve time for genuinely different fallback clients. No blind
|
||||
# retries on dozens of releases when their common host is unavailable.
|
||||
seconds=$((remaining / left)); [ "$seconds" -gt 0 ] || seconds=1
|
||||
left=$((left-1)); attempt_end=$(( $(download_clock) + seconds ))
|
||||
rm -f "$dst"; : >"$work/stats"; : >"$work/error"; rc=0
|
||||
case "$tool" in
|
||||
curl) download_run "$seconds" download_curl "$url" "$dst" "$work/stats" "$method" "$attempt_end" 2>"$work/error" || rc=$? ;;
|
||||
*)
|
||||
if command -v download_native_notice >/dev/null 2>&1; then download_native_notice; fi
|
||||
download_run "$seconds" "$tool" -T "$seconds" -O "$dst" "$url" >"$work/stats" 2>"$work/error" || rc=$? ;;
|
||||
esac
|
||||
code=000
|
||||
if [ "$tool" = curl ]; then
|
||||
read -r code ignored <"$work/stats" || true
|
||||
case "$code" in [1-5][0-9][0-9]) ;; *) code=000 ;; esac
|
||||
else
|
||||
code="$(LC_ALL=C sed -n -e 's/.*HTTP\/[0-9.]* *\([1-5][0-9][0-9]\).*/\1/p' -e 's/.*HTTP error \([1-5][0-9][0-9]\).*/\1/p' -e 's/.*awaiting response[. ]*\([1-5][0-9][0-9]\).*/\1/p' "$work/error" | tail -n 1)"
|
||||
code="${code:-000}"
|
||||
fi
|
||||
# Minimal images without curl keep bounded native HTTPS clients. These do
|
||||
# not offer curl's per-host resolver override.
|
||||
if truthy "$(uci_get wan_direct 0)"; then log 'Xray: curl отсутствует; загрузчик использует системный DNS'; fi
|
||||
rc=1
|
||||
case "$url" in https://*) ;; *) return 3 ;; esac
|
||||
if command -v uclient-fetch >/dev/null 2>&1; then
|
||||
xray_native_fetch "$dst" uclient-fetch -q -T 15 -O "$dst" "$url" && rc=0
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
xray_native_fetch "$dst" wget -q -T 15 -O "$dst" "$url" && rc=0
|
||||
if [ "$rc" = 0 ]; then
|
||||
[ -s "$dst" ] && [ "$(wc -c <"$dst")" -le 33554432 ] || rc=23
|
||||
fi
|
||||
[ "$rc" = 0 ] && [ -s "$dst" ] && [ "$(wc -c <"$dst")" -le 33554432 ]
|
||||
reason="$(download_reason "$rc" "$work/error" "$code")"
|
||||
[ "$rc" != 0 ] || reason=ok
|
||||
# Never print URLs, query strings, redirect signatures or raw headers.
|
||||
download_note "Download: stage=${DOWNLOAD_STAGE:-file}; tool=$tool; host=$origin; http=$code; rc=$rc; reason=$reason"
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "$reason" "$code" >"$DOWNLOAD_RESULT_FILE"
|
||||
[ "$rc" != 0 ] || return 0
|
||||
case "$reason" in write|invalid_https_url) break ;; esac
|
||||
done
|
||||
[ "$rc" != 28 ] || download_note 'Download: reason=timeout; file/preparation deadline reached or HTTP client timed out'
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "${reason:-no_http_client}" "${code:-000}" >"$DOWNLOAD_RESULT_FILE"
|
||||
return "$rc"
|
||||
)
|
||||
# END SHARED ROUTER DOWNLOADER
|
||||
|
||||
# Keep WAN policy for every curl redirect; native fallback uses system DNS.
|
||||
download_route() {
|
||||
local host port ip
|
||||
truthy "$(uci_get wan_direct 0)" || return 0
|
||||
host="${1#https://}"; port="${host##*:}"; host="${host%:*}"
|
||||
DL_DEVICE="$(wan_device)" || return 1
|
||||
ip="$(wan_resolve_host "$host")" || return 6
|
||||
DL_RESOLVE="$host:$port:$ip"
|
||||
}
|
||||
fetch_file() { remote_download "$@"; }
|
||||
download_native_notice() {
|
||||
if truthy "$(uci_get wan_direct 0)"; then log 'Download: native fallback uses system DNS; WAN settings unchanged'; fi
|
||||
}
|
||||
xray_native_fetch() (
|
||||
dst="$1"; shift
|
||||
trap 'result=$?; [ "$result" = 0 ] || rm -f "$dst"' EXIT
|
||||
ulimit -f 32768 || return 23
|
||||
download_run 120 "$@"
|
||||
)
|
||||
xray_prepare_timed() (
|
||||
now="$(download_clock)"; deadline=$((now + 300))
|
||||
[ -z "${XRAY_PREPARE_DEADLINE:-}" ] || [ "$XRAY_PREPARE_DEADLINE" -ge "$deadline" ] || deadline="$XRAY_PREPARE_DEADLINE"
|
||||
XRAY_PREPARE_DEADLINE="$deadline"
|
||||
export XRAY_PREPARE_DEADLINE
|
||||
remaining=$((deadline - now)); [ "$remaining" -gt 0 ] || return 28
|
||||
rc=0; download_run "$remaining" "$@" || rc=$?
|
||||
[ "$rc" != 28 ] || log 'Xray: preparation timeout (300s); existing Xray and cache preserved'
|
||||
return "$rc"
|
||||
)
|
||||
|
||||
install_package() {
|
||||
@@ -1781,10 +1951,10 @@ install_package() {
|
||||
rc=0
|
||||
if command -v apk >/dev/null 2>&1; then
|
||||
log "Xray dependency: apk -U add $1"
|
||||
apk -U add "$1" >&2 || rc=$?
|
||||
download_run 120 apk -U add "$1" >&2 || rc=$?
|
||||
elif command -v opkg >/dev/null 2>&1; then
|
||||
log "Xray dependency: opkg update && opkg install $1"
|
||||
opkg update >&2 && opkg install "$1" >&2 || rc=$?
|
||||
download_run 120 opkg update >&2 && download_run 120 opkg install "$1" >&2 || rc=$?
|
||||
else
|
||||
log 'Xray: no supported package manager (apk/opkg)'
|
||||
return 1
|
||||
@@ -1886,39 +2056,66 @@ xray_package_extract_binary() (
|
||||
xray_binary_usable() {
|
||||
[ -x "$1" ] && "$1" version >/dev/null 2>&1 && ! xray_requires_legacy_replacement "$1"
|
||||
}
|
||||
xray_probe_url() {
|
||||
# Use the same TLS/WAN/redirect policy as the actual GET.
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
fetch_file "$1" "$2" HEAD
|
||||
else
|
||||
# uclient-fetch has no HEAD mode. A bounded HTTPS GET is the probe
|
||||
# and payload together, with its size/digest checked before extraction.
|
||||
return 0
|
||||
xray_download_package() (
|
||||
url="$1"; package="$2"; tag="$3"; asset="$4"
|
||||
XRAY_FILE_DEADLINE=$(( $(download_clock) + 120 ))
|
||||
export XRAY_FILE_DEADLINE
|
||||
# No third-party proxy is assumed trusted. Opt-in mirrors serve only
|
||||
# published assets; the caller still verifies the OFFICIAL API digest.
|
||||
mirror="${XRAY_PACKAGE_MIRROR:-$(uci_get xray_package_mirror '')}"
|
||||
if [ -n "$mirror" ]; then
|
||||
case "$mirror" in *[\?\#\@]*|*[!A-Za-z0-9_./:+-]*) log 'Xray: invalid HTTPS mirror configuration'; return 3 ;; esac
|
||||
download_origin "$mirror" >/dev/null || return 3
|
||||
DOWNLOAD_SOURCE_DEADLINE=$(( $(download_clock) + 60 ))
|
||||
fi
|
||||
}
|
||||
DOWNLOAD_STAGE=xray-package
|
||||
rc=0; fetch_file "$url" "$package" || rc=$?
|
||||
[ "$rc" != 0 ] || return 0
|
||||
unset DOWNLOAD_SOURCE_DEADLINE
|
||||
if [ -n "$mirror" ]; then
|
||||
log 'Xray: official asset download failed; trying configured HTTPS mirror with official SHA256'
|
||||
DOWNLOAD_STAGE=xray-mirror
|
||||
fetch_file "${mirror%/}/$tag/$asset" "$package" && return 0
|
||||
rc=$?
|
||||
else
|
||||
log 'Xray: HTTPS mirror not configured; no third-party download proxy used'
|
||||
fi
|
||||
return "$rc"
|
||||
)
|
||||
|
||||
install_xray_tmp_locked() (
|
||||
XRAY_PREPARE_DEADLINE="${XRAY_PREPARE_DEADLINE:-$(( $(download_clock) + 300 ))}"
|
||||
export XRAY_PREPARE_DEADLINE
|
||||
dir="$(xray_runtime_dir)"
|
||||
mkdir -p "$dir" || return 1
|
||||
work="$(mktemp -d "$dir/.download.XXXXXX")" || return 1
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
ensure_ca_certificates || { log 'Xray: trusted CA certificates unavailable; existing Xray preserved'; return 1; }
|
||||
ensure_fetch_tool || { log 'Xray: need curl, uclient-fetch or wget'; return 1; }
|
||||
ensure_ca_certificates || { log 'Xray: stage=dependencies; trusted CA certificates unavailable; existing Xray preserved'; return 1; }
|
||||
ensure_fetch_tool || { log 'Xray: stage=dependencies; need curl, uclient-fetch or wget'; return 1; }
|
||||
command -v jsonfilter >/dev/null 2>&1 || install_package jsonfilter || { log 'Xray: stage=dependencies; jsonfilter unavailable'; return 1; }
|
||||
rc=1
|
||||
page=1
|
||||
while [ "$page" -le 10 ]; do
|
||||
xray_discover_releases "$work/candidates" "$work" "$page" || return 1
|
||||
[ "$(download_clock)" -lt "$XRAY_PREPARE_DEADLINE" ] || return 28
|
||||
xray_discover_releases "$work/candidates" "$work" "$page" || return $?
|
||||
while IFS='|' read -r tag asset url digest bytes; do
|
||||
# Keep the published name for native package-manager diagnostics.
|
||||
rm -f "$work/xray.new" "${package:-$work/unused}"
|
||||
package="$work/$asset"
|
||||
log "Xray: candidate: $asset; checking download URL..."
|
||||
xray_probe_url "$url" "$work/headers" || { rc=$?; log "Xray: URL unavailable (rc=$rc); candidate skipped"; continue; }
|
||||
log "Xray: загрузка пакета yichya/openwrt-xray/$asset; общий тайм-аут=120s"
|
||||
fetch_file "$url" "$package" || { rc=$?; log "ERROR: GitHub download unavailable (rc=$rc); existing Xray preserved"; continue; }
|
||||
[ "$(wc -c <"$package")" = "$bytes" ] || { log 'Xray: package length mismatch'; rc=1; continue; }
|
||||
log "Xray: candidate: $asset; downloading verified GET (file <=120s, preparation <=300s)"
|
||||
DOWNLOAD_RESULT_FILE="$work/download-result"
|
||||
xray_download_package "$url" "$package" "$tag" "$asset" || {
|
||||
rc=$?; http=''; reason=''; ignored=''
|
||||
[ ! -s "$DOWNLOAD_RESULT_FILE" ] || read -r ignored reason http <"$DOWNLOAD_RESULT_FILE"
|
||||
log "ERROR: published Xray package found but download failed (rc=$rc; reason=${reason:-network}; http=${http:-unknown}); existing Xray preserved"
|
||||
# Only a confirmed missing asset may select another candidate.
|
||||
# DNS/TLS/timeout/403 must not trigger a storm of old downloads.
|
||||
case "$http" in 404|410) continue ;; *) return "$rc" ;; esac
|
||||
}
|
||||
[ "$(wc -c <"$package")" = "$bytes" ] || { log 'Xray: stage=verify; reason=size; package length mismatch'; rc=1; continue; }
|
||||
log 'Xray: verifying package checksum...'
|
||||
[ "$(xray_digest "$package")" = "$digest" ] || { log 'Xray: package SHA256 mismatch; existing Xray preserved'; rc=1; continue; }
|
||||
[ "$(xray_digest "$package")" = "$digest" ] || { log 'Xray: stage=verify; reason=SHA256; package SHA256 mismatch; existing Xray preserved'; rc=1; continue; }
|
||||
xray_check_package_metadata "$package" "$work" "$asset" || { rc=$?; continue; }
|
||||
xray_package_extract_binary "$package" "$work/xray.new" "$asset" || { rc=$?; log "Xray: extraction failed for $asset (rc=$rc)"; continue; }
|
||||
[ -s "$work/xray.new" ] && [ "$(wc -c <"$work/xray.new")" -le 67108864 ] || { rc=1; continue; }
|
||||
@@ -1991,10 +2188,10 @@ prepare_xray_tmp() (
|
||||
if xray_binary_usable "$configured"; then return 0; fi
|
||||
xray_cache_restore && return 0
|
||||
log 'Xray: загрузочной копии нет; требуется загрузка из сети'
|
||||
install_xray_tmp_locked
|
||||
xray_prepare_timed install_xray_tmp_locked
|
||||
)
|
||||
prepare_xray() (
|
||||
ensure_xray_available || return 1
|
||||
ensure_xray_available || return $?
|
||||
bin="$(xray_bin_path)"
|
||||
case "$bin" in
|
||||
/tmp/*|"$(xray_runtime_dir)"/*)
|
||||
@@ -2095,10 +2292,10 @@ case "$cmd" in
|
||||
heartbeat_diagnostics
|
||||
;;
|
||||
install-xray-tmp)
|
||||
install_xray_tmp
|
||||
xray_prepare_timed install_xray_tmp
|
||||
;;
|
||||
prepare-xray)
|
||||
prepare_xray
|
||||
xray_prepare_timed prepare_xray
|
||||
;;
|
||||
xray-package-diagnostics)
|
||||
xray_package_diagnostics
|
||||
@@ -2112,6 +2309,12 @@ case "$cmd" in
|
||||
xray-control-execute)
|
||||
xray_control_execute "$@"
|
||||
;;
|
||||
tachyon-status)
|
||||
tachyon_json force
|
||||
;;
|
||||
tachyon-reconfigure)
|
||||
tachyon_reconfigure
|
||||
;;
|
||||
render-client)
|
||||
xray_apply_trace render-client
|
||||
render_client_config "$@" || exit $?
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
KEY_FILE="${KEY_FILE:-/etc/owrt-remote/web.key}"
|
||||
AGENT="${AGENT:-/usr/sbin/owrt-remote}"
|
||||
LOG_HELPER="${OWRT_REMOTE_LOG_HELPER:-/usr/lib/owrt-remote/logs.sh}"
|
||||
OWRT_REMOTE_UI_VERSION="2026-07-02-mobile-terminal-batch-v25"
|
||||
OWRT_REMOTE_UI_VERSION="2026-11-21-v122"
|
||||
PARAMS_FILE="${TMPDIR:-/tmp}/owrt-remote-cgi.$$"
|
||||
RESULT_TITLE=""
|
||||
RESULT_BODY=""
|
||||
@@ -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
|
||||
@@ -515,7 +515,7 @@ render_page() {
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="owrt-remote-ui-version" content="$OWRT_REMOTE_UI_VERSION">
|
||||
<title>OpenWrt Remote Hub v121</title>
|
||||
<title>OpenWrt Remote Hub v122</title>
|
||||
<script>
|
||||
try {
|
||||
const design = localStorage.getItem('owrtRemote:hubDesign');
|
||||
@@ -564,7 +564,7 @@ html[data-hub-shared-effects="1"] body::before,html[data-hub-shared-effects="1"]
|
||||
<div class="brand">
|
||||
<div class="brandPanel">
|
||||
<div class="titleRow">
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v121</span></span></h1>
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v122</span></span></h1>
|
||||
</div>
|
||||
<div class="links">
|
||||
<a class="uiPill" href="https://t.me/kzolotarev95" target="_blank" rel="noopener noreferrer">Telegram</a>
|
||||
@@ -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."
|
||||
|
||||
@@ -14,7 +14,7 @@ return view.extend({
|
||||
|
||||
if (!key) {
|
||||
return E('div', { 'class': 'cbi-map' }, [
|
||||
E('h2', {}, _('OpenWrt Remote Hub v121')),
|
||||
E('h2', {}, _('OpenWrt Remote Hub v122')),
|
||||
E('div', { 'class': 'alert-message warning' }, [
|
||||
_('Web key not found. Reinstall the module or create /etc/owrt-remote/web.key.')
|
||||
])
|
||||
@@ -34,7 +34,7 @@ return view.extend({
|
||||
}, 100);
|
||||
|
||||
return E('div', { 'class': 'cbi-map' }, [
|
||||
E('h2', {}, _('OpenWrt Remote Hub v121')),
|
||||
E('h2', {}, _('OpenWrt Remote Hub v122')),
|
||||
E('p', {}, _('Opening remote access panel...')),
|
||||
E('p', {}, [
|
||||
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Open panel'))
|
||||
|
||||
+186
-25
@@ -60,18 +60,156 @@ target_path() {
|
||||
printf '%s/%s' "${ROOT%/}" "$1"
|
||||
}
|
||||
|
||||
fetch() {
|
||||
local src dst
|
||||
src="$1"
|
||||
dst="$2"
|
||||
if command -v wget >/dev/null 2>&1; then
|
||||
wget -O "$dst" "$src"
|
||||
elif command -v curl >/dev/null 2>&1; then
|
||||
curl -fsSL "$src" -o "$dst"
|
||||
else
|
||||
die "для удаленной установки нужен wget или curl"
|
||||
fi
|
||||
# BEGIN SHARED ROUTER DOWNLOADER
|
||||
# Shared, embedded in install.sh and the router agent by embed-router-download.py.
|
||||
# No dependency on curl/jsonfilter/timeout is needed to bootstrap curl itself.
|
||||
download_clock() {
|
||||
if [ -r /proc/uptime ]; then cut -d. -f1 /proc/uptime; else date +%s; fi
|
||||
}
|
||||
download_note() {
|
||||
if command -v log >/dev/null 2>&1; then log "$*"; else printf '%s\n' "$*" >&2; fi
|
||||
}
|
||||
download_origin() {
|
||||
local authority
|
||||
case "$1" in https://?*) ;; *) return 3 ;; esac
|
||||
authority="${1#https://}"; authority="${authority%%/*}"
|
||||
case "$authority" in ''|*[@\?\#\ ]*|*[!A-Za-z0-9.:-]*) return 3 ;; esac
|
||||
case "$authority" in *:*) ;; *) authority="$authority:443" ;; esac
|
||||
printf 'https://%s' "$authority"
|
||||
}
|
||||
download_signal_tree() {
|
||||
local child
|
||||
# Kill descendants first: a timed-out shell function may own a DNS client.
|
||||
if [ -r "/proc/$1/task/$1/children" ]; then
|
||||
for child in $(cat "/proc/$1/task/$1/children"); do download_signal_tree "$child" "$2"; done
|
||||
fi
|
||||
kill -"$2" "$1" 2>/dev/null || true
|
||||
}
|
||||
download_kill_tree() {
|
||||
local ticks
|
||||
download_signal_tree "$1" TERM
|
||||
# Allow shell EXIT traps to release locks and staging files first.
|
||||
ticks=0
|
||||
while kill -0 "$1" 2>/dev/null && [ "$ticks" -lt 2 ]; do sleep 1; ticks=$((ticks+1)); done
|
||||
download_signal_tree "$1" KILL
|
||||
}
|
||||
download_run() (
|
||||
seconds="$1"; shift; child=''
|
||||
trap 'result=$?; [ -z "$child" ] || { download_kill_tree "$child"; wait "$child" 2>/dev/null || true; }; exit "$result"' EXIT
|
||||
trap 'exit 28' INT TERM
|
||||
"$@" & child=$!
|
||||
ticks=0
|
||||
while kill -0 "$child" 2>/dev/null; do
|
||||
[ "$ticks" -lt "$seconds" ] || return 28
|
||||
sleep 1; ticks=$((ticks+1))
|
||||
done
|
||||
rc=0; wait "$child" || rc=$?; child=''; return "$rc"
|
||||
)
|
||||
download_curl() (
|
||||
url="$1"; dst="$2"; stats="$3"; method="$4"; deadline="$5"; hop=0
|
||||
while [ "$hop" -le 5 ]; do
|
||||
origin="$(download_origin "$url")" || return 3
|
||||
set -- -q -fsS --connect-timeout 10 --noproxy '*' --proto '=https' --max-filesize 33554432
|
||||
[ "$method" != HEAD ] || set -- "$@" -I
|
||||
DL_DEVICE=''; DL_RESOLVE=''
|
||||
# The agent resolves every redirect through its selected WAN. The
|
||||
# installer has no routing hook and uses the router's system resolver.
|
||||
if command -v download_route >/dev/null 2>&1; then download_route "$origin" || return $?; fi
|
||||
[ -z "$DL_DEVICE" ] || set -- "$@" --interface "$DL_DEVICE"
|
||||
[ -z "$DL_RESOLVE" ] || set -- "$@" --resolve "$DL_RESOLVE"
|
||||
remaining=$((deadline - $(download_clock)))
|
||||
[ "$remaining" -gt 0 ] || return 28
|
||||
rc=0
|
||||
curl "$@" --max-time "$remaining.000" -o "$dst" -w '%{http_code} %{redirect_url}\n' "$url" >"$stats" || rc=$?
|
||||
[ "$rc" = 0 ] || return "$rc"
|
||||
code=''; redirect=''; read -r code redirect <"$stats" || true
|
||||
case "$code" in
|
||||
301|302|303|307|308) [ -n "$redirect" ] || return 47; url="$redirect"; hop=$((hop+1)) ;;
|
||||
200) [ -s "$dst" ] || return 52; return 0 ;;
|
||||
*) return 22 ;;
|
||||
esac
|
||||
done
|
||||
return 47
|
||||
)
|
||||
download_reason() {
|
||||
case "$1" in
|
||||
3) printf invalid_https_url; return ;; 6) printf DNS; return ;;
|
||||
23|27) printf write; return ;; 28|124|137) printf timeout; return ;;
|
||||
35|51|58|60|77|80|82|83|90|91) printf TLS; return ;;
|
||||
esac
|
||||
if LC_ALL=C grep -Eqi 'no space|permission denied|read-only|write error|file too large' "$2"; then printf write
|
||||
elif LC_ALL=C grep -Eqi 'resolv|bad address|name or service|DNS' "$2"; then printf DNS
|
||||
elif LC_ALL=C grep -qi 'uclient context' "$2"; then printf client_context
|
||||
elif LC_ALL=C grep -Eqi 'TLS|SSL|certificate' "$2"; then printf TLS
|
||||
elif LC_ALL=C grep -Eqi 'timed out|timeout' "$2"; then printf timeout
|
||||
elif [ "$3" != 000 ]; then printf HTTP
|
||||
else printf network; fi
|
||||
}
|
||||
download_tools() {
|
||||
local tool path identity seen
|
||||
seen='|'
|
||||
for tool in curl uclient-fetch wget; do
|
||||
path="$(command -v "$tool" 2>/dev/null)" || continue
|
||||
identity="$(readlink -f "$path" 2>/dev/null)"; identity="${identity:-$path}"
|
||||
case "$seen" in *"|$identity|"*) continue ;; esac
|
||||
seen="$seen$identity|"; printf '%s\n' "$tool"
|
||||
done
|
||||
}
|
||||
remote_download() (
|
||||
url="$1"; dst="$2"; method="${3:-GET}"
|
||||
work="$(mktemp -d "${TMPDIR:-/tmp}/owrt-download.XXXXXX")" || return 23
|
||||
trap 'result=$?; rm -rf "$work"; [ "$result" = 0 ] || rm -f "$dst"; exit "$result"' EXIT
|
||||
trap 'exit 28' INT TERM
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY
|
||||
# Also bound native clients and their error/response files on small RAM.
|
||||
ulimit -f 32768 || return 23
|
||||
deadline=$(( $(download_clock) + 120 ))
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || : >"$DOWNLOAD_RESULT_FILE"
|
||||
for outer in "${XRAY_PREPARE_DEADLINE:-}" "${XRAY_FILE_DEADLINE:-}" "${DOWNLOAD_SOURCE_DEADLINE:-}"; do
|
||||
[ -z "$outer" ] || [ "$outer" -ge "$deadline" ] || deadline="$outer"
|
||||
done
|
||||
origin="$(download_origin "$url")" || { download_note 'Download: reason=invalid_https_url; rc=3'; return 3; }
|
||||
tools="$(download_tools)"; set -- $tools; left="$#"; rc=127
|
||||
[ "$left" -gt 0 ] || download_note 'Download: stage=tools; reason=no_http_client; rc=127'
|
||||
for tool in $tools; do
|
||||
remaining=$((deadline - $(download_clock)))
|
||||
[ "$remaining" -gt 0 ] || { rc=28; reason=timeout; break; }
|
||||
# Reserve time for genuinely different fallback clients. No blind
|
||||
# retries on dozens of releases when their common host is unavailable.
|
||||
seconds=$((remaining / left)); [ "$seconds" -gt 0 ] || seconds=1
|
||||
left=$((left-1)); attempt_end=$(( $(download_clock) + seconds ))
|
||||
rm -f "$dst"; : >"$work/stats"; : >"$work/error"; rc=0
|
||||
case "$tool" in
|
||||
curl) download_run "$seconds" download_curl "$url" "$dst" "$work/stats" "$method" "$attempt_end" 2>"$work/error" || rc=$? ;;
|
||||
*)
|
||||
if command -v download_native_notice >/dev/null 2>&1; then download_native_notice; fi
|
||||
download_run "$seconds" "$tool" -T "$seconds" -O "$dst" "$url" >"$work/stats" 2>"$work/error" || rc=$? ;;
|
||||
esac
|
||||
code=000
|
||||
if [ "$tool" = curl ]; then
|
||||
read -r code ignored <"$work/stats" || true
|
||||
case "$code" in [1-5][0-9][0-9]) ;; *) code=000 ;; esac
|
||||
else
|
||||
code="$(LC_ALL=C sed -n -e 's/.*HTTP\/[0-9.]* *\([1-5][0-9][0-9]\).*/\1/p' -e 's/.*HTTP error \([1-5][0-9][0-9]\).*/\1/p' -e 's/.*awaiting response[. ]*\([1-5][0-9][0-9]\).*/\1/p' "$work/error" | tail -n 1)"
|
||||
code="${code:-000}"
|
||||
fi
|
||||
if [ "$rc" = 0 ]; then
|
||||
[ -s "$dst" ] && [ "$(wc -c <"$dst")" -le 33554432 ] || rc=23
|
||||
fi
|
||||
reason="$(download_reason "$rc" "$work/error" "$code")"
|
||||
[ "$rc" != 0 ] || reason=ok
|
||||
# Never print URLs, query strings, redirect signatures or raw headers.
|
||||
download_note "Download: stage=${DOWNLOAD_STAGE:-file}; tool=$tool; host=$origin; http=$code; rc=$rc; reason=$reason"
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "$reason" "$code" >"$DOWNLOAD_RESULT_FILE"
|
||||
[ "$rc" != 0 ] || return 0
|
||||
case "$reason" in write|invalid_https_url) break ;; esac
|
||||
done
|
||||
[ "$rc" != 28 ] || download_note 'Download: reason=timeout; file/preparation deadline reached or HTTP client timed out'
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "${reason:-no_http_client}" "${code:-000}" >"$DOWNLOAD_RESULT_FILE"
|
||||
return "$rc"
|
||||
)
|
||||
# END SHARED ROUTER DOWNLOADER
|
||||
fetch() { remote_download "$1" "$2"; }
|
||||
|
||||
install_file() {
|
||||
local rel mode src dst bust
|
||||
@@ -85,6 +223,7 @@ install_file() {
|
||||
run_step "file:$rel" cp "$src" "$INSTALL_CANDIDATE"
|
||||
else
|
||||
bust="$(date +%s 2>/dev/null || echo $$)"
|
||||
DOWNLOAD_STAGE="file:$rel"
|
||||
run_step "file:$rel" fetch "$RAW_URL/files/$rel?v=$bust" "$INSTALL_CANDIDATE"
|
||||
fi
|
||||
chmod "$mode" "$INSTALL_CANDIDATE"
|
||||
@@ -102,13 +241,7 @@ install_config() {
|
||||
info "Оставляю существующий конфиг: $dst"
|
||||
return
|
||||
fi
|
||||
if [ -f "$src" ]; then
|
||||
cp "$src" "$dst"
|
||||
else
|
||||
bust="$(date +%s 2>/dev/null || echo $$)"
|
||||
fetch "$RAW_URL/files/$rel?v=$bust" "$dst"
|
||||
fi
|
||||
chmod 0644 "$dst"
|
||||
install_file "$rel" 0644
|
||||
}
|
||||
|
||||
make_key() {
|
||||
@@ -198,12 +331,12 @@ install_packages() {
|
||||
manager="$(package_manager)"
|
||||
case "$manager" in
|
||||
opkg)
|
||||
run_step packages-index opkg update || return $?
|
||||
run_step packages-install opkg install "$@"
|
||||
run_step packages-index download_run 120 opkg update || return $?
|
||||
run_step packages-install download_run 120 opkg install "$@"
|
||||
;;
|
||||
apk)
|
||||
run_step packages-index apk update || return $?
|
||||
run_step packages-install apk add "$@"
|
||||
run_step packages-index download_run 120 apk update || return $?
|
||||
run_step packages-install download_run 120 apk add "$@"
|
||||
;;
|
||||
*)
|
||||
return 1
|
||||
@@ -211,6 +344,27 @@ install_packages() {
|
||||
esac
|
||||
}
|
||||
|
||||
ensure_install_dependencies() {
|
||||
local need ca
|
||||
[ "${ROOT%/}" = "" ] || return 0
|
||||
INSTALL_STAGE=dependencies
|
||||
need=''
|
||||
if ! command -v curl >/dev/null 2>&1 || ! curl --version >/dev/null 2>&1; then need="$need curl"; fi
|
||||
command -v jsonfilter >/dev/null 2>&1 || need="$need jsonfilter"
|
||||
if [ ! -s /etc/ssl/cert.pem ] && [ ! -s /etc/ssl/certs/ca-certificates.crt ]; then
|
||||
case "$(package_manager)" in apk) ca=ca-certificates ;; *) ca=ca-bundle ;; esac
|
||||
need="$need $ca"
|
||||
fi
|
||||
if [ -n "$need" ]; then
|
||||
info "Подготовка HTTPS/JSON зависимостей: $need"
|
||||
install_packages $need || die 'dependency installation failed; application files and existing Xray retained'
|
||||
fi
|
||||
INSTALL_STAGE=dependencies-check
|
||||
command -v curl >/dev/null 2>&1 && command -v jsonfilter >/dev/null 2>&1 || die 'curl/jsonfilter unavailable after dependency installation'
|
||||
curl --version >/dev/null 2>&1 || die 'installed curl cannot run on this firmware'
|
||||
[ -s /etc/ssl/cert.pem ] || [ -s /etc/ssl/certs/ca-certificates.crt ] || die 'trusted CA bundle unavailable after dependency installation'
|
||||
}
|
||||
|
||||
ensure_wol_support() {
|
||||
local need manager tool_pkg candidate
|
||||
[ "${ROOT%/}" = "" ] || return 0
|
||||
@@ -244,12 +398,16 @@ ensure_wol_support() {
|
||||
}
|
||||
|
||||
install_xray_runtime() {
|
||||
local remote_bin
|
||||
local remote_bin rc
|
||||
[ "${ROOT%/}" = "" ] || return 0
|
||||
remote_bin="$(target_path usr/sbin/owrt-remote)"
|
||||
[ -x "$remote_bin" ] || die "missing $remote_bin after install"
|
||||
info "Preparing Xray and its persistent boot cache..."
|
||||
run_step prepare-xray "$remote_bin" prepare-xray || die "failed to prepare Xray; see stage/command/rc above"
|
||||
rc=0; run_step prepare-xray "$remote_bin" prepare-xray || rc=$?
|
||||
if [ "$rc" != 0 ]; then
|
||||
printf 'ERROR: failed to prepare Xray; stage=prepare-xray rc=%s; see diagnostic above\n' "$rc" >&2
|
||||
return "$rc"
|
||||
fi
|
||||
}
|
||||
|
||||
verify_heartbeat() {
|
||||
@@ -282,6 +440,8 @@ verify_xray_start() {
|
||||
|
||||
# Stop the old log writer before replacing its storage code. Its bounded legacy
|
||||
# archive is migrated by the new log service, without moving any other /tmp data.
|
||||
ensure_install_dependencies
|
||||
|
||||
if [ "${ROOT%/}" = "" ] && [ -x /etc/init.d/owrt-remote-logs ]; then
|
||||
if /etc/init.d/owrt-remote-logs running >/dev/null 2>&1; then
|
||||
run_step logs-stop /etc/init.d/owrt-remote-logs stop
|
||||
@@ -292,6 +452,7 @@ INSTALL_STAGE=files
|
||||
install_file "usr/sbin/owrt-remote" 0755
|
||||
install_file "usr/lib/owrt-remote/wan.sh" 0644
|
||||
install_file "usr/lib/owrt-remote/control.sh" 0644
|
||||
install_file "usr/lib/owrt-remote/tachyon.sh" 0644
|
||||
install_file "usr/lib/owrt-remote/logs.sh" 0644
|
||||
install_file "etc/init.d/owrt-remote-logs" 0755
|
||||
install_file "etc/init.d/owrt-remote" 0755
|
||||
@@ -347,7 +508,7 @@ if [ "${ROOT%/}" = "" ]; then
|
||||
run_step xray-running verify_xray_start || die "Xray start verification failed"
|
||||
run_step heartbeat verify_heartbeat || die "Heartbeat verification failed (files and working Xray retained)"
|
||||
else
|
||||
info 'Remote is disabled; apply OpenWrt config from Hub to start the tunnel and Heartbeat.'
|
||||
info 'Установлено. Добавьте OpenWrt config из Hub для запуска туннеля'
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=luci-app-owrt-remote
|
||||
PKG_VERSION:=121
|
||||
PKG_RELEASE:=1
|
||||
PKG_VERSION:=122
|
||||
PKG_RELEASE:=4
|
||||
PKG_LICENSE:=MIT
|
||||
PKG_MAINTAINER:=kzolotarev95
|
||||
PKGARCH:=all
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep the self-contained installer and agent's downloader identical."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
start = '# BEGIN SHARED ROUTER DOWNLOADER\n'
|
||||
end = '# END SHARED ROUTER DOWNLOADER\n'
|
||||
block = start + (root / 'scripts/router-download.sh').read_text(encoding='utf-8').rstrip() + '\n' + end
|
||||
for name in ('install.sh', 'files/usr/sbin/owrt-remote'):
|
||||
path = root / name
|
||||
text = path.read_text(encoding='utf-8')
|
||||
before, rest = text.split(start, 1)
|
||||
_, after = rest.split(end, 1)
|
||||
updated = before + block + after
|
||||
if '--check' in sys.argv:
|
||||
if updated != text:
|
||||
raise SystemExit('Downloader out of date: ' + name)
|
||||
else:
|
||||
path.write_text(updated, encoding='utf-8', newline='\n')
|
||||
print('Shared router downloader: OK')
|
||||
@@ -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)]
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# Shared, embedded in install.sh and the router agent by embed-router-download.py.
|
||||
# No dependency on curl/jsonfilter/timeout is needed to bootstrap curl itself.
|
||||
download_clock() {
|
||||
if [ -r /proc/uptime ]; then cut -d. -f1 /proc/uptime; else date +%s; fi
|
||||
}
|
||||
download_note() {
|
||||
if command -v log >/dev/null 2>&1; then log "$*"; else printf '%s\n' "$*" >&2; fi
|
||||
}
|
||||
download_origin() {
|
||||
local authority
|
||||
case "$1" in https://?*) ;; *) return 3 ;; esac
|
||||
authority="${1#https://}"; authority="${authority%%/*}"
|
||||
case "$authority" in ''|*[@\?\#\ ]*|*[!A-Za-z0-9.:-]*) return 3 ;; esac
|
||||
case "$authority" in *:*) ;; *) authority="$authority:443" ;; esac
|
||||
printf 'https://%s' "$authority"
|
||||
}
|
||||
download_signal_tree() {
|
||||
local child
|
||||
# Kill descendants first: a timed-out shell function may own a DNS client.
|
||||
if [ -r "/proc/$1/task/$1/children" ]; then
|
||||
for child in $(cat "/proc/$1/task/$1/children"); do download_signal_tree "$child" "$2"; done
|
||||
fi
|
||||
kill -"$2" "$1" 2>/dev/null || true
|
||||
}
|
||||
download_kill_tree() {
|
||||
local ticks
|
||||
download_signal_tree "$1" TERM
|
||||
# Allow shell EXIT traps to release locks and staging files first.
|
||||
ticks=0
|
||||
while kill -0 "$1" 2>/dev/null && [ "$ticks" -lt 2 ]; do sleep 1; ticks=$((ticks+1)); done
|
||||
download_signal_tree "$1" KILL
|
||||
}
|
||||
download_run() (
|
||||
seconds="$1"; shift; child=''
|
||||
trap 'result=$?; [ -z "$child" ] || { download_kill_tree "$child"; wait "$child" 2>/dev/null || true; }; exit "$result"' EXIT
|
||||
trap 'exit 28' INT TERM
|
||||
"$@" & child=$!
|
||||
ticks=0
|
||||
while kill -0 "$child" 2>/dev/null; do
|
||||
[ "$ticks" -lt "$seconds" ] || return 28
|
||||
sleep 1; ticks=$((ticks+1))
|
||||
done
|
||||
rc=0; wait "$child" || rc=$?; child=''; return "$rc"
|
||||
)
|
||||
download_curl() (
|
||||
url="$1"; dst="$2"; stats="$3"; method="$4"; deadline="$5"; hop=0
|
||||
while [ "$hop" -le 5 ]; do
|
||||
origin="$(download_origin "$url")" || return 3
|
||||
set -- -q -fsS --connect-timeout 10 --noproxy '*' --proto '=https' --max-filesize 33554432
|
||||
[ "$method" != HEAD ] || set -- "$@" -I
|
||||
DL_DEVICE=''; DL_RESOLVE=''
|
||||
# The agent resolves every redirect through its selected WAN. The
|
||||
# installer has no routing hook and uses the router's system resolver.
|
||||
if command -v download_route >/dev/null 2>&1; then download_route "$origin" || return $?; fi
|
||||
[ -z "$DL_DEVICE" ] || set -- "$@" --interface "$DL_DEVICE"
|
||||
[ -z "$DL_RESOLVE" ] || set -- "$@" --resolve "$DL_RESOLVE"
|
||||
remaining=$((deadline - $(download_clock)))
|
||||
[ "$remaining" -gt 0 ] || return 28
|
||||
rc=0
|
||||
curl "$@" --max-time "$remaining.000" -o "$dst" -w '%{http_code} %{redirect_url}\n' "$url" >"$stats" || rc=$?
|
||||
[ "$rc" = 0 ] || return "$rc"
|
||||
code=''; redirect=''; read -r code redirect <"$stats" || true
|
||||
case "$code" in
|
||||
301|302|303|307|308) [ -n "$redirect" ] || return 47; url="$redirect"; hop=$((hop+1)) ;;
|
||||
200) [ -s "$dst" ] || return 52; return 0 ;;
|
||||
*) return 22 ;;
|
||||
esac
|
||||
done
|
||||
return 47
|
||||
)
|
||||
download_reason() {
|
||||
case "$1" in
|
||||
3) printf invalid_https_url; return ;; 6) printf DNS; return ;;
|
||||
23|27) printf write; return ;; 28|124|137) printf timeout; return ;;
|
||||
35|51|58|60|77|80|82|83|90|91) printf TLS; return ;;
|
||||
esac
|
||||
if LC_ALL=C grep -Eqi 'no space|permission denied|read-only|write error|file too large' "$2"; then printf write
|
||||
elif LC_ALL=C grep -Eqi 'resolv|bad address|name or service|DNS' "$2"; then printf DNS
|
||||
elif LC_ALL=C grep -qi 'uclient context' "$2"; then printf client_context
|
||||
elif LC_ALL=C grep -Eqi 'TLS|SSL|certificate' "$2"; then printf TLS
|
||||
elif LC_ALL=C grep -Eqi 'timed out|timeout' "$2"; then printf timeout
|
||||
elif [ "$3" != 000 ]; then printf HTTP
|
||||
else printf network; fi
|
||||
}
|
||||
download_tools() {
|
||||
local tool path identity seen
|
||||
seen='|'
|
||||
for tool in curl uclient-fetch wget; do
|
||||
path="$(command -v "$tool" 2>/dev/null)" || continue
|
||||
identity="$(readlink -f "$path" 2>/dev/null)"; identity="${identity:-$path}"
|
||||
case "$seen" in *"|$identity|"*) continue ;; esac
|
||||
seen="$seen$identity|"; printf '%s\n' "$tool"
|
||||
done
|
||||
}
|
||||
remote_download() (
|
||||
url="$1"; dst="$2"; method="${3:-GET}"
|
||||
work="$(mktemp -d "${TMPDIR:-/tmp}/owrt-download.XXXXXX")" || return 23
|
||||
trap 'result=$?; rm -rf "$work"; [ "$result" = 0 ] || rm -f "$dst"; exit "$result"' EXIT
|
||||
trap 'exit 28' INT TERM
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY
|
||||
# Also bound native clients and their error/response files on small RAM.
|
||||
ulimit -f 32768 || return 23
|
||||
deadline=$(( $(download_clock) + 120 ))
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || : >"$DOWNLOAD_RESULT_FILE"
|
||||
for outer in "${XRAY_PREPARE_DEADLINE:-}" "${XRAY_FILE_DEADLINE:-}" "${DOWNLOAD_SOURCE_DEADLINE:-}"; do
|
||||
[ -z "$outer" ] || [ "$outer" -ge "$deadline" ] || deadline="$outer"
|
||||
done
|
||||
origin="$(download_origin "$url")" || { download_note 'Download: reason=invalid_https_url; rc=3'; return 3; }
|
||||
tools="$(download_tools)"; set -- $tools; left="$#"; rc=127
|
||||
[ "$left" -gt 0 ] || download_note 'Download: stage=tools; reason=no_http_client; rc=127'
|
||||
for tool in $tools; do
|
||||
remaining=$((deadline - $(download_clock)))
|
||||
[ "$remaining" -gt 0 ] || { rc=28; reason=timeout; break; }
|
||||
# Reserve time for genuinely different fallback clients. No blind
|
||||
# retries on dozens of releases when their common host is unavailable.
|
||||
seconds=$((remaining / left)); [ "$seconds" -gt 0 ] || seconds=1
|
||||
left=$((left-1)); attempt_end=$(( $(download_clock) + seconds ))
|
||||
rm -f "$dst"; : >"$work/stats"; : >"$work/error"; rc=0
|
||||
case "$tool" in
|
||||
curl) download_run "$seconds" download_curl "$url" "$dst" "$work/stats" "$method" "$attempt_end" 2>"$work/error" || rc=$? ;;
|
||||
*)
|
||||
if command -v download_native_notice >/dev/null 2>&1; then download_native_notice; fi
|
||||
download_run "$seconds" "$tool" -T "$seconds" -O "$dst" "$url" >"$work/stats" 2>"$work/error" || rc=$? ;;
|
||||
esac
|
||||
code=000
|
||||
if [ "$tool" = curl ]; then
|
||||
read -r code ignored <"$work/stats" || true
|
||||
case "$code" in [1-5][0-9][0-9]) ;; *) code=000 ;; esac
|
||||
else
|
||||
code="$(LC_ALL=C sed -n -e 's/.*HTTP\/[0-9.]* *\([1-5][0-9][0-9]\).*/\1/p' -e 's/.*HTTP error \([1-5][0-9][0-9]\).*/\1/p' -e 's/.*awaiting response[. ]*\([1-5][0-9][0-9]\).*/\1/p' "$work/error" | tail -n 1)"
|
||||
code="${code:-000}"
|
||||
fi
|
||||
if [ "$rc" = 0 ]; then
|
||||
[ -s "$dst" ] && [ "$(wc -c <"$dst")" -le 33554432 ] || rc=23
|
||||
fi
|
||||
reason="$(download_reason "$rc" "$work/error" "$code")"
|
||||
[ "$rc" != 0 ] || reason=ok
|
||||
# Never print URLs, query strings, redirect signatures or raw headers.
|
||||
download_note "Download: stage=${DOWNLOAD_STAGE:-file}; tool=$tool; host=$origin; http=$code; rc=$rc; reason=$reason"
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "$reason" "$code" >"$DOWNLOAD_RESULT_FILE"
|
||||
[ "$rc" != 0 ] || return 0
|
||||
case "$reason" in write|invalid_https_url) break ;; esac
|
||||
done
|
||||
[ "$rc" != 28 ] || download_note 'Download: reason=timeout; file/preparation deadline reached or HTTP client timed out'
|
||||
[ -z "${DOWNLOAD_RESULT_FILE:-}" ] || printf '%s %s %s\n' "$rc" "${reason:-no_http_client}" "${code:-000}" >"$DOWNLOAD_RESULT_FILE"
|
||||
return "$rc"
|
||||
)
|
||||
@@ -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)
|
||||
|
||||
+16
-8
@@ -1,33 +1,41 @@
|
||||
# Версия v121
|
||||
# Версия v122
|
||||
|
||||
Версия v121 указана в панели VPS, на экране входа, в мобильной шапке,
|
||||
Исправления Tachyon для APK 3.0.5 выпускаются как пакетная ревизия 122-r2
|
||||
с тегом v122-r2. Номер интерфейсов остаётся v122; исходный тег v122 и пакеты
|
||||
122-r1 сохраняются.
|
||||
|
||||
Выпуск использует main и отдельный тег v122. GitHub Actions собирает IPK/APK,
|
||||
проверяет их и прикладывает к Releases → v122 после успешного завершения сборок
|
||||
и установки/обновления/удаления в OpenWrt VM. Выпущенная v121 сохраняется.
|
||||
|
||||
Версия v122 указана в панели VPS, на экране входа, в мобильной шапке,
|
||||
CGI и представлении LuCI роутера. Скрипты локальной установки, их проверки
|
||||
и документация используют тот же номер. Ссылки источников не менялись.
|
||||
|
||||
Установить локальную сборку на VPS:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v121.ps1" -Vps "root@179.43.187.107" -Action Install
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v122.ps1" -Vps "root@132.243.19.232" -Action Install
|
||||
```
|
||||
|
||||
В ходе текущего тестирования обновления через кнопку вместо обычной установки
|
||||
нужно использовать тестовые сборки из [HUB_UPDATE.md](HUB_UPDATE.md):
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\test-hub-self-update.ps1" -Vps "root@179.43.187.107" -Action Retest
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\test-hub-self-update.ps1" -Vps "root@132.243.19.232" -Action Retest
|
||||
```
|
||||
|
||||
Установить версию интерфейса роутера (CGI и LuCI):
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v121.ps1" -Router "root@192.168.2.1" -Action Install
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v122.ps1" -Router "root@192.168.2.1" -Action Install
|
||||
```
|
||||
|
||||
Скрипт сохраняет первую резервную копию и проверяет файлы до установки.
|
||||
На VPS дополнительно сверяется SHA-256 запущенной сборки через `/health?panel-update=1`;
|
||||
ответ от другой сборки не подтверждает успешную установку.
|
||||
Обновление через кнопку не позволяет установить более старую опубликованную
|
||||
версию поверх локальной v121. Для исправлений с тем же номером версии
|
||||
версию поверх локальной v122. Для исправлений с тем же номером версии
|
||||
по-прежнему проверяется SHA-256. Отдельный баннер «последняя версия» скрыт:
|
||||
при отсутствии обновлений остаётся зелёная кнопка «Обновление не требуется».
|
||||
При ошибке после замены возвращает файлы предыдущей попытки.
|
||||
@@ -37,8 +45,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\
|
||||
Для отката обычной установки VPS либо роутера повторить соответствующую
|
||||
команду с `-Action Rollback`. Копии:
|
||||
|
||||
- VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-v121`.
|
||||
- Роутер: `/root/owrt-remote-backup-before-v121` (CGI и LuCI).
|
||||
- VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-v122`.
|
||||
- Роутер: `/root/owrt-remote-backup-before-v122` (CGI и LuCI).
|
||||
|
||||
Для возврата из тестового режима обновления VPS повторить команду
|
||||
`test-hub-self-update.ps1` с `-Action Restore`: его копия хранится отдельно,
|
||||
|
||||
@@ -104,7 +104,7 @@ logger() { printf '%s\\n' "$3" | sh "$TEST_LOG_HELPER" append; }
|
||||
self.assertIn('GLOBAL_LOGS_ROUTER_Install_OK', result.stdout)
|
||||
for item in ('cgi', 'luci'):
|
||||
installed = self.root / self.targets[item].lstrip('/')
|
||||
self.assertIn('v121', installed.read_text(encoding='utf-8'))
|
||||
self.assertIn('v122', installed.read_text(encoding='utf-8'))
|
||||
for item, data in self.initial.items():
|
||||
self.assertEqual(self.backup.joinpath(item).read_bytes(), data)
|
||||
result = self.deploy('Rollback')
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -33,6 +33,16 @@ def preview_pages():
|
||||
for path, page in pages.items()}
|
||||
|
||||
|
||||
def tachyon_layout_preview():
|
||||
page = b'''<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<style>html,body{margin:0}.tachyon-bg-layer{position:fixed;inset:0;pointer-events:none}
|
||||
.tachyon-bg-layer svg{width:100%;height:100%;display:block}
|
||||
#maincontent{position:relative;padding:8px;box-sizing:border-box}main{height:400px}</style>
|
||||
</head><body><div class="tachyon-bg-layer"><svg viewBox="0 0 1600 900"></svg></div>
|
||||
<div id="maincontent"><main>Tachyon dashboard</main></div></body></html>'''
|
||||
return {'synthetic': hub.inject_hub_appearance('/tachyon/node-10/', page, 'text/html').decode()}
|
||||
|
||||
|
||||
class GlobalHubDesignTests(unittest.TestCase):
|
||||
def test_generated_pages_receive_the_shared_head(self):
|
||||
pages = {
|
||||
@@ -54,10 +64,14 @@ class GlobalHubDesignTests(unittest.TestCase):
|
||||
self.assertEqual(dashboard.count("owrt-hub-design-head"), 1)
|
||||
luci = b"<html><head><title>LuCI</title></head><body>router</body></html>"
|
||||
self.assertEqual(hub.inject_hub_appearance("/access/main/", luci, "text/html"), luci)
|
||||
for path in ('/tachyon/node-10/', '/tachyon/node-10/cgi-bin/luci/?view=main'):
|
||||
self.assertEqual(hub.inject_hub_appearance(path, luci, 'text/html; charset=utf-8'), luci)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--export-preview":
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--export-tachyon-layout":
|
||||
pathlib.Path(sys.argv[2]).write_text(json.dumps(tachyon_layout_preview()), encoding='utf-8')
|
||||
elif len(sys.argv) == 3 and sys.argv[1] == "--export-preview":
|
||||
pathlib.Path(sys.argv[2]).write_text(json.dumps(preview_pages(), ensure_ascii=False), encoding="utf-8")
|
||||
else:
|
||||
unittest.main()
|
||||
@@ -28,7 +28,7 @@ const html = template.replace('window.ROUTERS = [];', 'window.ROUTERS = '+JSON.s
|
||||
if (url.pathname === '/api/router-groups') return route.fulfill({json:{groups:[]}});
|
||||
if (url.pathname === '/api/notifications/wait') return route.fulfill({status:429,json:{busy:true},headers:{'Retry-After':'5'}});
|
||||
if (url.pathname === '/api/vps/resources') return route.fulfill({json:{ok:true,cpu:{percent:15},memory:{percent:35},disk:{percent:40}}});
|
||||
if (url.pathname === '/api/hub-update') return route.fulfill({json:{ok:true,checked:true,available:false,current_version:'v121'}});
|
||||
if (url.pathname === '/api/hub-update') return route.fulfill({json:{ok:true,checked:true,available:false,current_version:'v122'}});
|
||||
if (url.pathname.startsWith('/api/')) return route.fulfill({json:{ok:true,auth:{username:'root',is_owner:true,can_add_router:true}}});
|
||||
return route.abort();
|
||||
});
|
||||
|
||||
@@ -48,6 +48,7 @@ class UpdateTests(unittest.TestCase):
|
||||
mock.patch.object(hub, 'hub_update_lock', side_effect=lambda *a, **k: nullcontext()).start()
|
||||
self.install_logs = mock.patch.object(hub, 'hub_install_log_maintenance').start()
|
||||
self.rollback_logs = mock.patch.object(hub, 'hub_rollback_log_maintenance').start()
|
||||
self.bootstrap_logs = mock.patch.object(hub, 'hub_run_log_maintenance_unit').start()
|
||||
mock.patch.object(hub, 'hub_prune_log_maintenance_backups').start()
|
||||
|
||||
def response(self, data=NEW, url=None):
|
||||
@@ -70,7 +71,7 @@ class UpdateTests(unittest.TestCase):
|
||||
self.assertEqual(fetch.call_args.args[0].full_url, source + '/vps/owrt-remote-hub.py')
|
||||
data = self.manager.snapshot()
|
||||
self.assertTrue(data['available'])
|
||||
self.assertEqual(data['remote_version'], 'v121')
|
||||
self.assertEqual(data['remote_version'], 'v122')
|
||||
self.assertEqual(data['remote_revision'], hashlib.sha256(NEW).hexdigest())
|
||||
self.assertEqual(self.target.read_bytes(), SOURCE)
|
||||
|
||||
@@ -247,7 +248,7 @@ class UpdateTests(unittest.TestCase):
|
||||
job = {'id': 'a' * 32, 'status': 'restarting', 'revision': hub.HUB_LOADED_REVISION,
|
||||
'started_at': hub.time.time()}
|
||||
hub.hub_update_state(self.directory, job)
|
||||
self.install_logs.side_effect = None
|
||||
self.bootstrap_logs.side_effect = None
|
||||
captured = {}
|
||||
def thread(**kwargs):
|
||||
captured['install'] = kwargs['target']
|
||||
@@ -258,8 +259,9 @@ class UpdateTests(unittest.TestCase):
|
||||
self.assertEqual(self.manager.snapshot()['job']['status'], 'installing')
|
||||
captured['install']()
|
||||
self.assertEqual(self.manager.log_maintenance_status, 'ready')
|
||||
self.install_logs.assert_called_once_with(self.directory, job['id'], budget=40)
|
||||
self.install_logs.side_effect = RuntimeError('disk full')
|
||||
self.bootstrap_logs.assert_called_once_with(self.directory, job['id'], self.target)
|
||||
self.install_logs.assert_not_called()
|
||||
self.bootstrap_logs.side_effect = RuntimeError('disk full')
|
||||
captured['install']()
|
||||
self.assertEqual(self.manager.snapshot()['job']['status'], 'failed')
|
||||
self.assertIn('disk full', self.manager.snapshot()['job']['message'])
|
||||
|
||||
@@ -92,6 +92,38 @@ class ComponentTests(unittest.TestCase):
|
||||
self.assertTrue(hub.hub_log_maintenance_directory(self.directory, 'b' * 32).exists())
|
||||
self.assertTrue(other.exists())
|
||||
|
||||
def test_bootstrap_runs_in_separate_system_service_and_checks_receipt(self):
|
||||
target = self.directory / 'hub.py'
|
||||
with mock.patch.object(hub.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, '', '')) as run, \
|
||||
mock.patch.object(hub, 'hub_log_maintenance_receipt', return_value={
|
||||
'status': 'ready', 'sha256': hub.HUB_LOG_MAINTENANCE_SHA256}):
|
||||
hub.hub_run_log_maintenance_unit(self.directory, self.job_id, target)
|
||||
args = run.call_args.args[0]
|
||||
self.assertEqual(args[0], 'systemd-run')
|
||||
self.assertIn('--wait', args)
|
||||
self.assertIn('--pipe', args)
|
||||
self.assertIn('panel-log-maintenance-worker', args)
|
||||
self.assertIn(str(target), args)
|
||||
self.assertNotIn('--scope', args, 'a scope would inherit restricted Hub capabilities')
|
||||
self.assertFalse(any('CapabilityBoundingSet' in arg for arg in args))
|
||||
self.assertEqual(args[-2:], ['--directory', str(self.directory)])
|
||||
|
||||
def test_bootstrap_rejects_failed_unit_or_missing_receipt(self):
|
||||
for status, receipt, message in ((1, {}, 'Permission denied'), (0, {}, 'нет результата')):
|
||||
with self.subTest(status=status), \
|
||||
mock.patch.object(hub.subprocess, 'run', return_value=subprocess.CompletedProcess([], status, '', 'Permission denied')), \
|
||||
mock.patch.object(hub, 'hub_log_maintenance_receipt', return_value=receipt):
|
||||
with self.assertRaisesRegex(RuntimeError, message):
|
||||
hub.hub_run_log_maintenance_unit(self.directory, self.job_id, self.directory / 'hub.py')
|
||||
|
||||
def test_stale_privileged_worker_never_installs(self):
|
||||
for job in ({'id': 'd' * 32}, {'id': self.job_id, 'status': 'failed', 'revision': hub.HUB_LOADED_REVISION}):
|
||||
with mock.patch.object(hub, 'hub_update_state', return_value=job), \
|
||||
mock.patch.object(hub, 'hub_install_log_maintenance') as install:
|
||||
with self.assertRaisesRegex(RuntimeError, 'устарела'):
|
||||
hub.run_hub_log_maintenance_worker(self.job_id, self.directory)
|
||||
install.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -10,7 +10,7 @@ execFileSync(process.env.TEST_PYTHON || 'python', ['tests/test_vps_resources.py'
|
||||
const pageHtml = fs.readFileSync(path.join(output, 'dashboard.html'), 'utf8');
|
||||
function state() {
|
||||
return {ok:true,checked:true,checking:false,error:'',source:'https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main',
|
||||
current_revision:'a'.repeat(64),current_version:'v121',remote_revision:'b'.repeat(64),remote_version:'v121',source_older:false,available:true,job:{},csrf:'test-csrf'};
|
||||
current_revision:'a'.repeat(64),current_version:'v122',remote_revision:'b'.repeat(64),remote_version:'v122',source_older:false,available:true,job:{},csrf:'test-csrf'};
|
||||
}
|
||||
async function createFixture(browser,width,height,mobile) {
|
||||
const page = await browser.newPage({viewport:{width,height},isMobile:mobile,hasTouch:mobile});
|
||||
|
||||
@@ -97,5 +97,78 @@ esac
|
||||
self.assertEqual(calls.read_text().splitlines(),['rpcd running','rpcd '+operation,
|
||||
'uhttpd running','uhttpd '+operation])
|
||||
|
||||
def dependencies_driver(self, fail=False):
|
||||
source=self.installer.read_text(encoding='utf-8').split('# Stop the old log writer')[0]
|
||||
source=source.replace('/etc/ssl/cert.pem', self.root.joinpath('cert.pem').as_posix())
|
||||
source=source.replace('/etc/ssl/certs/ca-certificates.crt', self.root.joinpath('ca.crt').as_posix())
|
||||
source+='''
|
||||
ROOT=/
|
||||
command() {
|
||||
if [ "$1" = -v ]; then
|
||||
case "$2" in curl|jsonfilter) [ -f "$TMPDIR/deps-ready" ]; return $? ;; esac
|
||||
fi
|
||||
builtin command "$@"
|
||||
}
|
||||
package_manager() { printf apk; }
|
||||
install_packages() {
|
||||
printf '%s\\n' "$*" >"$TMPDIR/packages"
|
||||
[ "$DEPS_FAIL" != 1 ] || { echo 'apk repository unavailable' >&2; return 19; }
|
||||
printf CA >"$TMPDIR/ca.crt"; touch "$TMPDIR/deps-ready"
|
||||
}
|
||||
ensure_install_dependencies
|
||||
echo DEPENDENCIES_READY
|
||||
'''
|
||||
script=self.root/'deps.sh'; script.write_text(source,encoding='utf-8',newline='\n')
|
||||
return subprocess.run(self.args+[script.as_posix()],capture_output=True,encoding='utf-8',timeout=20,
|
||||
env={**self.env,'DEPS_FAIL':'1' if fail else '0'})
|
||||
|
||||
def test_missing_curl_ca_jsonfilter_are_prepared_with_apk_before_files(self):
|
||||
result=self.dependencies_driver()
|
||||
self.assertEqual(result.returncode,0,result.stderr)
|
||||
self.assertEqual(self.root.joinpath('packages').read_text().split(), ['curl','jsonfilter','ca-certificates'])
|
||||
self.assertIn('DEPENDENCIES_READY',result.stdout)
|
||||
|
||||
def test_dependency_failure_has_separate_stage_and_never_reaches_xray(self):
|
||||
result=self.dependencies_driver(fail=True)
|
||||
self.assertNotEqual(result.returncode,0)
|
||||
self.assertIn('stage=dependencies',result.stderr)
|
||||
self.assertIn('apk repository unavailable',result.stderr)
|
||||
self.assertNotIn('DEPENDENCIES_READY',result.stdout)
|
||||
|
||||
def runtime_driver(self, rc):
|
||||
installer=self.installer.read_text(encoding='utf-8')
|
||||
prefix=installer.split('# Stop the old log writer')[0]
|
||||
main=installer.split('\ninstall_xray_runtime\n',1)[1].split('\nkey=',1)[0]
|
||||
agent=self.root/'agent'
|
||||
agent.write_text('''#!/bin/sh
|
||||
echo "$1" >>"$TMPDIR/agent-calls"
|
||||
[ "$TEST_PREPARE_RC" = 0 ] || echo 'download failed: reason=DNS' >&2
|
||||
exit "$TEST_PREPARE_RC"
|
||||
''',encoding='utf-8',newline='\n')
|
||||
agent.chmod(0o755)
|
||||
source=prefix+'''
|
||||
ROOT=/
|
||||
target_path() { printf '%s/agent' "$TMPDIR"; }
|
||||
uci() { printf 0; }
|
||||
install_xray_runtime
|
||||
'''+main+'\necho FIRST_INSTALL_FINISHED\n'
|
||||
script=self.root/'runtime.sh';script.write_text(source,encoding='utf-8',newline='\n')
|
||||
return subprocess.run(self.args+[script.as_posix()],env={**self.env,'TEST_PREPARE_RC':str(rc)},
|
||||
capture_output=True,encoding='utf-8',timeout=20)
|
||||
|
||||
def test_prepared_first_install_without_hub_config_finishes_successfully(self):
|
||||
result=self.runtime_driver(0)
|
||||
self.assertEqual(result.returncode,0,result.stderr)
|
||||
self.assertIn('Установлено. Добавьте OpenWrt config из Hub для запуска туннеля',result.stdout)
|
||||
self.assertIn('FIRST_INSTALL_FINISHED',result.stdout)
|
||||
self.assertEqual(self.root.joinpath('agent-calls').read_text().splitlines(),['prepare-xray'])
|
||||
|
||||
def test_prepare_failure_keeps_original_rc_at_installer_boundary(self):
|
||||
result=self.runtime_driver(6)
|
||||
self.assertEqual(result.returncode,6,result.stderr)
|
||||
self.assertIn('stage=prepare-xray rc=6',result.stderr)
|
||||
self.assertIn('reason=DNS',result.stderr)
|
||||
self.assertNotIn('FIRST_INSTALL_FINISHED',result.stdout)
|
||||
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -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)
|
||||
|
||||
@@ -102,7 +102,7 @@ logger() { printf '%s\\n' "$3" | sh "$TEST_LOG_HELPER" append; }
|
||||
self.assertIn('PERSISTENT_LOGS_ROUTER_Install_OK', result.stdout)
|
||||
for item in ('cgi', 'luci'):
|
||||
installed = self.root / self.targets[item].lstrip('/')
|
||||
self.assertIn('v121', installed.read_text(encoding='utf-8'))
|
||||
self.assertIn('v122', installed.read_text(encoding='utf-8'))
|
||||
for item, data in self.initial.items():
|
||||
self.assertEqual(self.backup.joinpath(item).read_bytes(), data)
|
||||
result = self.deploy('Rollback')
|
||||
|
||||
@@ -131,7 +131,7 @@ class HubFixture:
|
||||
assert "groups" in json.loads(self.request("/api/router-groups"))
|
||||
assert "notifications" in json.loads(self.request("/api/notifications"))
|
||||
assert self.request("/access/test-router/") == b"router proxy fixture"
|
||||
assert b"v121" in self.request("/")
|
||||
assert b"v122" in self.request("/")
|
||||
self.app.snapshot_router_states()
|
||||
|
||||
def __exit__(self, *args):
|
||||
|
||||
@@ -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;});
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Download failures, fallback, budgets and preservation; no public network."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
import unittest
|
||||
|
||||
import test_xray_bootstrap as base
|
||||
|
||||
|
||||
class DownloaderTests(unittest.TestCase):
|
||||
config = base.XrayBootstrapTests.config
|
||||
shell = base.XrayBootstrapTests.raw_shell
|
||||
|
||||
def setUp(self):
|
||||
base.XrayBootstrapTests.setUp(self)
|
||||
if os.name == 'nt':
|
||||
self.clients += '\nulimit() { [ "$1 $2" = "-f 32768" ]; }\n'
|
||||
tools = self.directory / 'tools'
|
||||
tools.mkdir()
|
||||
native = tools / 'uclient-fetch'
|
||||
native.write_text('#!/bin/sh\n' + self.clients + '\nuclient_fetch_mock "$@"\n',
|
||||
encoding='utf-8', newline='\n')
|
||||
native.chmod(0o755)
|
||||
self.env['PATH'] = tools.as_posix() + os.pathsep + self.env['PATH']
|
||||
|
||||
clients = r'''
|
||||
command() {
|
||||
if [ "$1" = -v ]; then
|
||||
case "$2" in curl|wget|uclient-fetch)
|
||||
case " $TEST_TOOLS " in *" $2 "*) printf '%s\n' "$2"; return 0 ;; *) return 1 ;; esac ;;
|
||||
esac
|
||||
fi
|
||||
builtin command "$@"
|
||||
}
|
||||
curl() {
|
||||
printf 'curl\n' >>"$TEST_ROOT/clients"
|
||||
local previous arg output
|
||||
previous=''
|
||||
for arg in "$@"; do [ "$previous" != -o ] || output="$arg"; previous="$arg"; done
|
||||
printf partial >"$output"
|
||||
[ "${CURL_RC:-6}" = 0 ] || { printf 'could not resolve SECRET_URL\n' >&2; return "${CURL_RC:-6}"; }
|
||||
printf payload >"$output"; printf '200 \n'
|
||||
}
|
||||
uclient_fetch_mock() {
|
||||
printf 'uclient-fetch\n' >>"$TEST_ROOT/clients"
|
||||
local previous arg output
|
||||
previous=''
|
||||
for arg in "$@"; do [ "$previous" != -O ] || output="$arg"; previous="$arg"; done
|
||||
printf partial >"$output"
|
||||
[ "${NATIVE_RC:-0}" = 0 ] || { printf 'TLS certificate error\n' >&2; return "$NATIVE_RC"; }
|
||||
printf payload >"$output"
|
||||
}
|
||||
wget() { printf 'wget\n' >>"$TEST_ROOT/clients"; uclient_fetch_mock "$@"; }
|
||||
'''
|
||||
|
||||
def download(self, extra='', **env):
|
||||
return self.shell('fetch_file "https://github.com/test?token=SECRET_TOKEN" "$TEST_ROOT/download"',
|
||||
mocks=self.clients + extra, TEST_TOOLS='curl uclient-fetch wget', **env)
|
||||
|
||||
def test_curl_failure_switches_to_next_client_without_leaking_stderr_or_url(self):
|
||||
result = self.download()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.directory / 'download').read_text(), 'payload')
|
||||
self.assertEqual((self.directory / 'clients').read_text().splitlines(), ['curl', 'uclient-fetch'])
|
||||
self.assertIn('reason=DNS', result.stderr)
|
||||
self.assertIn('tool=uclient-fetch', result.stderr)
|
||||
self.assertNotIn('SECRET', result.stderr)
|
||||
self.assertFalse(list(self.directory.glob('owrt-download.*')))
|
||||
|
||||
def test_native_failure_keeps_original_rc_and_tls_reason(self):
|
||||
result = self.shell('fetch_file https://github.com/test "$TEST_ROOT/download"',
|
||||
mocks=self.clients, TEST_TOOLS='uclient-fetch', NATIVE_RC='7')
|
||||
self.assertEqual(result.returncode, 7, result.stderr)
|
||||
self.assertIn('rc=7; reason=TLS', result.stderr)
|
||||
self.assertFalse((self.directory / 'download').exists())
|
||||
|
||||
def test_wget_symlink_to_uclient_is_not_a_second_attempt(self):
|
||||
result = self.download(extra=r'''
|
||||
readlink() { case "$2" in wget|uclient-fetch) printf /bin/uclient-fetch ;; *) printf '%s' "$2" ;; esac; }
|
||||
''', NATIVE_RC='1')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual((self.directory / 'clients').read_text().splitlines(), ['curl', 'uclient-fetch'])
|
||||
|
||||
def test_expired_preparation_budget_prevents_all_requests(self):
|
||||
result = self.download(XRAY_PREPARE_DEADLINE='1')
|
||||
self.assertEqual(result.returncode, 28, result.stderr)
|
||||
self.assertFalse((self.directory / 'clients').exists())
|
||||
|
||||
def test_write_error_does_not_retry_another_client(self):
|
||||
result = self.download(CURL_RC='23')
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertIn('reason=write', result.stderr)
|
||||
self.assertEqual((self.directory / 'clients').read_text().splitlines(), ['curl'])
|
||||
|
||||
def test_no_head_gate_in_candidate_install(self):
|
||||
data = base.XrayBootstrapTests.make_binary(self)
|
||||
self.directory.joinpath('release.pkg').write_bytes(data)
|
||||
result = base.XrayBootstrapTests.shell(self, 'install_xray_tmp', mocks=r'''
|
||||
xray_probe_url() { echo forbidden-HEAD >&2; return 22; }
|
||||
fetch_file() { cp "$TEST_ROOT/release.pkg" "$2"; }
|
||||
''')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertNotIn('forbidden-HEAD', result.stderr)
|
||||
|
||||
def test_network_failure_does_not_search_old_releases_or_report_incompatibility(self):
|
||||
data = base.XrayBootstrapTests.make_binary(self)
|
||||
self.directory.joinpath('release.pkg').write_bytes(data)
|
||||
result = base.XrayBootstrapTests.shell(self, 'install_xray_tmp', mocks=r'''
|
||||
xray_discover_releases() {
|
||||
printf '2\n' >"$2/next-release-page"
|
||||
for asset in first second third; do
|
||||
printf 'v26.6.27|%s.ipk|https://github.com/%s|%s|%s\n' "$asset" "$asset" "$(xray_digest "$TEST_ROOT/release.pkg")" "$(wc -c <"$TEST_ROOT/release.pkg")"
|
||||
done >"$1"
|
||||
}
|
||||
fetch_file() { echo "$1" >>"$TEST_ROOT/clients"; return 6; }
|
||||
''')
|
||||
self.assertEqual(result.returncode, 6, result.stderr)
|
||||
self.assertEqual(len(self.directory.joinpath('clients').read_text().splitlines()), 1)
|
||||
self.assertIn('published Xray package found but download failed', result.stderr)
|
||||
self.assertNotIn('No compatible', result.stderr)
|
||||
self.assertTrue(self.binary.exists())
|
||||
|
||||
def test_prepare_preserves_original_download_return_code(self):
|
||||
result = self.shell('prepare_xray', mocks='ensure_xray_available() { return 6; }')
|
||||
self.assertEqual(result.returncode, 6, result.stderr)
|
||||
|
||||
def mirror_install(self, corrupt=False):
|
||||
good = base.XrayBootstrapTests.make_binary(self, 'working')
|
||||
cached = base.XrayBootstrapTests.cache(self, good)
|
||||
candidate = base.XrayBootstrapTests.make_binary(self, 'new')
|
||||
self.binary.write_bytes(good)
|
||||
self.directory.joinpath('release.pkg').write_bytes(candidate)
|
||||
result = base.XrayBootstrapTests.shell(self, 'install_xray_tmp', mocks=r'''
|
||||
fetch_file() {
|
||||
printf '%s %s\n' "$1" "$XRAY_FILE_DEADLINE" >>"$TEST_ROOT/clients"
|
||||
case "$1" in https://mirror.example/*)
|
||||
if [ "$TEST_CORRUPT" = 1 ]; then tr X Y <"$TEST_ROOT/release.pkg" >"$2"; else cp "$TEST_ROOT/release.pkg" "$2"; fi ;;
|
||||
*) return 6 ;;
|
||||
esac
|
||||
}
|
||||
''', XRAY_PACKAGE_MIRROR='https://mirror.example/xray', TEST_CORRUPT='1' if corrupt else '0')
|
||||
return result, good, candidate, cached
|
||||
|
||||
def test_opt_in_mirror_uses_same_file_deadline_and_official_digest(self):
|
||||
result, good, candidate, _ = self.mirror_install()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
calls = self.directory.joinpath('clients').read_text().splitlines()
|
||||
self.assertIn('https://mirror.example/xray/v26.6.27/test.ipk', calls[-1])
|
||||
self.assertEqual(calls[0].split()[-1], calls[-1].split()[-1])
|
||||
self.assertEqual(self.binary.read_bytes(), candidate)
|
||||
|
||||
def test_corrupted_mirror_file_cannot_replace_binary_or_boot_cache(self):
|
||||
result, good, candidate, cached = self.mirror_install(corrupt=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('SHA256 mismatch', result.stderr)
|
||||
self.assertEqual(self.binary.read_bytes(), good)
|
||||
self.assertTrue(cached.exists())
|
||||
|
||||
def test_embedded_install_and_agent_downloaders_match_the_single_source(self):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
result = subprocess.run([os.sys.executable, str(root / 'scripts/embed-router-download.py'), '--check'],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
@unittest.skipIf(os.name == 'nt', 'Linux /proc process-tree watchdog integration')
|
||||
def test_hung_client_is_killed_and_reaped_before_native_fallback(self):
|
||||
started = time.monotonic()
|
||||
result = self.shell('XRAY_FILE_DEADLINE=$(( $(download_clock) + 6 )); fetch_file https://github.com/test "$TEST_ROOT/download"',
|
||||
mocks=self.clients + r'''
|
||||
curl() {
|
||||
read -r child rest </proc/self/stat
|
||||
printf '%s\n' "$child" >"$TEST_ROOT/hung-pid"
|
||||
command sleep 30
|
||||
}
|
||||
''', TEST_TOOLS='curl uclient-fetch')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertLess(time.monotonic() - started, 9)
|
||||
pid = int(self.directory.joinpath('hung-pid').read_text())
|
||||
self.assertFalse(Path('/proc', str(pid)).exists(), 'HTTP child was not reaped')
|
||||
self.assertEqual(self.directory.joinpath('download').read_text(), 'payload')
|
||||
|
||||
@unittest.skipIf(os.name == 'nt', 'Linux ash TERM/EXIT trap integration')
|
||||
def test_preparation_deadline_runs_worker_cleanup_and_preserves_working_binary(self):
|
||||
good = base.XrayBootstrapTests.make_binary(self)
|
||||
result = self.shell('XRAY_PREPARE_DEADLINE=$(( $(download_clock) + 2 )); xray_prepare_timed hung_preparation',
|
||||
mocks=r'''
|
||||
hung_preparation() (
|
||||
trap 'rm -f "$TEST_ROOT/temporary-work"' EXIT
|
||||
trap 'exit 1' TERM INT
|
||||
touch "$TEST_ROOT/temporary-work"
|
||||
command sleep 30
|
||||
)
|
||||
''')
|
||||
self.assertEqual(result.returncode, 28, result.stderr)
|
||||
self.assertFalse(self.directory.joinpath('temporary-work').exists())
|
||||
self.assertEqual(self.binary.read_bytes(), good)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Per-router discovery lifecycle, authenticated proxy and fixed reverse targets."""
|
||||
import http.client
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import test_host_policy as base
|
||||
hub = base.hub
|
||||
|
||||
|
||||
def detected(**values):
|
||||
return dict(checked=True, installed=True, version='2.0.0~beta.8-1',
|
||||
mode='standalone', port=1680, service='running', available=True, **values)
|
||||
|
||||
|
||||
class StateTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.db = Path(self.temp.name) / 'hub.db'
|
||||
self.context = hub.connect(self.db)
|
||||
self.conn = self.context.__enter__()
|
||||
hub.init_db(self.conn)
|
||||
self.addCleanup(self.context.__exit__, None, None, None)
|
||||
for rid, port in [('a', 18080), ('b', 18081)]:
|
||||
hub.upsert_router(self.conn, dict(id=rid, entry_port=port))
|
||||
|
||||
def beat(self, rid='a', tachyon=None):
|
||||
return hub.heartbeat(self.conn, dict(id=rid, xray='running', tachyon=tachyon))
|
||||
|
||||
def test_independent_install_stop_remove_reinstall_and_network_recovery(self):
|
||||
a = self.beat(tachyon=detected())
|
||||
self.assertTrue(a['tachyon']['online'])
|
||||
self.assertNotIn('tachyon', self.beat('b', {'checked': True, 'installed': False}))
|
||||
port = a['tachyon_entry_port']
|
||||
self.assertTrue(a['_xray_reload_required'])
|
||||
value = detected(); value.update(service='stopped', available=False)
|
||||
a = self.beat(tachyon=value)
|
||||
self.assertFalse(a['tachyon']['online'])
|
||||
self.assertFalse(a['_xray_reload_required'], 'service status must not restart every tunnel')
|
||||
self.assertEqual(a['tachyon']['url'], '/tachyon/a/')
|
||||
a = self.beat(tachyon={'checked': False})
|
||||
self.assertIn('tachyon', a, 'inventory error is not uninstall')
|
||||
self.assertFalse(a['tachyon']['online'])
|
||||
a = self.beat(tachyon={'checked': True, 'installed': False})
|
||||
self.assertNotIn('tachyon', a)
|
||||
self.assertTrue(a['_xray_reload_required'])
|
||||
a = self.beat(tachyon=detected())
|
||||
self.assertEqual(a['tachyon_entry_port'], port)
|
||||
self.conn.execute("update routers set last_seen=1 where id='a'")
|
||||
self.assertFalse(hub.row_to_router(hub.get_router(self.conn, 'a'))['tachyon']['online'])
|
||||
self.assertTrue(self.beat(tachyon=detected())['tachyon']['online'])
|
||||
|
||||
def test_bad_endpoints_never_create_arbitrary_target(self):
|
||||
for patch in ({'port': 22}, {'port': '1680'}, {'port': 65536}, {'mode': 'http://evil'},
|
||||
{'port': True}, {'checked': 'true'}, {'installed': 'true'}):
|
||||
value = detected(); value.update(patch)
|
||||
self.assertIsNone(hub.normalize_tachyon(value), patch)
|
||||
value = detected(); value.update(host='169.254.169.254', token='SECRET')
|
||||
clean = hub.normalize_tachyon(value)
|
||||
self.assertNotIn('host', clean); self.assertNotIn('token', clean)
|
||||
|
||||
def test_both_generators_share_fixed_loopback_target_and_existing_reverse(self):
|
||||
a = self.beat(tachyon=detected())
|
||||
row = hub.get_router(self.conn, 'a')
|
||||
server = hub.make_server_xray_config([row])
|
||||
inbound = next(i for i in server['inbounds'] if i['tag'] == 'tachyon-a')
|
||||
self.assertEqual(inbound['listen'], '127.0.0.1')
|
||||
self.assertEqual(inbound['settings']['rewriteAddress'], '127.0.0.1')
|
||||
self.assertEqual(inbound['settings']['rewritePort'], 1680)
|
||||
self.assertEqual(inbound['settings']['address'], inbound['settings']['rewriteAddress'])
|
||||
self.assertEqual(inbound['settings']['port'], inbound['settings']['rewritePort'])
|
||||
self.assertEqual(inbound['settings']['network'], 'tcp')
|
||||
client = hub.make_router_xray_config(row)
|
||||
rule = client['routing']['rules'][0]
|
||||
self.assertEqual(rule['outboundTag'], 'router-tachyon')
|
||||
self.assertEqual(rule['ip'], ['127.0.0.1'])
|
||||
self.assertEqual(client['outbounds'][0]['settings']['redirect'], '127.0.0.1:1680')
|
||||
self.assertEqual(len(server['inbounds'][0]['settings']['clients']), 2)
|
||||
self.assertEqual(hub.get_router_by_any_port(self.conn, a['tachyon_entry_port'])['id'], 'a')
|
||||
with self.assertRaisesRegex(ValueError, 'Tachyon'):
|
||||
hub.upsert_router(self.conn, {'id': 'a', 'entry_port': a['tachyon_entry_port']})
|
||||
|
||||
def test_legacy_luci_uses_existing_admin_tunnel(self):
|
||||
value = detected(); value.update(mode='luci', port=0, version='1.3.13')
|
||||
self.beat(tachyon=value)
|
||||
self.assertFalse(any(i['tag'] == 'tachyon-a' for i in hub.make_server_xray_config([hub.get_router(self.conn, 'a')])['inbounds']))
|
||||
|
||||
def test_existing_report_with_no_entry_port_still_requests_server_reload(self):
|
||||
self.conn.execute("update routers set status_json=? where id='a'", (json.dumps({'tachyon': detected()}),))
|
||||
self.conn.commit()
|
||||
router = self.beat(tachyon=detected())
|
||||
self.assertGreater(router['tachyon_entry_port'], 0)
|
||||
self.assertTrue(router['_xray_reload_required'])
|
||||
|
||||
def test_rewrite_keeps_api_and_assets_inside_selected_router(self):
|
||||
body = b'<html><head></head><body><script>fetch("/api/login");fetch("/ubus");</script><img src="/assets/icon.png"></body></html>'
|
||||
rendered = hub.rewrite_html(body, '/tachyon/a', 'text/html').decode()
|
||||
for path in ('/api/login', '/ubus', '/assets/icon.png'):
|
||||
self.assertIn('/tachyon/a' + path, rendered)
|
||||
self.assertNotIn('/tachyon/a/api/login', hub.rewrite_html(body, '/access/a', 'text/html').decode())
|
||||
|
||||
|
||||
@unittest.skipUnless(base.SH, 'POSIX shell required')
|
||||
class DiscoveryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.harness = base.RouterShellTests()
|
||||
self.harness.setUp()
|
||||
self.addCleanup(self.harness.doCleanups)
|
||||
self.harness.config(vps_host='hub.example', vless_uuid='11111111-1111-4111-8111-111111111111')
|
||||
self.root = self.harness.directory
|
||||
self.harness.env.update(OWRT_REMOTE_TACHYON_HELPER=str(base.ROOT / 'files/usr/lib/owrt-remote/tachyon.sh').replace('\\', '/'),
|
||||
OWRT_REMOTE_TACHYON_RUNTIME=self.root.as_posix() + '/tachyon')
|
||||
if os.environ.get('TACHYON_TEST_BUSYBOX'):
|
||||
def busybox_shell(command, **env):
|
||||
mocks = re.sub(r'(?ms)^owrt-remote\(\) \{.*?^\}\n', '', base.MOCKS)
|
||||
return subprocess.run([os.environ['TACHYON_TEST_BUSYBOX'], 'ash'],
|
||||
input=self.harness.agent + '\n' + mocks + '\n' + command,
|
||||
env={**self.harness.env, **env}, cwd=base.ROOT, capture_output=True,
|
||||
encoding='utf-8', timeout=60)
|
||||
self.harness.run_shell = busybox_shell
|
||||
self.mocks = r'''
|
||||
opkg() {
|
||||
[ ! -e "$TEST_ROOT/inventory-error" ] || return 1
|
||||
[ ! -e "$TEST_ROOT/absent" ] || return 0
|
||||
printf 'Package: tachyon\nVersion: %s\nStatus: install user installed\n' "$TEST_VERSION"
|
||||
}
|
||||
curl() {
|
||||
[ "$TEST_HTTP" != fail ] || return 7
|
||||
for last do :; done
|
||||
case "$last" in
|
||||
*/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
|
||||
}
|
||||
ubus() { printf '{"running":%s}' "$TEST_SERVICE"; }
|
||||
jsonfilter() {
|
||||
"$TEST_PYTHON" -c 'import sys,json
|
||||
a=sys.argv[1:]; data=json.load(open(a[1])) if a and a[0]=="-i" else json.load(sys.stdin)
|
||||
path=a[-1]
|
||||
if "instances" in path: value=data.get("running")
|
||||
elif "router-tachyon" in path: value=next((o["settings"]["redirect"] for o in data.get("outbounds",[]) if o["tag"]=="router-tachyon"),"")
|
||||
else:
|
||||
value=data
|
||||
for key in path.removeprefix("@.").split("."): value=value.get(key,"") if isinstance(value,dict) else ""
|
||||
print(str(value).lower() if isinstance(value,bool) else value)' "$@"
|
||||
}
|
||||
'''
|
||||
|
||||
def run_shell(self, command, **env):
|
||||
return self.harness.run_shell(self.mocks + command, TEST_VERSION='2.0.0~beta.8-1',
|
||||
TEST_HTTP='200', TEST_SERVICE='true', **env)
|
||||
|
||||
def test_opkg_present_http_offline_inventory_failure_and_uninstall(self):
|
||||
result = self.run_shell('tachyon_json force')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)['port'], 1680)
|
||||
self.assertEqual(json.loads(result.stdout)['api'], '/api/agent/v1')
|
||||
self.assertEqual(json.loads(result.stdout)['version'], '2.0.0-beta.14')
|
||||
self.assertEqual(json.loads(result.stdout)['package_version'], '2.0.0~beta.8-1')
|
||||
self.assertTrue(json.loads(result.stdout)['available'])
|
||||
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='2.0.0', TEST_HTTP='fail', TEST_SERVICE='false')
|
||||
self.assertTrue(json.loads(result.stdout)['installed'])
|
||||
self.assertFalse(json.loads(result.stdout)['available'])
|
||||
self.root.joinpath('inventory-error').touch()
|
||||
self.assertFalse(json.loads(self.run_shell('tachyon_json force').stdout)['checked'])
|
||||
self.root.joinpath('inventory-error').unlink()
|
||||
self.root.joinpath('absent').touch()
|
||||
self.assertEqual(json.loads(self.run_shell('tachyon_json force').stdout), dict(checked=True, installed=False))
|
||||
self.assertFalse(list(self.root.glob('tachyon/probe.*')))
|
||||
|
||||
def test_apk_discovery_and_legacy_luci(self):
|
||||
code = r'''
|
||||
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', 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')
|
||||
result = self.run_shell('tachyon_json force')
|
||||
self.assertEqual(json.loads(result.stdout)['port'], 1800)
|
||||
self.harness.config(enabled='1')
|
||||
result = self.run_shell(r'''
|
||||
xray_control_stopped() { return 0; }
|
||||
xray_running() { return 0; }
|
||||
ubus() { echo unexpected >>"$TEST_ROOT/changed"; }
|
||||
tachyon_reconcile_xray
|
||||
''')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertFalse((self.root / 'changed').exists())
|
||||
|
||||
def test_shell_generator_matches_tachyon_route(self):
|
||||
result = self.run_shell('render_client_config --stdout')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
config = json.loads(result.stdout)
|
||||
self.assertEqual(config['outbounds'][0]['settings']['redirect'], '127.0.0.1:1680')
|
||||
self.assertEqual(config['routing']['rules'][0]['outboundTag'], 'router-tachyon')
|
||||
|
||||
|
||||
class ProxyTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.app = hub.App(Path(self.temp.name) / 'hub.db', 'session-test', 'agent-test', '')
|
||||
hub.write_json_private(hub.AUTH_FILE, {'username': 'owner', 'password_hash': 'unused'})
|
||||
class Backend(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path == '/layout':
|
||||
data = b'<html><head><style>.tachyon-bg-layer{position:fixed;inset:0}</style></head><body><div class="tachyon-bg-layer"></div><main>Tachyon</main></body></html>'
|
||||
self.send_response(200); self.send_header('Content-Type', 'text/html')
|
||||
self.send_header('Content-Length', str(len(data))); self.end_headers(); self.wfile.write(data)
|
||||
return
|
||||
data = json.dumps({'path': self.path, 'cookie': self.headers.get('Cookie', ''),
|
||||
'method': self.command, 'body': self.rfile.read(int(self.headers.get('Content-Length', 0))).decode()}).encode()
|
||||
self.send_response(200); self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Set-Cookie', 'tachyon_session=test-private; Path=/; HttpOnly')
|
||||
self.send_header('Content-Length', str(len(data))); self.end_headers(); self.wfile.write(data)
|
||||
do_POST = do_GET
|
||||
do_PUT = do_GET
|
||||
do_DELETE = do_GET
|
||||
def log_message(self, *args): pass
|
||||
self.backend = ThreadingHTTPServer(('127.0.0.1', 0), Backend)
|
||||
self.server = hub.HubHTTPServer(('127.0.0.1', 0), hub.Handler)
|
||||
self.server.app = self.app; self.server.is_tls = False
|
||||
for server in (self.backend, self.server):
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
|
||||
self.addCleanup(self.close, server, thread)
|
||||
with self.app.conn() as conn:
|
||||
hub.upsert_router(conn, {'id': 'main', 'entry_port': 18880})
|
||||
hub.heartbeat(conn, {'id': 'main', 'tachyon': detected()})
|
||||
conn.execute("update routers set tachyon_entry_port=? where id='main'", (self.backend.server_port,))
|
||||
hub.upsert_router(conn, {'id': 'absent'})
|
||||
|
||||
@staticmethod
|
||||
def close(server, thread):
|
||||
server.shutdown(); server.server_close(); thread.join(timeout=3)
|
||||
|
||||
def request(self, path='/tachyon/main/', method='GET', origin=None, cookie=True):
|
||||
headers = {}
|
||||
if cookie: headers['Cookie'] = 'owrt_remote_session=session-test; tachyon_session=private-router-session'
|
||||
if origin: headers['Origin'] = origin
|
||||
connection = http.client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=5)
|
||||
try:
|
||||
connection.request(method, path, body='{}' if method != 'GET' else None, headers=headers)
|
||||
with connection.getresponse() as result: return result.status, result.read(), result.getheaders()
|
||||
finally: connection.close()
|
||||
|
||||
def test_proxy_authentication_selected_router_cookie_scope_and_mutations(self):
|
||||
self.assertEqual(self.request(cookie=False)[0], 401)
|
||||
status, raw, headers = self.request('/tachyon/main/api/status?view=x')
|
||||
self.assertEqual(status, 200, raw)
|
||||
result = json.loads(raw)
|
||||
self.assertEqual(result['path'], '/api/status?view=x')
|
||||
self.assertNotIn('session-test', result['cookie'])
|
||||
self.assertIn('private-router-session', result['cookie'])
|
||||
cookie = next(v for k, v in headers if k.lower() == 'set-cookie')
|
||||
self.assertIn('Path=/tachyon/main/', cookie)
|
||||
self.assertEqual(self.request('/tachyon/absent/')[0], 404)
|
||||
self.assertEqual(self.request('/tachyon/missing/')[0], 404)
|
||||
with mock.patch.object(hub.Handler, 'router_access_allowed', return_value=False):
|
||||
self.assertEqual(self.request()[0], 403)
|
||||
self.assertEqual(self.request(method='POST', origin='https://foreign.example')[0], 403)
|
||||
origin = 'http://127.0.0.1:' + str(self.server.server_port)
|
||||
for method in ('POST', 'PUT', 'DELETE'):
|
||||
status, raw, _ = self.request('/tachyon/main/api/settings', method, origin)
|
||||
self.assertEqual(status, 200, raw)
|
||||
self.assertEqual(json.loads(raw)['method'], method)
|
||||
self.assertEqual(json.loads(raw)['body'], '{}')
|
||||
|
||||
def test_tachyon_html_keeps_own_layout_without_shared_hub_effects(self):
|
||||
status, raw, _ = self.request('/tachyon/main/layout')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertNotIn(b'owrt-hub-design-head', raw)
|
||||
self.assertNotIn(b'body>*:not(.seasonalFx)', raw)
|
||||
self.assertIn(b'.tachyon-bg-layer{position:fixed;inset:0}', raw)
|
||||
self.assertIn(b'const prefix = "/tachyon/main"', raw, 'URL forwarding still applies')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -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 => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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;});
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Exercise install/rollback and failure recovery in a disposable router tree."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from test_host_policy import ROOT, SH
|
||||
|
||||
|
||||
@unittest.skipUnless(SH, 'POSIX shell required')
|
||||
class DeployTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix='tachyon-deploy-')
|
||||
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')}
|
||||
for name in ('agent',):
|
||||
self.targets[name].write_text('#!/bin/sh\necho previous\n')
|
||||
self.before = {name: path.read_bytes() if path.exists() else None for name, path in self.targets.items()}
|
||||
self.script = (ROOT / 'vps/deploy-tachyon.ps1').read_text().split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
|
||||
self.script = self.script.replace('backup=/root/owrt-remote-backup-before-__BACKUP_NAME__-v121', 'backup=' + shlex.quote((self.root / 'backup').as_posix()))
|
||||
for name, target in self.targets.items():
|
||||
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() {
|
||||
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; }
|
||||
test_restart() { [ "${FAIL_RESTART:-0}" != 1 ]; }
|
||||
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, 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():
|
||||
text = 'if true; then\n' if bad and name == 'tachyon.sh' else (ROOT / source).read_text(encoding='utf-8')
|
||||
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')
|
||||
result = subprocess.run([SH], input=script, text=True, encoding='utf-8', capture_output=True,
|
||||
env={**self.env, 'FAIL_RESTART': str(int(fail))}, timeout=30)
|
||||
self.assertFalse(stage.exists())
|
||||
self.assertFalse(list(self.root.glob('*.new-sandbox')))
|
||||
return result
|
||||
|
||||
def assert_original(self):
|
||||
for name, path in self.targets.items():
|
||||
self.assertEqual(path.read_bytes() if path.exists() else None, self.before[name])
|
||||
|
||||
def test_install_twice_and_rollback_restore_absent_helper(self):
|
||||
for _ in range(2):
|
||||
result = self.deploy()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('TACHYON_INTEGRATION_Router_Install_OK', result.stdout)
|
||||
result = self.deploy('Rollback')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assert_original()
|
||||
|
||||
def test_invalid_candidate_and_missing_backup_do_not_change_files(self):
|
||||
self.assertNotEqual(self.deploy(bad=True).returncode, 0)
|
||||
self.assert_original()
|
||||
self.assertNotEqual(self.deploy('Rollback').returncode, 0)
|
||||
self.assert_original()
|
||||
|
||||
def test_restart_failure_restores_files_from_current_attempt(self):
|
||||
result = self.deploy(fail=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('restoring files', result.stderr)
|
||||
self.assertIn('Failed during restart', result.stderr)
|
||||
self.assertIn('Router deployment diagnostics:', result.stderr)
|
||||
self.assert_original()
|
||||
|
||||
def test_missing_timeout_applet_does_not_reject_router(self):
|
||||
result = self.deploy(no_timeout=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('shell timeout fallback will be used', result.stderr)
|
||||
self.assertIn('TACHYON_INTEGRATION_Router_Install_OK', result.stdout)
|
||||
|
||||
def test_failed_preflight_names_step_and_keeps_files(self):
|
||||
result = self.deploy(bad=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('tachyon.sh shell syntax check failed', result.stderr)
|
||||
self.assertIn('Failed during preflight', result.stderr)
|
||||
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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,47 @@
|
||||
// Requires Playwright; see docs/TACHYON_INTEGRATION.md for the layout scenario.
|
||||
const { chromium } = require('playwright');
|
||||
const fs = require('node:fs');
|
||||
const assert = require('node:assert/strict');
|
||||
const fixtures = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
(async () => {
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
...(process.env.OWRT_TEST_BROWSER_BIN ? {executablePath: process.env.OWRT_TEST_BROWSER_BIN} : {})
|
||||
});
|
||||
let count = 0;
|
||||
try {
|
||||
for (const [fixture, body] of Object.entries(fixtures)) {
|
||||
for (const [width, height] of [[1280,900], [390,844], [844,390]]) {
|
||||
for (const design of ['default','winter','lite']) {
|
||||
const context = await browser.newContext({viewport: {width,height}});
|
||||
try {
|
||||
await context.addInitScript(mode => {
|
||||
localStorage.setItem('owrtRemote:hubDesign', mode);
|
||||
localStorage.setItem('owrtRemote:seasonEffectMode', 'snow');
|
||||
}, design);
|
||||
await context.route('**/*', route => {
|
||||
if (route.request().isNavigationRequest()) return route.fulfill({status:200, contentType:'text/html', body});
|
||||
return route.abort(); // Layout check only: no RPC or router writes.
|
||||
});
|
||||
const page = await context.newPage();
|
||||
await page.goto('http://hub.test/tachyon/node-10/', {waitUntil:'domcontentloaded'});
|
||||
await page.waitForTimeout(80);
|
||||
const geometry = await page.evaluate(() => ({
|
||||
backgroundPosition: getComputedStyle(document.querySelector('.tachyon-bg-layer')).position,
|
||||
contentTop: document.querySelector('#maincontent').getBoundingClientRect().top,
|
||||
scrollY: window.scrollY,
|
||||
extraCanvas: Boolean(document.getElementById('seasonalFx'))
|
||||
}));
|
||||
const label = [fixture,width,height,design].join('/');
|
||||
assert.equal(geometry.backgroundPosition,'fixed',label);
|
||||
assert(geometry.contentTop >= -1 && geometry.contentTop <= 1, label + ': content pushed down: ' + geometry.contentTop);
|
||||
assert.equal(geometry.scrollY,0,label);
|
||||
assert.equal(geometry.extraCanvas,false,label);
|
||||
count++;
|
||||
} finally { await context.close(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
console.log('TACHYON_LAYOUT_OK: ' + count + ' browser cases; content starts at the top');
|
||||
})().catch(error => {console.error(error);process.exitCode=1;});
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Hub and Xray must be validated and restored as one local deployment."""
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from test_host_policy import ROOT, SH
|
||||
|
||||
|
||||
@unittest.skipUnless(SH, 'POSIX shell required')
|
||||
class RouteDeployTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.hub = self.root / 'hub.py'
|
||||
self.xray = self.root / 'xray.json'
|
||||
self.hub.write_text('old hub')
|
||||
self.xray.write_text('old xray')
|
||||
self.env = {**os.environ, 'PATH': str(Path(SH).parent) + os.pathsep + os.environ['PATH']}
|
||||
script = (ROOT / 'vps/deploy-tachyon-route-fix.ps1').read_text(encoding='utf-8')
|
||||
self.script = script.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
|
||||
for old, path in (('backup=/root/owrt-remote-backup-before-tachyon-route-fix-v121', self.root / 'backup'),
|
||||
('hub=/opt/owrt-remote/owrt-remote-hub.py', self.hub),
|
||||
('xray_config=/etc/xray/owrt-remote.json', self.xray)):
|
||||
self.script = self.script.replace(old, old.split('=', 1)[0] + '=' + shlex.quote(path.as_posix()))
|
||||
self.script = self.script.replace('test -x /usr/local/bin/xray', 'true').replace('/usr/local/bin/xray -test', 'test_xray -test')
|
||||
self.mocks = r'''
|
||||
python3() {
|
||||
if [ "$1" = -m ]; then return 0; fi
|
||||
if [ "$1" = - ] && [ "$#" = 3 ]; then cat >/dev/null; printf 'new xray' >"$3"; return; fi
|
||||
if [ "$1" = - ]; then cat >/dev/null; [ "${FAIL_HEALTH:-0}" = 0 ]; return; fi
|
||||
printf 'new xray' >"$4"
|
||||
}
|
||||
test_xray() { [ "${FAIL_VALIDATION:-0}" = 0 ]; }
|
||||
systemctl() { [ "${FAIL_RESTART:-0}" = 0 ]; }
|
||||
'''
|
||||
|
||||
def run_deploy(self, action='Install', **flags):
|
||||
stage = self.root / 'stage'
|
||||
stage.mkdir()
|
||||
(stage / 'hub.py').write_text('new hub')
|
||||
script = self.script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(stage.as_posix()))
|
||||
script = script.replace('__UPLOAD_NAME__', 'test').replace('__ACTION__', action)
|
||||
result = subprocess.run([SH], input=self.mocks + script, capture_output=True, text=True,
|
||||
env={**self.env, **flags}, timeout=20)
|
||||
self.assertFalse(stage.exists())
|
||||
return result
|
||||
|
||||
def test_success_and_rollback_restore_both_files(self):
|
||||
result = self.run_deploy()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.hub.read_text(), 'new hub')
|
||||
self.assertEqual(self.xray.read_text(), 'new xray')
|
||||
result = self.run_deploy('Rollback')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.hub.read_text(), 'old hub')
|
||||
self.assertEqual(self.xray.read_text(), 'old xray')
|
||||
|
||||
def test_invalid_xray_never_replaces_either_file(self):
|
||||
result = self.run_deploy(FAIL_VALIDATION='1')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('validate-xray', result.stderr)
|
||||
self.assertEqual(self.hub.read_text(), 'old hub')
|
||||
self.assertEqual(self.xray.read_text(), 'old xray')
|
||||
self.assertFalse((self.root / 'backup').exists())
|
||||
|
||||
def test_failed_restart_restores_current_attempt(self):
|
||||
result = self.run_deploy(FAIL_RESTART='1')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('Restoring Hub and Xray', result.stderr)
|
||||
self.assertEqual(self.hub.read_text(), 'old hub')
|
||||
self.assertEqual(self.xray.read_text(), 'old xray')
|
||||
|
||||
def test_missing_backup_is_read_only(self):
|
||||
result = self.run_deploy('Rollback')
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.hub.read_text(), 'old hub')
|
||||
self.assertEqual(self.xray.read_text(), 'old xray')
|
||||
|
||||
def test_config_patch_preserves_vless_port_clients_and_other_services(self):
|
||||
text=(ROOT/'vps/deploy-tachyon-route-fix.ps1').read_text()
|
||||
code=text.split("<<'PY'\n",1)[1].split('\nPY',1)[0]
|
||||
config={'inbounds':[{'tag':'vless','port':9443,'settings':{'clients':[{'id':'test-secret'}]}},
|
||||
{'tag':'tachyon-main','protocol':'tunnel','listen':'127.0.0.1','port':24000,
|
||||
'settings':{'allowedNetwork':'tcp','rewriteAddress':'127.0.0.1','rewritePort':1680}}],
|
||||
'outbounds':[{'tag':'custom','protocol':'freedom'}], 'log':{'loglevel':'warning'}}
|
||||
source=self.root/'source.json'; target=self.root/'candidate.json'
|
||||
source.write_text(json.dumps(config))
|
||||
result=subprocess.run([sys.executable,'-c',code,str(source),str(target)],capture_output=True,text=True)
|
||||
self.assertEqual(result.returncode,0,result.stderr)
|
||||
actual=json.loads(target.read_text())
|
||||
self.assertEqual(actual['inbounds'][0],config['inbounds'][0])
|
||||
self.assertEqual(actual['outbounds'],config['outbounds'])
|
||||
settings=actual['inbounds'][1]['settings']
|
||||
self.assertEqual(settings['port'],1680)
|
||||
self.assertEqual(settings['address'],'127.0.0.1')
|
||||
self.assertEqual(settings['network'],'tcp')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,30 @@
|
||||
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 code = source.slice(start, end).replaceAll('{{', '{').replaceAll('}}', '}');
|
||||
const escape = value => String(value).replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch]));
|
||||
const context = {escapeHtml: escape, escapeAttr: escape};
|
||||
vm.createContext(context); vm.runInContext(code, context);
|
||||
assert.equal(context.renderTachyon({}), '');
|
||||
assert.equal(context.renderTachyon({tachyon: {installed: false}}), '');
|
||||
const router = {permissions: {admin: true}, tachyon: {installed: true, version: '2.0.0~beta.8-1', online: true, url: '/tachyon/a/'}};
|
||||
let html = context.renderTachyon(router);
|
||||
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;
|
||||
assert(!context.renderTachyon(router).includes('<a '));
|
||||
router.permissions.admin = true; router.tachyon.version = '<img onerror=alert(1)>';
|
||||
assert(!context.renderTachyon(router).includes('<img '));
|
||||
assert.equal(source.split(String.fromCharCode(36) + '{{renderTachyon(r)}}').length - 1, 2);
|
||||
console.log('TACHYON_UI_OK: absent, installed, offline, access controls, escaping and both layouts');
|
||||
@@ -130,9 +130,9 @@ sleep() { return 0; }
|
||||
|
||||
|
||||
class VersionDeployTests(UpdateStatusDeployTests):
|
||||
deploy_file = 'deploy-version-v121.ps1'
|
||||
backup_name = 'hub.py.bak-before-v121'
|
||||
success_marker = 'HUB_V121_Install_OK'
|
||||
deploy_file = 'deploy-version-v122.ps1'
|
||||
backup_name = 'hub.py.bak-before-v122'
|
||||
success_marker = 'HUB_V122_Install_OK'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -402,11 +402,13 @@ xray_discover_releases() {
|
||||
printf 'v26.6.27|missing.ipk|https://github.com/missing|%s|%s\n' "$(xray_digest "$TEST_ROOT/release.pkg")" "$(wc -c <"$TEST_ROOT/release.pkg")" >"$1"
|
||||
printf 'v26.6.27|published.ipk|https://github.com/published|%s|%s\n' "$(xray_digest "$TEST_ROOT/release.pkg")" "$(wc -c <"$TEST_ROOT/release.pkg")" >>"$1"
|
||||
}
|
||||
xray_probe_url() { case "$1" in */missing) return 22 ;; esac; }
|
||||
fetch_file() { cp "$TEST_ROOT/release.pkg" "$2"; }
|
||||
fetch_file() {
|
||||
case "$1" in */missing) printf '22 HTTP 404\n' >"$DOWNLOAD_RESULT_FILE"; return 22 ;; esac
|
||||
cp "$TEST_ROOT/release.pkg" "$2"
|
||||
}
|
||||
''')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('URL unavailable (rc=22)', result.stderr)
|
||||
self.assertIn('http=404', result.stderr)
|
||||
self.assertEqual(self.binary.read_bytes(), data)
|
||||
self.assert_clean()
|
||||
|
||||
@@ -544,7 +546,7 @@ curl() {
|
||||
calls = (self.directory / 'fetches').read_text().splitlines()
|
||||
for call, host in zip(calls, ('github.com', 'release-assets.githubusercontent.com')):
|
||||
self.assertIn('--connect-timeout 10', call)
|
||||
self.assertIn('--max-time 120.000', call)
|
||||
self.assertRegex(call, r'--max-time [1-9][0-9]*\.000')
|
||||
self.assertIn('--resolve ' + host + ':443:192.0.2.42', call)
|
||||
self.assertIn('--interface wan', call)
|
||||
self.assertNotIn('--insecure', call)
|
||||
@@ -561,6 +563,10 @@ curl() {
|
||||
def test_download_timeout_removes_partial_data_and_preserves_error(self):
|
||||
result = self.shell('fetch_file https://github.com/test "$TEST_ROOT/download"', mocks=r'''
|
||||
curl() { local arg previous; previous=''; for arg in "$@"; do [ "$previous" != -o ] || echo partial >"$arg"; previous="$arg"; done; return 28; }
|
||||
command() {
|
||||
if [ "$1" = -v ]; then case "$2" in wget|uclient-fetch) return 1 ;; esac; fi
|
||||
builtin command "$@"
|
||||
}
|
||||
''')
|
||||
self.assertEqual(result.returncode, 28, result.stderr)
|
||||
self.assertFalse((self.directory / 'download').exists())
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Local download-fix payload installation and rollback, no SSH required."""
|
||||
import unittest
|
||||
from test_xray_apk_deploy import XrayApkDeploymentTests
|
||||
|
||||
|
||||
class XrayDownloadDeploymentTests(XrayApkDeploymentTests):
|
||||
deploy_name = 'deploy-xray-download-fix.ps1'
|
||||
backup_name = 'owrt-remote-backup-before-xray-download-v121'
|
||||
success_marker = 'XRAY_DOWNLOAD_ROUTER_Install_OK'
|
||||
|
||||
def test_failed_xray_preparation_restores_agent_and_retains_backup(self):
|
||||
self.env['PREPARE_RC'] = '13'
|
||||
result = self.deploy('Install')
|
||||
self.assertEqual(result.returncode, 13, result.stderr)
|
||||
self.assertIn('prepare-xray-download', result.stderr)
|
||||
self.assertEqual(self.targets['agent'].read_bytes(), self.original['agent'])
|
||||
self.assertEqual(self.backup.joinpath('agent').read_bytes(), self.original['agent'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -189,5 +189,28 @@ fetch_file() {
|
||||
self.assertEqual(self.directory.joinpath('next-release-page').read_text().strip(),'2')
|
||||
self.assertEqual(len(self.directory.joinpath('fetched').read_text().splitlines()),1)
|
||||
|
||||
def test_same_selector_matches_only_the_exact_published_target_for_apk_and_ipk(self):
|
||||
architectures = ('aarch64_cortex-a53', 'aarch64_cortex-a72', 'aarch64_generic',
|
||||
'arm_cortex-a7', 'arm_cortex-a7_neon-vfpv4', 'arm_cortex-a9',
|
||||
'mips_24kc', 'mipsel_24kc', 'mips64', 'i386', 'x86_64')
|
||||
for fmt in ('apk', 'ipk'):
|
||||
assets = []
|
||||
for arch in architectures:
|
||||
item = self.asset(arch=arch)
|
||||
if fmt == 'ipk':
|
||||
name = f'openwrt-xray_26.6.22-2_{arch}.ipk'
|
||||
item['browser_download_url'] = item['browser_download_url'].replace(item['name'], name)
|
||||
item['name'] = name
|
||||
assets.append(item)
|
||||
self.manifest([self.release(assets=assets)])
|
||||
for arch in architectures:
|
||||
with self.subTest(format=fmt, arch=arch):
|
||||
result = self.run_case('xray_discover_releases "$TEST_ROOT/candidates" "$TEST_ROOT"; cat "$TEST_ROOT/candidates"',
|
||||
mocks=f'xray_package_format() {{ printf {fmt}; }}', TEST_ARCH=arch)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
selected = result.stdout.strip().splitlines()
|
||||
self.assertEqual(len(selected), 1, result.stdout)
|
||||
self.assertIn(('-' if fmt == 'apk' else '_') + arch + '.' + fmt, selected[0])
|
||||
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -67,7 +67,7 @@ class ReverseTransportTests(unittest.TestCase):
|
||||
server.server_close()
|
||||
thread.join(timeout=3)
|
||||
|
||||
def check_pair(self, server_bin, shell_client=False):
|
||||
def check_pair(self, server_bin, shell_client=False, tachyon=False):
|
||||
processes, streams = [], []
|
||||
row = dict(id='probe', name='probe', entry_port=free_port(), ssh_entry_port=free_port(),
|
||||
vps_host='127.0.0.1', vless_port=free_port(), vless_uuid=str(uuid.uuid4()),
|
||||
@@ -75,6 +75,18 @@ class ReverseTransportTests(unittest.TestCase):
|
||||
reverse_tag='reverse-in', ssh_reverse_tag='reverse-in-ssh',
|
||||
admin_host='127.0.0.1', admin_port=self.http_server.server_port,
|
||||
ssh_host='127.0.0.1', ssh_port=self.ssh_server.server_address[1])
|
||||
if tachyon:
|
||||
class TachyonProbe(HTTPProbe):
|
||||
def do_GET(self):
|
||||
data = b'TACHYON_SELECTED_ROUTER_OK'
|
||||
self.send_response(200); self.send_header('Content-Length', str(len(data)))
|
||||
self.end_headers(); self.wfile.write(data)
|
||||
service = ThreadingHTTPServer(('127.0.0.1', 0), TachyonProbe)
|
||||
thread = threading.Thread(target=service.serve_forever, daemon=True); thread.start()
|
||||
self.addCleanup(self.close_server, service, thread)
|
||||
row['tachyon_entry_port'] = free_port()
|
||||
row['status_json'] = json.dumps({'tachyon': {'checked': True, 'installed': True,
|
||||
'mode': 'standalone', 'port': service.server_port, 'available': True}})
|
||||
configs = dict(server=hub.make_server_xray_config([row], listen_host='127.0.0.1',
|
||||
listen_port=row['vless_port']),
|
||||
client=hub.make_router_xray_config(row))
|
||||
@@ -87,7 +99,8 @@ class ReverseTransportTests(unittest.TestCase):
|
||||
reverse_tag=row['reverse_tag'], ssh_reverse_tag=row['ssh_reverse_tag'],
|
||||
admin_host=row['admin_host'], admin_port=row['admin_port'],
|
||||
ssh_host=row['ssh_host'], ssh_port=row['ssh_port'])
|
||||
result = harness.run_shell('render_client_config --stdout')
|
||||
injection = ('tachyon_tunnel_port() { printf ' + str(service.server_port) + '; }\n') if tachyon else ''
|
||||
result = harness.run_shell(injection + 'render_client_config --stdout')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
configs['client'] = json.loads(result.stdout)
|
||||
finally:
|
||||
@@ -127,6 +140,14 @@ class ReverseTransportTests(unittest.TestCase):
|
||||
with socket.create_connection(('127.0.0.1', row['ssh_entry_port']), timeout=3) as sock:
|
||||
sock.settimeout(3)
|
||||
self.assertEqual(sock.recv(128), b'SSH-2.0-OWRT_TEST\r\n', logs)
|
||||
if tachyon:
|
||||
connection = http.client.HTTPConnection('127.0.0.1', row['tachyon_entry_port'], timeout=5)
|
||||
try:
|
||||
connection.request('GET', '/')
|
||||
with connection.getresponse() as result:
|
||||
self.assertEqual((result.status, result.read()), (200, b'TACHYON_SELECTED_ROUTER_OK'), logs)
|
||||
finally:
|
||||
connection.close()
|
||||
finally:
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
@@ -149,6 +170,19 @@ class ReverseTransportTests(unittest.TestCase):
|
||||
def test_real_router_shell_config_with_modern_server(self):
|
||||
self.check_pair(Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).resolve(), shell_client=True)
|
||||
|
||||
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_NEW_XRAY_BIN'), 'POSIX shell and modern server required')
|
||||
def test_tachyon_admin_and_ssh_share_reverse_without_cross_routing(self):
|
||||
self.check_pair(Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).resolve(), shell_client=True, tachyon=True)
|
||||
|
||||
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_OLD_XRAY_BIN'), 'Legacy server Xray binary required')
|
||||
def test_tachyon_with_26327_server_preserves_destination_port(self):
|
||||
self.check_pair(Path(os.environ['OWRT_TEST_OLD_XRAY_BIN']).resolve(), shell_client=True, tachyon=True)
|
||||
|
||||
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_OLD_XRAY_BIN'), 'Legacy Xray binaries required')
|
||||
def test_tachyon_with_26327_router_and_server(self):
|
||||
self.client_bin = Path(os.environ['OWRT_TEST_OLD_XRAY_BIN']).resolve()
|
||||
self.check_pair(self.client_bin, shell_client=True, tachyon=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -25,9 +25,11 @@ fi
|
||||
|
||||
rmf usr/sbin/owrt-remote
|
||||
rmf usr/lib/owrt-remote/wan.sh
|
||||
rmf usr/lib/owrt-remote/tachyon.sh
|
||||
rmf usr/lib/owrt-remote/logs.sh
|
||||
rmf etc/init.d/owrt-remote-logs
|
||||
rm -rf "$(target_path tmp/owrt-remote-logs)"
|
||||
rm -rf "$(target_path tmp/owrt-remote-tachyon)"
|
||||
rmdir "$(target_path usr/lib/owrt-remote)" 2>/dev/null || true
|
||||
rmf etc/init.d/owrt-remote
|
||||
rmf www/cgi-bin/owrt-remote
|
||||
|
||||
@@ -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." }
|
||||
@@ -104,7 +104,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
command -v base64 >/dev/null
|
||||
command -v jsonfilter >/dev/null
|
||||
grep -F -q 'globalLogsToggle' "$stage/cgi"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
|
||||
grep -F -q 'log_sync_loop' "$stage/logs.sh"
|
||||
grep -F -q 'sync_global_logs' "$stage/agent"
|
||||
|
||||
@@ -57,7 +57,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = ('v121', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
|
||||
required = ('v122', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
|
||||
if 'class="backupCmds"' in source:
|
||||
print('Old backup command instructions remain in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -90,7 +90,7 @@ test -s "$config"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
test -s "$stage/luci"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
# curl is needed to preserve HTTPS SNI and bypass the local DNS/proxy.
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
if command -v opkg >/dev/null 2>&1; then opkg update && opkg install curl ca-bundle
|
||||
@@ -156,8 +156,8 @@ if [ '__ACTION__' = Install ]; then
|
||||
exit 1
|
||||
fi
|
||||
/usr/sbin/owrt-remote status
|
||||
grep -F -q 'v121' /www/cgi-bin/owrt-remote
|
||||
grep -F -q 'v121' /www/luci-static/resources/view/owrt_remote.js
|
||||
grep -F -q 'v122' /www/cgi-bin/owrt-remote
|
||||
grep -F -q 'v122' /www/luci-static/resources/view/owrt_remote.js
|
||||
echo HOST_POLICY_ROUTER_V121_OK
|
||||
else
|
||||
test -f "$backup/complete"
|
||||
@@ -200,7 +200,7 @@ test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'v121' "$stage/hub.py"
|
||||
grep -F -q 'v122' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/test_host_policy.py" HostPolicyTests -v
|
||||
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" -v
|
||||
|
||||
@@ -99,7 +99,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'heartbeat_set_url_if_changed()' "$stage/agent"
|
||||
grep -F -q 'reason=https-downgrade' "$stage/agent"
|
||||
for item in agent wan.sh; do grep -F -q -- '--post301' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
if [ ! -e "$backup" ]; then
|
||||
save_files "$stage/retained-backup"
|
||||
mv "$stage/retained-backup" "$backup"
|
||||
@@ -174,7 +174,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'def router_hub_origins(' "$stage/hub.py"
|
||||
grep -F -q 'v121' "$stage/hub.py"
|
||||
grep -F -q 'v122' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/host_policy.py" HostPolicyTests -v
|
||||
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" IntegrationTests -v
|
||||
|
||||
@@ -106,7 +106,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
exit 1
|
||||
fi
|
||||
grep -F -q 'globalLogsToggle' "$stage/cgi"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
grep -F -q 'LOG_BUFFER_LIMIT=16384' "$stage/logs.sh"
|
||||
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
|
||||
grep -F -q 'log_sync_loop' "$stage/logs.sh"
|
||||
|
||||
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
|
||||
import ast, pathlib, sys
|
||||
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
tree = ast.parse(source)
|
||||
assert 'v121' in source
|
||||
assert 'v122' in source
|
||||
assert 'v108' not in source
|
||||
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
|
||||
assert 'prepareLoginRecaptcha' in source
|
||||
|
||||
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
|
||||
import ast, pathlib, sys
|
||||
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
tree = ast.parse(source)
|
||||
assert 'v121' in source
|
||||
assert 'v122' in source
|
||||
assert 'v108' not in source
|
||||
factory = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'connect')
|
||||
assert any(isinstance(item, ast.Name) and item.id == 'contextmanager' for item in factory.decorator_list)
|
||||
|
||||
@@ -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." }
|
||||
@@ -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.' }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
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 tachyon-layout -PrepareOnly:$PrepareOnly
|
||||
@@ -0,0 +1,146 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-tachyon-route-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [Text.UTF8Encoding]::new($false)
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
umask 077
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-tachyon-route-fix-v121
|
||||
hub=/opt/owrt-remote/owrt-remote-hub.py
|
||||
xray_config=/etc/xray/owrt-remote.json
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
changed=0
|
||||
step=preflight
|
||||
snapshot() {
|
||||
mkdir -p "$1"; chmod 0700 "$1"
|
||||
cp -p "$hub" "$1/hub.py"
|
||||
cp -p "$xray_config" "$1/xray.json"
|
||||
: >"$1/complete"
|
||||
}
|
||||
apply_files() {
|
||||
cp "$1/hub.py" "$hub.new-__UPLOAD_NAME__"
|
||||
chmod 0755 "$hub.new-__UPLOAD_NAME__"; mv -f "$hub.new-__UPLOAD_NAME__" "$hub"
|
||||
cp "$1/xray.json" "$xray_config.new-__UPLOAD_NAME__"
|
||||
chmod 0600 "$xray_config.new-__UPLOAD_NAME__"; mv -f "$xray_config.new-__UPLOAD_NAME__" "$xray_config"
|
||||
}
|
||||
restart_services() {
|
||||
systemctl restart owrt-remote
|
||||
systemctl restart owrt-remote-xray
|
||||
}
|
||||
cleanup() {
|
||||
code=$?; trap - EXIT; set +e
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Tachyon route fix failed during $step (rc=$code)." >&2
|
||||
if [ "$changed" = 1 ]; then
|
||||
echo 'Restoring Hub and Xray configuration from before this attempt.' >&2
|
||||
apply_files "$stage/previous" && restart_services || echo 'Automatic restoration was not confirmed.' >&2
|
||||
fi
|
||||
fi
|
||||
rm -f "$hub.new-__UPLOAD_NAME__" "$xray_config.new-__UPLOAD_NAME__"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
test -s "$hub"; test -s "$xray_config"; test -x /usr/local/bin/xray
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
step=prepare-xray
|
||||
cp -p "$xray_config" "$stage/baseline-xray.json"
|
||||
"$python_bin" - "$stage/baseline-xray.json" "$stage/xray.json" <<'PY'
|
||||
import json,os,pathlib,sys
|
||||
config=json.loads(pathlib.Path(sys.argv[1]).read_text())
|
||||
changed=0
|
||||
for inbound in config.get('inbounds',[]):
|
||||
if inbound.get('protocol')!='tunnel' or not str(inbound.get('tag','')).startswith(('entry-','ssh-','tachyon-')):
|
||||
continue
|
||||
settings=inbound.get('settings',{})
|
||||
if not all(k in settings for k in ('allowedNetwork','rewriteAddress','rewritePort')):
|
||||
continue
|
||||
port=settings['rewritePort']
|
||||
if not isinstance(port,int) or isinstance(port,bool) or not 1<=port<=65535:
|
||||
raise SystemExit('Invalid reverse target port')
|
||||
settings.update(network=settings['allowedNetwork'],address=settings['rewriteAddress'],port=port)
|
||||
changed+=1
|
||||
out=pathlib.Path(sys.argv[2])
|
||||
out.write_text(json.dumps(config,ensure_ascii=False,indent=2)+'\n')
|
||||
os.chmod(out,0o600)
|
||||
print('Prepared compatible reverse listeners: '+str(changed))
|
||||
PY
|
||||
source_dir="$stage"
|
||||
else
|
||||
test -e "$backup/complete" && test -s "$backup/hub.py" && test -s "$backup/xray.json" || {
|
||||
echo "No complete backup: $backup. Nothing changed." >&2; exit 1;
|
||||
}
|
||||
source_dir="$backup"
|
||||
fi
|
||||
step=validate-xray
|
||||
/usr/local/bin/xray -test -config "$source_dir/xray.json"
|
||||
step=backup
|
||||
if [ '__ACTION__' = Install ] && [ ! -e "$backup/complete" ]; then
|
||||
test ! -e "$backup" || { echo "Incomplete backup exists: $backup" >&2; exit 1; }
|
||||
snapshot "$backup"
|
||||
fi
|
||||
snapshot "$stage/previous"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
cmp "$stage/baseline-xray.json" "$stage/previous/xray.json" || {
|
||||
echo 'Xray configuration changed during preflight; retry the installation.' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
changed=1
|
||||
step=apply-files
|
||||
apply_files "$source_dir"
|
||||
step=restart
|
||||
restart_services
|
||||
step=verify-health
|
||||
"$python_bin" - <<'PY'
|
||||
import hashlib,json,pathlib,time,urllib.request,subprocess
|
||||
expected=hashlib.sha256(pathlib.Path('/opt/owrt-remote/owrt-remote-hub.py').read_bytes()).hexdigest()
|
||||
client=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
for attempt in range(25):
|
||||
try:
|
||||
with client.open('http://127.0.0.1:8088/health?panel-update=1',timeout=2) as response:
|
||||
data=json.load(response)
|
||||
running=subprocess.run(['systemctl','is-active','--quiet','owrt-remote-xray']).returncode==0
|
||||
if data.get('ok') and data.get('revision')==expected and running: break
|
||||
except (OSError,ValueError): pass
|
||||
time.sleep(1)
|
||||
else: raise SystemExit('Hub revision or Xray service was not confirmed')
|
||||
print('Running Hub and Xray verified: '+expected)
|
||||
PY
|
||||
cmp "$source_dir/hub.py" "$hub"
|
||||
cmp "$source_dir/xray.json" "$xray_config"
|
||||
echo "Backup: $backup"
|
||||
echo 'TACHYON_ROUTE_FIX___ACTION___OK'
|
||||
'@
|
||||
try {
|
||||
[IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace([string][char]13, [string]::Empty)
|
||||
[IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript + [char]10, $Utf8)
|
||||
if ($Action -eq 'Install') {
|
||||
$Source = [IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace([string][char]13, [string]::Empty)
|
||||
[IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Source, $Utf8)
|
||||
}
|
||||
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||
& scp -O -o ConnectTimeout=20 -r -- $StageRoot "${Vps}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Vps "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed; success was not confirmed." }
|
||||
Write-Host "Tachyon route fix $Action finished successfully."
|
||||
} finally {
|
||||
if (-not $PrepareOnly -and (Test-Path -LiteralPath $StageRoot)) {
|
||||
$Resolved = [IO.Path]::GetFullPath($StageRoot)
|
||||
$Expected = [IO.Path]::GetFullPath((Join-Path ([IO.Path]::GetTempPath()) $UploadName))
|
||||
if ($Resolved -ne $Expected) { throw 'Unsafe staging cleanup path.' }
|
||||
Remove-Item -LiteralPath $Resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[ValidateSet('tachyon-integration', 'tachyon-layout', 'tachyon-detection', '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
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-tachyon-integration-' + [guid]::NewGuid().ToString('N')
|
||||
$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
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
kind=__KIND__
|
||||
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
|
||||
else
|
||||
names='agent tachyon.sh'
|
||||
fi
|
||||
target() {
|
||||
case "$1" in
|
||||
hub.py) echo /opt/owrt-remote/owrt-remote-hub.py ;;
|
||||
agent) echo /usr/sbin/owrt-remote ;;
|
||||
tachyon.sh) echo /usr/lib/owrt-remote/tachyon.sh ;;
|
||||
esac
|
||||
}
|
||||
snapshot() {
|
||||
folder="$1"
|
||||
mkdir -p "$folder"
|
||||
for name in $names; do
|
||||
path="$(target "$name")"
|
||||
if [ -e "$path" ]; then cp -p "$path" "$folder/$name"; else : >"$folder/$name.absent"; fi
|
||||
done
|
||||
printf '%s\n' "$kind" >"$folder/complete"
|
||||
}
|
||||
apply_files() {
|
||||
folder="$1"
|
||||
for name in $names; do
|
||||
path="$(target "$name")"
|
||||
if [ -e "$folder/$name.absent" ]; then
|
||||
rm -f "$path"
|
||||
else
|
||||
test -s "$folder/$name"
|
||||
mkdir -p "$(dirname "$path")"
|
||||
cp "$folder/$name" "$path.new-__UPLOAD_NAME__"
|
||||
if [ "$name" = tachyon.sh ]; then chmod 0644 "$path.new-__UPLOAD_NAME__"; else chmod 0755 "$path.new-__UPLOAD_NAME__"; fi
|
||||
mv -f "$path.new-__UPLOAD_NAME__" "$path"
|
||||
fi
|
||||
done
|
||||
}
|
||||
restart() {
|
||||
if [ "$kind" = Vps ]; then
|
||||
systemctl restart owrt-remote
|
||||
if [ "$action" = Rollback ] && systemctl is-active --quiet owrt-remote-xray; then
|
||||
/opt/owrt-remote/owrt-remote-run.sh render-xray --out /etc/xray/owrt-remote.json
|
||||
systemctl restart owrt-remote-xray
|
||||
fi
|
||||
else /etc/init.d/owrt-remote restart; fi
|
||||
}
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
set +e
|
||||
if [ "$code" -ne 0 ]; then echo "Failed during $step (rc=$code)." >&2; fi
|
||||
if [ "$code" -ne 0 ] && [ "$kind" = Router ]; then diagnose_router || true; fi
|
||||
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
|
||||
echo 'Deployment failed; restoring files from before this attempt.' >&2
|
||||
apply_files "$stage/previous" && restart || true
|
||||
fi
|
||||
if [ "$code" -ne 0 ] && [ "$kind" = Vps ]; then journalctl -u owrt-remote -n 35 --no-pager >&2 || true; fi
|
||||
for name in $names; do path="$(target "$name")"; rm -f "$path.new-__UPLOAD_NAME__"; done
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
diagnose_router() {
|
||||
[ "$kind" = Router ] || return 0
|
||||
echo 'Router deployment diagnostics:' >&2
|
||||
echo "stage=$stage action=$action" >&2
|
||||
for command_name in jsonfilter ubus timeout busybox; do
|
||||
if command -v "$command_name" >/dev/null 2>&1; then
|
||||
echo "command $command_name=$(command -v "$command_name")" >&2
|
||||
else
|
||||
echo "command $command_name=missing" >&2
|
||||
fi
|
||||
done
|
||||
echo 'owrt-remote service:' >&2
|
||||
ubus call service list '{"name":"owrt-remote"}' >&2 || true
|
||||
echo 'recent owrt-remote log:' >&2
|
||||
logread -e owrt-remote 2>/dev/null | tail -n 80 >&2 || true
|
||||
}
|
||||
fail_router() {
|
||||
echo "Router deployment error: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
|
||||
if [ "$action" = Install ]; then
|
||||
if [ "$kind" = Vps ]; then
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
"$python_bin" - "$stage/hub.py" <<'PY'
|
||||
import pathlib, sys
|
||||
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
for marker in ('def normalize_tachyon(', 'def router_tachyon(', 'tachyon_entry_port', 'function renderTachyon('):
|
||||
if marker not in source: raise SystemExit('Candidate missing: ' + marker)
|
||||
print('Hub candidate validated')
|
||||
PY
|
||||
else
|
||||
sh -n "$stage/agent" || fail_router 'agent shell syntax check failed'
|
||||
sh -n "$stage/tachyon.sh" || fail_router 'tachyon.sh shell syntax check failed'
|
||||
test -r /usr/lib/owrt-remote/control.sh || fail_router 'Update Remote v121 first: control.sh missing'
|
||||
command -v jsonfilter >/dev/null 2>&1 || fail_router 'jsonfilter is missing'
|
||||
command -v ubus >/dev/null 2>&1 || fail_router 'ubus is missing'
|
||||
# The agent has a bounded shell fallback when the optional BusyBox
|
||||
# timeout applet is absent, so this is informational rather than a
|
||||
# reason to reject an otherwise valid OpenWrt installation.
|
||||
if command -v timeout >/dev/null 2>&1; then
|
||||
echo 'Router preflight: timeout applet available' >&2
|
||||
elif command -v busybox >/dev/null 2>&1 && busybox timeout 45 true >/dev/null 2>&1; then
|
||||
echo 'Router preflight: BusyBox timeout applet available' >&2
|
||||
else
|
||||
echo 'Router preflight: timeout applet unavailable; agent shell timeout fallback will be used' >&2
|
||||
fi
|
||||
grep -Fq xray_control_dispatch "$stage/agent" || fail_router 'agent does not contain xray_control_dispatch'
|
||||
grep -Fq tachyon_json "$stage/tachyon.sh" || fail_router 'Tachyon discovery helper missing'
|
||||
fi
|
||||
step=backup
|
||||
if [ ! -e "$backup/complete" ]; then
|
||||
test ! -e "$backup" || { echo "Incomplete backup already exists: $backup" >&2; exit 1; }
|
||||
snapshot "$backup"
|
||||
fi
|
||||
test "$(cat "$backup/complete")" = "$kind"
|
||||
source_dir="$stage"
|
||||
else
|
||||
step=backup
|
||||
test "$(cat "$backup/complete" 2>/dev/null)" = "$kind" || { echo "No complete backup: $backup. Nothing changed." >&2; exit 1; }
|
||||
source_dir="$backup"
|
||||
fi
|
||||
for name in $names; do test -s "$source_dir/$name" || test -e "$source_dir/$name.absent"; done
|
||||
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
|
||||
if [ "$defer_restart" != 1 ]; then restart; fi
|
||||
|
||||
step=verify-health
|
||||
if [ "$kind" = Vps ]; then
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
"$python_bin" - <<'PY'
|
||||
import hashlib, json, pathlib, time, urllib.request
|
||||
expected = hashlib.sha256(pathlib.Path('/opt/owrt-remote/owrt-remote-hub.py').read_bytes()).hexdigest()
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
for attempt in range(20):
|
||||
try:
|
||||
with opener.open('http://127.0.0.1:8088/health?panel-update=1', timeout=3) as response:
|
||||
data = json.load(response)
|
||||
if data.get('ok') and data.get('revision') == expected: break
|
||||
except Exception: pass
|
||||
time.sleep(1)
|
||||
else: raise SystemExit('Running Hub revision/health was not confirmed')
|
||||
print('Running Hub revision verified: ' + expected)
|
||||
PY
|
||||
else
|
||||
healthy=0
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
state="$(ubus call service list '{"name":"owrt-remote"}' 2>/dev/null || true)"
|
||||
if [ "$(printf '%s' "$state" | jsonfilter -e '@["owrt-remote"].instances.heartbeat.running')" = true ]; then healthy=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
[ "$healthy" = 1 ] || fail_router 'Heartbeat instance did not start; deployment is being rolled back.'
|
||||
fi
|
||||
step=verify-files
|
||||
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
|
||||
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
|
||||
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') {
|
||||
@{ 'hub.py' = 'vps\owrt-remote-hub.py' }
|
||||
} else {
|
||||
@{ 'agent' = 'files\usr\sbin\owrt-remote'; 'tachyon.sh' = 'files\usr\lib\owrt-remote\tachyon.sh' }
|
||||
}
|
||||
foreach ($Entry in $Sources.GetEnumerator()) {
|
||||
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Entry.Value)).Replace("`r`n", "`n")
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Entry.Key), $Content, $Utf8)
|
||||
}
|
||||
}
|
||||
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||
$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.' }
|
||||
$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)
|
||||
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
|
||||
if ($Resolved -eq $Expected) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][ValidateNotNullOrEmpty()][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][ValidateNotNullOrEmpty()][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-version-v122-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v122
|
||||
candidate=$target.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
|
||||
show_failure() {
|
||||
echo '--- owrt-remote status ---' >&2
|
||||
systemctl --no-pager -l status owrt-remote >&2 || true
|
||||
echo '--- owrt-remote journal ---' >&2
|
||||
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Remote step failed with rc=$code" >&2
|
||||
show_failure
|
||||
fi
|
||||
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
|
||||
echo 'Restoring the previous Hub file...' >&2
|
||||
cp -p "$stage/previous.py" "$candidate"
|
||||
mv -f "$candidate" "$target"
|
||||
systemctl restart owrt-remote || true
|
||||
fi
|
||||
rm -f "$candidate"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
echo 'Validating candidate...'
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
"$python_bin" - "$stage/hub.py" <<'PY'
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = ('v122', 'def hub_update_require_version(', 'def hub_update_older_version(',
|
||||
"else if (state.checked && !state.checking) message('');")
|
||||
if 'v' + str(122 - 1) in source:
|
||||
print('Old UI version remains in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
missing = [marker for marker in required if marker not in source]
|
||||
if missing:
|
||||
for marker in missing:
|
||||
print('Missing marker:', repr(marker), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print('Candidate validation OK')
|
||||
PY
|
||||
if [ ! -e "$backup" ]; then
|
||||
cp -p "$target" "$backup"
|
||||
fi
|
||||
source_file="$stage/hub.py"
|
||||
else
|
||||
test -s "$backup"
|
||||
"$python_bin" -m py_compile "$backup"
|
||||
source_file="$backup"
|
||||
fi
|
||||
|
||||
expected_revision=$("$python_bin" - "$source_file" <<'PY'
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import sys
|
||||
print(hashlib.sha256(Path(sys.argv[1]).read_bytes()).hexdigest())
|
||||
PY
|
||||
)
|
||||
|
||||
cp -p "$target" "$stage/previous.py"
|
||||
cp "$source_file" "$candidate"
|
||||
chmod 0755 "$candidate"
|
||||
changed=1
|
||||
mv -f "$candidate" "$target"
|
||||
echo 'Restarting owrt-remote...'
|
||||
if ! systemctl restart owrt-remote; then
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
|
||||
healthy=0
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
|
||||
if systemctl is-active --quiet owrt-remote && "$python_bin" - "$expected_revision" > "$stage/health-check" 2>&1 <<'PY'
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open('http://127.0.0.1:8088/health?panel-update=1', timeout=3) as response:
|
||||
data = json.loads(response.read(4096))
|
||||
revision = data.get('revision', '')
|
||||
if not data.get('ok') or revision != sys.argv[1]:
|
||||
raise RuntimeError('Running Hub revision does not match the uploaded file: '
|
||||
+ (revision or '(not reported)') + '; expected ' + sys.argv[1])
|
||||
print('Running Hub revision verified: ' + revision)
|
||||
except Exception as error:
|
||||
print('Health verification failed: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
PY
|
||||
then
|
||||
healthy=1
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$healthy" -ne 1 ]; then
|
||||
echo 'The uploaded Hub build did not become ready; installation was not confirmed.' >&2
|
||||
cat "$stage/health-check" >&2 2>/dev/null || true
|
||||
show_failure
|
||||
exit 1
|
||||
fi
|
||||
cat "$stage/health-check"
|
||||
cmp "$source_file" "$target"
|
||||
printf '\nBackup: %s\nHUB_V122_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RouterScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-v122
|
||||
cgi=/www/cgi-bin/owrt-remote
|
||||
luci=/www/luci-static/resources/view/owrt_remote.js
|
||||
changed=0
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Router version __ACTION__ failed (rc=$code)." >&2
|
||||
if [ "$changed" = 1 ]; then
|
||||
echo 'Restoring the previous router UI files...' >&2
|
||||
cp -p "$stage/previous-cgi" "$cgi.new-__UPLOAD_NAME__" && mv -f "$cgi.new-__UPLOAD_NAME__" "$cgi" || true
|
||||
cp -p "$stage/previous-luci" "$luci.new-__UPLOAD_NAME__" && mv -f "$luci.new-__UPLOAD_NAME__" "$luci" || true
|
||||
fi
|
||||
fi
|
||||
rm -f "$cgi.new-__UPLOAD_NAME__" "$luci.new-__UPLOAD_NAME__"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
test -s "$cgi"
|
||||
test -s "$luci"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
sh -n "$stage/cgi"
|
||||
grep -F -q 'v122' "$stage/cgi"
|
||||
grep -F -q 'v122' "$stage/luci"
|
||||
if grep -F -q "v$((122 - 1))" "$stage/cgi" "$stage/luci"; then
|
||||
echo 'Old UI version remains in candidate.' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -e "$backup" ]; then
|
||||
mkdir -m 700 "$stage/retained"
|
||||
cp -p "$cgi" "$stage/retained/cgi"
|
||||
cp -p "$luci" "$stage/retained/luci"
|
||||
: >"$stage/retained/complete"
|
||||
mv "$stage/retained" "$backup"
|
||||
fi
|
||||
source_dir=$stage
|
||||
else
|
||||
source_dir=$backup
|
||||
fi
|
||||
if [ ! -f "$backup/complete" ] || [ ! -s "$backup/cgi" ] || [ ! -s "$backup/luci" ]; then
|
||||
echo "No complete backup: $backup. Nothing changed." >&2
|
||||
exit 1
|
||||
fi
|
||||
sh -n "$source_dir/cgi"
|
||||
cp -p "$cgi" "$stage/previous-cgi"
|
||||
cp -p "$luci" "$stage/previous-luci"
|
||||
cp "$source_dir/cgi" "$cgi.new-__UPLOAD_NAME__"
|
||||
chmod 0755 "$cgi.new-__UPLOAD_NAME__"
|
||||
cp "$source_dir/luci" "$luci.new-__UPLOAD_NAME__"
|
||||
chmod 0644 "$luci.new-__UPLOAD_NAME__"
|
||||
changed=1
|
||||
mv -f "$cgi.new-__UPLOAD_NAME__" "$cgi"
|
||||
mv -f "$luci.new-__UPLOAD_NAME__" "$luci"
|
||||
cmp "$source_dir/cgi" "$cgi"
|
||||
cmp "$source_dir/luci" "$luci"
|
||||
[ ! -x /etc/init.d/rpcd ] || /etc/init.d/rpcd restart || true
|
||||
[ ! -x /etc/init.d/uhttpd ] || /etc/init.d/uhttpd reload || true
|
||||
printf '\nBackup: %s\nROUTER_V122_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
$RemoteScript = $RouterScript
|
||||
$TargetMachine = $Router
|
||||
}
|
||||
else {
|
||||
$TargetMachine = $Vps
|
||||
}
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
[System.IO.File]::WriteAllText(
|
||||
(Join-Path $StageRoot 'run.sh'),
|
||||
$RemoteScript.Replace("`r`n", "`n") + "`n",
|
||||
$Utf8
|
||||
)
|
||||
|
||||
if ($Action -eq 'Install') {
|
||||
$Files = if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
@{ 'cgi' = 'files\www\cgi-bin\owrt-remote'; 'luci' = 'files\www\luci-static\resources\view\owrt_remote.js' }
|
||||
} else {
|
||||
@{ 'hub.py' = 'vps\owrt-remote-hub.py' }
|
||||
}
|
||||
foreach ($Name in $Files.Keys) {
|
||||
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Files[$Name])).Replace("`r`n", "`n")
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Name), $Content, $Utf8)
|
||||
}
|
||||
}
|
||||
|
||||
if ($PrepareOnly) {
|
||||
Write-Host "Prepared only: $StageRoot"
|
||||
return
|
||||
}
|
||||
|
||||
& scp -O -r -- $StageRoot "${TargetMachine}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=10 $TargetMachine "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "Version v122 $Action finished successfully. Refresh the panel."
|
||||
}
|
||||
finally {
|
||||
if (-not $PrepareOnly) {
|
||||
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
|
||||
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
|
||||
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) {
|
||||
throw 'Unsafe staging cleanup path.'
|
||||
}
|
||||
if (Test-Path -LiteralPath $Resolved) {
|
||||
Remove-Item -LiteralPath $Resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
grep -F -q 'v121' "$stage/hub.py"
|
||||
grep -F -q 'v122' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_VPS_WIDGETS_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
|
||||
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
|
||||
|
||||
@@ -81,7 +81,7 @@ test -s "$config"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent wan.sh cgi hotplug; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
test -s "$stage/luci"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
grep -F -q 'wan_interface_picker' "$stage/cgi"
|
||||
grep -F -q 'wan_select_interface()' "$stage/wan.sh"
|
||||
grep -F -q 'wan_reconcile_xray()' "$stage/agent"
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
param(
|
||||
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-xray-download-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
$Payloads = @{
|
||||
'agent' = 'files\usr\sbin\owrt-remote'
|
||||
}
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-download-v121
|
||||
key_file=/etc/owrt-remote/web.key
|
||||
key_candidate=$key_file.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
phase=preflight
|
||||
item_path() {
|
||||
case "$1" in
|
||||
agent) printf /usr/sbin/owrt-remote ;;
|
||||
esac
|
||||
}
|
||||
complete_backup() {
|
||||
[ -f "$1/complete" ] && [ -s "$1/agent" ]
|
||||
}
|
||||
restore_files() {
|
||||
local dir item path
|
||||
dir=$1
|
||||
complete_backup "$dir" || return 1
|
||||
for item in agent; do
|
||||
path=$(item_path "$item")
|
||||
cp -p "$dir/$item" "$path.new-__UPLOAD_NAME__" || return 1
|
||||
mv -f "$path.new-__UPLOAD_NAME__" "$path" || return 1
|
||||
done
|
||||
}
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
|
||||
if [ "$changed" = 1 ]; then
|
||||
echo 'Restoring the previous agent from this attempt.' >&2
|
||||
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
|
||||
fi
|
||||
fi
|
||||
for item in agent; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
|
||||
rm -f "$key_candidate"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
for item in agent; do
|
||||
path=$(item_path "$item")
|
||||
test -s "$path"
|
||||
done
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
grep -F -q 'xray_validate_transport_binary()' "$stage/agent"
|
||||
grep -F -q 'remote_download()' "$stage/agent"
|
||||
grep -F -q 'xray_discover_releases()' "$stage/agent"
|
||||
grep -F -q 'apk extract --allow-untrusted --no-chown --destination' "$stage/agent"
|
||||
grep -F -q 'xray_package_extract_binary "$package" "$work/xray.new" "$asset"' "$stage/agent"
|
||||
if [ ! -e "$backup_dir" ]; then
|
||||
mkdir -p "$stage/retained-backup"
|
||||
chmod 700 "$stage/retained-backup"
|
||||
for item in agent; do path=$(item_path "$item"); cp -p "$path" "$stage/retained-backup/$item"; done
|
||||
touch "$stage/retained-backup/complete"
|
||||
mv "$stage/retained-backup" "$backup_dir"
|
||||
fi
|
||||
complete_backup "$backup_dir" || { echo "Incomplete backup: $backup_dir. Nothing changed." >&2; exit 1; }
|
||||
source_dir=$stage
|
||||
else
|
||||
complete_backup "$backup_dir" || { echo "No complete backup: $backup_dir. Nothing changed." >&2; exit 1; }
|
||||
for item in agent; do sh -n "$backup_dir/$item"; done
|
||||
source_dir=$backup_dir
|
||||
fi
|
||||
printf 'Backup: %s\n' "$backup_dir"
|
||||
mkdir -p "$stage/previous"
|
||||
for item in agent; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
|
||||
touch "$stage/previous/complete"
|
||||
phase=install
|
||||
changed=1
|
||||
for item in agent; do
|
||||
path=$(item_path "$item")
|
||||
cp "$source_dir/$item" "$path.new-__UPLOAD_NAME__"
|
||||
chmod 755 "$path.new-__UPLOAD_NAME__"
|
||||
mv -f "$path.new-__UPLOAD_NAME__" "$path"
|
||||
done
|
||||
phase=verify
|
||||
for item in agent; do
|
||||
path=$(item_path "$item")
|
||||
sh -n "$path"
|
||||
cmp "$source_dir/$item" "$path"
|
||||
done
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
phase=prepare-xray-download
|
||||
# Replaces a known incompatible core, or restores/downloads a validated
|
||||
# compatible one. Does not render JSON or restart an existing tunnel.
|
||||
/usr/sbin/owrt-remote prepare-xray
|
||||
# install.sh creates the web key after Xray preparation. Recover that last
|
||||
# step if the first installation was interrupted by the APK defect.
|
||||
if [ ! -s "$key_file" ]; then
|
||||
phase=finish-first-install
|
||||
mkdir -p "$(dirname "$key_file")"
|
||||
if command -v hexdump >/dev/null 2>&1; then
|
||||
(umask 077; dd if=/dev/urandom bs=16 count=1 2>/dev/null | hexdump -v -e '16/1 "%02x"' >"$key_candidate")
|
||||
else
|
||||
(umask 077; dd if=/dev/urandom bs=16 count=1 2>/dev/null | od -An -v -tx1 | tr -d ' \n' >"$key_candidate")
|
||||
fi
|
||||
[ "$(wc -c <"$key_candidate")" -eq 32 ] || { echo 'Web key generation failed.' >&2; exit 1; }
|
||||
chmod 600 "$key_candidate"
|
||||
mv -f "$key_candidate" "$key_file"
|
||||
echo 'Web key created for the interrupted first installation.'
|
||||
fi
|
||||
fi
|
||||
# Rollback restores agent code only; retain the validated compatible core,
|
||||
# its boot cache, and all router settings. Never remove a working executable.
|
||||
printf '\nXRAY_DOWNLOAD_ROUTER_%s_OK\n' '__ACTION__'
|
||||
|
||||
'@
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
|
||||
if ($Action -eq 'Install') {
|
||||
foreach ($Item in $Payloads.GetEnumerator()) {
|
||||
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
|
||||
}
|
||||
}
|
||||
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||
& scp -O -r -- $StageRoot "${Router}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
|
||||
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "Xray download fix $Action finished successfully."
|
||||
} finally {
|
||||
if (-not $PrepareOnly) {
|
||||
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
|
||||
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
|
||||
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
|
||||
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidatePattern('^[a-zA-Z0-9_-]{1,80}$')][string]$RouterId = 'node-10'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Probe = @'
|
||||
python3 - <<'PY'
|
||||
import hashlib,http.client,json,pathlib,re,sqlite3,subprocess
|
||||
router_id='__ROUTER_ID__'
|
||||
with sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro',uri=True) as conn:
|
||||
conn.row_factory=sqlite3.Row
|
||||
row=conn.execute('select * from routers where id=?',(router_id,)).fetchone()
|
||||
if row is None: raise SystemExit('Router not found')
|
||||
status=json.loads(row['status_json'] or '{}')
|
||||
print('ROUTER',row['id'])
|
||||
print('PORTS',json.dumps({k:row[k] for k in ('entry_port','ssh_entry_port','tachyon_entry_port')}))
|
||||
print('REPORTED_TACHYON',json.dumps(status.get('tachyon',{})))
|
||||
config_path=pathlib.Path('/etc/xray/owrt-remote.json')
|
||||
data=json.loads(config_path.read_text())
|
||||
for entry in data.get('inbounds',[]):
|
||||
if entry.get('tag') in ('entry-'+router_id,'tachyon-'+router_id):
|
||||
print('INBOUND',json.dumps(entry))
|
||||
for rule in data.get('routing',{}).get('rules',[]):
|
||||
if any(t in ('entry-'+router_id,'tachyon-'+router_id) for t in rule.get('inboundTag',[])):
|
||||
print('RULE',json.dumps(rule))
|
||||
for name in ('entry_port','tachyon_entry_port'):
|
||||
port=int(row[name] or 0)
|
||||
if not port: continue
|
||||
c=http.client.HTTPConnection('127.0.0.1',port,timeout=5)
|
||||
try:
|
||||
c.request('GET','/')
|
||||
r=c.getresponse(); body=r.read(32768).decode('utf-8','replace')
|
||||
title=re.search(r'<title[^>]*>(.*?)</title>',body,re.S|re.I)
|
||||
print('HTTP_PROBE',name,'status=',r.status,'location=',r.getheader('Location'),'title=',title.group(1)[:150] if title else None)
|
||||
except Exception as exc: print('HTTP_PROBE',name,type(exc).__name__,str(exc))
|
||||
finally:c.close()
|
||||
for command in (['/usr/local/bin/xray','version'],['systemctl','show','owrt-remote-xray','-p','ExecStart','-p','MainPID']):
|
||||
r=subprocess.run(command,capture_output=True,text=True)
|
||||
print(r.stdout[:1600])
|
||||
print('TACHYON_VPS_READ_ONLY_DONE')
|
||||
PY
|
||||
'@
|
||||
$Probe = $Probe.Replace('__ROUTER_ID__', $RouterId).Replace([string][char]13, [string]::Empty)
|
||||
$Encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Probe + [char]10))
|
||||
& ssh -T -o ConnectTimeout=10 $Vps "printf %s $Encoded | base64 -d | sh -s"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Read-only VPS diagnostics failed.' }
|
||||
@@ -0,0 +1,47 @@
|
||||
param([string]$Router = 'root@192.168.2.1')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Probe = @'
|
||||
set +e
|
||||
echo '=== PACKAGE METADATA ==='
|
||||
if command -v apk >/dev/null 2>&1; then
|
||||
for p in tachyon luci-app-tachyon; do apk info -e "$p"; apk info -v "$p"; done
|
||||
elif command -v opkg >/dev/null 2>&1; then
|
||||
opkg status tachyon luci-app-tachyon | sed -n '/^Package:/p;/^Version:/p;/^Status:/p'
|
||||
fi
|
||||
echo '=== SERVICE FILES ==='
|
||||
ls -l /etc/init.d/*tachyon* /www/cgi-bin/tachyon* 2>/dev/null
|
||||
echo '=== UHTTPD LISTENERS AND DOCUMENT ROOTS ==='
|
||||
uci -q show uhttpd | sed -n '/=uhttpd$/p;/\.listen_http=/p;/\.home=/p;/\.cgi_prefix=/p;/\.ubus_prefix=/p'
|
||||
echo '=== TACHYON HTTP SETTINGS (NO SECRETS) ==='
|
||||
uci -q show tachyon | sed -n '/\.web_port=/p;/\.http_port=/p;/\.ui_port=/p;/\.listen_port=/p'
|
||||
echo '=== PROCD SERVICE STATES ==='
|
||||
for s in tachyon tachyon-core tachyon-web tachyon-http uhttpd; do
|
||||
printf '%s: ' "$s"
|
||||
ubus call service list "{\"name\":\"$s\"}" 2>/dev/null | jsonfilter -e '@.*.instances.*.running'
|
||||
done
|
||||
echo '=== LOCAL HTTP RESPONSES ==='
|
||||
for u in http://127.0.0.1:1680/ http://192.168.2.1:1680/ http://127.0.0.1/cgi-bin/luci/admin/services/tachyon; do
|
||||
printf '%s ' "$u"
|
||||
curl -q -s --noproxy '*' --max-time 3 -o /dev/null -w 'HTTP=%{http_code}\n' "$u"
|
||||
done
|
||||
echo '=== PUBLIC READ-ONLY HEALTH ENDPOINTS ==='
|
||||
for p in tachyon-api tachyon-agent; do
|
||||
printf '%s: ' "$p"
|
||||
curl -q -fsS --noproxy '*' --max-time 3 "http://127.0.0.1/cgi-bin/$p/health" 2>/dev/null |
|
||||
jsonfilter -e '@.success' -e '@.status' -e '@.version' -e '@.tachyon_core'
|
||||
done
|
||||
echo 'TACHYON_READ_ONLY_DIAGNOSTICS_DONE'
|
||||
echo '=== REMOTE ROUTER ID AND TACHYON STATE ==='
|
||||
uci -q get owrtremote.main.router_id
|
||||
owrt-remote tachyon-status
|
||||
echo '=== INSTALLED XRAY TACHYON ROUTE (NO KEYS) ==='
|
||||
cfg="$(uci -q get owrtremote.main.xray_config)"
|
||||
[ -n "$cfg" ] || cfg=/etc/xray/owrt-remote-client.json
|
||||
printf 'config=%s\n' "$cfg"
|
||||
jsonfilter -i "$cfg" -e '@.outbounds[@.tag="router-tachyon"].settings' -e '@.routing.rules' 2>/dev/null
|
||||
echo '=== CANDIDATE TACHYON ROUTE (NO KEYS) ==='
|
||||
owrt-remote render-client --stdout 2>/dev/null | jsonfilter -e '@.outbounds[@.tag="router-tachyon"].settings' -e '@.routing.rules' 2>/dev/null
|
||||
echo 'TACHYON_ROUTE_READ_ONLY_DONE'
|
||||
'@
|
||||
$Probe.Replace([string][char]13, [string]::Empty) | & ssh -T -o ConnectTimeout=10 $Router 'sh -s'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SSH diagnostics failed. Router settings were not changed.' }
|
||||
+691
-46
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user