Fix mobile Xray settings paste in router panel

This commit is contained in:
kzolotarev95 committed 2026-10-14 00:22:22 +04:00
1 parent 8ac9f84078
commit 0508438de0
5 files changed
+357 -8

No files matched your search

+54 -4
View File
@@ -8,6 +8,7 @@ RESULT_TITLE=""
RESULT_BODY=""
RESULT_KIND="info"
SHOW_XRAY_SETTINGS="0"
XRAY_SETTINGS_DRAFT=""
cleanup() {
rm -f "$PARAMS_FILE"
@@ -172,11 +173,58 @@ clear_config() {
set_result "Конфигурация очищена" "Поля VPS, Xray, LuCI и SSH очищены. Router ID и название оставлены." "warn"
}
normalize_xray_settings() {
# Only repair mobile typography around a complete UCI assignment. Values
# already enclosed in shell quotes (including names/tokens) stay unchanged.
LC_ALL=C awk '
function shell_quote(value, result, i, char) {
result = "\047"
for (i = 1; i <= length(value); i++) {
char = substr(value, i, 1)
result = result (char == "\047" ? "\047\042\047\042\047" : char)
}
return result "\047"
}
function scan_quotes(line, i, char) {
for (i = 1; i <= length(line); i++) {
char = substr(line, i, 1)
if (quote != "\047" && char == "\\") { i++; continue }
if (!quote && char == "#" && (i == 1 || substr(line, i - 1, 1) ~ /[ \t;]/)) break
if (char == quote) quote = ""
else if (!quote && (char == "\047" || char == "\042")) quote = char
}
}
NR == 1 { sub(/^\357\273\277/, "") }
{
line = $0
# Arbitrary shell input may contain a heredoc or multiline string.
# Preserve it verbatim instead of interpreting payload as commands.
if (index(line, "<<")) literal = 1
position = index(line, "=")
prefix = substr(line, 1, position)
gsub(/\302\240|\342\200\257/, " ", prefix)
if (!quote && !literal && !continued && position && prefix ~ /^[ \t]*uci[ \t]+(-q[ \t]+)?set[ \t]+owrtremote\.main(\.[a-zA-Z0-9_]+)?=$/) {
value = substr(line, position + 1)
sub(/[ \t]+$/, "", value)
if (value ~ /^\342\200\230.*\342\200\231$/ || value ~ /^\342\200\234.*\342\200\235$/) {
line = prefix shell_quote(substr(value, 4, length(value) - 6))
} else {
line = prefix substr(line, position + 1)
}
}
print line
scan_quotes(line)
continued = (line ~ /\\$/)
}
'
}
apply_xray_settings() {
local script script_file output rc
# HTML textarea POSTs use CRLF, even when the copied Hub commands use LF.
# BusyBox ash treats the trailing CR as part of keywords such as then/fi.
script="$(param xray_settings_script | tr -d '\r')"
XRAY_SETTINGS_DRAFT="$(param xray_settings_script | tr -d '\r')"
script="$(printf '%s\n' "$XRAY_SETTINGS_DRAFT" | normalize_xray_settings)"
output="${TMPDIR:-/tmp}/owrt-remote-apply.$$"
script_file="${TMPDIR:-/tmp}/owrt-remote-apply-script.$$"
rc=0
@@ -206,11 +254,13 @@ rc=$rc" "bad"
fi
if sh -e "$script_file" >"$output" 2>&1; then
XRAY_SETTINGS_DRAFT=""
set_result "Xray настройки применены" "$(cat "$output")" "ok"
else
rc=$?
set_result "Ошибка применения Xray настроек" "$(cat "$output")
rc=$rc" "bad"
rc=$rc
Вставленные команды сохранены в поле ниже. Проверь полный блок OpenWrt config: каждая команда должна быть на отдельной строке." "bad"
fi
rm -f "$script_file" "$output"
}
@@ -475,11 +525,11 @@ EOF
<p class="helperText">Вставь сюда блок команд из OpenWrt config на VPS. Роутер сам применит UCI, пересоберет Xray config, включит сервис и отправит heartbeat.</p>
<form method="post">
<input type="hidden" name="key" value="$(h "$key")">
<textarea class="scriptBox" name="xray_settings_script" spellcheck="false" placeholder="uci -q delete owrtremote.main
<textarea class="scriptBox" name="xray_settings_script" wrap="soft" spellcheck="false" autocorrect="off" autocapitalize="off" autocomplete="off" placeholder="uci -q delete owrtremote.main
uci set owrtremote.main=remote
uci set owrtremote.main.enabled='1'
...
owrt-remote heartbeat"></textarea>
owrt-remote heartbeat">$(h "$XRAY_SETTINGS_DRAFT")</textarea>
<div class="actions">
<button class="btn good" name="action" value="apply_xray_settings">Применить настройки</button>
<button class="btn" name="action" value="show_xray_settings">Очистить поле</button>
+47
View File
@@ -52,3 +52,50 @@ python tests/test_xray_apply.py -v
```
Переносы строк в формах описаны в [стандарте HTML](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html).
## Мобильная вставка команд (локальный фикс v114)
Воспроизведён отдельный случай `rc=255`: в строке
`uci set owrtremote.main.router_name=‘Дом у моря’` типографские кавычки
не являются кавычками shell. UCI получает лишние аргументы, хотя `sh -n`
не находит ошибки. По одному коду нельзя утверждать, что это причина
конкретного сбоя на телефоне; необходима проверка исходного блока.
В поле команд отключены автокоррекция, автоматический регистр и
автозаполнение. Перед применением удаляется начальный UTF-8 BOM;
в отдельных строках `uci set owrtremote.main...` исправляются неразрывные
разделители и внешние парные типографские кавычки. Содержимое значения
экранируется как буквальная строка: `$`, обратные кавычки и апострофы
не становятся командами. Значения в обычных shell-кавычках, многострочные
строки и heredoc не переписываются. При ошибке вставленный текст остаётся
в поле; настоящие ошибки выполнения по-прежнему останавливают скрипт.
Дополнительные тесты проверяют воспроизведение `255`, исправление мобильной
типографики, сохранение Unicode-значений, отсутствие исполнения символов
из значения, экранирование текста ошибки в HTML и сохранение остановки
при настоящей ошибке UCI.
Обновляется только `/www/cgi-bin/owrt-remote` на роутере, без перезапуска
служб и изменений настроек при установке. Резервная копия отдельная:
`/root/owrt-remote-backup-before-xray-mobile-v114/owrt-remote`.
Установка из PowerShell Windows 11:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-mobile-fix.ps1" -Router "root@192.168.1.1" -Action Install
```
После `XRAY_MOBILE_ROUTER_Install_OK` обновите страницу на телефоне,
снова вставьте полный блок **OpenWrt config** и примените его.
Откат CGI (применённые через форму настройки остаются текущими):
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-mobile-fix.ps1" -Router "root@192.168.1.1" -Action Rollback
```
Проверки установки и отката выполняются на временных файлах без SSH:
```powershell
python tests/test_xray_mobile_deploy.py -v
```
+74 -4
View File
@@ -41,6 +41,15 @@ class XrayApplyPostTests(unittest.TestCase):
'#!/bin/sh\n[ "$1" != render-client ] || [ "${RENDER_FAIL:-0}" = 0 ] || exit 7\n'
'printf "%s\\n" "$*" >>"$TEST_ROOT/operations"\n', encoding="utf-8", newline="\n")
tools.joinpath("owrt-remote").chmod(0o755)
tools.joinpath("uci").write_text(
'#!/bin/sh\n[ "$1" != -q ] || shift\n'
'[ "$#" = 2 ] || exit 255\n'
'case "$1" in\n'
' get) exit 1 ;;\n'
' set) printf "%s\\n" "$2" >>"$TEST_ROOT/uci-values" ;;\n'
' commit) printf "commit\\n" >>"$TEST_ROOT/operations" ;;\n'
' *) exit 255 ;;\nesac\n', encoding="utf-8", newline="\n")
tools.joinpath("uci").chmod(0o755)
self.env = {**os.environ, "TMPDIR": self.directory.as_posix(),
"TEST_ROOT": self.directory.as_posix(), "KEY_FILE": (self.directory / "key").as_posix(),
"TEST_STRICT_SH": Path(STRICT_SH).as_posix()}
@@ -59,20 +68,81 @@ sh() {
fi
"$TEST_STRICT_SH" "$@"
}
render_page() { printf 'KIND=%s\nTITLE=%s\nBODY=%s\n' "$RESULT_KIND" "$RESULT_TITLE" "$RESULT_BODY"; }
render_page() { printf 'KIND=%s\nTITLE=%s\nBODY=%s\nDRAFT=%s\n' "$RESULT_KIND" "$RESULT_TITLE" "$RESULT_BODY" "$XRAY_SETTINGS_DRAFT"; }
'''
self.cgi = self.directory / "cgi"
self.cgi.write_text(cgi.replace("\nread_request\n", mocks + "\nread_request\n", 1), encoding="utf-8", newline="\n")
self.render_cgi = self.directory / "render-cgi"
template = cgi.split('\tif [ "$SHOW_XRAY_SETTINGS" = "1" ]; then\n', 1)[1].split('\n\tfi\n', 1)[0]
render = '\nrender_page() {\nkey="$(param key)"\n' + template + '\n}\n'
self.render_cgi.write_text(cgi.replace("\nread_request\n", render + "\nread_request\n", 1), encoding="utf-8", newline="\n")
def post(self, script, key="test-web-key"):
body = urlencode({"key": key, "action": "apply_xray_settings", "xray_settings_script": script}).encode("ascii")
result = subprocess.run([SH, self.cgi.as_posix()], input=body, capture_output=True,
def post(self, script, key="test-web-key", render=False, action="apply_xray_settings"):
body = urlencode({"key": key, "action": action, "xray_settings_script": script}).encode("ascii")
result = subprocess.run([SH, (self.render_cgi if render else self.cgi).as_posix()], input=body, capture_output=True,
env={**self.env, "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded",
"CONTENT_LENGTH": str(len(body))}, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr.decode("utf-8", errors="replace"))
self.assertFalse(list(self.directory.glob("owrt-remote-*")), "CGI temporary files must be removed")
return result.stdout.decode("utf-8")
def test_mobile_smart_quotes_reproduce_uci_255_and_are_repaired(self):
script = 'uci set owrtremote.main.router_name=‘Дом у моря’\nuci commit owrtremote\n'
# UCI returns 255 for too many arguments; shell syntax validation alone
# accepts these typography quotes and splits the name into three words.
broken = self.directory / "broken.sh"
broken.write_text(script, encoding="utf-8", newline="\n")
result = subprocess.run([STRICT_SH, "-e", broken.as_posix()], env=self.env, capture_output=True)
self.assertEqual(result.returncode, 255)
response = self.post(script.replace("\n", "\r\n"))
self.assertIn("KIND=ok", response)
self.assertEqual(self.directory.joinpath("uci-values").read_text(encoding="utf-8"),
"owrtremote.main.router_name=Дом у моря\n")
def test_mobile_quotes_bom_and_nonbreaking_separators(self):
script = '\ufeffuci\u00a0-q\u202fset\u00a0owrtremote.main.router_name=“Папа\'s $HOME `id` & дом”\r\n'
self.assertIn("KIND=ok", self.post(script))
self.assertEqual(self.directory.joinpath("uci-values").read_text(encoding="utf-8"),
"owrtremote.main.router_name=Папа's $HOME `id` & дом\n")
def test_ascii_shell_quotes_preserve_unicode_values(self):
value = "Дом ‘у моря’\u00a0— “офис”\u202f+ 100% & $HOME `id`"
script = "uci set owrtremote.main.router_name='" + value + "'\n"
self.assertIn("KIND=ok", self.post(script))
self.assertEqual(self.directory.joinpath("uci-values").read_text(encoding="utf-8"),
"owrtremote.main.router_name=" + value + "\n")
self.assertEqual(self.directory.joinpath("executed.sh").read_text(encoding="utf-8"),
"#!/bin/sh\n" + script)
def test_genuine_uci_error_is_not_reported_as_success_and_keeps_draft(self):
script = 'uci set owrtremote.main.router_name=broken name\nuci commit owrtremote\n'
response = self.post(script)
self.assertIn("KIND=bad", response)
self.assertIn("rc=255", response)
self.assertIn("DRAFT=" + script.rstrip("\n"), response)
self.assertFalse(self.directory.joinpath("operations").exists())
def test_mobile_form_disables_text_rewriting_and_escapes_failed_draft(self):
# Render the actual CGI textarea template on an unsuccessful POST.
script = "printf '%s' '</textarea><script>bad</script>&'\nexit 255\n"
response = self.post(script, render=True)
self.assertIn('autocorrect="off" autocapitalize="off" autocomplete="off"', response)
self.assertIn('wrap="soft" spellcheck="false"', response)
self.assertIn("&lt;/textarea&gt;&lt;script&gt;bad&lt;/script&gt;&amp;", response)
self.assertNotIn("</textarea><script>bad</script>", response)
cleared = self.post(script, render=True, action="show_xray_settings")
self.assertNotIn("&lt;script&gt;bad&lt;/script&gt;", cleared)
def test_uci_looking_lines_in_multiline_values_and_heredocs_stay_literal(self):
value = 'before\nuci set owrtremote.main.router_name=‘Дом у моря’\nafter\n'
for script in ("printf '%s' '" + value + "' >\"$TEST_ROOT/literal\"\n",
'cat >"$TEST_ROOT/literal" <<\'EOF\'\n' + value + 'EOF\n'):
with self.subTest(script=script):
self.assertIn("KIND=ok", self.post(script))
self.assertEqual(self.directory.joinpath("executed.sh").read_bytes(),
("#!/bin/sh\n" + script).encode("utf-8"))
self.assertFalse(self.directory.joinpath("uci-values").exists())
def test_form_crlf_is_normalized_before_strict_shell_parsing(self):
script = "if [ x = x ]; then\n printf '%s' 'name + percent% & quote\"'\nfi\n"
response = self.post(script.replace("\n", "\r\n"))
+91
View File
@@ -0,0 +1,91 @@
"""Exercise CGI deployment/rollback with temporary files, never a real router."""
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
GIT_BIN = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "Git/usr/bin"
SH = shutil.which("sh")
if os.name == "nt" and (GIT_BIN / "sh.exe").exists():
SH = str(GIT_BIN / "sh.exe")
@unittest.skipUnless(SH, "A POSIX shell is required")
class XrayMobileDeploymentTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="owrt-mobile-deploy-")
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.target = self.root / "cgi"
self.target.write_text("#!/bin/sh\necho previous\n", encoding="utf-8", newline="\n")
self.backup_dir = self.root / "backup"
self.env = {**os.environ}
if os.name == "nt":
self.env["PATH"] = str(GIT_BIN) + os.pathsep + self.env["PATH"]
source = (ROOT / "vps/deploy-xray-mobile-fix.ps1").read_text(encoding="utf-8")
self.script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
self.script = self.script.replace("target=/www/cgi-bin/owrt-remote", "target=" + shlex.quote(self.target.as_posix()))
self.script = self.script.replace("backup_dir=/root/owrt-remote-backup-before-xray-mobile-v114",
"backup_dir=" + shlex.quote(self.backup_dir.as_posix()))
def deploy(self, action, content=None, fail_verify=False):
stage = self.root / "stage"
stage.mkdir()
if content is not None:
stage.joinpath("cgi").write_text(content, encoding="utf-8", newline="\n")
script = self.script.replace("stage=/tmp/__UPLOAD_NAME__", "stage=" + shlex.quote(stage.as_posix()))
script = script.replace("__ACTION__", action).replace("__UPLOAD_NAME__", "local-test")
if fail_verify:
script = script.replace('cmp "$source_file" "$target"', 'false')
result = subprocess.run([SH], input=script, encoding="utf-8", capture_output=True, env=self.env, timeout=20)
self.assertFalse(stage.exists(), "Staging files should be cleaned")
self.assertFalse(list(self.root.glob("cgi.new-*")))
return result
def test_install_then_rollback_preserve_first_backup(self):
previous = self.target.read_bytes()
content = (ROOT / "files/www/cgi-bin/owrt-remote").read_text(encoding="utf-8")
for attempt in range(2):
with self.subTest(attempt=attempt):
result = self.deploy("Install", content)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("XRAY_MOBILE_ROUTER_Install_OK", result.stdout)
self.assertEqual(self.target.read_bytes(), content.encode("utf-8"))
self.assertEqual(self.backup_dir.joinpath("owrt-remote").read_bytes(), previous)
result = self.deploy("Rollback")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("XRAY_MOBILE_ROUTER_Rollback_OK", result.stdout)
self.assertEqual(self.target.read_bytes(), previous)
def test_missing_backup_is_explained_without_changes(self):
previous = self.target.read_bytes()
result = self.deploy("Rollback")
self.assertNotEqual(result.returncode, 0)
self.assertIn("No backup on this router:", result.stderr)
self.assertIn("Nothing changed.", result.stderr)
self.assertEqual(self.target.read_bytes(), previous)
def test_invalid_candidate_is_rejected_before_backup_or_changes(self):
previous = self.target.read_bytes()
result = self.deploy("Install", "#!/bin/sh\nif true; then\n")
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed during preflight", result.stderr)
self.assertFalse(self.backup_dir.exists())
self.assertEqual(self.target.read_bytes(), previous)
def test_failed_verification_restores_previous_file(self):
previous = self.target.read_bytes()
content = (ROOT / "files/www/cgi-bin/owrt-remote").read_text(encoding="utf-8")
result = self.deploy("Install", content, fail_verify=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn("Failed during verify", result.stderr)
self.assertIn("Restoring the CGI", result.stderr)
self.assertEqual(self.target.read_bytes(), previous)
if __name__ == "__main__":
unittest.main()
+91
View File
@@ -0,0 +1,91 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Router,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-mobile-' + [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=/www/cgi-bin/owrt-remote
backup_dir=/root/owrt-remote-backup-before-xray-mobile-v114
backup=$backup_dir/owrt-remote
candidate=$target.new-__UPLOAD_NAME__
changed=0
phase=preflight
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 CGI from this attempt.' >&2
cp -p "$stage/previous" "$candidate"
mv -f "$candidate" "$target"
fi
fi
rm -f "$candidate"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
if [ '__ACTION__' = Install ]; then
test -s "$stage/cgi"
sh -n "$stage/cgi"
grep -F -q 'normalize_xray_settings()' "$stage/cgi"
grep -F -q 'autocorrect="off" autocapitalize="off"' "$stage/cgi"
phase=backup
mkdir -p "$backup_dir"
chmod 700 "$backup_dir"
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
test -s "$backup"
source_file=$stage/cgi
else
if [ ! -s "$backup" ]; then
printf 'No backup on this router: %s. Nothing changed.\n' "$backup" >&2
exit 1
fi
sh -n "$backup"
source_file=$backup
fi
printf 'Backup: %s\n' "$backup"
cp -p "$target" "$stage/previous"
phase=install
cp "$source_file" "$candidate"
chmod 755 "$candidate"
changed=1
mv -f "$candidate" "$target"
phase=verify
sh -n "$target"
cmp "$source_file" "$target"
printf '\nXRAY_MOBILE_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') {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot 'files\www\cgi-bin\owrt-remote')).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'cgi'), $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 "Router CGI $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 }
}
}