Release v115 with router global logs and mobile header layout

This commit is contained in:
kzolotarev95 committed 2026-10-14 03:39:33 +04:00
1 parent 0508438de0
commit 4ceb3d031a
39 files changed
+1181 -93

No files matched your search

+8
View File
@@ -168,6 +168,14 @@ hub.example.com
wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/install.sh?v=$(date +%s)" | sh wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/install.sh?v=$(date +%s)" | sh
``` ```
В панели самого роутера рядом с NetHaven VPN есть кнопка **Глобал логи**:
при открытии блока сразу загружаются сохранённые записи. Журнал можно скачать,
включить просмотр с обновлением каждые 3 секунды или очистить.
Записываются действия панели, Heartbeat, WAN и сообщения Xray.
Журнал хранится в `/tmp/owrt-remote-logs/`, занимает около 2 МБ максимум,
очищается каждые 24 часа и исчезает после перезагрузки. Сбор работает отдельно
от туннеля; остановка Xray не останавливает журнал. Ключи и пароли скрываются.
Проверка на роутере: Проверка на роутере:
```sh ```sh
+5
View File
@@ -54,6 +54,10 @@ stop_xray_processes() {
start_service() { start_service() {
mkdir -p /var/lock /var/run /tmp/owrt-xray mkdir -p /var/lock /var/run /tmp/owrt-xray
if [ -x /etc/init.d/owrt-remote-logs ]; then
/etc/init.d/owrt-remote-logs start >/dev/null 2>&1 || true
fi
logger -t owrt-remote 'Сервис: запуск' 2>/dev/null || true
if ! config_enabled; then if ! config_enabled; then
echo "owrt-remote disabled in /etc/config/owrtremote" echo "owrt-remote disabled in /etc/config/owrtremote"
@@ -81,6 +85,7 @@ reload_service() {
} }
stop_service() { stop_service() {
logger -t owrt-remote 'Сервис: остановка туннеля' 2>/dev/null || true
stop_xray_processes stop_xray_processes
/usr/sbin/owrt-remote wan-cleanup >/dev/null 2>&1 || true /usr/sbin/owrt-remote wan-cleanup >/dev/null 2>&1 || true
} }
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh /etc/rc.common
USE_PROCD=1
START=98
STOP=11
start_service() {
procd_open_instance journal
procd_set_param command /bin/sh /usr/lib/owrt-remote/logs.sh collect
procd_set_param respawn 3600 5 5
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}
+143
View File
@@ -0,0 +1,143 @@
#!/bin/sh
# The private Remote journal lives in RAM. It never changes the system logd.
LOG_DIR="${OWRT_REMOTE_LOG_DIR:-/tmp/owrt-remote-logs}"
LOG_LIMIT=1048576
LOG_KEEP_SECONDS=86400
log_clock() { cut -d. -f1 /proc/uptime; }
log_init() {
umask 077
mkdir -p "$LOG_DIR" || return 1
chmod 700 "$LOG_DIR"
}
log_lock() {
local attempt owner
log_init || return 1
attempt=0
while ! mkdir "$LOG_DIR/lock" 2>/dev/null; do
owner="$(cat "$LOG_DIR/lock/pid" 2>/dev/null)"
case "$owner" in
''|*[!0-9]*)
# Recover a writer killed between mkdir and writing its PID.
if [ "$attempt" -ge 20 ]; then
rm -f "$LOG_DIR/lock/pid"
rmdir "$LOG_DIR/lock" 2>/dev/null || true
fi ;;
*) if ! kill -0 "$owner" 2>/dev/null; then
rm -f "$LOG_DIR/lock/pid"
rmdir "$LOG_DIR/lock" 2>/dev/null || true
fi ;;
esac
attempt=$((attempt + 1))
[ "$attempt" -lt 100 ] || return 1
sleep 0.1
done
printf '%s\n' "$$" >"$LOG_DIR/lock/pid"
}
log_unlock() {
rm -f "$LOG_DIR/lock/pid"
rmdir "$LOG_DIR/lock" 2>/dev/null || true
}
log_reset_locked() {
: >"$LOG_DIR/current.log"
rm -f "$LOG_DIR/previous.log"
log_clock >"$LOG_DIR/age"
}
log_maintain_locked() {
local now age
now="$(log_clock)"
age="$(cat "$LOG_DIR/age" 2>/dev/null)"
case "$age" in ''|*[!0-9]*) log_reset_locked; return ;; esac
if [ "$now" -lt "$age" ] || [ "$((now - age))" -ge "$LOG_KEEP_SECONDS" ]; then
log_reset_locked
fi
}
log_redact() {
# Never retain command blocks containing credentials or authenticated URLs.
LC_ALL=C awk '
{
line = substr($0, 1, 4096); lower = tolower(line)
if (lower ~ /(authorization|hub_token|vless_uuid|ssh_vless_uuid|password|passwd|web[._ -]?key|[?&]key=|[?&]token=|"uuid"|"privatekey"|"password")/ ||
lower ~ /[0-9a-f][0-9a-f][0-9a-f][0-9a-f]-[0-9a-f-]+-[0-9a-f-]+-[0-9a-f-]+/)
print "[строка с ключом или паролем скрыта]"
else print line
}'
}
log_append() {
local line size
# Process one bounded line at a time and release the lock between writes.
log_redact | while IFS= read -r line; do
log_lock || exit 1
trap 'log_unlock' EXIT
trap 'exit 0' INT TERM
log_maintain_locked
size="$(wc -c <"$LOG_DIR/current.log")"
if [ "$size" -ge "$LOG_LIMIT" ]; then
mv -f "$LOG_DIR/current.log" "$LOG_DIR/previous.log"
: >"$LOG_DIR/current.log"
fi
printf '%s\n' "$line" >>"$LOG_DIR/current.log"
log_unlock
trap - EXIT INT TERM
done
}
log_read() {
local previous_size current_size
log_lock || return 1
log_maintain_locked
# Open the retained files under the lock, then release it before streaming
# to a slow phone. Downloads must not prevent the collector from writing.
previous_size=0
if [ -f "$LOG_DIR/previous.log" ]; then
previous_size="$(wc -c <"$LOG_DIR/previous.log")"
exec 3<"$LOG_DIR/previous.log"
else
exec 3</dev/null
fi
current_size="$(wc -c <"$LOG_DIR/current.log")"
exec 4<"$LOG_DIR/current.log"
log_unlock
if [ "${1:-}" = live ]; then
{ head -c "$previous_size" <&3; head -c "$current_size" <&4; } | tail -c 65536
else
head -c "$previous_size" <&3
head -c "$current_size" <&4
fi
exec 3<&- 4<&-
}
log_clear() {
log_lock || return 1
log_reset_locked
log_unlock
}
log_collect() {
# These variables must remain visible to EXIT even after this function returns.
log_init || return 1
fifo="$LOG_DIR/stream.$$"
mkfifo "$fifo" || return 1
reader=''; writer=''; timer=''
trap 'trap - EXIT; for child in "$reader" "$writer" "$timer"; do [ -z "$child" ] || kill "$child" 2>/dev/null || true; done; wait; rm -f "$fifo"' EXIT
trap 'exit 0' INT TERM
# Follow only new Remote/Xray service records: a clear must not reload history.
logread -f -e 'owrt-remote\(\[[0-9][0-9]*\]\)\{0,1\}:' >"$fifo" 2>/dev/null &
reader=$!
while IFS= read -r line; do printf '%s\n' "$line" | log_append; done <"$fifo" &
writer=$!
while :; do
log_lock || return 1
log_maintain_locked
log_unlock
sleep 60 & timer=$!
wait "$timer" || return 0
kill -0 "$reader" 2>/dev/null && kill -0 "$writer" 2>/dev/null || return 1
done
}
case "${1:-}" in
collect) log_collect ;;
read) log_read "${2:-}" ;;
clear) log_clear ;;
append) log_append ;;
event) { printf '%s owrt-remote: %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$2"; cat; } | log_append ;;
*) printf 'Usage: logs.sh collect|read [live]|clear|append|event MESSAGE\n' >&2; exit 2 ;;
esac
+16 -9
View File
@@ -12,7 +12,7 @@ log() {
} }
die() { die() {
printf 'ОШИБКА: %s\n' "$*" >&2 log "ОШИБКА: $*"
exit 1 exit 1
} }
@@ -559,7 +559,7 @@ render_client_config() {
cat >"$out" <<EOF cat >"$out" <<EOF
{ {
"log": { "log": {
"loglevel": "warning" "loglevel": "info"
}, },
"inbounds": [], "inbounds": [],
"outbounds": [ "outbounds": [
@@ -859,7 +859,7 @@ heartbeat_apply_hub_update() {
} }
send_heartbeat() { send_heartbeat() {
local hub_url token endpoint tmp response event used fallback_base local hub_url token endpoint tmp response event used fallback_base errors rc
event="${1:-}" event="${1:-}"
hub_url="$(uci_get hub_url '')" hub_url="$(uci_get hub_url '')"
token="$(uci_get hub_token '')" token="$(uci_get hub_token '')"
@@ -867,30 +867,35 @@ send_heartbeat() {
[ -n "$token" ] || die "hub_token пустой" [ -n "$token" ] || die "hub_token пустой"
if truthy "$(uci_get wan_direct 0)"; then if truthy "$(uci_get wan_direct 0)"; then
command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER" command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
wan_prepare || return 1 wan_prepare || { log 'Heartbeat: не удалось подготовить прямой WAN'; return 1; }
wan_reconcile_xray wan_reconcile_xray
fi fi
endpoint="${hub_url%/}/api/heartbeat" endpoint="${hub_url%/}/api/heartbeat"
tmp="${TMPDIR:-/tmp}/owrt-remote-heartbeat.$$" tmp="${TMPDIR:-/tmp}/owrt-remote-heartbeat.$$"
response="${TMPDIR:-/tmp}/owrt-remote-heartbeat.response.$$" response="${TMPDIR:-/tmp}/owrt-remote-heartbeat.response.$$"
errors="$response.error"
heartbeat_json "$event" >"$tmp" heartbeat_json "$event" >"$tmp"
used=0 used=0
for endpoint in $(heartbeat_candidate_endpoints); do for endpoint in $(heartbeat_candidate_endpoints); do
used=1 used=1
if post_json "$endpoint" "$token" "$tmp" >"$response" \ rc=0
&& grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then post_json "$endpoint" "$token" "$tmp" >"$response" 2>"$errors" || rc=$?
if [ "$rc" = 0 ] && grep -Eq '"ok"[[:space:]]*:[[:space:]]*true' "$response"; then
fallback_base="$(heartbeat_base_from_endpoint "$endpoint")" fallback_base="$(heartbeat_base_from_endpoint "$endpoint")"
if ! heartbeat_apply_hub_update "$response" "$fallback_base"; then if ! heartbeat_apply_hub_update "$response" "$fallback_base"; then
rm -f "$tmp" "$response" log 'Heartbeat: Hub ответил, но обновление настроек не применилось'
rm -f "$tmp" "$response" "$errors"
return 1 return 1
fi fi
cat "$response" cat "$response"
rm -f "$tmp" "$response" log "Heartbeat: OK; Hub=$fallback_base; WAN_direct=$(uci_get wan_direct 0); WAN_active=$(cat "$WAN_STATE/active-interface" 2>/dev/null)"
rm -f "$tmp" "$response" "$errors"
return 0 return 0
fi fi
log "Heartbeat: ошибка; endpoint=$endpoint; rc=$rc; $(head -c 1024 "$errors"); ответ=$(head -c 1024 "$response")"
done done
rm -f "$tmp" "$response" rm -f "$tmp" "$response" "$errors"
[ "$used" = "1" ] || die "hub_url/public_url/vps_host пустые" [ "$used" = "1" ] || die "hub_url/public_url/vps_host пустые"
return 1 return 1
} }
@@ -969,6 +974,7 @@ heartbeat_loop() {
local interval local interval
interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)" interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
[ "$interval" -lt 10 ] && interval=10 [ "$interval" -lt 10 ] && interval=10
log "Heartbeat: цикл запущен; интервал=${interval}s"
while :; do while :; do
if send_heartbeat >/dev/null 2>&1; then if send_heartbeat >/dev/null 2>&1; then
heartbeat_mark_ok heartbeat_mark_ok
@@ -1227,6 +1233,7 @@ run_xray() {
xray_config="$(render_client_config)" || die "cannot create Xray configuration" xray_config="$(render_client_config)" || die "cannot create Xray configuration"
[ -n "$xray_config" ] && [ -s "$xray_config" ] || die "Xray configuration is missing or empty" [ -n "$xray_config" ] && [ -s "$xray_config" ] || die "Xray configuration is missing or empty"
[ -x "$xray_bin" ] || die "xray not found or not executable: $xray_bin" [ -x "$xray_bin" ] || die "xray not found or not executable: $xray_bin"
log "Xray: запуск туннеля; config=$xray_config; VPS=$(uci_get vps_host ''):$(uci_get vps_port 8443); WAN_direct=$(uci_get wan_direct 0); WAN_selected=$(uci_get wan_interface wan)"
if "$xray_bin" help 2>/dev/null | grep -q 'run'; then if "$xray_bin" help 2>/dev/null | grep -q 'run'; then
exec "$xray_bin" run -config "$xray_config" exec "$xray_bin" run -config "$xray_config"
+179 -2
View File
@@ -2,6 +2,7 @@
KEY_FILE="${KEY_FILE:-/etc/owrt-remote/web.key}" KEY_FILE="${KEY_FILE:-/etc/owrt-remote/web.key}"
AGENT="${AGENT:-/usr/sbin/owrt-remote}" AGENT="${AGENT:-/usr/sbin/owrt-remote}"
LOG_HELPER="${OWRT_REMOTE_LOG_HELPER:-/usr/lib/owrt-remote/logs.sh}"
OWRT_REMOTE_UI_VERSION="2026-07-02-mobile-terminal-batch-v25" OWRT_REMOTE_UI_VERSION="2026-07-02-mobile-terminal-batch-v25"
PARAMS_FILE="${TMPDIR:-/tmp}/owrt-remote-cgi.$$" PARAMS_FILE="${TMPDIR:-/tmp}/owrt-remote-cgi.$$"
RESULT_TITLE="" RESULT_TITLE=""
@@ -131,6 +132,39 @@ set_result() {
RESULT_TITLE="$1" RESULT_TITLE="$1"
RESULT_BODY="$2" RESULT_BODY="$2"
RESULT_KIND="${3:-info}" RESULT_KIND="${3:-info}"
if [ -r "$LOG_HELPER" ]; then
printf '%s\n' "$RESULT_BODY" | sh "$LOG_HELPER" event "Панель: $RESULT_TITLE; результат=$RESULT_KIND" >/dev/null 2>&1 || true
fi
}
logs_response() {
local mode
mode="$1"
if [ ! -r "$LOG_HELPER" ]; then
printf 'Status: 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n'
printf 'Сборщик логов не установлен. Установи локальный фикс целиком.\n'
return
fi
if [ "$mode" = clear ]; then
if [ "${REQUEST_METHOD:-GET}" != POST ]; then
printf 'Status: 405 Method Not Allowed\r\nAllow: POST\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n'
return
fi
if sh "$LOG_HELPER" clear; then
printf 'Content-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n'
printf 'Логи Remote очищены.\n'
else
printf 'Status: 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n'
printf 'Не удалось очистить логи. Повтори через несколько секунд.\n'
fi
return
fi
printf 'Content-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n'
if [ "$mode" = download ]; then
printf 'Content-Disposition: attachment; filename="owrt-remote-global-%s.log"\r\n' "$(date '+%Y%m%d-%H%M%S')"
fi
printf '\r\n'
sh "$LOG_HELPER" read "$mode"
} }
save_config() { save_config() {
@@ -161,6 +195,9 @@ save_config() {
uci_set wan_interface "$wan_interfaces" uci_set wan_interface "$wan_interfaces"
uci_set wan_dns "$(param wan_dns)" uci_set wan_dns "$(param wan_dns)"
uci commit owrtremote uci commit owrtremote
if [ -r "$LOG_HELPER" ]; then
printf '' | sh "$LOG_HELPER" event "Панель: сохранены настройки; enabled=$enabled; Hub=$(uci_get hub_url ''); VPS=$(uci_get vps_host ''):$(uci_get vps_port 8443); WAN_direct=$(uci_get wan_direct 0); WAN_selected=$wan_interfaces" >/dev/null 2>&1 || true
fi
set_result "Настройки сохранены" "Если менял Xray или VPS-поля, перезапусти сервис." "ok" set_result "Настройки сохранены" "Если менял Xray или VPS-поля, перезапусти сервис." "ok"
} }
@@ -437,7 +474,7 @@ render_page() {
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="owrt-remote-ui-version" content="$OWRT_REMOTE_UI_VERSION"> <meta name="owrt-remote-ui-version" content="$OWRT_REMOTE_UI_VERSION">
<title>OpenWrt Remote Hub v114</title> <title>OpenWrt Remote Hub v115</title>
<style> <style>
:root{color-scheme:dark;--bg:#07040f;--panel:rgba(19,14,32,.88);--text:#f7f2ff;--muted:#b9adc9;--line:rgba(169,126,255,.24);--blue:#7c3aed;--green:#22c55e;--red:#fb7185;--amber:#f59e0b;--teal:#a855f7;--grid:rgba(168,85,247,.16)} :root{color-scheme:dark;--bg:#07040f;--panel:rgba(19,14,32,.88);--text:#f7f2ff;--muted:#b9adc9;--line:rgba(169,126,255,.24);--blue:#7c3aed;--green:#22c55e;--red:#fb7185;--amber:#f59e0b;--teal:#a855f7;--grid:rgba(168,85,247,.16)}
*{box-sizing:border-box}body{position:relative;min-height:100vh;margin:0;overflow-x:hidden;background-color:var(--bg);background-image:radial-gradient(circle at 12% 8%,rgba(168,85,247,.46),transparent 31%),radial-gradient(circle at 82% 12%,rgba(79,70,229,.38),transparent 30%),radial-gradient(circle at 50% 105%,rgba(236,72,153,.26),transparent 35%),linear-gradient(145deg,#07040f,#120a24 48%,#05030a),repeating-linear-gradient(0deg,transparent 0 30px,var(--grid) 31px),repeating-linear-gradient(90deg,transparent 0 30px,var(--grid) 31px);background-size:130% 130%,140% 140%,135% 135%,100% 100%,31px 31px,31px 31px;background-attachment:fixed;color:var(--text);font:14px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;animation:bgFlow 22s ease-in-out infinite alternate} *{box-sizing:border-box}body{position:relative;min-height:100vh;margin:0;overflow-x:hidden;background-color:var(--bg);background-image:radial-gradient(circle at 12% 8%,rgba(168,85,247,.46),transparent 31%),radial-gradient(circle at 82% 12%,rgba(79,70,229,.38),transparent 30%),radial-gradient(circle at 50% 105%,rgba(236,72,153,.26),transparent 35%),linear-gradient(145deg,#07040f,#120a24 48%,#05030a),repeating-linear-gradient(0deg,transparent 0 30px,var(--grid) 31px),repeating-linear-gradient(90deg,transparent 0 30px,var(--grid) 31px);background-size:130% 130%,140% 140%,135% 135%,100% 100%,31px 31px,31px 31px;background-attachment:fixed;color:var(--text);font:14px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;animation:bgFlow 22s ease-in-out infinite alternate}
@@ -458,8 +495,11 @@ form{margin:0}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr
.helperText{margin:0 0 12px;color:var(--muted)}.xrayApply{margin-top:14px;padding:16px;border:1px solid rgba(34,211,238,.42);border-radius:8px;background:linear-gradient(135deg,rgba(34,211,238,.16),rgba(124,58,237,.20),rgba(236,72,153,.11));box-shadow:0 18px 42px rgba(34,211,238,.10)}.xrayApply h3{margin:0 0 8px;font-size:16px;color:#a5f3fc}.scriptBox{width:100%;min-height:260px;resize:vertical;border:1px solid rgba(34,211,238,.28);border-radius:8px;background:rgba(255,255,255,.07);padding:12px;color:var(--text);font:12px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre;overflow:auto} .helperText{margin:0 0 12px;color:var(--muted)}.xrayApply{margin-top:14px;padding:16px;border:1px solid rgba(34,211,238,.42);border-radius:8px;background:linear-gradient(135deg,rgba(34,211,238,.16),rgba(124,58,237,.20),rgba(236,72,153,.11));box-shadow:0 18px 42px rgba(34,211,238,.10)}.xrayApply h3{margin:0 0 8px;font-size:16px;color:#a5f3fc}.scriptBox{width:100%;min-height:260px;resize:vertical;border:1px solid rgba(34,211,238,.28);border-radius:8px;background:rgba(255,255,255,.07);padding:12px;color:var(--text);font:12px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre;overflow:auto}
.brandPanel{display:grid;grid-template-columns:repeat(2,minmax(0,132px));gap:8px}.brandPanel .titleRow,.brandPanel .links{grid-column:1/-1}.brandPanel .appBanner{width:100%;min-width:0}.brandPanel .links{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:0}.brandPanel .links a{width:100%;min-width:0} .brandPanel{display:grid;grid-template-columns:repeat(2,minmax(0,132px));gap:8px}.brandPanel .titleRow,.brandPanel .links{grid-column:1/-1}.brandPanel .appBanner{width:100%;min-width:0}.brandPanel .links{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:0}.brandPanel .links a{width:100%;min-width:0}
.wanPicker{border:1px solid var(--line);border-radius:8px;background:rgba(8,5,18,.72)}.wanPicker summary{display:flex;align-items:center;justify-content:center;gap:5px;min-height:40px;padding:10px 11px;cursor:pointer;list-style:none;font-weight:700}.wanPicker summary::-webkit-details-marker{display:none}.wanPicker summary::after{content:"▾";margin-left:auto;color:var(--muted)}.wanPicker[open] summary::after{content:"▴"}.wanPickerList{display:flex;flex-direction:column;gap:4px;max-height:240px;overflow:auto;padding:6px;border-top:1px solid var(--line)}.wanChoice{display:flex;align-items:center;gap:10px;min-height:40px;padding:8px;border-radius:6px;cursor:pointer;overflow-wrap:anywhere}.wanChoice:hover{background:rgba(255,255,255,.08)}.wanChoice input{width:18px;height:18px;min-width:18px;padding:0;margin:0;accent-color:var(--blue)}.wanPicked{margin-top:6px;font-size:12px;color:var(--muted);overflow-wrap:anywhere} .wanPicker{border:1px solid var(--line);border-radius:8px;background:rgba(8,5,18,.72)}.wanPicker summary{display:flex;align-items:center;justify-content:center;gap:5px;min-height:40px;padding:10px 11px;cursor:pointer;list-style:none;font-weight:700}.wanPicker summary::-webkit-details-marker{display:none}.wanPicker summary::after{content:"▾";margin-left:auto;color:var(--muted)}.wanPicker[open] summary::after{content:"▴"}.wanPickerList{display:flex;flex-direction:column;gap:4px;max-height:240px;overflow:auto;padding:6px;border-top:1px solid var(--line)}.wanChoice{display:flex;align-items:center;gap:10px;min-height:40px;padding:8px;border-radius:6px;cursor:pointer;overflow-wrap:anywhere}.wanChoice:hover{background:rgba(255,255,255,.08)}.wanChoice input{width:18px;height:18px;min-width:18px;padding:0;margin:0;accent-color:var(--blue)}.wanPicked{margin-top:6px;font-size:12px;color:var(--muted);overflow-wrap:anywhere}
.globalLogsPanel[hidden]{display:none}.globalLogsPanel{margin-top:16px}.globalLogsPanel .actions{justify-content:flex-start;margin:0 0 12px}.globalLogsText{margin:12px 0 0;max-height:55vh;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word;font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;background:rgba(8,5,18,.72);border:1px solid var(--line);border-radius:8px;padding:12px;min-height:150px}.globalLogsStatus{color:var(--muted);overflow-wrap:anywhere}.globalLogsToggle{cursor:pointer;font-family:inherit;border-color:rgba(34,197,94,.65);background:var(--green);color:#07120a;box-shadow:0 10px 22px rgba(34,197,94,.22)}
.globalLogsNote{margin:0 0 12px;padding:10px 12px;border:1px solid rgba(245,158,11,.35);border-left:3px solid var(--amber);border-radius:8px;background:rgba(245,158,11,.10);color:#fde68a;font-size:12px;line-height:1.5;overflow-wrap:anywhere}
@media(max-width:820px){.grid,.formgrid,.metrics{grid-template-columns:1fr}.linkMetric{grid-column:span 1}.metricLine{align-items:center;justify-content:center}.miniGo{width:auto;justify-content:center;display:inline-flex}.hero{align-items:flex-start;flex-direction:column}.topActions{justify-content:flex-start;padding-top:0}.wrap{padding:14px}h1{font-size:24px}.appBanner{width:auto;max-width:100%;justify-content:center;min-height:36px;padding:8px 12px}.panelHead{align-items:stretch;flex-direction:column}.headActionForm .btn{width:100%}.actions .btn,.actions button{width:100%}} @media(max-width:820px){.grid,.formgrid,.metrics{grid-template-columns:1fr}.linkMetric{grid-column:span 1}.metricLine{align-items:center;justify-content:center}.miniGo{width:auto;justify-content:center;display:inline-flex}.hero{align-items:flex-start;flex-direction:column}.topActions{justify-content:flex-start;padding-top:0}.wrap{padding:14px}h1{font-size:24px}.appBanner{width:auto;max-width:100%;justify-content:center;min-height:36px;padding:8px 12px}.panelHead{align-items:stretch;flex-direction:column}.headActionForm .btn{width:100%}.actions .btn,.actions button{width:100%}}
@media(max-width:820px){.brandPanel{grid-template-columns:repeat(2,minmax(0,1fr));width:100%}.brandPanel .appBanner{width:100%}} @media(max-width:820px){.brandPanel{grid-template-columns:repeat(2,minmax(0,1fr));width:100%}.brandPanel .appBanner{width:100%}}
@media(max-width:820px){.hero{gap:10px}.hero .brand{width:100%;min-width:0}.hero .uiPill,.hero .appBanner{width:100%;min-width:0;min-height:44px}.hero .appBanner{line-height:1.2}.topActions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));width:100%;gap:8px}.vpnCard,.returnCard{width:100%;min-width:0}.returnCard{grid-column:1/-1}.backBtn{white-space:normal;text-align:center}}
</style> </style>
</head> </head>
<body> <body>
@@ -468,7 +508,7 @@ form{margin:0}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr
<div class="brand"> <div class="brand">
<div class="brandPanel"> <div class="brandPanel">
<div class="titleRow"> <div class="titleRow">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v114</span></span></h1> <h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v115</span></span></h1>
</div> </div>
<div class="links"> <div class="links">
<a class="uiPill" href="https://t.me/kzolotarev95" target="_blank" rel="noopener noreferrer">Telegram</a> <a class="uiPill" href="https://t.me/kzolotarev95" target="_blank" rel="noopener noreferrer">Telegram</a>
@@ -483,12 +523,25 @@ form{margin:0}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr
<span>NetHaven VPN</span> <span>NetHaven VPN</span>
</a> </a>
</div> </div>
<button class="uiPill globalLogsToggle" id="globalLogsToggle" type="button" aria-expanded="false" aria-controls="globalLogsPanel">Глобал логи</button>
<div class="returnCard"> <div class="returnCard">
<a class="uiPill backBtn" href="/cgi-bin/luci/">Вернуться в службы OpenWrt</a> <a class="uiPill backBtn" href="/cgi-bin/luci/">Вернуться в службы OpenWrt</a>
</div> </div>
</div> </div>
</section> </section>
<section class="panel globalLogsPanel" id="globalLogsPanel" hidden>
<div class="panelHead"><h2>Глобал логи</h2><button class="btn" id="globalLogsClose" type="button">Закрыть</button></div>
<blockquote class="globalLogsNote">Действия панели, Heartbeat, WAN и ошибки Xray этого роутера. Журнал хранится в оперативной памяти, очищается после перезагрузки и каждые 24 часа. Максимум около 2 МБ. Ключи и пароли скрываются.</blockquote>
<div class="actions">
<a class="btn" href="?key=$(h "$key")&amp;action=logs_download">Скачать логи</a>
<button class="btn" id="globalLogsLive" type="button">Запустить в реальном времени</button>
<button class="btn bad" id="globalLogsClear" type="button">Очистить логи</button>
</div>
<div class="globalLogsStatus" id="globalLogsStatus" role="status">Сохранённые записи показаны ниже. Нажми «Запустить в реальном времени», чтобы обновлять их каждые 3 секунды.</div>
<pre class="globalLogsText" id="globalLogsText" tabindex="0">Загрузка записей журнала…</pre>
</section>
<section class="grid"> <section class="grid">
<div class="panel"> <div class="panel">
<h2>Состояние</h2> <h2>Состояние</h2>
@@ -594,6 +647,118 @@ EOF
</section> </section>
</main> </main>
<script> <script>
(function() {
var panel = document.getElementById('globalLogsPanel');
var toggle = document.getElementById('globalLogsToggle');
var close = document.getElementById('globalLogsClose');
var live = document.getElementById('globalLogsLive');
var clear = document.getElementById('globalLogsClear');
var output = document.getElementById('globalLogsText');
var status = document.getElementById('globalLogsStatus');
var timer = null, controller = null, generation = 0, running = false;
function endpoint(action) {
var url = new URL(window.location.href);
url.searchParams.set('action', action);
url.searchParams.delete('_');
return url;
}
function stop() {
running = false;
generation++;
if (timer !== null) window.clearTimeout(timer);
timer = null;
if (controller) controller.abort();
controller = null;
live.textContent = 'Запустить в реальном времени';
live.setAttribute('aria-pressed', 'false');
}
async function refresh(once) {
if ((!running && !once) || panel.hidden || document.hidden) return;
var current = generation;
var request = new AbortController();
controller = request;
var timeout = window.setTimeout(function() { request.abort(); }, 10000);
try {
var response = await fetch(endpoint('logs_live'), {cache: 'no-store', signal: request.signal});
if (!response.ok) throw new Error('HTTP ' + response.status);
var text = await response.text();
if (current !== generation || (!running && !once)) return;
if ((response.headers.get('Content-Type') || '').indexOf('text/plain') !== 0) throw new Error('Доступ к журналу завершён. Открой панель заново.');
var atBottom = output.scrollHeight - output.clientHeight - output.scrollTop < 24;
var previousTop = output.scrollTop;
if (output.textContent !== text) {
output.textContent = text || (once ? 'Журнал пока пуст. Новые записи появятся после действий в панели или событий Remote. Нажми «Запустить в реальном времени», чтобы увидеть их.' : 'Журнал пуст. Новые события появятся автоматически.');
output.scrollTop = atBottom ? output.scrollHeight : previousTop;
}
status.textContent = (once ? 'Сохранённые записи' : 'Просмотр в реальном времени') + ' · обновлено ' + new Date().toLocaleTimeString() + ' · последние 64 КБ журнала' + (once ? '. Для автообновления нажми «Запустить в реальном времени».' : '');
} catch (error) {
if (current === generation && (running || once)) {
status.textContent = 'Не удалось получить логи: ' + error.message + (once ? '. Для повторной загрузки нажми «Запустить в реальном времени».' : '. Повтор через 3 секунды.');
if (once) output.textContent = 'Записи журнала не загружены. Ошибка указана выше.';
}
} finally {
window.clearTimeout(timeout);
if (controller === request) controller = null;
if (!once && current === generation && running && !panel.hidden && !document.hidden) timer = window.setTimeout(refresh, 3000);
}
}
toggle.addEventListener('click', function() {
panel.hidden = !panel.hidden;
toggle.setAttribute('aria-expanded', String(!panel.hidden));
if (panel.hidden) { stop(); status.textContent = 'Просмотр остановлен.'; }
else {
stop();
output.textContent = 'Загрузка записей журнала…';
status.textContent = 'Загружаю сохранённые записи с роутера…';
refresh(true);
}
});
close.addEventListener('click', function() {
panel.hidden = true;
toggle.setAttribute('aria-expanded', 'false');
stop();
status.textContent = 'Просмотр остановлен.';
});
live.addEventListener('click', function() {
if (running) { stop(); status.textContent = 'Просмотр остановлен.'; return; }
stop();
running = true;
generation++;
live.textContent = 'Остановить просмотр';
live.setAttribute('aria-pressed', 'true');
refresh();
});
clear.addEventListener('click', async function() {
var resume = running;
stop();
clear.disabled = true;
live.disabled = true;
var request = new AbortController();
var timeout = window.setTimeout(function() { request.abort(); }, 10000);
try {
var response = await fetch(endpoint('logs_clear'), {method: 'POST', cache: 'no-store', signal: request.signal});
var text = await response.text();
if (!response.ok || (response.headers.get('Content-Type') || '').indexOf('text/plain') !== 0) throw new Error('HTTP ' + response.status);
output.textContent = 'Журнал очищен.';
status.textContent = text.trim();
} catch (error) { status.textContent = 'Не удалось очистить логи: ' + error.message; }
finally {
window.clearTimeout(timeout);
clear.disabled = false;
live.disabled = false;
if (resume && !panel.hidden) { running = true; generation++; live.textContent = 'Остановить просмотр'; live.setAttribute('aria-pressed', 'true'); refresh(); }
}
});
document.addEventListener('visibilitychange', function() {
if (!running) return;
generation++;
if (timer !== null) window.clearTimeout(timer);
timer = null;
if (controller) controller.abort();
if (!document.hidden) refresh();
});
window.addEventListener('pagehide', stop);
})();
document.querySelectorAll('[data-wan-picker]').forEach(function(picker) { document.querySelectorAll('[data-wan-picker]').forEach(function(picker) {
var field = picker.closest('.wanField'); var field = picker.closest('.wanField');
var inputs = Array.from(picker.querySelectorAll('input[name="wan_interface"]')); var inputs = Array.from(picker.querySelectorAll('input[name="wan_interface"]'));
@@ -620,6 +785,18 @@ fi
action="$(param action)" action="$(param action)"
case "$action" in
logs_download) logs_response download; exit 0 ;;
logs_live) logs_response live; exit 0 ;;
logs_clear) logs_response clear; exit 0 ;;
esac
if [ "${REQUEST_METHOD:-GET}" = POST ] && [ -n "$action" ] && [ -r "$LOG_HELPER" ]; then
printf '' | sh "$LOG_HELPER" event "Панель: действие=$action; начало" >/dev/null 2>&1 || true
elif [ "${REQUEST_METHOD:-GET}" = GET ] && [ -z "$action" ] && [ -r "$LOG_HELPER" ]; then
printf '' | sh "$LOG_HELPER" event 'Панель: открыта' >/dev/null 2>&1 || true
fi
if [ "$action" = "download_config" ]; then if [ "$action" = "download_config" ]; then
http_json http_json
"$AGENT" render-client --stdout 2>&1 "$AGENT" render-client --stdout 2>&1
@@ -14,7 +14,7 @@ return view.extend({
if (!key) { if (!key) {
return E('div', { 'class': 'cbi-map' }, [ return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Remote Hub v114')), E('h2', {}, _('OpenWrt Remote Hub v115')),
E('div', { 'class': 'alert-message warning' }, [ E('div', { 'class': 'alert-message warning' }, [
_('Web key not found. Reinstall the module or create /etc/owrt-remote/web.key.') _('Web key not found. Reinstall the module or create /etc/owrt-remote/web.key.')
]) ])
@@ -34,7 +34,7 @@ return view.extend({
}, 100); }, 100);
return E('div', { 'class': 'cbi-map' }, [ return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Remote Hub v114')), E('h2', {}, _('OpenWrt Remote Hub v115')),
E('p', {}, _('Opening remote access panel...')), E('p', {}, _('Opening remote access panel...')),
E('p', {}, [ E('p', {}, [
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Open panel')) E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Open panel'))
+7
View File
@@ -216,6 +216,8 @@ install_xray_runtime() {
install_file "usr/sbin/owrt-remote" 0755 install_file "usr/sbin/owrt-remote" 0755
install_file "usr/lib/owrt-remote/wan.sh" 0644 install_file "usr/lib/owrt-remote/wan.sh" 0644
install_file "usr/lib/owrt-remote/logs.sh" 0644
install_file "etc/init.d/owrt-remote-logs" 0755
install_file "etc/init.d/owrt-remote" 0755 install_file "etc/init.d/owrt-remote" 0755
install_file "etc/hotplug.d/iface/99-owrt-remote" 0755 install_file "etc/hotplug.d/iface/99-owrt-remote" 0755
install_config install_config
@@ -226,6 +228,11 @@ install_file "www/luci-static/resources/view/owrt_remote.js" 0644
ensure_wol_support ensure_wol_support
if [ "${ROOT%/}" = "" ]; then
/etc/init.d/owrt-remote-logs enable
/etc/init.d/owrt-remote-logs restart
fi
rm -f "$(target_path usr/lib/lua/luci/controller/owrt_remote.lua)" 2>/dev/null || true rm -f "$(target_path usr/lib/lua/luci/controller/owrt_remote.lua)" 2>/dev/null || true
rm -rf "$(target_path tmp/luci-indexcache)" "$(target_path tmp/luci-modulecache)" "$(target_path tmp/luci-indexcache.)"* "$(target_path tmp/luci-modulecache.)"* 2>/dev/null || true rm -rf "$(target_path tmp/luci-indexcache)" "$(target_path tmp/luci-modulecache)" "$(target_path tmp/luci-indexcache.)"* "$(target_path tmp/luci-modulecache.)"* 2>/dev/null || true
+12 -12
View File
@@ -1,4 +1,4 @@
# Фиксация VPS host и независимое соединение Remote через WAN (v114) # Фиксация VPS host и независимое соединение Remote через WAN (v115)
`vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение `vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение
используется и когда опция отсутствует у старой установки. Только явно используется и когда опция отсутствует у старой установки. Только явно
@@ -42,8 +42,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-hub-url-fix.
``` ```
Откат: те же команды с `-Action Rollback`, без `-HubUrl`. Резервные копии: Откат: те же команды с `-Action Rollback`, без `-HubUrl`. Резервные копии:
`/root/owrt-remote-backup-before-hub-url-v114` на роутере и `/root/owrt-remote-backup-before-hub-url-v115` на роутере и
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v114` на VPS. `/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v115` на VPS.
`HEARTBEAT_OK` подтверждает ответ Hub. Если файлы установлены, но Hub недоступен, `HEARTBEAT_OK` подтверждает ответ Hub. Если файлы установлены, но Hub недоступен,
скрипт отдельно сообщает `HEARTBEAT_FAILED`; это не подтверждение связи. скрипт отдельно сообщает `HEARTBEAT_FAILED`; это не подтверждение связи.
@@ -125,21 +125,21 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.
Установка загружает локальные файлы, без Git. До остановки службы проверяются Установка загружает локальные файлы, без Git. До остановки службы проверяются
доступность WAN и поддержка таблицы реальной командой ip на роутере. доступность WAN и поддержка таблицы реальной командой ip на роутере.
На роутер загружается и файл LuCI: версия v114 появляется и в основной На роутер загружается и файл LuCI: версия v115 появляется и в основной
CGI-панели, и в странице входа в неё через LuCI. CGI-панели, и в странице входа в неё через LuCI.
Сначала сохраняются файлы Сначала сохраняются файлы
и конфигурация; после замены проверяется heartbeat/health. При ошибке и конфигурация; после замены проверяется heartbeat/health. При ошибке
автоматически восстанавливается состояние перед текущей попыткой. автоматически восстанавливается состояние перед текущей попыткой.
Сохранённая резервная копия для ручного отката не перезаписывается. Сохранённая резервная копия для ручного отката не перезаписывается.
* Роутер: `/root/owrt-remote-backup-before-host-policy-v114` — агент, * Роутер: `/root/owrt-remote-backup-before-host-policy-v115` — агент,
helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге). helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге).
* VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v114`. * VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v115`.
База роутеров и настройки авторизации не заменяются. База роутеров и настройки авторизации не заменяются.
Успешная установка заканчивается `HOST_POLICY_ROUTER_V114_OK` на роутере Успешная установка заканчивается `HOST_POLICY_ROUTER_V115_OK` на роутере
и `HOST_POLICY_VPS_V114_Install_OK` на VPS. Старые резервные копии предыдущей и `HOST_POLICY_VPS_V115_Install_OK` на VPS. Старые резервные копии предыдущей
версии сохраняются; новые команды отката используют отдельные копии для v114. версии сохраняются; новые команды отката используют отдельные копии для v115.
### Переход с nftables-маркировки на адресную маршрутизацию ### Переход с nftables-маркировки на адресную маршрутизацию
@@ -148,11 +148,11 @@ CGI-панели, и в странице входа в неё через LuCI.
Обновление VPS для этого изменения не требуется. Обновление VPS для этого изменения не требуется.
```powershell ```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PreserveConnectionSettings -BackupName "podkop-compat-v114" -Action Install powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PreserveConnectionSettings -BackupName "podkop-compat-v115" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v114" -Action Rollback powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v115" -Action Rollback
``` ```
Копия: `/root/owrt-remote-backup-before-podkop-compat-v114`. Копия: `/root/owrt-remote-backup-before-podkop-compat-v115`.
После установки повторите диагностику Podkop. Предупреждение от прежних правил После установки повторите диагностику Podkop. Предупреждение от прежних правил
Remote должно исчезнуть. Настоящие дополнительные правила других приложений Remote должно исчезнуть. Настоящие дополнительные правила других приложений
по-прежнему обнаруживаются штатной диагностикой. по-прежнему обнаруживаются штатной диагностикой.
+3 -3
View File
@@ -1,4 +1,4 @@
# reCAPTCHA v3 в OpenWrt Remote Hub v114 # reCAPTCHA v3 в OpenWrt Remote Hub v115
В меню владельца, в блоке «Капча на экране входа», доступны цифры, В меню владельца, в блоке «Капча на экране входа», доступны цифры,
Google reCAPTCHA v2 Checkbox и Google reCAPTCHA v3. Установка обновления Google reCAPTCHA v2 Checkbox и Google reCAPTCHA v3. Установка обновления
@@ -74,8 +74,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-recaptcha-v3
непосредственно перед попыткой. Резервные копии при повторном запуске непосредственно перед попыткой. Резервные копии при повторном запуске
не перезаписываются: не перезаписываются:
* `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v114` * `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v115`
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v114.json` (режим 0600). * `/opt/owrt-remote/captcha-before-recaptcha-v3-v115.json` (режим 0600).
Скрипт рассчитан на стандартные пути установленного Hub: Скрипт рассчитан на стандартные пути установленного Hub:
`/opt/owrt-remote/owrt-remote-hub.py`, `/var/lib/owrt-remote/hub-auth.json` `/opt/owrt-remote/owrt-remote-hub.py`, `/var/lib/owrt-remote/hub-auth.json`
+3 -3
View File
@@ -1,6 +1,6 @@
# Аудит ресурсов OpenWrt Remote Hub v114 # Аудит ресурсов OpenWrt Remote Hub v115
Исправления внесены поверх `7f809fd`. Версия панели остаётся v114. Исправления внесены поверх `7f809fd`. Версия панели остаётся v115.
## SQLite ## SQLite
@@ -115,7 +115,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-resource-fix
Установщик загружает локальный файл без Git, запускает изолированные тесты, Установщик загружает локальный файл без Git, запускает изолированные тесты,
сохраняет исходный серверный файл: сохраняет исходный серверный файл:
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v114`, `/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v115`,
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health. атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
Существующая резервная копия не перезаписывается. При ошибке установки Существующая резервная копия не перезаписывается. При ошибке установки
восстанавливается файл, работавший непосредственно перед текущей попыткой. восстанавливается файл, работавший непосредственно перед текущей попыткой.
+4 -4
View File
@@ -1,4 +1,4 @@
# Виджеты ресурсов VPS (v114) # Виджеты ресурсов VPS (v115)
Три карточки ЦП, ОЗУ и ДИСК находятся над кнопками «Рестарт Xray VPS», Три карточки ЦП, ОЗУ и ДИСК находятся над кнопками «Рестарт Xray VPS»,
профилем и выходом. На ПК ширина и высота совпадают с кнопками под ними. профилем и выходом. На ПК ширина и высота совпадают с кнопками под ними.
@@ -23,7 +23,7 @@ vCPU и объёмы занятой/общей памяти и диска.
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-vps-widgets.ps1" -Vps "root@193.233.82.38" -Action Install powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-vps-widgets.ps1" -Vps "root@193.233.82.38" -Action Install
``` ```
После `VPS_WIDGETS_V114_Install_OK` обновите страницу через Ctrl+F5. После `VPS_WIDGETS_V115_Install_OK` обновите страницу через Ctrl+F5.
Скрипт загружает локальный файл, проверяет его до замены, перезапускает Скрипт загружает локальный файл, проверяет его до замены, перезапускает
службу и проверяет health. При ошибке после замены восстанавливает файл службу и проверяет health. При ошибке после замены восстанавливает файл
перед текущей попыткой. База данных и настройки не заменяются. перед текущей попыткой. База данных и настройки не заменяются.
@@ -33,8 +33,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\
``` ```
Откат использует неизменяемую копию первого состояния до установки: Откат использует неизменяемую копию первого состояния до установки:
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v114`. `/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v115`.
Успешное завершение: `VPS_WIDGETS_V114_Rollback_OK`. Успешное завершение: `VPS_WIDGETS_V115_Rollback_OK`.
## Локальные проверки ## Локальные проверки
+2 -2
View File
@@ -1,4 +1,4 @@
# Несколько WAN интерфейсов и резервирование (v114) # Несколько WAN интерфейсов и резервирование (v115)
Кнопка **Выбрать интерфейсы** раскрывает список с галочками. Можно отметить Кнопка **Выбрать интерфейсы** раскрывает список с галочками. Можно отметить
один, два, три и больше интерфейсов. Список содержит имена один, два, три и больше интерфейсов. Список содержит имена
@@ -46,7 +46,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\
Скрипт устанавливает CGI, LuCI, агент, WAN helper и hotplug вместе. До замены Скрипт устанавливает CGI, LuCI, агент, WAN helper и hotplug вместе. До замены
сохраняются прежние файлы, UCI-настройки и Xray config в сохраняются прежние файлы, UCI-настройки и Xray config в
`/root/owrt-remote-backup-before-wan-multi-v114`. `/root/owrt-remote-backup-before-wan-multi-v115`.
Успех подтверждает `WAN_MULTI_ROUTER_Install_OK`. После установки обновить Успех подтверждает `WAN_MULTI_ROUTER_Install_OK`. После установки обновить
панель роутера через Ctrl+F5, отметить интерфейсы и сохранить выбор. панель роутера через Ctrl+F5, отметить интерфейсы и сохранить выбор.
VPS обновлять не требуется. Старый `deploy-wan-interface-picker.ps1` VPS обновлять не требуется. Старый `deploy-wan-interface-picker.ps1`
+3 -3
View File
@@ -1,4 +1,4 @@
# Исправление запуска прямого WAN в v114 # Исправление запуска прямого WAN в v115
На проблемном роутере обычный `wan` был поднят, имел IPv4-адрес, На проблемном роутере обычный `wan` был поднят, имел IPv4-адрес,
маршрут и рабочий DNS. Проверка `ip -4 route show table 210` возвращала маршрут и рабочий DNS. Проверка `ip -4 route show table 210` возвращала
@@ -16,7 +16,7 @@ instance после шести падений. Из-за остановленн
конфигурации останавливают агент до запуска Xray. конфигурации останавливают агент до запуска Xray.
Изменены только `files/usr/lib/owrt-remote/wan.sh` и Изменены только `files/usr/lib/owrt-remote/wan.sh` и
`files/usr/sbin/owrt-remote`. Версия остаётся v114. Настройки Podkop, `files/usr/sbin/owrt-remote`. Версия остаётся v115. Настройки Podkop,
LAN и источники установки GitHub/GitLab не меняются. Обновление VPS LAN и источники установки GitHub/GitLab не меняются. Обновление VPS
для этого исправления не требуется. для этого исправления не требуется.
@@ -28,7 +28,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\
Скрипт перед заменой проверяет синтаксис и подготовку WAN новым helper, Скрипт перед заменой проверяет синтаксис и подготовку WAN новым helper,
сохраняет агент, helper, UCI и Xray-конфигурацию в сохраняет агент, helper, UCI и Xray-конфигурацию в
`/root/owrt-remote-backup-before-wan-stability-v114`. Сохранённая копия `/root/owrt-remote-backup-before-wan-stability-v115`. Сохранённая копия
не перезаписывается при повторной установке. После замены выполняются не перезаписывается при повторной установке. После замены выполняются
перезапуск, проверка процесса Xray и настоящий heartbeat до Hub. перезапуск, проверка процесса Xray и настоящий heartbeat до Hub.
При ошибке восстанавливается состояние до текущей попытки. При ошибке восстанавливается состояние до текущей попытки.
+4 -4
View File
@@ -1,4 +1,4 @@
# Применение OpenWrt config через панель роутера (v114) # Применение OpenWrt config через панель роутера (v115)
При отправке textarea браузер кодирует переносы строк как CRLF. CGI При отправке textarea браузер кодирует переносы строк как CRLF. CGI
декодировал их без нормализации и записывал CR в исполняемый shell-скрипт. декодировал их без нормализации и записывал CR в исполняемый shell-скрипт.
@@ -22,7 +22,7 @@ CRLF и LF, heredoc, пустые строки, кодированные сим
Скрипт обновляет только CGI на роутере. VPS обновлять для этого фикса Скрипт обновляет только CGI на роутере. VPS обновлять для этого фикса
не требуется. До замены сохраняется первая резервная копия CGI: не требуется. До замены сохраняется первая резервная копия CGI:
`/root/owrt-remote-backup-before-xray-apply-v114/owrt-remote`. `/root/owrt-remote-backup-before-xray-apply-v115/owrt-remote`.
Из PowerShell Windows 11; замените IP, если адрес роутера отличается: Из PowerShell Windows 11; замените IP, если адрес роутера отличается:
@@ -53,7 +53,7 @@ python tests/test_xray_apply.py -v
Переносы строк в формах описаны в [стандарте HTML](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html). Переносы строк в формах описаны в [стандарте HTML](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html).
## Мобильная вставка команд (локальный фикс v114) ## Мобильная вставка команд (локальный фикс v115)
Воспроизведён отдельный случай `rc=255`: в строке Воспроизведён отдельный случай `rc=255`: в строке
`uci set owrtremote.main.router_name=‘Дом у моря’` типографские кавычки `uci set owrtremote.main.router_name=‘Дом у моря’` типографские кавычки
@@ -77,7 +77,7 @@ python tests/test_xray_apply.py -v
Обновляется только `/www/cgi-bin/owrt-remote` на роутере, без перезапуска Обновляется только `/www/cgi-bin/owrt-remote` на роутере, без перезапуска
служб и изменений настроек при установке. Резервная копия отдельная: служб и изменений настроек при установке. Резервная копия отдельная:
`/root/owrt-remote-backup-before-xray-mobile-v114/owrt-remote`. `/root/owrt-remote-backup-before-xray-mobile-v115/owrt-remote`.
Установка из PowerShell Windows 11: Установка из PowerShell Windows 11:
+156
View File
@@ -0,0 +1,156 @@
"""Exercise the real RAM journal and authorized router CGI with temporary files."""
import concurrent.futures
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from urllib.parse import urlencode
ROOT = Path(__file__).resolve().parents[1]
GIT_BIN = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/usr/bin'
SH = str(GIT_BIN / 'sh.exe') if os.name == 'nt' else shutil.which('sh')
@unittest.skipUnless(SH, 'POSIX shell required')
class GlobalLogTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='global-log-tests-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.log_dir = self.root / 'journal'
self.helper = self.root / 'logs.sh'
source = (ROOT / 'files/usr/lib/owrt-remote/logs.sh').read_text(encoding='utf-8')
source = source.replace('log_clock() { cut -d. -f1 /proc/uptime; }',
'log_clock() { echo "${TEST_UPTIME:-1000}"; }')
self.helper.write_text(source, encoding='utf-8', newline='\n')
self.cgi = self.root / 'cgi'
self.cgi.write_text((ROOT / 'files/www/cgi-bin/owrt-remote').read_text(encoding='utf-8'),
encoding='utf-8', newline='\n')
self.key = self.root / 'key'
self.key.write_text('test-key', encoding='utf-8')
self.env = {**os.environ, 'OWRT_REMOTE_LOG_DIR': self.log_dir.as_posix(),
'OWRT_REMOTE_LOG_HELPER': self.helper.as_posix(), 'TMPDIR': self.root.as_posix(),
'KEY_FILE': self.key.as_posix(), 'TEST_UPTIME': '1000'}
if os.name == 'nt':
self.env['PATH'] = str(GIT_BIN) + os.pathsep + self.env['PATH']
def helper_call(self, command, text='', *args, env=None):
result = subprocess.run([SH, self.helper.as_posix(), command, *args], input=text,
encoding='utf-8', capture_output=True, env=env or self.env, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout
def cgi_call(self, action, key='test-key', method='GET'):
query = urlencode({'action': action, 'key': key})
result = subprocess.run([SH, self.cgi.as_posix()], input='', encoding='utf-8',
capture_output=True, timeout=20,
env={**self.env, 'QUERY_STRING': query, 'REQUEST_METHOD': method})
self.assertEqual(result.returncode, 0, result.stderr)
return result.stdout
def test_download_is_attachment_and_live_is_bounded_plain_text(self):
self.helper_call('append', 'Xray connected\n' + 'x' * 1024 + '\n')
downloaded = self.cgi_call('logs_download')
self.assertIn('Content-Disposition: attachment; filename="owrt-remote-global-', downloaded)
self.assertIn('Xray connected', downloaded)
self.assertIn('Cache-Control: no-store', downloaded)
for _ in range(70):
self.helper_call('append', 'y' * 1024 + '\n')
live = self.cgi_call('logs_live').split('\n\n', 1)[1]
self.assertLessEqual(len(live.encode()), 65536)
self.assertNotIn('Content-Disposition', self.cgi_call('logs_live'))
def test_clear_requires_post_and_correct_key(self):
self.helper_call('append', 'retain this event\n')
self.assertIn('Доступ запрещен', self.cgi_call('logs_download', key='wrong'))
self.assertIn('Доступ запрещен', self.cgi_call('logs_clear', key='wrong', method='POST'))
self.assertIn('405 Method Not Allowed', self.cgi_call('logs_clear'))
self.assertIn('retain this event', self.helper_call('read'))
self.assertIn('Логи Remote очищены', self.cgi_call('logs_clear', method='POST'))
self.assertEqual(self.helper_call('read'), '')
self.helper_call('append', 'new event\n')
self.assertEqual(self.helper_call('read'), 'new event\n')
def test_retention_uses_uptime_and_clears_on_reboot(self):
self.helper_call('append', 'old event\n')
self.assertIn('old event', self.helper_call('read', env={**self.env, 'TEST_UPTIME': '87399'}))
self.assertEqual(self.helper_call('read', env={**self.env, 'TEST_UPTIME': '87400'}), '')
self.helper_call('append', 'after daily clear\n', env={**self.env, 'TEST_UPTIME': '87401'})
self.assertEqual(self.helper_call('read', env={**self.env, 'TEST_UPTIME': '20'}), '')
def test_rotation_retains_recent_log_and_clear_removes_both(self):
self.helper_call('clear')
current = self.log_dir / 'current.log'
current.write_text('A' * 1048576, encoding='utf-8')
self.helper_call('append', 'second file\n')
self.assertTrue((self.log_dir / 'previous.log').exists())
self.assertEqual(current.read_text(), 'second file\n')
current.write_text('B' * 1048576, encoding='utf-8')
self.helper_call('append', 'third file\n')
output = self.helper_call('read')
self.assertNotIn('A', output)
self.assertTrue(output.endswith('third file\n'))
self.helper_call('clear')
self.assertFalse((self.log_dir / 'previous.log').exists())
self.assertEqual(current.read_text(), '')
def test_secrets_are_redacted_before_storage_and_html_is_literal(self):
text = ('Heartbeat OK\nuci set owrtremote.main.hub_token=SECRET_TOKEN\n'
'Authorization: Bearer SECRET_AUTH\nhttps://hub.test/?key=SECRET_KEY\n'
'{"uuid":"SECRET_UUID"}\nabcdef12-abcd-1234-abcd-abcdef123456\n<script>alert(1)</script>\n')
self.helper_call('append', text)
stored = self.helper_call('read')
self.assertNotIn('SECRET_', stored)
self.assertNotIn('abcdef12-abcd-1234-abcd-abcdef123456', stored)
self.assertIn('Heartbeat OK', stored)
self.assertIn('<script>alert(1)</script>', stored)
self.assertIn('Content-Type: text/plain', self.cgi_call('logs_live'))
def test_parallel_events_do_not_corrupt_or_drop_lines(self):
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(lambda i: self.helper_call('append', f'event-{i}\n'), range(12)))
self.assertEqual(set(self.helper_call('read').splitlines()), {f'event-{i}' for i in range(12)})
self.assertFalse((self.log_dir / 'lock').exists())
def test_stale_lock_recovers(self):
self.helper_call('clear')
lock = self.log_dir / 'lock'
lock.mkdir()
(lock / 'pid').write_text('99999999')
self.helper_call('append', 'recovered\n')
self.assertEqual(self.helper_call('read'), 'recovered\n')
def test_missing_collector_is_reported(self):
self.helper.unlink()
self.assertIn('503 Service Unavailable', self.cgi_call('logs_live'))
def test_empty_lock_left_by_killed_writer_recovers(self):
self.helper_call('clear')
(self.log_dir / 'lock').mkdir()
self.helper_call('append', 'after empty lock\n')
self.assertEqual(self.helper_call('read'), 'after empty lock\n')
def test_collector_failure_cleans_both_children_and_fifo(self):
source = self.helper.read_text(encoding='utf-8')
mocks = '''
log_init() { return 0; }
mkfifo() { return 0; }
logread() { return 0; }
log_lock() { return 1; }
kill() { printf 'KILL=%s\\n' "$*"; }
wait() { return 0; }
rm() { printf 'REMOVE=%s\\n' "$*"; }
'''
self.helper.write_text(source.replace('case "${1:-}" in', mocks + '\ncase "${1:-}" in', 1),
encoding='utf-8', newline='\n')
result = subprocess.run([SH, self.helper.as_posix(), 'collect'], capture_output=True,
encoding='utf-8', env=self.env, timeout=10)
self.assertNotEqual(result.returncode, 0)
self.assertEqual(result.stdout.count('KILL='), 2)
self.assertIn('REMOVE=-f ' + self.log_dir.as_posix() + '/stream.', result.stdout)
if __name__ == '__main__':
unittest.main()
+132
View File
@@ -0,0 +1,132 @@
"""Install/rollback journal files against a sandbox, never a real router."""
import os
import re
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
GIT_BIN = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/usr/bin'
SH = str(GIT_BIN / 'sh.exe') if os.name == 'nt' else shutil.which('sh')
@unittest.skipUnless(SH, 'POSIX shell required')
class GlobalLogsDeploymentTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='global-log-deploy-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.targets = {
'cgi': '/www/cgi-bin/owrt-remote', 'agent': '/usr/sbin/owrt-remote',
'init': '/etc/init.d/owrt-remote', 'logs.sh': '/usr/lib/owrt-remote/logs.sh',
'logs-init': '/etc/init.d/owrt-remote-logs',
'luci': '/www/luci-static/resources/view/owrt_remote.js',
}
self.initial = {}
for item in ('cgi', 'agent', 'init', 'luci'):
path = self.root / self.targets[item].lstrip('/')
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('#!/bin/sh\necho previous-' + item + '\n', encoding='utf-8', newline='\n')
self.initial[item] = path.read_bytes()
self.backup = self.root / 'backup'
source = (ROOT / 'vps/deploy-global-logs.ps1').read_text(encoding='utf-8')
self.script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
# Absolute paths are replaced only in this disposable test copy.
mappings = {target: (self.root / target.lstrip('/')).as_posix() for target in self.targets.values()}
mappings['/usr/lib/owrt-remote'] = (self.root / 'usr/lib/owrt-remote').as_posix()
mappings['/www/luci-static/resources/view'] = (self.root / 'www/luci-static/resources/view').as_posix()
mappings['/tmp/luci-indexcache'] = (self.root / 'luci-indexcache').as_posix()
mappings['/tmp/luci-modulecache'] = (self.root / 'luci-modulecache').as_posix()
mappings['/etc/init.d/rpcd'] = (self.root / 'etc/init.d/rpcd').as_posix()
mappings['/etc/init.d/uhttpd'] = (self.root / 'etc/init.d/uhttpd').as_posix()
mappings['/tmp/owrt-remote-logs'] = (self.root / 'journal').as_posix()
mappings['/root/owrt-remote-backup-before-global-logs-v115'] = self.backup.as_posix()
pattern = '|'.join(re.escape(target) for target in sorted(mappings, key=len, reverse=True))
self.script = re.sub(pattern, lambda match: mappings[match.group()], self.script)
# Existing sandbox service scripts only print markers. Mock readiness.
mocks = '''
logread() { return 0; }
ubus() { printf '{"running": true}\\n'; }
mkfifo() { return 0; }
logger() { printf '%s\\n' "$3" | sh "$TEST_LOG_HELPER" append; }
'''
self.script = self.script.replace('for item in cgi agent init;', mocks + '\nfor item in cgi agent init;', 1)
self.env = {**os.environ, 'OWRT_REMOTE_LOG_DIR': (self.root / 'journal').as_posix()}
self.env['TEST_LOG_HELPER'] = (self.root / 'usr/lib/owrt-remote/logs.sh').as_posix()
if os.name == 'nt':
self.env['PATH'] = str(GIT_BIN) + os.pathsep + self.env['PATH']
def deploy(self, action, bad=False, fail_verify=False):
stage = self.root / 'stage'
stage.mkdir()
candidates = {
'cgi': 'files/www/cgi-bin/owrt-remote', 'agent': 'files/usr/sbin/owrt-remote',
'init': 'files/etc/init.d/owrt-remote', 'logs.sh': 'files/usr/lib/owrt-remote/logs.sh',
'logs-init': 'files/etc/init.d/owrt-remote-logs',
'luci': 'files/www/luci-static/resources/view/owrt_remote.js',
}
if action == 'Install':
for item, source in candidates.items():
text = (ROOT / source).read_text(encoding='utf-8')
if item == 'logs.sh':
text = text.replace('log_clock() { cut -d. -f1 /proc/uptime; }', 'log_clock() { echo 1000; }')
if item == 'logs-init':
text = '#!/bin/sh\necho logs-service-$1\n'
if bad and item == 'cgi':
text = '#!/bin/sh\nif true; then\n'
stage.joinpath(item).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('__ACTION__', action)
if fail_verify:
script = script.replace('cmp "$stage/$item" "$path"', 'false')
result = subprocess.run([SH], input=script, encoding='utf-8', capture_output=True,
env=self.env, timeout=30)
self.assertFalse(stage.exists())
self.assertFalse(list(self.root.rglob('*.new-sandbox')))
return result
def assert_initial(self):
for item, data in self.initial.items():
self.assertEqual((self.root / self.targets[item].lstrip('/')).read_bytes(), data)
for item in ('logs.sh', 'logs-init'):
self.assertFalse((self.root / self.targets[item].lstrip('/')).exists())
def test_install_then_rollback_retains_first_backup(self):
for _ in range(2):
result = self.deploy('Install')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('GLOBAL_LOGS_ROUTER_Install_OK', result.stdout)
for item in ('cgi', 'luci'):
installed = self.root / self.targets[item].lstrip('/')
self.assertIn('v115', installed.read_text(encoding='utf-8'))
for item, data in self.initial.items():
self.assertEqual(self.backup.joinpath(item).read_bytes(), data)
result = self.deploy('Rollback')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('GLOBAL_LOGS_ROUTER_Rollback_OK', result.stdout)
self.assert_initial()
def test_missing_backup_changes_nothing(self):
result = self.deploy('Rollback')
self.assertNotEqual(result.returncode, 0)
self.assertIn('No complete backup:', result.stderr)
self.assert_initial()
def test_invalid_candidate_rejected_before_backup(self):
result = self.deploy('Install', bad=True)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.backup.exists())
self.assert_initial()
def test_failed_verification_restores_all_previous_files(self):
result = self.deploy('Install', fail_verify=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('Restoring files from this attempt.', result.stderr)
self.assert_initial()
if __name__ == '__main__':
unittest.main()
+93
View File
@@ -0,0 +1,93 @@
// Real desktop/mobile browser: literal log text, scrolling, clear and polling.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { chromium } = require('playwright');
const root = path.resolve('.test-output/global-logs');
let text = Array.from({length: 150}, (_, i) => `Heartbeat ${i}: OK`).join('\n');
let reads = 0, clears = 0;
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.searchParams.get('action') === 'logs_live') {
reads++;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
return res.end(text);
}
if (url.searchParams.get('action') === 'logs_clear') {
assert.equal(req.method, 'POST');
clears++;
text = '';
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
return res.end('Логи Remote очищены.');
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end(fs.readFileSync(path.join(root, 'router.html')));
});
(async () => {
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({headless: true, channel: 'chrome'});
try {
for (const mobile of [false, true]) {
text = Array.from({length: 150}, (_, i) => `Heartbeat ${i}: OK`).join('\n');
const page = await browser.newPage({viewport: mobile ? {width: 390, height: 844} : {width: 1280, height: 900}});
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(`http://127.0.0.1:${server.address().port}/cgi-bin/owrt-remote?key=preview-key`);
assert.equal(await page.locator('#globalLogsPanel').isVisible(), false);
const vpn = await page.getByRole('link', {name: 'NetHaven VPN'}).boundingBox();
const toggle = await page.locator('#globalLogsToggle').boundingBox();
assert(Math.abs(toggle.y - vpn.y) < 3, 'logs button stays alongside VPN');
assert(Math.abs(toggle.width - vpn.width) < 1, 'same pill width');
assert.equal(await page.locator('#globalLogsToggle').evaluate(el => getComputedStyle(el).backgroundColor), 'rgb(34, 197, 94)');
if (mobile) {
const telegram = await page.getByRole('link', {name: 'Telegram', exact: true}).boundingBox();
const github = await page.getByRole('link', {name: 'GitHub', exact: true}).boundingBox();
const banner = await page.locator('.appBanner').boundingBox();
const back = await page.getByRole('link', {name: 'Вернуться в службы OpenWrt'}).boundingBox();
assert.equal(telegram.y, github.y, 'social links occupy one row');
assert.equal(telegram.width, toggle.width, 'all paired buttons have equal width');
assert.equal(telegram.x, vpn.x, 'left column aligns across header');
assert.equal(github.x, toggle.x, 'right column aligns across header');
assert.equal(banner.width, back.width, 'title and return span same width');
assert.equal(telegram.height, toggle.height, 'header buttons have equal height');
assert(vpn.y >= telegram.y + telegram.height + 8, 'header rows have spacing');
assert(back.y >= toggle.y + toggle.height + 8, 'return follows paired buttons');
}
assert(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth));
const beforeOpen = reads;
await page.locator('#globalLogsToggle').click();
assert.equal(await page.locator('#globalLogsPanel').isVisible(), true);
await page.waitForFunction(() => document.querySelector('#globalLogsText').textContent.includes('Heartbeat 149'));
assert.equal(reads, beforeOpen + 1, 'opening displays existing records immediately');
assert.equal(await page.locator('#globalLogsLive').textContent(), 'Запустить в реальном времени');
await page.waitForTimeout(3300);
assert.equal(reads, beforeOpen + 1, 'snapshot does not start automatic polling');
await page.locator('#globalLogsLive').click();
await page.waitForFunction(() => document.querySelector('#globalLogsText').textContent.includes('Heartbeat 149'));
assert.equal(await page.locator('#globalLogsLive').textContent(), 'Остановить просмотр');
await page.locator('#globalLogsText').evaluate(el => {el.scrollTop = 40;});
text += '\nnew event\n<script>window.bad=1</script>';
await page.waitForFunction(() => document.querySelector('#globalLogsText').textContent.includes('new event'));
assert.equal(await page.locator('#globalLogsText').evaluate(el => el.scrollTop), 40);
assert.equal(await page.evaluate(() => window.bad), undefined);
assert.equal(await page.locator('#globalLogsText script').count(), 0);
await page.screenshot({path: path.join(root, mobile ? 'mobile.png' : 'desktop.png'), fullPage: true});
const before = clears;
await page.locator('#globalLogsClear').click();
await page.waitForFunction(() => document.querySelector('#globalLogsText').textContent.includes('пуст'));
assert.equal(clears, before + 1);
await page.locator('#globalLogsClose').click();
assert.equal(await page.locator('#globalLogsPanel').isVisible(), false);
const stoppedAt = reads;
await page.waitForTimeout(3300);
assert.equal(reads, stoppedAt, 'closing panel stops polling');
assert.deepEqual(errors, []);
await page.close();
console.log('GLOBAL_LOGS_UI_OK', mobile ? 'mobile' : 'desktop');
}
} finally {
await browser.close();
server.close();
}
})().catch(error => {console.error(error); server.close(); process.exitCode = 1;});
+1 -1
View File
@@ -131,7 +131,7 @@ class HubFixture:
assert "groups" in json.loads(self.request("/api/router-groups")) assert "groups" in json.loads(self.request("/api/router-groups"))
assert "notifications" in json.loads(self.request("/api/notifications")) assert "notifications" in json.loads(self.request("/api/notifications"))
assert self.request("/access/test-router/") == b"router proxy fixture" assert self.request("/access/test-router/") == b"router proxy fixture"
assert b"v114" in self.request("/") assert b"v115" in self.request("/")
self.app.snapshot_router_states() self.app.snapshot_router_states()
def __exit__(self, *args): def __exit__(self, *args):
+1 -1
View File
@@ -31,7 +31,7 @@ class WanStabilityRollbackTests(unittest.TestCase):
source = (ROOT / "vps/deploy-wan-stability-fix.ps1").read_text(encoding="utf-8") source = (ROOT / "vps/deploy-wan-stability-fix.ps1").read_text(encoding="utf-8")
script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0] script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
script = script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(self.stage.as_posix())) script = script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(self.stage.as_posix()))
script = script.replace('backup=/root/owrt-remote-backup-before-wan-stability-v114', 'backup=' + shlex.quote(self.backup.as_posix())) script = script.replace('backup=/root/owrt-remote-backup-before-wan-stability-v115', 'backup=' + shlex.quote(self.backup.as_posix()))
script = script.replace('config=/etc/config/owrtremote', 'config=' + shlex.quote(self.files["config"].as_posix())) script = script.replace('config=/etc/config/owrtremote', 'config=' + shlex.quote(self.files["config"].as_posix()))
for name, original in (("agent", "/usr/sbin/owrt-remote"), ("wan.sh", "/usr/lib/owrt-remote/wan.sh")): for name, original in (("agent", "/usr/sbin/owrt-remote"), ("wan.sh", "/usr/lib/owrt-remote/wan.sh")):
script = script.replace('printf ' + original + ' ;;', "printf '%s' " + shlex.quote(self.files[name].as_posix()) + ' ;;') script = script.replace('printf ' + original + ' ;;', "printf '%s' " + shlex.quote(self.files[name].as_posix()) + ' ;;')
+1 -1
View File
@@ -29,7 +29,7 @@ class XrayMobileDeploymentTests(unittest.TestCase):
source = (ROOT / "vps/deploy-xray-mobile-fix.ps1").read_text(encoding="utf-8") 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 = 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("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-v114", self.script = self.script.replace("backup_dir=/root/owrt-remote-backup-before-xray-mobile-v115",
"backup_dir=" + shlex.quote(self.backup_dir.as_posix())) "backup_dir=" + shlex.quote(self.backup_dir.as_posix()))
def deploy(self, action, content=None, fail_verify=False): def deploy(self, action, content=None, fail_verify=False):
+8
View File
@@ -18,8 +18,16 @@ if [ -x "$(target_path etc/init.d/owrt-remote)" ]; then
"$(target_path etc/init.d/owrt-remote)" disable >/dev/null 2>&1 || true "$(target_path etc/init.d/owrt-remote)" disable >/dev/null 2>&1 || true
fi fi
if [ -x "$(target_path etc/init.d/owrt-remote-logs)" ]; then
"$(target_path etc/init.d/owrt-remote-logs)" stop >/dev/null 2>&1 || true
"$(target_path etc/init.d/owrt-remote-logs)" disable >/dev/null 2>&1 || true
fi
rmf usr/sbin/owrt-remote rmf usr/sbin/owrt-remote
rmf usr/lib/owrt-remote/wan.sh rmf usr/lib/owrt-remote/wan.sh
rmf usr/lib/owrt-remote/logs.sh
rmf etc/init.d/owrt-remote-logs
rm -rf "$(target_path tmp/owrt-remote-logs)"
rmdir "$(target_path usr/lib/owrt-remote)" 2>/dev/null || true rmdir "$(target_path usr/lib/owrt-remote)" 2>/dev/null || true
rmf etc/init.d/owrt-remote rmf etc/init.d/owrt-remote
rmf www/cgi-bin/owrt-remote rmf www/cgi-bin/owrt-remote
+192
View File
@@ -0,0 +1,192 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Router,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-global-logs-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-global-logs-v115
items='cgi agent init logs.sh logs-init luci'
changed=0
phase=preflight
item_path() {
case "$1" in
cgi) echo /www/cgi-bin/owrt-remote ;;
agent) echo /usr/sbin/owrt-remote ;;
init) echo /etc/init.d/owrt-remote ;;
logs.sh) echo /usr/lib/owrt-remote/logs.sh ;;
logs-init) echo /etc/init.d/owrt-remote-logs ;;
luci) echo /www/luci-static/resources/view/owrt_remote.js ;;
esac
}
refresh_router_ui() {
rm -rf /tmp/luci-indexcache /tmp/luci-modulecache
if [ -x /etc/init.d/rpcd ]; then /etc/init.d/rpcd restart || true; fi
if [ -x /etc/init.d/uhttpd ]; then /etc/init.d/uhttpd reload || true; fi
}
save_files() {
local dir item path
dir=$1
mkdir -p "$dir"
chmod 700 "$dir"
for item in $items; do
path=$(item_path "$item")
if [ -e "$path" ]; then cp -p "$path" "$dir/$item"; else : >"$dir/$item.absent"; fi
done
if [ -x /etc/init.d/owrt-remote-logs ] && /etc/init.d/owrt-remote-logs enabled; then : >"$dir/logs-enabled"; fi
if ubus call service list '{"name":"owrt-remote-logs"}' 2>/dev/null | grep -q '"running": true'; then : >"$dir/logs-running"; fi
if /usr/sbin/owrt-remote status 2>/dev/null | grep -q '^xray_state: running'; then : >"$dir/tunnel-running"; fi
: >"$dir/complete"
}
validate_backup() {
local dir item
dir=$1
[ -f "$dir/complete" ] || return 1
for item in $items; do
[ -s "$dir/$item" ] || [ -f "$dir/$item.absent" ] || return 1
done
}
restore_files() {
local dir item path
dir=$1
validate_backup "$dir" || { echo "Incomplete backup: $dir" >&2; return 1; }
if [ -x /etc/init.d/owrt-remote-logs ]; then
/etc/init.d/owrt-remote-logs stop || true
/etc/init.d/owrt-remote-logs disable || true
fi
for item in $items; do
path=$(item_path "$item")
if [ -f "$dir/$item.absent" ]; then
rm -f "$path" || return 1
else
cp -p "$dir/$item" "$path" || return 1
fi
done
if [ -x /etc/init.d/owrt-remote-logs ]; then
[ ! -f "$dir/logs-enabled" ] || /etc/init.d/owrt-remote-logs enable
[ ! -f "$dir/logs-running" ] || /etc/init.d/owrt-remote-logs start
else
rm -rf /tmp/owrt-remote-logs
fi
if [ -f "$stage/previous/tunnel-running" ]; then /etc/init.d/owrt-remote restart; fi
refresh_router_ui
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
if [ "$changed" = 1 ]; then
echo 'Restoring files from this attempt.' >&2
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
fi
fi
for item in $items; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
for item in cgi agent init; do path=$(item_path "$item"); test -s "$path"; done
if [ '__ACTION__' = Install ]; then
for item in $items; do test -s "$stage/$item"; done
for item in cgi agent init logs.sh logs-init; do sh -n "$stage/$item"; done
command -v logread >/dev/null
command -v ubus >/dev/null
command -v mkfifo >/dev/null
grep -F -q 'globalLogsToggle' "$stage/cgi"
for item in cgi luci; do grep -F -q 'v115' "$stage/$item"; done
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
phase=backup
if [ ! -e "$backup" ]; then save_files "$stage/retained"; mv "$stage/retained" "$backup"; fi
validate_backup "$backup" || { echo "Incomplete backup: $backup. Nothing changed." >&2; exit 1; }
save_files "$stage/previous"
phase=install
changed=1
if [ -x /etc/init.d/owrt-remote-logs ]; then /etc/init.d/owrt-remote-logs stop; fi
mkdir -p /usr/lib/owrt-remote /www/luci-static/resources/view
for item in $items; do
path=$(item_path "$item")
cp "$stage/$item" "$path.new-__UPLOAD_NAME__"
case "$item" in logs.sh|luci) chmod 644 "$path.new-__UPLOAD_NAME__" ;; *) chmod 755 "$path.new-__UPLOAD_NAME__" ;; esac
mv -f "$path.new-__UPLOAD_NAME__" "$path"
done
/etc/init.d/owrt-remote-logs enable
/etc/init.d/owrt-remote-logs start
phase=verify
ready=0
for attempt in 1 2 3 4 5; do
if ubus call service list '{"name":"owrt-remote-logs"}' | grep -q '"running": true'; then ready=1; break; fi
sleep 1
done
if [ "$ready" != 1 ]; then echo 'Log collector did not start.' >&2; logread -e owrt-remote | tail -n 30 >&2; exit 1; fi
marker='Глобал логи: collector-__UPLOAD_NAME__'
ready=0
for attempt in 1 2 3 4 5; do
logger -t owrt-remote "$marker"
sleep 1
if sh /usr/lib/owrt-remote/logs.sh read | grep -F -q "$marker"; then ready=1; break; fi
done
if [ "$ready" != 1 ]; then echo 'Log collector is running but did not capture the test event.' >&2; exit 1; fi
for item in $items; do path=$(item_path "$item"); cmp "$stage/$item" "$path"; done
if [ -f "$stage/previous/tunnel-running" ]; then
phase=tunnel-restart
/etc/init.d/owrt-remote restart
ready=0
for attempt in 1 2 3 4 5 6 7 8 9 10; do
if /usr/sbin/owrt-remote status | grep -q '^xray_state: running'; then ready=1; break; fi
sleep 1
done
if [ "$ready" != 1 ]; then echo 'Tunnel did not restart.' >&2; logread -e owrt-remote | tail -n 30 >&2; exit 1; fi
fi
refresh_router_ui
echo 'Log collector: running. Router settings preserved.'
else
validate_backup "$backup" || { echo "No complete backup: $backup. Nothing changed." >&2; exit 1; }
save_files "$stage/previous"
changed=1
phase=rollback
restore_files "$backup"
fi
printf 'Backup: %s\n' "$backup"
printf '\nGLOBAL_LOGS_ROUTER_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
$Files = @{
'cgi' = 'files\www\cgi-bin\owrt-remote'
'agent' = 'files\usr\sbin\owrt-remote'
'init' = 'files\etc\init.d\owrt-remote'
'logs.sh' = 'files\usr\lib\owrt-remote\logs.sh'
'logs-init' = 'files\etc\init.d\owrt-remote-logs'
'luci' = 'files\www\luci-static\resources\view\owrt_remote.js'
}
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
foreach ($Item in $Files.GetEnumerator()) {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -r -- $StageRoot "${Router}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Global logs $Action finished successfully. Refresh the router panel with Ctrl+F5."
} finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ $RemoteScript = @'
#!/bin/sh #!/bin/sh
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v114 backup=/root/owrt-remote-backup-before-heartbeat-redirect-v115
agent=/usr/sbin/owrt-remote agent=/usr/sbin/owrt-remote
wan=/usr/lib/owrt-remote/wan.sh wan=/usr/lib/owrt-remote/wan.sh
changed=0 changed=0
+9 -9
View File
@@ -5,7 +5,7 @@ param(
[string]$PinnedVpsHost = '193.233.82.38', [string]$PinnedVpsHost = '193.233.82.38',
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$WanInterface = 'wan', [ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$WanInterface = 'wan',
[switch]$PreserveConnectionSettings, [switch]$PreserveConnectionSettings,
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v114', [ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v115',
[switch]$PrepareOnly [switch]$PrepareOnly
) )
@@ -90,7 +90,7 @@ test -s "$config"
if [ '__ACTION__' = Install ]; then if [ '__ACTION__' = Install ]; then
for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done
test -s "$stage/luci" test -s "$stage/luci"
for item in cgi luci; do grep -F -q 'v114' "$stage/$item"; done for item in cgi luci; do grep -F -q 'v115' "$stage/$item"; done
# curl is needed to preserve HTTPS SNI and bypass the local DNS/proxy. # 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 curl >/dev/null 2>&1; then
if command -v opkg >/dev/null 2>&1; then opkg update && opkg install curl ca-bundle 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 exit 1
fi fi
/usr/sbin/owrt-remote status /usr/sbin/owrt-remote status
grep -F -q 'v114' /www/cgi-bin/owrt-remote grep -F -q 'v115' /www/cgi-bin/owrt-remote
grep -F -q 'v114' /www/luci-static/resources/view/owrt_remote.js grep -F -q 'v115' /www/luci-static/resources/view/owrt_remote.js
echo HOST_POLICY_ROUTER_V114_OK echo HOST_POLICY_ROUTER_V115_OK
else else
test -f "$backup/complete" test -f "$backup/complete"
save_files "$stage/previous" save_files "$stage/previous"
changed=1 changed=1
restore_files "$backup" restore_files "$backup"
/usr/sbin/owrt-remote status /usr/sbin/owrt-remote status
echo HOST_POLICY_ROUTER_V114_ROLLBACK_OK echo HOST_POLICY_ROUTER_V115_ROLLBACK_OK
fi fi
'@ '@
} else { } else {
@@ -180,7 +180,7 @@ fi
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v115
changed=0 changed=0
cleanup() { cleanup() {
code=$? code=$?
@@ -200,7 +200,7 @@ test -s "$target"
python_bin=/opt/owrt-remote/venv/bin/python python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3 [ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then if [ '__ACTION__' = Install ]; then
grep -F -q 'v114' "$stage/hub.py" grep -F -q 'v115' "$stage/hub.py"
"$python_bin" -m py_compile "$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_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 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 done
test "$healthy" = 1 test "$healthy" = 1
cmp "$candidate" "$target" cmp "$candidate" "$target"
printf '\nHOST_POLICY_VPS_V114_%s_OK\n' '__ACTION__' printf '\nHOST_POLICY_VPS_V115_%s_OK\n' '__ACTION__'
'@ '@
} }
+6 -6
View File
@@ -34,7 +34,7 @@ if ($Target -eq 'Router') {
#!/bin/sh #!/bin/sh
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-hub-url-v114 backup=/root/owrt-remote-backup-before-hub-url-v115
chmod 700 "$stage" chmod 700 "$stage"
config=/etc/config/owrtremote config=/etc/config/owrtremote
changed=0 changed=0
@@ -99,7 +99,7 @@ if [ '__ACTION__' = Install ]; then
grep -F -q 'heartbeat_set_url_if_changed()' "$stage/agent" grep -F -q 'heartbeat_set_url_if_changed()' "$stage/agent"
grep -F -q 'reason=https-downgrade' "$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 agent wan.sh; do grep -F -q -- '--post301' "$stage/$item"; done
for item in cgi luci; do grep -F -q 'v114' "$stage/$item"; done for item in cgi luci; do grep -F -q 'v115' "$stage/$item"; done
if [ ! -e "$backup" ]; then if [ ! -e "$backup" ]; then
save_files "$stage/retained-backup" save_files "$stage/retained-backup"
mv "$stage/retained-backup" "$backup" mv "$stage/retained-backup" "$backup"
@@ -138,7 +138,7 @@ else
changed=1 changed=1
restore_files "$backup" restore_files "$backup"
fi fi
printf '\nBackup: %s\nHUB_URL_ROUTER_V114_%s_OK\n' "$backup" '__ACTION__' printf '\nBackup: %s\nHUB_URL_ROUTER_V115_%s_OK\n' "$backup" '__ACTION__'
'@ '@
} else { } else {
$Payloads = @{ $Payloads = @{
@@ -152,7 +152,7 @@ set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
chmod 700 "$stage" chmod 700 "$stage"
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
@@ -174,7 +174,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3 [ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then if [ '__ACTION__' = Install ]; then
grep -F -q 'def router_hub_origins(' "$stage/hub.py" grep -F -q 'def router_hub_origins(' "$stage/hub.py"
grep -F -q 'v114' "$stage/hub.py" grep -F -q 'v115' "$stage/hub.py"
"$python_bin" -m py_compile "$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_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 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 done
test "$healthy" = 1 test "$healthy" = 1
cmp "$source_file" "$target" cmp "$source_file" "$target"
printf '\nBackup: %s\nHUB_URL_VPS_V114_%s_OK\n' "$backup" '__ACTION__' printf '\nBackup: %s\nHUB_URL_VPS_V115_%s_OK\n' "$backup" '__ACTION__'
'@ '@
} }
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__HUB_URL__', $HubUrl) $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__HUB_URL__', $HubUrl)
+2 -2
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
@@ -59,7 +59,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done done
test "$healthy" = 1 test "$healthy" = 1
cmp "$source_file" "$target" cmp "$source_file" "$target"
printf '\nBackup: %s\nONLINE_STATUS_V114_%s_OK\n' "$backup" '__ACTION__' printf '\nBackup: %s\nONLINE_STATUS_V115_%s_OK\n' "$backup" '__ACTION__'
'@ '@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action) $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try { try {
+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
@@ -105,7 +105,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1 exit 1
fi fi
cmp "$source_file" "$target" cmp "$source_file" "$target"
printf '\nBackup: %s\nPASSWORD_LOGOUT_V114_%s_OK\n' "$backup" '__ACTION__' printf '\nBackup: %s\nPASSWORD_LOGOUT_V115_%s_OK\n' "$backup" '__ACTION__'
'@ '@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action) $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
+6 -6
View File
@@ -17,8 +17,8 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v115
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v114.json captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v115.json
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8') source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source) tree = ast.parse(source)
assert 'v114' in source assert 'v115' in source
assert 'v108' not in source assert 'v108' not in source
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
assert 'prepareLoginRecaptcha' in source assert 'prepareLoginRecaptcha' in source
@@ -88,7 +88,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0 test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)" 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' systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RECAPTCHA_V3_V114_OK echo RECAPTCHA_V3_V115_OK
'@ '@
} elseif ($Action -eq 'Rollback') { } elseif ($Action -eq 'Rollback') {
$RemoteScript = @' $RemoteScript = @'
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V114_OK
set -Eeuo pipefail set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v115
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v114.json captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v115.json
candidate=$target.rollback-__UPLOAD_NAME__ candidate=$target.rollback-__UPLOAD_NAME__
changed=0 changed=0
restore_captcha() { restore_captcha() {
+4 -4
View File
@@ -18,7 +18,7 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8') source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source) tree = ast.parse(source)
assert 'v114' in source assert 'v115' in source
assert 'v108' not in source assert 'v108' not in source
factory = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'connect') 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) 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 test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)" 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' systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RESOURCE_FIX_V114_OK echo RESOURCE_FIX_V115_OK
'@ '@
} elseif ($Action -eq 'Rollback') { } elseif ($Action -eq 'Rollback') {
$RemoteScript = @' $RemoteScript = @'
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V114_OK
set -Eeuo pipefail set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v115
candidate=$target.rollback-__UPLOAD_NAME__ candidate=$target.rollback-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1 exit 1
fi fi
cmp "$source_file" "$target" cmp "$source_file" "$target"
printf '\nBackup: %s\nROUTER_CARD_UI_V114_%s_OK\n' "$backup" '__ACTION__' printf '\nBackup: %s\nROUTER_CARD_UI_V115_%s_OK\n' "$backup" '__ACTION__'
'@ '@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action) $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
+146
View File
@@ -0,0 +1,146 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-version-v115-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v115
candidate=$target.new-__UPLOAD_NAME__
changed=0
show_failure() {
echo '--- owrt-remote status ---' >&2
systemctl --no-pager -l status owrt-remote >&2 || true
echo '--- owrt-remote journal ---' >&2
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
echo "Remote step failed with rc=$code" >&2
show_failure
fi
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
echo 'Restoring the previous Hub file...' >&2
cp -p "$stage/previous.py" "$candidate"
mv -f "$candidate" "$target"
systemctl restart owrt-remote || true
fi
rm -f "$candidate"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
test -s "$stage/hub.py"
echo 'Validating candidate...'
"$python_bin" -m py_compile "$stage/hub.py"
"$python_bin" - "$stage/hub.py" <<'PY'
from pathlib import Path
import sys
source = Path(sys.argv[1]).read_text(encoding='utf-8')
required = ('v115',)
if 'v' + '114' in source:
print('Old UI version remains in candidate', file=sys.stderr)
raise SystemExit(1)
missing = [marker for marker in required if marker not in source]
if missing:
for marker in missing:
print('Missing marker:', repr(marker), file=sys.stderr)
raise SystemExit(1)
print('Candidate validation OK')
PY
if [ ! -e "$backup" ]; then
cp -p "$target" "$backup"
fi
source_file="$stage/hub.py"
else
test -s "$backup"
"$python_bin" -m py_compile "$backup"
source_file="$backup"
fi
cp -p "$target" "$stage/previous.py"
cp "$source_file" "$candidate"
chmod 0755 "$candidate"
changed=1
mv -f "$candidate" "$target"
echo 'Restarting owrt-remote...'
if ! systemctl restart owrt-remote; then
show_failure
exit 1
fi
healthy=0
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then
healthy=1
break
fi
sleep 2
done
if [ "$healthy" -ne 1 ]; then
echo 'Health check did not become ready.' >&2
show_failure
exit 1
fi
cmp "$source_file" "$target"
printf '\nBackup: %s\nHUB_V115_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText(
(Join-Path $StageRoot 'run.sh'),
$RemoteScript.Replace("`r`n", "`n") + "`n",
$Utf8
)
if ($Action -eq 'Install') {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Content, $Utf8)
}
if ($PrepareOnly) {
Write-Host "Prepared only: $StageRoot"
return
}
& scp -O -r -- $StageRoot "${Vps}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
& ssh -T -o ConnectTimeout=10 $Vps "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Hub v115 $Action finished successfully. Refresh the Hub panel."
}
finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) {
throw 'Unsafe staging cleanup path.'
}
if (Test-Path -LiteralPath $Resolved) {
Remove-Item -LiteralPath $Resolved -Recurse -Force
}
}
}
+3 -3
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
@@ -37,7 +37,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3 [ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then if [ '__ACTION__' = Install ]; then
test -s "$stage/hub.py" test -s "$stage/hub.py"
grep -F -q 'v114' "$stage/hub.py" grep -F -q 'v115' "$stage/hub.py"
"$python_bin" -m py_compile "$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 OWRT_VPS_WIDGETS_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi 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) 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 test "$code" = 401
fi fi
printf '\nVPS_WIDGETS_V114_%s_OK\n' '__ACTION__' printf '\nVPS_WIDGETS_V115_%s_OK\n' '__ACTION__'
'@ '@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action) $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try { try {
+2 -2
View File
@@ -20,7 +20,7 @@ $RemoteScript = @'
#!/bin/sh #!/bin/sh
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-wan-multi-v114 backup=/root/owrt-remote-backup-before-wan-multi-v115
config=/etc/config/owrtremote config=/etc/config/owrtremote
changed=0 changed=0
item_path() { item_path() {
@@ -81,7 +81,7 @@ test -s "$config"
if [ '__ACTION__' = Install ]; then if [ '__ACTION__' = Install ]; then
for item in agent wan.sh cgi hotplug; do test -s "$stage/$item"; sh -n "$stage/$item"; done for item in agent wan.sh cgi hotplug; do test -s "$stage/$item"; sh -n "$stage/$item"; done
test -s "$stage/luci" test -s "$stage/luci"
for item in cgi luci; do grep -F -q 'v114' "$stage/$item"; done for item in cgi luci; do grep -F -q 'v115' "$stage/$item"; done
grep -F -q 'wan_interface_picker' "$stage/cgi" grep -F -q 'wan_interface_picker' "$stage/cgi"
grep -F -q 'wan_select_interface()' "$stage/wan.sh" grep -F -q 'wan_select_interface()' "$stage/wan.sh"
grep -F -q 'wan_reconcile_xray()' "$stage/agent" grep -F -q 'wan_reconcile_xray()' "$stage/agent"
+1 -1
View File
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh #!/bin/sh
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-wan-stability-v114 backup=/root/owrt-remote-backup-before-wan-stability-v115
config=/etc/config/owrtremote config=/etc/config/owrtremote
changed=0 changed=0
fail() { fail() {
+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v114 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v115
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
@@ -72,7 +72,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done done
test "$healthy" = 1 test "$healthy" = 1
cmp "$source_file" "$target" cmp "$source_file" "$target"
printf '\nBackup: %s\nWEB_PUSH_V114_%s_OK\n' "$backup" '__ACTION__' printf '\nBackup: %s\nWEB_PUSH_V115_%s_OK\n' "$backup" '__ACTION__'
'@ '@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action) $RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
+1 -1
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/www/cgi-bin/owrt-remote target=/www/cgi-bin/owrt-remote
backup_dir=/root/owrt-remote-backup-before-xray-apply-v114 backup_dir=/root/owrt-remote-backup-before-xray-apply-v115
backup=$backup_dir/owrt-remote backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
+1 -1
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu set -eu
stage=/tmp/__UPLOAD_NAME__ stage=/tmp/__UPLOAD_NAME__
target=/www/cgi-bin/owrt-remote target=/www/cgi-bin/owrt-remote
backup_dir=/root/owrt-remote-backup-before-xray-mobile-v114 backup_dir=/root/owrt-remote-backup-before-xray-mobile-v115
backup=$backup_dir/owrt-remote backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
+4 -4
View File
@@ -4861,7 +4861,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
<div class="brand"> <div class="brand">
<div class="desktopHeader"> <div class="desktopHeader">
<div class="desktopHeaderTop"> <div class="desktopHeaderTop">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v114</span></span></h1> <h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v115</span></span></h1>
<div class="routerSearchDock" id="routerSearchDock"> <div class="routerSearchDock" id="routerSearchDock">
<button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false"> <button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false">
<span>Поиск роутеров</span> <span>Поиск роутеров</span>
@@ -5214,7 +5214,7 @@ systemctl restart owrt-remote-xray</pre>
</div> </div>
</div> </div>
<div class="mobileSearchDock" id="mobileRouterSearchDock"> <div class="mobileSearchDock" id="mobileRouterSearchDock">
<span class="mobileSearchVersion">v114</span> <span class="mobileSearchVersion">v115</span>
<button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false"> <button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false">
<span>Поиск роутеров</span> <span>Поиск роутеров</span>
</button> </button>
@@ -12578,7 +12578,7 @@ button:hover{{filter:brightness(1.06)}}
<form class="login" method="post" action="/login"> <form class="login" method="post" action="/login">
{error_html} {error_html}
<span class="brand"> <span class="brand">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v114</span></span></h1> <h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v115</span></span></h1>
</span> </span>
<label for="hubUsername">Логин</label> <label for="hubUsername">Логин</label>
<input id="hubUsername" name="username" autocomplete="off" autofocus required> <input id="hubUsername" name="username" autocomplete="off" autofocus required>
@@ -13050,7 +13050,7 @@ body::after{{content:"";position:fixed;inset:0;pointer-events:none;background:li
<circle cx="65" cy="59" r="3" fill="#E5F2FF"/> <circle cx="65" cy="59" r="3" fill="#E5F2FF"/>
</svg> </svg>
</div> </div>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v114</span></h2> <h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v115</span></h2>
</div> </div>
</div> </div>
<div class="brandBottom"> <div class="brandBottom">