chore: bump release to v114
This commit is contained in:
1 parent
d54d551cd5
commit
84f4d43486
22 files changed
+693
-99
No files matched your search
@@ -795,6 +795,26 @@ heartbeat_candidate_endpoints() {
|
|||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
|
heartbeat_set_url_if_changed() {
|
||||||
|
local key next current ignored_file ignored
|
||||||
|
key="$1"
|
||||||
|
next="$2"
|
||||||
|
case "$next" in http://?*|https://?*) ;; *) return 1 ;; esac
|
||||||
|
current="$(uci_get "$key" '')"
|
||||||
|
case "$current|$next" in
|
||||||
|
https://*'|'http://*)
|
||||||
|
ignored_file="${TMPDIR:-/tmp}/owrt-remote-$key-ignored"
|
||||||
|
ignored="$current|$next"
|
||||||
|
if [ "$(cat "$ignored_file" 2>/dev/null)" != "$ignored" ]; then
|
||||||
|
log "heartbeat kept $key: current=$current proposed=$next reason=https-downgrade"
|
||||||
|
printf '%s' "$ignored" >"$ignored_file"
|
||||||
|
fi
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
uci_set_if_changed "$key" "$next"
|
||||||
|
}
|
||||||
|
|
||||||
heartbeat_apply_hub_update() {
|
heartbeat_apply_hub_update() {
|
||||||
local response_file fallback_base next_hub_url next_public_url next_vps_host changed old_vps_host mode ignored_file ignored
|
local response_file fallback_base next_hub_url next_public_url next_vps_host changed old_vps_host mode ignored_file ignored
|
||||||
response_file="$1"
|
response_file="$1"
|
||||||
@@ -804,12 +824,15 @@ heartbeat_apply_hub_update() {
|
|||||||
next_vps_host="$(json_extract_object_string "$response_file" hub_update vps_host)"
|
next_vps_host="$(json_extract_object_string "$response_file" hub_update vps_host)"
|
||||||
old_vps_host="$(uci_get vps_host '')"
|
old_vps_host="$(uci_get vps_host '')"
|
||||||
mode="$(vps_host_mode)"
|
mode="$(vps_host_mode)"
|
||||||
[ -n "$next_hub_url" ] || next_hub_url="$fallback_base"
|
# A fallback is a temporary transport, not a new configured Hub URL.
|
||||||
|
if [ -z "$next_hub_url" ] && [ -z "$(uci_get hub_url '')" ]; then
|
||||||
|
next_hub_url="$fallback_base"
|
||||||
|
fi
|
||||||
changed=0
|
changed=0
|
||||||
if uci_set_if_changed hub_url "$next_hub_url"; then
|
if heartbeat_set_url_if_changed hub_url "$next_hub_url"; then
|
||||||
changed=1
|
changed=1
|
||||||
fi
|
fi
|
||||||
if uci_set_if_changed public_url "$next_public_url"; then
|
if heartbeat_set_url_if_changed public_url "$next_public_url"; then
|
||||||
changed=1
|
changed=1
|
||||||
fi
|
fi
|
||||||
if [ "$mode" = auto ]; then
|
if [ "$mode" = auto ]; then
|
||||||
|
|||||||
@@ -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 v113</title>
|
<title>OpenWrt Remote Hub v114</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">v113</span></span></h1>
|
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v114</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>
|
||||||
@@ -517,7 +517,7 @@ EOF
|
|||||||
field vps_host "VPS host" text "IP или домен VPS, куда Xray роутера подключается reverse-туннелем. Бери IP/домен своего VPS."
|
field vps_host "VPS host" text "IP или домен VPS, куда Xray роутера подключается reverse-туннелем. Бери IP/домен своего VPS."
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
<label class="check"><input type="checkbox" name="vps_host_auto" value="1" $vps_host_auto_checked> Автоматически обновлять VPS host</label>
|
<label class="check"><input type="checkbox" name="vps_host_auto" value="1" $vps_host_auto_checked> Автоматически обновлять VPS host</label>
|
||||||
<span class="hint">Выключено: заданный VPS host сохраняется, heartbeat не меняет его.</span>
|
<span class="hint">Управляет только адресом Xray: выключено — VPS host сохраняется; включено — Hub может изменить его и перезапустить Xray. Hub URL настраивается отдельно.</span>
|
||||||
<label class="check"><input type="checkbox" name="wan_direct" value="1" $wan_direct_checked> Соединение с Hub напрямую через WAN</label>
|
<label class="check"><input type="checkbox" name="wan_direct" value="1" $wan_direct_checked> Соединение с Hub напрямую через WAN</label>
|
||||||
<span class="hint">Heartbeat и Xray обходят Podkop. DNS берётся с WAN, настройки LAN не меняются.</span>
|
<span class="hint">Heartbeat и Xray обходят Podkop. DNS берётся с WAN, настройки LAN не меняются.</span>
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -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 v113')),
|
E('h2', {}, _('OpenWrt Remote Hub v114')),
|
||||||
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 v113')),
|
E('h2', {}, _('OpenWrt Remote Hub v114')),
|
||||||
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'))
|
||||||
|
|||||||
+39
-10
@@ -1,4 +1,4 @@
|
|||||||
# Фиксация VPS host и независимое соединение Remote через WAN (v113)
|
# Фиксация VPS host и независимое соединение Remote через WAN (v114)
|
||||||
|
|
||||||
`vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение
|
`vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение
|
||||||
используется и когда опция отсутствует у старой установки. Только явно
|
используется и когда опция отсутствует у старой установки. Только явно
|
||||||
@@ -12,12 +12,41 @@ Hub сохраняет прежнее поведение для старых а
|
|||||||
при старой версии Hub. Для полного фикса сначала обновляется роутер.
|
при старой версии Hub. Для полного фикса сначала обновляется роутер.
|
||||||
|
|
||||||
На роутере в настройках есть «Автоматически обновлять VPS host».
|
На роутере в настройках есть «Автоматически обновлять VPS host».
|
||||||
|
Эта галочка относится только к адресу reverse-подключения Xray, не к Hub URL.
|
||||||
|
При автоматическом изменении VPS host агент перезапускает Xray; в ручном
|
||||||
|
режиме адрес подключения остаётся заданным пользователем.
|
||||||
Блок «Настроить VPS host» убран из карточек Hub на ПК и мобильном.
|
Блок «Настроить VPS host» убран из карточек Hub на ПК и мобильном.
|
||||||
Он не появляется при периодическом обновлении карточек. Сам механизм
|
Он не появляется при периодическом обновлении карточек. Сам механизм
|
||||||
ручного/автоматического режима и API применения адреса по SSH сохраняются.
|
ручного/автоматического режима и API применения адреса по SSH сохраняются.
|
||||||
OpenWrt config / автоматическое переприменение конфигурации больше не
|
OpenWrt config / автоматическое переприменение конфигурации больше не
|
||||||
удаляет всю UCI-секцию и сохраняет существующий ручной адрес и WAN-параметры.
|
удаляет всю UCI-секцию и сохраняет существующий ручной адрес и WAN-параметры.
|
||||||
|
|
||||||
|
## Защита Hub URL от автоматического перехода HTTPS → HTTP
|
||||||
|
|
||||||
|
Heartbeat больше не заменяет сохранённые HTTPS-адреса Hub URL и Public URL
|
||||||
|
на HTTP из ответа сервера. Резервное подключение тоже не становится новым
|
||||||
|
Hub URL, если адрес уже настроен. Отклонение видно в logread с причиной
|
||||||
|
`https-downgrade`; одинаковые предложения не повторяются в журнале.
|
||||||
|
Hub использует известный HTTPS для того же домена вместо старого HTTP
|
||||||
|
при ответе heartbeat и формировании конфигурации. HTTPS на нестандартном
|
||||||
|
порту и установки, работающие только по HTTP, сохраняются. Изменить схему
|
||||||
|
вручную через настройки по-прежнему можно.
|
||||||
|
|
||||||
|
Для этого локального исправления есть отдельная установка с резервными
|
||||||
|
копиями файлов и конфигурации. `-HubUrl` явно возвращает адрес на роутере;
|
||||||
|
VPS host и его автоматический режим эта установка не меняет.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-hub-url-fix.ps1" -Target Router -Machine "root@192.168.1.1" -HubUrl "https://owrt-zks95.developer.li" -Action Install
|
||||||
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-hub-url-fix.ps1" -Target Vps -Machine "root@193.233.82.38" -Action Install
|
||||||
|
```
|
||||||
|
|
||||||
|
Откат: те же команды с `-Action Rollback`, без `-HubUrl`. Резервные копии:
|
||||||
|
`/root/owrt-remote-backup-before-hub-url-v114` на роутере и
|
||||||
|
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-hub-url-v114` на VPS.
|
||||||
|
`HEARTBEAT_OK` подтверждает ответ Hub. Если файлы установлены, но Hub недоступен,
|
||||||
|
скрипт отдельно сообщает `HEARTBEAT_FAILED`; это не подтверждение связи.
|
||||||
|
|
||||||
## Прямой WAN
|
## Прямой WAN
|
||||||
|
|
||||||
`wan_direct=1` включает отдельный маршрут для Remote; по умолчанию эта
|
`wan_direct=1` включает отдельный маршрут для Remote; по умолчанию эта
|
||||||
@@ -96,21 +125,21 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.
|
|||||||
|
|
||||||
Установка загружает локальные файлы, без Git. До остановки службы проверяются
|
Установка загружает локальные файлы, без Git. До остановки службы проверяются
|
||||||
доступность WAN и поддержка таблицы реальной командой ip на роутере.
|
доступность WAN и поддержка таблицы реальной командой ip на роутере.
|
||||||
На роутер загружается и файл LuCI: версия v113 появляется и в основной
|
На роутер загружается и файл LuCI: версия v114 появляется и в основной
|
||||||
CGI-панели, и в странице входа в неё через LuCI.
|
CGI-панели, и в странице входа в неё через LuCI.
|
||||||
Сначала сохраняются файлы
|
Сначала сохраняются файлы
|
||||||
и конфигурация; после замены проверяется heartbeat/health. При ошибке
|
и конфигурация; после замены проверяется heartbeat/health. При ошибке
|
||||||
автоматически восстанавливается состояние перед текущей попыткой.
|
автоматически восстанавливается состояние перед текущей попыткой.
|
||||||
Сохранённая резервная копия для ручного отката не перезаписывается.
|
Сохранённая резервная копия для ручного отката не перезаписывается.
|
||||||
|
|
||||||
* Роутер: `/root/owrt-remote-backup-before-host-policy-v113` — агент,
|
* Роутер: `/root/owrt-remote-backup-before-host-policy-v114` — агент,
|
||||||
helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге).
|
helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге).
|
||||||
* VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v113`.
|
* VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v114`.
|
||||||
База роутеров и настройки авторизации не заменяются.
|
База роутеров и настройки авторизации не заменяются.
|
||||||
|
|
||||||
Успешная установка заканчивается `HOST_POLICY_ROUTER_V113_OK` на роутере
|
Успешная установка заканчивается `HOST_POLICY_ROUTER_V114_OK` на роутере
|
||||||
и `HOST_POLICY_VPS_V113_Install_OK` на VPS. Старые резервные копии предыдущей
|
и `HOST_POLICY_VPS_V114_Install_OK` на VPS. Старые резервные копии предыдущей
|
||||||
версии сохраняются; новые команды отката используют отдельные копии для v113.
|
версии сохраняются; новые команды отката используют отдельные копии для v114.
|
||||||
|
|
||||||
### Переход с nftables-маркировки на адресную маршрутизацию
|
### Переход с nftables-маркировки на адресную маршрутизацию
|
||||||
|
|
||||||
@@ -119,11 +148,11 @@ CGI-панели, и в странице входа в неё через LuCI.
|
|||||||
Обновление VPS для этого изменения не требуется.
|
Обновление VPS для этого изменения не требуется.
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PreserveConnectionSettings -BackupName "podkop-compat-v113" -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-v114" -Action Install
|
||||||
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
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v114" -Action Rollback
|
||||||
```
|
```
|
||||||
|
|
||||||
Копия: `/root/owrt-remote-backup-before-podkop-compat-v113`.
|
Копия: `/root/owrt-remote-backup-before-podkop-compat-v114`.
|
||||||
После установки повторите диагностику Podkop. Предупреждение от прежних правил
|
После установки повторите диагностику Podkop. Предупреждение от прежних правил
|
||||||
Remote должно исчезнуть. Настоящие дополнительные правила других приложений
|
Remote должно исчезнуть. Настоящие дополнительные правила других приложений
|
||||||
по-прежнему обнаруживаются штатной диагностикой.
|
по-прежнему обнаруживаются штатной диагностикой.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# reCAPTCHA v3 в OpenWrt Remote Hub v113
|
# reCAPTCHA v3 в OpenWrt Remote Hub v114
|
||||||
|
|
||||||
В меню владельца, в блоке «Капча на экране входа», доступны цифры,
|
В меню владельца, в блоке «Капча на экране входа», доступны цифры,
|
||||||
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-v113`
|
* `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v114`
|
||||||
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v113.json` (режим 0600).
|
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v114.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`
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Аудит ресурсов OpenWrt Remote Hub v113
|
# Аудит ресурсов OpenWrt Remote Hub v114
|
||||||
|
|
||||||
Исправления внесены поверх `7f809fd`. Версия панели остаётся v113.
|
Исправления внесены поверх `7f809fd`. Версия панели остаётся v114.
|
||||||
|
|
||||||
## 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-v113`,
|
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v114`,
|
||||||
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
|
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
|
||||||
Существующая резервная копия не перезаписывается. При ошибке установки
|
Существующая резервная копия не перезаписывается. При ошибке установки
|
||||||
восстанавливается файл, работавший непосредственно перед текущей попыткой.
|
восстанавливается файл, работавший непосредственно перед текущей попыткой.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Виджеты ресурсов VPS (v113)
|
# Виджеты ресурсов VPS (v114)
|
||||||
|
|
||||||
Три карточки ЦП, ОЗУ и ДИСК находятся над кнопками «Рестарт 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_V113_Install_OK` обновите страницу через Ctrl+F5.
|
После `VPS_WIDGETS_V114_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-v113`.
|
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v114`.
|
||||||
Успешное завершение: `VPS_WIDGETS_V113_Rollback_OK`.
|
Успешное завершение: `VPS_WIDGETS_V114_Rollback_OK`.
|
||||||
|
|
||||||
## Локальные проверки
|
## Локальные проверки
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Несколько WAN интерфейсов и резервирование (v113)
|
# Несколько WAN интерфейсов и резервирование (v114)
|
||||||
|
|
||||||
Кнопка **Выбрать интерфейсы** раскрывает список с галочками. Можно отметить
|
Кнопка **Выбрать интерфейсы** раскрывает список с галочками. Можно отметить
|
||||||
один, два, три и больше интерфейсов. Список содержит имена
|
один, два, три и больше интерфейсов. Список содержит имена
|
||||||
@@ -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-v113`.
|
`/root/owrt-remote-backup-before-wan-multi-v114`.
|
||||||
Успех подтверждает `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
@@ -1,4 +1,4 @@
|
|||||||
# Применение OpenWrt config через панель роутера (v113)
|
# Применение OpenWrt config через панель роутера (v114)
|
||||||
|
|
||||||
При отправке 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-v113/owrt-remote`.
|
`/root/owrt-remote-backup-before-xray-apply-v114/owrt-remote`.
|
||||||
|
|
||||||
Из PowerShell Windows 11; замените IP, если адрес роутера отличается:
|
Из PowerShell Windows 11; замените IP, если адрес роутера отличается:
|
||||||
|
|
||||||
|
|||||||
@@ -167,6 +167,33 @@ class HostPolicyTests(unittest.TestCase):
|
|||||||
def test_auto_heartbeat_retains_central_host(self):
|
def test_auto_heartbeat_retains_central_host(self):
|
||||||
self.assertEqual(hub.canonical_router_hub_update(self.row("auto"))["vps_host"], "hub.example")
|
self.assertEqual(hub.canonical_router_hub_update(self.row("auto"))["vps_host"], "hub.example")
|
||||||
|
|
||||||
|
def test_stale_http_public_url_prefers_known_https_for_heartbeat_and_rebind(self):
|
||||||
|
for secure_source in ("app", "request", "status"):
|
||||||
|
with self.subTest(source=secure_source):
|
||||||
|
row = {"vps_host": "hub.example", "public_url": "http://hub.example:8088"}
|
||||||
|
app_url = "https://hub.example:9443" if secure_source == "app" else ""
|
||||||
|
request_url = "https://hub.example:9443" if secure_source == "request" else "http://hub.example:8088"
|
||||||
|
if secure_source == "status":
|
||||||
|
row["status_json"] = json.dumps({"hub_url": "https://hub.example:9443"})
|
||||||
|
update = hub.canonical_router_hub_update(row, app_url, request_url)
|
||||||
|
bundle, url, _ = hub.router_current_hub_bundle(row, app_url, request_url)
|
||||||
|
self.assertEqual(update["hub_url"], "https://hub.example:9443")
|
||||||
|
self.assertEqual(update["public_url"], "https://hub.example:9443")
|
||||||
|
self.assertEqual(url, update["hub_url"])
|
||||||
|
self.assertEqual(bundle["public_url"], update["public_url"])
|
||||||
|
|
||||||
|
def test_hub_url_selection_preserves_http_only_and_custom_https_endpoints(self):
|
||||||
|
cases = (
|
||||||
|
({"public_url": "http://hub.example"}, "", "http://hub.example:8088", "http://hub.example:8088"),
|
||||||
|
({"public_url": "https://hub.example:9443"}, "https://hub.example", "http://hub.example:8088", "https://hub.example:9443"),
|
||||||
|
({"public_url": "http://private.example:8088"}, "https://other.example", "", "http://private.example:8088"),
|
||||||
|
)
|
||||||
|
for row, app_url, request_url, expected in cases:
|
||||||
|
with self.subTest(expected=expected):
|
||||||
|
update = hub.canonical_router_hub_update(row, app_url, request_url)
|
||||||
|
self.assertEqual(update["hub_url"], expected)
|
||||||
|
self.assertEqual(hub.router_current_hub_bundle(row, app_url, request_url)[1], expected)
|
||||||
|
|
||||||
def test_rebind_prefers_manual_reported_ip_over_public_hostname(self):
|
def test_rebind_prefers_manual_reported_ip_over_public_hostname(self):
|
||||||
bundle, url, host = hub.router_current_hub_bundle(self.row(), "https://hub.example")
|
bundle, url, host = hub.router_current_hub_bundle(self.row(), "https://hub.example")
|
||||||
self.assertEqual(host, "193.233.82.38")
|
self.assertEqual(host, "193.233.82.38")
|
||||||
@@ -255,6 +282,54 @@ class RouterShellTests(unittest.TestCase):
|
|||||||
self.assertEqual(result.stdout, "hub.example")
|
self.assertEqual(result.stdout, "hub.example")
|
||||||
self.assertIn("old=193.233.82.38 new=hub.example reason=hub_update mode=auto", result.stderr)
|
self.assertIn("old=193.233.82.38 new=hub.example reason=hub_update mode=auto", result.stderr)
|
||||||
|
|
||||||
|
def test_heartbeat_never_downgrades_configured_https_in_manual_or_auto_mode(self):
|
||||||
|
(self.directory / "response").write_text(json.dumps({"hub_update": {
|
||||||
|
"hub_url": "http://hub.example", "public_url": "http://hub.example",
|
||||||
|
}}), encoding="utf-8")
|
||||||
|
for mode in ("manual", "auto"):
|
||||||
|
with self.subTest(mode=mode):
|
||||||
|
self.config(vps_host_mode=mode, vps_host="193.233.82.38",
|
||||||
|
hub_url="https://hub.example:9443", public_url="https://hub.example:9443")
|
||||||
|
result = self.run_shell('''
|
||||||
|
heartbeat_apply_hub_update "$TEST_ROOT/response" http://hub.example:8088
|
||||||
|
heartbeat_apply_hub_update "$TEST_ROOT/response" http://hub.example:8088
|
||||||
|
printf '%s|%s|%s' "$(uci_get hub_url '')" "$(uci_get public_url '')" "$(uci_get vps_host '')"
|
||||||
|
''')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(result.stdout, "https://hub.example:9443|https://hub.example:9443|193.233.82.38")
|
||||||
|
self.assertFalse((self.directory / "commits").exists())
|
||||||
|
log = (self.directory / "log").read_text()
|
||||||
|
self.assertEqual(log.count("reason=https-downgrade"), 2, "repeated proposals must not flood the log")
|
||||||
|
|
||||||
|
def test_successful_fallback_heartbeat_does_not_replace_configured_hub_url(self):
|
||||||
|
self.config(hub_url="https://hub.example", hub_token="test-token", vps_host="193.233.82.38")
|
||||||
|
result = self.run_shell('''
|
||||||
|
heartbeat_json() { printf '{"id":"test-router"}'; }
|
||||||
|
post_json() {
|
||||||
|
case "$1" in
|
||||||
|
http://193.233.82.38:8088/api/heartbeat) printf '{"ok":true}' ;;
|
||||||
|
*) return 1 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
send_heartbeat >/dev/null || exit
|
||||||
|
printf '%s' "$(uci_get hub_url '')"
|
||||||
|
''')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(result.stdout, "https://hub.example")
|
||||||
|
self.assertFalse((self.directory / "commits").exists())
|
||||||
|
|
||||||
|
def test_heartbeat_still_upgrades_http_and_supports_http_only_installations(self):
|
||||||
|
for current, proposed in (("http://hub.example:8088", "https://hub.example:9443"),
|
||||||
|
("http://old.example:8088", "http://new.example:8088")):
|
||||||
|
with self.subTest(proposed=proposed):
|
||||||
|
self.config(hub_url=current, public_url=current)
|
||||||
|
(self.directory / "response").write_text(json.dumps({"hub_update": {
|
||||||
|
"hub_url": proposed, "public_url": proposed,
|
||||||
|
}}), encoding="utf-8")
|
||||||
|
result = self.run_shell('heartbeat_apply_hub_update "$TEST_ROOT/response" http://fallback.example; printf "%s|%s" "$(uci_get hub_url \'\')" "$(uci_get public_url \'\')"')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(result.stdout, f"{proposed}|{proposed}")
|
||||||
|
|
||||||
def test_hub_generated_rebind_preserves_manual_ip_and_wan_options(self):
|
def test_hub_generated_rebind_preserves_manual_ip_and_wan_options(self):
|
||||||
self.config(vps_host="193.233.82.38", wan_direct="1", wan_dns="9.9.9.9", wan_interface="internet")
|
self.config(vps_host="193.233.82.38", wan_direct="1", wan_dns="9.9.9.9", wan_interface="internet")
|
||||||
payload = hub.build_openwrt_config_payload(self.row(), "https://hub.example")
|
payload = hub.build_openwrt_config_payload(self.row(), "https://hub.example")
|
||||||
|
|||||||
@@ -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"v113" in self.request("/")
|
assert b"v114" in self.request("/")
|
||||||
self.app.snapshot_router_states()
|
self.app.snapshot_router_states()
|
||||||
|
|
||||||
def __exit__(self, *args):
|
def __exit__(self, *args):
|
||||||
@@ -296,6 +296,16 @@ class OtherResourceTests(unittest.TestCase):
|
|||||||
self.assertEqual(hub.send_web_push({"endpoint": "https://test"}, {}), "gone")
|
self.assertEqual(hub.send_web_push({"endpoint": "https://test"}, {}), "gone")
|
||||||
response.close.assert_called_once()
|
response.close.assert_called_once()
|
||||||
|
|
||||||
|
def test_web_push_reuses_existing_registration_before_subscribing(self):
|
||||||
|
page = hub.dashboard_html([], "test-owner", auth_bootstrap={"is_owner": True})
|
||||||
|
self.assertIn("subscription = await pushManager.getSubscription();", page)
|
||||||
|
self.assertIn("Update the existing registration in place", page)
|
||||||
|
self.assertIn("forceFresh: false", page)
|
||||||
|
self.assertNotIn("directSubscribeFirst: isIOSDevice()", page)
|
||||||
|
self.assertIn("pushsubscriptionchange", hub.service_worker_js())
|
||||||
|
self.assertIn("push_test: false", hub.service_worker_js())
|
||||||
|
self.assertIn('if not bool(payload.get("push_test", True))', SOURCE.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
def test_atomic_failure_removes_temp_and_preserves_target(self):
|
def test_atomic_failure_removes_temp_and_preserves_target(self):
|
||||||
with tempfile.TemporaryDirectory(dir=STATE.name) as name:
|
with tempfile.TemporaryDirectory(dir=STATE.name) as name:
|
||||||
target = Path(name) / "original.txt"
|
target = Path(name) / "original.txt"
|
||||||
@@ -428,6 +438,30 @@ class OtherResourceTests(unittest.TestCase):
|
|||||||
|
|
||||||
|
|
||||||
class IntegrationTests(unittest.TestCase):
|
class IntegrationTests(unittest.TestCase):
|
||||||
|
def test_push_subscription_sync_does_not_send_duplicate_test(self):
|
||||||
|
with HubFixture() as fixture:
|
||||||
|
payload = {
|
||||||
|
"endpoint": "https://push.example/subscription-sync",
|
||||||
|
"keys": {"p256dh": "p256dh", "auth": "auth"},
|
||||||
|
"client_hint": "hub",
|
||||||
|
"push_test": False,
|
||||||
|
}
|
||||||
|
with mock.patch.object(hub, "send_web_push") as send:
|
||||||
|
response = json.loads(fixture.request("/api/push/subscribe", payload))
|
||||||
|
self.assertTrue(response["ok"])
|
||||||
|
self.assertEqual(response["delivery"], "registered")
|
||||||
|
send.assert_not_called()
|
||||||
|
|
||||||
|
def test_heartbeat_response_recovers_https_from_reported_router_settings(self):
|
||||||
|
with HubFixture() as fixture:
|
||||||
|
payload = {"id": "test-router", "hub_url": "https://hub.example:9443",
|
||||||
|
"public_url": "http://hub.example:8088", "vps_host_mode": "manual"}
|
||||||
|
response = json.loads(fixture.request("/api/heartbeat", payload))
|
||||||
|
self.assertTrue(response["ok"])
|
||||||
|
self.assertEqual(response["hub_update"]["hub_url"], "https://hub.example:9443")
|
||||||
|
self.assertEqual(response["hub_update"]["public_url"], "https://hub.example:9443")
|
||||||
|
self.assertNotIn("vps_host", response["hub_update"])
|
||||||
|
|
||||||
def test_router_online_grace_tolerates_delayed_heartbeat_and_custom_interval(self):
|
def test_router_online_grace_tolerates_delayed_heartbeat_and_custom_interval(self):
|
||||||
now = hub.now_ts()
|
now = hub.now_ts()
|
||||||
base = {
|
base = {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ $RemoteScript = @'
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -eu
|
set -eu
|
||||||
stage=/tmp/__UPLOAD_NAME__
|
stage=/tmp/__UPLOAD_NAME__
|
||||||
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v113
|
backup=/root/owrt-remote-backup-before-heartbeat-redirect-v114
|
||||||
agent=/usr/sbin/owrt-remote
|
agent=/usr/sbin/owrt-remote
|
||||||
wan=/usr/lib/owrt-remote/wan.sh
|
wan=/usr/lib/owrt-remote/wan.sh
|
||||||
changed=0
|
changed=0
|
||||||
|
|||||||
@@ -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-v113',
|
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v114',
|
||||||
[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 'v113' "$stage/$item"; done
|
for item in cgi luci; do grep -F -q 'v114' "$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 'v113' /www/cgi-bin/owrt-remote
|
grep -F -q 'v114' /www/cgi-bin/owrt-remote
|
||||||
grep -F -q 'v113' /www/luci-static/resources/view/owrt_remote.js
|
grep -F -q 'v114' /www/luci-static/resources/view/owrt_remote.js
|
||||||
echo HOST_POLICY_ROUTER_V113_OK
|
echo HOST_POLICY_ROUTER_V114_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_V113_ROLLBACK_OK
|
echo HOST_POLICY_ROUTER_V114_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-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v114
|
||||||
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 'v113' "$stage/hub.py"
|
grep -F -q 'v114' "$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_V113_%s_OK\n' '__ACTION__'
|
printf '\nHOST_POLICY_VPS_V114_%s_OK\n' '__ACTION__'
|
||||||
'@
|
'@
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)][ValidateSet('Router', 'Vps')][string]$Target,
|
||||||
|
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Machine,
|
||||||
|
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||||
|
[string]$HubUrl = '',
|
||||||
|
[switch]$PrepareOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||||
|
$UploadName = 'owrt-hub-url-' + [guid]::NewGuid().ToString('N')
|
||||||
|
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||||
|
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||||
|
if ($HubUrl) {
|
||||||
|
$HubUri = $null
|
||||||
|
if (-not [Uri]::TryCreate($HubUrl, [UriKind]::Absolute, [ref]$HubUri) -or
|
||||||
|
$HubUri.Scheme -notin @('http', 'https') -or -not $HubUri.Host -or
|
||||||
|
$HubUri.UserInfo -or $HubUri.Query -or $HubUri.Fragment -or
|
||||||
|
$HubUri.AbsolutePath -ne '/' -or $HubUrl -notmatch '^https?://[A-Za-z0-9.\[\]:-]+/?$') {
|
||||||
|
throw 'HubUrl must be an HTTP/HTTPS origin, for example https://hub.example:9443.'
|
||||||
|
}
|
||||||
|
if ($Target -ne 'Router' -or $Action -ne 'Install') { throw 'HubUrl is only used by Router Install.' }
|
||||||
|
$HubUrl = $HubUrl.TrimEnd('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($Target -eq 'Router') {
|
||||||
|
$Payloads = @{
|
||||||
|
'agent' = 'files\usr\sbin\owrt-remote'
|
||||||
|
'wan.sh' = 'files\usr\lib\owrt-remote\wan.sh'
|
||||||
|
'cgi' = 'files\www\cgi-bin\owrt-remote'
|
||||||
|
'luci' = 'files\www\luci-static\resources\view\owrt_remote.js'
|
||||||
|
}
|
||||||
|
$RemoteScript = @'
|
||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
stage=/tmp/__UPLOAD_NAME__
|
||||||
|
backup=/root/owrt-remote-backup-before-hub-url-v114
|
||||||
|
chmod 700 "$stage"
|
||||||
|
config=/etc/config/owrtremote
|
||||||
|
changed=0
|
||||||
|
item_path() {
|
||||||
|
case "$1" in
|
||||||
|
agent) printf /usr/sbin/owrt-remote ;;
|
||||||
|
wan.sh) printf /usr/lib/owrt-remote/wan.sh ;;
|
||||||
|
cgi) printf /www/cgi-bin/owrt-remote ;;
|
||||||
|
luci) printf /www/luci-static/resources/view/owrt_remote.js ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
save_files() {
|
||||||
|
dir=$1
|
||||||
|
mkdir -p "$dir"
|
||||||
|
chmod 700 "$dir"
|
||||||
|
cp -p "$config" "$dir/config"
|
||||||
|
for item in agent wan.sh cgi luci; do
|
||||||
|
path=$(item_path "$item")
|
||||||
|
test -s "$path"
|
||||||
|
cp -p "$path" "$dir/$item"
|
||||||
|
done
|
||||||
|
xray_config=$(uci -q get owrtremote.main.xray_config || true)
|
||||||
|
[ -n "$xray_config" ] || xray_config=/etc/xray/owrt-remote-client.json
|
||||||
|
printf '%s' "$xray_config" >"$dir/xray-path"
|
||||||
|
if [ -f "$xray_config" ]; then cp -p "$xray_config" "$dir/xray"; else touch "$dir/xray.absent"; fi
|
||||||
|
chmod 600 "$dir/config" "$dir/xray-path"
|
||||||
|
[ ! -f "$dir/xray" ] || chmod 600 "$dir/xray"
|
||||||
|
touch "$dir/complete"
|
||||||
|
}
|
||||||
|
restore_files() {
|
||||||
|
dir=$1
|
||||||
|
test -f "$dir/complete"
|
||||||
|
/etc/init.d/owrt-remote stop >/dev/null 2>&1 || true
|
||||||
|
cp -p "$dir/config" "$config"
|
||||||
|
for item in agent wan.sh cgi luci; do
|
||||||
|
path=$(item_path "$item")
|
||||||
|
cp -p "$dir/$item" "$path"
|
||||||
|
done
|
||||||
|
xray_config=$(cat "$dir/xray-path")
|
||||||
|
if [ -f "$dir/xray.absent" ]; then rm -f "$xray_config"; else cp -p "$dir/xray" "$xray_config"; fi
|
||||||
|
/etc/init.d/owrt-remote restart
|
||||||
|
}
|
||||||
|
cleanup() {
|
||||||
|
code=$?
|
||||||
|
trap - EXIT
|
||||||
|
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
|
||||||
|
echo 'Operation failed; restoring the files and settings from this attempt.' >&2
|
||||||
|
restore_files "$stage/previous" || true
|
||||||
|
fi
|
||||||
|
for item in agent wan.sh cgi luci; do
|
||||||
|
path=$(item_path "$item")
|
||||||
|
rm -f "$path.new-__UPLOAD_NAME__"
|
||||||
|
done
|
||||||
|
rm -rf "$stage"
|
||||||
|
exit "$code"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
test -s "$config"
|
||||||
|
if [ '__ACTION__' = Install ]; then
|
||||||
|
for item in agent wan.sh cgi; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||||
|
test -s "$stage/luci"
|
||||||
|
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 'v114' "$stage/$item"; done
|
||||||
|
if [ ! -e "$backup" ]; then
|
||||||
|
save_files "$stage/retained-backup"
|
||||||
|
mv "$stage/retained-backup" "$backup"
|
||||||
|
fi
|
||||||
|
test -f "$backup/complete"
|
||||||
|
save_files "$stage/previous"
|
||||||
|
changed=1
|
||||||
|
/etc/init.d/owrt-remote stop >/dev/null 2>&1 || true
|
||||||
|
for item in agent wan.sh cgi luci; do
|
||||||
|
path=$(item_path "$item")
|
||||||
|
cp "$stage/$item" "$path.new-__UPLOAD_NAME__"
|
||||||
|
case "$item" in wan.sh|luci) chmod 644 "$path.new-__UPLOAD_NAME__" ;; *) chmod 755 "$path.new-__UPLOAD_NAME__" ;; esac
|
||||||
|
mv -f "$path.new-__UPLOAD_NAME__" "$path"
|
||||||
|
done
|
||||||
|
if [ -n '__HUB_URL__' ]; then
|
||||||
|
uci set 'owrtremote.main.hub_url=__HUB_URL__'
|
||||||
|
uci commit owrtremote
|
||||||
|
fi
|
||||||
|
/etc/init.d/owrt-remote restart
|
||||||
|
for item in agent wan.sh cgi luci; do
|
||||||
|
path=$(item_path "$item")
|
||||||
|
cmp "$stage/$item" "$path"
|
||||||
|
done
|
||||||
|
printf 'Installed Hub URL: %s\n' "$(uci -q get owrtremote.main.hub_url || true)"
|
||||||
|
# Failure to reach Hub is reported separately from successful file installation.
|
||||||
|
if /usr/sbin/owrt-remote heartbeat >"$stage/heartbeat.json"; then
|
||||||
|
printf 'HEARTBEAT_OK\n'
|
||||||
|
else
|
||||||
|
printf 'Files installed, but Heartbeat failed. Check the connection and router logs.\n' >&2
|
||||||
|
printf 'HEARTBEAT_FAILED\n'
|
||||||
|
fi
|
||||||
|
printf 'Hub URL after Heartbeat: %s\n' "$(uci -q get owrtremote.main.hub_url || true)"
|
||||||
|
else
|
||||||
|
test -f "$backup/complete"
|
||||||
|
save_files "$stage/previous"
|
||||||
|
changed=1
|
||||||
|
restore_files "$backup"
|
||||||
|
fi
|
||||||
|
printf '\nBackup: %s\nHUB_URL_ROUTER_V114_%s_OK\n' "$backup" '__ACTION__'
|
||||||
|
'@
|
||||||
|
} else {
|
||||||
|
$Payloads = @{
|
||||||
|
'hub.py' = 'vps\owrt-remote-hub.py'
|
||||||
|
'host_policy.py' = 'tests\test_host_policy.py'
|
||||||
|
'resources.py' = 'tests\test_resource_lifecycle.py'
|
||||||
|
}
|
||||||
|
$RemoteScript = @'
|
||||||
|
#!/bin/sh
|
||||||
|
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-v114
|
||||||
|
candidate=$target.new-__UPLOAD_NAME__
|
||||||
|
changed=0
|
||||||
|
cleanup() {
|
||||||
|
code=$?
|
||||||
|
trap - EXIT
|
||||||
|
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
|
||||||
|
echo 'Operation failed; restoring Hub from this attempt.' >&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
|
||||||
|
grep -F -q 'def router_hub_origins(' "$stage/hub.py"
|
||||||
|
grep -F -q 'v114' "$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
|
||||||
|
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\nHUB_URL_VPS_V114_%s_OK\n' "$backup" '__ACTION__'
|
||||||
|
'@
|
||||||
|
}
|
||||||
|
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__HUB_URL__', $HubUrl)
|
||||||
|
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 "${Machine}:/tmp/"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Installation has not started.' }
|
||||||
|
& ssh -T -o ConnectTimeout=10 $Machine "sh /tmp/$UploadName/run.sh"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||||
|
Write-Host "Hub URL $Target $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 }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ $RemoteScript = @'
|
|||||||
set -eu
|
set -eu
|
||||||
stage=/tmp/__UPLOAD_NAME__
|
stage=/tmp/__UPLOAD_NAME__
|
||||||
target=/opt/owrt-remote/owrt-remote-hub.py
|
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||||
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-online-status-v114
|
||||||
candidate=$target.new-__UPLOAD_NAME__
|
candidate=$target.new-__UPLOAD_NAME__
|
||||||
changed=0
|
changed=0
|
||||||
cleanup() {
|
cleanup() {
|
||||||
@@ -59,7 +59,7 @@ for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
|||||||
done
|
done
|
||||||
test "$healthy" = 1
|
test "$healthy" = 1
|
||||||
cmp "$source_file" "$target"
|
cmp "$source_file" "$target"
|
||||||
printf '\nBackup: %s\nONLINE_STATUS_V113_%s_OK\n' "$backup" '__ACTION__'
|
printf '\nBackup: %s\nONLINE_STATUS_V114_%s_OK\n' "$backup" '__ACTION__'
|
||||||
'@
|
'@
|
||||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -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-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v114
|
||||||
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v113.json
|
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v114.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 'v113' in source
|
assert 'v114' 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_V113_OK
|
echo RECAPTCHA_V3_V114_OK
|
||||||
'@
|
'@
|
||||||
} elseif ($Action -eq 'Rollback') {
|
} elseif ($Action -eq 'Rollback') {
|
||||||
$RemoteScript = @'
|
$RemoteScript = @'
|
||||||
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V113_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-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v114
|
||||||
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v113.json
|
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v114.json
|
||||||
candidate=$target.rollback-__UPLOAD_NAME__
|
candidate=$target.rollback-__UPLOAD_NAME__
|
||||||
changed=0
|
changed=0
|
||||||
restore_captcha() {
|
restore_captcha() {
|
||||||
|
|||||||
@@ -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-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v114
|
||||||
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 'v113' in source
|
assert 'v114' 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_V113_OK
|
echo RESOURCE_FIX_V114_OK
|
||||||
'@
|
'@
|
||||||
} elseif ($Action -eq 'Rollback') {
|
} elseif ($Action -eq 'Rollback') {
|
||||||
$RemoteScript = @'
|
$RemoteScript = @'
|
||||||
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V113_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-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v114
|
||||||
candidate=$target.rollback-__UPLOAD_NAME__
|
candidate=$target.rollback-__UPLOAD_NAME__
|
||||||
changed=0
|
changed=0
|
||||||
cleanup() {
|
cleanup() {
|
||||||
|
|||||||
@@ -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-v113
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v114
|
||||||
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 'v113' "$stage/hub.py"
|
grep -F -q 'v114' "$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_V113_%s_OK\n' '__ACTION__'
|
printf '\nVPS_WIDGETS_V114_%s_OK\n' '__ACTION__'
|
||||||
'@
|
'@
|
||||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -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-v113
|
backup=/root/owrt-remote-backup-before-wan-multi-v114
|
||||||
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 'v113' "$stage/$item"; done
|
for item in cgi luci; do grep -F -q 'v114' "$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"
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
|
||||||
|
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||||
|
[switch]$PrepareOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||||
|
$UploadName = 'owrt-web-push-' + [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-web-push-v114
|
||||||
|
candidate=$target.new-__UPLOAD_NAME__
|
||||||
|
changed=0
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
code=$?
|
||||||
|
trap - EXIT
|
||||||
|
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; 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 'Existing subscriptions must be reused' "$stage/hub.py"
|
||||||
|
grep -F -q 'Update the existing registration in place' "$stage/hub.py"
|
||||||
|
grep -F -q 'subscription = await pushManager.getSubscription();' "$stage/hub.py"
|
||||||
|
grep -F -q 'forceFresh: false' "$stage/hub.py"
|
||||||
|
grep -F -q 'push_test: false' "$stage/hub.py"
|
||||||
|
grep -F -q 'result in ("gone", "stale")' "$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\nWEB_PUSH_V114_%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 "Web Push 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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-v113
|
backup_dir=/root/owrt-remote-backup-before-xray-apply-v114
|
||||||
backup=$backup_dir/owrt-remote
|
backup=$backup_dir/owrt-remote
|
||||||
candidate=$target.new-__UPLOAD_NAME__
|
candidate=$target.new-__UPLOAD_NAME__
|
||||||
changed=0
|
changed=0
|
||||||
|
|||||||
+124
-38
@@ -1367,7 +1367,7 @@ def row_int_value(row, key, default=0):
|
|||||||
return int(default)
|
return int(default)
|
||||||
|
|
||||||
|
|
||||||
def router_reported_connection(router, *, legacy_mode="auto"):
|
def router_reported_status(router):
|
||||||
row = dict(router or {})
|
row = dict(router or {})
|
||||||
status = row.get("status")
|
status = row.get("status")
|
||||||
if not isinstance(status, dict):
|
if not isinstance(status, dict):
|
||||||
@@ -1377,6 +1377,12 @@ def router_reported_connection(router, *, legacy_mode="auto"):
|
|||||||
status = {}
|
status = {}
|
||||||
if not isinstance(status, dict):
|
if not isinstance(status, dict):
|
||||||
status = {}
|
status = {}
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
def router_reported_connection(router, *, legacy_mode="auto"):
|
||||||
|
row = dict(router or {})
|
||||||
|
status = router_reported_status(row)
|
||||||
# Legacy agents had automatic endpoint updates. Keep that server behavior
|
# Legacy agents had automatic endpoint updates. Keep that server behavior
|
||||||
# until they report a policy; the patched agent itself defaults to manual.
|
# until they report a policy; the patched agent itself defaults to manual.
|
||||||
mode = legacy_mode if status.get("vps_host_mode") is None else ("auto" if status.get("vps_host_mode") == "auto" else "manual")
|
mode = legacy_mode if status.get("vps_host_mode") is None else ("auto" if status.get("vps_host_mode") == "auto" else "manual")
|
||||||
@@ -1431,14 +1437,34 @@ echo VPS_HOST_APPLIED
|
|||||||
'''
|
'''
|
||||||
|
|
||||||
|
|
||||||
def canonical_router_hub_update(router, app_public_url="", request_origin=""):
|
def router_hub_origins(router, app_public_url="", request_origin=""):
|
||||||
router = router or {}
|
router = dict(router or {})
|
||||||
|
status = router_reported_status(router)
|
||||||
router_public_url = public_url_origin(router.get("public_url", ""))
|
router_public_url = public_url_origin(router.get("public_url", ""))
|
||||||
app_origin = public_url_origin(app_public_url)
|
app_origin = public_url_origin(app_public_url)
|
||||||
request_origin = public_url_origin(request_origin)
|
request_origin = public_url_origin(request_origin)
|
||||||
public_url = prefer_origin_with_explicit_port(router_public_url, app_origin)
|
public_url = prefer_origin_with_explicit_port(router_public_url, app_origin)
|
||||||
public_url = prefer_origin_with_explicit_port(public_url, request_origin)
|
public_url = prefer_origin_with_explicit_port(public_url, request_origin)
|
||||||
|
# A stale HTTP row or an internal HTTP request must not override a known
|
||||||
|
# HTTPS origin for the same Hub. Keep custom hosts and HTTPS ports intact.
|
||||||
|
if urllib.parse.urlsplit(public_url).scheme == "http":
|
||||||
|
for candidate in (
|
||||||
|
app_origin,
|
||||||
|
request_origin,
|
||||||
|
public_url_origin(status.get("hub_url", "")),
|
||||||
|
public_url_origin(status.get("public_url", "")),
|
||||||
|
):
|
||||||
|
parts = urllib.parse.urlsplit(candidate)
|
||||||
|
if parts.scheme == "https" and parts.hostname == urllib.parse.urlsplit(public_url).hostname:
|
||||||
|
public_url = candidate
|
||||||
|
break
|
||||||
hub_url = public_url or request_origin
|
hub_url = public_url or request_origin
|
||||||
|
return public_url, hub_url
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_router_hub_update(router, app_public_url="", request_origin=""):
|
||||||
|
router = router or {}
|
||||||
|
public_url, hub_url = router_hub_origins(router, app_public_url, request_origin)
|
||||||
vps_host = str(router.get("vps_host") or "").strip()
|
vps_host = str(router.get("vps_host") or "").strip()
|
||||||
if not vps_host and hub_url:
|
if not vps_host and hub_url:
|
||||||
try:
|
try:
|
||||||
@@ -2504,6 +2530,8 @@ def send_web_push(subscription, payload):
|
|||||||
detail = detail[:160]
|
detail = detail[:160]
|
||||||
if status_code in (404, 410):
|
if status_code in (404, 410):
|
||||||
return "gone"
|
return "gone"
|
||||||
|
if status_code in (400, 401, 403):
|
||||||
|
return "stale"
|
||||||
if detail:
|
if detail:
|
||||||
return f"error:{status_code or exc.__class__.__name__}:{detail}"
|
return f"error:{status_code or exc.__class__.__name__}:{detail}"
|
||||||
return f"error:{status_code or exc.__class__.__name__}"
|
return f"error:{status_code or exc.__class__.__name__}"
|
||||||
@@ -2519,6 +2547,8 @@ def push_result_message(result, subscription=None):
|
|||||||
return "На VPS не готов Web Push. Запусти свежий install-vps.sh и проверь HTTPS."
|
return "На VPS не готов Web Push. Запусти свежий install-vps.sh и проверь HTTPS."
|
||||||
if result == "gone":
|
if result == "gone":
|
||||||
return "Подписка браузера устарела. Включи push заново на этом устройстве."
|
return "Подписка браузера устарела. Включи push заново на этом устройстве."
|
||||||
|
if result == "stale":
|
||||||
|
return "Подписка браузера больше не совпадает с ключами VPS. Hub удалил её; включи Push заново на этом устройстве."
|
||||||
if str(result).startswith("error:"):
|
if str(result).startswith("error:"):
|
||||||
parts = str(result).split(":", 2)
|
parts = str(result).split(":", 2)
|
||||||
code = parts[1] if len(parts) > 1 and parts[1] else "unknown"
|
code = parts[1] if len(parts) > 1 and parts[1] else "unknown"
|
||||||
@@ -2551,7 +2581,7 @@ def queue_web_push_payload(payload, subscriptions=None):
|
|||||||
"result": result,
|
"result": result,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
if result == "gone":
|
if result in ("gone", "stale"):
|
||||||
gone.append(subscription.get("endpoint", ""))
|
gone.append(subscription.get("endpoint", ""))
|
||||||
for endpoint in gone:
|
for endpoint in gone:
|
||||||
remove_push_subscription(endpoint)
|
remove_push_subscription(endpoint)
|
||||||
@@ -2583,6 +2613,56 @@ self.addEventListener('activate', event => {
|
|||||||
event.waitUntil(self.clients.claim());
|
event.waitUntil(self.clients.claim());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function pushBase64ToUint8Array(value) {
|
||||||
|
const padding = '='.repeat((4 - value.length % 4) % 4);
|
||||||
|
const base64 = (value + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
const raw = atob(base64);
|
||||||
|
const output = new Uint8Array(raw.length);
|
||||||
|
for (let i = 0; i < raw.length; i++) output[i] = raw.charCodeAt(i);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function syncChangedPushSubscription(event) {
|
||||||
|
const oldEndpoint = event && event.oldSubscription && event.oldSubscription.endpoint || '';
|
||||||
|
let subscription = event && event.newSubscription || null;
|
||||||
|
try {
|
||||||
|
if (!subscription) {
|
||||||
|
const keyResponse = await fetch('/api/push/vapid-public-key', {cache: 'no-store', credentials: 'same-origin'});
|
||||||
|
const keyData = await keyResponse.json().catch(() => ({}));
|
||||||
|
if (!keyResponse.ok || !keyData.ok || !keyData.publicKey) return;
|
||||||
|
subscription = await self.registration.pushManager.subscribe({
|
||||||
|
userVisibleOnly: true,
|
||||||
|
applicationServerKey: pushBase64ToUint8Array(keyData.publicKey)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!subscription) return;
|
||||||
|
const body = {
|
||||||
|
...(subscription.toJSON ? subscription.toJSON() : subscription),
|
||||||
|
client_hint: 'hub',
|
||||||
|
push_test: false
|
||||||
|
};
|
||||||
|
const response = await fetch('/api/push/subscribe', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
});
|
||||||
|
if (!response.ok) return;
|
||||||
|
if (oldEndpoint && subscription.endpoint && oldEndpoint !== subscription.endpoint) {
|
||||||
|
await fetch('/api/push/unsubscribe', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({endpoint: oldEndpoint})
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.addEventListener('pushsubscriptionchange', event => {
|
||||||
|
event.waitUntil(syncChangedPushSubscription(event));
|
||||||
|
});
|
||||||
|
|
||||||
self.addEventListener('push', event => {
|
self.addEventListener('push', event => {
|
||||||
let data = {};
|
let data = {};
|
||||||
try {
|
try {
|
||||||
@@ -3695,12 +3775,10 @@ def rewrite_router_endpoints(conn, vps_host="", public_url="", preserve_vps_fall
|
|||||||
|
|
||||||
def router_current_hub_bundle(router, app_public_url="", request_origin="", fallback_host=""):
|
def router_current_hub_bundle(router, app_public_url="", request_origin="", fallback_host=""):
|
||||||
row = dict(router or {})
|
row = dict(router or {})
|
||||||
router_public_url = public_url_origin(row.get("public_url", ""))
|
|
||||||
app_origin = public_url_origin(app_public_url)
|
app_origin = public_url_origin(app_public_url)
|
||||||
request_origin = public_url_origin(request_origin)
|
request_origin = public_url_origin(request_origin)
|
||||||
public_url = prefer_origin_with_explicit_port(router_public_url, app_origin)
|
public_url, hub_url = router_hub_origins(row, app_public_url, request_origin)
|
||||||
public_url = prefer_origin_with_explicit_port(public_url, request_origin)
|
hub_url = hub_url or router_fallback_hub_url(row, fallback_host, 8088)
|
||||||
hub_url = public_url or request_origin or router_fallback_hub_url(row, fallback_host, 8088)
|
|
||||||
reported_mode, reported_host = router_reported_connection(row)
|
reported_mode, reported_host = router_reported_connection(row)
|
||||||
config_vps_host = (
|
config_vps_host = (
|
||||||
(reported_host if reported_mode == "manual" else "")
|
(reported_host if reported_mode == "manual" else "")
|
||||||
@@ -4778,7 +4856,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">v113</span></span></h1>
|
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v114</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>
|
||||||
@@ -5131,7 +5209,7 @@ systemctl restart owrt-remote-xray</pre>
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mobileSearchDock" id="mobileRouterSearchDock">
|
<div class="mobileSearchDock" id="mobileRouterSearchDock">
|
||||||
<span class="mobileSearchVersion">v113</span>
|
<span class="mobileSearchVersion">v114</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>
|
||||||
@@ -10478,7 +10556,7 @@ let pushVapidConfig = embeddedPushVapidConfig();
|
|||||||
let pushVapidPromise = null;
|
let pushVapidPromise = null;
|
||||||
|
|
||||||
function pushEnvironmentReady() {{
|
function pushEnvironmentReady() {{
|
||||||
return !!(((pushServiceWorkerReady && pushServiceWorkerReady.pushManager) || hasWindowPushManager()) && pushVapidConfig && pushVapidConfig.publicKey);
|
return !!(((pushRegistrationUsable(pushServiceWorkerReady)) || hasWindowPushManager()) && pushVapidConfig && pushVapidConfig.publicKey);
|
||||||
}}
|
}}
|
||||||
|
|
||||||
function ensureClientVersion() {{
|
function ensureClientVersion() {{
|
||||||
@@ -10669,7 +10747,9 @@ async function warmPushEnvironment({{silent = true}} = {{}}) {{
|
|||||||
try {{
|
try {{
|
||||||
const tasks = [fetchPushVapidConfig()];
|
const tasks = [fetchPushVapidConfig()];
|
||||||
if ('serviceWorker' in navigator) {{
|
if ('serviceWorker' in navigator) {{
|
||||||
tasks.unshift(ensurePushServiceWorkerReady({{forceFresh: isIOSDevice() && !hasWindowPushManager(), forceUpdate: isIOSDevice() && !hasWindowPushManager()}}).catch((e) => {{
|
// Update the existing registration in place. On iOS, forcing a new
|
||||||
|
// registration can detach Safari's existing PushSubscription.
|
||||||
|
tasks.unshift(ensurePushServiceWorkerReady({{forceFresh: false, forceUpdate: true}}).catch((e) => {{
|
||||||
if (hasWindowPushManager()) return null;
|
if (hasWindowPushManager()) return null;
|
||||||
throw e;
|
throw e;
|
||||||
}}));
|
}}));
|
||||||
@@ -10710,17 +10790,20 @@ async function resolvePushSubscriptionManager({{forceFresh = false, forceUpdate
|
|||||||
}};
|
}};
|
||||||
}}
|
}}
|
||||||
|
|
||||||
async function registerPushSubscription({{preferCached = false, directSubscribeFirst = false}} = {{}}) {{
|
async function registerPushSubscription({{preferCached = false, directSubscribeFirst = false, sendTest = true}} = {{}}) {{
|
||||||
let ready = pushServiceWorkerReady;
|
let ready = pushServiceWorkerReady;
|
||||||
let keyData = pushVapidConfig;
|
let keyData = pushVapidConfig;
|
||||||
let pushManager = ready && ready.pushManager ? ready.pushManager : null;
|
let pushManager = ready && ready.pushManager ? ready.pushManager : null;
|
||||||
let pushSource = 'serviceWorker';
|
let pushSource = 'serviceWorker';
|
||||||
const preferWindowManager = hasWindowPushManager();
|
const preferWindowManager = hasWindowPushManager();
|
||||||
const requireFreshRegistration = preferWindowManager || isIOSDevice() || !preferCached || !pushEnvironmentReady();
|
// Read an existing subscription before subscribing. Calling subscribe()
|
||||||
|
// first is unreliable in iOS standalone Safari and can produce a broken
|
||||||
|
// PushRegistration even when the current subscription is still valid.
|
||||||
|
const requireFreshRegistration = preferWindowManager || !pushEnvironmentReady();
|
||||||
if (requireFreshRegistration) {{
|
if (requireFreshRegistration) {{
|
||||||
const resolved = await resolvePushSubscriptionManager({{
|
const resolved = await resolvePushSubscriptionManager({{
|
||||||
forceFresh: !preferWindowManager && isIOSDevice(),
|
forceFresh: false,
|
||||||
forceUpdate: !preferWindowManager && isIOSDevice()
|
forceUpdate: false
|
||||||
}});
|
}});
|
||||||
ready = resolved.registration;
|
ready = resolved.registration;
|
||||||
keyData = resolved.keyData;
|
keyData = resolved.keyData;
|
||||||
@@ -10738,22 +10821,10 @@ async function registerPushSubscription({{preferCached = false, directSubscribeF
|
|||||||
const trySubscribe = async () => {{
|
const trySubscribe = async () => {{
|
||||||
return await pushManager.subscribe(subscribeOptions);
|
return await pushManager.subscribe(subscribeOptions);
|
||||||
}};
|
}};
|
||||||
if (directSubscribeFirst && isIOSDevice()) {{
|
|
||||||
try {{
|
|
||||||
subscription = await trySubscribe();
|
|
||||||
}} catch (e) {{
|
|
||||||
if (!(pushSource === 'serviceWorker' && isPushInitStateError(e))) {{
|
|
||||||
if (String((e && e.name) || '').toLowerCase() === 'aborterror') {{
|
|
||||||
throw new Error('iPhone прервал создание push-подписки. Полностью закрой Hub свайпом, открой снова с экрана Домой и повтори "Включить Push".');
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
if (pushSource !== 'serviceWorker' || !isPushInitStateError(e)) {{
|
|
||||||
throw new Error(`pushManager.subscribe failed: ${{pushErrorText(e, 'unknown error')}}`);
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
try {{
|
try {{
|
||||||
if (!subscription) subscription = await pushManager.getSubscription();
|
// Existing subscriptions must be reused. This is essential for iOS,
|
||||||
|
// where subscribe() before getSubscription() may throw InvalidStateError.
|
||||||
|
subscription = await pushManager.getSubscription();
|
||||||
}} catch (e) {{
|
}} catch (e) {{
|
||||||
if (!isPushInitStateError(e)) {{
|
if (!isPushInitStateError(e)) {{
|
||||||
throw new Error(`pushManager.getSubscription failed: ${{pushErrorText(e, 'unknown error')}}`);
|
throw new Error(`pushManager.getSubscription failed: ${{pushErrorText(e, 'unknown error')}}`);
|
||||||
@@ -10761,7 +10832,9 @@ async function registerPushSubscription({{preferCached = false, directSubscribeF
|
|||||||
if (pushSource !== 'serviceWorker') {{
|
if (pushSource !== 'serviceWorker') {{
|
||||||
throw new Error(`pushManager.getSubscription failed: ${{pushErrorText(e, 'unknown error')}}`);
|
throw new Error(`pushManager.getSubscription failed: ${{pushErrorText(e, 'unknown error')}}`);
|
||||||
}}
|
}}
|
||||||
await resetHubPushState({{unregister: false}});
|
// Only the recovery path unregisters the worker. Normal checks reuse the
|
||||||
|
// current registration so Safari keeps its valid PushSubscription.
|
||||||
|
await resetHubPushState({{unregister: true}});
|
||||||
const resolved = await resolvePushSubscriptionManager({{forceFresh: true, forceUpdate: true}});
|
const resolved = await resolvePushSubscriptionManager({{forceFresh: true, forceUpdate: true}});
|
||||||
ready = resolved.registration;
|
ready = resolved.registration;
|
||||||
keyData = resolved.keyData;
|
keyData = resolved.keyData;
|
||||||
@@ -10809,7 +10882,7 @@ async function registerPushSubscription({{preferCached = false, directSubscribeF
|
|||||||
res = await fetch('/api/push/subscribe', {{
|
res = await fetch('/api/push/subscribe', {{
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {{'Content-Type': 'application/json'}},
|
headers: {{'Content-Type': 'application/json'}},
|
||||||
body: JSON.stringify({{...(subscription.toJSON ? subscription.toJSON() : subscription), client_hint: currentClientHint()}})
|
body: JSON.stringify({{...(subscription.toJSON ? subscription.toJSON() : subscription), client_hint: currentClientHint(), push_test: !!sendTest}})
|
||||||
}});
|
}});
|
||||||
}} catch (e) {{
|
}} catch (e) {{
|
||||||
throw new Error(`Не смог отправить подписку на VPS: ${{pushErrorText(e, 'network error')}}`);
|
throw new Error(`Не смог отправить подписку на VPS: ${{pushErrorText(e, 'network error')}}`);
|
||||||
@@ -10857,7 +10930,7 @@ async function enableNotifications() {{
|
|||||||
}}
|
}}
|
||||||
showRouterMsg('Включаю настоящий Web Push для этого устройства...');
|
showRouterMsg('Включаю настоящий Web Push для этого устройства...');
|
||||||
setNotifyStatus(`Пробую включить Web Push. Текущее состояние: ${{pushSupportSummary()}}`);
|
setNotifyStatus(`Пробую включить Web Push. Текущее состояние: ${{pushSupportSummary()}}`);
|
||||||
await registerPushSubscription({{preferCached: isIOSDevice(), directSubscribeFirst: isIOSDevice()}});
|
await registerPushSubscription({{preferCached: isIOSDevice()}});
|
||||||
localStorage.setItem('owrtPushEnabled', '1');
|
localStorage.setItem('owrtPushEnabled', '1');
|
||||||
showRouterMsg('Push включён. Теперь уведомления должны приходить даже когда вкладка закрыта.');
|
showRouterMsg('Push включён. Теперь уведомления должны приходить даже когда вкладка закрыта.');
|
||||||
setNotifyStatus(`Web Push включён. Текущее состояние: ${{pushSupportSummary()}}`);
|
setNotifyStatus(`Web Push включён. Текущее состояние: ${{pushSupportSummary()}}`);
|
||||||
@@ -10899,7 +10972,7 @@ async function testPushDelivery() {{
|
|||||||
}}
|
}}
|
||||||
showRouterMsg('Проверяю доставку Web Push на это устройство...');
|
showRouterMsg('Проверяю доставку Web Push на это устройство...');
|
||||||
setNotifyStatus(`Проверяю доставку Web Push. Текущее состояние: ${{pushSupportSummary()}}`);
|
setNotifyStatus(`Проверяю доставку Web Push. Текущее состояние: ${{pushSupportSummary()}}`);
|
||||||
const data = await registerPushSubscription({{preferCached: isIOSDevice(), directSubscribeFirst: isIOSDevice()}});
|
const data = await registerPushSubscription({{preferCached: isIOSDevice(), sendTest: true}});
|
||||||
const client = data && data.subscription && data.subscription.client ? data.subscription.client : 'устройство';
|
const client = data && data.subscription && data.subscription.client ? data.subscription.client : 'устройство';
|
||||||
showRouterMsg(`VPS принял подписку и отправил тестовый Web Push на ${{client}}.`);
|
showRouterMsg(`VPS принял подписку и отправил тестовый Web Push на ${{client}}.`);
|
||||||
setNotifyStatus(`VPS принял подписку и отправил тестовый Web Push на ${{client}}.`);
|
setNotifyStatus(`VPS принял подписку и отправил тестовый Web Push на ${{client}}.`);
|
||||||
@@ -12659,7 +12732,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">v113</span></span></h1>
|
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v114</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>
|
||||||
@@ -13131,7 +13204,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">v113</span></h2>
|
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v114</span></h2>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="brandBottom">
|
<div class="brandBottom">
|
||||||
@@ -17604,6 +17677,19 @@ exit 127
|
|||||||
client_ip,
|
client_ip,
|
||||||
user_agent,
|
user_agent,
|
||||||
)
|
)
|
||||||
|
if not bool(payload.get("push_test", True)):
|
||||||
|
self.send_json(
|
||||||
|
200,
|
||||||
|
{
|
||||||
|
"ok": True,
|
||||||
|
"delivery": "registered",
|
||||||
|
"subscription": {
|
||||||
|
"id": subscription.get("id"),
|
||||||
|
"client": subscription.get("client"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return
|
||||||
test_payload = {
|
test_payload = {
|
||||||
"title": APP_NAME,
|
"title": APP_NAME,
|
||||||
"body": "Push включён на этом устройстве.",
|
"body": "Push включён на этом устройстве.",
|
||||||
@@ -17632,7 +17718,7 @@ exit 127
|
|||||||
],
|
],
|
||||||
"ok" if result == "ok" else "partial",
|
"ok" if result == "ok" else "partial",
|
||||||
)
|
)
|
||||||
if result == "gone":
|
if result in ("gone", "stale"):
|
||||||
remove_push_subscription(subscription.get("endpoint", ""))
|
remove_push_subscription(subscription.get("endpoint", ""))
|
||||||
if result != "ok":
|
if result != "ok":
|
||||||
self.send_json(503, {"ok": False, "error": push_result_message(result, subscription), "delivery": result, "subscription": {"id": subscription.get("id"), "client": subscription.get("client")}})
|
self.send_json(503, {"ok": False, "error": push_result_message(result, subscription), "delivery": result, "subscription": {"id": subscription.get("id"), "client": subscription.get("client")}})
|
||||||
|
|||||||
Reference in new issue
Block a user