From 6cf3ae7c0f4958b644008a14f60943d488584a51 Mon Sep 17 00:00:00 2001
From: kzolotarev95
Date: Thu, 5 Nov 2026 23:40:08 +0400
Subject: [PATCH] Add heartbeat Xray remote control and v121
---
README.md | 7 +
docs/xray-control.md | 113 +++++++
files/etc/init.d/owrt-remote | 17 +-
files/usr/lib/owrt-remote/control.sh | 201 ++++++++++++
files/usr/sbin/owrt-remote | 20 ++
files/www/cgi-bin/owrt-remote | 4 +-
.../luci-static/resources/view/owrt_remote.js | 4 +-
install.sh | 1 +
tests/HEARTBEAT_TRANSPORT.md | 4 +-
tests/HOST_POLICY.md | 24 +-
tests/HUB_DESIGN.md | 4 +-
tests/HUB_UPDATE.md | 14 +-
tests/LOG_COLLECTOR.md | 4 +-
tests/PERSISTENT_LOGS.md | 2 +-
tests/RECAPTCHA_V3.md | 6 +-
tests/REQUEST_LOAD.md | 2 +-
tests/RESOURCE_AUDIT.md | 6 +-
tests/ROUTER_UPDATES.md | 4 +-
tests/VERSION.md | 16 +-
tests/VPS_WIDGETS.md | 8 +-
tests/WAN_DNS.md | 4 +-
tests/WAN_INTERFACE_PICKER.md | 4 +-
tests/WAN_RECOVERY.md | 4 +-
tests/WAN_STABILITY.md | 6 +-
tests/XRAY_APPLY.md | 12 +-
tests/XRAY_BOOT.md | 4 +-
tests/XRAY_COMPAT.md | 6 +-
tests/test_global_logs_deploy.py | 6 +-
tests/test_global_logs_vps_deploy.py | 4 +-
tests/test_heartbeat_transport_deploy.py | 2 +-
tests/test_hub_design_deploy.py | 4 +-
tests/test_hub_design_ui.cjs | 2 +-
tests/test_hub_update.py | 2 +-
tests/test_hub_update_ui.cjs | 2 +-
tests/test_log_collector_deploy.py | 2 +-
tests/test_persistent_logs_deploy.py | 6 +-
tests/test_persistent_logs_vps_deploy.py | 4 +-
tests/test_request_load_deploy.py | 2 +-
tests/test_resource_lifecycle.py | 2 +-
tests/test_router_effects.py | 4 +-
tests/test_router_name_deploy.py | 4 +-
tests/test_router_updates_deploy.py | 4 +-
tests/test_update_status_ui_deploy.py | 10 +-
tests/test_wan_dns_deploy.py | 2 +-
tests/test_wan_recovery_deploy.py | 2 +-
tests/test_wan_stability_deploy.py | 2 +-
tests/test_xray_apk_deploy.py | 2 +-
tests/test_xray_boot_deploy.py | 2 +-
tests/test_xray_compat_deploy.py | 2 +-
tests/test_xray_control.py | 176 +++++++++++
tests/test_xray_control_agent.py | 170 ++++++++++
tests/test_xray_control_deploy.py | 115 +++++++
tests/test_xray_control_ui.cjs | 97 ++++++
tests/test_xray_mobile_deploy.py | 2 +-
tests/test_xray_reverse_deploy.py | 4 +-
tests/test_xray_validation_deploy.py | 2 +-
vps/deploy-dashboard-layout-fix.ps1 | 4 +-
vps/deploy-dashboard-menu-fix.ps1 | 4 +-
vps/deploy-global-logs-vps.ps1 | 4 +-
vps/deploy-global-logs.ps1 | 4 +-
vps/deploy-group-colors-fix.ps1 | 8 +-
vps/deploy-heartbeat-redirect.ps1 | 2 +-
vps/deploy-heartbeat-transport-fix.ps1 | 2 +-
vps/deploy-host-policy.ps1 | 18 +-
vps/deploy-hub-design.ps1 | 4 +-
vps/deploy-hub-self-update.ps1 | 4 +-
vps/deploy-hub-url-fix.ps1 | 12 +-
vps/deploy-log-collector-fix.ps1 | 2 +-
vps/deploy-online-status-fix.ps1 | 4 +-
vps/deploy-password-logout-fix.ps1 | 4 +-
vps/deploy-persistent-logs-vps.ps1 | 4 +-
vps/deploy-persistent-logs.ps1 | 4 +-
vps/deploy-recaptcha-v3.ps1 | 12 +-
vps/deploy-request-load-fix.ps1 | 4 +-
vps/deploy-resource-fix.ps1 | 8 +-
vps/deploy-router-card-ui-fix.ps1 | 4 +-
vps/deploy-router-effects.ps1 | 4 +-
vps/deploy-router-name-fix.ps1 | 4 +-
vps/deploy-router-updates.ps1 | 4 +-
vps/deploy-update-status-ui.ps1 | 4 +-
...rsion-v120.ps1 => deploy-version-v121.ps1} | 22 +-
vps/deploy-vps-resources-fix.ps1 | 4 +-
vps/deploy-vps-widgets.ps1 | 6 +-
vps/deploy-wan-dns-fix.ps1 | 2 +-
vps/deploy-wan-multi.ps1 | 4 +-
vps/deploy-wan-recovery-fix.ps1 | 2 +-
vps/deploy-wan-stability-fix.ps1 | 2 +-
vps/deploy-web-push-fix.ps1 | 4 +-
vps/deploy-xray-apk-fix.ps1 | 2 +-
vps/deploy-xray-apply-fix.ps1 | 2 +-
vps/deploy-xray-boot-fix.ps1 | 2 +-
vps/deploy-xray-compat-fix.ps1 | 2 +-
vps/deploy-xray-control-ui.ps1 | 8 +
vps/deploy-xray-control.ps1 | 218 +++++++++++++
vps/deploy-xray-mobile-fix.ps1 | 2 +-
vps/deploy-xray-reverse-fix.ps1 | 2 +-
vps/deploy-xray-reverse-vps.ps1 | 2 +-
vps/deploy-xray-source-fix.ps1 | 2 +-
vps/deploy-xray-validation-fix.ps1 | 2 +-
vps/owrt-remote-hub.py | 292 +++++++++++++++++-
100 files changed, 1631 insertions(+), 218 deletions(-)
create mode 100644 docs/xray-control.md
create mode 100644 files/usr/lib/owrt-remote/control.sh
create mode 100644 tests/test_xray_control.py
create mode 100644 tests/test_xray_control_agent.py
create mode 100644 tests/test_xray_control_deploy.py
create mode 100644 tests/test_xray_control_ui.cjs
rename vps/{deploy-version-v120.ps1 => deploy-version-v121.ps1} (93%)
create mode 100644 vps/deploy-xray-control-ui.ps1
create mode 100644 vps/deploy-xray-control.ps1
diff --git a/README.md b/README.md
index c41fa3f..a2c0226 100644
--- a/README.md
+++ b/README.md
@@ -38,6 +38,13 @@
Роутер сам подключается к VPS изнутри сети, а ты заходишь в Hub-панель и открываешь нужный роутер, LuCI или SSH Web Terminal.
+
+Remote управление Xray: запуск, остановка и перезапуск Xray выбранного роутера
+через Heartbeat, с проверкой результата и журналом действий. Работает при остановленном
+Xray и недоступном SSH-туннеле, если агент продолжает связываться с Hub.
+Нужны обновлённые Hub и агент. Описание и проверка.
+
+
diff --git a/docs/xray-control.md b/docs/xray-control.md
new file mode 100644
index 0000000..2950d14
--- /dev/null
+++ b/docs/xray-control.md
@@ -0,0 +1,113 @@
+# Remote управление Xray через Heartbeat
+
+В карточке роутера на VPS кнопка **Remote управление Xray** открывает отдельную
+вкладку. Доступны запуск, остановка, перезапуск, последний подтверждённый статус
+Xray и журнал результатов. Доступ определяется правом управления выбранным
+роутером (`G`). Дизайн и эффекты наследуются от панели Hub.
+
+Нужны обновлённые Hub и агент на каждом управляемом роутере. Старая версия агента
+отображается в этой вкладке с просьбой обновить её. Команды выполняются агентом
+на роутере; пароль SSH и обратный Xray-туннель для доставки не нужны.
+
+## Доставка и проверка результата
+
+- Hub сохраняет команду в SQLite и возвращает её в ответе на следующий
+ аутентифицированный Heartbeat **этого** роутера. Интервал Heartbeat сохраняется.
+- Разрешены только `start`, `stop`, `restart`. Произвольный shell-код не принимается.
+- Агент сохраняет идентификатор до исполнения и запускает ограниченный по времени
+ обработчик procd. Повторная доставка того же идентификатора не повторяет команду.
+- Остановка удаляет только instance `xray`. Instance `heartbeat` остаётся активным.
+ Флаг `/etc/owrt-remote/control/stopped` сохраняет намеренную остановку после
+ восстановления WAN и перезагрузки. Кнопка запуска снимает этот флаг.
+- Перед запуском/перезапуском проверяется конфигурация. Ошибка проверки сохраняет
+ действующий туннель. Успех старта подтверждается наличием процесса Xray, успех
+ остановки — его отсутствием. Это подтверждение процесса, а не проверка всей
+ цепочки доступа к LuCI/SSH.
+- Итог приходит следующим Heartbeat. Получение команды не считается успехом.
+ Если за три минуты нет доставки или результата, отображается соответствующий
+ тайм-аут. Поздно доставленный итог принятой команды может подтвердить результат.
+- После аварийного завершения обработчика/перезагрузки неопределённая команда
+ не повторяется автоматически; агент сообщает о прерывании.
+- История ограничена 100 командами на роутер, на странице видны последние 30.
+ Действия также попадают в «Глобал логи». На роутере хранится только последний
+ результат; вывод команды и блокировки находятся в `/tmp`, вывод ограничен.
+
+## Журнал и время ожидания
+
+Кнопка «Очистить логи» удаляет из этой вкладки завершённые записи и их вывод.
+Последний результат сверху тоже очищается. Действующая команда остаётся видимой
+и продолжает работу; глобальные логи и история других роутеров сохраняются.
+Идентификаторы очищенных команд остаются в ограниченной таблице для защиты
+от повторного выполнения. Повторные Heartbeat не возвращают очищенный вывод.
+
+При запуске, остановке и перезапуске таймер обновляется каждую секунду без
+дополнительных запросов к роутеру. Он показывает прошедшее время, приблизительное
+ожидание ближайшего Heartbeat и результата, а также остаток общего лимита
+в три минуты. Оценка учитывает сообщённый интервал Heartbeat и лимит обработчика
+45 секунд. Это ориентир: при задержке сети результат может прийти позднее.
+После завершения видна длительность ожидания и выполнения. Перезагрузка вкладки
+не сбрасывает таймер; отсчёт привязан ко времени Hub, а не часам телефона.
+
+Для установки только этой правки на VPS:
+
+```powershell
+$Fix = "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-control-ui.ps1"
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@179.43.187.107" -Action Install
+```
+
+Откат к панели, которая была перед этой правкой:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@179.43.187.107" -Action Rollback
+```
+
+Её отдельная резервная копия:
+`/root/owrt-remote-backup-before-xray-control-ui-v121`. База данных при откате
+файла не восстанавливается; очищенные результаты остаются очищенными.
+
+Если полностью выключен сервис Remote, потерян интернет или Heartbeat не доходит
+до Hub, канал доставки отсутствует. Остановка одного Xray этот канал не выключает.
+Для обновления старого агента при уже неработающем туннеле нужен другой доступ к
+роутеру; новая функция появляется после установки обновлённого агента.
+
+## Установка локальной сборки из PowerShell Windows 11
+
+Сначала VPS, затем каждый нужный роутер:
+
+```powershell
+$Fix = "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-control.ps1"
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@179.43.187.107" -Action Install
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router "root@192.168.2.1" -Action Install
+```
+
+Откат файлов из резервной копии:
+
+```powershell
+$Fix = "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-control.ps1"
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Router "root@192.168.2.1" -Action Rollback
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File $Fix -Vps "root@179.43.187.107" -Action Rollback
+```
+
+Копии находятся в `/root/owrt-remote-backup-before-xray-control-v121` отдельно
+на каждом устройстве. Ошибка установки восстанавливает файлы, которые были до
+текущей попытки. База Hub, ключи и настройки роутера при откате файлов сохраняются.
+
+## Проверка на устройствах
+
+1. Обновить вкладку Hub, открыть управление у выбранного роутера. Дождаться
+ Heartbeat с подтверждением поддержки функции.
+2. Остановить Xray и дождаться итога «Успешно». Проверить, что агент остаётся
+ онлайн и время последнего Heartbeat обновляется.
+3. При недоступных LuCI/SSH нажать «Запустить Xray» в открытой вкладке Hub.
+ Дождаться подтверждения запуска, затем проверить LuCI/SSH.
+4. Проверить перезапуск, журнал действий и «Глобал логи». Убедиться, что соседние
+ роутеры продолжают работать.
+
+Локальные проверки:
+
+```powershell
+python -m unittest discover -s tests -p "test_xray_control*.py" -v
+```
+
+Shell-тесты моделируют procd/Xray и выполняют настоящий обработчик в BusyBox ash,
+если тестовый BusyBox доступен. Они не заменяют проверку на физическом OpenWrt.
diff --git a/files/etc/init.d/owrt-remote b/files/etc/init.d/owrt-remote
index c584430..73f08a3 100644
--- a/files/etc/init.d/owrt-remote
+++ b/files/etc/init.d/owrt-remote
@@ -64,13 +64,16 @@ start_service() {
return 0
fi
- procd_open_instance xray
- procd_set_param command /usr/sbin/owrt-remote run
- procd_set_param env OWRT_REMOTE_SERVICE_LOG=1
- procd_set_param respawn 3600 5 5
- procd_set_param stdout 1
- procd_set_param stderr 1
- procd_close_instance
+ # A remote Xray stop must survive service reloads without stopping Heartbeat.
+ if [ ! -e /etc/owrt-remote/control/stopped ]; then
+ procd_open_instance xray
+ procd_set_param command /usr/sbin/owrt-remote run
+ procd_set_param env OWRT_REMOTE_SERVICE_LOG=1
+ procd_set_param respawn 3600 5 5
+ procd_set_param stdout 1
+ procd_set_param stderr 1
+ procd_close_instance
+ fi
procd_open_instance heartbeat
procd_set_param command /usr/sbin/owrt-remote heartbeat-loop
diff --git a/files/usr/lib/owrt-remote/control.sh b/files/usr/lib/owrt-remote/control.sh
new file mode 100644
index 0000000..00d824e
--- /dev/null
+++ b/files/usr/lib/owrt-remote/control.sh
@@ -0,0 +1,201 @@
+#!/bin/sh
+# Fixed Xray operations delivered by authenticated Heartbeat. Never eval Hub input.
+CONTROL_STATE="${OWRT_REMOTE_CONTROL_STATE:-/etc/owrt-remote/control}"
+CONTROL_RUNTIME="${OWRT_REMOTE_CONTROL_RUNTIME:-/tmp/owrt-remote-control}"
+
+xray_control_stopped() { [ -e "$CONTROL_STATE/stopped" ]; }
+
+xray_control_lock() {
+ local path owner self rest
+ path="$1"
+ mkdir -p "$CONTROL_RUNTIME" || return 1
+ if ! mkdir "$path" 2>/dev/null; then
+ owner="$(cat "$path/pid" 2>/dev/null)"
+ case "$owner" in
+ ''|*[!0-9]*)
+ sleep 1
+ owner="$(cat "$path/pid" 2>/dev/null)"
+ ;;
+ esac
+ case "$owner" in ''|*[!0-9]*) ;; *) kill -0 "$owner" 2>/dev/null && return 1 ;; esac
+ # Only reap a dead, fully initialized owner; never another process's new lock.
+ mkdir "$path/reap" 2>/dev/null || return 1
+ [ "$(cat "$path/pid" 2>/dev/null)" = "$owner" ] || { rmdir "$path/reap"; return 1; }
+ rm -f "$path/pid"
+ rmdir "$path/reap" "$path" 2>/dev/null || return 1
+ mkdir "$path" 2>/dev/null || return 1
+ fi
+ self=$$
+ [ ! -r /proc/self/stat ] || read -r self rest "$path/pid"
+}
+
+xray_control_save() (
+ umask 077
+ mkdir -p "$CONTROL_STATE" || return 1
+ state_xray=stopped; xray_running && state_xray=running
+ temp="$(mktemp "$CONTROL_STATE/.result.XXXXXX")" || return 1
+ trap 'rm -f "$temp"' EXIT
+ trap 'exit 1' INT TERM
+ printf '{"id":%s,"action":%s,"status":%s,"rc":%s,"xray":%s,"message":%s,"boot":%s,"accepted":%s}\n' \
+ "$(json_string "$1")" "$(json_string "$2")" "$(json_string "$3")" "$4" \
+ "$(json_string "$state_xray")" "$(json_string "$5")" \
+ "$(json_string "$(cat /proc/sys/kernel/random/boot_id 2>/dev/null)")" "$(safe_num "$(uptime_seconds)" 0)" >"$temp" &&
+ mv -f "$temp" "$CONTROL_STATE/result.json"
+ rc=$?; rm -f "$temp"; return "$rc"
+)
+
+xray_control_result_json() {
+ local state id action service boot accepted now
+ if [ -s "$CONTROL_STATE/result.json" ]; then
+ state="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.status' 2>/dev/null)"
+ case "$state" in running|succeeded|failed|interrupted) ;; *) printf null; return 0 ;; esac
+ if [ "$state" = running ]; then
+ boot="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.boot')"
+ accepted="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.accepted')"
+ now="$(safe_num "$(uptime_seconds)" 0)"
+ accepted="$(safe_num "$accepted" 0)"
+ service="$(ubus call service list '{"name":"owrt-remote"}' 2>/dev/null)" || service=''
+ if [ "$boot" != "$(cat /proc/sys/kernel/random/boot_id 2>/dev/null)" ] || {
+ [ $((now-accepted)) -ge 15 ] && [ -n "$service" ] &&
+ [ "$(printf '%s' "$service" | jsonfilter -e '@["owrt-remote"].instances.control.running' 2>/dev/null)" != true ];
+ }; then
+ id="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.id')"
+ action="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.action')"
+ # A worker may have written its final result between the first read and procd query.
+ if [ "$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.status')" = running ]; then
+ xray_control_save "$id" "$action" interrupted 1 'Обработчик прерван или роутер перезагрузился; повтор команды автоматически не выполняется.' || return 1
+ fi
+ fi
+ fi
+ head -c 4096 "$CONTROL_STATE/result.json"
+ else
+ printf null
+ fi
+}
+
+xray_control_dispatch() (
+ id="$(jsonfilter -i "$1" -e '@.xray_command.id' 2>/dev/null)"
+ [ -n "$id" ] || return 0
+ [ "${#id}" = 32 ] || return 1
+ case "$id" in *[!a-f0-9]*) return 1 ;; esac
+ action="$(jsonfilter -i "$1" -e '@.xray_command.action' 2>/dev/null)"
+ case "$action" in start|stop|restart) ;; *) return 1 ;; esac
+ xray_control_lock "$CONTROL_RUNTIME/dispatch-lock" || return 0
+ trap 'rm -f "$CONTROL_RUNTIME/dispatch-lock/pid"; rmdir "$CONTROL_RUNTIME/dispatch-lock" 2>/dev/null || true' EXIT
+ trap 'exit 1' INT TERM
+ previous="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.id' 2>/dev/null)"
+ [ "$previous" != "$id" ] || return 0
+ state="$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.status' 2>/dev/null)"
+ [ "$state" != running ] || return 0
+ # Persist the claim before executing. Duplicate deliveries/reboots cannot replay a restart.
+ xray_control_save "$id" "$action" running 0 'Команда принята агентом роутера.' || {
+ log 'ОШИБКА: Remote Xray: невозможно сохранить состояние команды; выполнение отменено'
+ return 1
+ }
+ request="{\"name\":\"owrt-remote\",\"instances\":{\"control\":{\"command\":[\"/usr/sbin/owrt-remote\",\"xray-control-worker\",\"$id\",\"$action\"],\"stdout\":true,\"stderr\":true}}}"
+ if ! ubus call service add "$request" >/dev/null 2>&1; then
+ xray_control_save "$id" "$action" failed 1 'procd не принял обработчик команды; Xray не изменён.'
+ return 1
+ fi
+ log "Remote Xray: команда=$id действие=$action принята через Heartbeat"
+)
+
+xray_control_execute() {
+ local action binary state attempt
+ action="$1"
+ case "$action" in start|stop|restart) ;; *) return 2 ;; esac
+ if [ "$action" != stop ]; then
+ truthy "$(uci_get enabled 0)" || { printf 'Remote выключен в настройках роутера; сначала включи агент.\n'; return 1; }
+ binary="$(xray_bin_path)"
+ [ -x "$binary" ] || { printf 'Бинарник Xray отсутствует; установи Xray на роутере.\n'; return 1; }
+ render_client_config >/dev/null || return $?
+ fi
+ if [ "$action" != start ]; then
+ # Suppress WAN auto-recovery before removing only the Xray instance.
+ : >"$CONTROL_STATE/stopped" || return 1
+ state="$(ubus call service list '{"name":"owrt-remote"}' 2>/dev/null)" || return 1
+ if printf '%s' "$state" | jsonfilter -e '@["owrt-remote"].instances.xray' 2>/dev/null | grep -q .; then
+ ubus call service delete '{"name":"owrt-remote","instance":"xray"}' >/dev/null || return 1
+ fi
+ stop_xray || return $?
+ if xray_running; then printf 'Xray не остановился.\n'; return 1; fi
+ if [ "$action" = stop ]; then printf 'Xray остановлен. Агент и Heartbeat продолжают работать.\n'; return 0; fi
+ fi
+ rm -f "$CONTROL_STATE/stopped" || return 1
+ if [ "$action" = start ] && xray_running; then printf 'Xray уже запущен.\n'; return 0; fi
+ ubus call service add '{"name":"owrt-remote","instances":{"xray":{"command":["/usr/sbin/owrt-remote","run"],"env":{"OWRT_REMOTE_SERVICE_LOG":"1"},"respawn":["3600","5","5"],"stdout":true,"stderr":true}}}' >/dev/null || return 1
+ attempt=0
+ while [ "$attempt" -lt 20 ]; do
+ sleep 1
+ if xray_running; then
+ sleep 2
+ if xray_running; then printf 'Xray запущен; процесс проверен. Heartbeat работает независимо.\n'; return 0; fi
+ fi
+ attempt=$((attempt+1))
+ done
+ printf 'Процесс Xray не появился за 20 секунд. Проверь WAN и Глобал логи; регистрация procd не считается успешным запуском.\n'
+ return 1
+}
+
+xray_control_shell_timeout() (
+ control_child=''
+ trap 'result=$?; [ -z "$control_child" ] || { kill -TERM "$control_child" 2>/dev/null || true; kill -KILL "$control_child" 2>/dev/null || true; wait "$control_child" 2>/dev/null || true; }; exit "$result"' EXIT
+ trap 'exit 1' INT TERM
+ "$@" & control_child=$!
+ ticks=0
+ while kill -0 "$control_child" 2>/dev/null; do
+ if [ "$ticks" -ge 45 ]; then
+ kill -TERM "$control_child" 2>/dev/null || true
+ sleep 1
+ kill -KILL "$control_child" 2>/dev/null || true
+ wait "$control_child" 2>/dev/null || true
+ control_child=''
+ return 124
+ fi
+ sleep 1
+ ticks=$((ticks+1))
+ done
+ rc=0
+ wait "$control_child" || rc=$?
+ control_child=''
+ return "$rc"
+)
+
+run_xray_control_limited() {
+ if command -v timeout >/dev/null 2>&1; then
+ timeout 45 "$@"
+ elif command -v busybox >/dev/null 2>&1 && busybox timeout 45 true >/dev/null 2>&1; then
+ busybox timeout 45 "$@"
+ else
+ xray_control_shell_timeout "$@"
+ fi
+}
+
+xray_control_worker() (
+ umask 077
+ id="$1"; action="$2"
+ [ "${#id}" = 32 ] || return 2
+ case "$id" in *[!a-f0-9]*) return 2 ;; esac
+ case "$action" in start|stop|restart) ;; *) return 2 ;; esac
+ [ "$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.id')" = "$id" ] || return 1
+ [ "$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.action')" = "$action" ] || return 1
+ mkdir -p "$CONTROL_RUNTIME" || return 1
+ # procd starts a single named instance; mkdir also serializes manual worker calls.
+ xray_control_lock "$CONTROL_RUNTIME/worker-lock" || return 1
+ trap 'rm -f "$CONTROL_RUNTIME/output" "$CONTROL_RUNTIME/worker-lock/pid"; rmdir "$CONTROL_RUNTIME/worker-lock" 2>/dev/null || true' EXIT
+ [ "$(jsonfilter -i "$CONTROL_STATE/result.json" -e '@.status')" = running ] || return 0
+ trap 'xray_control_save "$id" "$action" interrupted 1 "Обработчик команды был остановлен."; exit 1' INT TERM
+ rc=0
+ (ulimit -f 8; run_xray_control_limited /usr/sbin/owrt-remote xray-control-execute "$action") >"$CONTROL_RUNTIME/output" 2>&1 || rc=$?
+ message="$(tail -c 1200 "$CONTROL_RUNTIME/output" | sed -E '/[Aa]uthorization|hub_token|vless_uuid|[Pp]assword|[Pp]asswd|[?&](key|token)=/c\[секрет скрыт]')"
+ status=failed
+ if [ "$rc" = 0 ]; then
+ if [ "$action" = stop ]; then xray_running && rc=1; else xray_running || rc=1; fi
+ [ "$rc" != 0 ] || status=succeeded
+ fi
+ [ "$rc" != 124 ] || message='Истекло 45 секунд выполнения команды; проверь WAN и журнал Xray.'
+ [ -n "$message" ] || message="Команда завершилась с rc=$rc; проверь Глобал логи."
+ xray_control_save "$id" "$action" "$status" "$rc" "$message" || return 1
+ log "Remote Xray: команда=$id действие=$action результат=$status rc=$rc"
+)
diff --git a/files/usr/sbin/owrt-remote b/files/usr/sbin/owrt-remote
index c7c39f6..d60ca2f 100644
--- a/files/usr/sbin/owrt-remote
+++ b/files/usr/sbin/owrt-remote
@@ -141,6 +141,14 @@ WAN_HELPER="${OWRT_REMOTE_WAN_HELPER:-/usr/lib/owrt-remote/wan.sh}"
if [ -r "$WAN_HELPER" ]; then
. "$WAN_HELPER"
fi
+CONTROL_HELPER="${OWRT_REMOTE_CONTROL_HELPER:-/usr/lib/owrt-remote/control.sh}"
+if [ -r "$CONTROL_HELPER" ]; then
+ . "$CONTROL_HELPER"
+else
+ xray_control_stopped() { return 1; }
+ xray_control_result_json() { printf null; }
+ xray_control_dispatch() { return 0; }
+fi
host_model() {
if [ -r /tmp/sysinfo/model ]; then
@@ -863,6 +871,8 @@ heartbeat_json() {
"flash": $(json_string "$(flash_text)"),
"temperature": $(json_string "$(temperature_text)"),
"xray": $(json_string "$xray_state"),
+ "xray_control": $([ -r "$CONTROL_HELPER" ] && printf 1 || printf 0),
+ "xray_control_result": $(xray_control_result_json || printf null),
"ssh": $(json_string "$ssh_state"),
"event": $(json_string "$event"),
"service": $(json_string "$service_state")
@@ -1290,6 +1300,7 @@ send_heartbeat() {
printf '%s\n' "endpoint=$safe_endpoint; attempt=$attempt/$max_attempts; rc=0; reason=ok; elapsed_ms=$elapsed; $(tail -n 1 "$metrics")" >"$dir/last"
mv -f "$dir/last" "${TMPDIR:-/tmp}/owrt-remote-heartbeat-last"
cat "$response"
+ xray_control_dispatch "$response" || log 'Remote Xray: команда не принята; повторная доставка при следующем Heartbeat'
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
@@ -1316,6 +1327,7 @@ send_heartbeat() {
wan_reconcile_xray() {
local config bound device
+ xray_control_stopped && return 0
truthy "$(uci_get enabled 0)" || return 0
device="$(wan_device)" || return 1
if ! xray_running; then
@@ -1331,6 +1343,7 @@ wan_reconcile_xray() {
wan_recover_xray() {
local lock owner rest state running heartbeat now last attempt
+ xray_control_stopped && return 0
(
umask 077
lock="${TMPDIR:-/tmp}/owrt-remote-xray-recovery"
@@ -2031,6 +2044,7 @@ wait_for_selected_wan() {
run_xray() {
local enabled xray_bin xray_config
+ xray_control_stopped && { log 'Xray: остановлен через Remote; Heartbeat продолжает работать'; return 0; }
enabled="$(uci_get enabled 0)"
truthy "$enabled" || die "service disabled: set option enabled '1'"
@@ -2085,6 +2099,12 @@ case "$cmd" in
stop-xray)
stop_xray
;;
+ xray-control-worker)
+ xray_control_worker "$@"
+ ;;
+ xray-control-execute)
+ xray_control_execute "$@"
+ ;;
render-client)
xray_apply_trace render-client
render_client_config "$@" || exit $?
diff --git a/files/www/cgi-bin/owrt-remote b/files/www/cgi-bin/owrt-remote
index f120e89..22ee3d6 100644
--- a/files/www/cgi-bin/owrt-remote
+++ b/files/www/cgi-bin/owrt-remote
@@ -515,7 +515,7 @@ render_page() {
-OpenWrt Remote Hub v120
+OpenWrt Remote Hub v121
'}, 'csrf')
+ script = re.search(r'', page, re.S)[1]
+ result = subprocess.run([node, '--check'], input=script, text=True, capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertNotIn('', page)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_xray_control_agent.py b/tests/test_xray_control_agent.py
new file mode 100644
index 0000000..b20ebd7
--- /dev/null
+++ b/tests/test_xray_control_agent.py
@@ -0,0 +1,170 @@
+"""Exercise the actual shell control helper with simulated procd and Xray."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+import test_host_policy as base
+
+ROOT = base.ROOT
+BUSYBOX = ROOT / '.test-output/busybox/busybox64.exe'
+SHELL = str(BUSYBOX) if BUSYBOX.exists() else base.SH
+
+MOCKS = r'''
+jsonfilter() {
+ if [ "$1" = -i ]; then source="$2"; expr="$4"; else source=-; expr="$2"; fi
+ "$TEST_PYTHON" "$TEST_ROOT/jsonfilter.py" "$source" "$expr"
+}
+xray_running() { [ -e "$TEST_ROOT/xray-running" ]; }
+xray_bin_path() { printf '%s/bin' "$TEST_ROOT"; }
+render_client_config() {
+ [ ! -f "$TEST_ROOT/invalid-config" ] || { printf 'Xray rejected configuration\n' >&2; return 23; }
+ printf '%s/config.json' "$TEST_ROOT"
+}
+stop_xray() { rm -f "$TEST_ROOT/xray-running"; }
+sleep() { :; }
+uptime_seconds() { printf '%s' "${NOW:-100}"; }
+timeout() { shift; shift; shift; xray_control_execute "$@"; }
+ubus() {
+ printf '%s\n' "$*" >>"$TEST_ROOT/ubus-calls"
+ case "$3" in
+ list) printf '{"owrt-remote":{"instances":{"heartbeat":{"running":true},"xray":{"running":true},"control":{"running":false}}}}' ;;
+ add)
+ case "$4" in *xray-control-worker*) : ;; *) touch "$TEST_ROOT/xray-running" ;; esac ;;
+ delete)
+ [ "$4" = '{"name":"owrt-remote","instance":"xray"}' ] || return 9
+ rm -f "$TEST_ROOT/xray-running" ;;
+ esac
+}
+'''
+
+
+@unittest.skipUnless(SHELL, 'POSIX shell required')
+class AgentTests(unittest.TestCase):
+ setUp = base.RouterShellTests.setUp
+ config = base.RouterShellTests.config
+
+ def prepare(self, action='stop'):
+ self.config(enabled='1', wan_direct='1')
+ self.env.update(OWRT_REMOTE_CONTROL_HELPER=(ROOT / 'files/usr/lib/owrt-remote/control.sh').as_posix(),
+ OWRT_REMOTE_CONTROL_STATE=(self.directory / 'state').as_posix(),
+ OWRT_REMOTE_CONTROL_RUNTIME=(self.directory / 'runtime').as_posix())
+ binary = self.directory / 'bin'
+ binary.write_text('#!/bin/sh\nexit 0\n')
+ binary.chmod(0o755)
+ self.directory.joinpath('response').write_text(json.dumps({'ok': True, 'xray_command': {'id': 'a'*32, 'action': action}}))
+ self.directory.joinpath('jsonfilter.py').write_text('''import json,re,sys
+try:
+ data=json.load(sys.stdin if sys.argv[1]=='-' else open(sys.argv[1]))
+ for key in re.findall(r'[a-zA-Z_][a-zA-Z_0-9-]*', sys.argv[2][1:]): data=data[key]
+ print(json.dumps(data) if isinstance(data,(dict,bool)) else data)
+except (KeyError,ValueError,TypeError,FileNotFoundError): pass
+''')
+
+ def shell(self, commands):
+ args = [SHELL, 'ash'] if 'busybox' in SHELL.lower() else [SHELL]
+ return subprocess.run(args, input=self.agent + '\n' + base.MOCKS + '\n' + MOCKS + '\n' + commands,
+ encoding='utf-8', capture_output=True, cwd=ROOT, env=self.env, timeout=40)
+
+ def test_stop_keeps_heartbeat_and_blocks_wan_auto_recovery(self):
+ self.prepare()
+ result = self.shell(r'''
+touch "$TEST_ROOT/xray-running"
+xray_control_dispatch "$TEST_ROOT/response" || exit
+xray_control_worker aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa stop || exit
+xray_control_stopped || exit 5
+wan_reconcile_xray || exit
+xray_control_result_json
+''')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ value = json.loads(result.stdout)
+ self.assertEqual(value['status'], 'succeeded')
+ self.assertEqual(value['xray'], 'stopped')
+ calls = self.directory.joinpath('ubus-calls').read_text()
+ self.assertIn('"instance":"xray"', calls)
+ self.assertNotIn('"instance":"heartbeat"', calls)
+ self.assertNotIn('wan-recovery', calls)
+
+ def test_start_when_tunnel_and_ssh_are_down(self):
+ self.prepare('start')
+ result = self.shell(r'''
+mkdir -p "$CONTROL_STATE"; touch "$CONTROL_STATE/stopped"
+xray_control_dispatch "$TEST_ROOT/response" || exit
+xray_control_worker aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa start || exit
+xray_control_result_json
+''')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)['xray'], 'running')
+ self.assertFalse(self.directory.joinpath('state/stopped').exists())
+
+ def test_replay_does_not_restart_again_and_bad_action_never_executes(self):
+ self.prepare('restart')
+ result = self.shell(r'''
+xray_control_dispatch "$TEST_ROOT/response" || exit
+xray_control_worker aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa restart || exit
+xray_control_dispatch "$TEST_ROOT/response" || exit
+xray_control_dispatch "$TEST_ROOT/response" || exit
+xray_control_result_json
+''')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ calls = self.directory.joinpath('ubus-calls').read_text()
+ self.assertEqual(calls.count('xray-control-worker'), 1)
+ self.directory.joinpath('response').write_text(json.dumps({'xray_command': {'id': 'b'*32, 'action': 'stop; touch injected'}}))
+ result = self.shell('xray_control_dispatch "$TEST_ROOT/response"')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('injected', self.directory.joinpath('ubus-calls').read_text())
+
+ def test_invalid_config_preserves_running_tunnel_and_reports_real_error(self):
+ self.prepare('restart')
+ result = self.shell(r'''
+touch "$TEST_ROOT/xray-running" "$TEST_ROOT/invalid-config"
+xray_control_dispatch "$TEST_ROOT/response" || exit
+xray_control_worker aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa restart || exit
+xray_control_result_json
+''')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ value = json.loads(result.stdout)
+ self.assertEqual(value['status'], 'failed')
+ self.assertEqual(value['rc'], 23)
+ self.assertIn('Xray rejected configuration', value['message'])
+ self.assertTrue(self.directory.joinpath('xray-running').exists())
+ self.assertFalse(self.directory.joinpath('state/stopped').exists())
+
+ def test_dead_worker_is_reported_without_replay_and_stale_lock_is_recovered(self):
+ self.prepare()
+ result = self.shell(r'''
+mkdir -p "$CONTROL_RUNTIME/dispatch-lock"
+printf '99999999\n' >"$CONTROL_RUNTIME/dispatch-lock/pid"
+xray_control_dispatch "$TEST_ROOT/response" || exit
+NOW=120
+xray_control_result_json
+xray_control_dispatch "$TEST_ROOT/response" || exit
+''')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(json.loads(result.stdout)['status'], 'interrupted')
+ self.assertEqual(self.directory.joinpath('ubus-calls').read_text().count('xray-control-worker'), 1)
+
+ def test_shell_timeout_without_optional_applet_returns_result_and_reaps_child(self):
+ helper = (ROOT / 'files/usr/lib/owrt-remote/control.sh').read_text(encoding='utf-8')
+ # Shorten the watchdog ticks, without substituting the control flow.
+ helper = helper.replace('[ "$ticks" -ge 45 ]', '[ "$ticks" -ge 2 ]')
+ prefix = r'''
+command() { return 1; }
+sleep() { "$TEST_PYTHON" -c 'import time; time.sleep(0.05)'; }
+'''
+ args = [SHELL, 'ash'] if 'busybox' in SHELL.lower() else [SHELL]
+ commands = '''
+failcmd() { return 7; }
+run_xray_control_limited failcmd
+printf 'FAIL_RC=%s\\n' "$?"
+'''
+ result = subprocess.run(args, input=helper + prefix + '\n' + commands,
+ encoding='utf-8', capture_output=True, env={**self.env, 'TEST_PYTHON': os.environ.get('PYTHON', 'python')}, timeout=10)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('FAIL_RC=7', result.stdout)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_xray_control_deploy.py b/tests/test_xray_control_deploy.py
new file mode 100644
index 0000000..d449989
--- /dev/null
+++ b/tests/test_xray_control_deploy.py
@@ -0,0 +1,115 @@
+"""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 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='xray-control-deploy-')
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.env = dict(os.environ)
+ 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', 'control.sh', 'init')}
+ for name in ('agent', 'init'):
+ 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-xray-control.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', 'control.sh': '/usr/lib/owrt-remote/control.sh', 'init': '/etc/init.d/owrt-remote'}[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')
+ mocks = '''
+ubus() { printf '{}'; }
+jsonfilter() { printf true; }
+timeout() { return 0; }
+busybox() { return 127; }
+test_restart() { [ "${FAIL_RESTART:-0}" != 1 ]; }
+sleep() { :; }
+'''
+ self.script = mocks + self.script
+
+ def deploy(self, action='Install', bad=False, fail=False, no_timeout=False):
+ stage = self.root / 'stage'
+ stage.mkdir()
+ for name, source in {'agent': 'files/usr/sbin/owrt-remote', 'control.sh': 'files/usr/lib/owrt-remote/control.sh', 'init': 'files/etc/init.d/owrt-remote'}.items():
+ text = 'if true; then\n' if bad and name == 'control.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)
+ 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('XRAY_CONTROL_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('XRAY_CONTROL_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('control.sh shell syntax check failed', result.stderr)
+ self.assertIn('Failed during preflight', result.stderr)
+ self.assertNotIn('restoring files', result.stderr)
+ self.assert_original()
+
+ @unittest.skipUnless(os.name == 'nt', 'PowerShell required')
+ def test_powershell_stages_utf8_and_valid_shell(self):
+ self.assertTrue((ROOT / 'vps/deploy-xray-control.ps1').read_bytes().isascii())
+ result = subprocess.run(['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
+ str(ROOT / 'vps/deploy-xray-control.ps1'), '-Router', 'unused', '-PrepareOnly'],
+ capture_output=True, encoding='utf-8', timeout=30,
+ env={**os.environ, 'TEMP': str(self.root), 'TMP': str(self.root)})
+ self.assertEqual(result.returncode, 0, result.stderr)
+ folder = next(self.root.glob('owrt-xray-control-*'))
+ self.assertEqual(folder.joinpath('control.sh').read_bytes(), (ROOT / 'files/usr/lib/owrt-remote/control.sh').read_text(encoding='utf-8').encode())
+ check = subprocess.run([SH, '-n', str(folder / 'run.sh')], capture_output=True, text=True)
+ self.assertEqual(check.returncode, 0, check.stderr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_xray_control_ui.cjs b/tests/test_xray_control_ui.cjs
new file mode 100644
index 0000000..63ce692
--- /dev/null
+++ b/tests/test_xray_control_ui.cjs
@@ -0,0 +1,97 @@
+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/xray-control');
+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='xray-control-preview-') as state:
+ os.environ['OWRT_REMOTE_STATE_DIR'] = state
+ spec = importlib.util.spec_from_file_location('preview_hub', 'vps/owrt-remote-hub.py')
+ hub = importlib.util.module_from_spec(spec); sys.modules[spec.name] = hub; spec.loader.exec_module(hub)
+ page = hub.router_xray_control_html({'id':'main','name':'Роутер тест'}, 'csrf-test')
+ Path('.test-output/xray-control/page.html').write_text(page, encoding='utf-8')
+`], {env:{...process.env,PYTHONIOENCODING:'utf-8'}});
+const html = fs.readFileSync(path.join(output, 'page.html'), 'utf8');
+const BASE = 1793890000;
+const url = 'http://127.0.0.1:9999/router/main/xray-control';
+(async()=>{
+ const browser = await chromium.launch({headless:true,channel:'chrome'});
+ try {
+ for (const [width,height] of [[1280,900],[320,740],[390,844],[844,390]]) {
+ const page = await browser.newPage({viewport:{width,height}});
+ await page.clock.install({time:new Date(BASE*1000)});
+ const fixture = {now:BASE,history:[],reads:0,posts:[],inflight:0,maxInflight:0};
+ const errors=[];page.on('pageerror',error=>errors.push(error.message));
+ await page.route('**/*', async route=>{
+ const req=route.request();
+ if(new URL(req.url()).pathname.startsWith('/api/')) {
+ fixture.inflight++;fixture.maxInflight=Math.max(fixture.maxInflight,fixture.inflight);
+ try {
+ if(req.method()==='POST') {
+ assert.equal(req.headers()['x-xray-control-csrf'],'csrf-test');
+ const body=req.postDataJSON();fixture.posts.push(body);
+ if(body.action==='clear_history')fixture.history=fixture.history.filter(item=>['queued','delivered','running'].includes(item.status));
+ else fixture.history.unshift({id:body.request_id,action:body.action,status:'queued',result:'',created_at:fixture.now,delivered_at:0,completed_at:0});
+ } else fixture.reads++;
+ await route.fulfill({json:{ok:true,name:'Роутер тест',online:true,xray:'running',supported:true,
+ last_seen:fixture.now,server_time:fixture.now,heartbeat_interval:30,
+ command_timeout_seconds:180,execution_timeout_seconds:45,history:fixture.history}});
+ } finally {fixture.inflight--;}
+ } else await route.fulfill({contentType:'text/html',body:html});
+ });
+ await page.goto(url);
+ await page.waitForFunction(()=>document.getElementById('resultTitle').textContent==='Журнал действий пуст.');
+ assert(await page.locator('#clearHistory').isDisabled());
+ for(const action of ['start','stop','restart']) {
+ await page.locator(`[data-action="${action}"]`).click();
+ await page.waitForFunction(()=>document.getElementById('resultTitle').textContent.startsWith('Ожидает Heartbeat'));
+ const before=fixture.reads;
+ await page.clock.runFor(1100);
+ assert((await page.locator('#operationTimer').textContent()).includes('Прошло: 00:01'));
+ assert((await page.locator('#operationTimer').textContent()).includes('Ориентир до итогового ответа: ~'));
+ assert.equal(fixture.reads,before,'seconds timer must not add network requests');
+ assert.equal(await page.locator('[data-action]:disabled').count(),3);
+ assert(await page.locator('#clearHistory').isDisabled(),'active-only journal cannot be erased');
+ fixture.now+=12;
+ fixture.history[0].status='succeeded';fixture.history[0].completed_at=fixture.now;
+ fixture.history[0].result='Configuration OK.\nXray запущен; процесс проверен.\n'+'длинная_строка_'.repeat(25);
+ await page.clock.runFor(3000);
+ await page.waitForFunction(()=>document.getElementById('resultTitle').textContent.startsWith('Успешно'));
+ assert((await page.locator('#operationTimer').textContent()).includes('00:12'));
+ const completed=await page.locator('#operationTimer').textContent();
+ await page.clock.runFor(1500);
+ assert.equal(await page.locator('#operationTimer').textContent(),completed,'final duration stays fixed');
+ assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'no horizontal overflow at '+width);
+ if(action==='restart')await page.screenshot({path:path.join(output,'completed-'+width+'.png'),fullPage:true});
+ await page.locator('#clearHistory').click();
+ await page.waitForFunction(()=>document.getElementById('resultTitle').textContent==='Журнал действий пуст.');
+ assert.equal(await page.locator('.entry').count(),0);
+ assert.equal(await page.locator('#resultOutput').textContent(),'');
+ assert(await page.locator('#operationTimer').isHidden());
+ }
+ fixture.history=[{id:'a'.repeat(32),action:'restart',status:'running',created_at:fixture.now-20,delivered_at:fixture.now-15,completed_at:0,result:'Команда принята агентом.'}];
+ await page.reload();
+ await page.waitForFunction(()=>document.getElementById('operationTimer').textContent.includes('Прошло: 00:20'));
+ const text=await page.locator('#operationTimer').textContent();
+ await page.clock.setSystemTime(new Date((BASE+43200)*1000));
+ assert.equal(await page.locator('#operationTimer').textContent(),text,'local clock changes must not shift elapsed time');
+ await page.evaluate(()=>window.dispatchEvent(new Event('pagehide')));
+ const paused=fixture.reads;
+ await page.clock.runFor(10000);
+ assert.equal(fixture.reads,paused,'pagehide stops polls');
+ fixture.now+=10;
+ await page.evaluate(()=>{window.dispatchEvent(new Event('pageshow'));window.dispatchEvent(new Event('pageshow'));});
+ await page.waitForFunction(()=>document.getElementById('operationTimer').textContent.includes('Прошло: 00:30'));
+ await page.clock.runFor(6000);
+ assert(fixture.reads<=paused+3,'pageshow must not create parallel poll loops');
+ assert.equal(fixture.maxInflight,1);
+ assert.deepEqual(errors,[]);
+ console.log('XRAY_CONTROL_UI_OK',width,'all actions, timer, clear, reload and lifecycle');
+ await page.close();
+ }
+ } finally {await browser.close();}
+})().catch(error=>{console.error(error);process.exitCode=1;});
diff --git a/tests/test_xray_mobile_deploy.py b/tests/test_xray_mobile_deploy.py
index 957aed4..19d0ff2 100644
--- a/tests/test_xray_mobile_deploy.py
+++ b/tests/test_xray_mobile_deploy.py
@@ -29,7 +29,7 @@ class XrayMobileDeploymentTests(unittest.TestCase):
source = (ROOT / "vps/deploy-xray-mobile-fix.ps1").read_text(encoding="utf-8")
self.script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
self.script = self.script.replace("target=/www/cgi-bin/owrt-remote", "target=" + shlex.quote(self.target.as_posix()))
- self.script = self.script.replace("backup_dir=/root/owrt-remote-backup-before-xray-mobile-v120",
+ self.script = self.script.replace("backup_dir=/root/owrt-remote-backup-before-xray-mobile-v121",
"backup_dir=" + shlex.quote(self.backup_dir.as_posix()))
def deploy(self, action, content=None, fail_verify=False):
diff --git a/tests/test_xray_reverse_deploy.py b/tests/test_xray_reverse_deploy.py
index 026e046..bfac00c 100644
--- a/tests/test_xray_reverse_deploy.py
+++ b/tests/test_xray_reverse_deploy.py
@@ -7,7 +7,7 @@ import test_update_status_ui_deploy as vps_deploy
class ReverseRouterDeploymentTests(router_deploy.XrayValidationDeploymentTests):
deploy_name = 'deploy-xray-reverse-fix.ps1'
- backup_name = 'owrt-remote-backup-before-xray-reverse-v120'
+ backup_name = 'owrt-remote-backup-before-xray-reverse-v121'
success_marker = 'XRAY_REVERSE_ROUTER_Install_OK'
@staticmethod
@@ -78,7 +78,7 @@ test_restart() {
class ReverseVpsDeploymentTests(vps_deploy.UpdateStatusDeployTests):
deploy_file = 'deploy-xray-reverse-vps.ps1'
- backup_name = 'hub.py.bak-before-xray-reverse-v120'
+ backup_name = 'hub.py.bak-before-xray-reverse-v121'
success_marker = 'XRAY_REVERSE_VPS_Install_OK'
diff --git a/tests/test_xray_validation_deploy.py b/tests/test_xray_validation_deploy.py
index 8675fd8..15a4f5a 100644
--- a/tests/test_xray_validation_deploy.py
+++ b/tests/test_xray_validation_deploy.py
@@ -12,7 +12,7 @@ from test_xray_mobile_deploy import SH, GIT_BIN, ROOT
@unittest.skipUnless(SH, "POSIX shell required")
class XrayValidationDeploymentTests(unittest.TestCase):
deploy_name = 'deploy-xray-validation-fix.ps1'
- backup_name = 'owrt-remote-backup-before-xray-validation-v120'
+ backup_name = 'owrt-remote-backup-before-xray-validation-v121'
success_marker = 'XRAY_VALIDATION_ROUTER_Install_OK'
def setUp(self):
diff --git a/vps/deploy-dashboard-layout-fix.ps1 b/vps/deploy-dashboard-layout-fix.ps1
index 20efa99..f166787 100644
--- a/vps/deploy-dashboard-layout-fix.ps1
+++ b/vps/deploy-dashboard-layout-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-layout-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-layout-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nDASHBOARD_LAYOUT_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nDASHBOARD_LAYOUT_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-dashboard-menu-fix.ps1 b/vps/deploy-dashboard-menu-fix.ps1
index 3057bf3..3ced2da 100644
--- a/vps/deploy-dashboard-menu-fix.ps1
+++ b/vps/deploy-dashboard-menu-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-menu-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-dashboard-menu-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -108,7 +108,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nDASHBOARD_MENU_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nDASHBOARD_MENU_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-global-logs-vps.ps1 b/vps/deploy-global-logs-vps.ps1
index 70033c4..5a39787 100644
--- a/vps/deploy-global-logs-vps.ps1
+++ b/vps/deploy-global-logs-vps.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-global-logs-ui-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-global-logs-ui-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -107,7 +107,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nGLOBAL_LOGS_VPS_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nGLOBAL_LOGS_VPS_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-global-logs.ps1 b/vps/deploy-global-logs.ps1
index dcd7ef6..695a932 100644
--- a/vps/deploy-global-logs.ps1
+++ b/vps/deploy-global-logs.ps1
@@ -13,7 +13,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-global-logs-stop-v120
+backup=/root/owrt-remote-backup-before-global-logs-stop-v121
items='cgi agent init logs.sh logs-init luci'
changed=0
phase=preflight
@@ -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 'v120' "$stage/$item"; done
+ for item in cgi luci; do grep -F -q 'v121' "$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"
diff --git a/vps/deploy-group-colors-fix.ps1 b/vps/deploy-group-colors-fix.ps1
index 00aba9c..19c892d 100644
--- a/vps/deploy-group-colors-fix.ps1
+++ b/vps/deploy-group-colors-fix.ps1
@@ -6,7 +6,7 @@ param(
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
-$UploadName = 'owrt-group-colors-v120-' + [guid]::NewGuid().ToString('N')
+$UploadName = 'owrt-group-colors-v121-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-group-colors-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-group-colors-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -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 = ('v120', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
+required = ('v121', '#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)
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nGROUP_COLORS_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nGROUP_COLORS_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-heartbeat-redirect.ps1 b/vps/deploy-heartbeat-redirect.ps1
index f41b257..dcccf02 100644
--- a/vps/deploy-heartbeat-redirect.ps1
+++ b/vps/deploy-heartbeat-redirect.ps1
@@ -13,7 +13,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-heartbeat-redirect-v120
+backup=/root/owrt-remote-backup-before-heartbeat-redirect-v121
agent=/usr/sbin/owrt-remote
wan=/usr/lib/owrt-remote/wan.sh
changed=0
diff --git a/vps/deploy-heartbeat-transport-fix.ps1 b/vps/deploy-heartbeat-transport-fix.ps1
index 403ce5d..b0f333b 100644
--- a/vps/deploy-heartbeat-transport-fix.ps1
+++ b/vps/deploy-heartbeat-transport-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-heartbeat-transport-v120
+backup_dir=/root/owrt-remote-backup-before-heartbeat-transport-v121
changed=0
phase=preflight
item_path() {
diff --git a/vps/deploy-host-policy.ps1 b/vps/deploy-host-policy.ps1
index ac44c4a..2e0e96f 100644
--- a/vps/deploy-host-policy.ps1
+++ b/vps/deploy-host-policy.ps1
@@ -5,7 +5,7 @@ param(
[string]$PinnedVpsHost = '193.233.82.38',
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$WanInterface = 'wan',
[switch]$PreserveConnectionSettings,
- [ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v120',
+ [ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v121',
[switch]$PrepareOnly
)
@@ -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 'v120' "$stage/$item"; done
+ for item in cgi luci; do grep -F -q 'v121' "$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,16 +156,16 @@ if [ '__ACTION__' = Install ]; then
exit 1
fi
/usr/sbin/owrt-remote status
- grep -F -q 'v120' /www/cgi-bin/owrt-remote
- grep -F -q 'v120' /www/luci-static/resources/view/owrt_remote.js
- echo HOST_POLICY_ROUTER_V120_OK
+ grep -F -q 'v121' /www/cgi-bin/owrt-remote
+ grep -F -q 'v121' /www/luci-static/resources/view/owrt_remote.js
+ echo HOST_POLICY_ROUTER_V121_OK
else
test -f "$backup/complete"
save_files "$stage/previous"
changed=1
restore_files "$backup"
/usr/sbin/owrt-remote status
- echo HOST_POLICY_ROUTER_V120_ROLLBACK_OK
+ echo HOST_POLICY_ROUTER_V121_ROLLBACK_OK
fi
'@
} else {
@@ -180,7 +180,7 @@ fi
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v121
changed=0
cleanup() {
code=$?
@@ -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 'v120' "$stage/hub.py"
+ grep -F -q 'v121' "$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
@@ -226,7 +226,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$candidate" "$target"
-printf '\nHOST_POLICY_VPS_V120_%s_OK\n' '__ACTION__'
+printf '\nHOST_POLICY_VPS_V121_%s_OK\n' '__ACTION__'
'@
}
diff --git a/vps/deploy-hub-design.ps1 b/vps/deploy-hub-design.ps1
index 5ac1879..4b944fd 100644
--- a/vps/deploy-hub-design.ps1
+++ b/vps/deploy-hub-design.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-design-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-design-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -130,7 +130,7 @@ if [ "$healthy" -ne 1 ]; then
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
-printf '\nBackup: %s\nHUB_DESIGN_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nHUB_DESIGN_V121_%s_OK\n' "$backup" '__ACTION__'
if [ '__ACTION__' = Install ]; then
echo 'Refresh the Hub page and open Effects to choose the panel design.'
echo 'This fix is LOCAL. The panel update button can replace it with the published repository build.'
diff --git a/vps/deploy-hub-self-update.ps1 b/vps/deploy-hub-self-update.ps1
index 3b9931d..b9de081 100644
--- a/vps/deploy-hub-self-update.ps1
+++ b/vps/deploy-hub-self-update.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-self-update-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-self-update-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -107,7 +107,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nHUB_SELF_UPDATE_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nHUB_SELF_UPDATE_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-hub-url-fix.ps1 b/vps/deploy-hub-url-fix.ps1
index ffb0c0a..64a7015 100644
--- a/vps/deploy-hub-url-fix.ps1
+++ b/vps/deploy-hub-url-fix.ps1
@@ -34,7 +34,7 @@ if ($Target -eq 'Router') {
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-hub-url-v120
+backup=/root/owrt-remote-backup-before-hub-url-v121
chmod 700 "$stage"
config=/etc/config/owrtremote
changed=0
@@ -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 'v120' "$stage/$item"; done
+ for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
if [ ! -e "$backup" ]; then
save_files "$stage/retained-backup"
mv "$stage/retained-backup" "$backup"
@@ -138,7 +138,7 @@ else
changed=1
restore_files "$backup"
fi
-printf '\nBackup: %s\nHUB_URL_ROUTER_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nHUB_URL_ROUTER_V121_%s_OK\n' "$backup" '__ACTION__'
'@
} else {
$Payloads = @{
@@ -152,7 +152,7 @@ set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
chmod 700 "$stage"
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -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 'v120' "$stage/hub.py"
+ grep -F -q 'v121' "$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
@@ -198,7 +198,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$source_file" "$target"
-printf '\nBackup: %s\nHUB_URL_VPS_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nHUB_URL_VPS_V121_%s_OK\n' "$backup" '__ACTION__'
'@
}
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__HUB_URL__', $HubUrl)
diff --git a/vps/deploy-log-collector-fix.ps1 b/vps/deploy-log-collector-fix.ps1
index fe0631d..54c4a14 100644
--- a/vps/deploy-log-collector-fix.ps1
+++ b/vps/deploy-log-collector-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-log-collector-v120
+backup_dir=/root/owrt-remote-backup-before-log-collector-v121
changed=0
phase=preflight
items='logs.sh logs-init'
diff --git a/vps/deploy-online-status-fix.ps1 b/vps/deploy-online-status-fix.ps1
index 32c5101..0e2d8ef 100644
--- a/vps/deploy-online-status-fix.ps1
+++ b/vps/deploy-online-status-fix.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -59,7 +59,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$source_file" "$target"
-printf '\nBackup: %s\nONLINE_STATUS_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nONLINE_STATUS_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
diff --git a/vps/deploy-password-logout-fix.ps1 b/vps/deploy-password-logout-fix.ps1
index 98c8412..bc31eab 100644
--- a/vps/deploy-password-logout-fix.ps1
+++ b/vps/deploy-password-logout-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -105,7 +105,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nPASSWORD_LOGOUT_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nPASSWORD_LOGOUT_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-persistent-logs-vps.ps1 b/vps/deploy-persistent-logs-vps.ps1
index f52fcdd..f4fc01a 100644
--- a/vps/deploy-persistent-logs-vps.ps1
+++ b/vps/deploy-persistent-logs-vps.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-persistent-logs-sync-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-persistent-logs-sync-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -144,7 +144,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nPERSISTENT_LOGS_VPS_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nPERSISTENT_LOGS_VPS_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-persistent-logs.ps1 b/vps/deploy-persistent-logs.ps1
index 20d23a8..55990a8 100644
--- a/vps/deploy-persistent-logs.ps1
+++ b/vps/deploy-persistent-logs.ps1
@@ -13,7 +13,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-persistent-logs-v120
+backup=/root/owrt-remote-backup-before-persistent-logs-v121
items='cgi agent logs.sh logs-init luci'
changed=0
phase=preflight
@@ -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 'v120' "$stage/$item"; done
+ for item in cgi luci; do grep -F -q 'v121' "$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"
diff --git a/vps/deploy-recaptcha-v3.ps1 b/vps/deploy-recaptcha-v3.ps1
index b58833d..202334d 100644
--- a/vps/deploy-recaptcha-v3.ps1
+++ b/vps/deploy-recaptcha-v3.ps1
@@ -17,8 +17,8 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v120
-captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v120.json
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v121
+captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v121.json
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -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 'v120' in source
+assert 'v121' in source
assert 'v108' not in source
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
assert 'prepareLoginRecaptcha' in source
@@ -88,7 +88,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
-echo RECAPTCHA_V3_V120_OK
+echo RECAPTCHA_V3_V121_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V120_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v120
-captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v120.json
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v121
+captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v121.json
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
restore_captcha() {
diff --git a/vps/deploy-request-load-fix.ps1 b/vps/deploy-request-load-fix.ps1
index 93836de..eef8287 100644
--- a/vps/deploy-request-load-fix.ps1
+++ b/vps/deploy-request-load-fix.ps1
@@ -15,7 +15,7 @@ set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/root/owrt-remote-backup-before-request-load-v120
+backup=/root/owrt-remote-backup-before-request-load-v121
policy=/etc/nginx/conf.d/owrt-remote-log-policy.conf
journal=/etc/systemd/journald.conf.d/owrt-remote-limits.conf
logrotate=/etc/logrotate.d/owrt-remote
@@ -184,7 +184,7 @@ PY
done
[ "$healthy" = 1 ]
-printf '\nBackup: %s\nREQUEST_LOAD_FIX_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nREQUEST_LOAD_FIX_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-resource-fix.ps1 b/vps/deploy-resource-fix.ps1
index cf2b5e8..5aa983f 100644
--- a/vps/deploy-resource-fix.ps1
+++ b/vps/deploy-resource-fix.ps1
@@ -18,7 +18,7 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -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 'v120' in source
+assert 'v121' 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)
@@ -78,7 +78,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
-echo RESOURCE_FIX_V120_OK
+echo RESOURCE_FIX_V121_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V120_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v121
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
cleanup() {
diff --git a/vps/deploy-router-card-ui-fix.ps1 b/vps/deploy-router-card-ui-fix.ps1
index 52c1afd..8b298fc 100644
--- a/vps/deploy-router-card-ui-fix.ps1
+++ b/vps/deploy-router-card-ui-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nROUTER_CARD_UI_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nROUTER_CARD_UI_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-router-effects.ps1 b/vps/deploy-router-effects.ps1
index fb4f0f2..41dfd62 100644
--- a/vps/deploy-router-effects.ps1
+++ b/vps/deploy-router-effects.ps1
@@ -15,7 +15,7 @@ set -eu
stage=/tmp/__UPLOAD_NAME__
cgi=/www/cgi-bin/owrt-remote
effects=/www/luci-static/resources/owrt_remote_effects.js
-backup=/root/owrt-remote-backup-before-router-effects-v120
+backup=/root/owrt-remote-backup-before-router-effects-v121
changed=0
restore_file() {
@@ -85,7 +85,7 @@ if [ '__ACTION__' = Install ]; then
grep -F -q 'id="routerEffectsPanel"' "$cgi"
grep -F -q 'function initHubAppearance()' "$effects"
fi
-printf '\nBackup: %s\nROUTER_EFFECTS_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nROUTER_EFFECTS_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-router-name-fix.ps1 b/vps/deploy-router-name-fix.ps1
index 65e2536..f0c4a3d 100644
--- a/vps/deploy-router-name-fix.ps1
+++ b/vps/deploy-router-name-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-name-fix-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-name-fix-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -135,7 +135,7 @@ if [ "$healthy" -ne 1 ]; then
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
-printf '\nBackup: %s\nROUTER_NAME_FIX_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nROUTER_NAME_FIX_V121_%s_OK\n' "$backup" '__ACTION__'
if [ '__ACTION__' = Install ]; then
echo 'Refresh the Hub and router updates tabs to check the renamed routers.'
echo 'This fix is LOCAL. The panel update button can replace it with the published repository build.'
diff --git a/vps/deploy-router-updates.ps1 b/vps/deploy-router-updates.ps1
index d6955e8..23bb547 100644
--- a/vps/deploy-router-updates.ps1
+++ b/vps/deploy-router-updates.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-reboot-all-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-reboot-all-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -125,7 +125,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nROUTER_UPDATES_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nROUTER_UPDATES_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-update-status-ui.ps1 b/vps/deploy-update-status-ui.ps1
index 3a991aa..7bf001a 100644
--- a/vps/deploy-update-status-ui.ps1
+++ b/vps/deploy-update-status-ui.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-update-status-ui-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-update-status-ui-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -139,7 +139,7 @@ if [ "$healthy" -ne 1 ]; then
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
-printf '\nBackup: %s\nUPDATE_STATUS_UI_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nUPDATE_STATUS_UI_V121_%s_OK\n' "$backup" '__ACTION__'
if [ '__ACTION__' = Install ]; then
echo 'Reload the Hub page (Ctrl+F5) to load the new UI.'
echo 'This fix is LOCAL. The panel update button can replace it with the published repository build.'
diff --git a/vps/deploy-version-v120.ps1 b/vps/deploy-version-v121.ps1
similarity index 93%
rename from vps/deploy-version-v120.ps1
rename to vps/deploy-version-v121.ps1
index 9722511..e1a5e45 100644
--- a/vps/deploy-version-v120.ps1
+++ b/vps/deploy-version-v121.ps1
@@ -7,7 +7,7 @@ param(
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
-$UploadName = 'owrt-version-v120-' + [guid]::NewGuid().ToString('N')
+$UploadName = 'owrt-version-v121-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
@@ -16,7 +16,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -58,9 +58,9 @@ if [ '__ACTION__' = Install ]; then
from pathlib import Path
import sys
source = Path(sys.argv[1]).read_text(encoding='utf-8')
-required = ('v120', 'def hub_update_require_version(', 'def hub_update_older_version(',
+required = ('v121', 'def hub_update_require_version(', 'def hub_update_older_version(',
"else if (state.checked && !state.checking) message('');")
-if 'v' + str(120 - 1) in source:
+if 'v' + str(121 - 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]
@@ -133,14 +133,14 @@ if [ "$healthy" -ne 1 ]; then
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
-printf '\nBackup: %s\nHUB_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nHUB_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RouterScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-v120
+backup=/root/owrt-remote-backup-before-v121
cgi=/www/cgi-bin/owrt-remote
luci=/www/luci-static/resources/view/owrt_remote.js
changed=0
@@ -164,9 +164,9 @@ test -s "$cgi"
test -s "$luci"
if [ '__ACTION__' = Install ]; then
sh -n "$stage/cgi"
- grep -F -q 'v120' "$stage/cgi"
- grep -F -q 'v120' "$stage/luci"
- if grep -F -q "v$((120 - 1))" "$stage/cgi" "$stage/luci"; then
+ grep -F -q 'v121' "$stage/cgi"
+ grep -F -q 'v121' "$stage/luci"
+ if grep -F -q "v$((121 - 1))" "$stage/cgi" "$stage/luci"; then
echo 'Old UI version remains in candidate.' >&2
exit 1
fi
@@ -199,7 +199,7 @@ 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_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nROUTER_V121_%s_OK\n' "$backup" '__ACTION__'
'@
if ($PSCmdlet.ParameterSetName -eq 'Router') {
@@ -240,7 +240,7 @@ try {
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 v120 $Action finished successfully. Refresh the panel."
+ Write-Host "Version v121 $Action finished successfully. Refresh the panel."
}
finally {
if (-not $PrepareOnly) {
diff --git a/vps/deploy-vps-resources-fix.ps1 b/vps/deploy-vps-resources-fix.ps1
index 8eb1ec9..acfbfa4 100644
--- a/vps/deploy-vps-resources-fix.ps1
+++ b/vps/deploy-vps-resources-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-resources-live-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-resources-live-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -107,7 +107,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
-printf '\nBackup: %s\nVPS_RESOURCES_LIVE_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nVPS_RESOURCES_LIVE_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-vps-widgets.ps1 b/vps/deploy-vps-widgets.ps1
index f640087..24754c9 100644
--- a/vps/deploy-vps-widgets.ps1
+++ b/vps/deploy-vps-widgets.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -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 'v120' "$stage/hub.py"
+ grep -F -q 'v121' "$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
@@ -67,7 +67,7 @@ if [ '__ACTION__' = Install ]; then
code=$(curl -sS --max-time 5 -o "$stage/response.json" -w '%{http_code}' http://127.0.0.1:8088/api/vps/resources)
test "$code" = 401
fi
-printf '\nVPS_WIDGETS_V120_%s_OK\n' '__ACTION__'
+printf '\nVPS_WIDGETS_V121_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
diff --git a/vps/deploy-wan-dns-fix.ps1 b/vps/deploy-wan-dns-fix.ps1
index b9c2f0c..36eaaa0 100644
--- a/vps/deploy-wan-dns-fix.ps1
+++ b/vps/deploy-wan-dns-fix.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/usr/lib/owrt-remote/wan.sh
-backup_dir=/root/owrt-remote-backup-before-wan-dns-v120
+backup_dir=/root/owrt-remote-backup-before-wan-dns-v121
changed=0
phase=preflight
heartbeat_pid() {
diff --git a/vps/deploy-wan-multi.ps1 b/vps/deploy-wan-multi.ps1
index e38f5fe..f3f8c6e 100644
--- a/vps/deploy-wan-multi.ps1
+++ b/vps/deploy-wan-multi.ps1
@@ -20,7 +20,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-wan-multi-v120
+backup=/root/owrt-remote-backup-before-wan-multi-v121
config=/etc/config/owrtremote
changed=0
item_path() {
@@ -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 'v120' "$stage/$item"; done
+ for item in cgi luci; do grep -F -q 'v121' "$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"
diff --git a/vps/deploy-wan-recovery-fix.ps1 b/vps/deploy-wan-recovery-fix.ps1
index e81deed..9f09caf 100644
--- a/vps/deploy-wan-recovery-fix.ps1
+++ b/vps/deploy-wan-recovery-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-wan-recovery-v120
+backup_dir=/root/owrt-remote-backup-before-wan-recovery-v121
changed=0
phase=preflight
item_path() {
diff --git a/vps/deploy-wan-stability-fix.ps1 b/vps/deploy-wan-stability-fix.ps1
index 17c22e2..ca5058a 100644
--- a/vps/deploy-wan-stability-fix.ps1
+++ b/vps/deploy-wan-stability-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup=/root/owrt-remote-backup-before-wan-stability-v120
+backup=/root/owrt-remote-backup-before-wan-stability-v121
config=/etc/config/owrtremote
changed=0
fail() {
diff --git a/vps/deploy-web-push-fix.ps1 b/vps/deploy-web-push-fix.ps1
index 07251f6..eae79ed 100644
--- a/vps/deploy-web-push-fix.ps1
+++ b/vps/deploy-web-push-fix.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -72,7 +72,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$source_file" "$target"
-printf '\nBackup: %s\nWEB_PUSH_V120_%s_OK\n' "$backup" '__ACTION__'
+printf '\nBackup: %s\nWEB_PUSH_V121_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
diff --git a/vps/deploy-xray-apk-fix.ps1 b/vps/deploy-xray-apk-fix.ps1
index 70254cb..2ffee7c 100644
--- a/vps/deploy-xray-apk-fix.ps1
+++ b/vps/deploy-xray-apk-fix.ps1
@@ -16,7 +16,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-xray-apk-v120
+backup_dir=/root/owrt-remote-backup-before-xray-apk-v121
key_file=/etc/owrt-remote/web.key
key_candidate=$key_file.new-__UPLOAD_NAME__
changed=0
diff --git a/vps/deploy-xray-apply-fix.ps1 b/vps/deploy-xray-apply-fix.ps1
index b10bd96..f9c463b 100644
--- a/vps/deploy-xray-apply-fix.ps1
+++ b/vps/deploy-xray-apply-fix.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/www/cgi-bin/owrt-remote
-backup_dir=/root/owrt-remote-backup-before-xray-apply-v120
+backup_dir=/root/owrt-remote-backup-before-xray-apply-v121
backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__
changed=0
diff --git a/vps/deploy-xray-boot-fix.ps1 b/vps/deploy-xray-boot-fix.ps1
index dfdec7c..64ebecf 100644
--- a/vps/deploy-xray-boot-fix.ps1
+++ b/vps/deploy-xray-boot-fix.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/usr/sbin/owrt-remote
-backup_dir=/root/owrt-remote-backup-before-xray-boot-v120
+backup_dir=/root/owrt-remote-backup-before-xray-boot-v121
changed=0
phase=preflight
heartbeat_pid() {
diff --git a/vps/deploy-xray-compat-fix.ps1 b/vps/deploy-xray-compat-fix.ps1
index 6219b55..35172df 100644
--- a/vps/deploy-xray-compat-fix.ps1
+++ b/vps/deploy-xray-compat-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-xray-compat-v120
+backup_dir=/root/owrt-remote-backup-before-xray-compat-v121
changed=0
phase=preflight
item_path() {
diff --git a/vps/deploy-xray-control-ui.ps1 b/vps/deploy-xray-control-ui.ps1
new file mode 100644
index 0000000..8312324
--- /dev/null
+++ b/vps/deploy-xray-control-ui.ps1
@@ -0,0 +1,8 @@
+param(
+ [Parameter(Mandatory = $true)][string]$Vps,
+ [ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
+ [switch]$PrepareOnly
+)
+
+$ErrorActionPreference = 'Stop'
+& (Join-Path $PSScriptRoot 'deploy-xray-control.ps1') -Vps $Vps -Action $Action -BackupName 'xray-control-ui' -PrepareOnly:$PrepareOnly
diff --git a/vps/deploy-xray-control.ps1 b/vps/deploy-xray-control.ps1
new file mode 100644
index 0000000..0418eff
--- /dev/null
+++ b/vps/deploy-xray-control.ps1
@@ -0,0 +1,218 @@
+param(
+ [Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
+ [Parameter(Mandatory = $true, ParameterSetName = 'Router')][string]$Router,
+ [ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
+ [ValidateSet('xray-control', 'xray-control-ui')][string]$BackupName = 'xray-control',
+ [switch]$PrepareOnly
+)
+
+$ErrorActionPreference = 'Stop'
+$RepoRoot = Split-Path -Parent $PSScriptRoot
+$UploadName = 'owrt-xray-control-' + [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 }
+
+$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
+
+if [ "$kind" = Vps ]; then
+ names=hub.py
+else
+ names='agent control.sh init'
+fi
+target() {
+ case "$1" in
+ hub.py) echo /opt/owrt-remote/owrt-remote-hub.py ;;
+ agent) echo /usr/sbin/owrt-remote ;;
+ control.sh) echo /usr/lib/owrt-remote/control.sh ;;
+ init) echo /etc/init.d/owrt-remote ;;
+ 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" = control.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; 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 xray_control_exchange(', 'def router_xray_control_html(', 'X-Xray-Control-CSRF', 'router_xray_commands'):
+ 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/control.sh" || fail_router 'control.sh shell syntax check failed'
+ sh -n "$stage/init" || fail_router 'init shell syntax check failed'
+ 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 xray_control_worker "$stage/control.sh" || fail_router 'control.sh does not contain xray_control_worker'
+ 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"
+step=restart
+restart
+
+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
+printf '\nBackup: %s\nXRAY_CONTROL_%s_%s_OK\n' "$backup" "$kind" "$action"
+'@
+
+try {
+ [System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
+ $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__KIND__', $TargetKind).Replace('__ACTION__', $Action).Replace('__BACKUP_NAME__', $BackupName)
+ [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'; 'control.sh' = 'files\usr\lib\owrt-remote\control.sh'; 'init' = 'files\etc\init.d\owrt-remote' }
+ }
+ 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 }
+ & scp -O -o ConnectTimeout=20 -r -- $StageRoot "${Destination}:/tmp/"
+ if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
+ & ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Destination "sh /tmp/$UploadName/run.sh"
+ if ($LASTEXITCODE -ne 0) { throw "$Action failed. Success was not confirmed; see output above." }
+ Write-Host "Xray remote control $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 }
+ }
+}
diff --git a/vps/deploy-xray-mobile-fix.ps1 b/vps/deploy-xray-mobile-fix.ps1
index 025a15d..fa0c6f9 100644
--- a/vps/deploy-xray-mobile-fix.ps1
+++ b/vps/deploy-xray-mobile-fix.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/www/cgi-bin/owrt-remote
-backup_dir=/root/owrt-remote-backup-before-xray-mobile-v120
+backup_dir=/root/owrt-remote-backup-before-xray-mobile-v121
backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__
changed=0
diff --git a/vps/deploy-xray-reverse-fix.ps1 b/vps/deploy-xray-reverse-fix.ps1
index eeefe30..59d7dcd 100644
--- a/vps/deploy-xray-reverse-fix.ps1
+++ b/vps/deploy-xray-reverse-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-xray-reverse-v120
+backup_dir=/root/owrt-remote-backup-before-xray-reverse-v121
changed=0
restart_attempted=0
phase=preflight
diff --git a/vps/deploy-xray-reverse-vps.ps1 b/vps/deploy-xray-reverse-vps.ps1
index c173262..582d203 100644
--- a/vps/deploy-xray-reverse-vps.ps1
+++ b/vps/deploy-xray-reverse-vps.ps1
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
-backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-xray-reverse-v120
+backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-xray-reverse-v121
candidate=$target.new-__UPLOAD_NAME__
changed=0
diff --git a/vps/deploy-xray-source-fix.ps1 b/vps/deploy-xray-source-fix.ps1
index 4e4fd73..067dba5 100644
--- a/vps/deploy-xray-source-fix.ps1
+++ b/vps/deploy-xray-source-fix.ps1
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/usr/sbin/owrt-remote
-backup_dir=/root/owrt-remote-backup-before-xray-source-v120
+backup_dir=/root/owrt-remote-backup-before-xray-source-v121
runtime=/tmp/owrt-xray/xray
changed=0
phase=preflight
diff --git a/vps/deploy-xray-validation-fix.ps1 b/vps/deploy-xray-validation-fix.ps1
index e627ccb..c2f1abf 100644
--- a/vps/deploy-xray-validation-fix.ps1
+++ b/vps/deploy-xray-validation-fix.ps1
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
-backup_dir=/root/owrt-remote-backup-before-xray-validation-v120
+backup_dir=/root/owrt-remote-backup-before-xray-validation-v121
changed=0
phase=preflight
item_path() {
diff --git a/vps/owrt-remote-hub.py b/vps/owrt-remote-hub.py
index e22bf2f..8888443 100644
--- a/vps/owrt-remote-hub.py
+++ b/vps/owrt-remote-hub.py
@@ -3623,6 +3623,19 @@ def init_db(conn):
journal_id text not null default '', cursor integer not null default 0,
updated_at integer not null default 0, last_sync integer not null default 0,
clear_request text not null default '')''')
+ conn.execute('''create table if not exists router_xray_commands (
+ id text primary key,
+ router_id text not null,
+ action text not null,
+ status text not null default 'queued',
+ result text not null default '',
+ created_at integer not null,
+ started_at integer not null default 0,
+ completed_at integer not null default 0,
+ delivered_at integer not null default 0
+ )''')
+ conn.execute('create index if not exists router_xray_commands_router_idx on router_xray_commands(router_id, created_at)')
+ ensure_column(conn, 'router_xray_commands', 'hidden', 'integer not null default 0')
ensure_column(conn, 'router_logs', 'state_json', "text not null default '{}'")
ensure_column(conn, 'router_logs', 'state_at', 'integer not null default 0')
ensure_column(conn, "routers", "custom_name", "text not null default ''")
@@ -4226,6 +4239,120 @@ def upsert_router(conn, values):
return get_router(conn, router_id)
+XRAY_CONTROL_ACTIONS = {'start': 'Запустить', 'stop': 'Остановить', 'restart': 'Перезапустить'}
+XRAY_CONTROL_TIMEOUT_SECONDS = 180
+XRAY_CONTROL_EXECUTION_SECONDS = 45
+
+
+def xray_control_audit(conn, router_id, message, level='OK'):
+ conn.execute('insert or ignore into router_logs(router_id) values (?)', (router_id,))
+ raw = bytes(conn.execute('select content from router_logs where router_id=?', (router_id,)).fetchone()[0])
+ raw = (raw + f'[{level}] {iso_time(now_ts())} Hub: Remote Xray: {message}\n'.encode())[-ROUTER_LOG_MAX_BYTES:]
+ conn.execute('update router_logs set content=?, updated_at=? where router_id=?', (raw, now_ts(), router_id))
+
+
+def xray_control_expire(conn, router_id):
+ ts = now_ts()
+ query = "select * from router_xray_commands where router_id=? and status in ('queued','delivered','running') and created_at < ?"
+ if not conn.execute(query, (router_id, ts - XRAY_CONTROL_TIMEOUT_SECONDS)).fetchone():
+ return
+ # Most UI polls stay read-only. Serialize expiry only when a command is actually overdue.
+ conn.execute('update routers set last_seen=last_seen where id=?', (router_id,))
+ rows = conn.execute(query, (router_id, ts - XRAY_CONTROL_TIMEOUT_SECONDS)).fetchall()
+ for row in rows:
+ if ts - row['created_at'] <= XRAY_CONTROL_TIMEOUT_SECONDS:
+ continue
+ message = ('Команда не доставлена: агент не вышел на связь за 3 минуты. Команда отменена.'
+ if not row['delivered_at'] else
+ 'Результат не подтверждён: агент не прислал итог за 3 минуты. Проверь журнал и текущий статус Xray.')
+ status = 'expired' if not row['delivered_at'] else 'unconfirmed'
+ conn.execute('update router_xray_commands set status=?, result=?, completed_at=? where id=?', (status, message, ts, row['id']))
+ xray_control_audit(conn, router_id, message, 'WARN')
+
+
+def xray_control_enqueue(conn, router_id, action, request_id):
+ if not isinstance(action, str) or action not in XRAY_CONTROL_ACTIONS or not re.fullmatch(r'[a-f0-9]{32}', str(request_id or '')):
+ raise ValueError('Недопустимая команда или идентификатор запроса.')
+ # Acquire the DB writer before checking the queue; concurrent tabs cannot enqueue two operations.
+ conn.execute('update routers set last_seen=last_seen where id=?', (router_id,))
+ row = get_active_router(conn, router_id)
+ if not row:
+ raise ValueError('Роутер не найден.')
+ previous = conn.execute('select * from router_xray_commands where id=?', (request_id,)).fetchone()
+ if previous:
+ if previous['router_id'] != router_id or previous['action'] != action:
+ raise ValueError('Этот идентификатор уже использован другой командой.')
+ return
+ if router_reported_status(row).get('xray_control') != 1:
+ raise ValueError('Сначала обнови агент на этом роутере: управление через Heartbeat ещё не поддерживается.')
+ xray_control_expire(conn, router_id)
+ if conn.execute("select 1 from router_xray_commands where router_id=? and status in ('queued','delivered','running')", (router_id,)).fetchone():
+ raise ValueError('Предыдущая команда ещё выполняется или ожидает Heartbeat.')
+ conn.execute('insert into router_xray_commands(id,router_id,action,created_at) values (?,?,?,?)', (request_id, router_id, action, now_ts()))
+ conn.execute('delete from router_xray_commands where router_id=? and id not in (select id from router_xray_commands where router_id=? order by created_at desc,rowid desc limit 100)', (router_id, router_id))
+ xray_control_audit(conn, router_id, f'{XRAY_CONTROL_ACTIONS[action]} Xray: команда {request_id[:8]} поставлена в очередь.')
+
+
+def xray_control_exchange(conn, router_id, payload):
+ conn.execute('update routers set last_seen=last_seen where id=?', (router_id,))
+ result = payload.get('xray_control_result')
+ if isinstance(result, dict):
+ command = conn.execute('select * from router_xray_commands where id=? and router_id=?',
+ (str(result.get('id') or ''), router_id)).fetchone()
+ state, rc, xray = result.get('status'), result.get('rc'), result.get('xray')
+ if (command and not command['hidden'] and command['delivered_at'] and command['action'] == result.get('action')
+ and command['status'] in {'delivered', 'running', 'unconfirmed'}
+ and state in {'running', 'succeeded', 'failed', 'interrupted'}
+ and not (command['status'] == 'unconfirmed' and state == 'running')
+ and type(rc) is int and 0 <= rc <= 255 and xray in {'running', 'stopped'}):
+ if state == 'succeeded' and (rc != 0 or xray != ('stopped' if command['action'] == 'stop' else 'running')):
+ state = 'failed'
+ message = str(result.get('message') or '')[:1500]
+ message = redact_router_log_bytes(message.encode()).decode('utf-8', 'replace')
+ if state != command['status']:
+ conn.execute('update router_xray_commands set status=?,result=?,started_at=case when started_at=0 then ? else started_at end,completed_at=? where id=?',
+ (state, message, now_ts(), 0 if state == 'running' else now_ts(), command['id']))
+ xray_control_audit(conn, router_id, f'{XRAY_CONTROL_ACTIONS[command["action"]]} Xray: {message} (rc={rc}, Xray={xray}).',
+ 'OK' if state in {'running', 'succeeded'} else 'ERROR')
+ xray_control_expire(conn, router_id)
+ if payload.get('xray_control') != 1:
+ return None
+ row = conn.execute("select * from router_xray_commands where router_id=? and status in ('queued','delivered') order by created_at limit 1", (router_id,)).fetchone()
+ if not row:
+ return None
+ conn.execute("update router_xray_commands set status='delivered',delivered_at=case when delivered_at=0 then ? else delivered_at end where id=?", (now_ts(), row['id']))
+ return {'id': row['id'], 'action': row['action']}
+
+
+def xray_control_clear_history(conn, router_id):
+ # Keep bounded ID tombstones for retry protection, but erase completed output.
+ # Active commands must remain visible and deliverable even from another tab.
+ conn.execute('update routers set last_seen=last_seen where id=?', (router_id,))
+ if not get_active_router(conn, router_id):
+ raise ValueError('Роутер не найден.')
+ xray_control_expire(conn, router_id)
+ conn.execute("update router_xray_commands set hidden=1,result='' where router_id=? and status not in ('queued','delivered','running')",
+ (router_id,))
+
+
+def xray_control_snapshot(conn, router_id):
+ row = get_active_router(conn, router_id)
+ if not row:
+ raise ValueError('Роутер не найден.')
+ xray_control_expire(conn, router_id)
+ router = row_to_router(row)
+ try:
+ interval = int(router['status'].get('heartbeat_interval') or 30)
+ except (TypeError, ValueError):
+ interval = 30
+ return {'ok': True, 'router_id': router_id, 'name': router['name'], 'online': router['online'],
+ 'last_seen': router['last_seen'], 'xray': router['status'].get('xray', 'unknown'),
+ 'supported': router['status'].get('xray_control') == 1,
+ 'server_time': now_ts(), 'heartbeat_interval': min(max(interval, 10), 3600),
+ 'command_timeout_seconds': XRAY_CONTROL_TIMEOUT_SECONDS, 'execution_timeout_seconds': XRAY_CONTROL_EXECUTION_SECONDS,
+ 'history': [dict(item) for item in conn.execute('select * from router_xray_commands where router_id=? and hidden=0 order by created_at desc,rowid desc limit 30', (router_id,))]}
+
+
def heartbeat(conn, payload):
router_id = clean_router_id(payload.get("id"))
row = get_router(conn, router_id)
@@ -6299,7 +6426,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding