Fix VPS host persistence and direct WAN routing in v111

This commit is contained in:
kzolotarev95 committed 2026-10-08 09:20:35 +04:00
1 parent 411f95d6ba
commit b854d3a001
20 files changed
+2097 -49

No files matched your search

+4
View File
@@ -9,6 +9,10 @@ config remote 'main'
option xray_bin '/usr/bin/xray'
option xray_config '/etc/xray/owrt-remote-client.json'
option vps_host ''
option vps_host_mode 'manual'
option wan_direct '0'
option wan_interface 'wan'
option wan_dns ''
option vps_port '8443'
option vless_uuid ''
option vless_encryption 'none'
+1
View File
@@ -82,6 +82,7 @@ reload_service() {
stop_service() {
stop_xray_processes
/usr/sbin/owrt-remote wan-cleanup >/dev/null 2>&1 || true
}
service_triggers() {
+366
View File
@@ -0,0 +1,366 @@
#!/bin/sh
# Private routing state for router-originated Remote traffic only. No LAN,
# dnsmasq, Podkop configuration or sing-box service is modified.
WAN_STATE="${TMPDIR:-/tmp}/owrt-remote-wan"
# BusyBox ip accepts a limited range of table IDs; stay below 256.
WAN_TABLE=210
WAN_PRIORITY=104
# Only used to recognize and remove the previous implementation's rules.
WAN_MARK=0x40000000
PODKOP_BYPASS_MARK=0x00200000
wan_ip_literal() {
[ -n "$1" ] || return 1
case "$1" in
*:* ) printf '%s' "$1" | grep -Eq '^[0-9a-fA-F:]+$' ;;
*) printf '%s' "$1" | awk -F. 'NF != 4 { exit 1 } { for (i=1;i<=4;i++) if ($i !~ /^[0-9]+$/ || $i > 255) exit 1 }' ;;
esac
}
wan_url_host() {
local authority
authority="${1#*://}"
authority="${authority%%/*}"
case "$authority" in
\[*\]*) authority="${authority#\[}"; printf '%s' "${authority%%\]*}" ;;
*) printf '%s' "${authority%%:*}" ;;
esac
}
wan_url_port() {
local authority port
authority="${1#*://}"; authority="${authority%%/*}"
case "$authority" in
\[*\]:*) port="${authority##*\]:}" ;;
*:* ) port="${authority##*:}" ;;
*) case "$1" in https://*) port=443 ;; *) port=80 ;; esac ;;
esac
port="$(safe_num "$port" 0)"
[ "$port" -gt 0 ] && [ "$port" -le 65535 ] || return 1
printf '%s' "$port"
}
wan_device() {
local iface device
iface="${OWRT_REMOTE_WAN_INTERFACE:-$(uci_get wan_interface wan)}"
device="$(ubus call "network.interface.$iface" status 2>/dev/null | jsonfilter -e '@.l3_device' 2>/dev/null)"
[ -n "$device" ] || return 1
case "$device" in *[!a-zA-Z0-9_.:-]*) return 1 ;; esac
printf '%s' "$device"
}
wan_dns_server() {
local dns
dns="$(uci_get wan_dns '')"
if [ -z "$dns" ]; then
dns="$(ubus call "network.interface.$(uci_get wan_interface wan)" status 2>/dev/null | jsonfilter -e '@["dns-server"][0]' 2>/dev/null)"
fi
[ -n "$dns" ] || dns=1.1.1.1
wan_ip_literal "$dns" || return 1
case "$dns" in 127.*|::1) dns=1.1.1.1 ;; esac
printf '%s' "$dns"
}
wan_resolve_host() {
local host dns answer cache now saved_ts saved_ip
host="$1"
wan_ip_literal "$host" && { printf '%s' "$host"; return; }
case "$host" in ''|*[!a-zA-Z0-9_.-]*) return 1 ;; esac
dns="$(wan_dns_server)" || return 1
cache="$WAN_STATE/resolve-$(safe_id "$host-$dns")"
now="$(date +%s)"
saved_ts=0; saved_ip=''
[ ! -r "$cache" ] || read -r saved_ts saved_ip <"$cache"
if [ -n "$saved_ip" ] && [ $((now - saved_ts)) -lt 300 ]; then
printf '%s' "$saved_ip"; return
fi
# Query WAN's resolver explicitly, never the local dnsmasq/sing-box resolver.
answer="$(nslookup -timeout=3 -retry=1 "$host" "$dns" 2>/dev/null | awk '
/^Name:/ { in_answer=1 }
in_answer && /^Address([[:space:]][0-9]+)?:/ {
for (i=2;i<=NF;i++) if ($i ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) { print $i; exit }
}')"
case "$answer" in 198.18.*|198.19.*) answer='' ;; esac
if wan_ip_literal "$answer"; then
mkdir -p "$WAN_STATE"
printf '%s %s\n' "$now" "$answer" >"$cache.tmp.$$"
mv "$cache.tmp.$$" "$cache"
printf '%s' "$answer"; return
fi
if [ -n "$saved_ip" ] && [ $((now - saved_ts)) -lt 3600 ]; then
log "WAN DNS unavailable for $host; using last successful WAN address $saved_ip"
printf '%s' "$saved_ip"; return
fi
log "WAN DNS failed: host=$host resolver=$dns"
return 1
}
wan_endpoint_ip() {
local host pinned
host="$(wan_url_host "$1")"
pinned="$(uci_get vps_host '')"
# Preserve HTTP Host and TLS SNI while connecting to the manually pinned VPS.
if ! wan_ip_literal "$host" && [ "$(vps_host_mode)" = manual ] && wan_ip_literal "$pinned"; then
printf '%s' "$pinned"
else
wan_resolve_host "$host"
fi
}
wan_owned_rule_pattern() {
# iif lo selects locally originated traffic, never forwarded LAN packets.
printf '^%s:[[:space:]]*from all (fwmark %s(/0xffffffff)?|to [0-9a-fA-F:.]+(/32|/128)? iif lo) lookup %s[[:space:]]*$' "$WAN_PRIORITY" "$WAN_MARK" "$WAN_TABLE"
}
wan_address_key() {
# Compare IPv6 rules even when ip prints a different compression/zero form.
printf '%s\n' "${1%%/*}" | awk '
/:/ {
s=tolower($0); split(s, halves, "::")
left=split(halves[1], a, ":"); right=split(halves[2], b, ":")
for(i=1;i<=left;i++) parts[++n]=a[i]
if(index(s,"::")) for(i=left+right;i<8;i++) parts[++n]="0"
for(i=1;i<=right;i++) parts[++n]=b[i]
for(i=1;i<=n;i++) { sub(/^0+/, "", parts[i]); if(parts[i]=="") parts[i]="0"; printf "%s%s", i==1?"":":", parts[i] }
print ""; next
}
{ print }
'
}
wan_destination_addresses() {
ip -"$1" rule show | grep -E "$(wan_owned_rule_pattern)" | awk '{ for(i=1;i<NF;i++) if($i=="to") print $(i+1) }'
}
wan_has_destination_rule() {
local family key old
family="$1"; key="$(wan_address_key "$2")"
for old in $(wan_destination_addresses "$family"); do
[ "$(wan_address_key "$old")" != "$key" ] || return 0
done
return 1
}
wan_remove_legacy_rules() {
# Match the complete old selector before each deletion, including duplicates.
# A different mark mask/source/interface belongs to another application.
while ip -"$1" rule show 2>/dev/null | grep -Eq "^$WAN_PRIORITY:[[:space:]]*from all fwmark $WAN_MARK(/0xffffffff)? lookup $WAN_TABLE[[:space:]]*$"; do
ip -"$1" rule del priority "$WAN_PRIORITY" fwmark "$WAN_MARK" table "$WAN_TABLE" || return 1
done
}
wan_xray_addresses() {
local config tag address
config="$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
[ -r "$config" ] || return 0
# Retain the address of the running tunnel until its config is regenerated.
for tag in vps-interconn vps-ssh-interconn; do
address="$(jsonfilter -i "$config" -e "@.outbounds[@.tag=\"$tag\"].settings.address" 2>/dev/null)"
if wan_ip_literal "$address"; then printf '%s\n' "$address"; fi
done
}
wan_apply_destination_rules() {
local dns endpoints targets keys address family old key
dns="$1"; endpoints="$2"
targets="$WAN_STATE/targets.new.$$"; keys="$WAN_STATE/target-keys.$$"
{
printf '%s\n' "$dns"
[ ! -r "$endpoints" ] || awk 'NF { print $1 }' "$endpoints"
wan_xray_addresses
if [ "${3:-0}" = 1 ]; then
wan_destination_addresses 4
wan_destination_addresses 6
fi
} | awk 'NF && !seen[$0]++' >"$targets"
: >"$keys"
while read -r address; do
address="${address%%/*}"
wan_ip_literal "$address" || return 1
case "$address" in *:*) family=6 ;; *) family=4 ;; esac
key="$(wan_address_key "$address")"
printf '%s\n' "$key" >>"$keys"
if ! wan_has_destination_rule "$family" "$address"; then
ip -"$family" rule add priority "$WAN_PRIORITY" iif lo to "$address" table "$WAN_TABLE" || return 1
fi
done <"$targets"
# Add replacements first; remove obsolete addresses only after all succeed.
for family in 4 6; do
for old in $(wan_destination_addresses "$family"); do
key="$(wan_address_key "$old")"
if ! grep -Fqx "$key" "$keys"; then
while ip -"$family" rule del priority "$WAN_PRIORITY" iif lo to "$old" table "$WAN_TABLE" 2>/dev/null; do :; done
fi
done
# Migrate only the old Remote mark rule, never Podkop's own policy rules.
wan_remove_legacy_rules "$family" || return 1
done
mv "$targets" "$WAN_STATE/targets"
rm -f "$keys"
}
wan_remove_legacy_firewall() {
if nft list table inet owrt_remote_wan >/dev/null 2>&1; then
nft delete table inet owrt_remote_wan || { log 'Cannot remove legacy Remote marking table'; return 1; }
fi
}
wan_check_table() {
local family rules routes own error
family="$1"
rules="$(ip -"$family" rule show)" || return 1
own="$(wan_owned_rule_pattern)"
# Never reuse another service's policy priority or routing table.
if printf '%s\n' "$rules" | grep -E "^$WAN_PRIORITY:|lookup $WAN_TABLE([[:space:]]|$)" | grep -Ev "$own" | grep -q .; then
log "WAN IPv$family table $WAN_TABLE or priority $WAN_PRIORITY is already used by another rule"; return 1
fi
error="$WAN_STATE/table-error.$$"
if ! routes="$(ip -"$family" route show table "$WAN_TABLE" 2>"$error")"; then
# iproute2 returns an error for an empty, not-yet-created table.
if ! grep -qi 'FIB table does not exist' "$error"; then
cat "$error" >&2; rm -f "$error"; return 1
fi
fi
rm -f "$error"
if [ -n "$routes" ] && [ ! -f "$WAN_STATE/route-owner-$family" ] && ! printf '%s\n' "$rules" | grep -Eq "$own"; then
log "WAN IPv$family table $WAN_TABLE is not empty and does not belong to Remote"; return 1
fi
}
wan_preflight() {
local device tool
for tool in ip nft ubus jsonfilter curl nslookup; do
command -v "$tool" >/dev/null 2>&1 || { log "WAN direct requires $tool"; return 1; }
done
device="$(wan_device)" || { log "WAN interface is not ready: $(uci_get wan_interface wan)"; return 1; }
case "$device" in tun*|sing*|podkop*) log "WAN direct cannot use a proxy/TUN device: $device"; return 1 ;; esac
ip -4 route show table main default dev "$device" | grep -q '^default' || {
log "WAN has no IPv4 default route on $device"; return 1
}
mkdir -p "$WAN_STATE"
wan_check_table 4 || return 1
if ip -6 rule show >/dev/null 2>&1; then wan_check_table 6 || return 1; fi
}
wan_prepare_locked() {
local device dns gateway family host ip url port
wan_preflight || return 1
device="$(wan_device)" || return 1
dns="$(wan_dns_server)" || return 1
# Use only routes belonging to the selected physical WAN, never a TUN default.
for family in 4 6; do
# Some OpenWrt kernels disable IPv6 completely; IPv4 Remote must still work.
if [ "$family" = 6 ] && ! ip -6 rule show >/dev/null 2>&1; then continue; fi
# Remember ownership before the first mutation, including partial failures.
: >"$WAN_STATE/route-owner-$family"
gateway="$(ip -"$family" route show table main default dev "$device" | awk 'NR==1 { for(i=1;i<NF;i++) if($i=="via") print $(i+1) }')"
if ip -"$family" route show table main default dev "$device" | grep -q '^default'; then
if [ -n "$gateway" ]; then
ip -"$family" route replace default via "$gateway" dev "$device" onlink table "$WAN_TABLE" || return 1
else
ip -"$family" route replace default dev "$device" table "$WAN_TABLE" || return 1
fi
else
ip -"$family" route flush table "$WAN_TABLE" 2>/dev/null || true
fi
# Do not fall through to a proxy route when the physical WAN is absent.
# A default route wins over this terminal unreachable route while WAN is up.
ip -"$family" route replace unreachable default metric 42760 table "$WAN_TABLE" || return 1
done
# Route DNS before resolving Hub, retaining existing tunnel/HTTP addresses.
[ -e "$WAN_STATE/endpoints" ] || : >"$WAN_STATE/endpoints"
wan_apply_destination_rules "$dns" "$WAN_STATE/endpoints" 1 || return 1
wan_remove_legacy_firewall || return 1
host="$(uci_get vps_host '')"
ip="$(wan_resolve_host "$host")" || return 1
port="$(safe_num "$(uci_get vps_port 8443)" 8443)"
[ "$port" -gt 0 ] && [ "$port" -le 65535 ] || return 1
printf '%s %s\n' "$ip" "$port" >"$WAN_STATE/endpoints.new.$$"
# Include fallback web ports, with curl still verifying HTTPS certificates.
for port in 80 443 8088; do printf '%s %s\n' "$ip" "$port" >>"$WAN_STATE/endpoints.new.$$"; done
for url in "$(uci_get hub_url '')" "$(uci_get public_url '')"; do
[ -n "$url" ] || continue
ip="$(wan_endpoint_ip "$url")" || continue
port="$(wan_url_port "$url")" || continue
printf '%s %s\n' "$ip" "$port" >>"$WAN_STATE/endpoints.new.$$"
done
awk '!seen[$0]++' "$WAN_STATE/endpoints.new.$$" >"$WAN_STATE/endpoints.dedup.$$"
mv "$WAN_STATE/endpoints.dedup.$$" "$WAN_STATE/endpoints.new.$$"
wan_apply_destination_rules "$dns" "$WAN_STATE/endpoints.new.$$" || return 1
mv "$WAN_STATE/endpoints.new.$$" "$WAN_STATE/endpoints"
}
wan_prepare() (
local try_num owner
mkdir -p "$WAN_STATE"
try_num=0
while ! mkdir "$WAN_STATE/lock" 2>/dev/null; do
owner="$(cat "$WAN_STATE/lock/pid" 2>/dev/null)"
case "$owner" in ''|*[!0-9]*) ;; *)
if ! kill -0 "$owner" 2>/dev/null; then
rm -f "$WAN_STATE/lock/pid"
rmdir "$WAN_STATE/lock" 2>/dev/null || true
fi
;;
esac
try_num=$((try_num+1)); [ "$try_num" -lt 15 ] || return 1
sleep 1
done
printf '%s' "$$" >"$WAN_STATE/lock/pid"
trap 'rm -f "$WAN_STATE/lock/pid" "$WAN_STATE/endpoints.new.$$" "$WAN_STATE/endpoints.dedup.$$" "$WAN_STATE/targets.new.$$" "$WAN_STATE/target-keys.$$"; rmdir "$WAN_STATE/lock" 2>/dev/null || true' EXIT
trap 'exit 1' INT TERM
wan_prepare_locked
)
wan_post_json() {
local url token file host port ip device
url="$1"; token="$2"; file="$3"
host="$(wan_url_host "$url")"
port="$(wan_url_port "$url")" || return 1
ip="$(wan_endpoint_ip "$url")" || return 1
device="$(wan_device)" || return 1
# A resolver cache may expire between prepare and this request. Refresh
# direct routes before sending to a newly resolved IP.
if ! grep -Fqx "$ip $port" "$WAN_STATE/endpoints" 2>/dev/null; then
wan_prepare || return 1
grep -Fqx "$ip $port" "$WAN_STATE/endpoints" || return 1
fi
case "$ip" in *:*) ip="[$ip]" ;; esac
# No redirect-following or certificate bypass; Host and SNI remain the URL's.
curl -fsS --noproxy '*' --interface "$device" --connect-timeout 4 --max-time 10 \
--resolve "$host:$port:$ip" \
-H "Authorization: Bearer $token" -H 'Content-Type: application/json' \
--data-binary "@$file" "$url"
}
wan_cleanup() {
local family owned address
nft delete table inet owrt_remote_wan 2>/dev/null || true
for family in 4 6; do
owned=0
if [ -f "$WAN_STATE/route-owner-$family" ] || ip -"$family" rule show 2>/dev/null | grep -Eq "$(wan_owned_rule_pattern)"; then owned=1; fi
for address in $(wan_destination_addresses "$family"); do
while ip -"$family" rule del priority "$WAN_PRIORITY" iif lo to "$address" table "$WAN_TABLE" 2>/dev/null; do :; done
done
wan_remove_legacy_rules "$family" 2>/dev/null || true
if [ "$owned" = 1 ]; then ip -"$family" route flush table "$WAN_TABLE" 2>/dev/null || true; fi
rm -f "$WAN_STATE/route-owner-$family"
done
# Only volatile resolver cache owned by this module.
rm -f "$WAN_STATE"/resolve-* "$WAN_STATE/endpoints" "$WAN_STATE/targets"
rm -f "$WAN_STATE/lock/pid"
rmdir "$WAN_STATE/lock" "$WAN_STATE" 2>/dev/null || true
}
wan_diagnostics() {
printf 'vps_host=%s mode=%s WAN_direct=%s\n' "$(uci_get vps_host '')" "$(vps_host_mode)" "$(uci_get wan_direct 0)"
printf 'WAN_device=%s WAN_DNS=%s\n' "$(wan_device)" "$(wan_dns_server)"
printf 'System DNS (compare with WAN DNS):\n'
nslookup -timeout=3 -retry=1 "$(wan_url_host "$(uci_get hub_url '')")" 2>&1 || true
printf '\nWAN DNS:\n'
nslookup -timeout=3 -retry=1 "$(wan_url_host "$(uci_get hub_url '')")" "$(wan_dns_server)" 2>&1 || true
printf '\nRemote routes/rules:\n'
ip -4 rule show
ip -4 route show table "$WAN_TABLE"
printf 'Remote does not create additional nftables marking rules.\n'
}
+84 -16
View File
@@ -8,6 +8,7 @@ XRAY_RELEASE_BASE_URL="${XRAY_RELEASE_BASE_URL:-https://github.com/XTLS/Xray-cor
log() {
printf '%s\n' "$*" >&2
logger -t owrt-remote "$*" 2>/dev/null || true
}
die() {
@@ -26,6 +27,7 @@ usage() {
owrt-remote run
owrt-remote heartbeat
owrt-remote heartbeat-loop
owrt-remote network-diagnostics
Настройки лежат в /etc/config/owrtremote.
EOF
@@ -101,6 +103,20 @@ uci_set_if_changed() {
return 0
}
# Existing installations also default to manual: only an explicit opt-in may
# let a heartbeat replace the administrator's tunnel endpoint.
vps_host_mode() {
case "$(uci_get vps_host_mode manual)" in
auto) printf auto ;;
*) printf manual ;;
esac
}
WAN_HELPER="${OWRT_REMOTE_WAN_HELPER:-/usr/lib/owrt-remote/wan.sh}"
if [ -r "$WAN_HELPER" ]; then
. "$WAN_HELPER"
fi
host_model() {
if [ -r /tmp/sysinfo/model ]; then
cat /tmp/sysinfo/model
@@ -507,6 +523,14 @@ render_client_config() {
router_id="$(safe_id "$(uci_get router_id main)")"
vps_host="$(uci_get vps_host '')"
local wan_sockopt
wan_sockopt=''
if truthy "$(uci_get wan_direct 0)"; then
command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
wan_prepare || die "не удалось подготовить прямое соединение через WAN"
vps_host="$(wan_resolve_host "$vps_host")" || die "VPS host не разрешается через WAN DNS"
wan_sockopt=", \"sockopt\": {\"mark\": $((PODKOP_BYPASS_MARK)), \"interface\": \"$(json_escape "$(wan_device)")\"}"
fi
vps_port="$(safe_num "$(uci_get vps_port 8443)" 8443)"
uuid="$(uci_get vless_uuid '')"
ssh_uuid="$(uci_get ssh_vless_uuid '')"
@@ -567,7 +591,7 @@ render_client_config() {
},
"streamSettings": {
"network": "tcp",
"security": "none"
"security": "none"$wan_sockopt
}
},
{
@@ -585,7 +609,7 @@ render_client_config() {
},
"streamSettings": {
"network": "tcp",
"security": "none"
"security": "none"$wan_sockopt
}
}
],
@@ -678,6 +702,9 @@ heartbeat_json() {
"ssh_host": $(json_string "$(uci_get ssh_host 127.0.0.1)"),
"ssh_port": $(safe_num "$(uci_get ssh_port 22)" 22),
"hub_url": $(json_string "$hub_url"),
"vps_host": $(json_string "$(uci_get vps_host '')"),
"vps_host_mode": $(json_string "$(vps_host_mode)"),
"wan_direct": $(json_string "$(uci_get wan_direct 0)"),
"uptime": $(safe_num "$(uptime_seconds)" 0),
"load": $(json_string "$(load_text)"),
"memory": $(json_string "$(memory_text)"),
@@ -696,23 +723,27 @@ post_json() {
url="$1"
token="$2"
file="$3"
if command -v wget >/dev/null 2>&1; then
wget -q -O - \
--header="Authorization: Bearer $token" \
--header="Content-Type: application/json" \
--post-file="$file" "$url"
if truthy "$(uci_get wan_direct 0)"; then
wan_post_json "$url" "$token" "$file"
return
fi
if command -v curl >/dev/null 2>&1; then
curl -fsS \
curl -fsS --connect-timeout 4 --max-time 10 --noproxy '*' \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
--data-binary "@$file" "$url"
return
fi
if command -v wget >/dev/null 2>&1; then
http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY= ALL_PROXY= all_proxy= wget -q -T 10 -O - \
--header="Authorization: Bearer $token" \
--header="Content-Type: application/json" \
--post-file="$file" "$url"
return
fi
if command -v uclient-fetch >/dev/null 2>&1; then
uclient-fetch -q -O - \
http_proxy= https_proxy= HTTP_PROXY= HTTPS_PROXY= ALL_PROXY= all_proxy= uclient-fetch -q -T 10 -O - \
--header="Authorization: Bearer $token" \
--header="Content-Type: application/json" \
--post-file="$file" "$url"
@@ -760,12 +791,14 @@ heartbeat_candidate_endpoints() {
}
heartbeat_apply_hub_update() {
local response_file fallback_base next_hub_url next_public_url next_vps_host changed
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"
fallback_base="$2"
next_hub_url="$(json_extract_object_string "$response_file" hub_update hub_url)"
next_public_url="$(json_extract_object_string "$response_file" hub_update public_url)"
next_vps_host="$(json_extract_object_string "$response_file" hub_update vps_host)"
old_vps_host="$(uci_get vps_host '')"
mode="$(vps_host_mode)"
[ -n "$next_hub_url" ] || next_hub_url="$fallback_base"
changed=0
if uci_set_if_changed hub_url "$next_hub_url"; then
@@ -774,12 +807,26 @@ heartbeat_apply_hub_update() {
if uci_set_if_changed public_url "$next_public_url"; then
changed=1
fi
if uci_set_if_changed vps_host "$next_vps_host"; then
changed=1
if [ "$mode" = auto ]; then
if uci_set_if_changed vps_host "$next_vps_host"; then
changed=1
fi
elif [ -n "$next_vps_host" ] && [ "$old_vps_host" != "$next_vps_host" ]; then
ignored_file="${TMPDIR:-/tmp}/owrt-remote-vps-host-ignored"
ignored="$old_vps_host|$next_vps_host"
if [ "$(cat "$ignored_file" 2>/dev/null)" != "$ignored" ]; then
log "heartbeat kept vps_host: current=$old_vps_host proposed=$next_vps_host reason=manual"
printf '%s' "$ignored" >"$ignored_file"
fi
fi
[ "$changed" = "1" ] || return 0
uci commit "$CONFIG" >/dev/null 2>&1 || true
uci commit "$CONFIG" >/dev/null 2>&1 || return 1
log "heartbeat updated hub settings: hub_url=$(uci_get hub_url '') public_url=$(uci_get public_url '') vps_host=$(uci_get vps_host '')"
if [ "$mode" = auto ] && [ -n "$next_vps_host" ] && [ "$old_vps_host" != "$next_vps_host" ]; then
log "heartbeat updated vps_host: old=$old_vps_host new=$next_vps_host reason=hub_update mode=auto"
# The running Xray keeps its old address until it is restarted.
( sleep 2; /etc/init.d/owrt-remote restart >/dev/null 2>&1 ) </dev/null >/dev/null 2>&1 &
fi
}
send_heartbeat() {
@@ -789,6 +836,10 @@ send_heartbeat() {
token="$(uci_get hub_token '')"
[ -n "$hub_url" ] || die "hub_url пустой"
[ -n "$token" ] || die "hub_token пустой"
if truthy "$(uci_get wan_direct 0)"; then
command -v wan_prepare >/dev/null 2>&1 || die "WAN helper missing: $WAN_HELPER"
wan_prepare || return 1
fi
endpoint="${hub_url%/}/api/heartbeat"
tmp="${TMPDIR:-/tmp}/owrt-remote-heartbeat.$$"
@@ -799,14 +850,17 @@ send_heartbeat() {
used=1
if post_json "$endpoint" "$token" "$tmp" >"$response"; then
fallback_base="$(heartbeat_base_from_endpoint "$endpoint")"
heartbeat_apply_hub_update "$response" "$fallback_base"
if ! heartbeat_apply_hub_update "$response" "$fallback_base"; then
rm -f "$tmp" "$response"
return 1
fi
cat "$response"
rm -f "$tmp" "$response"
return 0
fi
done
rm -f "$tmp" "$response"
[ "$used" = "1" ] || die "hub_url/public_url/vps_host пустые"
[ "$used" = "1" ] || die "hub_url/public_url/vps_host пустые"
return 1
}
@@ -867,6 +921,8 @@ status() {
printf 'enabled: %s\n' "$(uci_get enabled 0)"
printf 'hub_url: %s\n' "$(uci_get hub_url '')"
printf 'vps_host: %s\n' "$(uci_get vps_host '')"
printf 'vps_host_mode: %s\n' "$(vps_host_mode)"
printf 'wan_direct: %s\n' "$(uci_get wan_direct 0)"
printf 'vps_port: %s\n' "$(uci_get vps_port 8443)"
printf 'xray_bin: %s\n' "$(xray_bin_path)"
printf 'xray_config: %s\n' "$(uci_get xray_config /etc/xray/owrt-remote-client.json)"
@@ -1124,6 +1180,18 @@ case "$cmd" in
doctor)
doctor
;;
wan-prepare)
wan_prepare
;;
wan-preflight)
wan_preflight
;;
wan-cleanup)
wan_cleanup
;;
network-diagnostics)
wan_diagnostics
;;
install-xray-tmp)
install_xray_tmp
;;
+19 -3
View File
@@ -136,13 +136,17 @@ save_config() {
for field in router_id router_name role hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port public_url; do
uci_set "$field" "$(param "$field")"
done
if has_param vps_host_auto; then uci_set vps_host_mode auto; else uci_set vps_host_mode manual; fi
if has_param wan_direct; then uci_set wan_direct 1; else uci_set wan_direct 0; fi
uci_set wan_interface "$(param wan_interface)"
uci_set wan_dns "$(param wan_dns)"
uci commit owrtremote
set_result "Настройки сохранены" "Если менял Xray или VPS-поля, перезапусти сервис." "ok"
}
clear_config() {
local field
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_host_mode wan_direct wan_interface wan_dns vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
uci -q delete "owrtremote.main.$field"
done
uci commit owrtremote
@@ -279,6 +283,10 @@ EOF
render_page() {
local key router_id router_name hub_url service_state service_tone xray_state xray_tone enabled_checked status_text
local vps_host_auto_checked wan_direct_checked
vps_host_auto_checked=''; wan_direct_checked=''
[ "$(uci_get vps_host_mode manual)" != auto ] || vps_host_auto_checked=checked
[ "$(uci_get wan_direct 0)" != 1 ] || wan_direct_checked=checked
key="$(param key)"
router_id="$(uci_get router_id main)"
router_name="$(uci_get router_name "$router_id")"
@@ -314,7 +322,7 @@ render_page() {
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="owrt-remote-ui-version" content="$OWRT_REMOTE_UI_VERSION">
<title>OpenWrt Remote Hub v110</title>
<title>OpenWrt Remote Hub v111</title>
<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)}
*{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}
@@ -344,7 +352,7 @@ form{margin:0}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr
<div class="brand">
<div class="brandPanel">
<div class="titleRow">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v110</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v111</span></span></h1>
</div>
<div class="links">
<a class="uiPill" href="https://t.me/kzolotarev95" target="_blank" rel="noopener noreferrer">Telegram</a>
@@ -441,6 +449,14 @@ EOF
field xray_bin "Xray binary" text "Путь к Xray на роутере. Если ставил пакет xray-core, обычно оставь /usr/bin/xray."
field xray_config "Xray config" text "Куда агент сохранит клиентский Xray-конфиг. Обычно оставь /etc/xray/owrt-remote-client.json."
field vps_host "VPS host" text "IP или домен VPS, куда Xray роутера подключается reverse-туннелем. Бери IP/домен своего VPS."
cat <<EOF
<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>
<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>
EOF
field wan_interface "WAN интерфейс" text "Логическое имя WAN из OpenWrt, обычно wan. Пустое поле означает wan."
field wan_dns "WAN DNS" text "Необязательно: IP DNS-сервера для Remote. Пустое поле — DNS от провайдера на WAN."
field vps_port "VPS Xray port" number "Порт Xray на VPS для reverse-туннеля. Должен совпадать с render-xray на VPS, обычно 8443."
field vless_uuid "VLESS UUID" text "Уникальный UUID роутера. Бери из карточки роутера на VPS или из команды print-openwrt-config."
field vless_encryption "VLESS encryption" text "Для этой схемы оставь none. Меняй только если сам меняешь Xray-конфиг на VPS."
@@ -14,7 +14,7 @@ return view.extend({
if (!key) {
return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Remote Hub v110')),
E('h2', {}, _('OpenWrt Remote Hub v111')),
E('div', { 'class': 'alert-message warning' }, [
_('Web key not found. Reinstall the module or create /etc/owrt-remote/web.key.')
])
@@ -34,7 +34,7 @@ return view.extend({
}, 100);
return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Remote Hub v110')),
E('h2', {}, _('OpenWrt Remote Hub v111')),
E('p', {}, _('Opening remote access panel...')),
E('p', {}, [
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Open panel'))
+1
View File
@@ -215,6 +215,7 @@ install_xray_runtime() {
}
install_file "usr/sbin/owrt-remote" 0755
install_file "usr/lib/owrt-remote/wan.sh" 0644
install_file "etc/init.d/owrt-remote" 0755
install_file "etc/hotplug.d/iface/99-owrt-remote" 0755
install_config
+145
View File
@@ -0,0 +1,145 @@
# Фиксация VPS host и независимое соединение Remote через WAN (v111)
`vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение
используется и когда опция отсутствует у старой установки. Только явно
выбранное `auto` позволяет принять `hub_update.vps_host`. Ни один ответ
heartbeat не может сам включить автоматический режим. Изменения и
отклонённые предложения пишутся через `logger -t owrt-remote` в logread;
повтор одинакового отклонённого предложения не засоряет журнал.
Hub сохраняет прежнее поведение для старых агентов, ещё не сообщающих
режим. Сам обновлённый агент по умолчанию защищает ручной адрес даже
при старой версии Hub. Для полного фикса сначала обновляется роутер.
На роутере в настройках есть «Автоматически обновлять VPS host».
Блок «Настроить VPS host» убран из карточек Hub на ПК и мобильном.
Он не появляется при периодическом обновлении карточек. Сам механизм
ручного/автоматического режима и API применения адреса по SSH сохраняются.
OpenWrt config / автоматическое переприменение конфигурации больше не
удаляет всю UCI-секцию и сохраняет существующий ручной адрес и WAN-параметры.
## Прямой WAN
`wan_direct=1` включает отдельный маршрут для Remote; по умолчанию эта
опция выключена в поставляемой конфигурации и старых установках. Скрипт
локальной установки ниже включает её для тестирования на вашем роутере.
* `wan_interface=wan` — логическое имя интерфейса OpenWrt. Реальный
`l3_device` (включая PPPoE) берётся через ubus. Он должен иметь физический
default route в main; TUN-устройства не принимаются как WAN.
* Таблица маршрутов `210` и приоритет `104` принадлежат Remote.
В таблицу копируется только default route выбранного WAN.
Номер таблицы совместим со штатным BusyBox ip. Занятые другим сервисом
таблица или приоритет приводят к отказу до изменения маршрутов.
* Вместо дополнительных nftables-правил используются адресные `ip rule`
с `iif lo`. Они выбирают только пакеты, созданные самим роутером, к реальным
адресам Hub, действующего Xray и DNS выбранного WAN. LAN/FORWARD не меняются.
Ограничение по портам не используется: весь локальный трафик к этим адресам
идёт через WAN. Приоритет 104 выше стандартного правила Podkop 105.
* Только два VPS-outbound Xray получают SO_MARK `0x00200000` (штатный bypass
Podkop) и привязку к WAN-интерфейсу. Дополнительная nft-таблица не создаётся;
прежняя `inet owrt_remote_wan` и собственные правила `0x40000000` удаляются
при переходе. Проверка предупреждений самого Podkop не изменяется.
Локальные подключения к админке и SSH продолжают работать локально.
* Для доменов используется прямой запрос к DNS провайдера на WAN
(можно задать `wan_dns`). Ответ FakeIP 198.18.0.0/15 отклоняется.
Успешный ответ кешируется 5 минут, при временном сбое допускается
использование предыдущего ответа максимум час.
* При ручном IP домен HTTPS Hub соединяется с этим IP через curl `--resolve`:
сохраняются Host, SNI и проверка сертификата. Проверка TLS не отключается.
Xray соединяется с IP без DNS. Запросы heartbeat ограничены по времени.
* Правила обновляются при heartbeat и старте, очищаются при остановке/откате.
Настройки Podkop, dnsmasq и службы sing-box не изменяются.
Это отделяет соединение Remote от Podkop. Общая схема fallback для клиентов
LAN при **аварийном падении** sing-box относится к настройкам самого Podkop;
этот фикс не обещает восстановление DNS/FakeIP-сессий всей LAN.
## Что известно о домене
08.10.2026 системный DNS на компьютере разработки возвращает для
`owrt-zks95.developer.li` IPv4 `193.233.82.38`. Это не подтверждает, что
роутер получает тот же ответ. В стандартном Podkop dnsmasq направляется
на DNS sing-box. Поэтому разница «IP работает, домен периодически не
работает» может быть вызвана DNS/FakeIP/маршрутизацией, но без логов
самого роутера нельзя утверждать точную причину.
После установки команда `owrt-remote network-diagnostics` сравнивает
системный DNS с прямым WAN DNS и показывает собственные правила Remote.
В вывод не включаются Hub token, UUID и SSH-пароли. Для проверки поведения
при работающем и остановленном Podkop нужен настоящий OpenWrt-роутер.
Источники:
[DNS, OUTPUT и диагностика Podkop 0.7.22](https://github.com/itdoginfo/podkop/blob/0.7.22/podkop/files/usr/bin/podkop),
[маркировка Podkop 0.7.22](https://github.com/itdoginfo/podkop/blob/0.7.22/podkop/files/usr/lib/constants.sh),
[Xray sockopt](https://xtls.github.io/en/config/transports/sockopt.html),
[локальные пакеты и iif lo](https://man7.org/linux/man-pages/man8/ip-rule.8.html),
[ограничение ID таблиц в BusyBox ip](https://github.com/mirror/busybox/blob/master/networking/libiproute/rt_names.c).
## Установка и откат с Windows 11
В PowerShell из каталога проекта. При другом IP роутера или логическом
имени WAN замените значения параметров. VPS host фиксируется на указанном IP.
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PinnedVpsHost "193.233.82.38" -WanInterface "wan" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Vps -Machine "root@193.233.82.38" -Action Install
```
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -Action Rollback
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Vps -Machine "root@193.233.82.38" -Action Rollback
```
Установка загружает локальные файлы, без Git. До остановки службы проверяются
доступность WAN и поддержка таблицы реальной командой ip на роутере.
На роутер загружается и файл LuCI: версия v111 появляется и в основной
CGI-панели, и в странице входа в неё через LuCI.
Сначала сохраняются файлы
и конфигурация; после замены проверяется heartbeat/health. При ошибке
автоматически восстанавливается состояние перед текущей попыткой.
Сохранённая резервная копия для ручного отката не перезаписывается.
* Роутер: `/root/owrt-remote-backup-before-host-policy-v111` — агент,
helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге).
* VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v111`.
База роутеров и настройки авторизации не заменяются.
Успешная установка заканчивается `HOST_POLICY_ROUTER_V111_OK` на роутере
и `HOST_POLICY_VPS_V111_Install_OK` на VPS. Старые резервные копии предыдущей
версии сохраняются; новые команды отката используют отдельные копии для v111.
### Переход с nftables-маркировки на адресную маршрутизацию
Для уже настроенного роутера используется отдельная резервная копия.
Эти команды сохраняют существующие VPS host, ручной/auto режим и WAN-настройки.
Обновление VPS для этого изменения не требуется.
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PreserveConnectionSettings -BackupName "podkop-compat-v111" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v111" -Action Rollback
```
Копия: `/root/owrt-remote-backup-before-podkop-compat-v111`.
После установки повторите диагностику Podkop. Предупреждение от прежних правил
Remote должно исчезнуть. Настоящие дополнительные правила других приложений
по-прежнему обнаруживаются штатной диагностикой.
## Локальные проверки
```powershell
python -m unittest discover -s tests -v
python tests/test_recaptcha.py --export-js .test-output/recaptcha
node --check .test-output/recaptcha/dashboard.js
node tests/test_host_policy_ui.cjs .test-output/recaptcha/dashboard.js
```
Shell-тесты исполняют код агента в Git for Windows sh или Linux sh
с подменёнными UCI, ubus, DNS, nft, ip и curl. Проверяются ручной/auto режим,
сохранение IP при rebind, реальные аргументы curl/Xray, WAN-таблицы,
миграция прежних правил, отсутствие дубликатов при heartbeat, сохранение
адреса работающего туннеля при смене DNS, IPv6, ошибки DNS и восстановление.
Оригинальная функция `check_nft_rules` из Podkop 0.7.22 исполняется на подменённом
nft: прежние правила дают предупреждение, переход убирает его, а посторонние
маркирующие правила по-прежнему вызывают предупреждение.
Это не заменяет аппаратную проверку nftables и Podkop на OpenWrt.
+3 -3
View File
@@ -1,4 +1,4 @@
# reCAPTCHA v3 в OpenWrt Remote Hub v110
# reCAPTCHA v3 в OpenWrt Remote Hub v111
В меню владельца, в блоке «Капча на экране входа», доступны цифры,
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-v110`
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json` (режим 0600).
* `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v111`
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v111.json` (режим 0600).
Скрипт рассчитан на стандартные пути установленного Hub:
`/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 v110
# Аудит ресурсов OpenWrt Remote Hub v111
Исправления внесены поверх `7f809fd`. Версия панели остаётся v110.
Исправления внесены поверх `7f809fd`. Версия панели остаётся v111.
## SQLite
@@ -115,7 +115,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-resource-fix
Установщик загружает локальный файл без Git, запускает изолированные тесты,
сохраняет исходный серверный файл:
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110`,
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v111`,
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
Существующая резервная копия не перезаписывается. При ошибке установки
восстанавливается файл, работавший непосредственно перед текущей попыткой.
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+86
View File
@@ -0,0 +1,86 @@
# Diagnostic fixture from Podkop 0.7.22 (GPL-2.0; see PODKOP-LICENSE).
# https://github.com/itdoginfo/podkop/blob/0.7.22/podkop/files/usr/bin/podkop
# Commit c0a2736bb95884c19fedf638345ed6148c5fd6af
check_nft_rules() {
local table_exist=0
local rules_mangle_exist=0
local rules_mangle_counters=0
local rules_mangle_output_exist=0
local rules_mangle_output_counters=0
local rules_proxy_exist=0
local rules_proxy_counters=0
local rules_other_mark_exist=0
# Generate traffic through PodkopTable
curl -m 3 -s "https://$CHECK_PROXY_IP_DOMAIN/check" > /dev/null 2>&1 &
local pid1=$!
curl -m 3 -s "https://$FAKEIP_TEST_DOMAIN/check" > /dev/null 2>&1 &
local pid2=$!
wait $pid1 2> /dev/null
wait $pid2 2> /dev/null
sleep 1
# Check if PodkopTable exists
if nft list table inet "$NFT_TABLE_NAME" > /dev/null 2>&1; then
table_exist=1
# Check mangle chain rules
if nft list chain inet "$NFT_TABLE_NAME" mangle > /dev/null 2>&1; then
local mangle_output
mangle_output=$(nft list chain inet "$NFT_TABLE_NAME" mangle)
if echo "$mangle_output" | grep -q "counter"; then
rules_mangle_exist=1
if echo "$mangle_output" | grep "counter" | grep -qv "packets 0 bytes 0"; then
rules_mangle_counters=1
fi
fi
fi
# Check mangle_output chain rules
if nft list chain inet "$NFT_TABLE_NAME" mangle_output > /dev/null 2>&1; then
local mangle_output_output
mangle_output_output=$(nft list chain inet "$NFT_TABLE_NAME" mangle_output)
if echo "$mangle_output_output" | grep -q "counter"; then
rules_mangle_output_exist=1
if echo "$mangle_output_output" | grep "counter" | grep -qv "packets 0 bytes 0"; then
rules_mangle_output_counters=1
fi
fi
fi
# Check proxy chain rules
if nft list chain inet "$NFT_TABLE_NAME" proxy > /dev/null 2>&1; then
local proxy_output
proxy_output=$(nft list chain inet "$NFT_TABLE_NAME" proxy)
if echo "$proxy_output" | grep -q "counter"; then
rules_proxy_exist=1
if echo "$proxy_output" | grep "counter" | grep -qv "packets 0 bytes 0"; then
rules_proxy_counters=1
fi
fi
fi
fi
# Check for other mark rules outside PodkopTable
nft list tables 2> /dev/null | while read -r _ family table_name; do
[ -z "$table_name" ] && continue
[ "$table_name" = "$NFT_TABLE_NAME" ] && continue
if nft list table "$family" "$table_name" 2> /dev/null | grep -q "meta mark set"; then
touch /tmp/podkop_mark_check.$$
break
fi
done
if [ -f /tmp/podkop_mark_check.$$ ]; then
rules_other_mark_exist=1
rm -f /tmp/podkop_mark_check.$$
fi
echo "{\"table_exist\":$table_exist,\"rules_mangle_exist\":$rules_mangle_exist,\"rules_mangle_counters\":$rules_mangle_counters,\"rules_mangle_output_exist\":$rules_mangle_output_exist,\"rules_mangle_output_counters\":$rules_mangle_output_counters,\"rules_proxy_exist\":$rules_proxy_exist,\"rules_proxy_counters\":$rules_proxy_counters,\"rules_other_mark_exist\":$rules_other_mark_exist}" | jq .
}
+488
View File
@@ -0,0 +1,488 @@
"""Host locking and WAN isolation regressions; no router/network is required."""
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
SOURCE = Path(os.environ.get("OWRT_HOST_POLICY_HUB_SOURCE", ROOT / "vps/owrt-remote-hub.py"))
STATE = tempfile.TemporaryDirectory(prefix="owrt-host-policy-tests-")
spec = importlib.util.spec_from_file_location("host_policy_hub", SOURCE)
hub = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = hub
with mock.patch.dict(os.environ, {"OWRT_REMOTE_STATE_DIR": STATE.name}):
spec.loader.exec_module(hub)
SH = shutil.which("sh")
if not SH and os.name == "nt":
candidate = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "Git/usr/bin/sh.exe"
SH = str(candidate) if candidate.exists() else None
MOCKS = r'''
uci() {
[ "$1" != -q ] || shift
case "$1" in
get)
if [ "$2" = owrtremote.main ]; then echo remote; return; fi
awk -F= -v key="$2" '$1==key { sub(/^[^=]*=/, ""); print; found=1; exit } END { if (!found) exit 1 }' "$TEST_ROOT/uci"
;;
set)
key="${2%%=*}"; value="${2#*=}"
awk -F= -v key="$key" '$1!=key' "$TEST_ROOT/uci" >"$TEST_ROOT/uci.new"
printf '%s=%s\n' "$key" "$value" >>"$TEST_ROOT/uci.new"
mv "$TEST_ROOT/uci.new" "$TEST_ROOT/uci"
;;
commit) echo commit >>"$TEST_ROOT/commits" ;;
delete) return 0 ;;
esac
}
logger() { printf '%s\n' "$*" >>"$TEST_ROOT/log"; }
owrt-remote() {
[ "$1" != status ] || { printf 'vps_host_mode: manual\n'; return; }
[ "$1" != render-client ] || [ "${RENDER_FAIL:-0}" = 0 ]
}
ubus() { printf '{}'; }
jsonfilter() {
if [ "$1" = -i ]; then
"$TEST_PYTHON" -c 'import json, re, sys; data=json.load(open(sys.argv[1])); tag=re.search(r"tag=\"([^\"]+)\"", sys.argv[2]).group(1); print(next((o.get("settings", {}).get("address", "") for o in data.get("outbounds", []) if o.get("tag")==tag), ""))' "$2" "$4"
return
fi
cat >/dev/null
case "$2" in '@.l3_device') printf pppoe-wan ;; *) printf 1.1.1.1 ;; esac
}
ip() {
local previous arg family action rule address mark priority table
printf '%s\n' "$*" >>"$TEST_ROOT/ip"
# BusyBox's table parser rejects large IDs (older builds even above 255).
previous=''
for arg in "$@"; do
if [ "$previous" = table ] && [ "$arg" -eq "$arg" ] 2>/dev/null && [ "$arg" -gt 255 ]; then
printf "ip: invalid argument '%s' to 'table'\n" "$arg" >&2; return 1
fi
previous="$arg"
done
family="${1#-}"
if [ "$2" = rule ]; then
[ "$family" != 6 ] || [ "${IPV6_DISABLED:-0}" = 0 ] || return 1
touch "$TEST_ROOT/rules-$family"
action="$3"
if [ "$action" = show ]; then
cat "$TEST_ROOT/rules-$family"
elif [ "$action" = add ] || [ "$action" = del ]; then
shift 3
address=''; mark=''; priority=''; table=''
while [ "$#" -gt 0 ]; do
case "$1" in
priority) priority="$2" ;;
to) address="$2" ;;
fwmark) mark="$2" ;;
table) table="$2" ;;
iif) [ "$2" = lo ] || return 1 ;;
*) return 1 ;;
esac
shift 2
done
if [ -n "$address" ]; then
# ip normalizes IPv6 spelling in the actual kernel's rule dump.
case "$address" in *:*) address="$("$TEST_PYTHON" -c 'import ipaddress,sys; print(ipaddress.ip_interface(sys.argv[1]).ip.compressed)' "$address")" ;; esac
rule="$priority: from all to $address iif lo lookup $table"
else
rule="$priority: from all fwmark $mark lookup $table"
fi
if [ "$action" = add ]; then
[ "${RULE_ADD_FAIL:-}" != "$address" ] || return 1
printf '%s\n' "$rule" >>"$TEST_ROOT/rules-$family"
else
awk -v rule="$rule" '$0==rule { found=1; next } { print } END { if(!found) exit 1 }' "$TEST_ROOT/rules-$family" >"$TEST_ROOT/rules-new-$family" || return 1
mv "$TEST_ROOT/rules-new-$family" "$TEST_ROOT/rules-$family"
fi
return 0
fi
fi
case "$*" in
'-6 rule show') [ "${IPV6_DISABLED:-0}" = 0 ] || return 1 ;;
'-4 route show table main default dev pppoe-wan')
[ "${WAN_DOWN:-0}" = 0 ] && echo 'default via 10.0.0.1 dev pppoe-wan' ;;
'-4 rule show')
case "${TABLE_CONFLICT:-}" in
rule) echo '105: from all fwmark 0x10000 lookup 210' ;;
priority) echo '104: from all fwmark 0x10000 lookup 105' ;;
esac ;;
'-4 route show table 210')
if [ "${TABLE_MISSING:-0}" = 1 ]; then echo 'Error: ipv4: FIB table does not exist.' >&2; return 2; fi
[ "${TABLE_CONFLICT:-}" != route ] || echo 'default via 192.0.2.1 dev other-wan' ;;
esac
return 0
}
nft() {
printf '%s\n' "$*" >>"$TEST_ROOT/nft"
case "$*" in
'list tables')
printf 'table inet PodkopTable\n'
[ ! -f "$TEST_ROOT/legacy-nft" ] || printf 'table inet owrt_remote_wan\n'
[ ! -f "$TEST_ROOT/foreign-nft" ] || printf 'table inet vpn_other\n'
return 0 ;;
'list table inet PodkopTable') printf 'meta mark set 0x00100000\n'; return 0 ;;
'list chain inet PodkopTable '*) printf 'counter packets 12 bytes 1200\n'; return 0 ;;
'list table inet owrt_remote_wan') test -f "$TEST_ROOT/legacy-nft" && cat "$TEST_ROOT/legacy-nft" ;;
'list table inet vpn_other') test -f "$TEST_ROOT/foreign-nft" && cat "$TEST_ROOT/foreign-nft" ;;
'delete table inet owrt_remote_wan')
[ "${NFT_FAIL:-0}" = 0 ] || return 1
rm -f "$TEST_ROOT/legacy-nft" ;;
*) return 1 ;;
esac
}
nslookup() {
printf '%s\n' "$*" >>"$TEST_ROOT/dns"
[ "${DNS_FAIL:-0}" = 0 ] || return 1
printf 'Server: 1.1.1.1\nAddress: 1.1.1.1:53\n\nName: hub.example\nAddress 1: %s\n' "${DNS_ANSWER:-193.233.82.38}"
}
curl() { printf '<%s>\n' "$@" >"$TEST_ROOT/curl"; }
'''
class HostPolicyTests(unittest.TestCase):
def row(self, mode="manual", host="193.233.82.38"):
return {"id": "test-router", "vps_host": "hub.example", "public_url": "https://hub.example", "status_json": json.dumps({"vps_host_mode": mode, "vps_host": host})}
def test_manual_heartbeat_never_proposes_a_new_tunnel_host(self):
for row in (self.row(), {"vps_host": "hub.example", "status": {"vps_host_mode": "manual"}}):
update = hub.canonical_router_hub_update(row, "https://hub.example")
self.assertNotIn("vps_host", update)
self.assertEqual(update["hub_url"], "https://hub.example")
def test_legacy_agent_keeps_central_update_until_policy_reported(self):
self.assertEqual(hub.canonical_router_hub_update({"vps_host": "hub.example"})["vps_host"], "hub.example")
def test_new_config_explicitly_defaults_to_manual(self):
payload = hub.build_openwrt_config_payload({"id": "new", "vps_host": "193.233.82.38"}, "https://hub.example")
self.assertEqual(payload["vps_host_mode"], "manual")
def test_auto_heartbeat_retains_central_host(self):
self.assertEqual(hub.canonical_router_hub_update(self.row("auto"))["vps_host"], "hub.example")
def test_rebind_prefers_manual_reported_ip_over_public_hostname(self):
bundle, url, host = hub.router_current_hub_bundle(self.row(), "https://hub.example")
self.assertEqual(host, "193.233.82.38")
self.assertEqual(url, "https://hub.example")
self.assertEqual(bundle["vps_host"], host)
def test_mode_reads_row_and_api_status_and_handles_invalid_json(self):
for status in ("not-json", "[]", "null"):
self.assertEqual(hub.router_reported_connection({"status_json": status, "vps_host": "193.233.82.38"}), ("auto", "193.233.82.38"))
self.assertEqual(hub.router_reported_connection({"status": {"vps_host_mode": "auto", "vps_host": "hub.example"}}), ("auto", "hub.example"))
def test_ui_script_validates_before_ssh_and_checks_agent_version(self):
for host in ("", "https://hub.example", "host:8443", "x'; reboot", "bad..domain", "-bad.host", "999.999.999.999"):
with self.assertRaises(ValueError):
hub.make_router_vps_host_script(host, "manual")
with self.assertRaises(ValueError):
hub.make_router_vps_host_script("193.233.82.38", "invalid")
self.assertIn("Сначала обнови агент", hub.make_router_vps_host_script("193.233.82.38", "manual"))
def test_hub_ui_endpoint_requires_owner_and_only_saves_after_remote_ack(self):
from types import SimpleNamespace
db = Path(STATE.name) / "policy-api.db"
with hub.connect(db) as conn:
hub.init_db(conn)
hub.upsert_router(conn, {"id": "test", "vps_host": "old.example"})
handler = object.__new__(hub.Handler)
handler.server = SimpleNamespace(app=SimpleNamespace(conn=lambda: hub.connect(db)))
handler.parsed = lambda: SimpleNamespace(path="/api/router/test/vps-host")
handler.maybe_proxy_luci_absolute = lambda path: False
handler.require_admin = lambda: True
handler.send_json = mock.Mock()
handler.run_router_ssh_script = mock.Mock(return_value="VPS_HOST_APPLIED\n")
handler.read_payload = mock.Mock(return_value={"vps_host": "193.233.82.38", "vps_host_mode": "manual", "ssh_password": "test-password"})
handler.require_owner = lambda **kwargs: False
handler.do_POST()
handler.read_payload.assert_not_called()
handler.run_router_ssh_script.assert_not_called()
handler.require_owner = lambda **kwargs: True
handler.run_router_ssh_script.side_effect = RuntimeError("SSH failed")
handler.do_POST()
with hub.connect(db) as conn:
self.assertEqual(hub.get_router(conn, "test")["vps_host"], "old.example")
self.assertEqual(handler.send_json.call_args.args[0], 400)
handler.run_router_ssh_script.side_effect = None
handler.do_POST()
self.assertEqual(handler.send_json.call_args.args[0], 200)
with hub.connect(db) as conn:
row = hub.get_router(conn, "test")
self.assertEqual(row["vps_host"], "193.233.82.38")
self.assertEqual(hub.router_reported_connection(row), ("manual", "193.233.82.38"))
@unittest.skipUnless(SH, "a POSIX shell (Git for Windows or Linux) is required")
class RouterShellTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="owrt-shell-tests-")
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
(self.directory / "uci").write_text("", encoding="utf-8")
self.agent = (ROOT / "files/usr/sbin/owrt-remote").read_text(encoding="utf-8").split('cmd="${1:-help}"')[0]
self.env = {**os.environ, "TEST_ROOT": self.directory.as_posix(), "TMPDIR": self.directory.as_posix(), "TEST_PYTHON": Path(sys.executable).as_posix(), "OWRT_REMOTE_WAN_HELPER": (ROOT / "files/usr/lib/owrt-remote/wan.sh").as_posix()}
def config(self, **kwargs):
(self.directory / "uci").write_text("".join(f"owrtremote.main.{key}={value}\n" for key, value in kwargs.items()), encoding="utf-8")
def run_shell(self, commands, **env):
return subprocess.run([SH], input=self.agent + "\n" + MOCKS + "\n" + commands, encoding="utf-8", capture_output=True, env={**self.env, **env}, cwd=ROOT, timeout=30)
def test_old_and_explicit_manual_modes_ignore_host_rewrite(self):
response = {"hub_update": {"vps_host": "hub.example", "hub_url": "https://hub.example", "public_url": "https://hub.example"}}
(self.directory / "response").write_text(json.dumps(response), encoding="utf-8")
for mode in (None, "manual", "invalid"):
values = {"vps_host": "193.233.82.38", "hub_url": "https://hub.example", "public_url": "https://hub.example"}
if mode: values["vps_host_mode"] = mode
self.config(**values)
result = self.run_shell('heartbeat_apply_hub_update "$TEST_ROOT/response" https://hub.example; uci_get vps_host ""')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "193.233.82.38")
self.assertIn("reason=manual", (self.directory / "log").read_text(encoding="utf-8"))
def test_explicit_auto_changes_host_and_logs_old_new_reason(self):
self.config(vps_host="193.233.82.38", vps_host_mode="auto")
(self.directory / "response").write_text(json.dumps({"hub_update": {"vps_host": "hub.example"}}), encoding="utf-8")
result = self.run_shell('heartbeat_apply_hub_update "$TEST_ROOT/response" https://hub.example; uci_get vps_host ""')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "hub.example")
self.assertIn("old=193.233.82.38 new=hub.example reason=hub_update mode=auto", result.stderr)
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")
payload = hub.build_openwrt_config_payload(self.row(), "https://hub.example")
script = "\n".join(hub.build_openwrt_config_lines(payload, mode="ssh-apply"))
result = self.run_shell(script + '\nprintf "host=%s wan=%s dns=%s iface=%s" "$(uci_get vps_host "")" "$(uci_get wan_direct "")" "$(uci_get wan_dns "")" "$(uci_get wan_interface "")"')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("host=193.233.82.38 wan=1 dns=9.9.9.9 iface=internet", result.stdout)
def row(self):
return {"id": "test-router", "name": "test", "vps_host": "hub.example", "reverse_tag": "test-in"}
def test_wan_routes_only_local_hub_and_dns_without_nft_marking(self):
self.config(vps_host="193.233.82.38", hub_url="https://hub.example", vps_host_mode="manual")
result = self.run_shell("wan_prepare")
self.assertEqual(result.returncode, 0, result.stderr)
rules = (self.directory / "rules-4").read_text().splitlines()
self.assertEqual(set(rules), {"104: from all to 193.233.82.38 iif lo lookup 210", "104: from all to 1.1.1.1 iif lo lookup 210"})
self.assertTrue(all(" iif lo " in rule for rule in rules), "forwarded br-lan traffic must not match")
self.assertNotIn("mark set", (self.directory / "nft").read_text())
routes = (self.directory / "ip").read_text()
self.assertIn("via 10.0.0.1 dev pppoe-wan onlink table 210", routes)
self.assertIn("priority 104 iif lo to 193.233.82.38 table 210", routes)
self.assertIn("unreachable default metric 42760 table 210", routes)
self.assertFalse((self.directory / "dns").exists(), "an IP pin does not need DNS")
def test_busybox_large_table_failure_is_detected_before_route_mutation(self):
self.config(vps_host="193.233.82.38")
result = self.run_shell("WAN_TABLE=20110; wan_preflight")
self.assertNotEqual(result.returncode, 0)
self.assertIn("invalid argument '20110' to 'table'", result.stderr)
self.assertNotIn("route replace", (self.directory / "ip").read_text())
self.assertFalse((self.directory / "nft").exists())
result = self.run_shell("wan_prepare")
self.assertEqual(result.returncode, 0, result.stderr)
def test_foreign_table_or_priority_is_preserved_on_failure_and_cleanup(self):
self.config(vps_host="193.233.82.38")
for conflict in ("rule", "priority", "route"):
result = self.run_shell("wan_prepare", TABLE_CONFLICT=conflict)
self.assertNotEqual(result.returncode, 0)
self.assertIn("WAN IPv4 table 210", result.stderr)
self.assertNotIn("route replace", (self.directory / "ip").read_text())
nft_log = self.directory / "nft"
self.assertNotIn("-f", nft_log.read_text() if nft_log.exists() else "")
result = self.run_shell("wan_cleanup", TABLE_CONFLICT=conflict)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("route flush", (self.directory / "ip").read_text())
def test_cleanup_removes_routes_owned_during_partial_prepare_failure(self):
self.config(vps_host="193.233.82.38")
(self.directory / "legacy-nft").write_text("meta mark set 0x40000000\n")
result = self.run_shell("wan_prepare", NFT_FAIL="1")
self.assertNotEqual(result.returncode, 0)
result = self.run_shell("wan_cleanup")
self.assertEqual(result.returncode, 0, result.stderr)
routes = (self.directory / "ip").read_text()
self.assertIn("-4 route flush table 210", routes)
self.assertIn("-6 route flush table 210", routes)
self.assertFalse((self.directory / "owrt-remote-wan/route-owner-4").exists())
def test_cleanup_preserves_foreign_rule_with_different_mark_mask(self):
self.config(vps_host="193.233.82.38")
foreign = "104: from all fwmark 0x40000000/0x40000000 lookup 210\n"
(self.directory / "rules-4").write_text(foreign)
result = self.run_shell("wan_prepare")
self.assertNotEqual(result.returncode, 0)
result = self.run_shell("wan_cleanup")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.directory / "rules-4").read_text(), foreign)
log = (self.directory / "ip").read_text()
self.assertNotIn("rule del", log)
self.assertNotIn("route flush", log)
def test_ipv4_prepares_with_disabled_ipv6_and_missing_iproute2_table(self):
self.config(vps_host="193.233.82.38")
result = self.run_shell("wan_prepare", IPV6_DISABLED="1", TABLE_MISSING="1")
self.assertEqual(result.returncode, 0, result.stderr)
routes = (self.directory / "ip").read_text()
self.assertIn("-4 route replace default", routes)
self.assertNotIn("-6 route replace", routes)
def test_curl_preserves_https_hostname_and_uses_pinned_ip(self):
self.config(vps_host="193.233.82.38", vps_host_mode="manual")
result = self.run_shell('wan_prepare && wan_post_json https://hub.example/api/heartbeat test-token "$TEST_ROOT/payload"')
self.assertEqual(result.returncode, 0, result.stderr)
args = (self.directory / "curl").read_text()
self.assertIn("<hub.example:443:193.233.82.38>", args)
self.assertIn("<pppoe-wan>", args)
self.assertIn("<https://hub.example/api/heartbeat>", args)
self.assertNotIn("<-k>", args)
self.assertIn("<--max-time>\n<10>", args)
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")
result = self.run_shell('wan_endpoint_ip http://192.0.2.5:8088/api/heartbeat')
self.assertEqual(result.stdout, "192.0.2.5")
def test_wan_refresh_does_not_accumulate_policy_rules(self):
self.config(vps_host="193.233.82.38", hub_url="https://hub.example")
result = self.run_shell('wan_prepare && wan_prepare && wan_prepare')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.directory / "ip").read_text().count("rule add"), 2)
def test_migration_passes_original_podkop_diagnostic_and_keeps_foreign_warnings(self):
self.config(vps_host="193.233.82.38", wan_direct="1")
legacy = self.directory / "legacy-nft"
legacy.write_text("meta mark set 0x40000000\n")
(self.directory / "rules-4").write_text("104: from all fwmark 0x40000000 lookup 210\n105: from all fwmark 0x100000/0x100000 lookup podkop\n")
# Execute upstream's unmodified diagnostic logic; only isolate its temp path.
diagnostic = (ROOT / "tests/fixtures/podkop-0.7.22-check-nft.sh").read_text().replace("/tmp/podkop_mark_check", '"$TEST_ROOT"/podkop_mark_check')
setup = diagnostic + '\nNFT_TABLE_NAME=PodkopTable; jq() { cat; }; sleep() { :; }\n'
result = self.run_shell(setup + 'check_nft_rules; wan_prepare || exit; check_nft_rules')
self.assertEqual(result.returncode, 0, result.stderr)
before, after = [json.loads(line) for line in result.stdout.splitlines()]
self.assertEqual(before["rules_other_mark_exist"], 1)
self.assertEqual(after["rules_other_mark_exist"], 0)
self.assertTrue(all(value == 1 for key, value in after.items() if key != "rules_other_mark_exist"))
self.assertFalse(legacy.exists())
rules = (self.directory / "rules-4").read_text()
self.assertNotIn("0x40000000", rules)
self.assertIn("105: from all fwmark 0x100000/0x100000 lookup podkop", rules)
(self.directory / "foreign-nft").write_text("meta mark set 0x10\n")
result = self.run_shell(setup + 'wan_prepare || exit; check_nft_rules')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout)["rules_other_mark_exist"], 1)
self.assertTrue((self.directory / "foreign-nft").exists())
def test_changed_hub_keeps_running_xray_destination_and_prunes_stale_http_ip(self):
config = self.directory / "xray.json"
config.write_text(json.dumps({"outbounds": [{"tag": "vps-interconn", "settings": {"address": "193.233.82.38"}}]}))
self.config(vps_host="192.0.2.2", public_url="https://192.0.2.3:9443", xray_config=config.as_posix())
(self.directory / "rules-4").write_text("104: from all to 192.0.2.99 iif lo lookup 210\n")
result = self.run_shell('wan_prepare')
self.assertEqual(result.returncode, 0, result.stderr)
rules = (self.directory / "rules-4").read_text()
self.assertIn("193.233.82.38 iif lo", rules)
self.assertIn("192.0.2.2 iif lo", rules)
self.assertIn("192.0.2.3 iif lo", rules)
self.assertNotIn("192.0.2.99", rules)
self.assertIn("192.0.2.3 9443", (self.directory / "owrt-remote-wan/endpoints").read_text())
config.write_text(json.dumps({"outbounds": [{"tag": "vps-interconn", "settings": {"address": "192.0.2.2"}}]}))
result = self.run_shell('wan_prepare && wan_cleanup')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.directory / "rules-4").read_text(), "")
def test_ipv6_compression_does_not_duplicate_rules(self):
self.config(vps_host="2001:0db8:0:0:0:0:0:1", wan_dns="2001:4860:4860::8888")
result = self.run_shell('wan_prepare && wan_prepare; wan_address_key ::1; wan_address_key 2001:db8::; wan_address_key ::')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.splitlines(), ["0:0:0:0:0:0:0:1", "2001:db8:0:0:0:0:0:0", "0:0:0:0:0:0:0:0"])
rules = (self.directory / "rules-6").read_text().splitlines()
self.assertEqual(len(rules), 2)
self.assertEqual((self.directory / "ip").read_text().count("rule add"), 2)
def test_failed_replacement_retains_previous_direct_destination(self):
self.config(vps_host="192.0.2.2")
(self.directory / "rules-4").write_text("104: from all to 192.0.2.1 iif lo lookup 210\n")
result = self.run_shell('wan_prepare', RULE_ADD_FAIL="192.0.2.2")
self.assertNotEqual(result.returncode, 0)
self.assertIn("192.0.2.1 iif lo", (self.directory / "rules-4").read_text())
self.assertFalse((self.directory / "owrt-remote-wan/lock").exists())
def test_dns_failure_does_not_fall_back_to_system_resolver(self):
self.config(vps_host="hub.example")
result = self.run_shell('wan_resolve_host hub.example', DNS_FAIL="1")
self.assertNotEqual(result.returncode, 0)
self.assertEqual((self.directory / "dns").read_text().count("nslookup"), 0)
self.assertIn("hub.example 1.1.1.1", (self.directory / "dns").read_text())
def test_wan_dns_ignores_local_fakeip_and_uses_uplink_resolver(self):
self.config(vps_host="hub.example", wan_dns="9.9.9.9")
result = self.run_shell('wan_prepare; wan_resolve_host hub.example')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "193.233.82.38")
self.assertIn("hub.example 9.9.9.9", (self.directory / "dns").read_text())
result = self.run_shell('rm -f "$WAN_STATE"/resolve-*; wan_resolve_host hub.example', DNS_ANSWER="198.18.1.5")
self.assertNotEqual(result.returncode, 0)
def test_wan_prepare_fails_without_wan_and_releases_lock_on_failure(self):
self.config(vps_host="193.233.82.38")
(self.directory / "legacy-nft").write_text("meta mark set 0x40000000\n")
for env in ({"WAN_DOWN": "1"}, {"NFT_FAIL": "1"}):
result = self.run_shell("wan_prepare", **env)
self.assertNotEqual(result.returncode, 0)
self.assertFalse((self.directory / "owrt-remote-wan/lock").exists())
def test_xray_only_reverse_sockets_are_bound_to_wan(self):
self.config(vps_host="193.233.82.38", wan_direct="1", vless_uuid="test-uuid")
result = self.run_shell("render_client_config --stdout")
self.assertEqual(result.returncode, 0, result.stderr)
config = json.loads(result.stdout)
for outbound in config["outbounds"]:
if outbound["tag"].startswith("vps-"):
self.assertEqual(outbound["streamSettings"]["sockopt"], {"mark": 2097152, "interface": "pppoe-wan"})
self.assertEqual(outbound["settings"]["address"], "193.233.82.38")
else:
self.assertNotIn("streamSettings", outbound)
def test_hub_ui_change_restores_previous_host_if_render_fails(self):
self.config(vps_host="193.233.82.38", vps_host_mode="manual")
result = self.run_shell(hub.make_router_vps_host_script("hub.example", "auto"), RENDER_FAIL="1")
self.assertNotEqual(result.returncode, 0)
config = (self.directory / "uci").read_text()
self.assertIn("vps_host=193.233.82.38", config)
self.assertIn("vps_host_mode=manual", config)
def test_cgi_saves_manual_auto_and_wan_flags_without_exposing_secrets(self):
cgi = (ROOT / "files/www/cgi-bin/owrt-remote").read_text(encoding="utf-8").split('\nread_request\n')[0]
self.config(vps_host="193.233.82.38", vps_host_mode="auto")
commands = cgi + '''
param() {
case "$1" in
vps_host) echo 193.233.82.38 ;;
wan_interface) echo wan ;;
*) printf '' ;;
esac
}
has_param() { [ "$1" = wan_direct ]; }
save_config
printf '%s %s' "$(uci_get vps_host_mode '')" "$(uci_get wan_direct '')"
has_param() { [ "$1" = vps_host_auto ]; }
save_config
printf ' %s %s' "$(uci_get vps_host_mode '')" "$(uci_get wan_direct '')"
'''
result = self.run_shell(commands)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "manual 1 auto 0")
if __name__ == "__main__":
unittest.main()
+96
View File
@@ -0,0 +1,96 @@
// Run after: python tests/test_recaptcha.py --export-js .test-output/recaptcha
// node tests/test_host_policy_ui.cjs .test-output/recaptcha/dashboard.js
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(process.argv[2], 'utf8').replace(/\r\n/g, '\n');
const begin = source.indexOf('const vpsHostDrafts = new Map();');
const end = source.indexOf('\nfunction renderRouterNotesPanel(', begin);
const handlersBegin = source.indexOf("cards.addEventListener('input', (ev) => {\n const field = ev.target.closest('[data-vps-field]');");
const handlersEnd = source.indexOf("\ncards.addEventListener('click', async (ev) => {\n const pickerToggle", handlersBegin);
assert(begin >= 0 && end > begin && handlersBegin > 0 && handlersEnd > handlersBegin);
const handlers = {};
let renders = 0, request;
const router = {id: 'test', online: true, permissions: {owner: true}, status: {vps_host: '193.233.82.38', vps_host_mode: 'manual'}};
const context = {
escapeHtml: value => String(value).replace(/[<>&"']/g, ch => ({'<':'&lt;', '>':'&gt;', '&':'&amp;', '"':'&quot;', "'":'&#39;'}[ch])),
escapeAttr: value => String(value).replace(/"/g, '&quot;'),
cards: {addEventListener(kind, handler) { handlers[kind] = handler; }},
selectedRouter() { return router; },
requestRouterRender() { renders++; },
replaceRouterInList(next) { Object.assign(router, next); },
async fetch(url, options) {
request = {url, payload: JSON.parse(options.body)};
return {ok: true, async json() { return {ok: true, router: {...router, status: {vps_host: request.payload.vps_host, vps_host_mode: request.payload.vps_host_mode}}}; }};
},
};
vm.createContext(context);
vm.runInContext(source.slice(begin, end) + '\n' + source.slice(handlersBegin, handlersEnd), context);
const eventFor = (selector, node) => ({target: {closest(wanted) { return wanted === selector ? node : null; }}});
(async () => {
assert.equal(context.renderVpsHostSettings({...router, permissions: {manage: true}}), '', 'owner permission is required');
const state = context.getVpsHostDraft(router);
await handlers.click(eventFor('[data-vps-toggle]', {dataset: {vpsToggle: 'test'}}));
assert.equal(state.open, true);
handlers.input(eventFor('[data-vps-field]', {dataset: {vpsRouter: 'test', vpsField: 'host'}, type: 'text', value: '192.0.2.8'}));
handlers.input(eventFor('[data-vps-field]', {dataset: {vpsRouter: 'test', vpsField: 'auto'}, type: 'checkbox', checked: true}));
handlers.input(eventFor('[data-vps-field]', {dataset: {vpsRouter: 'test', vpsField: 'password'}, type: 'password', value: 'test-password'}));
context.renderVpsHostSettings(router); // simulate polling refresh
assert.equal(state.host, '192.0.2.8');
assert.equal(state.auto, true);
assert.equal(state.open, true);
await handlers.click(eventFor('[data-vps-save]', {dataset: {vpsSave: 'test'}}));
assert.equal(request.url, '/api/router/test/vps-host');
assert.equal(request.payload.vps_host_mode, 'auto');
assert.equal(request.payload.vps_host, '192.0.2.8');
assert.equal(state.password, '');
assert.equal(state.dirty, false);
assert.equal(state.saving, false);
context.fetch = async () => ({ok: false, async json() { return {error: 'SSH failed'}; }});
state.dirty = true;
state.password = 'test-password';
await handlers.click(eventFor('[data-vps-save]', {dataset: {vpsSave: 'test'}}));
assert.equal(state.message, 'SSH failed');
assert.equal(state.dirty, true);
assert.equal(state.password, '');
assert.equal(state.saving, false);
assert(renders > 0);
console.log('HOST_POLICY_UI_OK: owner access, draft persistence, explicit apply, remote failure and password clearing');
// Exercise the active card renderer: hidden controls must not return on polling.
const renderBegin = source.indexOf('render = function(list) {');
const renderEnd = source.indexOf('\nfunction renderRouterView()', renderBegin);
assert(renderBegin >= 0 && renderEnd > renderBegin);
const identity = value => String(value ?? '');
const empty = () => '';
Object.assign(context, {
syncRouterNotesState: empty, syncExpandedActionPanels: empty,
groupName: () => 'Без группы', metricPlaceholder: identity, duration: identity,
formatLoad: identity, formatMemory: identity, flashValueForRouter: empty,
formatFlash: identity, temperatureValueForRouter: empty, routerSupportsWol: () => false,
getWolState: () => ({open: false}), getTrafficState: () => ({open: false}),
routerNotesPreview: empty, actionPanelId: id => 'actions-' + id,
expandedActionPanels: new Set(), expandedCardDetails: new Set(),
expandedGroupPickers: new Set(), openRouterGroups: new Set(['__ungrouped__']),
mobileCardsMq: {matches: false}, authIsOwner: () => true, groupPickerButtonsHtml: empty,
renderModelMetric: empty, modelGetsLegendBadge: () => false, metric: empty,
statusRu: identity, ago: empty, metricHtml: empty, formatMemoryHtml: empty,
memoryClass: empty, formatFlashHtml: empty, flashClass: empty,
formatTemperatureHtml: empty, tempClass: empty, syncActionToggleStates: empty,
});
vm.runInContext(source.slice(renderBegin, renderEnd), context);
for (const mobile of [false, true]) {
context.mobileCardsMq.matches = mobile;
for (const expanded of [false, true]) {
context.expandedCardDetails.clear();
if (expanded) context.expandedCardDetails.add('router-details-test');
for (let refresh = 0; refresh < 3; refresh++) {
context.render([{...router, name: 'Test router', online: true}]);
assert(!/data-vps-(toggle|field|save)/.test(context.cards.innerHTML));
assert(!context.cards.innerHTML.includes('Настроить VPS host'));
assert(context.cards.innerHTML.includes('Test router'));
}
}
}
console.log('VPS_HOST_CONTROLS_HIDDEN_OK: desktop, mobile, expanded cards and polling');
})().catch(error => { console.error(error); process.exitCode = 1; });
+1 -1
View File
@@ -131,7 +131,7 @@ class HubFixture:
assert "groups" in json.loads(self.request("/api/router-groups"))
assert "notifications" in json.loads(self.request("/api/notifications"))
assert self.request("/access/test-router/") == b"router proxy fixture"
assert b"v110" in self.request("/")
assert b"v111" in self.request("/")
self.app.snapshot_router_states()
def __exit__(self, *args):
+2
View File
@@ -19,6 +19,8 @@ if [ -x "$(target_path etc/init.d/owrt-remote)" ]; then
fi
rmf usr/sbin/owrt-remote
rmf usr/lib/owrt-remote/wan.sh
rmdir "$(target_path usr/lib/owrt-remote)" 2>/dev/null || true
rmf etc/init.d/owrt-remote
rmf www/cgi-bin/owrt-remote
rmf usr/lib/lua/luci/controller/owrt_remote.lua
+258
View File
@@ -0,0 +1,258 @@
param(
[Parameter(Mandatory = $true)][ValidateSet('Router', 'Vps')][string]$Target,
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Machine,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[string]$PinnedVpsHost = '193.233.82.38',
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$WanInterface = 'wan',
[switch]$PreserveConnectionSettings,
[ValidatePattern('^[a-zA-Z0-9_-]+$')][string]$BackupName = 'host-policy-v111',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-host-policy-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$Payloads = @{}
if ($PinnedVpsHost -notmatch '^[a-zA-Z0-9][a-zA-Z0-9.:-]*$') { throw 'Invalid VPS host. Use an IP or domain without URL or port.' }
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'
'init' = 'files\etc\init.d\owrt-remote'
}
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup=/root/owrt-remote-backup-before-__BACKUP_NAME__
config=/etc/config/owrtremote
changed=0
save_files() {
dir=$1
mkdir -p "$dir"
chmod 700 "$dir"
cp -p "$config" "$dir/config"
for item in agent wan.sh cgi luci init; do
case "$item" in
agent) path=/usr/sbin/owrt-remote ;;
wan.sh) path=/usr/lib/owrt-remote/wan.sh ;;
cgi) path=/www/cgi-bin/owrt-remote ;;
luci) path=/www/luci-static/resources/view/owrt_remote.js ;;
init) path=/etc/init.d/owrt-remote ;;
esac
if [ -f "$path" ]; then cp -p "$path" "$dir/$item"; else touch "$dir/$item.absent"; fi
done
xray_config=$(uci -q get owrtremote.main.xray_config || echo /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
/usr/sbin/owrt-remote wan-cleanup >/dev/null 2>&1 || true
cp -p "$dir/config" "$config"
for item in agent wan.sh cgi luci init; do
case "$item" in
agent) path=/usr/sbin/owrt-remote ;;
wan.sh) path=/usr/lib/owrt-remote/wan.sh ;;
cgi) path=/www/cgi-bin/owrt-remote ;;
luci) path=/www/luci-static/resources/view/owrt_remote.js ;;
init) path=/etc/init.d/owrt-remote ;;
esac
if [ -f "$dir/$item.absent" ]; then rm -f "$path"; else cp -p "$dir/$item" "$path"; fi
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 this attempt.' >&2
logread -e owrt-remote | tail -n 25 >&2 || true
restore_files "$stage/previous" || true
fi
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$config"
if [ '__ACTION__' = Install ]; then
for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done
test -s "$stage/luci"
for item in cgi luci; do grep -F -q 'v111' "$stage/$item"; done
# curl is needed to preserve HTTPS SNI and bypass the local DNS/proxy.
if ! command -v curl >/dev/null 2>&1; then
if command -v opkg >/dev/null 2>&1; then opkg update && opkg install curl ca-bundle
elif command -v apk >/dev/null 2>&1; then apk add curl ca-certificates
else echo 'Install curl and CA certificates first.' >&2; exit 1; fi
fi
for tool in ip nft ubus jsonfilter nslookup curl; do command -v "$tool" >/dev/null 2>&1 || { echo "Missing tool: $tool" >&2; exit 1; }; done
# Check the router's real ip implementation and WAN before stopping Remote.
if [ '__PRESERVE_CONNECTION__' = 1 ]; then
expected_host=$(uci -q get owrtremote.main.vps_host)
expected_mode=$(uci -q get owrtremote.main.vps_host_mode || echo manual)
expected_direct=$(uci -q get owrtremote.main.wan_direct || echo 0)
if [ "$expected_direct" = 1 ]; then OWRT_REMOTE_WAN_HELPER="$stage/wan.sh" sh "$stage/agent" wan-preflight; fi
else
expected_host='__PINNED_HOST__'
expected_mode=manual
expected_direct=1
OWRT_REMOTE_WAN_HELPER="$stage/wan.sh" OWRT_REMOTE_WAN_INTERFACE='__WAN_INTERFACE__' sh "$stage/agent" wan-preflight
fi
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
# procd may already have no instance after a previous failed installation.
/etc/init.d/owrt-remote stop || true
mkdir -p /usr/lib/owrt-remote /www/luci-static/resources/view
for item in agent wan.sh cgi luci init; do
case "$item" in
agent) path=/usr/sbin/owrt-remote; mode=755 ;;
wan.sh) path=/usr/lib/owrt-remote/wan.sh; mode=644 ;;
cgi) path=/www/cgi-bin/owrt-remote; mode=755 ;;
luci) path=/www/luci-static/resources/view/owrt_remote.js; mode=644 ;;
init) path=/etc/init.d/owrt-remote; mode=755 ;;
esac
cp "$stage/$item" "$path.new"
chmod "$mode" "$path.new"
mv "$path.new" "$path"
done
if [ '__PRESERVE_CONNECTION__' != 1 ]; then
uci set 'owrtremote.main.vps_host=__PINNED_HOST__'
uci set owrtremote.main.vps_host_mode=manual
uci set owrtremote.main.wan_direct=1
uci set 'owrtremote.main.wan_interface=__WAN_INTERFACE__'
uci commit owrtremote
fi
/usr/sbin/owrt-remote render-client >/dev/null
/etc/init.d/owrt-remote restart
ready=0
for attempt in 1 2 3 4 5 6 7 8 9 10; do
if /usr/sbin/owrt-remote status | grep -q '^xray_state: running'; then ready=1; break; fi
sleep 2
done
test "$ready" = 1
/usr/sbin/owrt-remote heartbeat
if [ "$expected_mode" = manual ]; then test "$(uci -q get owrtremote.main.vps_host)" = "$expected_host"; fi
test "$(uci -q get owrtremote.main.vps_host_mode || echo manual)" = "$expected_mode"
test "$(uci -q get owrtremote.main.wan_direct || echo 0)" = "$expected_direct"
if nft list table inet owrt_remote_wan >/dev/null 2>&1; then
echo 'Legacy Remote marking table still exists.' >&2
exit 1
fi
/usr/sbin/owrt-remote status
grep -F -q 'v111' /www/cgi-bin/owrt-remote
grep -F -q 'v111' /www/luci-static/resources/view/owrt_remote.js
echo HOST_POLICY_ROUTER_V111_OK
else
test -f "$backup/complete"
save_files "$stage/previous"
changed=1
restore_files "$backup"
/usr/sbin/owrt-remote status
echo HOST_POLICY_ROUTER_V111_ROLLBACK_OK
fi
'@
} else {
$Payloads = @{
'hub.py' = 'vps\owrt-remote-hub.py'
'test_host_policy.py' = 'tests\test_host_policy.py'
'resources.py' = 'tests\test_resource_lifecycle.py'
'recaptcha.py' = 'tests\test_recaptcha.py'
}
$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-host-policy-v111
changed=0
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
echo 'Operation failed; restoring this attempt.' >&2
journalctl -u owrt-remote -n 30 --no-pager >&2 || true
cp -p "$stage/previous.py" "$target.new"
mv "$target.new" "$target"
systemctl restart owrt-remote || true
fi
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 'v111' "$stage/hub.py"
"$python_bin" -m py_compile "$stage/hub.py"
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/test_host_policy.py" HostPolicyTests -v
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" -v
OWRT_RECAPTCHA_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/recaptcha.py" -v
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
test -s "$backup"
candidate="$stage/hub.py"
else
test -s "$backup"
"$python_bin" -m py_compile "$backup"
candidate="$backup"
fi
cp -p "$target" "$stage/previous.py"
cp "$candidate" "$target.new"
chmod 755 "$target.new"
changed=1
mv "$target.new" "$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 "$candidate" "$target"
printf '\nHOST_POLICY_VPS_V111_%s_OK\n' '__ACTION__'
'@
}
$PreserveValue = if ($PreserveConnectionSettings) { '1' } else { '0' }
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace('__PINNED_HOST__', $PinnedVpsHost).Replace('__WAN_INTERFACE__', $WanInterface).Replace('__PRESERVE_CONNECTION__', $PreserveValue).Replace('__BACKUP_NAME__', $BackupName)
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()) {
$Source = Join-Path $RepoRoot $Item.Value
$Content = [System.IO.File]::ReadAllText($Source).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. The 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 "$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 }
}
}
+6 -6
View File
@@ -17,8 +17,8 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v110
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v111
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v111.json
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source)
assert 'v110' in source
assert 'v111' in source
assert 'v108' not in source
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
assert 'prepareLoginRecaptcha' in source
@@ -88,7 +88,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RECAPTCHA_V3_V110_OK
echo RECAPTCHA_V3_V111_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -96,8 +96,8 @@ echo RECAPTCHA_V3_V110_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v110
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v111
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v111.json
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
restore_captcha() {
+4 -4
View File
@@ -18,7 +18,7 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v111
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source)
assert 'v110' in source
assert 'v111' in source
assert 'v108' not in source
factory = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'connect')
assert any(isinstance(item, ast.Name) and item.id == 'contextmanager' for item in factory.decorator_list)
@@ -78,7 +78,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RESOURCE_FIX_V110_OK
echo RESOURCE_FIX_V111_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V110_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v111
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
cleanup() {
+189 -11
View File
@@ -12,6 +12,7 @@ import hmac
import hashlib
import html
import http.client
import ipaddress
import json
import math
import os
@@ -1364,6 +1365,70 @@ def row_int_value(row, key, default=0):
return int(default)
def router_reported_connection(router, *, legacy_mode="auto"):
row = dict(router or {})
status = row.get("status")
if not isinstance(status, dict):
try:
status = json.loads(row.get("status_json") or "{}")
except (ValueError, TypeError):
status = {}
if not isinstance(status, dict):
status = {}
# Legacy agents had automatic endpoint updates. Keep that server behavior
# 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")
host = str(status.get("vps_host") or row.get("vps_host") or "").strip()
return mode, host
def validate_router_vps_host(value):
host = str(value or "").strip()
try:
return str(ipaddress.ip_address(host))
except ValueError:
pass
if re.fullmatch(r"[0-9.]+", host):
raise ValueError("Некорректный IP-адрес VPS host")
if len(host) > 253 or not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?", host):
raise ValueError("VPS host должен быть IP-адресом или доменом без URL и порта")
if any(not label or len(label) > 63 or label.startswith("-") or label.endswith("-") for label in host.split(".")):
raise ValueError("Некорректный домен VPS host")
return host.lower()
def make_router_vps_host_script(host, mode):
host = validate_router_vps_host(host)
if mode not in ("manual", "auto"):
raise ValueError("VPS host mode должен быть manual или auto")
return f'''set -eu
owrt-remote status | grep -q '^vps_host_mode:' || {{ echo 'Сначала обнови агент на роутере' >&2; exit 1; }}
old_host="$(uci -q get owrtremote.main.vps_host || true)"
old_mode="$(uci -q get owrtremote.main.vps_host_mode || true)"
applied=0
cleanup() {{
code=$?
trap - EXIT
if [ "$applied" = 0 ]; then
uci set "owrtremote.main.vps_host=$old_host"
if [ -n "$old_mode" ]; then uci set "owrtremote.main.vps_host_mode=$old_mode"; else uci -q delete owrtremote.main.vps_host_mode || true; fi
uci commit owrtremote
owrt-remote render-client >/dev/null 2>&1 || true
fi
exit "$code"
}}
trap cleanup EXIT
uci set 'owrtremote.main.vps_host={sh_quote(host)}'
uci set 'owrtremote.main.vps_host_mode={mode}'
uci commit owrtremote
owrt-remote render-client >/dev/null
applied=1
logger -t owrt-remote "VPS host changed by Hub UI: old=$old_host new={host} mode={mode}" || true
( sleep 2; /etc/init.d/owrt-remote restart >/dev/null 2>&1 ) </dev/null >/dev/null 2>&1 &
echo VPS_HOST_APPLIED
'''
def canonical_router_hub_update(router, app_public_url="", request_origin=""):
router = router or {}
router_public_url = public_url_origin(router.get("public_url", ""))
@@ -1378,11 +1443,15 @@ def canonical_router_hub_update(router, app_public_url="", request_origin=""):
vps_host = urllib.parse.urlsplit(hub_url).hostname or ""
except Exception:
vps_host = ""
return {
update = {
"hub_url": hub_url,
"public_url": public_url,
"vps_host": vps_host,
}
# Router is authoritative for a manually fixed tunnel address. Patched
# agents also protect it locally while the Hub is still on an old version.
if router_reported_connection(router)[0] == "auto":
update["vps_host"] = vps_host
return update
def verify_password_login(username, password, otp=""):
@@ -3619,9 +3688,11 @@ def router_current_hub_bundle(router, app_public_url="", request_origin="", fall
public_url = prefer_origin_with_explicit_port(router_public_url, app_origin)
public_url = prefer_origin_with_explicit_port(public_url, request_origin)
hub_url = public_url or request_origin or router_fallback_hub_url(row, fallback_host, 8088)
reported_mode, reported_host = router_reported_connection(row)
config_vps_host = (
vps_host_name(public_url or hub_url)
(reported_host if reported_mode == "manual" else "")
or str(row.get("vps_host") or "").strip()
or vps_host_name(public_url or hub_url)
or vps_host_name(app_origin or request_origin)
or vps_host_name(router_fallback_hub_url(row, fallback_host, 8088))
or ""
@@ -4266,6 +4337,7 @@ def build_openwrt_config_payload(row, hub_url, vps_host_override="", public_url_
"role": row_str_value(row, "role", "node"),
"hub_url": str(hub_url or ""),
"vps_host": effective_vps_host,
"vps_host_mode": router_reported_connection(row, legacy_mode="manual")[0],
"vps_port": row_int_value(row, "vless_port", DEFAULT_VLESS_PORT),
"vless_uuid": row_str_value(row, "vless_uuid"),
"vless_encryption": row_str_value(row, "vless_encryption", "none"),
@@ -4288,8 +4360,9 @@ def build_openwrt_config_payload(row, hub_url, vps_host_override="", public_url_
def build_openwrt_config_lines(payload, mode="manual"):
lines = [
"uci -q delete owrtremote.main",
"uci set owrtremote.main=remote",
"owrt_saved_host=\"$(uci -q get owrtremote.main.vps_host 2>/dev/null || true)\"",
"owrt_saved_mode=\"$(uci -q get owrtremote.main.vps_host_mode 2>/dev/null || echo manual)\"",
"uci -q get owrtremote.main >/dev/null 2>&1 || uci set owrtremote.main=remote",
"uci set owrtremote.main.enabled='1'",
f"uci set owrtremote.main.router_id='{sh_quote(payload['id'])}'",
f"uci set owrtremote.main.router_name='{sh_quote(payload['name'])}'",
@@ -4299,7 +4372,12 @@ def build_openwrt_config_lines(payload, mode="manual"):
"uci set owrtremote.main.heartbeat_interval='30'",
"uci set owrtremote.main.xray_bin='/usr/bin/xray'",
"uci set owrtremote.main.xray_config='/etc/xray/owrt-remote-client.json'",
f"uci set owrtremote.main.vps_host='{sh_quote(payload['vps_host'])}'",
"if [ \"$owrt_saved_mode\" = auto ] || [ -z \"$owrt_saved_host\" ]; then",
f" uci set owrtremote.main.vps_host='{sh_quote(payload['vps_host'])}'",
f" uci set owrtremote.main.vps_host_mode='{sh_quote(payload.get('vps_host_mode', 'manual'))}'",
"else",
" uci set owrtremote.main.vps_host_mode='manual'",
"fi",
f"uci set owrtremote.main.vps_port='{payload['vps_port']}'",
f"uci set owrtremote.main.vless_uuid='{sh_quote(payload['vless_uuid'])}'",
f"uci set owrtremote.main.vless_encryption='{sh_quote(payload['vless_encryption'])}'",
@@ -4661,7 +4739,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
<div class="brand">
<div class="desktopHeader">
<div class="desktopHeaderTop">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v110</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v111</span></span></h1>
<div class="routerSearchDock" id="routerSearchDock">
<button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false">
<span>Поиск роутеров</span>
@@ -5013,7 +5091,7 @@ systemctl restart owrt-remote-xray</pre>
</div>
</div>
<div class="mobileSearchDock" id="mobileRouterSearchDock">
<span class="mobileSearchVersion">v110</span>
<span class="mobileSearchVersion">v111</span>
<button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false">
<span>Поиск роутеров</span>
</button>
@@ -5500,7 +5578,7 @@ function hasOpenWolPicker() {{
function activeWolInteractiveField() {{
const active = document.activeElement;
return active && typeof active.matches === 'function' && active.matches('[data-wol-password],[data-wol-select],[data-traffic-password],[data-router-notes-input]') ? active : null;
return active && typeof active.matches === 'function' && active.matches('[data-wol-password],[data-wol-select],[data-traffic-password],[data-router-notes-input],[data-vps-field]') ? active : null;
}}
function shouldDeferRouterRender() {{
@@ -7721,6 +7799,36 @@ function normalizeRouterName(value) {{
return String(value || '').trim().replace(/\\s+/g, ' ').slice(0, 80);
}}
const vpsHostDrafts = new Map();
function getVpsHostDraft(router) {{
if (!vpsHostDrafts.has(router.id)) {{
const status = router.status || {{}};
vpsHostDrafts.set(router.id, {{open: false, host: status.vps_host || router.vps_host || '', auto: status.vps_host_mode === 'auto', password: '', dirty: false, saving: false, message: ''}});
}}
const state = vpsHostDrafts.get(router.id);
if (!state.dirty && !state.saving) {{
state.host = (router.status || {{}}).vps_host || router.vps_host || '';
state.auto = (router.status || {{}}).vps_host_mode === 'auto';
}}
return state;
}}
function renderVpsHostSettings(router) {{
if (!(router.permissions || {{}}).owner) return '';
const state = getVpsHostDraft(router);
const key = escapeAttr(router.id);
return `<div class="wolPanel" style="margin-top:10px">
<button class="btn" type="button" data-vps-toggle="${{key}}" aria-expanded="${{state.open ? 'true' : 'false'}}">${{state.open ? 'Скрыть VPS host' : 'Настроить VPS host'}}</button>
${{state.open ? `<div style="display:grid;gap:10px;margin-top:10px;min-width:0">
<label style="display:grid;gap:5px;min-width:0">VPS host<input style="width:100%;min-width:0" data-vps-field="host" data-vps-router="${{key}}" value="${{escapeAttr(state.host)}}" placeholder="IP или домен VPS"></label>
<label style="display:flex;align-items:center;gap:8px"><input type="checkbox" data-vps-field="auto" data-vps-router="${{key}}"${{state.auto ? ' checked' : ''}}> Автоматически обновлять VPS host</label>
<label style="display:grid;gap:5px;min-width:0">Пароль SSH роутера<input style="width:100%;min-width:0" type="password" autocomplete="off" data-vps-field="password" data-vps-router="${{key}}" value="${{escapeAttr(state.password)}}" placeholder="Пусто, если доступ по ключу"></label>
<span>Выключено: heartbeat сохраняет указанный адрес. Сохранение применяется на роутере через SSH.</span>
<button class="btn" type="button" data-vps-save="${{key}}"${{state.saving || !router.online ? ' disabled' : ''}}>${{state.saving ? 'Сохраняю...' : 'Сохранить VPS host'}}</button>
<span>${{escapeHtml(state.message)}}</span>
</div>` : ''}}
</div>`;
}}
function renderRouterNotesPanel(router) {{
const permissions = router && router.permissions && typeof router.permissions === 'object' ? router.permissions : {{}};
const canEdit = Boolean(permissions.notes_edit || permissions.manage);
@@ -8536,6 +8644,46 @@ routerForm.addEventListener('submit', async (ev) => {{
cards.addEventListener('input', (ev) => {{
const field = ev.target.closest('[data-vps-field]');
if (!field) return;
const router = selectedRouter(field.dataset.vpsRouter);
if (!router) return;
const state = getVpsHostDraft(router);
state[field.dataset.vpsField] = field.type === 'checkbox' ? field.checked : field.value;
state.dirty = true;
}});
cards.addEventListener('click', async (ev) => {{
const toggle = ev.target.closest('[data-vps-toggle]');
if (toggle) {{
const router = selectedRouter(toggle.dataset.vpsToggle);
if (!router) return;
const state = getVpsHostDraft(router);
state.open = !state.open;
requestRouterRender();
return;
}}
const save = ev.target.closest('[data-vps-save]');
if (!save) return;
const key = save.dataset.vpsSave;
const router = selectedRouter(key);
if (!router) return;
const state = getVpsHostDraft(router);
if (state.saving) return;
state.saving = true;
state.message = '';
requestRouterRender();
try {{
const res = await fetch('/api/router/' + encodeURIComponent(key) + '/vps-host', {{method: 'POST', headers: {{'Content-Type': 'application/json'}}, body: JSON.stringify({{vps_host: state.host, vps_host_mode: state.auto ? 'auto' : 'manual', ssh_password: state.password}})}});
const data = await res.json();
if (!res.ok || !data.ok) throw new Error(data.error || 'Не удалось сохранить VPS host');
replaceRouterInList(data.router);
state.dirty = false;
state.message = 'Настройки сохранены на роутере.';
}} catch (error) {{ state.message = error.message; }}
finally {{ state.saving = false; state.password = ''; requestRouterRender(); }}
}});
cards.addEventListener('click', async (ev) => {{
const pickerToggle = ev.target.closest('[data-router-group-picker-toggle]');
if (pickerToggle) {{
@@ -12405,7 +12553,7 @@ button:hover{{filter:brightness(1.06)}}
<form class="login" method="post" action="/login">
{error_html}
<span class="brand">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v110</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v111</span></span></h1>
</span>
<label for="hubUsername">Логин</label>
<input id="hubUsername" name="username" autocomplete="off" autofocus required>
@@ -12877,7 +13025,7 @@ body::after{{content:"";position:fixed;inset:0;pointer-events:none;background:li
<circle cx="65" cy="59" r="3" fill="#E5F2FF"/>
</svg>
</div>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v110</span></h2>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v111</span></h2>
</div>
</div>
<div class="brandBottom">
@@ -17428,6 +17576,36 @@ exit 127
except Exception as exc:
self.send_json(400, {"ok": False, "error": str(exc)})
return
if path.startswith("/api/router/") and path.endswith("/vps-host"):
if not self.require_owner(json_mode=True):
return
try:
parts = path.strip("/").split("/")
if len(parts) != 4:
raise ValueError("Некорректный путь")
router_id = urllib.parse.unquote(parts[2])
payload = self.read_payload()
host = validate_router_vps_host(payload.get("vps_host"))
mode = str(payload.get("vps_host_mode") or "manual")
script = make_router_vps_host_script(host, mode)
with self.app.conn() as conn:
row = get_active_router(conn, router_id)
if not row:
raise ValueError("Роутер не найден")
output = self.run_router_ssh_script(row, script, timeout=35, ssh_password=payload.get("ssh_password", ""))
if "VPS_HOST_APPLIED" not in output:
raise ValueError("Роутер не подтвердил применение настройки")
with self.app.conn() as conn:
fresh = get_active_router(conn, router_id)
status = row_to_router(fresh).get("status", {})
status.update({"vps_host": host, "vps_host_mode": mode})
conn.execute("update routers set vps_host = ?, status_json = ?, updated_at = ? where id = ?", (host, json.dumps(status, ensure_ascii=False), now_ts(), router_id))
conn.commit()
router = row_to_router(get_router(conn, router_id))
self.send_json(200, {"ok": True, "router": router})
except Exception as exc:
self.send_json(400, {"ok": False, "error": str(exc)})
return
if path == "/api/router":
if not self.require_add_router(json_mode=True):
return