Release v117 with persistent logs and WAN tunnel recovery

This commit is contained in:
kzolotarev95 committed 2026-10-15 23:08:19 +04:00
1 parent 5f65a3d811
commit b62db40daf
61 files changed
+3080 -438

No files matched your search

+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-global-logs-ui-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-global-logs-ui-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -107,7 +107,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
printf '\nBackup: %s\nGLOBAL_LOGS_VPS_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nGLOBAL_LOGS_VPS_V117_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
+4 -3
View File
@@ -13,7 +13,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-global-logs-stop-v116
backup=/root/owrt-remote-backup-before-global-logs-stop-v117
items='cgi agent init logs.sh logs-init luci'
changed=0
phase=preflight
@@ -104,7 +104,7 @@ if [ '__ACTION__' = Install ]; then
command -v base64 >/dev/null
command -v jsonfilter >/dev/null
grep -F -q 'globalLogsToggle' "$stage/cgi"
for item in cgi luci; do grep -F -q 'v116' "$stage/$item"; done
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
grep -F -q 'log_sync_loop' "$stage/logs.sh"
grep -F -q 'sync_global_logs' "$stage/agent"
@@ -131,7 +131,8 @@ if [ '__ACTION__' = Install ]; then
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__'
# Generate UTF-8 on the router; Windows PowerShell 5.1 reads scripts as ANSI.
marker="$(printf '\320\223\320\273\320\276\320\261\320\260\320\273\040\320\273\320\276\320\263\320\270\072') collector-__UPLOAD_NAME__"
ready=0
for attempt in 1 2 3 4 5; do
logger -t owrt-remote "$marker"
+149
View File
@@ -0,0 +1,149 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-group-colors-v117-' + [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-group-colors-v117
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 = ('v117', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
if 'class="backupCmds"' in source:
print('Old backup command instructions remain in candidate', file=sys.stderr)
raise SystemExit(1)
if 'v' + '116' 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\nGROUP_COLORS_V117_%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 "Group colors fix $Action finished successfully. Refresh the Hub 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
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v116
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v117
agent=/usr/sbin/owrt-remote
wan=/usr/lib/owrt-remote/wan.sh
changed=0
+1 -1
View File
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-heartbeat-transport-v116
backup_dir=/root/owrt-remote-backup-before-heartbeat-transport-v117
changed=0
phase=preflight
item_path() {
+9 -9
View File
@@ -5,7 +5,7 @@ param(
[string]$PinnedVpsHost = '193.233.82.38',
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$WanInterface = 'wan',
[switch]$PreserveConnectionSettings,
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v116',
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v117',
[switch]$PrepareOnly
)
@@ -90,7 +90,7 @@ test -s "$config"
if [ '__ACTION__' = Install ]; then
for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done
test -s "$stage/luci"
for item in cgi luci; do grep -F -q 'v116' "$stage/$item"; done
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
# curl is needed to preserve HTTPS SNI and bypass the local DNS/proxy.
if ! command -v curl >/dev/null 2>&1; then
if command -v opkg >/dev/null 2>&1; then opkg update && opkg install curl ca-bundle
@@ -156,16 +156,16 @@ if [ '__ACTION__' = Install ]; then
exit 1
fi
/usr/sbin/owrt-remote status
grep -F -q 'v116' /www/cgi-bin/owrt-remote
grep -F -q 'v116' /www/luci-static/resources/view/owrt_remote.js
echo HOST_POLICY_ROUTER_V116_OK
grep -F -q 'v117' /www/cgi-bin/owrt-remote
grep -F -q 'v117' /www/luci-static/resources/view/owrt_remote.js
echo HOST_POLICY_ROUTER_V117_OK
else
test -f "$backup/complete"
save_files "$stage/previous"
changed=1
restore_files "$backup"
/usr/sbin/owrt-remote status
echo HOST_POLICY_ROUTER_V116_ROLLBACK_OK
echo HOST_POLICY_ROUTER_V117_ROLLBACK_OK
fi
'@
} else {
@@ -180,7 +180,7 @@ fi
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v117
changed=0
cleanup() {
code=$?
@@ -200,7 +200,7 @@ test -s "$target"
python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
grep -F -q 'v116' "$stage/hub.py"
grep -F -q 'v117' "$stage/hub.py"
"$python_bin" -m py_compile "$stage/hub.py"
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/test_host_policy.py" HostPolicyTests -v
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" -v
@@ -226,7 +226,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$candidate" "$target"
printf '\nHOST_POLICY_VPS_V116_%s_OK\n' '__ACTION__'
printf '\nHOST_POLICY_VPS_V117_%s_OK\n' '__ACTION__'
'@
}
+6 -6
View File
@@ -34,7 +34,7 @@ if ($Target -eq 'Router') {
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-hub-url-v116
backup=/root/owrt-remote-backup-before-hub-url-v117
chmod 700 "$stage"
config=/etc/config/owrtremote
changed=0
@@ -99,7 +99,7 @@ if [ '__ACTION__' = Install ]; then
grep -F -q 'heartbeat_set_url_if_changed()' "$stage/agent"
grep -F -q 'reason=https-downgrade' "$stage/agent"
for item in agent wan.sh; do grep -F -q -- '--post301' "$stage/$item"; done
for item in cgi luci; do grep -F -q 'v116' "$stage/$item"; done
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
if [ ! -e "$backup" ]; then
save_files "$stage/retained-backup"
mv "$stage/retained-backup" "$backup"
@@ -138,7 +138,7 @@ else
changed=1
restore_files "$backup"
fi
printf '\nBackup: %s\nHUB_URL_ROUTER_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nHUB_URL_ROUTER_V117_%s_OK\n' "$backup" '__ACTION__'
'@
} else {
$Payloads = @{
@@ -152,7 +152,7 @@ set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
chmod 700 "$stage"
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -174,7 +174,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
grep -F -q 'def router_hub_origins(' "$stage/hub.py"
grep -F -q 'v116' "$stage/hub.py"
grep -F -q 'v117' "$stage/hub.py"
"$python_bin" -m py_compile "$stage/hub.py"
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/host_policy.py" HostPolicyTests -v
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" IntegrationTests -v
@@ -198,7 +198,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$source_file" "$target"
printf '\nBackup: %s\nHUB_URL_VPS_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nHUB_URL_VPS_V117_%s_OK\n' "$backup" '__ACTION__'
'@
}
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__HUB_URL__', $HubUrl)
+2 -2
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -59,7 +59,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$source_file" "$target"
printf '\nBackup: %s\nONLINE_STATUS_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nONLINE_STATUS_V117_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-password-logout-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -105,7 +105,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
printf '\nBackup: %s\nPASSWORD_LOGOUT_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nPASSWORD_LOGOUT_V117_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
+187
View File
@@ -0,0 +1,187 @@
param(
[ValidateNotNullOrEmpty()][string]$Vps = 'root@193.233.82.38',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-persistent-logs-vps-' + [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-persistent-logs-sync-v117
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 = (
'def receive_router_logs(',
'def router_log_storage(',
'def router_log_diagnosis(',
'def router_logs_html(',
'def router_logs_api(',
'data-global-logs-link=',
'ROUTER_LOG_MAX_BYTES = 2 * 1024 * 1024',
)
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
# Read only the running Hub's relevant environment/argv; never print tokens.
hub_pid=$(systemctl show -p MainPID --value owrt-remote)
case "$hub_pid" in ''|*[!0-9]*|0) echo 'Cannot identify the running Hub storage.' >&2; exit 1 ;; esac
"$python_bin" - "$stage/hub.py" "$hub_pid" <<'PY'
import importlib.util
import json
import os
from pathlib import Path
import sys
sys.dont_write_bytecode = True
pid = sys.argv[2]
environment = Path('/proc/' + pid + '/environ').read_bytes().split(b'\0')
for item in environment:
key, _, value = item.partition(b'=')
if key in (b'OWRT_REMOTE_STATE_DIR', b'OWRT_REMOTE_DB'):
os.environ[key.decode()] = os.fsdecode(value)
spec = importlib.util.spec_from_file_location('storage_preflight', sys.argv[1])
hub = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = hub
spec.loader.exec_module(hub)
db_path = hub.DB_PATH
args = Path('/proc/' + pid + '/cmdline').read_bytes().split(b'\0')
for index, arg in enumerate(args):
if arg == b'--db' and index + 1 < len(args):
db_path = Path(os.fsdecode(args[index + 1]))
elif arg.startswith(b'--db='):
db_path = Path(os.fsdecode(arg[5:]))
if not db_path.is_absolute():
db_path = Path('/proc/' + pid + '/cwd').resolve() / db_path
storage = hub.router_log_storage(db_path)
print('VPS log archive storage:', json.dumps(storage, ensure_ascii=False))
if storage['persistent'] is not True or not storage.get('writable'):
raise SystemExit('Archive is not confirmed on writable persistent disk. Nothing installed; check the Hub database mount.')
if not db_path.is_file() or not os.access(db_path, os.W_OK):
raise SystemExit('Hub database is missing or not writable. Nothing installed.')
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\nPERSISTENT_LOGS_VPS_V117_%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 "Persistent logs VPS $Action finished successfully. Refresh Hub 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
}
}
}
+195
View File
@@ -0,0 +1,195 @@
param(
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-persistent-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-persistent-logs-v117
items='cgi agent 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() {
# Updated CGI and LuCI assets need no rpcd restart; keep management sessions alive.
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
: >"$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.new-__UPLOAD_NAME__" && mv -f "$path.new-__UPLOAD_NAME__" "$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
: # Preserve both journals for manual recovery.
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 logs.sh logs-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 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
command -v base64 >/dev/null
command -v jsonfilter >/dev/null
if ! command -v sha256sum >/dev/null 2>&1 && ! command -v md5sum >/dev/null 2>&1 && ! command -v cksum >/dev/null 2>&1; then
echo 'No supported checksum utility (sha256sum, md5sum or cksum). Nothing installed.' >&2
exit 1
fi
grep -F -q 'globalLogsToggle' "$stage/cgi"
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
grep -F -q 'LOG_BUFFER_LIMIT=16384' "$stage/logs.sh"
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
grep -F -q 'log_sync_loop' "$stage/logs.sh"
grep -F -q 'log_repair_legacy_locked' "$stage/logs.sh"
grep -F -q 'sync_global_logs' "$stage/agent"
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
phase=legacy-migration
sh /usr/lib/owrt-remote/logs.sh migrate
/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
# Generate UTF-8 on the router; Windows PowerShell 5.1 reads scripts as ANSI.
marker="$(printf '\320\223\320\273\320\276\320\261\320\260\320\273\040\320\273\320\276\320\263\320\270\072') 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
phase=storage-check
sh /usr/lib/owrt-remote/logs.sh flush force
sh /usr/lib/owrt-remote/logs.sh status
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 '\nPERSISTENT_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'
'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 "Persistent 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 }
}
}
+6 -6
View File
@@ -17,8 +17,8 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v116
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v116.json
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v117
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v117.json
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source)
assert 'v116' in source
assert 'v117' in source
assert 'v108' not in source
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
assert 'prepareLoginRecaptcha' in source
@@ -88,7 +88,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RECAPTCHA_V3_V116_OK
echo RECAPTCHA_V3_V117_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V116_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v116
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v116.json
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v117
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v117.json
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
restore_captcha() {
+4 -4
View File
@@ -18,7 +18,7 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source)
assert 'v116' in source
assert 'v117' in source
assert 'v108' not in source
factory = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'connect')
assert any(isinstance(item, ast.Name) and item.id == 'contextmanager' for item in factory.decorator_list)
@@ -78,7 +78,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RESOURCE_FIX_V116_OK
echo RESOURCE_FIX_V117_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V116_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v117
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
cleanup() {
+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-router-card-ui-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -106,7 +106,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
printf '\nBackup: %s\nROUTER_CARD_UI_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nROUTER_CARD_UI_V117_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
@@ -6,7 +6,7 @@ param(
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-version-v116-' + [guid]::NewGuid().ToString('N')
$UploadName = 'owrt-version-v117-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -57,8 +57,8 @@ if [ '__ACTION__' = Install ]; then
from pathlib import Path
import sys
source = Path(sys.argv[1]).read_text(encoding='utf-8')
required = ('v116',)
if 'v' + '115' in source:
required = ('v117',)
if 'v' + '116' 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]
@@ -103,7 +103,7 @@ if [ "$healthy" -ne 1 ]; then
exit 1
fi
cmp "$source_file" "$target"
printf '\nBackup: %s\nHUB_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nHUB_V117_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
@@ -130,7 +130,7 @@ try {
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 v116 $Action finished successfully. Refresh the Hub panel."
Write-Host "Hub v117 $Action finished successfully. Refresh the Hub panel."
}
finally {
if (-not $PrepareOnly) {
+3 -3
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -37,7 +37,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
test -s "$stage/hub.py"
grep -F -q 'v116' "$stage/hub.py"
grep -F -q 'v117' "$stage/hub.py"
"$python_bin" -m py_compile "$stage/hub.py"
OWRT_VPS_WIDGETS_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
@@ -67,7 +67,7 @@ if [ '__ACTION__' = Install ]; then
code=$(curl -sS --max-time 5 -o "$stage/response.json" -w '%{http_code}' http://127.0.0.1:8088/api/vps/resources)
test "$code" = 401
fi
printf '\nVPS_WIDGETS_V116_%s_OK\n' '__ACTION__'
printf '\nVPS_WIDGETS_V117_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
+1 -1
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/usr/lib/owrt-remote/wan.sh
backup_dir=/root/owrt-remote-backup-before-wan-dns-v116
backup_dir=/root/owrt-remote-backup-before-wan-dns-v117
changed=0
phase=preflight
heartbeat_pid() {
+2 -2
View File
@@ -20,7 +20,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-wan-multi-v116
backup=/root/owrt-remote-backup-before-wan-multi-v117
config=/etc/config/owrtremote
changed=0
item_path() {
@@ -81,7 +81,7 @@ test -s "$config"
if [ '__ACTION__' = Install ]; then
for item in agent wan.sh cgi hotplug; do test -s "$stage/$item"; sh -n "$stage/$item"; done
test -s "$stage/luci"
for item in cgi luci; do grep -F -q 'v116' "$stage/$item"; done
for item in cgi luci; do grep -F -q 'v117' "$stage/$item"; done
grep -F -q 'wan_interface_picker' "$stage/cgi"
grep -F -q 'wan_select_interface()' "$stage/wan.sh"
grep -F -q 'wan_reconcile_xray()' "$stage/agent"
+154
View File
@@ -0,0 +1,154 @@
param(
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-wan-recovery-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$Payloads = @{
'wan.sh' = 'files\usr\lib\owrt-remote\wan.sh'
'agent' = 'files\usr\sbin\owrt-remote'
}
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-wan-recovery-v117
changed=0
phase=preflight
item_path() {
case "$1" in
wan.sh) printf /usr/lib/owrt-remote/wan.sh ;;
agent) printf /usr/sbin/owrt-remote ;;
esac
}
complete_backup() {
[ -f "$1/complete" ] && [ -s "$1/wan.sh" ] && [ -s "$1/agent" ]
}
restore_files() {
local dir item path
dir=$1
complete_backup "$dir" || return 1
for item in agent wan.sh; do
path=$(item_path "$item")
cp -p "$dir/$item" "$path.new-__UPLOAD_NAME__" || return 1
mv -f "$path.new-__UPLOAD_NAME__" "$path" || return 1
done
}
heartbeat_pid() {
local state
state=$(ubus call service list '{"name":"owrt-remote"}') || return 1
printf '%s' "$state" | jsonfilter -e '@["owrt-remote"].instances.heartbeat.pid' 2>/dev/null || true
}
refresh_heartbeat() {
local old_pid new_pid attempt
old_pid=$(heartbeat_pid) || return 1
case "$old_pid" in ''|0) echo 'Heartbeat loop is stopped; files will be used at its next start.'; return 0 ;; *[!0-9]*) return 1 ;; esac
# Signal only the supervised heartbeat shell; procd respawns it from the
# new agent. A healthy Xray instance stays running; a crashed one can recover.
ubus call service signal '{"name":"owrt-remote","instance":"heartbeat","signal":9}' >/dev/null || return 1
attempt=0
while [ "$attempt" -lt 20 ]; do
sleep 1
new_pid=$(heartbeat_pid) || return 1
case "$new_pid" in ''|0|*[!0-9]*) ;; *)
[ "$new_pid" = "$old_pid" ] || { echo 'Heartbeat loop reloaded; WAN recovery is active for enabled tunnels.'; return 0; } ;;
esac
attempt=$((attempt+1))
done
echo 'Heartbeat loop did not respawn. Code will be restored.' >&2
return 1
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
if [ "$changed" = 1 ]; then
echo 'Restoring the agent and WAN helper from this attempt.' >&2
restore_files "$stage/previous" && refresh_heartbeat || echo 'Restore failed; retained backup is available.' >&2
fi
fi
for item in agent wan.sh; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
for item in agent wan.sh; do
path=$(item_path "$item")
test -s "$path"
done
heartbeat_pid >/dev/null
if [ '__ACTION__' = Install ]; then
for item in agent wan.sh; do test -s "$stage/$item"; sh -n "$stage/$item"; done
grep -F -q 'wan_recover_xray()' "$stage/agent"
grep -F -q 'wait_for_selected_wan()' "$stage/agent"
grep -F -q 'reason=https_required' "$stage/agent"
grep -F -q 'remote_curl_post' "$stage/wan.sh"
if [ ! -e "$backup_dir" ]; then
mkdir -p "$stage/retained-backup"
chmod 700 "$stage/retained-backup"
for item in agent wan.sh; do path=$(item_path "$item"); cp -p "$path" "$stage/retained-backup/$item"; done
touch "$stage/retained-backup/complete"
mv "$stage/retained-backup" "$backup_dir"
fi
complete_backup "$backup_dir" || { echo "Incomplete backup: $backup_dir. Nothing changed." >&2; exit 1; }
source_dir=$stage
else
complete_backup "$backup_dir" || { echo "No complete backup: $backup_dir. Nothing changed." >&2; exit 1; }
for item in agent wan.sh; do sh -n "$backup_dir/$item"; done
source_dir=$backup_dir
fi
printf 'Backup: %s\n' "$backup_dir"
mkdir -p "$stage/previous"
for item in agent wan.sh; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
touch "$stage/previous/complete"
phase=install
changed=1
for item in agent wan.sh; do
path=$(item_path "$item")
cp "$source_dir/$item" "$path.new-__UPLOAD_NAME__"
chmod 755 "$path.new-__UPLOAD_NAME__"
mv -f "$path.new-__UPLOAD_NAME__" "$path"
done
phase=verify
for item in agent wan.sh; do
path=$(item_path "$item")
sh -n "$path"
cmp "$source_dir/$item" "$path"
done
phase=heartbeat-reload
refresh_heartbeat
# The reloaded heartbeat recovers an enabled, crashed Xray instance when WAN
# returns. A healthy tunnel is not restarted by this deployment.
printf '\nWAN_RECOVERY_ROUTER_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
foreach ($Item in $Payloads.GetEnumerator()) {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -r -- $StageRoot "${Router}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "WAN recovery fix $Action finished successfully."
} finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-wan-stability-v116
backup=/root/owrt-remote-backup-before-wan-stability-v117
config=/etc/config/owrtremote
changed=0
fail() {
+2 -2
View File
@@ -15,7 +15,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v116
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-web-push-v117
candidate=$target.new-__UPLOAD_NAME__
changed=0
@@ -72,7 +72,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
done
test "$healthy" = 1
cmp "$source_file" "$target"
printf '\nBackup: %s\nWEB_PUSH_V116_%s_OK\n' "$backup" '__ACTION__'
printf '\nBackup: %s\nWEB_PUSH_V117_%s_OK\n' "$backup" '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
+1 -1
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/www/cgi-bin/owrt-remote
backup_dir=/root/owrt-remote-backup-before-xray-apply-v116
backup_dir=/root/owrt-remote-backup-before-xray-apply-v117
backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__
changed=0
+1 -1
View File
@@ -14,7 +14,7 @@ $RemoteScript = @'
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/www/cgi-bin/owrt-remote
backup_dir=/root/owrt-remote-backup-before-xray-mobile-v116
backup_dir=/root/owrt-remote-backup-before-xray-mobile-v117
backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__
changed=0
+1 -1
View File
@@ -17,7 +17,7 @@ $RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-xray-validation-v116
backup_dir=/root/owrt-remote-backup-before-xray-validation-v117
changed=0
phase=preflight
item_path() {
+55 -32
View File
@@ -3087,6 +3087,38 @@ ROUTER_LOG_MAX_BYTES = 2 * 1024 * 1024
ROUTER_LOG_BATCH_MAX_BYTES = 65536
def router_log_storage(db_path):
"""Describe the archive's real backing mount, including symlinked DB paths."""
path = Path(db_path).resolve()
result = {'path': str(path), 'filesystem': 'unknown', 'persistent': None,
'limit_bytes': ROUTER_LOG_MAX_BYTES}
if sys.platform != 'linux':
return result
def unescape(value):
return re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value)
try:
mounts = []
with open('/proc/self/mountinfo', encoding='utf-8') as source:
for line in source:
fields, separator, tail = line.partition(' - ')
left, right = fields.split(), tail.split()
if not separator or len(left) < 6 or len(right) < 3:
continue
mount = Path(unescape(left[4]))
if path.is_relative_to(mount):
mounts.append((len(mount.parts), right[0], left[5]))
if mounts:
_, filesystem, flags = max(mounts, key=lambda item: item[0])
persistent = (False if filesystem in {'tmpfs', 'ramfs', 'rootfs'} else
True if filesystem in {'ext2', 'ext3', 'ext4', 'xfs', 'btrfs', 'f2fs',
'jfs', 'zfs', 'ubifs', 'jffs2', 'nfs', 'nfs4', 'ceph'} else None)
result.update(filesystem=filesystem, persistent=persistent,
writable='rw' in flags.split(','))
except OSError:
pass
return result
def redact_router_log_bytes(raw):
"""Defense in depth: do not archive credentials supplied by older agents."""
secret = re.compile(rb'authorization|hub_token|vless_uuid|ssh_vless_uuid|password|passwd|web[._ -]?key|[?&](?:key|token)=|"(?:uuid|privatekey)"|[0-9a-f]{8}-[0-9a-f-]{27,}', re.I)
@@ -3137,6 +3169,12 @@ def receive_router_logs(conn, router_id, batch, state=None):
conn.execute('update router_logs set last_sync = ? where router_id = ?', (ts, router_id))
return {'journal_id': journal_id, 'offset': end, 'clear_request': pending}
cursor = int(row['cursor']) if row['journal_id'] == journal_id else 0
# A status-only packet cannot prove delivery of any journal bytes. Older
# helpers sent from=to=total even when every chunk was skipped. Acknowledging
# that number permanently hid the retained records and invented rotation gaps.
if not raw and not pending:
conn.execute('update router_logs set last_sync = ? where router_id = ?', (ts, router_id))
return {'journal_id': journal_id, 'offset': cursor, 'clear_request': ''}
if not pending and row['journal_id'] == journal_id and end <= cursor:
conn.execute('update router_logs set last_sync = ? where router_id = ?', (ts, router_id))
return {'journal_id': journal_id, 'offset': cursor, 'clear_request': ''}
@@ -3145,7 +3183,7 @@ def receive_router_logs(conn, router_id, batch, state=None):
cursor = start
stored = b''
elif row['journal_id'] and row['journal_id'] != journal_id:
stored += ('[OK] ' + iso_time(ts) + ' Роутер начал новый журнал: перезагрузка или очистка в ОЗУ.\n').encode('utf-8')
stored += ('[OK] ' + iso_time(ts) + ' Роутер начал новый журнал: очистка или восстановление сохранённой истории.\n').encode('utf-8')
if start > cursor:
stored += ('[WARN] ' + iso_time(ts) + ' Часть записей не доставлена до ротации журнала на роутере.\n').encode('utf-8')
if end > cursor:
@@ -4968,11 +5006,16 @@ body::before{{content:"";position:fixed;inset:-25%;z-index:0;pointer-events:none
.brand{{display:flex;align-items:center;gap:14px;width:100%;min-width:0}}
h1{{margin:0;font-size:29px;line-height:1.2;letter-spacing:0}}.appBanner{{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:36px;min-width:132px;padding:8px 14px;border:1px solid rgba(34,211,238,.38);border-radius:999px;background:linear-gradient(110deg,rgba(34,211,238,.14),rgba(124,58,237,.24),rgba(236,72,153,.14));color:#f3e8ff;text-decoration:none;font-weight:800;font-size:13px;line-height:1;white-space:nowrap;box-shadow:0 10px 24px rgba(124,58,237,.16),inset 0 1px 0 rgba(255,255,255,.10);overflow:hidden}}.appBanner::before{{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.20),transparent);transform:translateX(-120%);animation:bannerShine 6.2s ease-in-out infinite}}.appBanner span{{position:relative}}.appBannerVersion{{color:#fb7185;text-shadow:0 0 12px rgba(251,113,133,.35)}}.muted{{color:var(--muted)}}.top p{{margin:4px 0 0}}.links,.headerActions{{display:flex;align-items:center;gap:8px}}.links{{margin-top:0;flex-wrap:nowrap}}.links a,.badge{{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:36px;min-width:132px;padding:8px 14px;border:1px solid var(--line);border-radius:999px;background:rgba(255,255,255,.08);color:#f3e8ff;text-decoration:none;font-weight:800;font-size:13px;line-height:1;white-space:nowrap;overflow:hidden}}.headerActions{{position:relative;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));align-self:flex-start;justify-content:flex-start;align-content:flex-start;flex:1 1 auto;min-width:0;gap:8px;padding-top:0;max-width:none}}.headerActions .badge,.headerActions .btn{{width:100%;min-height:36px;min-width:0;padding:8px 10px;border-radius:999px;font-weight:800;font-size:12px;line-height:1;white-space:nowrap}}.headerActions .btn[href="/logout"]{{margin-left:0}}.badge{{background:rgba(255,255,255,.08);color:#f3e8ff;box-shadow:inset 0 1px 0 rgba(255,255,255,.06)}}.nethavenTop{{border-color:rgba(34,211,238,.46);background:linear-gradient(110deg,rgba(14,165,233,.20),rgba(168,85,247,.22),rgba(34,197,94,.14));color:#ecfeff;box-shadow:0 10px 24px rgba(14,165,233,.14),inset 0 1px 0 rgba(255,255,255,.10)}}.nethavenTop::before{{content:"";position:absolute;inset:0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.24),transparent);transform:translateX(-120%);animation:bannerShine 6.2s ease-in-out infinite;pointer-events:none}}.authToggle{{cursor:pointer}}.dot{{width:9px;height:9px;border-radius:999px;background:var(--red);box-shadow:0 0 13px rgba(251,113,133,.72)}}.dot.on{{background:var(--green);box-shadow:0 0 13px rgba(34,197,94,.75)}}.dot.warn{{background:var(--amber);box-shadow:0 0 13px rgba(245,158,11,.75)}}
.toolbar{{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.2fr) minmax(84px,.52fr) minmax(100px,.65fr) minmax(0,1fr) minmax(0,1fr) minmax(116px,.68fr);gap:8px;margin:18px 0;padding:14px 16px;background:linear-gradient(180deg,rgba(255,255,255,.08),rgba(255,255,255,.045)),var(--panel);border:1px solid var(--line);border-radius:8px;box-shadow:0 18px 46px rgba(0,0,0,.20);backdrop-filter:blur(10px);width:100%;max-width:100%;box-sizing:border-box}}.toolbar>*{{width:100%;min-width:0}}.toolbar input,.toolbar select{{background:rgba(255,255,255,.08);border-color:var(--line);color:#f3e8ff;box-shadow:inset 0 1px 0 rgba(255,255,255,.05)}}.toolbar input::placeholder{{color:#b9adc9}}
@media(min-width:681px){{
#routerForm select,#routerGroupFilter{{color-scheme:dark}}
#routerForm select option,#routerGroupFilter option{{background-color:#221a34;color:#f7f2ff}}
#routerForm select option:checked,#routerGroupFilter option:checked{{background-color:#7c3aed;color:#fff}}
}}
.authMenu{{position:absolute;right:0;top:calc(100% + 10px);z-index:60;width:min(640px,calc(100vw - 44px));max-height:min(820px,calc(100svh - 120px));overflow:auto;padding:16px;background:linear-gradient(180deg,rgba(255,255,255,.09),rgba(255,255,255,.05)),rgba(19,14,32,.96);border:1px solid var(--line);border-radius:8px;box-shadow:0 24px 70px rgba(0,0,0,.36);backdrop-filter:blur(12px);scrollbar-width:thin}}.authMenu[hidden]{{display:none}}.authMenu>h2,.authMenu>p{{display:none}}.authMenuHead{{position:relative;display:block}}.authMenuHead>div{{min-width:0}}.authMenuHead p{{display:none}}.authMenu h2{{margin:0 0 4px;font-size:18px}}.authMenuClose{{display:none;position:absolute;top:14px;right:14px;min-height:34px;padding:7px 12px;border-radius:999px;white-space:nowrap}}.authMenu p{{margin:0 0 12px;color:var(--muted)}}.authGrid{{display:grid;grid-template-columns:1fr;gap:10px}}.authGrid .wide{{grid-column:1/-1}}.msg{{margin-top:10px;color:#bbf7d0;font-weight:750}}.msg.bad{{color:#fecdd3}}.formMsg{{margin:-8px 0 18px;padding:10px 12px;border:1px solid rgba(34,197,94,.34);border-radius:8px;background:rgba(34,197,94,.12);color:#bbf7d0;font-weight:800}}.formMsg.bad{{border-color:rgba(251,113,133,.4);background:rgba(251,113,133,.13);color:#fecdd3}}
.authGroup{{margin-top:14px;border:1px solid rgba(34,211,238,.22);border-radius:14px;background:linear-gradient(180deg,rgba(255,255,255,.06),rgba(255,255,255,.03)),rgba(15,10,26,.78);box-shadow:inset 0 1px 0 rgba(255,255,255,.04)}}.authGroupSummary{{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;cursor:pointer;list-style:none}}.authGroupSummary::-webkit-details-marker{{display:none}}.authGroupTitle strong{{display:block;color:#f7f2ff;font-size:15px;font-weight:900;line-height:1.15}}.authGroupTitle span{{display:block;margin-top:4px;color:var(--muted);font-size:12px;line-height:1.35}}.authGroupChevron{{display:inline-flex;align-items:center;justify-content:center;flex:0 0 28px;width:28px;height:28px;border:1px solid rgba(34,211,238,.24);border-radius:999px;background:rgba(34,211,238,.08);color:#dbeafe;font-size:16px;line-height:1;transition:transform .18s ease,background .18s ease,border-color .18s ease}}.authGroup[open] .authGroupChevron{{transform:rotate(180deg);background:rgba(34,197,94,.12);border-color:rgba(34,197,94,.24)}}.authGroupBody{{padding:0 14px 14px;border-top:1px solid rgba(255,255,255,.08)}}.authGroupBody>.authPasswordSection{{margin-top:14px;padding-top:0;border-top:0}}.authGroupBody>.authOverview{{margin-top:0;padding-top:14px;border-top:0}}.authGroupBody>.sessionBox{{margin-top:14px;padding-top:0;border-top:0}}.authGroupBody>.notifyBox{{margin-top:14px;padding-top:0;border-top:0}}.authGroupBody>.backupBox{{margin-top:14px;padding-top:0;border-top:0}}.authOverview{{display:grid;gap:10px;margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}}.authPills{{display:flex;flex-wrap:wrap;gap:8px}}.authPill{{display:inline-flex;align-items:center;gap:7px;padding:7px 10px;border:1px solid rgba(34,211,238,.24);border-radius:999px;background:rgba(34,211,238,.08);color:#dbeafe;font-size:12px;font-weight:850}}.authPill.off{{border-color:rgba(255,255,255,.10);background:rgba(255,255,255,.06);color:#c4b5fd}}.authSection{{margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}}.authSectionHead{{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;margin-bottom:8px}}.authSectionHead h3{{margin:0;font-size:15px}}.authSectionHead p{{margin:4px 0 0;color:var(--muted);font-size:12px;line-height:1.35}}.authSectionState{{display:inline-flex;align-items:center;justify-content:center;min-height:30px;padding:6px 10px;border:1px solid rgba(34,197,94,.30);border-radius:999px;background:rgba(34,197,94,.12);color:#bbf7d0;font-size:12px;font-weight:850;white-space:nowrap}}.authSectionState.off{{border-color:rgba(255,255,255,.10);background:rgba(255,255,255,.06);color:#c4b5fd}}.authSectionState.warn{{border-color:rgba(251,191,36,.28);background:rgba(251,191,36,.11);color:#fde68a}}.authFields{{display:grid;grid-template-columns:1fr 1fr;gap:8px}}.authFields .wide{{grid-column:1/-1}}.authFields input,.authFields textarea{{width:100%;min-width:0}}.authFields textarea{{min-height:92px;resize:vertical}}.authActions{{display:flex;gap:8px;flex-wrap:wrap;margin-top:8px}}.authActions .sessionBtn,.authActions .btn,.authActions button{{flex:1 1 180px}}.authHint{{margin:8px 0 0;color:var(--muted);font-size:12px;line-height:1.35}}.authRememberToggle{{display:inline-flex;align-items:center;gap:8px;min-height:34px;padding:7px 11px;border:1px solid rgba(255,255,255,.10);border-radius:999px;background:rgba(255,255,255,.05);color:var(--muted);font-size:12px;font-weight:750;cursor:pointer;user-select:none}}.authRememberToggle input{{width:14px;height:14px;margin:0;flex:0 0 14px;accent-color:#22c55e}}.authSecretBox{{margin-top:10px;padding:10px;border:1px solid rgba(34,211,238,.24);border-radius:8px;background:rgba(34,211,238,.08)}}.authSecretBox strong{{display:block;margin-bottom:6px;font-size:12px;color:#f7f2ff}}.authSecretValue{{margin:0;padding:9px 10px;border:1px solid rgba(255,255,255,.08);border-radius:8px;background:rgba(0,0,0,.18);color:#c4b5fd;font:12px/1.4 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;word-break:break-word}}.authList{{display:grid;gap:8px;margin-top:10px}}.authRow{{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:start;border:1px solid var(--line);border-radius:8px;background:rgba(255,255,255,.055);padding:9px}}.authRowAll{{border-style:dashed;background:linear-gradient(135deg,rgba(34,211,238,.10),rgba(34,197,94,.08),rgba(255,255,255,.04))}}.authRowTitle{{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-weight:900}}.authRowMeta{{margin-top:4px;color:var(--muted);font-size:12px;line-height:1.35;word-break:break-word}}.authRowKey{{margin-top:7px;padding:8px;border:1px solid rgba(255,255,255,.08);border-radius:7px;background:rgba(0,0,0,.18);color:#c4b5fd;font:11px/1.35 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;word-break:break-all}}.authRouterFlags{{justify-content:flex-end}}.authFlagPill{{gap:6px;min-height:30px;padding:5px 8px;cursor:pointer;user-select:nonLine truncated
.sessionBox{{margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}}.sessionHead{{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:8px}}.sessionHead h3{{margin:0;font-size:15px}}.sessionList{{display:grid;gap:8px;max-height:260px;overflow:auto;padding-right:2px}}.sessionRow{{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:center;border:1px solid var(--line);border-radius:8px;background:rgba(255,255,255,.055);padding:9px;text-align:left}}.sessionTitle{{display:flex;gap:7px;align-items:center;flex-wrap:wrap;font-weight:900}}.sessionMeta{{margin-top:3px;color:var(--muted);font-size:12px;line-height:1.35;word-break:break-word}}.sessionCurrent{{border:1px solid rgba(34,197,94,.38);border-radius:999px;padding:2px 7px;color:#bbf7d0;background:rgba(34,197,94,.13);font-size:11px}}.sessionBtn{{padding:7px 9px;font-size:12px;border-radius:999px}}.sessionEmpty{{padding:10px;border:1px dashed var(--line);border-radius:8px;color:var(--muted);text-align:center}}
.notifyBox{{margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}}.notifyActions{{display:flex;gap:7px;align-items:center;justify-content:flex-end;flex-wrap:wrap}}.notifyHint{{margin:-4px 0 10px;color:var(--muted);font-size:12px;line-height:1.35}}.notifyList{{display:grid;gap:8px;max-height:260px;overflow:auto;padding-right:2px}}.notifyRow{{border:1px solid var(--line);border-radius:8px;background:rgba(255,255,255,.055);padding:9px;text-align:left}}.notifyTitle{{display:flex;align-items:center;justify-content:space-between;gap:8px;font-weight:950}}.notifyTitle span:first-child{{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}.notifyTime{{color:var(--muted);font-size:11px;font-weight:750;white-space:nowrap}}.notifyBody{{margin-top:4px;color:#ddd6fe;font-size:12px;line-height:1.35;word-break:break-word}}.notifyDetails{{margin:7px 0 0;padding:8px;border:1px solid rgba(255,255,255,.08);border-radius:7px;background:rgba(0,0,0,.18);color:#c4b5fd;font:11px/1.35 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre-wrap;max-height:92px;overflow:auto}}.notifyRow.warn{{border-color:rgba(245,158,11,.34);background:rgba(245,158,11,.08)}}.notifyRow.bad{{border-color:rgba(251,113,133,.38);background:rgba(251,113,133,.09)}}.notifyBtn.on{{border-color:rgba(34,197,94,.36);background:rgba(34,197,94,.15);color:#bbf7d0}}
.backupBox{{margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}}.backupGrid{{display:grid;grid-template-columns:1fr 1fr;gap:8px}}.backupGrid .wide{{grid-column:1/-1}}.backupGrid input[type=file]{{padding:8px;background:rgba(8,5,18,.72);border:1px solid var(--line);border-radius:8px;color:#ddd6fe;min-width:0}}.backupHint{{margin:0 0 10px;color:var(--muted);font-size:12px;line-height:1.35}}.backupCmds{{display:grid;gap:8px;margin-top:10px}}.backupCmd{{border:1px solid rgba(255,255,255,.10);border-radius:8px;background:rgba(0,0,0,.18);padding:9px}}.backupCmd strong{{display:block;margin-bottom:5px;color:#f7f2ff;font-size:12px}}.backupCmd pre{{margin:0;white-space:pre-wrap;word-break:break-word;color:#c4b5fd;font:11px/1.35 ui-monospace,SFMono-Regular,Consolas,monospace}}#backupRewrite{{border-color:rgba(251,191,36,.42);background:linear-gradient(135deg,rgba(251,191,36,.28),rgba(245,158,11,.22));color:#fff7cc;box-shadow:0 10px 24px rgba(245,158,11,.14),inset 0 1px 0 rgba(255,255,255,.12)}}#backupRewrite:hover{{border-color:rgba(251,191,36,.56);background:linear-gradient(135deg,rgba(251,191,36,.34),rgba(245,158,11,.28))}}.backupMsg{{margin-top:9px;color:#bbf7d0;font-size:12px;font-weight:800;line-height:1.35}}.backupMsg.bad{{color:#fecdd3}}
.backupBox{{margin-top:14px;padding-top:12px;border-top:1px solid var(--line)}}.backupGrid{{display:grid;grid-template-columns:1fr 1fr;gap:8px}}.backupGrid .wide{{grid-column:1/-1}}.backupGrid input[type=file]{{padding:8px;background:rgba(8,5,18,.72);border:1px solid var(--line);border-radius:8px;color:#ddd6fe;min-width:0}}.backupHint{{margin:0 0 10px;color:var(--muted);font-size:12px;line-height:1.35}}#backupRewrite{{border-color:rgba(251,191,36,.42);background:linear-gradient(135deg,rgba(251,191,36,.28),rgba(245,158,11,.22));color:#fff7cc;box-shadow:0 10px 24px rgba(245,158,11,.14),inset 0 1px 0 rgba(255,255,255,.12)}}#backupRewrite:hover{{border-color:rgba(251,191,36,.56);background:linear-gradient(135deg,rgba(251,191,36,.34),rgba(245,158,11,.28))}}.backupMsg{{margin-top:9px;color:#bbf7d0;font-size:12px;font-weight:800;line-height:1.35}}.backupMsg.bad{{color:#fecdd3}}
input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding:10px 11px;background:rgba(8,5,18,.72);color:var(--text)}}button,.btn{{border:1px solid rgba(255,255,255,.10);border-radius:8px;padding:10px 13px;background:rgba(255,255,255,.10);color:#f7f2ff;font-weight:850;text-decoration:none;cursor:pointer;display:inline-flex;justify-content:center;align-items:center}}.authToggle{{border-radius:999px;padding:8px 14px;background:rgba(255,255,255,.08);color:#f3e8ff}}button.primary,.btn.primary{{background:var(--blue);color:#fff;box-shadow:0 10px 22px rgba(124,58,237,.22)}}button.bad,.btn.bad{{background:rgba(251,113,133,.16);color:#fecdd3}}.btn.good{{background:rgba(34,197,94,.16);color:#bbf7d0}}.btn.disabled{{opacity:.45;cursor:not-allowed}}
.summary{{display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end}}.miniStat{{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:36px;min-width:132px;border:1px solid var(--line);border-radius:999px;background:rgba(255,255,255,.07);padding:8px 12px;color:#ddd6fe;font-weight:800;font-size:13px;line-height:1;white-space:nowrap}}
.routerStats{{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));align-items:start;gap:8px;margin:0 0 10px}}.statCard{{position:relative;min-height:54px;overflow:hidden;border:1px solid var(--line);border-radius:8px;padding:8px 10px 7px;background:linear-gradient(180deg,rgba(255,255,255,.075),rgba(255,255,255,.04)),var(--panel);box-shadow:0 8px 20px rgba(0,0,0,.14);text-align:center;box-sizing:border-box}}.statCard::before{{content:"";position:absolute;inset:0 0 auto 0;height:2px;background:var(--cyan)}}.statCard span{{display:block;color:var(--muted);font-size:10px;font-weight:850;text-transform:uppercase;letter-spacing:.035em}}.statCard strong{{display:block;margin-top:0;font-size:22px;line-height:1;color:#f7f2ff}}.statCard em{{display:block;min-width:0;margin-top:2px;padding:0 2px;color:#c4b5fd;font-style:normal;font-size:10px;line-height:1.15}}.statCard.online::before{{background:var(--green)}}.statCard.online strong{{color:#bbf7d0}}.statCard.offline::before{{background:var(--red)}}.statCard.offline strong{{color:#fecdd3}}.statCard.total::before{{background:var(--cyan)}}.statCard.total strong{{color:#a5f3fc}}.statCardHead{{display:flex;align-items:center;justify-content:center;min-height:14px}}.statCard.has-popover{{overflow:visible;z-index:12}}.statValueRow,.offlineStatRow{{position:relative;display:flex;align-items:center;justify-content:center;min-height:20px;margin-top:3px}}.offlineMoreBtn{{position:absolute;right:6px;top:50%;transform:translateY(-50%);display:inline-flex;align-items:center;justify-content:center;min-height:22px;padding:0 8px;border:1px solid rgba(251,113,133,.34);border-radius:999px;background:rgba(251,113,133,.12);color:#fecdd3;font-size:10px;font-weight:900;line-height:1;cursor:pointer;white-space:nowrap}}.offlineMoreBtn[aria-expanded="true"]{{background:rgba(251,113,133,.18);border-color:rgba(251,113,133,.48)}}.offlinePopover{{position:absolute;top:calc(100% + 8px);right:6px;width:min(340px,calc(100vw - 30px));padding:10px;border:1px solid rgba(251,113,133,.28);border-radius:12px;background:linear-gradient(180deg,rgba(49,28,44,.98),rgba(30,18,40,.98));box-shadow:0 22px 50px rgba(0,0,0,.34);text-align:left;z-index:25}}.offlinePopover[hidden]{{display:none!important}}.offlineList{{display:grid;gap:6px;max-height:170px;overflow:auto;padding-right:2px}}.offlineItem{{border:1px solid rgba(251,113,133,.18);border-radius:8px;padding:7px 8px;background:rgba(251,113,133,.08)}}.offlineName{{display:block;color:#fdf2f8;font-size:11px;font-weight:900;line-height:1.25;text-transform:none;letter-spacing:0}}
@@ -5022,7 +5065,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
<div class="brand">
<div class="desktopHeader">
<div class="desktopHeaderTop">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v116</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v117</span></span></h1>
<div class="routerSearchDock" id="routerSearchDock">
<button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false">
<span>Поиск роутеров</span>
@@ -5334,29 +5377,6 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
<a class="sessionBtn btn good" id="backupDownload" href="/api/backup/download">Скачать</a>
</div>
<div class="backupHint">Архив переносит БД роутеров, логин, токены Hub/агента, push-ключи и уведомления. Для переезда на другой IP укажи новый VPS host/Public URL перед восстановлением.</div>
<div class="backupCmds">
<div class="backupCmd">
<strong>1. Сделать backup на старой VPS</strong>
<pre>/opt/owrt-remote/owrt-remote-hub.py backup --out /root/owrt-hub-backup.tar.gz</pre>
</div>
<div class="backupCmd">
<strong>2. Поднять Hub на новой VPS</strong>
<pre>curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/install-vps.sh?v=$(date +%s)" | sh</pre>
</div>
<div class="backupCmd">
<strong>3. Перенести архив на новую VPS</strong>
<pre>scp /root/owrt-hub-backup.tar.gz root@NEW_IP:/root/owrt-hub-backup.tar.gz</pre>
</div>
<div class="backupCmd">
<strong>4. Восстановить на новой VPS с новым IP/domain</strong>
<pre>/opt/owrt-remote/owrt-remote-hub.py restore --file /root/owrt-hub-backup.tar.gz --vps-host NEW_IP_OR_DOMAIN --public-url https://NEW_DOMAIN</pre>
</div>
<div class="backupCmd">
<strong>5. Применить после restore</strong>
<pre>systemctl restart owrt-remote
systemctl restart owrt-remote-xray</pre>
</div>
</div>
<div class="backupGrid">
<input class="wide" id="backupFile" type="file" accept=".gz,.tgz,.tar.gz,application/gzip,application/x-gzip">
<input id="backupVpsHost" placeholder="Новый VPS host/IP">
@@ -5375,7 +5395,7 @@ systemctl restart owrt-remote-xray</pre>
</div>
</div>
<div class="mobileSearchDock" id="mobileRouterSearchDock">
<span class="mobileSearchVersion">v116</span>
<span class="mobileSearchVersion">v117</span>
<button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false">
<span>Поиск роутеров</span>
</button>
@@ -12203,10 +12223,10 @@ def router_logs_html(router):
@media(max-width:680px),(pointer:coarse){body{background-attachment:scroll;background-image:linear-gradient(145deg,#07040f,#120a24 54%,#05030a)}.legend{justify-content:center;text-align:center;row-gap:8px}}
</style></head><body><main class="wrap"><section class="panel">
<div class="head"><h1>Глобал логи</h1><a class="btn" href="/">Вернуться в Hub</a></div><h2>__TITLE__</h2>
<blockquote class="note">Действия панели, Heartbeat, WAN, предупреждения и ошибки Xray этого роутера. Копия доставляется на VPS каждые 3 секунды, пока доступна связь. Если роутер оффлайн, доступны последние доставленные записи. На роутере журнал хранится только в ОЗУ и очищается после перезагрузки и каждые 24 часа. Архив VPS сохраняется отдельно: до 2 МБ на роутер. Ключи и пароли скрываются.</blockquote>
<blockquote class="note">Действия панели, Heartbeat, WAN, предупреждения и ошибки Xray этого роутера. Доставка проверяется каждые 3 секунды; новые записи обычно появляются после пакетной записи на Flash, до 60 секунд. На обновлённом роутере журнал сохраняется на проверенной Flash, временный буфер ограничен 16 КиБ. Если роутер оффлайн, доступны последние доставленные записи. Архив VPS хранится в SQLite на диске: до 2 МиБ на роутер. Ключи и пароли скрываются.</blockquote>
<div class="legend" aria-label="Цвета журнала"><span class="ok">● Успешно</span><span class="warn">● Предупреждение</span><span class="error">● Ошибка</span></div>
<div class="actions"><a class="btn" href="__DOWNLOAD__">Скачать логи</a><button class="btn" id="logsLive" type="button">Запустить в реальном времени</button><button class="btn bad" id="logsClear" type="button">Очистить логи</button></div>
<div id="logsDiagnosis" class="warn" role="status">Получаю состояние роутера…</div><div id="logsStatus" role="status">Загружаю сохранённые записи с VPS…</div><pre id="logsText" tabindex="0">Загрузка записей журнала…</pre>
<div id="logsDiagnosis" class="warn" role="status">Получаю состояние роутера…</div><div id="logsStorage" role="status"></div><div id="logsStatus" role="status">Загружаю сохранённые записи с VPS…</div><pre id="logsText" tabindex="0">Загрузка записей журнала…</pre>
</section></main><script>
(function(){
const endpoint=__ENDPOINT__, output=document.getElementById('logsText'), status=document.getElementById('logsStatus'), diagnosis=document.getElementById('logsDiagnosis'), live=document.getElementById('logsLive'), clear=document.getElementById('logsClear');
@@ -12231,6 +12251,8 @@ def router_logs_html(router):
const data=await response.json();if(current!==generation)return;
render(data.text||'');
showDiagnosis(data);
const storage=data.storage, storageLabel=document.getElementById('logsStorage');
if(storage){storageLabel.className=storage.persistent===false?'error':storage.persistent===true?'ok':'warn';storageLabel.textContent=(storage.persistent===false?'Внимание: архив VPS находится в RAM и исчезнет после перезагрузки.':storage.persistent===true?'Архив VPS: постоянный диск.':'Архив VPS: тип хранилища не подтверждён.')+' '+storage.path+' · '+storage.filesystem+' · Лимит: 2 МиБ на роутер.';}
status.textContent=(data.online?'Роутер онлайн':'Роутер оффлайн — показан архив VPS')+' · Последняя доставка: '+stamp(data.last_sync)+' · Объём архива: '+Math.ceil(data.bytes/1024)+' КБ'+(data.bytes>65536?' · На экране последние 64 КБ; полный журнал доступен через «Скачать логи».':'')+(data.pending_clear?' · Очистка журнала роутера ожидает связи.':'');
}catch(error){if(current===generation)status.textContent='Не удалось получить логи: '+error.message+(running?'. Повтор через 3 секунды.':'');}
finally{clearTimeout(timeout);if(controller===request)controller=null;if(current===generation&&running&&!document.hidden)timer=setTimeout(refresh,3000);}
@@ -12815,7 +12837,7 @@ button:hover{{filter:brightness(1.06)}}
<form class="login" method="post" action="/login">
{error_html}
<span class="brand">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v116</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v117</span></span></h1>
</span>
<label for="hubUsername">Логин</label>
<input id="hubUsername" name="username" autocomplete="off" autofocus required>
@@ -13287,7 +13309,7 @@ body::after{{content:"";position:fixed;inset:0;pointer-events:none;background:li
<circle cx="65" cy="59" r="3" fill="#E5F2FF"/>
</svg>
</div>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v116</span></h2>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v117</span></h2>
</div>
</div>
<div class="brandBottom">
@@ -15852,7 +15874,8 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}}
self.send_bytes(200, raw, 'text/plain; charset=utf-8',
[('Cache-Control', 'no-store'), ('Content-Disposition', f'attachment; filename="{filename}"')])
else:
payload = {'ok': True, 'router_id': router_id, 'online': router['online'], **snapshot}
payload = {'ok': True, 'router_id': router_id, 'online': router['online'],
'storage': router_log_storage(self.app.db_path), **snapshot}
if mode == 'clear':
payload['message'] = 'Архив VPS очищен. Журнал роутера будет очищен при следующем соединении.'
self.send_json(200, payload)