chore: bump release to v113

This commit is contained in:
kzolotarev95 committed 2026-10-11 15:30:40 +04:00
1 parent bcbcb071cc
commit d54d551cd5
21 files changed
+310 -66

No files matched your search

+4 -2
View File
@@ -380,8 +380,10 @@ wan_post_json() {
grep -Fqx "$ip $port" "$WAN_STATE/endpoints" || return 1 grep -Fqx "$ip $port" "$WAN_STATE/endpoints" || return 1
fi fi
case "$ip" in *:*) ip="[$ip]" ;; esac case "$ip" in *:*) ip="[$ip]" ;; esac
# No redirect-following or certificate bypass; Host and SNI remain the URL's. # Follow nginx HTTP-to-HTTPS redirects while preserving this JSON POST.
curl -fsS --noproxy '*' --interface "$device" --connect-timeout 4 --max-time 10 \ # Host and TLS SNI remain the configured URL's; no certificate bypass is used.
curl -fsSL --location --max-redirs 3 --post301 --post302 --post303 \
--noproxy '*' --interface "$device" --connect-timeout 4 --max-time 10 \
--resolve "$host:$port:$ip" \ --resolve "$host:$port:$ip" \
-H "Authorization: Bearer $token" -H 'Content-Type: application/json' \ -H "Authorization: Bearer $token" -H 'Content-Type: application/json' \
--data-binary "@$file" "$url" --data-binary "@$file" "$url"
+8 -3
View File
@@ -664,13 +664,15 @@ run_xray() {
} }
heartbeat_json() { heartbeat_json() {
local router_id router_name role public_url hub_url xray_state service_state ssh_state event local router_id router_name role public_url hub_url xray_state service_state ssh_state event heartbeat_interval
event="${1:-}" event="${1:-}"
router_id="$(safe_id "$(uci_get router_id main)")" router_id="$(safe_id "$(uci_get router_id main)")"
router_name="$(uci_get router_name "$router_id")" router_name="$(uci_get router_name "$router_id")"
role="$(uci_get role node)" role="$(uci_get role node)"
public_url="$(uci_get public_url '')" public_url="$(uci_get public_url '')"
hub_url="$(uci_get hub_url '')" hub_url="$(uci_get hub_url '')"
heartbeat_interval="$(safe_num "$(uci_get heartbeat_interval 30)" 30)"
[ "$heartbeat_interval" -lt 10 ] && heartbeat_interval=10
if xray_running; then if xray_running; then
xray_state="running" xray_state="running"
@@ -706,6 +708,7 @@ heartbeat_json() {
"vps_host": $(json_string "$(uci_get vps_host '')"), "vps_host": $(json_string "$(uci_get vps_host '')"),
"vps_host_mode": $(json_string "$(vps_host_mode)"), "vps_host_mode": $(json_string "$(vps_host_mode)"),
"wan_direct": $(json_string "$(uci_get wan_direct 0)"), "wan_direct": $(json_string "$(uci_get wan_direct 0)"),
"heartbeat_interval": $heartbeat_interval,
"uptime": $(safe_num "$(uptime_seconds)" 0), "uptime": $(safe_num "$(uptime_seconds)" 0),
"load": $(json_string "$(load_text)"), "load": $(json_string "$(load_text)"),
"memory": $(json_string "$(memory_text)"), "memory": $(json_string "$(memory_text)"),
@@ -730,7 +733,8 @@ post_json() {
fi fi
if command -v curl >/dev/null 2>&1; then if command -v curl >/dev/null 2>&1; then
curl -fsS --connect-timeout 4 --max-time 10 --noproxy '*' \ curl -fsSL --location --max-redirs 3 --post301 --post302 --post303 \
--connect-timeout 4 --max-time 10 --noproxy '*' \
-H "Authorization: Bearer $token" \ -H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary "@$file" "$url" --data-binary "@$file" "$url"
@@ -850,7 +854,8 @@ send_heartbeat() {
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"; then if post_json "$endpoint" "$token" "$tmp" >"$response" \
&& 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" rm -f "$tmp" "$response"
+2 -2
View File
@@ -387,7 +387,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 v112</title> <title>OpenWrt Remote Hub v113</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}
@@ -418,7 +418,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">v112</span></span></h1> <h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v113</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>
@@ -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 v112')), E('h2', {}, _('OpenWrt Remote Hub v113')),
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 v112')), E('h2', {}, _('OpenWrt Remote Hub v113')),
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'))
+10 -10
View File
@@ -1,4 +1,4 @@
# Фиксация VPS host и независимое соединение Remote через WAN (v112) # Фиксация VPS host и независимое соединение Remote через WAN (v113)
`vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение `vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение
используется и когда опция отсутствует у старой установки. Только явно используется и когда опция отсутствует у старой установки. Только явно
@@ -96,21 +96,21 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.
Установка загружает локальные файлы, без Git. До остановки службы проверяются Установка загружает локальные файлы, без Git. До остановки службы проверяются
доступность WAN и поддержка таблицы реальной командой ip на роутере. доступность WAN и поддержка таблицы реальной командой ip на роутере.
На роутер загружается и файл LuCI: версия v112 появляется и в основной На роутер загружается и файл LuCI: версия v113 появляется и в основной
CGI-панели, и в странице входа в неё через LuCI. CGI-панели, и в странице входа в неё через LuCI.
Сначала сохраняются файлы Сначала сохраняются файлы
и конфигурация; после замены проверяется heartbeat/health. При ошибке и конфигурация; после замены проверяется heartbeat/health. При ошибке
автоматически восстанавливается состояние перед текущей попыткой. автоматически восстанавливается состояние перед текущей попыткой.
Сохранённая резервная копия для ручного отката не перезаписывается. Сохранённая резервная копия для ручного отката не перезаписывается.
* Роутер: `/root/owrt-remote-backup-before-host-policy-v112` — агент, * Роутер: `/root/owrt-remote-backup-before-host-policy-v113` — агент,
helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге). helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге).
* VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v112`. * VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v113`.
База роутеров и настройки авторизации не заменяются. База роутеров и настройки авторизации не заменяются.
Успешная установка заканчивается `HOST_POLICY_ROUTER_V112_OK` на роутере Успешная установка заканчивается `HOST_POLICY_ROUTER_V113_OK` на роутере
и `HOST_POLICY_VPS_V112_Install_OK` на VPS. Старые резервные копии предыдущей и `HOST_POLICY_VPS_V113_Install_OK` на VPS. Старые резервные копии предыдущей
версии сохраняются; новые команды отката используют отдельные копии для v112. версии сохраняются; новые команды отката используют отдельные копии для v113.
### Переход с nftables-маркировки на адресную маршрутизацию ### Переход с nftables-маркировки на адресную маршрутизацию
@@ -119,11 +119,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-v112" -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-v113" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v112" -Action Rollback powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v113" -Action Rollback
``` ```
Копия: `/root/owrt-remote-backup-before-podkop-compat-v112`. Копия: `/root/owrt-remote-backup-before-podkop-compat-v113`.
После установки повторите диагностику Podkop. Предупреждение от прежних правил После установки повторите диагностику Podkop. Предупреждение от прежних правил
Remote должно исчезнуть. Настоящие дополнительные правила других приложений Remote должно исчезнуть. Настоящие дополнительные правила других приложений
по-прежнему обнаруживаются штатной диагностикой. по-прежнему обнаруживаются штатной диагностикой.
+3 -3
View File
@@ -1,4 +1,4 @@
# reCAPTCHA v3 в OpenWrt Remote Hub v112 # reCAPTCHA v3 в OpenWrt Remote Hub v113
В меню владельца, в блоке «Капча на экране входа», доступны цифры, В меню владельца, в блоке «Капча на экране входа», доступны цифры,
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-v112` * `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v113`
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v112.json` (режим 0600). * `/opt/owrt-remote/captcha-before-recaptcha-v3-v113.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 v112 # Аудит ресурсов OpenWrt Remote Hub v113
Исправления внесены поверх `7f809fd`. Версия панели остаётся v112. Исправления внесены поверх `7f809fd`. Версия панели остаётся v113.
## 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-v112`, `/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v113`,
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health. атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
Существующая резервная копия не перезаписывается. При ошибке установки Существующая резервная копия не перезаписывается. При ошибке установки
восстанавливается файл, работавший непосредственно перед текущей попыткой. восстанавливается файл, работавший непосредственно перед текущей попыткой.
+4 -4
View File
@@ -1,4 +1,4 @@
# Виджеты ресурсов VPS (v112) # Виджеты ресурсов VPS (v113)
Три карточки ЦП, ОЗУ и ДИСК находятся над кнопками «Рестарт 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_V112_Install_OK` обновите страницу через Ctrl+F5. После `VPS_WIDGETS_V113_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-v112`. `/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v113`.
Успешное завершение: `VPS_WIDGETS_V112_Rollback_OK`. Успешное завершение: `VPS_WIDGETS_V113_Rollback_OK`.
## Локальные проверки ## Локальные проверки
+2 -2
View File
@@ -1,4 +1,4 @@
# Несколько WAN интерфейсов и резервирование (v112) # Несколько WAN интерфейсов и резервирование (v113)
Кнопка **Выбрать интерфейсы** раскрывает список с галочками. Можно отметить Кнопка **Выбрать интерфейсы** раскрывает список с галочками. Можно отметить
один, два, три и больше интерфейсов. Список содержит имена один, два, три и больше интерфейсов. Список содержит имена
@@ -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-v112`. `/root/owrt-remote-backup-before-wan-multi-v113`.
Успех подтверждает `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`
+2 -2
View File
@@ -1,4 +1,4 @@
# Применение OpenWrt config через панель роутера (v112) # Применение OpenWrt config через панель роутера (v113)
При отправке 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-v112/owrt-remote`. `/root/owrt-remote-backup-before-xray-apply-v113/owrt-remote`.
Из PowerShell Windows 11; замените IP, если адрес роутера отличается: Из PowerShell Windows 11; замените IP, если адрес роутера отличается:
+18
View File
@@ -346,6 +346,24 @@ class RouterShellTests(unittest.TestCase):
self.assertIn("<https://hub.example/api/heartbeat>", args) self.assertIn("<https://hub.example/api/heartbeat>", args)
self.assertNotIn("<-k>", args) self.assertNotIn("<-k>", args)
self.assertIn("<--max-time>\n<10>", args) self.assertIn("<--max-time>\n<10>", args)
self.assertIn("<--location>", args)
self.assertIn("<--post301>", args)
self.assertIn("<--post302>", args)
self.assertIn("<--post303>", args)
def test_plain_http_heartbeat_accepts_json_after_redirect_follow(self):
self.config(vps_host="193.233.82.38", vps_host_mode="manual")
result = self.run_shell('''
curl() {
printf '<%s>\n' "$@" >"$TEST_ROOT/curl"
printf '{"ok":true}'
}
post_json http://hub.example/api/heartbeat test-token "$TEST_ROOT/payload"
''')
self.assertEqual(result.returncode, 0, result.stderr)
args = (self.directory / "curl").read_text()
self.assertIn("<--location>", args)
self.assertIn("<--post301>", args)
def test_literal_ip_fallback_is_not_rewritten_to_a_different_pin(self): def test_literal_ip_fallback_is_not_rewritten_to_a_different_pin(self):
self.config(vps_host="193.233.82.38", vps_host_mode="manual") self.config(vps_host="193.233.82.38", vps_host_mode="manual")
+23 -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"v112" in self.request("/") assert b"v113" in self.request("/")
self.app.snapshot_router_states() self.app.snapshot_router_states()
def __exit__(self, *args): def __exit__(self, *args):
@@ -428,6 +428,28 @@ class OtherResourceTests(unittest.TestCase):
class IntegrationTests(unittest.TestCase): class IntegrationTests(unittest.TestCase):
def test_router_online_grace_tolerates_delayed_heartbeat_and_custom_interval(self):
now = hub.now_ts()
base = {
"id": "delayed-router",
"name": "Delayed Router",
"custom_name": "",
"notes": "",
"created_at": now,
"updated_at": now,
"status_json": json.dumps({"heartbeat_interval": 30}),
}
router = hub.row_to_router({**base, "last_seen": now - 120})
self.assertTrue(router["online"], "a short WAN/Xray rebind must not mark the router offline")
router = hub.row_to_router({**base, "last_seen": now - 181})
self.assertFalse(router["online"])
custom = hub.row_to_router({
**base,
"status_json": json.dumps({"heartbeat_interval": 120}),
"last_seen": now - 350,
})
self.assertTrue(custom["online"], "the grace period must follow a slower configured heartbeat")
def test_panel_api_proxy_heartbeat_and_monitor(self): def test_panel_api_proxy_heartbeat_and_monitor(self):
with HubFixture() as fixture: with HubFixture() as fixture:
for _ in range(5): for _ in range(5):
+94
View File
@@ -0,0 +1,94 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Router,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-heartbeat-redirect-' + [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-heartbeat-redirect-v113
agent=/usr/sbin/owrt-remote
wan=/usr/lib/owrt-remote/wan.sh
changed=0
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
/etc/init.d/owrt-remote stop >/dev/null 2>&1 || true
cp -p "$stage/previous-agent" "$agent" || true
cp -p "$stage/previous-wan" "$wan" || true
/etc/init.d/owrt-remote restart >/dev/null 2>&1 || true
fi
rm -f "$agent.new-__UPLOAD_NAME__" "$wan.new-__UPLOAD_NAME__"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$agent"
test -s "$wan"
if [ '__ACTION__' = Install ]; then
test -s "$stage/agent"
test -s "$stage/wan.sh"
sh -n "$stage/agent"
sh -n "$stage/wan.sh"
grep -F -q -- '--post301' "$stage/agent"
grep -F -q -- '--post301' "$stage/wan.sh"
mkdir -p "$backup"
chmod 700 "$backup"
if [ ! -e "$backup/agent" ]; then cp -p "$agent" "$backup/agent"; fi
if [ ! -e "$backup/wan.sh" ]; then cp -p "$wan" "$backup/wan.sh"; fi
source_agent="$stage/agent"
source_wan="$stage/wan.sh"
else
test -s "$backup/agent"
test -s "$backup/wan.sh"
source_agent="$backup/agent"
source_wan="$backup/wan.sh"
fi
cp -p "$agent" "$stage/previous-agent"
cp -p "$wan" "$stage/previous-wan"
changed=1
cp "$source_agent" "$agent.new-__UPLOAD_NAME__"
chmod 0755 "$agent.new-__UPLOAD_NAME__"
mv -f "$agent.new-__UPLOAD_NAME__" "$agent"
cp "$source_wan" "$wan.new-__UPLOAD_NAME__"
chmod 0644 "$wan.new-__UPLOAD_NAME__"
mv -f "$wan.new-__UPLOAD_NAME__" "$wan"
/etc/init.d/owrt-remote restart
sh -n "$agent"
sh -n "$wan"
cmp "$source_agent" "$agent"
cmp "$source_wan" "$wan"
printf '\nBackup: %s\nHEARTBEAT_REDIRECT_ROUTER_%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') {
foreach ($Item in @{ 'agent' = 'files\usr\sbin\owrt-remote'; 'wan.sh' = 'files\usr\lib\owrt-remote\wan.sh' }.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 router was not changed.' }
& 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 "Heartbeat redirect 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 }
}
}
+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-v112', [ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v113',
[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 'v112' "$stage/$item"; done for item in cgi luci; do grep -F -q 'v113' "$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 'v112' /www/cgi-bin/owrt-remote grep -F -q 'v113' /www/cgi-bin/owrt-remote
grep -F -q 'v112' /www/luci-static/resources/view/owrt_remote.js grep -F -q 'v113' /www/luci-static/resources/view/owrt_remote.js
echo HOST_POLICY_ROUTER_V112_OK echo HOST_POLICY_ROUTER_V113_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_V112_ROLLBACK_OK echo HOST_POLICY_ROUTER_V113_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-v112 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v113
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 'v112' "$stage/hub.py" grep -F -q 'v113' "$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_V112_%s_OK\n' '__ACTION__' printf '\nHOST_POLICY_VPS_V113_%s_OK\n' '__ACTION__'
'@ '@
} }
+90
View File
@@ -0,0 +1,90 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-online-status-' + [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-online-status-v113
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
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"
grep -F -q 'router_online_timeout' "$stage/hub.py"
grep -F -q 'ONLINE_AFTER_SECONDS' "$stage/hub.py"
"$python_bin" -m py_compile "$stage/hub.py"
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
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 755 "$candidate"
changed=1
mv -f "$candidate" "$target"
systemctl restart owrt-remote
healthy=0
for attempt in 1 2 3 4 5 6 7 8 9 10; 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
test "$healthy" = 1
cmp "$source_file" "$target"
printf '\nBackup: %s\nONLINE_STATUS_V113_%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') {
foreach ($Item in @{
'hub.py' = 'vps\owrt-remote-hub.py'
'tests.py' = 'tests\test_resource_lifecycle.py'
}.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 "${Vps}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Installation has not started.' }
& 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 "Online status 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 }
}
}
+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-v112 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v113
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v112.json captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v113.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 'v112' in source assert 'v113' 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_V112_OK echo RECAPTCHA_V3_V113_OK
'@ '@
} elseif ($Action -eq 'Rollback') { } elseif ($Action -eq 'Rollback') {
$RemoteScript = @' $RemoteScript = @'
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V112_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-v112 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v113
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v112.json captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v113.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-v112 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v113
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 'v112' in source assert 'v113' 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_V112_OK echo RESOURCE_FIX_V113_OK
'@ '@
} elseif ($Action -eq 'Rollback') { } elseif ($Action -eq 'Rollback') {
$RemoteScript = @' $RemoteScript = @'
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V112_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-v112 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v113
candidate=$target.rollback-__UPLOAD_NAME__ candidate=$target.rollback-__UPLOAD_NAME__
changed=0 changed=0
cleanup() { cleanup() {
+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-v112 backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v113
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 'v112' "$stage/hub.py" grep -F -q 'v113' "$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_V112_%s_OK\n' '__ACTION__' printf '\nVPS_WIDGETS_V113_%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-v112 backup=/root/owrt-remote-backup-before-wan-multi-v113
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 'v112' "$stage/$item"; done for item in cgi luci; do grep -F -q 'v113' "$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
@@ -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-v112 backup_dir=/root/owrt-remote-backup-before-xray-apply-v113
backup=$backup_dir/owrt-remote backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__ candidate=$target.new-__UPLOAD_NAME__
changed=0 changed=0
+20 -7
View File
@@ -93,7 +93,9 @@ AGENT_TOKEN_FILE = STATE_DIR / "agent.token"
XRAY_WAN_RECONNECT_FILE = STATE_DIR / "xray-wan-reconnect-restart.json" XRAY_WAN_RECONNECT_FILE = STATE_DIR / "xray-wan-reconnect-restart.json"
TRAFFIC_COUNTERS_FILE = STATE_DIR / "hub-traffic-counters.json" TRAFFIC_COUNTERS_FILE = STATE_DIR / "hub-traffic-counters.json"
ACME_WEBROOT = STATE_DIR / "acme-webroot" ACME_WEBROOT = STATE_DIR / "acme-webroot"
ONLINE_AFTER_SECONDS = int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "75")) # Heartbeats normally arrive every 30 seconds. A short WAN/Xray rebind can
# take longer than the old 75-second window while the reverse tunnel remains usable.
ONLINE_AFTER_SECONDS = max(75, int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "180")))
DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443")) DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443"))
REQUEST_QUEUE_SIZE = int(os.environ.get("OWRT_REMOTE_REQUEST_QUEUE_SIZE", "128")) REQUEST_QUEUE_SIZE = int(os.environ.get("OWRT_REMOTE_REQUEST_QUEUE_SIZE", "128"))
ROUTER_PROXY_LIMIT = max(1, int(os.environ.get("OWRT_REMOTE_ROUTER_PROXY_LIMIT", "4"))) ROUTER_PROXY_LIMIT = max(1, int(os.environ.get("OWRT_REMOTE_ROUTER_PROXY_LIMIT", "4")))
@@ -3446,7 +3448,7 @@ def row_to_router(row):
data["name"] = custom_name data["name"] = custom_name
last_seen = data.get("last_seen") last_seen = data.get("last_seen")
service_enabled = str(status.get("service") or "").lower() != "disabled" service_enabled = str(status.get("service") or "").lower() != "disabled"
online = bool(last_seen and now_ts() - int(last_seen) <= ONLINE_AFTER_SECONDS) online = bool(last_seen and now_ts() - int(last_seen) <= router_online_timeout(status))
data["status"] = status data["status"] = status
data["service_enabled"] = service_enabled data["service_enabled"] = service_enabled
data["online"] = online data["online"] = online
@@ -3460,6 +3462,17 @@ def row_to_router(row):
return data return data
def router_online_timeout(status):
"""Return a heartbeat grace period that tolerates WAN/Xray rebinds."""
status = status if isinstance(status, dict) else {}
try:
interval = int(status.get("heartbeat_interval") or 30)
except (TypeError, ValueError):
interval = 30
interval = min(max(interval, 10), 3600)
return max(ONLINE_AFTER_SECONDS, interval * 3 + 30)
def router_with_access(router, account): def router_with_access(router, account):
router = dict(router or {}) router = dict(router or {})
router_id = str(router.get("id") or "") router_id = str(router.get("id") or "")
@@ -3559,7 +3572,7 @@ def notify_router_online(router, dedupe_seconds=45):
def notify_router_offline(router, dedupe_seconds=0): def notify_router_offline(router, dedupe_seconds=0):
label = router_notification_label(router) label = router_notification_label(router)
grace = max(ONLINE_AFTER_SECONDS, 1) grace = router_online_timeout((router or {}).get("status"))
add_notification( add_notification(
"router_offline", "router_offline",
"Роутер пропал из сети", "Роутер пропал из сети",
@@ -4765,7 +4778,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">v112</span></span></h1> <h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v113</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>
@@ -5118,7 +5131,7 @@ systemctl restart owrt-remote-xray</pre>
</div> </div>
</div> </div>
<div class="mobileSearchDock" id="mobileRouterSearchDock"> <div class="mobileSearchDock" id="mobileRouterSearchDock">
<span class="mobileSearchVersion">v112</span> <span class="mobileSearchVersion">v113</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>
@@ -12646,7 +12659,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">v112</span></span></h1> <h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v113</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>
@@ -13118,7 +13131,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">v112</span></h2> <h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v113</span></h2>
</div> </div>
</div> </div>
<div class="brandBottom"> <div class="brandBottom">