Fix Xray reverse access and compatible router core installation

This commit is contained in:
kzolotarev95 committed 2026-10-29 13:06:54 +04:00
1 parent 5956daa8c2
commit d7d350fd8b
14 files changed
+1135 -32

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
param(
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-compat-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$Payloads = @{
'cgi' = 'files\www\cgi-bin\owrt-remote'
'agent' = 'files\usr\sbin\owrt-remote'
}
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-xray-compat-v119
changed=0
phase=preflight
item_path() {
case "$1" in
cgi) printf /www/cgi-bin/owrt-remote ;;
agent) printf /usr/sbin/owrt-remote ;;
esac
}
complete_backup() {
[ -f "$1/complete" ] && [ -s "$1/cgi" ] && [ -s "$1/agent" ]
}
restore_files() {
local dir item path
dir=$1
complete_backup "$dir" || return 1
for item in cgi agent; do
path=$(item_path "$item")
cp -p "$dir/$item" "$path.new-__UPLOAD_NAME__" || return 1
mv -f "$path.new-__UPLOAD_NAME__" "$path" || return 1
done
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
if [ "$changed" = 1 ]; then
echo 'Restoring the agent and CGI from this attempt.' >&2
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
fi
fi
for item in cgi agent; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
trap 'exit 1' INT TERM
for item in cgi agent; do
path=$(item_path "$item")
test -s "$path"
done
if [ '__ACTION__' = Install ]; then
for item in cgi agent; do test -s "$stage/$item"; sh -n "$stage/$item"; done
grep -F -q 'xray_validate_transport_binary()' "$stage/agent"
grep -F -q '26.6.27' "$stage/agent"
grep -F -q 'OWRT_REMOTE_APPLY_TRACE' "$stage/cgi"
if [ ! -e "$backup_dir" ]; then
mkdir -p "$stage/retained-backup"
chmod 700 "$stage/retained-backup"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/retained-backup/$item"; done
touch "$stage/retained-backup/complete"
mv "$stage/retained-backup" "$backup_dir"
fi
complete_backup "$backup_dir" || { echo "Incomplete backup: $backup_dir. Nothing changed." >&2; exit 1; }
source_dir=$stage
else
complete_backup "$backup_dir" || { echo "No complete backup: $backup_dir. Nothing changed." >&2; exit 1; }
for item in cgi agent; do sh -n "$backup_dir/$item"; done
source_dir=$backup_dir
fi
printf 'Backup: %s\n' "$backup_dir"
mkdir -p "$stage/previous"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
touch "$stage/previous/complete"
phase=install
changed=1
for item in cgi agent; do
path=$(item_path "$item")
cp "$source_dir/$item" "$path.new-__UPLOAD_NAME__"
chmod 755 "$path.new-__UPLOAD_NAME__"
mv -f "$path.new-__UPLOAD_NAME__" "$path"
done
phase=verify
for item in cgi agent; do
path=$(item_path "$item")
sh -n "$path"
cmp "$source_dir/$item" "$path"
done
if [ '__ACTION__' = Install ]; then
phase=prepare-compatible-xray
# Replaces a known incompatible core, or restores/downloads a validated
# compatible one. Does not render JSON or restart an existing tunnel.
/usr/sbin/owrt-remote prepare-xray
fi
# Rollback restores agent/CGI code only; retain the validated compatible core,
# its boot cache, and all router settings. Never remove a working executable.
printf '\nXRAY_COMPAT_ROUTER_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
foreach ($Item in $Payloads.GetEnumerator()) {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -r -- $StageRoot "${Router}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Xray compatibility fix $Action finished successfully."
} finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+165
View File
@@ -0,0 +1,165 @@
param(
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-reverse-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$Payloads = @{
'cgi' = 'files\www\cgi-bin\owrt-remote'
'agent' = 'files\usr\sbin\owrt-remote'
}
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-xray-reverse-v119
changed=0
restart_attempted=0
phase=preflight
config=$(uci -q get owrtremote.main.xray_config || true)
[ -n "$config" ] || config=/etc/xray/owrt-remote-client.json
case "$config" in /*) ;; *) echo 'xray_config must be absolute.' >&2; exit 1 ;; esac
item_path() {
case "$1" in
cgi) printf /www/cgi-bin/owrt-remote ;;
agent) printf /usr/sbin/owrt-remote ;;
esac
}
complete_backup() {
[ -f "$1/complete" ] && [ -s "$1/cgi" ] && [ -s "$1/agent" ] &&
[ -s "$1/config-path" ] && { [ -s "$1/config.json" ] || [ -f "$1/config-missing" ]; }
}
save_config() {
printf '%s\n' "$config" >"$1/config-path"
if [ -f "$config" ]; then cp -p "$config" "$1/config.json"; else touch "$1/config-missing"; fi
}
restore_config() {
[ "$(cat "$1/config-path")" = "$config" ] || return 1
if [ -f "$1/config-missing" ]; then
rm -f "$config"
else
cp -p "$1/config.json" "$config.new-__UPLOAD_NAME__" || return 1
mv -f "$config.new-__UPLOAD_NAME__" "$config" || return 1
fi
}
restore_files() {
local dir item path
dir=$1
complete_backup "$dir" || return 1
for item in cgi agent; do
path=$(item_path "$item")
cp -p "$dir/$item" "$path.new-__UPLOAD_NAME__" || return 1
mv -f "$path.new-__UPLOAD_NAME__" "$path" || return 1
done
restore_config "$dir"
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
if [ "$changed" = 1 ]; then
echo 'Restoring the agent and CGI from this attempt.' >&2
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
if [ "$restart_attempted" = 1 ] && [ -s "$config" ]; then /etc/init.d/owrt-remote restart >&2 || true; fi
fi
fi
for item in cgi agent; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
rm -f "$config.new-__UPLOAD_NAME__"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
trap 'exit 1' INT TERM
for item in cgi agent; do
path=$(item_path "$item")
test -s "$path"
done
if [ '__ACTION__' = Install ]; then
for item in cgi agent; do test -s "$stage/$item"; sh -n "$stage/$item"; done
grep -F -q 'xray_validate_transport_binary()' "$stage/agent"
grep -F -q '26.6.27' "$stage/agent"
grep -F -q '"finalRules"' "$stage/agent"
grep -F -q 'OWRT_REMOTE_APPLY_TRACE' "$stage/cgi"
if [ ! -e "$backup_dir" ]; then
mkdir -p "$stage/retained-backup"
chmod 700 "$stage/retained-backup"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/retained-backup/$item"; done
save_config "$stage/retained-backup"
touch "$stage/retained-backup/complete"
mv "$stage/retained-backup" "$backup_dir"
fi
complete_backup "$backup_dir" || { echo "Incomplete backup: $backup_dir. Nothing changed." >&2; exit 1; }
source_dir=$stage
else
complete_backup "$backup_dir" || { echo "No complete backup: $backup_dir. Nothing changed." >&2; exit 1; }
[ "$(cat "$backup_dir/config-path")" = "$config" ] || { echo 'xray_config changed since backup. Nothing changed.' >&2; exit 1; }
for item in cgi agent; do sh -n "$backup_dir/$item"; done
source_dir=$backup_dir
fi
printf 'Backup: %s\n' "$backup_dir"
mkdir -p "$stage/previous"
chmod 700 "$stage/previous"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
save_config "$stage/previous"
touch "$stage/previous/complete"
phase=install
changed=1
for item in cgi agent; do
path=$(item_path "$item")
cp "$source_dir/$item" "$path.new-__UPLOAD_NAME__"
chmod 755 "$path.new-__UPLOAD_NAME__"
mv -f "$path.new-__UPLOAD_NAME__" "$path"
done
phase=verify
for item in cgi agent; do
path=$(item_path "$item")
sh -n "$path"
cmp "$source_dir/$item" "$path"
done
if [ '__ACTION__' = Install ]; then
phase=validate-client-config
# render-client validates the candidate with Xray before atomic replacement.
/usr/sbin/owrt-remote render-client
grep -F -q '"finalRules"' "$config"
else
phase=restore-client-config
restore_config "$backup_dir"
fi
phase=restart-tunnel
restart_attempted=1
/etc/init.d/owrt-remote restart
# Keep the compatible core and its boot cache on rollback; restore the saved
# agent, CGI and JSON. The VPS server binary does not need a downgrade.
printf '\nXRAY_REVERSE_ROUTER_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
foreach ($Item in $Payloads.GetEnumerator()) {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -r -- $StageRoot "${Router}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Xray reverse fix $Action finished successfully."
} finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+178
View File
@@ -0,0 +1,178 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-reverse-vps-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-xray-reverse-v119
candidate=$target.new-__UPLOAD_NAME__
changed=0
show_failure() {
echo '--- owrt-remote status ---' >&2
systemctl --no-pager -l status owrt-remote >&2 || true
echo '--- owrt-remote journal ---' >&2
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
echo "Remote step failed with rc=$code" >&2
show_failure
fi
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
echo 'Restoring the previous Hub file...' >&2
cp -p "$stage/previous.py" "$candidate"
mv -f "$candidate" "$target"
systemctl restart owrt-remote || true
fi
rm -f "$candidate"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
test -s "$stage/hub.py"
echo 'Validating candidate...'
"$python_bin" -m py_compile "$stage/hub.py"
"$python_bin" - "$stage/hub.py" <<'PY'
from pathlib import Path
import sys
source = Path(sys.argv[1]).read_text(encoding='utf-8')
required = (
'"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["admin_port"])}]',
'"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["ssh_port"] or 22)}]',
)
missing = [marker for marker in required if marker not in source]
if missing:
for marker in missing:
print('Missing marker:', repr(marker), file=sys.stderr)
raise SystemExit(1)
print('Candidate validation OK')
PY
if [ ! -e "$backup" ]; then
cp -p "$target" "$backup"
fi
source_file="$stage/hub.py"
else
test -s "$backup"
"$python_bin" -m py_compile "$backup"
source_file="$backup"
fi
expected_revision=$("$python_bin" - "$source_file" <<'PY'
import hashlib
from pathlib import Path
import sys
print(hashlib.sha256(Path(sys.argv[1]).read_bytes()).hexdigest())
PY
)
cp -p "$target" "$stage/previous.py"
cp "$source_file" "$candidate"
chmod 0755 "$candidate"
changed=1
mv -f "$candidate" "$target"
echo 'Restarting owrt-remote...'
if ! systemctl restart owrt-remote; then
show_failure
exit 1
fi
healthy=0
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
if systemctl is-active --quiet owrt-remote && "$python_bin" - "$expected_revision" > "$stage/health-check" 2>&1 <<'PY'
import json
import sys
import urllib.request
try:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open('http://127.0.0.1:8088/health?panel-update=1', timeout=3) as response:
data = json.loads(response.read(4096))
revision = data.get('revision', '')
if not data.get('ok') or revision != sys.argv[1]:
raise RuntimeError('Running Hub revision does not match the uploaded file: '
+ (revision or '(not reported)') + '; expected ' + sys.argv[1])
print('Running Hub revision verified: ' + revision)
except Exception as error:
print('Health verification failed: ' + str(error), file=sys.stderr)
raise SystemExit(1)
PY
then
healthy=1
break
fi
sleep 2
done
if [ "$healthy" -ne 1 ]; then
echo 'The uploaded Hub build did not become ready; installation was not confirmed.' >&2
cat "$stage/health-check" >&2 2>/dev/null || true
show_failure
exit 1
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
printf '\nBackup: %s\nXRAY_REVERSE_VPS_%s_OK\n' "$backup" '__ACTION__'
if [ '__ACTION__' = Install ]; then
echo 'Hub client generator updated. The router fix must also be installed.'
echo 'The VPS Xray core and running server configuration are unchanged.'
fi
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText(
(Join-Path $StageRoot 'run.sh'),
$RemoteScript.Replace("`r`n", "`n") + "`n",
$Utf8
)
if ($Action -eq 'Install') {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Content, $Utf8)
}
if ($PrepareOnly) {
Write-Host "Prepared only: $StageRoot"
return
}
& scp -O -r -- $StageRoot "${Vps}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
& ssh -T -o ConnectTimeout=10 $Vps "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Xray reverse Hub fix $Action finished successfully."
}
finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) {
throw 'Unsafe staging cleanup path.'
}
if (Test-Path -LiteralPath $Resolved) {
Remove-Item -LiteralPath $Resolved -Recurse -Force
}
}
}
+4
View File
@@ -4488,6 +4488,9 @@ def make_router_xray_config(row):
"protocol": "freedom",
"settings": {
"redirect": f"{row['admin_host']}:{int(row['admin_port'])}",
# VLESS reverse is denied by Freedom's default final rule.
# Redirect fixes the destination; allow only its TCP port.
"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["admin_port"])}],
},
},
{
@@ -4495,6 +4498,7 @@ def make_router_xray_config(row):
"protocol": "freedom",
"settings": {
"redirect": f"{row['ssh_host'] or '127.0.0.1'}:{int(row['ssh_port'] or 22)}",
"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["ssh_port"] or 22)}],
},
},
{