Release v122 with Tachyon integration and resilient Xray downloads
OpenWrt IPK and APK / Validate source and resolve stable SDKs (push) Waiting to run
OpenWrt IPK and APK / Validate source and resolve stable SDKs (push) Waiting to run
This commit is contained in:
1 parent
f4ccbf82f3
commit
70a4705e67
50 files changed
+3173
-181
No files matched your search
@@ -104,7 +104,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
command -v base64 >/dev/null
|
||||
command -v jsonfilter >/dev/null
|
||||
grep -F -q 'globalLogsToggle' "$stage/cgi"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
|
||||
grep -F -q 'log_sync_loop' "$stage/logs.sh"
|
||||
grep -F -q 'sync_global_logs' "$stage/agent"
|
||||
|
||||
@@ -57,7 +57,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
from pathlib import Path
|
||||
import sys
|
||||
source = Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
required = ('v121', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
|
||||
required = ('v122', '#routerForm select option,#routerGroupFilter option', 'background-color:#221a34', 'id="backupDownload"', 'id="backupRestore"')
|
||||
if 'class="backupCmds"' in source:
|
||||
print('Old backup command instructions remain in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -90,7 +90,7 @@ test -s "$config"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent wan.sh cgi init; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
test -s "$stage/luci"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
# curl is needed to preserve HTTPS SNI and bypass the local DNS/proxy.
|
||||
if ! command -v curl >/dev/null 2>&1; then
|
||||
if command -v opkg >/dev/null 2>&1; then opkg update && opkg install curl ca-bundle
|
||||
@@ -156,8 +156,8 @@ if [ '__ACTION__' = Install ]; then
|
||||
exit 1
|
||||
fi
|
||||
/usr/sbin/owrt-remote status
|
||||
grep -F -q 'v121' /www/cgi-bin/owrt-remote
|
||||
grep -F -q 'v121' /www/luci-static/resources/view/owrt_remote.js
|
||||
grep -F -q 'v122' /www/cgi-bin/owrt-remote
|
||||
grep -F -q 'v122' /www/luci-static/resources/view/owrt_remote.js
|
||||
echo HOST_POLICY_ROUTER_V121_OK
|
||||
else
|
||||
test -f "$backup/complete"
|
||||
@@ -200,7 +200,7 @@ test -s "$target"
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'v121' "$stage/hub.py"
|
||||
grep -F -q 'v122' "$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
|
||||
|
||||
@@ -99,7 +99,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'heartbeat_set_url_if_changed()' "$stage/agent"
|
||||
grep -F -q 'reason=https-downgrade' "$stage/agent"
|
||||
for item in agent wan.sh; do grep -F -q -- '--post301' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
if [ ! -e "$backup" ]; then
|
||||
save_files "$stage/retained-backup"
|
||||
mv "$stage/retained-backup" "$backup"
|
||||
@@ -174,7 +174,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
grep -F -q 'def router_hub_origins(' "$stage/hub.py"
|
||||
grep -F -q 'v121' "$stage/hub.py"
|
||||
grep -F -q 'v122' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_HOST_POLICY_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/host_policy.py" HostPolicyTests -v
|
||||
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" IntegrationTests -v
|
||||
|
||||
@@ -106,7 +106,7 @@ if [ '__ACTION__' = Install ]; then
|
||||
exit 1
|
||||
fi
|
||||
grep -F -q 'globalLogsToggle' "$stage/cgi"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
grep -F -q 'LOG_BUFFER_LIMIT=16384' "$stage/logs.sh"
|
||||
grep -F -q 'LOG_KEEP_SECONDS=86400' "$stage/logs.sh"
|
||||
grep -F -q 'log_sync_loop' "$stage/logs.sh"
|
||||
|
||||
@@ -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 'v121' in source
|
||||
assert 'v122' in source
|
||||
assert 'v108' not in source
|
||||
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
|
||||
assert 'prepareLoginRecaptcha' in source
|
||||
|
||||
@@ -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 'v121' in source
|
||||
assert 'v122' 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)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
& (Join-Path $PSScriptRoot 'deploy-tachyon.ps1') -Vps $Vps -Action $Action -BackupName tachyon-layout -PrepareOnly:$PrepareOnly
|
||||
@@ -0,0 +1,146 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-tachyon-route-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [Text.UTF8Encoding]::new($false)
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
umask 077
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-tachyon-route-fix-v121
|
||||
hub=/opt/owrt-remote/owrt-remote-hub.py
|
||||
xray_config=/etc/xray/owrt-remote.json
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
changed=0
|
||||
step=preflight
|
||||
snapshot() {
|
||||
mkdir -p "$1"; chmod 0700 "$1"
|
||||
cp -p "$hub" "$1/hub.py"
|
||||
cp -p "$xray_config" "$1/xray.json"
|
||||
: >"$1/complete"
|
||||
}
|
||||
apply_files() {
|
||||
cp "$1/hub.py" "$hub.new-__UPLOAD_NAME__"
|
||||
chmod 0755 "$hub.new-__UPLOAD_NAME__"; mv -f "$hub.new-__UPLOAD_NAME__" "$hub"
|
||||
cp "$1/xray.json" "$xray_config.new-__UPLOAD_NAME__"
|
||||
chmod 0600 "$xray_config.new-__UPLOAD_NAME__"; mv -f "$xray_config.new-__UPLOAD_NAME__" "$xray_config"
|
||||
}
|
||||
restart_services() {
|
||||
systemctl restart owrt-remote
|
||||
systemctl restart owrt-remote-xray
|
||||
}
|
||||
cleanup() {
|
||||
code=$?; trap - EXIT; set +e
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Tachyon route fix failed during $step (rc=$code)." >&2
|
||||
if [ "$changed" = 1 ]; then
|
||||
echo 'Restoring Hub and Xray configuration from before this attempt.' >&2
|
||||
apply_files "$stage/previous" && restart_services || echo 'Automatic restoration was not confirmed.' >&2
|
||||
fi
|
||||
fi
|
||||
rm -f "$hub.new-__UPLOAD_NAME__" "$xray_config.new-__UPLOAD_NAME__"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
test -s "$hub"; test -s "$xray_config"; test -x /usr/local/bin/xray
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
step=prepare-xray
|
||||
cp -p "$xray_config" "$stage/baseline-xray.json"
|
||||
"$python_bin" - "$stage/baseline-xray.json" "$stage/xray.json" <<'PY'
|
||||
import json,os,pathlib,sys
|
||||
config=json.loads(pathlib.Path(sys.argv[1]).read_text())
|
||||
changed=0
|
||||
for inbound in config.get('inbounds',[]):
|
||||
if inbound.get('protocol')!='tunnel' or not str(inbound.get('tag','')).startswith(('entry-','ssh-','tachyon-')):
|
||||
continue
|
||||
settings=inbound.get('settings',{})
|
||||
if not all(k in settings for k in ('allowedNetwork','rewriteAddress','rewritePort')):
|
||||
continue
|
||||
port=settings['rewritePort']
|
||||
if not isinstance(port,int) or isinstance(port,bool) or not 1<=port<=65535:
|
||||
raise SystemExit('Invalid reverse target port')
|
||||
settings.update(network=settings['allowedNetwork'],address=settings['rewriteAddress'],port=port)
|
||||
changed+=1
|
||||
out=pathlib.Path(sys.argv[2])
|
||||
out.write_text(json.dumps(config,ensure_ascii=False,indent=2)+'\n')
|
||||
os.chmod(out,0o600)
|
||||
print('Prepared compatible reverse listeners: '+str(changed))
|
||||
PY
|
||||
source_dir="$stage"
|
||||
else
|
||||
test -e "$backup/complete" && test -s "$backup/hub.py" && test -s "$backup/xray.json" || {
|
||||
echo "No complete backup: $backup. Nothing changed." >&2; exit 1;
|
||||
}
|
||||
source_dir="$backup"
|
||||
fi
|
||||
step=validate-xray
|
||||
/usr/local/bin/xray -test -config "$source_dir/xray.json"
|
||||
step=backup
|
||||
if [ '__ACTION__' = Install ] && [ ! -e "$backup/complete" ]; then
|
||||
test ! -e "$backup" || { echo "Incomplete backup exists: $backup" >&2; exit 1; }
|
||||
snapshot "$backup"
|
||||
fi
|
||||
snapshot "$stage/previous"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
cmp "$stage/baseline-xray.json" "$stage/previous/xray.json" || {
|
||||
echo 'Xray configuration changed during preflight; retry the installation.' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
changed=1
|
||||
step=apply-files
|
||||
apply_files "$source_dir"
|
||||
step=restart
|
||||
restart_services
|
||||
step=verify-health
|
||||
"$python_bin" - <<'PY'
|
||||
import hashlib,json,pathlib,time,urllib.request,subprocess
|
||||
expected=hashlib.sha256(pathlib.Path('/opt/owrt-remote/owrt-remote-hub.py').read_bytes()).hexdigest()
|
||||
client=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
for attempt in range(25):
|
||||
try:
|
||||
with client.open('http://127.0.0.1:8088/health?panel-update=1',timeout=2) as response:
|
||||
data=json.load(response)
|
||||
running=subprocess.run(['systemctl','is-active','--quiet','owrt-remote-xray']).returncode==0
|
||||
if data.get('ok') and data.get('revision')==expected and running: break
|
||||
except (OSError,ValueError): pass
|
||||
time.sleep(1)
|
||||
else: raise SystemExit('Hub revision or Xray service was not confirmed')
|
||||
print('Running Hub and Xray verified: '+expected)
|
||||
PY
|
||||
cmp "$source_dir/hub.py" "$hub"
|
||||
cmp "$source_dir/xray.json" "$xray_config"
|
||||
echo "Backup: $backup"
|
||||
echo 'TACHYON_ROUTE_FIX___ACTION___OK'
|
||||
'@
|
||||
try {
|
||||
[IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action).Replace([string][char]13, [string]::Empty)
|
||||
[IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript + [char]10, $Utf8)
|
||||
if ($Action -eq 'Install') {
|
||||
$Source = [IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace([string][char]13, [string]::Empty)
|
||||
[IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Source, $Utf8)
|
||||
}
|
||||
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||
& scp -O -o ConnectTimeout=20 -r -- $StageRoot "${Vps}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Vps "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed; success was not confirmed." }
|
||||
Write-Host "Tachyon route fix $Action finished successfully."
|
||||
} finally {
|
||||
if (-not $PrepareOnly -and (Test-Path -LiteralPath $StageRoot)) {
|
||||
$Resolved = [IO.Path]::GetFullPath($StageRoot)
|
||||
$Expected = [IO.Path]::GetFullPath((Join-Path ([IO.Path]::GetTempPath()) $UploadName))
|
||||
if ($Resolved -ne $Expected) { throw 'Unsafe staging cleanup path.' }
|
||||
Remove-Item -LiteralPath $Resolved -Recurse -Force
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[ValidateSet('tachyon-integration', 'tachyon-layout')][string]$BackupName = 'tachyon-integration',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-tachyon-integration-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
$TargetKind = $PSCmdlet.ParameterSetName
|
||||
$Destination = if ($TargetKind -eq 'Vps') { $Vps } else { $Router }
|
||||
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
kind=__KIND__
|
||||
action=__ACTION__
|
||||
backup=/root/owrt-remote-backup-before-__BACKUP_NAME__-v121
|
||||
changed=0
|
||||
step=preflight
|
||||
|
||||
if [ "$kind" = Vps ]; then
|
||||
names=hub.py
|
||||
else
|
||||
names='agent tachyon.sh'
|
||||
fi
|
||||
target() {
|
||||
case "$1" in
|
||||
hub.py) echo /opt/owrt-remote/owrt-remote-hub.py ;;
|
||||
agent) echo /usr/sbin/owrt-remote ;;
|
||||
tachyon.sh) echo /usr/lib/owrt-remote/tachyon.sh ;;
|
||||
esac
|
||||
}
|
||||
snapshot() {
|
||||
folder="$1"
|
||||
mkdir -p "$folder"
|
||||
for name in $names; do
|
||||
path="$(target "$name")"
|
||||
if [ -e "$path" ]; then cp -p "$path" "$folder/$name"; else : >"$folder/$name.absent"; fi
|
||||
done
|
||||
printf '%s\n' "$kind" >"$folder/complete"
|
||||
}
|
||||
apply_files() {
|
||||
folder="$1"
|
||||
for name in $names; do
|
||||
path="$(target "$name")"
|
||||
if [ -e "$folder/$name.absent" ]; then
|
||||
rm -f "$path"
|
||||
else
|
||||
test -s "$folder/$name"
|
||||
mkdir -p "$(dirname "$path")"
|
||||
cp "$folder/$name" "$path.new-__UPLOAD_NAME__"
|
||||
if [ "$name" = tachyon.sh ]; then chmod 0644 "$path.new-__UPLOAD_NAME__"; else chmod 0755 "$path.new-__UPLOAD_NAME__"; fi
|
||||
mv -f "$path.new-__UPLOAD_NAME__" "$path"
|
||||
fi
|
||||
done
|
||||
}
|
||||
restart() {
|
||||
if [ "$kind" = Vps ]; then
|
||||
systemctl restart owrt-remote
|
||||
if [ "$action" = Rollback ] && systemctl is-active --quiet owrt-remote-xray; then
|
||||
/opt/owrt-remote/owrt-remote-run.sh render-xray --out /etc/xray/owrt-remote.json
|
||||
systemctl restart owrt-remote-xray
|
||||
fi
|
||||
else /etc/init.d/owrt-remote restart; fi
|
||||
}
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
set +e
|
||||
if [ "$code" -ne 0 ]; then echo "Failed during $step (rc=$code)." >&2; fi
|
||||
if [ "$code" -ne 0 ] && [ "$kind" = Router ]; then diagnose_router || true; fi
|
||||
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
|
||||
echo 'Deployment failed; restoring files from before this attempt.' >&2
|
||||
apply_files "$stage/previous" && restart || true
|
||||
fi
|
||||
if [ "$code" -ne 0 ] && [ "$kind" = Vps ]; then journalctl -u owrt-remote -n 35 --no-pager >&2 || true; fi
|
||||
for name in $names; do path="$(target "$name")"; rm -f "$path.new-__UPLOAD_NAME__"; done
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
diagnose_router() {
|
||||
[ "$kind" = Router ] || return 0
|
||||
echo 'Router deployment diagnostics:' >&2
|
||||
echo "stage=$stage action=$action" >&2
|
||||
for command_name in jsonfilter ubus timeout busybox; do
|
||||
if command -v "$command_name" >/dev/null 2>&1; then
|
||||
echo "command $command_name=$(command -v "$command_name")" >&2
|
||||
else
|
||||
echo "command $command_name=missing" >&2
|
||||
fi
|
||||
done
|
||||
echo 'owrt-remote service:' >&2
|
||||
ubus call service list '{"name":"owrt-remote"}' >&2 || true
|
||||
echo 'recent owrt-remote log:' >&2
|
||||
logread -e owrt-remote 2>/dev/null | tail -n 80 >&2 || true
|
||||
}
|
||||
fail_router() {
|
||||
echo "Router deployment error: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
|
||||
if [ "$action" = Install ]; then
|
||||
if [ "$kind" = Vps ]; then
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
"$python_bin" - "$stage/hub.py" <<'PY'
|
||||
import pathlib, sys
|
||||
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
|
||||
for marker in ('def normalize_tachyon(', 'def router_tachyon(', 'tachyon_entry_port', 'function renderTachyon('):
|
||||
if marker not in source: raise SystemExit('Candidate missing: ' + marker)
|
||||
print('Hub candidate validated')
|
||||
PY
|
||||
else
|
||||
sh -n "$stage/agent" || fail_router 'agent shell syntax check failed'
|
||||
sh -n "$stage/tachyon.sh" || fail_router 'tachyon.sh shell syntax check failed'
|
||||
test -r /usr/lib/owrt-remote/control.sh || fail_router 'Update Remote v121 first: control.sh missing'
|
||||
command -v jsonfilter >/dev/null 2>&1 || fail_router 'jsonfilter is missing'
|
||||
command -v ubus >/dev/null 2>&1 || fail_router 'ubus is missing'
|
||||
# The agent has a bounded shell fallback when the optional BusyBox
|
||||
# timeout applet is absent, so this is informational rather than a
|
||||
# reason to reject an otherwise valid OpenWrt installation.
|
||||
if command -v timeout >/dev/null 2>&1; then
|
||||
echo 'Router preflight: timeout applet available' >&2
|
||||
elif command -v busybox >/dev/null 2>&1 && busybox timeout 45 true >/dev/null 2>&1; then
|
||||
echo 'Router preflight: BusyBox timeout applet available' >&2
|
||||
else
|
||||
echo 'Router preflight: timeout applet unavailable; agent shell timeout fallback will be used' >&2
|
||||
fi
|
||||
grep -Fq xray_control_dispatch "$stage/agent" || fail_router 'agent does not contain xray_control_dispatch'
|
||||
grep -Fq tachyon_json "$stage/tachyon.sh" || fail_router 'Tachyon discovery helper missing'
|
||||
fi
|
||||
step=backup
|
||||
if [ ! -e "$backup/complete" ]; then
|
||||
test ! -e "$backup" || { echo "Incomplete backup already exists: $backup" >&2; exit 1; }
|
||||
snapshot "$backup"
|
||||
fi
|
||||
test "$(cat "$backup/complete")" = "$kind"
|
||||
source_dir="$stage"
|
||||
else
|
||||
step=backup
|
||||
test "$(cat "$backup/complete" 2>/dev/null)" = "$kind" || { echo "No complete backup: $backup. Nothing changed." >&2; exit 1; }
|
||||
source_dir="$backup"
|
||||
fi
|
||||
for name in $names; do test -s "$source_dir/$name" || test -e "$source_dir/$name.absent"; done
|
||||
snapshot "$stage/previous"
|
||||
changed=1
|
||||
step=apply-files
|
||||
apply_files "$source_dir"
|
||||
step=restart
|
||||
restart
|
||||
|
||||
step=verify-health
|
||||
if [ "$kind" = Vps ]; then
|
||||
python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
"$python_bin" - <<'PY'
|
||||
import hashlib, json, pathlib, time, urllib.request
|
||||
expected = hashlib.sha256(pathlib.Path('/opt/owrt-remote/owrt-remote-hub.py').read_bytes()).hexdigest()
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
for attempt in range(20):
|
||||
try:
|
||||
with opener.open('http://127.0.0.1:8088/health?panel-update=1', timeout=3) as response:
|
||||
data = json.load(response)
|
||||
if data.get('ok') and data.get('revision') == expected: break
|
||||
except Exception: pass
|
||||
time.sleep(1)
|
||||
else: raise SystemExit('Running Hub revision/health was not confirmed')
|
||||
print('Running Hub revision verified: ' + expected)
|
||||
PY
|
||||
else
|
||||
healthy=0
|
||||
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||
state="$(ubus call service list '{"name":"owrt-remote"}' 2>/dev/null || true)"
|
||||
if [ "$(printf '%s' "$state" | jsonfilter -e '@["owrt-remote"].instances.heartbeat.running')" = true ]; then healthy=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
[ "$healthy" = 1 ] || fail_router 'Heartbeat instance did not start; deployment is being rolled back.'
|
||||
fi
|
||||
step=verify-files
|
||||
for name in $names; do
|
||||
path="$(target "$name")"
|
||||
if [ -e "$source_dir/$name.absent" ]; then test ! -e "$path"; else cmp "$source_dir/$name" "$path"; fi
|
||||
done
|
||||
printf '\nBackup: %s\nTACHYON_INTEGRATION_%s_%s_OK\n' "$backup" "$kind" "$action"
|
||||
'@
|
||||
|
||||
try {
|
||||
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__KIND__', $TargetKind).Replace('__ACTION__', $Action).Replace('__BACKUP_NAME__', $BackupName)
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
|
||||
if ($Action -eq 'Install') {
|
||||
$Sources = if ($TargetKind -eq 'Vps') {
|
||||
@{ 'hub.py' = 'vps\owrt-remote-hub.py' }
|
||||
} else {
|
||||
@{ 'agent' = 'files\usr\sbin\owrt-remote'; 'tachyon.sh' = 'files\usr\lib\owrt-remote\tachyon.sh' }
|
||||
}
|
||||
foreach ($Entry in $Sources.GetEnumerator()) {
|
||||
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Entry.Value)).Replace("`r`n", "`n")
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Entry.Key), $Content, $Utf8)
|
||||
}
|
||||
}
|
||||
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||
& scp -O -o ConnectTimeout=20 -r -- $StageRoot "${Destination}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=20 -o ServerAliveInterval=15 $Destination "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. Success was not confirmed; see output above." }
|
||||
Write-Host "Tachyon integration $TargetKind $Action finished successfully."
|
||||
} finally {
|
||||
if (-not $PrepareOnly -and (Test-Path -LiteralPath $StageRoot)) {
|
||||
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
|
||||
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
|
||||
if ($Resolved -eq $Expected) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Vps')][ValidateNotNullOrEmpty()][string]$Vps,
|
||||
[Parameter(Mandatory = $true, ParameterSetName = 'Router')][ValidateNotNullOrEmpty()][string]$Router,
|
||||
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||
[switch]$PrepareOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$UploadName = 'owrt-version-v122-' + [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-v122
|
||||
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 = ('v122', 'def hub_update_require_version(', 'def hub_update_older_version(',
|
||||
"else if (state.checked && !state.checking) message('');")
|
||||
if 'v' + str(122 - 1) in source:
|
||||
print('Old UI version remains in candidate', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
missing = [marker for marker in required if marker not in source]
|
||||
if missing:
|
||||
for marker in missing:
|
||||
print('Missing marker:', repr(marker), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
print('Candidate validation OK')
|
||||
PY
|
||||
if [ ! -e "$backup" ]; then
|
||||
cp -p "$target" "$backup"
|
||||
fi
|
||||
source_file="$stage/hub.py"
|
||||
else
|
||||
test -s "$backup"
|
||||
"$python_bin" -m py_compile "$backup"
|
||||
source_file="$backup"
|
||||
fi
|
||||
|
||||
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\nHUB_V122_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
$RouterScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup=/root/owrt-remote-backup-before-v122
|
||||
cgi=/www/cgi-bin/owrt-remote
|
||||
luci=/www/luci-static/resources/view/owrt_remote.js
|
||||
changed=0
|
||||
cleanup() {
|
||||
code=$?
|
||||
trap - EXIT
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "Router version __ACTION__ failed (rc=$code)." >&2
|
||||
if [ "$changed" = 1 ]; then
|
||||
echo 'Restoring the previous router UI files...' >&2
|
||||
cp -p "$stage/previous-cgi" "$cgi.new-__UPLOAD_NAME__" && mv -f "$cgi.new-__UPLOAD_NAME__" "$cgi" || true
|
||||
cp -p "$stage/previous-luci" "$luci.new-__UPLOAD_NAME__" && mv -f "$luci.new-__UPLOAD_NAME__" "$luci" || true
|
||||
fi
|
||||
fi
|
||||
rm -f "$cgi.new-__UPLOAD_NAME__" "$luci.new-__UPLOAD_NAME__"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
test -s "$cgi"
|
||||
test -s "$luci"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
sh -n "$stage/cgi"
|
||||
grep -F -q 'v122' "$stage/cgi"
|
||||
grep -F -q 'v122' "$stage/luci"
|
||||
if grep -F -q "v$((122 - 1))" "$stage/cgi" "$stage/luci"; then
|
||||
echo 'Old UI version remains in candidate.' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -e "$backup" ]; then
|
||||
mkdir -m 700 "$stage/retained"
|
||||
cp -p "$cgi" "$stage/retained/cgi"
|
||||
cp -p "$luci" "$stage/retained/luci"
|
||||
: >"$stage/retained/complete"
|
||||
mv "$stage/retained" "$backup"
|
||||
fi
|
||||
source_dir=$stage
|
||||
else
|
||||
source_dir=$backup
|
||||
fi
|
||||
if [ ! -f "$backup/complete" ] || [ ! -s "$backup/cgi" ] || [ ! -s "$backup/luci" ]; then
|
||||
echo "No complete backup: $backup. Nothing changed." >&2
|
||||
exit 1
|
||||
fi
|
||||
sh -n "$source_dir/cgi"
|
||||
cp -p "$cgi" "$stage/previous-cgi"
|
||||
cp -p "$luci" "$stage/previous-luci"
|
||||
cp "$source_dir/cgi" "$cgi.new-__UPLOAD_NAME__"
|
||||
chmod 0755 "$cgi.new-__UPLOAD_NAME__"
|
||||
cp "$source_dir/luci" "$luci.new-__UPLOAD_NAME__"
|
||||
chmod 0644 "$luci.new-__UPLOAD_NAME__"
|
||||
changed=1
|
||||
mv -f "$cgi.new-__UPLOAD_NAME__" "$cgi"
|
||||
mv -f "$luci.new-__UPLOAD_NAME__" "$luci"
|
||||
cmp "$source_dir/cgi" "$cgi"
|
||||
cmp "$source_dir/luci" "$luci"
|
||||
[ ! -x /etc/init.d/rpcd ] || /etc/init.d/rpcd restart || true
|
||||
[ ! -x /etc/init.d/uhttpd ] || /etc/init.d/uhttpd reload || true
|
||||
printf '\nBackup: %s\nROUTER_V122_%s_OK\n' "$backup" '__ACTION__'
|
||||
'@
|
||||
|
||||
if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
$RemoteScript = $RouterScript
|
||||
$TargetMachine = $Router
|
||||
}
|
||||
else {
|
||||
$TargetMachine = $Vps
|
||||
}
|
||||
$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') {
|
||||
$Files = if ($PSCmdlet.ParameterSetName -eq 'Router') {
|
||||
@{ 'cgi' = 'files\www\cgi-bin\owrt-remote'; 'luci' = 'files\www\luci-static\resources\view\owrt_remote.js' }
|
||||
} else {
|
||||
@{ 'hub.py' = 'vps\owrt-remote-hub.py' }
|
||||
}
|
||||
foreach ($Name in $Files.Keys) {
|
||||
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Files[$Name])).Replace("`r`n", "`n")
|
||||
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Name), $Content, $Utf8)
|
||||
}
|
||||
}
|
||||
|
||||
if ($PrepareOnly) {
|
||||
Write-Host "Prepared only: $StageRoot"
|
||||
return
|
||||
}
|
||||
|
||||
& scp -O -r -- $StageRoot "${TargetMachine}:/tmp/"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Target was not changed.' }
|
||||
& ssh -T -o ConnectTimeout=10 $TargetMachine "sh /tmp/$UploadName/run.sh"
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||
Write-Host "Version v122 $Action finished successfully. Refresh the panel."
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ python_bin=/opt/owrt-remote/venv/bin/python
|
||||
[ -x "$python_bin" ] || python_bin=python3
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
test -s "$stage/hub.py"
|
||||
grep -F -q 'v121' "$stage/hub.py"
|
||||
grep -F -q 'v122' "$stage/hub.py"
|
||||
"$python_bin" -m py_compile "$stage/hub.py"
|
||||
OWRT_VPS_WIDGETS_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
|
||||
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
|
||||
|
||||
@@ -81,7 +81,7 @@ test -s "$config"
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent wan.sh cgi hotplug; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
test -s "$stage/luci"
|
||||
for item in cgi luci; do grep -F -q 'v121' "$stage/$item"; done
|
||||
for item in cgi luci; do grep -F -q 'v122' "$stage/$item"; done
|
||||
grep -F -q 'wan_interface_picker' "$stage/cgi"
|
||||
grep -F -q 'wan_select_interface()' "$stage/wan.sh"
|
||||
grep -F -q 'wan_reconcile_xray()' "$stage/agent"
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
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-download-' + [guid]::NewGuid().ToString('N')
|
||||
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
$Payloads = @{
|
||||
'agent' = 'files\usr\sbin\owrt-remote'
|
||||
}
|
||||
$RemoteScript = @'
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
stage=/tmp/__UPLOAD_NAME__
|
||||
backup_dir=/root/owrt-remote-backup-before-xray-download-v121
|
||||
key_file=/etc/owrt-remote/web.key
|
||||
key_candidate=$key_file.new-__UPLOAD_NAME__
|
||||
changed=0
|
||||
phase=preflight
|
||||
item_path() {
|
||||
case "$1" in
|
||||
agent) printf /usr/sbin/owrt-remote ;;
|
||||
esac
|
||||
}
|
||||
complete_backup() {
|
||||
[ -f "$1/complete" ] && [ -s "$1/agent" ]
|
||||
}
|
||||
restore_files() {
|
||||
local dir item path
|
||||
dir=$1
|
||||
complete_backup "$dir" || return 1
|
||||
for item in 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 previous agent from this attempt.' >&2
|
||||
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
|
||||
fi
|
||||
fi
|
||||
for item in agent; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
|
||||
rm -f "$key_candidate"
|
||||
rm -rf "$stage"
|
||||
exit "$code"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 1' INT TERM
|
||||
for item in agent; do
|
||||
path=$(item_path "$item")
|
||||
test -s "$path"
|
||||
done
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
for item in agent; do test -s "$stage/$item"; sh -n "$stage/$item"; done
|
||||
grep -F -q 'xray_validate_transport_binary()' "$stage/agent"
|
||||
grep -F -q 'remote_download()' "$stage/agent"
|
||||
grep -F -q 'xray_discover_releases()' "$stage/agent"
|
||||
grep -F -q 'apk extract --allow-untrusted --no-chown --destination' "$stage/agent"
|
||||
grep -F -q 'xray_package_extract_binary "$package" "$work/xray.new" "$asset"' "$stage/agent"
|
||||
if [ ! -e "$backup_dir" ]; then
|
||||
mkdir -p "$stage/retained-backup"
|
||||
chmod 700 "$stage/retained-backup"
|
||||
for item in 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 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 agent; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
|
||||
touch "$stage/previous/complete"
|
||||
phase=install
|
||||
changed=1
|
||||
for item in 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 agent; do
|
||||
path=$(item_path "$item")
|
||||
sh -n "$path"
|
||||
cmp "$source_dir/$item" "$path"
|
||||
done
|
||||
if [ '__ACTION__' = Install ]; then
|
||||
phase=prepare-xray-download
|
||||
# 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
|
||||
# install.sh creates the web key after Xray preparation. Recover that last
|
||||
# step if the first installation was interrupted by the APK defect.
|
||||
if [ ! -s "$key_file" ]; then
|
||||
phase=finish-first-install
|
||||
mkdir -p "$(dirname "$key_file")"
|
||||
if command -v hexdump >/dev/null 2>&1; then
|
||||
(umask 077; dd if=/dev/urandom bs=16 count=1 2>/dev/null | hexdump -v -e '16/1 "%02x"' >"$key_candidate")
|
||||
else
|
||||
(umask 077; dd if=/dev/urandom bs=16 count=1 2>/dev/null | od -An -v -tx1 | tr -d ' \n' >"$key_candidate")
|
||||
fi
|
||||
[ "$(wc -c <"$key_candidate")" -eq 32 ] || { echo 'Web key generation failed.' >&2; exit 1; }
|
||||
chmod 600 "$key_candidate"
|
||||
mv -f "$key_candidate" "$key_file"
|
||||
echo 'Web key created for the interrupted first installation.'
|
||||
fi
|
||||
fi
|
||||
# Rollback restores agent code only; retain the validated compatible core,
|
||||
# its boot cache, and all router settings. Never remove a working executable.
|
||||
printf '\nXRAY_DOWNLOAD_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 download 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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
param(
|
||||
[string]$Vps = 'root@132.243.19.232',
|
||||
[ValidatePattern('^[a-zA-Z0-9_-]{1,80}$')][string]$RouterId = 'node-10'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Probe = @'
|
||||
python3 - <<'PY'
|
||||
import hashlib,http.client,json,pathlib,re,sqlite3,subprocess
|
||||
router_id='__ROUTER_ID__'
|
||||
with sqlite3.connect('file:/var/lib/owrt-remote/hub.db?mode=ro',uri=True) as conn:
|
||||
conn.row_factory=sqlite3.Row
|
||||
row=conn.execute('select * from routers where id=?',(router_id,)).fetchone()
|
||||
if row is None: raise SystemExit('Router not found')
|
||||
status=json.loads(row['status_json'] or '{}')
|
||||
print('ROUTER',row['id'])
|
||||
print('PORTS',json.dumps({k:row[k] for k in ('entry_port','ssh_entry_port','tachyon_entry_port')}))
|
||||
print('REPORTED_TACHYON',json.dumps(status.get('tachyon',{})))
|
||||
config_path=pathlib.Path('/etc/xray/owrt-remote.json')
|
||||
data=json.loads(config_path.read_text())
|
||||
for entry in data.get('inbounds',[]):
|
||||
if entry.get('tag') in ('entry-'+router_id,'tachyon-'+router_id):
|
||||
print('INBOUND',json.dumps(entry))
|
||||
for rule in data.get('routing',{}).get('rules',[]):
|
||||
if any(t in ('entry-'+router_id,'tachyon-'+router_id) for t in rule.get('inboundTag',[])):
|
||||
print('RULE',json.dumps(rule))
|
||||
for name in ('entry_port','tachyon_entry_port'):
|
||||
port=int(row[name] or 0)
|
||||
if not port: continue
|
||||
c=http.client.HTTPConnection('127.0.0.1',port,timeout=5)
|
||||
try:
|
||||
c.request('GET','/')
|
||||
r=c.getresponse(); body=r.read(32768).decode('utf-8','replace')
|
||||
title=re.search(r'<title[^>]*>(.*?)</title>',body,re.S|re.I)
|
||||
print('HTTP_PROBE',name,'status=',r.status,'location=',r.getheader('Location'),'title=',title.group(1)[:150] if title else None)
|
||||
except Exception as exc: print('HTTP_PROBE',name,type(exc).__name__,str(exc))
|
||||
finally:c.close()
|
||||
for command in (['/usr/local/bin/xray','version'],['systemctl','show','owrt-remote-xray','-p','ExecStart','-p','MainPID']):
|
||||
r=subprocess.run(command,capture_output=True,text=True)
|
||||
print(r.stdout[:1600])
|
||||
print('TACHYON_VPS_READ_ONLY_DONE')
|
||||
PY
|
||||
'@
|
||||
$Probe = $Probe.Replace('__ROUTER_ID__', $RouterId).Replace([string][char]13, [string]::Empty)
|
||||
$Encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($Probe + [char]10))
|
||||
& ssh -T -o ConnectTimeout=10 $Vps "printf %s $Encoded | base64 -d | sh -s"
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Read-only VPS diagnostics failed.' }
|
||||
@@ -0,0 +1,47 @@
|
||||
param([string]$Router = 'root@192.168.2.1')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Probe = @'
|
||||
set +e
|
||||
echo '=== PACKAGE METADATA ==='
|
||||
if command -v apk >/dev/null 2>&1; then
|
||||
for p in tachyon luci-app-tachyon; do apk info -e "$p"; apk info -v "$p"; done
|
||||
elif command -v opkg >/dev/null 2>&1; then
|
||||
opkg status tachyon luci-app-tachyon | sed -n '/^Package:/p;/^Version:/p;/^Status:/p'
|
||||
fi
|
||||
echo '=== SERVICE FILES ==='
|
||||
ls -l /etc/init.d/*tachyon* /www/cgi-bin/tachyon* 2>/dev/null
|
||||
echo '=== UHTTPD LISTENERS AND DOCUMENT ROOTS ==='
|
||||
uci -q show uhttpd | sed -n '/=uhttpd$/p;/\.listen_http=/p;/\.home=/p;/\.cgi_prefix=/p;/\.ubus_prefix=/p'
|
||||
echo '=== TACHYON HTTP SETTINGS (NO SECRETS) ==='
|
||||
uci -q show tachyon | sed -n '/\.web_port=/p;/\.http_port=/p;/\.ui_port=/p;/\.listen_port=/p'
|
||||
echo '=== PROCD SERVICE STATES ==='
|
||||
for s in tachyon tachyon-core tachyon-web tachyon-http uhttpd; do
|
||||
printf '%s: ' "$s"
|
||||
ubus call service list "{\"name\":\"$s\"}" 2>/dev/null | jsonfilter -e '@.*.instances.*.running'
|
||||
done
|
||||
echo '=== LOCAL HTTP RESPONSES ==='
|
||||
for u in http://127.0.0.1:1680/ http://192.168.2.1:1680/ http://127.0.0.1/cgi-bin/luci/admin/services/tachyon; do
|
||||
printf '%s ' "$u"
|
||||
curl -q -s --noproxy '*' --max-time 3 -o /dev/null -w 'HTTP=%{http_code}\n' "$u"
|
||||
done
|
||||
echo '=== PUBLIC READ-ONLY HEALTH ENDPOINTS ==='
|
||||
for p in tachyon-api tachyon-agent; do
|
||||
printf '%s: ' "$p"
|
||||
curl -q -fsS --noproxy '*' --max-time 3 "http://127.0.0.1/cgi-bin/$p/health" 2>/dev/null |
|
||||
jsonfilter -e '@.success' -e '@.status' -e '@.version' -e '@.tachyon_core'
|
||||
done
|
||||
echo 'TACHYON_READ_ONLY_DIAGNOSTICS_DONE'
|
||||
echo '=== REMOTE ROUTER ID AND TACHYON STATE ==='
|
||||
uci -q get owrtremote.main.router_id
|
||||
owrt-remote tachyon-status
|
||||
echo '=== INSTALLED XRAY TACHYON ROUTE (NO KEYS) ==='
|
||||
cfg="$(uci -q get owrtremote.main.xray_config)"
|
||||
[ -n "$cfg" ] || cfg=/etc/xray/owrt-remote-client.json
|
||||
printf 'config=%s\n' "$cfg"
|
||||
jsonfilter -i "$cfg" -e '@.outbounds[@.tag="router-tachyon"].settings' -e '@.routing.rules' 2>/dev/null
|
||||
echo '=== CANDIDATE TACHYON ROUTE (NO KEYS) ==='
|
||||
owrt-remote render-client --stdout 2>/dev/null | jsonfilter -e '@.outbounds[@.tag="router-tachyon"].settings' -e '@.routing.rules' 2>/dev/null
|
||||
echo 'TACHYON_ROUTE_READ_ONLY_DONE'
|
||||
'@
|
||||
$Probe.Replace([string][char]13, [string]::Empty) | & ssh -T -o ConnectTimeout=10 $Router 'sh -s'
|
||||
if ($LASTEXITCODE -ne 0) { throw 'SSH diagnostics failed. Router settings were not changed.' }
|
||||
+172
-18
@@ -3644,6 +3644,7 @@ def init_db(conn):
|
||||
ensure_column(conn, "routers", "group_id", "text not null default ''")
|
||||
ensure_column(conn, "routers", "deleted_at", "integer not null default 0")
|
||||
ensure_column(conn, "routers", "ssh_entry_port", "integer not null default 0")
|
||||
ensure_column(conn, "routers", "tachyon_entry_port", "integer not null default 0")
|
||||
ensure_column(conn, "routers", "ssh_vless_uuid", "text not null default ''")
|
||||
ensure_column(conn, "routers", "ssh_reverse_tag", "text not null default ''")
|
||||
ensure_column(conn, "routers", "ssh_host", "text not null default '127.0.0.1'")
|
||||
@@ -3734,15 +3735,15 @@ def get_active_router(conn, router_id):
|
||||
|
||||
def get_router_by_entry_port(conn, entry_port, exclude_id=""):
|
||||
return conn.execute(
|
||||
"select * from routers where coalesce(deleted_at, 0) = 0 and (entry_port = ? or ssh_entry_port = ?) and id != ?",
|
||||
(int(entry_port), int(entry_port), exclude_id),
|
||||
"select * from routers where coalesce(deleted_at, 0) = 0 and (entry_port = ? or ssh_entry_port = ? or tachyon_entry_port = ?) and id != ?",
|
||||
(int(entry_port), int(entry_port), int(entry_port), exclude_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def get_router_by_any_port(conn, port, exclude_id=""):
|
||||
return conn.execute(
|
||||
"select * from routers where coalesce(deleted_at, 0) = 0 and (entry_port = ? or ssh_entry_port = ?) and id != ?",
|
||||
(int(port), int(port), exclude_id),
|
||||
"select * from routers where coalesce(deleted_at, 0) = 0 and (entry_port = ? or ssh_entry_port = ? or tachyon_entry_port = ?) and id != ?",
|
||||
(int(port), int(port), int(port), exclude_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
@@ -3766,6 +3767,53 @@ def list_router_rows(conn):
|
||||
).fetchall()
|
||||
|
||||
|
||||
def normalize_tachyon(value):
|
||||
if not isinstance(value, dict) or value.get('checked') is not True:
|
||||
return None
|
||||
if value.get('installed') is False:
|
||||
return {'checked': True, 'installed': False}
|
||||
if value.get('installed') is not True:
|
||||
return None
|
||||
mode = value.get('mode')
|
||||
if mode not in {'standalone', 'luci'}:
|
||||
return None
|
||||
port = value.get('port', 0)
|
||||
if isinstance(port, bool) or not isinstance(port, int):
|
||||
return None
|
||||
if mode == 'standalone' and not 1024 <= port <= 65535:
|
||||
return None
|
||||
return {'checked': True, 'installed': True, 'mode': mode,
|
||||
'port': port if mode == 'standalone' else 0,
|
||||
'version': re.sub(r'[^a-zA-Z0-9.+~_-]', '', str(value.get('version') or ''))[:80],
|
||||
'package_version': re.sub(r'[^a-zA-Z0-9.+~_-]', '', str(value.get('package_version') or value.get('version') or ''))[:80],
|
||||
'service': value.get('service') if value.get('service') in {'running', 'stopped'} else 'unknown',
|
||||
'available': value.get('available') is True,
|
||||
'api': value.get('api') if value.get('api') in {'/api/agent/v1', '/cgi-bin/tachyon-api', '/cgi-bin/tachyon-agent'} else ''}
|
||||
|
||||
|
||||
def router_tachyon(row):
|
||||
try:
|
||||
status = row.get('status') if isinstance(row, dict) and 'status' in row else json.loads(row['status_json'] or '{}')
|
||||
return normalize_tachyon(status.get('tachyon')) or {}
|
||||
except (KeyError, IndexError, TypeError, ValueError, AttributeError):
|
||||
return {}
|
||||
|
||||
|
||||
def allocate_tachyon_entry(conn):
|
||||
used = {int(row[0]) for column in ('entry_port', 'ssh_entry_port', 'tachyon_entry_port')
|
||||
for row in conn.execute('select ' + column + ' from routers') if row[0]}
|
||||
for port in range(24000, 65000):
|
||||
if port in used:
|
||||
continue
|
||||
with socket.socket() as probe:
|
||||
try:
|
||||
probe.bind(('127.0.0.1', port))
|
||||
except OSError:
|
||||
continue
|
||||
return port
|
||||
raise RuntimeError('Нет свободного локального порта для Tachyon.')
|
||||
|
||||
|
||||
def row_to_router(row):
|
||||
data = dict(row)
|
||||
try:
|
||||
@@ -3804,6 +3852,10 @@ def row_to_router(row):
|
||||
data["status"] = status
|
||||
data["service_enabled"] = service_enabled
|
||||
data["online"] = online
|
||||
tachyon = router_tachyon(data)
|
||||
if tachyon.get('installed'):
|
||||
data['tachyon'] = {**tachyon, 'online': bool(online and status.get('xray') == 'running' and tachyon.get('available')),
|
||||
'url': f"/tachyon/{urllib.parse.quote(data['id'], safe='')}/"}
|
||||
data["last_seen_iso"] = iso_time(last_seen)
|
||||
data["access_url"] = f"/access/{urllib.parse.quote(data['id'])}/"
|
||||
data["ssh_url"] = f"/ssh/{urllib.parse.quote(data['id'])}/"
|
||||
@@ -4187,6 +4239,8 @@ def upsert_router(conn, values):
|
||||
payload["entry_port"],
|
||||
payload["ssh_entry_port"],
|
||||
)
|
||||
if current and int(current['tachyon_entry_port'] or 0) in {payload['entry_port'], payload['ssh_entry_port']} - {0}:
|
||||
raise ValueError('Этот локальный порт уже используется интеграцией Tachyon.')
|
||||
if current:
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -4358,6 +4412,13 @@ def xray_control_snapshot(conn, router_id):
|
||||
def heartbeat(conn, payload):
|
||||
router_id = clean_router_id(payload.get("id"))
|
||||
row = get_router(conn, router_id)
|
||||
payload = dict(payload)
|
||||
tachyon = normalize_tachyon(payload.get('tachyon'))
|
||||
if tachyon is None:
|
||||
tachyon = router_tachyon(row) if row else {}
|
||||
if tachyon:
|
||||
tachyon = {**tachyon, 'available': False}
|
||||
payload['tachyon'] = tachyon
|
||||
ts = now_ts()
|
||||
status_json = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
was_deleted = router_deleted(row)
|
||||
@@ -4425,6 +4486,17 @@ def heartbeat(conn, payload):
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
old_tachyon = router_tachyon(row)
|
||||
old_endpoint = old_tachyon.get('port', 0) if old_tachyon.get('installed') and old_tachyon.get('mode') == 'standalone' else 0
|
||||
new_endpoint = tachyon.get('port', 0) if tachyon.get('installed') and tachyon.get('mode') == 'standalone' else 0
|
||||
tachyon_reload = old_endpoint != new_endpoint
|
||||
if tachyon.get('installed') and tachyon.get('mode') == 'standalone' and not row['tachyon_entry_port']:
|
||||
conn.execute('begin immediate')
|
||||
current_entry = conn.execute('select tachyon_entry_port from routers where id=?', (router_id,)).fetchone()[0]
|
||||
if not current_entry:
|
||||
conn.execute('update routers set tachyon_entry_port=? where id=?', (allocate_tachyon_entry(conn), router_id))
|
||||
tachyon_reload = True
|
||||
conn.commit()
|
||||
router = row_to_router(get_router(conn, router_id))
|
||||
entry_now = int(router.get("entry_port") or 0)
|
||||
ssh_entry_now = int(router.get("ssh_entry_port") or 0)
|
||||
@@ -4432,6 +4504,7 @@ def heartbeat(conn, payload):
|
||||
(entry_now or ssh_entry_now)
|
||||
and (
|
||||
was_deleted
|
||||
or tachyon_reload
|
||||
or created_with_xray_ports
|
||||
or old_entry_port != entry_now
|
||||
or old_ssh_entry_port != ssh_entry_now
|
||||
@@ -4618,6 +4691,14 @@ def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLE
|
||||
"outboundTag": reverse_out,
|
||||
}
|
||||
)
|
||||
tachyon = router_tachyon(row)
|
||||
tachyon_entry = int(dict(row).get('tachyon_entry_port') or 0)
|
||||
if tachyon.get('installed') and tachyon.get('mode') == 'standalone' and tachyon_entry:
|
||||
tag = f'tachyon-{router_id}'
|
||||
inbounds.append({'tag': tag, 'listen': '127.0.0.1', 'port': tachyon_entry,
|
||||
'protocol': 'tunnel', 'settings': {'allowedNetwork': 'tcp',
|
||||
'rewriteAddress': '127.0.0.1', 'rewritePort': tachyon['port']}})
|
||||
rules.append({'type': 'field', 'inboundTag': [tag], 'outboundTag': reverse_out})
|
||||
if ssh_entry_port > 0:
|
||||
ssh_in = f"ssh-{router_id}"
|
||||
inbounds.append(
|
||||
@@ -4641,6 +4722,16 @@ def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLE
|
||||
}
|
||||
)
|
||||
|
||||
# Xray 26.3.27 accepts the tunnel alias but only reads the original
|
||||
# dokodemo address/port/network fields. Without them it forwards the
|
||||
# inbound listener's local port, so the router's Tachyon rule never matches
|
||||
# and the admin fallback receives the connection. Emit both spellings with
|
||||
# identical values; newer cores use the explicit rewrite fields.
|
||||
for inbound in inbounds:
|
||||
if inbound.get('protocol') == 'tunnel':
|
||||
settings = inbound['settings']
|
||||
settings.update(network=settings['allowedNetwork'], address=settings['rewriteAddress'],
|
||||
port=settings['rewritePort'])
|
||||
return {
|
||||
"log": {"loglevel": "warning"},
|
||||
"inbounds": inbounds,
|
||||
@@ -4653,7 +4744,7 @@ def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLE
|
||||
def make_router_xray_config(row):
|
||||
bridge_tag = row["reverse_tag"]
|
||||
ssh_bridge_tag = row["ssh_reverse_tag"] or f"{bridge_tag}-ssh"
|
||||
return {
|
||||
config = {
|
||||
"log": {"loglevel": "warning"},
|
||||
"inbounds": [],
|
||||
"outbounds": [
|
||||
@@ -4718,6 +4809,14 @@ def make_router_xray_config(row):
|
||||
},
|
||||
"remarks": f"OpenWrt Remote client for {row['id']}",
|
||||
}
|
||||
tachyon = router_tachyon(row)
|
||||
if tachyon.get('installed') and tachyon.get('mode') == 'standalone':
|
||||
port = tachyon['port']
|
||||
config['outbounds'].insert(0, {'tag': 'router-tachyon', 'protocol': 'freedom', 'settings': {
|
||||
'redirect': f'127.0.0.1:{port}', 'finalRules': [{'action': 'allow', 'network': 'tcp', 'port': port}]}})
|
||||
config['routing']['rules'].insert(0, {'type': 'field', 'inboundTag': [bridge_tag],
|
||||
'ip': ['127.0.0.1'], 'port': port, 'outboundTag': 'router-tachyon'})
|
||||
return config
|
||||
|
||||
|
||||
def reload_vps_xray(db_path=DB_PATH):
|
||||
@@ -6259,7 +6358,7 @@ def inject_hub_appearance(path, body, content_type):
|
||||
if "text/html" not in (content_type or "").lower():
|
||||
return body
|
||||
request_path = str(path or "").split("?", 1)[0]
|
||||
if request_path.startswith(("/access/", "/api/", "/cgi-bin/")):
|
||||
if request_path.startswith(("/access/", "/tachyon/", "/api/", "/cgi-bin/")):
|
||||
return body
|
||||
try:
|
||||
text = body.decode("utf-8")
|
||||
@@ -6428,7 +6527,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">v121</span></span></h1>
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v122</span></span></h1>
|
||||
<button class="badge hubUpdateButton" data-hub-update type="button" {'hidden' if not is_owner else ''}>Проверить обновление панели</button>
|
||||
<div class="routerSearchDock" id="routerSearchDock">
|
||||
<button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false">
|
||||
@@ -6767,7 +6866,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
||||
</div>
|
||||
{vps_resource_widgets_html(mobile=True, resources=vps_resources)}
|
||||
<div class="mobileSearchDock" id="mobileHubUpdateDock">
|
||||
<span class="mobileSearchVersion">v121</span>
|
||||
<span class="mobileSearchVersion">v122</span>
|
||||
<button class="badge hubUpdateButton" data-hub-update type="button" {'hidden' if not is_owner else ''}>Проверить обновление панели</button>
|
||||
</div>
|
||||
<div class="mobileSearchDock" id="mobileSeasonDock" aria-label="Зимние эффекты">
|
||||
@@ -8355,6 +8454,16 @@ function formatLoad(value) {{
|
||||
return value || 'Неизвестно';
|
||||
}}
|
||||
|
||||
function renderTachyon(router) {{
|
||||
const t = router.tachyon;
|
||||
if (!t || !t.installed) return '';
|
||||
const label = t.online ? 'Online' : 'Offline';
|
||||
const button = (router.permissions || {{}}).admin
|
||||
? `<a class="btn" href="${{escapeAttr(t.url)}}" target="_blank" rel="noopener noreferrer">Открыть Tachyon</a>`
|
||||
: '<span class="btn disabled">Открыть Tachyon</span>';
|
||||
return `<div class="tachyonIntegration" style="display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:8px;padding:10px;margin-top:10px;border:1px solid var(--line,rgba(180,150,220,.25));border-radius:12px"><strong>Tachyon ${{escapeHtml(t.version || '')}}</strong><span style="color:${{t.online ? '#74e3ac' : '#f2bc6b'}}">${{label}}</span>${{button}}</div>`;
|
||||
}}
|
||||
|
||||
function render(list) {{
|
||||
syncExpandedActionPanels(list);
|
||||
if (!list.length) {{
|
||||
@@ -8433,6 +8542,7 @@ function render(list) {{
|
||||
<div class="metrics">
|
||||
${{metricsHtml}}
|
||||
</div>
|
||||
${{renderTachyon(r)}}
|
||||
<button class="actionToggle primary" type="button" data-actions-toggle="${{escapeAttr(actionsId)}}" aria-expanded="${{actionsOpen ? 'true' : 'false'}}">${{actionsOpen ? 'Скрыть действия' : 'Открыть действия'}}</button>
|
||||
<div class="actions mobileCollapsed${{actionsOpen ? ' open' : ''}}" id="${{escapeAttr(actionsId)}}">
|
||||
${{adminButton}}
|
||||
@@ -8657,6 +8767,7 @@ render = function(list) {{
|
||||
<div class="metrics">
|
||||
${{metricsHtml}}
|
||||
</div>
|
||||
${{renderTachyon(r)}}
|
||||
<button class="actionToggle primary" type="button" data-actions-toggle="${{escapeAttr(actionsId)}}" aria-expanded="${{actionsOpen ? 'true' : 'false'}}">${{actionsOpen ? 'Скрыть действия' : 'Открыть действия'}}</button>
|
||||
<div class="actions mobileCollapsed${{actionsOpen ? ' open' : ''}}" id="${{escapeAttr(actionsId)}}">
|
||||
${{adminButton}}
|
||||
@@ -13754,7 +13865,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">v121</span></span></h1>
|
||||
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v122</span></span></h1>
|
||||
</span>
|
||||
<label for="hubUsername">Логин</label>
|
||||
<input id="hubUsername" name="username" autocomplete="off" autofocus required>
|
||||
@@ -14226,7 +14337,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">v121</span></h2>
|
||||
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v122</span></h2>
|
||||
</div>
|
||||
</div>
|
||||
<div class="brandBottom">
|
||||
@@ -19830,6 +19941,9 @@ exit 127
|
||||
if path.startswith("/ssh/"):
|
||||
self.ssh_page()
|
||||
return
|
||||
if path.startswith("/tachyon/"):
|
||||
self.proxy_access(path, tachyon=True)
|
||||
return
|
||||
if path.startswith("/access/"):
|
||||
self.proxy_access(path)
|
||||
return
|
||||
@@ -20091,6 +20205,9 @@ exit 127
|
||||
self.log_message("heartbeat error: %s", exc)
|
||||
self.send_json(400, {"ok": False, "error": str(exc)})
|
||||
return
|
||||
if path.startswith("/tachyon/"):
|
||||
self.proxy_access(path, tachyon=True)
|
||||
return
|
||||
if path.startswith("/access/"):
|
||||
self.proxy_access(path)
|
||||
return
|
||||
@@ -20711,7 +20828,17 @@ exit 127
|
||||
return
|
||||
self.send_text(404, "not found")
|
||||
|
||||
def proxy_access(self, path):
|
||||
def do_PUT(self):
|
||||
path = self.parsed().path
|
||||
if path.startswith('/tachyon/'):
|
||||
self.proxy_access(path, tachyon=True)
|
||||
else:
|
||||
self.send_text(405, 'Method not allowed')
|
||||
|
||||
do_PATCH = do_PUT
|
||||
do_DELETE = do_PUT
|
||||
|
||||
def proxy_access(self, path, tachyon=False):
|
||||
parts = path.split("/", 3)
|
||||
if len(parts) < 3 or not parts[2]:
|
||||
self.redirect("/")
|
||||
@@ -20719,6 +20846,12 @@ exit 127
|
||||
router_id = urllib.parse.unquote(parts[2])
|
||||
if not self.require_router_access(router_id, "A"):
|
||||
return
|
||||
if tachyon and self.command not in ('GET', 'HEAD', 'OPTIONS'):
|
||||
origin = self.headers.get('Origin') or self.headers.get('Referer', '')
|
||||
parsed_origin = urllib.parse.urlsplit(origin)
|
||||
if not origin or f'{parsed_origin.scheme}://{parsed_origin.netloc}' != self.request_origin():
|
||||
self.send_text(403, 'Недопустимый источник запроса Tachyon.')
|
||||
return
|
||||
rest = "/" + parts[3] if len(parts) == 4 else "/"
|
||||
with self.app.conn() as conn:
|
||||
row = get_active_router(conn, router_id)
|
||||
@@ -20726,6 +20859,17 @@ exit 127
|
||||
self.send_text(404, "router not found")
|
||||
return
|
||||
port = int(row["entry_port"] or 0)
|
||||
prefix = f"/{'tachyon' if tachyon else 'access'}/{urllib.parse.quote(router_id, safe='')}"
|
||||
if tachyon:
|
||||
integration = router_tachyon(row)
|
||||
if not integration.get('installed'):
|
||||
self.send_text(404, 'Tachyon не обнаружен на этом роутере.')
|
||||
return
|
||||
if integration.get('mode') == 'standalone':
|
||||
port = int(row['tachyon_entry_port'] or 0)
|
||||
elif rest == '/':
|
||||
self.redirect(f"/access/{urllib.parse.quote(router_id, safe='')}/cgi-bin/luci/admin/services/tachyon")
|
||||
return
|
||||
if port <= 0:
|
||||
self.send_text(400, "router has no entry_port")
|
||||
return
|
||||
@@ -20737,7 +20881,7 @@ exit 127
|
||||
target += "?" + urllib.parse.urlencode(query)
|
||||
|
||||
is_static = self.command in ("GET", "HEAD") and is_luci_static_target(target)
|
||||
cache_key = static_cache_key(router_id, target) if is_static else None
|
||||
cache_key = static_cache_key(('tachyon:' if tachyon else '') + router_id, target) if is_static else None
|
||||
if cache_key:
|
||||
cached = static_cache_get(cache_key)
|
||||
if cached:
|
||||
@@ -20746,7 +20890,7 @@ exit 127
|
||||
self.send_raw_bytes(status, resp_body, content_type, resp_headers)
|
||||
return
|
||||
|
||||
body = self.read_body() if self.command in ("POST", "PUT", "PATCH") else None
|
||||
body = self.read_body() if self.command in ("POST", "PUT", "PATCH", "DELETE") else None
|
||||
headers = {}
|
||||
skip = {"host", "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "content-length", "accept-encoding"}
|
||||
for key, value in self.headers.items():
|
||||
@@ -20757,14 +20901,19 @@ exit 127
|
||||
if not value:
|
||||
continue
|
||||
elif key.lower() == "referer":
|
||||
value = rewrite_forward_url(value, router_id, port)
|
||||
if tachyon:
|
||||
parsed = urllib.parse.urlsplit(value)
|
||||
ref_path = parsed.path.removeprefix(prefix)
|
||||
value = urllib.parse.urlunsplit(('http', f'127.0.0.1:{port}', ref_path or '/', parsed.query, ''))
|
||||
else:
|
||||
value = rewrite_forward_url(value, router_id, port)
|
||||
elif key.lower() == "origin":
|
||||
value = f"http://127.0.0.1:{port}"
|
||||
headers[key] = value
|
||||
headers["Host"] = f"127.0.0.1:{port}"
|
||||
headers["Connection"] = "close"
|
||||
headers["X-Forwarded-Host"] = self.headers.get("Host", "")
|
||||
headers["X-Forwarded-Prefix"] = f"/access/{urllib.parse.quote(router_id)}"
|
||||
headers["X-Forwarded-Prefix"] = prefix
|
||||
headers["X-Forwarded-Proto"] = "http"
|
||||
if body is not None:
|
||||
headers["Content-Length"] = str(len(body))
|
||||
@@ -20802,7 +20951,6 @@ exit 127
|
||||
if last_exc is not None:
|
||||
raise last_exc
|
||||
resp_headers = []
|
||||
prefix = f"/access/{urllib.parse.quote(router_id)}"
|
||||
public_hosts = normalize_public_hosts(
|
||||
self.headers.get("Host", ""),
|
||||
self.app.public_url,
|
||||
@@ -20820,7 +20968,7 @@ exit 127
|
||||
if low == "location":
|
||||
value = rewrite_location(value, prefix, port)
|
||||
if low == "set-cookie":
|
||||
value = rewrite_cookie_path(value, "/")
|
||||
value = rewrite_cookie_path(value, prefix + '/' if tachyon else "/")
|
||||
resp_headers.append((key, value))
|
||||
if should_rewrite_body(content_type):
|
||||
resp_body = rewrite_html(resp_body, prefix, content_type, public_hosts)
|
||||
@@ -20832,7 +20980,7 @@ exit 127
|
||||
content_type or "application/octet-stream",
|
||||
static_cache_headers(resp_headers),
|
||||
)
|
||||
if not is_static:
|
||||
if not is_static and not tachyon:
|
||||
resp_headers.append(("Set-Cookie", current_router_cookie(router_id)))
|
||||
if is_static:
|
||||
self.send_raw_bytes(
|
||||
@@ -20885,6 +21033,7 @@ def proxy_runtime_script(prefix):
|
||||
(function() {
|
||||
const prefix = %s;
|
||||
const roots = ["/ubus", "/cgi-bin/luci", "/luci-static"];
|
||||
if (prefix.startsWith("/tachyon/")) roots.push("/api", "/login", "/cgi-bin/cgi-exec", "/cgi-bin/cgi-download", "/assets", "/favicon.ico");
|
||||
window.__owrtRemotePrefix = prefix;
|
||||
function fixUrl(url) {
|
||||
const original = url;
|
||||
@@ -21147,6 +21296,11 @@ def rewrite_html(body, prefix, content_type="", public_hosts=None):
|
||||
text = text.replace(old, new)
|
||||
text = rewrite_public_absolute_urls(text, prefix, public_hosts or [])
|
||||
text = rewrite_remaining_luci_roots(text, prefix)
|
||||
if prefix.startswith('/tachyon/'):
|
||||
# Match only the beginning of a quoted URL. Replacing every /login
|
||||
# would corrupt /api/login, and replacing every /api can corrupt IDs.
|
||||
text = re.sub(r"""(["'])(/(?:api|login|assets|favicon[.]ico|cgi-bin/cgi-exec|cgi-bin/cgi-download))(?=[/?#"'\\])""",
|
||||
lambda m: m[1] + prefix + m[2], text)
|
||||
text = restore_luci_resource_root(text, protected_resource_roots)
|
||||
if "text/html" in (content_type or "").lower():
|
||||
script = proxy_runtime_script(prefix)
|
||||
|
||||
Reference in new issue
Block a user