+
+
+
+BYDLO apt repository
+
+
+BYDLO apt repository
+Подписанный репозиторий apt для Debian, Ubuntu и производных. Пакеты: amd64 и arm64.
+
+Инструкция подключения: docs/LINUX.md.
+
+
+EOF
+
+echo "apt repository: $output"
+echo "suite: $suite, component: $component, architectures: ${architectures[*]}"
+echo "signing key: $key"
diff --git a/scripts/test-apt-repository.sh b/scripts/test-apt-repository.sh
new file mode 100644
index 00000000..48c5fbb5
--- /dev/null
+++ b/scripts/test-apt-repository.sh
@@ -0,0 +1,139 @@
+#!/usr/bin/env bash
+# Synthetic regression for scripts/build-apt-repository.sh (issue #488).
+# Builds a repository from fake .deb files with a throwaway key generated inside this script, then
+# checks the structure, the checksums and the signature. Never installs a package, never runs apt,
+# never touches /etc and never uses the network.
+set -euo pipefail
+
+# shellcheck source=scripts/env.sh
+source "$(dirname "${BASH_SOURCE[0]}")/env.sh"
+
+case "$(uname -s)" in
+ MINGW*|MSYS*|CYGWIN*)
+ echo "apt repository regression skipped: needs dpkg-dev and gnupg (Linux only)"
+ exit 0
+ ;;
+esac
+
+for tool in dpkg-deb dpkg-scanpackages gpg gpgv sha256sum; do
+ command -v "$tool" > /dev/null ||
+ { echo "apt repository regression: $tool not found (install dpkg-dev and gnupg)" >&2; exit 1; }
+done
+
+fail() { echo "apt repository regression: $*" >&2; exit 1; }
+
+fixture=$(mktemp -d "$BYDLO_ROOT/.tmp/apt-repository-XXXXXXXX")
+trap 'rm -rf "$fixture"' EXIT
+
+# A throwaway key: nothing here is trusted by any client and it never leaves the fixture.
+export GNUPGHOME="$fixture/gnupg"
+install -d -m 0700 "$GNUPGHOME"
+gpg --batch --quiet --pinentry-mode loopback --passphrase '' \
+ --quick-generate-key 'BYDLO apt regression ' rsa3072 sign 1d
+
+make_deb() {
+ local arch=$1 version=$2 root="$fixture/deb-$1"
+ install -d "$root/DEBIAN" "$root/opt/bydlo"
+ printf 'synthetic payload for %s\n' "$arch" > "$root/opt/bydlo/BYDLO"
+ cat > "$root/DEBIAN/control" <
+Section: net
+Priority: optional
+Description: synthetic package for the apt repository regression
+EOF
+ dpkg-deb --root-owner-group -Zxz --build "$root" "$fixture/debs/bydlo_${version}_${arch}.deb" > /dev/null
+}
+
+install -d "$fixture/debs"
+make_deb amd64 0.4.3
+make_deb arm64 0.4.3
+# Anything that is not a .deb must be ignored instead of indexed.
+printf 'not a package\n' > "$fixture/debs/README.txt"
+
+bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/debs" "$fixture/site"
+
+release_dir="$fixture/site/dists/stable"
+for file in "$release_dir/Release" "$release_dir/Release.gpg" "$release_dir/InRelease" \
+ "$fixture/site/bydlo.gpg" "$fixture/site/bydlo.gpg.asc" "$fixture/site/bydlo.gpg.fingerprint"; do
+ [[ -s $file ]] || fail "missing $(basename "$file")"
+done
+
+# Every index listed in Release must match its size and SHA-256.
+release_checksums_ok() {
+ local dir=$1
+ ( cd "$dir" && awk '/^SHA256:/ {flag=1; next} /^[A-Za-z]/ {flag=0} flag && NF==3 {print $1" "$3}' Release ) |
+ ( cd "$dir" && sha256sum -c --strict --quiet - ) > /dev/null 2>&1
+}
+release_checksums_ok "$release_dir" || fail "Release checksums do not match the index files"
+
+# apt verifies with gpgv against the installed keyring, so check exactly that path first.
+gpgv --keyring "$fixture/site/bydlo.gpg" "$release_dir/InRelease" > /dev/null 2>&1 ||
+ fail "InRelease does not verify with the published keyring"
+gpgv --keyring "$fixture/site/bydlo.gpg" "$release_dir/Release.gpg" "$release_dir/Release" > /dev/null 2>&1 ||
+ fail "Release.gpg does not verify with the published keyring"
+
+# The armored copy must carry the same key, so a user can compare the fingerprint by hand.
+export GNUPGHOME="$fixture/verify"
+install -d -m 0700 "$GNUPGHOME"
+gpg --batch --quiet --import "$fixture/site/bydlo.gpg.asc"
+fingerprint=$(gpg --batch --with-colons --fingerprint | awk -F: '/^fpr:/ {print $10; exit}')
+[[ $(cat "$fixture/site/bydlo.gpg.fingerprint") == "$fingerprint" ]] ||
+ fail "bydlo.gpg.fingerprint does not match the published key"
+
+for arch in amd64 arm64; do
+ packages="$release_dir/main/binary-$arch/Packages"
+ [[ -s $packages ]] || fail "missing Packages for $arch"
+ [[ -s "${packages}.gz" ]] || fail "missing Packages.gz for $arch"
+ grep -qx 'Package: bydlo' "$packages" || fail "Packages for $arch does not list bydlo"
+ grep -qx "Architecture: $arch" "$packages" || fail "Packages for $arch has the wrong Architecture"
+ grep -qx 'Version: 0.4.3' "$packages" || fail "Packages for $arch has the wrong Version"
+ filename=$(awk '/^Filename:/ {print $2}' "$packages")
+ [[ $filename == "pool/main/b/bydlo/bydlo_0.4.3_$arch.deb" ]] ||
+ fail "Packages for $arch has an unexpected Filename: $filename"
+ [[ -f "$fixture/site/$filename" ]] || fail "Packages for $arch points at a missing file: $filename"
+ expected=$(awk '/^SHA256:/ {print $2}' "$packages")
+ actual=$(sha256sum "$fixture/site/$filename" | cut -d' ' -f1)
+ [[ $expected == "$actual" ]] || fail "Packages for $arch has a wrong SHA256 for $filename"
+done
+
+# The checks must be able to fail: a modified index and a modified signature are both rejected.
+cp "$release_dir/main/binary-amd64/Packages" "$fixture/Packages.orig"
+printf '\n' >> "$release_dir/main/binary-amd64/Packages"
+if release_checksums_ok "$release_dir"; then fail "a modified Packages file was accepted"; fi
+cp "$fixture/Packages.orig" "$release_dir/main/binary-amd64/Packages"
+release_checksums_ok "$release_dir" || fail "restoring Packages did not restore the checksums"
+
+sed 's/^Date: .*/Date: Thu, 01 Jan 1970 00:00:00 UTC/' "$release_dir/InRelease" > "$fixture/InRelease.tampered"
+if gpg --batch --verify "$fixture/InRelease.tampered" > /dev/null 2>&1; then
+ fail "a modified InRelease was accepted"
+fi
+
+# Rotation: the new key signs while the old key stays published for one transition release.
+export GNUPGHOME="$fixture/gnupg"
+gpg --batch --quiet --pinentry-mode loopback --passphrase '' \
+ --quick-generate-key 'BYDLO apt regression next ' rsa3072 sign 1d
+next=$(gpg --batch --with-colons --list-secret-keys 'BYDLO apt regression next' | awk -F: '/^fpr:/ {print $10; exit}')
+previous=$(gpg --batch --with-colons --list-secret-keys 'BYDLO apt regression <' | awk -F: '/^fpr:/ {print $10; exit}')
+bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/debs" "$fixture/rotated" \
+ --key "$next" --extra-key "$previous"
+gpgv --keyring "$fixture/rotated/bydlo.gpg" "$fixture/rotated/dists/stable/InRelease" > /dev/null 2>&1 ||
+ fail "the rotated keyring does not verify InRelease"
+grep -qx "$previous" "$fixture/rotated/bydlo.gpg.fingerprint" || fail "the old key is missing from the rotated keyring"
+grep -qx "$next" "$fixture/rotated/bydlo.gpg.fingerprint" || fail "the new key is missing from the rotated keyring"
+
+# Two files for one version and architecture would make Packages ambiguous.
+cp "$fixture/debs/bydlo_0.4.3_amd64.deb" "$fixture/debs/bydlo_0.4.3_amd64-copy.deb"
+if bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/debs" "$fixture/duplicate" > /dev/null 2>&1; then
+ fail "a duplicate package version was accepted"
+fi
+rm "$fixture/debs/bydlo_0.4.3_amd64-copy.deb"
+
+install -d "$fixture/empty"
+if bash "$BYDLO_ROOT/scripts/build-apt-repository.sh" "$fixture/empty" "$fixture/empty-site" > /dev/null 2>&1; then
+ fail "an input directory without .deb files was accepted"
+fi
+
+echo "apt repository regression passed: amd64 + arm64, signed Release/InRelease verified"
diff --git a/src/Bydlo.App/App.axaml.cs b/src/Bydlo.App/App.axaml.cs
index 07c92534..a2bc26f3 100644
--- a/src/Bydlo.App/App.axaml.cs
+++ b/src/Bydlo.App/App.axaml.cs
@@ -106,6 +106,9 @@ public override void OnFrameworkInitializationCompleted()
else if (ApplicationLifetime is ISingleViewApplicationLifetime single)
{
single.MainView = new MainView { DataContext = shell };
+ // No window event on this head: the view exists, so the readiness confirmation can run (issue #412).
+ Services.ConfirmUpdateReadiness();
+ shell.ShowUpdateRecoveryToast();
}
base.OnFrameworkInitializationCompleted();
diff --git a/src/Bydlo.App/Assets/Strings/en.json b/src/Bydlo.App/Assets/Strings/en.json
index 9e887e8d..1c8e3fa9 100644
--- a/src/Bydlo.App/Assets/Strings/en.json
+++ b/src/Bydlo.App/Assets/Strings/en.json
@@ -1,4 +1,6 @@
{
+ "tools.zapret.helper.hint": "Zapret needs a privileged service. Installing it stops BYDLO connections and requests administrator approval (PolKit on Linux). After installation, Zapret starts automatically; the app continues without root rights.",
+ "tools.zapret.helper.install": "Install service and start Zapret",
"connections.search": "Find by name, host or protocol",
"connections.search.empty": "No servers match your search.",
"connections.actions": "Server actions",
@@ -358,6 +360,7 @@
"chain.empty": "No chains yet. Combine two or more servers into a relay.",
"chain.new": "New chain",
"chain.edit": "Edit chain",
+ "chain.actions": "Chain actions",
"chain.name": "Chain name",
"chain.hops": "Servers in order",
"chain.add.hop": "Add server",
@@ -495,6 +498,9 @@
"tools.tg.cfdomains": "Own Cloudflare domains (optional)",
"tools.tg.cfdomains.hint": "One domain per line. Empty: the list maintained by Flowseal, refreshed every hour.",
"tools.tg.verbose": "Verbose logging",
+ "tools.tg.proxyprotocol": "PROXY protocol v1 header from a reverse proxy",
+ "tools.tg.proxyprotocol.sources": "Trusted header sources",
+ "tools.tg.proxyprotocol.sources.hint": "One IP address per line. Empty: loopback only (127.0.0.1, ::1). Only these peers may send the header; bytes from anyone else are read as normal client data. For nginx or HAProxy with proxy_protocol on.",
"tools.tg.runtime.builtin": "Built-in engine: no Python or extra downloads needed.",
"tools.tg.badport": "Port must be between 1 and 65535.",
"tools.tg.notelegram": "Telegram did not open. Copy the link and send it to yourself in Telegram.",
@@ -574,6 +580,10 @@
"settings.appearance": "Appearance",
"settings.theme": "Theme",
+ "settings.scale": "Interface scale",
+ "settings.scale.hint": "Scales text, buttons, fields, paddings and icons together. 100% matches the system DPI; the system scale is applied on top of this value.",
+ "settings.scale.reset": "Reset to 100%",
+ "settings.scale.reset.done": "Interface scale reset to 100%.",
"settings.language": "Language",
"theme.light": "Light",
"theme.oled": "Black",
@@ -729,6 +739,7 @@
"error.engine.tg.platform": "TgWsProxy is not available on this platform yet.",
"error.engine.tg.secret": "The TgWsProxy secret is missing or invalid. Generate a new one in Tools → TgWsProxy.",
"error.engine.tg.dcip": "Invalid DC → IP line. Use the DC:IP format, for example 4:149.154.167.220.",
+ "error.engine.tg.proxyprotocol": "Invalid trusted PROXY protocol source. Use an IP address, for example 127.0.0.1.",
"error.engine.singbox.platform": "sing-box on this platform is planned (VpnService integration).",
"error.engine.singbox.missing": "sing-box is not installed. Install it from Tools → Engines.",
"error.engine.tun.admin": "TUN mode needs administrator rights. Restart BYDLO as administrator or use Local proxy mode.",
@@ -773,12 +784,18 @@
"settings.update.auto.unavailable": "Unavailable for this copy: it was started from an archive or in Mock Mode. Install the Setup.exe build to update automatically.",
"settings.update.deferred": "The update is downloaded but postponed. It installs on the next exit after every connection stops.",
"settings.update.manual.deb": "BYDLO was installed from a .deb package, so your package manager owns it. Download the new .deb from the release page and install it with sudo apt install ./bydlo__amd64.deb. No apt repository is configured, so apt upgrade alone will not find new versions.",
+ "settings.update.manual.deb.repository": "BYDLO was installed from a .deb package and the BYDLO apt repository is configured, so apt owns it. Update it with sudo apt update && sudo apt upgrade. The built-in updater never changes files owned by dpkg.",
"settings.update.manual.arch": "BYDLO was installed from an Arch package, so pacman owns it. Update it with your AUR helper (for example yay -S bydlo-bin) or rebuild the package. The built-in updater never changes files owned by pacman.",
"settings.update.manual.nix": "BYDLO was installed from the Nix flake, so Nix owns it. Update it with nix profile upgrade or by rebuilding your NixOS configuration.",
"settings.update.manual.portable": "This copy runs from a portable folder or an old ZIP release. To update, quit BYDLO completely, replace the whole folder with the new release and keep your data directory. Automatic migration to an installed build is not provided.",
"settings.update.manual.unknown": "This copy was not installed by a supported package, so automatic updates are unavailable. Install a release package to receive updates.",
"settings.update.detail.unavailable": "This copy runs from an archive and cannot update itself. Install the Setup.exe build to receive updates.",
"settings.update.detail.consent": "Automatic updates are off. Allow them under GitHub access.",
+ "settings.update.recovery.blocked": "The last update did not confirm readiness. Automatic updates are paused until you download an update manually.",
+ "settings.update.recovery.previous": "The installer kept the previous package in the installation folder, so a return to the previous version is possible without downloading it again. BYDLO does not run that rollback automatically: reinstall the previous release from the release page.",
+ "settings.update.recovery.manual": "The previous package is not kept on this platform, so returning to the working version requires a manual reinstall from the release page.",
+ "update.recovery.blocked": "The last update did not confirm readiness. Automatic updates are paused; BYDLO {0} is running. Settings or profiles that could not be read were restored from the snapshot taken before the update.",
+ "update.recovery.interrupted": "The update was interrupted before it replaced any files. BYDLO {0} is still running; download the update again to retry.",
"update.trust.catalog": "The update catalog could not be verified, so nothing was installed. The current version is kept.",
"update.trust.expired": "The update catalog has expired or the system clock is wrong, so nothing was installed. Check the date and time and try again.",
"update.trust.unsupported": "This update is not offered for your platform or channel, so nothing was installed. The current version is kept.",
@@ -827,7 +844,7 @@
"tools.select.warning": "Takes several minutes and temporarily enables Zapret. Administrator/root rights are required. You can cancel; the original state is restored before applying a result.",
"tools.select.brief": "Success {0}, errors {1}, timeouts {2}, unknown {3}",
"tools.select.curl": "curl is missing or incompatible. Install curl with HTTP/TLS support and retry.",
- "tools.select.details": "Takes several minutes and temporarily enables Zapret. Administrator/root rights are required. Tests each BAT configuration or native preset twice with the Test Zapret 1.10.3 standard HTTP/TLS suite. Results describe only these URLs and HTTP/TLS checks, not video playback, Discord voice, UDP or the whole BAT script. The original running configuration is restored before you apply a result.",
+ "tools.select.details": "Takes several minutes and temporarily enables Zapret. Administrator/root rights are required. Tests each BAT configuration or native preset twice with the Test Zapret 1.10.4 standard HTTP/TLS suite. Results describe only these URLs and HTTP/TLS checks, not video playback, Discord voice, UDP or the whole BAT script. The original running configuration is restored before you apply a result.",
"tools.select.scope": "What is tested",
"tools.startup.title": "Saved strategy check",
"tools.startup.scope": "Checks only the remembered strategy with the Test Zapret HTTP/TLS suite (HTTP, TLS 1.2, TLS 1.3). Other strategies are never started. Success here does not prove that video playback, voice chat or UDP work.",
diff --git a/src/Bydlo.App/Assets/Strings/ru.json b/src/Bydlo.App/Assets/Strings/ru.json
index 369b7e22..7033c5d6 100644
--- a/src/Bydlo.App/Assets/Strings/ru.json
+++ b/src/Bydlo.App/Assets/Strings/ru.json
@@ -1,4 +1,6 @@
{
+ "tools.zapret.helper.hint": "Для Zapret нужна привилегированная служба. Её установка остановит подключения BYDLO и запросит подтверждение администратора (PolKit на Linux). После установки Zapret запустится автоматически; приложение продолжит работать без root-прав.",
+ "tools.zapret.helper.install": "Установить службу и запустить Zapret",
"connections.search": "Поиск по имени, адресу или протоколу",
"connections.search.empty": "Серверы по этому запросу не найдены.",
"connections.actions": "Действия с сервером",
@@ -358,6 +360,7 @@
"chain.empty": "Цепочек пока нет. Объедините два или более серверов в relay.",
"chain.new": "Новая цепочка",
"chain.edit": "Изменить цепочку",
+ "chain.actions": "Действия с цепочкой",
"chain.name": "Название цепочки",
"chain.hops": "Серверы по порядку",
"chain.add.hop": "Добавить сервер",
@@ -495,6 +498,9 @@
"tools.tg.cfdomains": "Свои домены Cloudflare (необязательно)",
"tools.tg.cfdomains.hint": "Один домен на строку. Пусто — список Flowseal, обновляется раз в час.",
"tools.tg.verbose": "Подробные логи",
+ "tools.tg.proxyprotocol": "Заголовок PROXY protocol v1 от reverse proxy",
+ "tools.tg.proxyprotocol.sources": "Доверенные источники заголовка",
+ "tools.tg.proxyprotocol.sources.hint": "Один IP-адрес на строку. Пусто — только loopback (127.0.0.1, ::1). Заголовок принимается только от этих адресов, байты остальных читаются как обычные данные клиента. Для nginx или HAProxy с включённым proxy_protocol.",
"tools.tg.runtime.builtin": "Встроенный движок: Python и дополнительные загрузки не нужны.",
"tools.tg.badport": "Порт должен быть от 1 до 65535.",
"tools.tg.notelegram": "Telegram не открылся. Скопируйте ссылку и отправьте её себе в «Избранное».",
@@ -574,6 +580,10 @@
"settings.appearance": "Внешний вид",
"settings.theme": "Тема",
+ "settings.scale": "Масштаб интерфейса",
+ "settings.scale.hint": "Увеличивает текст, кнопки, поля, отступы и значки одновременно. 100% соответствует системному DPI; системный масштаб применяется поверх этого значения.",
+ "settings.scale.reset": "Сбросить до 100%",
+ "settings.scale.reset.done": "Масштаб интерфейса сброшен до 100%.",
"settings.language": "Язык",
"theme.light": "Светлая",
"theme.oled": "Чёрная",
@@ -730,6 +740,7 @@
"error.engine.tg.platform": "TgWsProxy пока недоступен на этой платформе.",
"error.engine.tg.secret": "Секрет TgWsProxy отсутствует или повреждён. Создайте новый в «Инструменты → TgWsProxy».",
"error.engine.tg.dcip": "Неверная строка DC → IP. Формат DC:IP, например 4:149.154.167.220.",
+ "error.engine.tg.proxyprotocol": "Неверный доверенный источник PROXY protocol. Укажите IP-адрес, например 127.0.0.1.",
"error.engine.singbox.platform": "Поддержка sing-box на этой платформе запланирована (интеграция VpnService).",
"error.engine.singbox.missing": "sing-box не установлен. Установите его в «Инструменты → Движки».",
"error.engine.tun.admin": "Для режима TUN нужны права администратора. Перезапустите BYDLO от имени администратора или используйте режим локального прокси.",
@@ -774,10 +785,16 @@
"settings.update.auto.unavailable": "Недоступно для этой копии: она запущена из архива или в Mock-режиме. Установите сборку из Setup.exe для автоматических обновлений.",
"settings.update.deferred": "Обновление скачано, но отложено. Оно установится при следующем выходе после остановки всех подключений.",
"settings.update.manual.deb": "BYDLO установлен из пакета .deb, поэтому обновлением управляет пакетный менеджер. Скачайте новый .deb со страницы релиза и установите его командой sudo apt install ./bydlo_<версия>_amd64.deb. Репозиторий apt для BYDLO не настраивается, поэтому apt upgrade сам новые версии не найдёт.",
+ "settings.update.manual.deb.repository": "BYDLO установлен из пакета .deb, и репозиторий apt для BYDLO подключён, поэтому обновлением управляет apt. Обновите командой sudo apt update && sudo apt upgrade. Встроенное обновление не меняет файлы, которыми управляет dpkg.",
"settings.update.manual.arch": "BYDLO установлен из пакета Arch, поэтому обновлением управляет pacman. Обновите пакет помощником AUR (например, yay -S bydlo-bin) или пересоберите пакет. Встроенное обновление не меняет файлы, которыми управляет pacman.",
"settings.update.manual.nix": "BYDLO установлен из flake Nix, поэтому обновлением управляет Nix. Обновите его командой nix profile upgrade или пересборкой конфигурации NixOS.",
"settings.update.manual.portable": "Эта копия запущена из переносимой папки или старого ZIP-архива. Чтобы обновиться, полностью закройте BYDLO, замените всю папку новой версией и сохраните каталог данных. Автоматического перехода на установленную сборку нет.",
"settings.update.manual.unknown": "Эта копия не установлена поддерживаемым пакетом, поэтому автоматические обновления недоступны. Установите пакет из релиза, чтобы получать обновления.",
+ "settings.update.recovery.blocked": "Последнее обновление не подтвердило готовность. Автоматические обновления приостановлены, пока вы не скачаете обновление вручную.",
+ "settings.update.recovery.previous": "Установщик сохранил предыдущий пакет в каталоге установки, поэтому вернуться к предыдущей версии можно без повторной загрузки. BYDLO не выполняет такой откат автоматически: переустановите предыдущий релиз со страницы релизов.",
+ "settings.update.recovery.manual": "На этой платформе предыдущий пакет не сохраняется, поэтому для возврата к рабочей версии нужна ручная переустановка со страницы релизов.",
+ "update.recovery.blocked": "Последнее обновление не подтвердило готовность. Автоматические обновления приостановлены; работает BYDLO {0}. Настройки или профили, которые не удалось прочитать, восстановлены из снимка, сделанного перед обновлением.",
+ "update.recovery.interrupted": "Обновление прервалось до замены файлов. Работает BYDLO {0}; чтобы повторить, скачайте обновление снова.",
"update.trust.catalog": "Не удалось проверить каталог обновлений, поэтому ничего не установлено. Текущая версия сохранена.",
"update.trust.expired": "Срок действия каталога обновлений истёк или системные часы неверны, поэтому ничего не установлено. Проверьте дату и время и повторите попытку.",
"update.trust.unsupported": "Это обновление не предлагается для вашей платформы или канала, поэтому ничего не установлено. Текущая версия сохранена.",
@@ -826,7 +843,7 @@
"tools.select.warning": "Займёт несколько минут и временно включит Zapret. Нужны права администратора/root. Можно отменить; перед применением результата исходное состояние восстанавливается.",
"tools.select.brief": "Успехи {0}, ошибки {1}, таймауты {2}, неизвестно {3}",
"tools.select.curl": "curl отсутствует или несовместим. Установите curl с поддержкой HTTP/TLS и повторите подбор.",
- "tools.select.details": "Займёт несколько минут и временно включит Zapret. Нужны права администратора/root. Каждый BAT-конфиг или нативный пресет проверяется дважды стандартными HTTP/TLS-проверками Test Zapret 1.10.3. Результат относится только к выбранным URL и HTTP/TLS, а не к воспроизведению видео, голосу Discord, UDP или всему BAT-скрипту. Перед применением результата исходное состояние восстанавливается.",
+ "tools.select.details": "Займёт несколько минут и временно включит Zapret. Нужны права администратора/root. Каждый BAT-конфиг или нативный пресет проверяется дважды стандартными HTTP/TLS-проверками Test Zapret 1.10.4. Результат относится только к выбранным URL и HTTP/TLS, а не к воспроизведению видео, голосу Discord, UDP или всему BAT-скрипту. Перед применением результата исходное состояние восстанавливается.",
"tools.select.scope": "Что проверяется",
"tools.startup.title": "Проверка сохранённой стратегии",
"tools.startup.scope": "Проверяется только запомненная стратегия набором HTTP/TLS-проверок Test Zapret (HTTP, TLS 1.2, TLS 1.3). Остальные стратегии не запускаются. Успех не означает, что будут работать видео, голосовой чат или UDP.",
diff --git a/src/Bydlo.App/Services/AppServices.cs b/src/Bydlo.App/Services/AppServices.cs
index a7e4ea8c..e8c01ee0 100644
--- a/src/Bydlo.App/Services/AppServices.cs
+++ b/src/Bydlo.App/Services/AppServices.cs
@@ -38,6 +38,9 @@ private AppServices(string[] args, IPrivilegeService? privileges)
Http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
Http.DefaultRequestHeaders.UserAgent.ParseAdd(Bydlo.Core.AppVersion.UserAgent);
Lock = EngineLock.LoadEmbedded();
+ InstallKind = AppInstallLocator.CreateDefault().Detect(AppContext.BaseDirectory, Environment.ProcessPath);
+ UpdateRecovery = new UpdateRecovery(Paths.DataDirectory, AppContext.BaseDirectory, InstallKind,
+ Bydlo.Core.AppVersion.Current, EngineLock.BundleVersion);
Installer = new EngineInstaller(Http, Lock, Paths.EnginesDirectory);
Locator = new EngineLocator(Installer, PlatformInfo.Current);
ZapretFirewall = new ZapretFirewall(Runner, Installer.UserDataDirectory);
@@ -60,8 +63,11 @@ private AppServices(string[] args, IPrivilegeService? privileges)
AutomaticUpdates = new(() => new PackagedAppUpdater(Paths.DataDirectory, Http))
{
// Package markers decide who owns updates; a writable path alone never enables the built-in updater.
- InstallKind = AppInstallLocator.CreateDefault().Detect(AppContext.BaseDirectory, Environment.ProcessPath),
+ InstallKind = InstallKind,
+ Recovery = UpdateRecovery,
};
+ // Read-only probe of /etc/apt: the app never runs apt and never writes to system files (issue #488).
+ AptRepositoryConfigured = OperatingSystem.IsLinux() && AptRepositorySource.IsConfigured();
}
public string[] Args { get; }
@@ -137,6 +143,18 @@ private AppServices(string[] args, IPrivilegeService? privileges)
public AutomaticAppUpdater AutomaticUpdates { get; }
+ /// How this copy was installed (issue #413).
+ public AppInstallKind InstallKind { get; }
+
+ /// Local update recovery journal and readiness confirmation (issue #412).
+ public UpdateRecovery UpdateRecovery { get; }
+
+ ///
+ /// Whether an apt source for the BYDLO repository is configured (issue #488). Detected once at
+ /// startup; tests and the headless UI verification override it.
+ ///
+ public bool AptRepositoryConfigured { get; set; }
+
/// Whether privileged engines are delegated to the installed helper.
public bool UsesPrivilegedHelper => HelperManagement.IsSupported && !Privileges.IsElevated &&
!IsMock && !NetworkSafetyGuard.IsLocked && HelperManagement.IsInstalled;
@@ -147,6 +165,8 @@ private AppServices(string[] args, IPrivilegeService? privileges)
public static async Task CreateAsync(string[] args, IPrivilegeService? privileges = null)
{
var s = new AppServices(args, privileges);
+ // Recovery runs before any user data is read: a snapshot restored here is what the app then loads (issue #412).
+ s.UpdateRecovery.PrepareStartup();
var firstRun = !File.Exists(s.Paths.SettingsFile);
s.Settings = await s.SettingsStore.LoadAsync().ConfigureAwait(false);
if (firstRun)
@@ -184,6 +204,31 @@ public static async Task CreateAsync(string[] args, IPrivilegeServi
public Task SaveSettingsAsync() => SettingsStore.SaveAsync(Settings);
+ ///
+ /// Local readiness confirmation for a freshly installed version (issue #412). Called once the UI is up;
+ /// it only inspects local state and never starts a tunnel, an engine, a driver or a network request.
+ ///
+ public void ConfirmUpdateReadiness()
+ {
+ if (!UpdateRecovery.IsPending) { return; }
+ var readiness = new UpdateReadiness(
+ uiStarted: true,
+ userDataLoaded: IsUserDataLoaded(SettingsStore.LoadStatus) && IsUserDataLoaded(Profiles.LoadStatus),
+ componentsConsistent: UpdateRecovery.ComponentsConsistent(Bydlo.Core.AppVersion.Current, EngineLock.BundleVersion),
+ helperCompatible: !HelperManagement.IsOutdated(ExpectedHelperBuild));
+ var result = UpdateRecovery.Confirm(readiness);
+ Log.Info("update", $"Update readiness: {result}. Phase: {UpdateRecovery.Journal?.Phase}. " +
+ $"Failed checks: {string.Join(',', readiness.Failures)}. Notes: {string.Join(',', readiness.Notes)}.");
+ if (result == UpdateRecoveryConfirmation.RolledBack)
+ {
+ Log.Error("update", "The new version did not confirm readiness; automatic updates are paused.");
+ }
+ }
+
+ /// A missing file is fine; a reset or unreadable one means the new version did not load user data.
+ private static bool IsUserDataLoaded(StoreLoadStatus status) =>
+ status is StoreLoadStatus.Ok or StoreLoadStatus.Missing or StoreLoadStatus.RecoveredFromBackup;
+
public async Task RestoreBackupAsync(Bydlo.Core.Backup.BackupData data, Bydlo.Core.Backup.BackupImportMode mode)
{
var restored = Bydlo.Core.Backup.BackupArchive.ImportSettings(data, Settings, mode);
diff --git a/src/Bydlo.App/Services/DesktopIntegration.cs b/src/Bydlo.App/Services/DesktopIntegration.cs
index 5fd1e14a..7d7f2ee8 100644
--- a/src/Bydlo.App/Services/DesktopIntegration.cs
+++ b/src/Bydlo.App/Services/DesktopIntegration.cs
@@ -28,6 +28,16 @@ public sealed class DesktopIntegration : IDisposable
private bool _disposed;
private bool _startupHandled;
private bool _refreshPending;
+ private readonly NativeMenu _menu = new();
+ private readonly NativeMenu _servers = new();
+ private readonly NativeMenuItem _open = new();
+ private readonly NativeMenuItem _status = new() { IsEnabled = false };
+ private readonly NativeMenuItem _connect = new();
+ private readonly NativeMenuItem _serverList = new();
+ private readonly NativeMenuItem _zapret = new();
+ private readonly NativeMenuItem _tg = new();
+ private readonly NativeMenuItem _exit = new();
+ private string? _profilesState;
public DesktopIntegration(MainViewModel shell, Window window, IClassicDesktopStyleApplicationLifetime lifetime)
{
@@ -35,7 +45,23 @@ public DesktopIntegration(MainViewModel shell, Window window, IClassicDesktopSty
_window = window;
_lifetime = lifetime;
_nativeNotifications = new DesktopNotifications(shell.Services.Runner);
- _tray = new TrayIcon { IsVisible = true };
+ _open.Command = new RelayCommand(ShowWindow);
+ _connect.Command = shell.Home.ToggleConnectionCommand;
+ _serverList.Menu = _servers;
+ _zapret.Command = shell.Tools.ToggleZapretCommand;
+ _tg.Command = shell.Tools.ToggleTgCommand;
+ _exit.Command = new AsyncRelayCommand(ExitAsync);
+ _menu.Items.Add(_open);
+ _menu.Items.Add(_status);
+ _menu.Items.Add(_connect);
+ _menu.Items.Add(_serverList);
+ _menu.Items.Add(new NativeMenuItemSeparator());
+ _menu.Items.Add(_zapret);
+ _menu.Items.Add(_tg);
+ _menu.Items.Add(new NativeMenuItemSeparator());
+ _menu.Items.Add(_exit);
+ // Avalonia.Native retains the exported menu identity. Never replace it during refresh.
+ _tray = new TrayIcon { Menu = _menu, IsVisible = true };
TrayIcon.SetIcons(Application.Current!, new TrayIcons { _tray });
_tray.Clicked += OnTrayClicked;
window.Closing += OnClosing;
@@ -119,6 +145,9 @@ private async void OnOpened(object? sender, EventArgs e)
if (_startupHandled) { return; }
_startupHandled = true;
var services = _shell.Services;
+ // The window is up: this is the local readiness confirmation of a freshly installed version (issue #412).
+ services.ConfirmUpdateReadiness();
+ _shell.ShowUpdateRecoveryToast();
if (services.Args.Contains("--autostart", StringComparer.Ordinal) &&
services.Settings.OnboardingCompleted && services.Settings.MinimizeToTray &&
_tray.NativeMenuExporter is not null) { _window.Hide(); }
@@ -153,33 +182,47 @@ private void Refresh()
_shell.Home.ZapretState, _shell.Home.TgState, _shell.SelectedProfile?.Id.ToString(),
string.Join(';', _shell.Profiles.Select(p => p.Id + ":" + p.Name)));
if (state == _menuState) { return; }
- _menuState = state;
_tray.ToolTipText = "BYDLO · " + _shell.Home.StatusText + "\nZapret · " + _shell.Home.ZapretState + "\nTgWsProxy · " + _shell.Home.TgState;
- var menu = new NativeMenu();
- menu.Items.Add(Item(l["tray.open"], new RelayCommand(ShowWindow)));
- menu.Items.Add(new NativeMenuItem { Header = _shell.Home.StatusText, IsEnabled = false });
- menu.Items.Add(Item(_shell.Home.ButtonText, _shell.Home.ToggleConnectionCommand));
- var servers = new NativeMenu();
- foreach (var profile in _shell.Profiles)
+ _open.Header = l["tray.open"];
+ _status.Header = _shell.Home.StatusText;
+ _connect.Header = _shell.Home.ButtonText;
+ _serverList.Header = l["tray.servers"];
+ _serverList.IsEnabled = _shell.Profiles.Count > 0;
+ _zapret.Header = "Zapret · " + _shell.Home.ZapretState;
+ _tg.Header = "TgWsProxy · " + _shell.Home.TgState;
+ _exit.Header = l["tray.exit"];
+ var profilesState = string.Join(';', _shell.Profiles.Select(p => p.Id + ":" + p.Name));
+ if (profilesState != _profilesState)
{
- servers.Items.Add(new NativeMenuItem
+ _servers.Items.Clear();
+ foreach (var profile in _shell.Profiles)
{
- Header = profile.Name, ToggleType = NativeMenuItemToggleType.Radio,
- IsChecked = _shell.SelectedProfile?.Id == profile.Id,
- Command = new RelayCommand(() => _shell.SelectedProfile = profile),
- });
+ _servers.Items.Add(new NativeMenuItem
+ {
+ Header = profile.Name, ToggleType = NativeMenuItemToggleType.Radio,
+ // Resolve by id on click: editing a profile replaces its item without renaming it,
+ // so a captured item would connect with the pre-edit settings.
+ Command = new RelayCommand(() => SelectProfile(profile.Id)),
+ });
+ }
+ _profilesState = profilesState;
+ }
+ for (var i = 0; i < _shell.Profiles.Count; i++)
+ {
+ ((NativeMenuItem)_servers.Items[i]).IsChecked = _shell.SelectedProfile?.Id == _shell.Profiles[i].Id;
}
- menu.Items.Add(new NativeMenuItem { Header = l["tray.servers"], Menu = servers, IsEnabled = servers.Items.Count > 0 });
- menu.Items.Add(new NativeMenuItemSeparator());
- menu.Items.Add(Item("Zapret · " + _shell.Home.ZapretState, _shell.Tools.ToggleZapretCommand));
- menu.Items.Add(Item("TgWsProxy · " + _shell.Home.TgState, _shell.Tools.ToggleTgCommand));
- menu.Items.Add(new NativeMenuItemSeparator());
- menu.Items.Add(Item(l["tray.exit"], new AsyncRelayCommand(ExitAsync)));
- _tray.Menu = menu;
UpdateIcon();
+ _menuState = state;
}
- private static NativeMenuItem Item(string header, System.Windows.Input.ICommand command) => new() { Header = header, Command = command };
+ /// Selects the current item for ; a profile deleted meanwhile is ignored.
+ internal void SelectProfile(Guid id)
+ {
+ if (_shell.Profiles.FirstOrDefault(p => p.Id == id) is { } current)
+ {
+ _shell.SelectedProfile = current;
+ }
+ }
private ConnectionStatus? _iconStatus;
private void UpdateIcon()
diff --git a/src/Bydlo.App/Services/LayoutMetrics.cs b/src/Bydlo.App/Services/LayoutMetrics.cs
new file mode 100644
index 00000000..1b9ddb52
--- /dev/null
+++ b/src/Bydlo.App/Services/LayoutMetrics.cs
@@ -0,0 +1,23 @@
+namespace Bydlo.App.Services;
+
+///
+/// Layout math for the interface scale (issue #477). The scale is applied once by a
+/// LayoutTransformControl at the root of the shell, so every control keeps working in
+/// unscaled layout units; only the width available to the shell shrinks as the scale grows.
+///
+public static class LayoutMetrics
+{
+ /// Below this unscaled width the sidebar collapses into bottom navigation (phones, narrow windows).
+ public const double CompactWidth = 760;
+
+ ///
+ /// Unscaled layout width of a shell that occupies at
+ /// . The navigation switch compares this value, so the breakpoint
+ /// stays at the same physical size for every interface scale.
+ ///
+ public static double EffectiveWidth(double scaledWidth, double scale) =>
+ scale > 0 && double.IsFinite(scale) ? scaledWidth / scale : scaledWidth;
+
+ /// True when the sidebar must collapse into bottom navigation.
+ public static bool IsCompact(double effectiveWidth) => effectiveWidth < CompactWidth;
+}
diff --git a/src/Bydlo.App/Services/PackagedAppUpdater.cs b/src/Bydlo.App/Services/PackagedAppUpdater.cs
index 50dfdd3f..595e08ce 100644
--- a/src/Bydlo.App/Services/PackagedAppUpdater.cs
+++ b/src/Bydlo.App/Services/PackagedAppUpdater.cs
@@ -22,6 +22,9 @@ internal sealed class PackagedAppUpdater(string dataDirectory, HttpClient http)
public bool IsInstalled => !File.Exists(Path.Combine(AppContext.BaseDirectory, "portable.txt")) &&
AutomaticAppUpdater.HasSeparateDataDirectory(AppContext.BaseDirectory, dataDirectory) && _manager.IsInstalled;
+ /// Version Velopack will install on the next exit; the recovery journal records it (issue #412).
+ public string? PendingVersion => _manager.UpdatePendingRestart?.Version?.ToString();
+
public async Task DownloadLatestAsync(IProgress? progress, CancellationToken ct)
{
NetworkSafetyGuard.EnsureAllowed("download application update");
diff --git a/src/Bydlo.App/Services/UpdateGuidance.cs b/src/Bydlo.App/Services/UpdateGuidance.cs
index 0d457836..10f4d2a5 100644
--- a/src/Bydlo.App/Services/UpdateGuidance.cs
+++ b/src/Bydlo.App/Services/UpdateGuidance.cs
@@ -8,8 +8,15 @@ namespace Bydlo.App.Services;
///
public static class UpdateGuidance
{
- public static string KeyFor(AppInstallKind kind) => kind switch
+ public static string KeyFor(AppInstallKind kind) => KeyFor(kind, false);
+
+ ///
+ /// A Debian install with a configured BYDLO apt source is updated by apt itself, so the text must
+ /// say apt upgrade instead of "download the .deb again" (issue #488).
+ ///
+ public static string KeyFor(AppInstallKind kind, bool aptRepositoryConfigured) => kind switch
{
+ AppInstallKind.Debian when aptRepositoryConfigured => "settings.update.manual.deb.repository",
AppInstallKind.Debian => "settings.update.manual.deb",
AppInstallKind.Arch => "settings.update.manual.arch",
AppInstallKind.Nix => "settings.update.manual.nix",
diff --git a/src/Bydlo.App/Themes/Styles.axaml b/src/Bydlo.App/Themes/Styles.axaml
index 531931d7..4f4d15da 100644
--- a/src/Bydlo.App/Themes/Styles.axaml
+++ b/src/Bydlo.App/Themes/Styles.axaml
@@ -450,6 +450,20 @@
+
+
+
+
@@ -534,7 +548,4 @@
-
diff --git a/src/Bydlo.App/ViewModels/MainViewModel.cs b/src/Bydlo.App/ViewModels/MainViewModel.cs
index f593b0e5..1d0baf9a 100644
--- a/src/Bydlo.App/ViewModels/MainViewModel.cs
+++ b/src/Bydlo.App/ViewModels/MainViewModel.cs
@@ -1,4 +1,5 @@
using System.Collections.ObjectModel;
+using Avalonia.Media;
using Avalonia.Threading;
using Bydlo.App.Services;
using Bydlo.Core.Connection;
@@ -69,6 +70,7 @@ public MainViewModel(AppServices services, Bydlo.Core.Import.SubscriptionClient?
_isOnboardingVisible = !services.Settings.OnboardingCompleted;
_onboardingLanguage = services.Settings.Language;
_onboardingTheme = services.Settings.Theme;
+ _interfaceScale = services.Settings.InterfaceScale;
_consentAutomaticUpdates = services.Settings.ConsentAutomaticUpdates;
_consentNotifications = services.Settings.ConsentNotifications;
_consentThemes = services.Settings.ConsentThemes;
@@ -114,6 +116,7 @@ public MainViewModel(AppServices services, Bydlo.Core.Import.SubscriptionClient?
Loc.Instance.PropertyChanged += (_, _) => OnNoticeLanguageChanged();
RefreshCrashReports();
ShowStoreRecoveryToasts();
+ ShowUpdateRecoveryToast();
_ = RunStartupChecksAsync();
services.StartSubscriptionAutoRefresh(Connections.RunAutoRefreshAsync);
}
@@ -141,6 +144,30 @@ private void ShowStoreRecoveryToasts()
}
}
+ private UpdateRecoveryStartup? _shownUpdateRecovery;
+
+ ///
+ /// Explains an interrupted or unconfirmed update. Called once at startup and again after the readiness
+ /// confirmation, which may turn the state into (issue #412).
+ ///
+ public void ShowUpdateRecoveryToast()
+ {
+ var startup = Services.UpdateRecovery.Startup;
+ if (startup == _shownUpdateRecovery) { return; }
+ _shownUpdateRecovery = startup;
+ switch (startup)
+ {
+ case UpdateRecoveryStartup.Blocked:
+ ShowToast(Loc.T("update.recovery.blocked", Bydlo.Core.AppVersion.Current), isError: true,
+ localizationKey: "update.recovery.blocked", localizationArguments: [Bydlo.Core.AppVersion.Current]);
+ break;
+ case UpdateRecoveryStartup.Interrupted:
+ ShowToast(Loc.T("update.recovery.interrupted", Bydlo.Core.AppVersion.Current), isError: true,
+ localizationKey: "update.recovery.interrupted", localizationArguments: [Bydlo.Core.AppVersion.Current]);
+ break;
+ }
+ }
+
public AppServices Services { get; }
public HomeViewModel Home { get; }
@@ -183,6 +210,13 @@ private async Task OpenImport(string source)
AddServerWizard.ChooseQrCommand.Execute(null);
await AddServerWizard.SelectQrCommand.ExecuteAsync(null);
break;
+ case "manual":
+ AddServerWizard.ChooseManualCommand.Execute(null);
+ break;
+ case "subscription":
+ AddServerWizard.ChooseLinkCommand.Execute(null);
+ AddServerWizard.ImportTypeIndex = 2;
+ break;
default:
AddServerWizard.ChooseLinkCommand.Execute(null);
if (source == "clipboard") { await AddServerWizard.PasteCommand.ExecuteAsync(null); }
@@ -271,6 +305,36 @@ private void EditChain(ChainItem item)
[NotifyPropertyChangedFor(nameof(IsSettingsDetail))]
private bool _isCompact;
+ /// Shell width in scaled layout units, reported by the root view (issue #477).
+ [ObservableProperty]
+ private double _layoutWidth;
+
+ /// Interface scale in percent; the root view applies it as a layout transform.
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(InterfaceScaleFactor))]
+ [NotifyPropertyChangedFor(nameof(InterfaceScaleTransform))]
+ private int _interfaceScale = AppSettings.DefaultInterfaceScale;
+
+ /// Layout multiplier for ; 1.0 is 100%.
+ public double InterfaceScaleFactor => AppSettings.ClampInterfaceScale(InterfaceScale) / 100.0;
+
+ ///
+ /// Layout transform for the shell root. A new instance per change makes the
+ /// LayoutTransformControl re-measure instead of relying on a mutated matrix.
+ ///
+ public ITransform InterfaceScaleTransform => new ScaleTransform(InterfaceScaleFactor, InterfaceScaleFactor);
+
+ partial void OnLayoutWidthChanged(double value) => RefreshCompact();
+
+ partial void OnInterfaceScaleChanged(int value) => RefreshCompact();
+
+ ///
+ /// The scale shrinks the unscaled layout width, so the sidebar/bottom switch must compare the
+ /// effective width instead of the window width.
+ ///
+ private void RefreshCompact() =>
+ IsCompact = LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(LayoutWidth, InterfaceScaleFactor));
+
[ObservableProperty]
private ProfileItem? _selectedProfile;
diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs
index ecc2a4db..1591761b 100644
--- a/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs
+++ b/src/Bydlo.App/ViewModels/SettingsViewModel.Backup.cs
@@ -133,19 +133,13 @@ private async Task OpenBackup()
if (files.Count == 0) { return; }
using var file = files[0];
await using var stream = await file.OpenReadAsync();
- using var buffer = new MemoryStream();
- var chunk = new byte[8192];
- int count;
- while ((count = await stream.ReadAsync(chunk)) > 0)
- {
- if (buffer.Length + count > BackupArchive.MaximumFileSize) { throw new InvalidDataException(); }
- buffer.Write(chunk, 0, count);
- }
+ // One bounded buffer, handed to the session without another copy (issue #394).
+ var archive = await BackupArchive.ReadFileAsync(stream);
var password = BackupPassword;
var lifetime = Services.ShutdownToken;
var opened = await Task.Run(() =>
{
- var session = BackupArchive.OpenImport(buffer.ToArray(), password);
+ var session = BackupArchive.OpenImportOwned(archive, password);
// Register on the worker too: shutdown can stop the UI dispatcher before
// this await resumes and transfers ownership to the ViewModel.
try { return (Session: session, Shutdown: lifetime.Register(session.Dispose)); }
diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs
index 0d37eac2..5961c402 100644
--- a/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs
+++ b/src/Bydlo.App/ViewModels/SettingsViewModel.Updates.cs
@@ -47,18 +47,21 @@ partial void OnAutoUpdateAppChanged(bool value)
///
/// Single status line. The packaged update state is authoritative, so a release notification can never
- /// replace "downloaded, installs on exit" with "new version available" (issue #413).
+ /// replace "downloaded, installs on exit" with "new version available" (issue #413). A failed confirmation
+ /// of the previous version wins over both, because automatic updates are paused (issue #412).
///
- public string UpdateStatus => Services.AutomaticUpdates.State switch
- {
- AppUpdateState.Downloading => L["settings.update.downloading"],
- AppUpdateState.Ready => L["settings.update.ready"],
- AppUpdateState.Deferred => L["settings.update.deferred"],
- AppUpdateState.Failed => _updateFailureStatus ?? L["settings.update.error"],
- AppUpdateState.Available when Services.AutomaticUpdates.AvailableVersion is { } version =>
- Loc.T("settings.update.available", version),
- _ => _updateCheckStatus,
- };
+ public string UpdateStatus => Services.UpdateRecovery.AutoApplyBlocked
+ ? L["settings.update.recovery.blocked"]
+ : Services.AutomaticUpdates.State switch
+ {
+ AppUpdateState.Downloading => L["settings.update.downloading"],
+ AppUpdateState.Ready => L["settings.update.ready"],
+ AppUpdateState.Deferred => L["settings.update.deferred"],
+ AppUpdateState.Failed => _updateFailureStatus ?? L["settings.update.error"],
+ AppUpdateState.Available when Services.AutomaticUpdates.AvailableVersion is { } version =>
+ Loc.T("settings.update.available", version),
+ _ => _updateCheckStatus,
+ };
/// Secondary line: last check time or live progress.
[ObservableProperty]
@@ -113,9 +116,15 @@ public void RefreshUpdateState()
var blocked = Services.IsMock || NetworkSafetyGuard.IsLocked;
OnPropertyChanged(nameof(SupportsAutomaticUpdates));
IsAutoUpdateAvailable = SupportsAutomaticUpdates && !blocked && Services.AutomaticUpdates.IsAvailable();
- UpdateGuidanceText = SupportsAutomaticUpdates
- ? (blocked ? L["settings.update.auto.unavailable"] : "")
- : L[UpdateGuidance.KeyFor(Services.AutomaticUpdates.InstallKind)];
+ // Only mention the kept package when the installer really left one next to the app (issue #412).
+ var recoveryGuidance = Services.UpdateRecovery.PreviousPackageAvailable
+ ? "settings.update.recovery.previous"
+ : "settings.update.recovery.manual";
+ UpdateGuidanceText = Services.UpdateRecovery.AutoApplyBlocked
+ ? L[recoveryGuidance]
+ : SupportsAutomaticUpdates
+ ? (blocked ? L["settings.update.auto.unavailable"] : "")
+ : L[UpdateGuidance.KeyFor(Services.AutomaticUpdates.InstallKind, Services.AptRepositoryConfigured)];
RefreshUpdateDetail();
OnPropertyChanged(nameof(UpdateStatus));
}
diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.cs
index 8f1789e1..8c0760a7 100644
--- a/src/Bydlo.App/ViewModels/SettingsViewModel.cs
+++ b/src/Bydlo.App/ViewModels/SettingsViewModel.cs
@@ -25,22 +25,25 @@ public sealed partial class SettingsViewModel : PageViewModel
[ObservableProperty] private string _helperStatus = "";
[RelayCommand]
- private Task InstallHelperAsync() => ChangeHelperAsync(true);
+ private async Task InstallHelperAsync() { await ChangeHelperAsync(true); }
[RelayCommand]
- private Task RemoveHelperAsync() => ChangeHelperAsync(false);
+ private async Task RemoveHelperAsync() { await ChangeHelperAsync(false); }
- private async Task ChangeHelperAsync(bool install)
+ internal Task InstallHelperForZapretAsync() => ChangeHelperAsync(true);
+
+ private async Task ChangeHelperAsync(bool install)
{
- if (!CanManageHelper) { return; }
+ if (!CanManageHelper) { return false; }
HelperBusy = true;
try
{
await Services.Connections.StopAllAsync();
var success = await Bydlo.Platform.HelperManagement.ChangeAsync(install, userConsent: true);
HelperStatus = Loc.Instance[success ? "helper.changed" : "helper.error"];
+ return success;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
- { HelperStatus = Loc.Instance["helper.error"]; }
+ { HelperStatus = Loc.Instance["helper.error"]; return false; }
finally
{
HelperBusy = false;
@@ -55,6 +58,7 @@ public SettingsViewModel(MainViewModel shell)
var s = Services.Settings;
_theme = s.Theme;
_reduceMotion = s.ReduceMotion;
+ _interfaceScale = s.InterfaceScale;
_language = s.Language;
_mockMode = Services.IsMock;
_mockScenario = s.MockScenario;
@@ -90,6 +94,7 @@ public override void OnShown()
var s = Services.Settings;
Theme = s.Theme;
ReduceMotion = s.ReduceMotion;
+ InterfaceScale = s.InterfaceScale;
Language = s.Language;
MockMode = Services.IsMock;
MockScenario = s.MockScenario;
@@ -130,6 +135,31 @@ partial void OnReduceMotionChanged(bool value)
Persist();
}
+ /// Selectable interface scales in percent (issue #477).
+ public static IReadOnlyList InterfaceScales { get; } = AppSettings.InterfaceScaleSteps;
+
+ [ObservableProperty] private int _interfaceScale;
+
+ partial void OnInterfaceScaleChanged(int value)
+ {
+ var clamped = AppSettings.ClampInterfaceScale(value);
+ if (clamped != value)
+ {
+ InterfaceScale = clamped;
+ return;
+ }
+ Services.Settings.InterfaceScale = clamped;
+ Shell.InterfaceScale = clamped;
+ Persist();
+ }
+
+ [RelayCommand]
+ private void ResetInterfaceScale()
+ {
+ InterfaceScale = AppSettings.DefaultInterfaceScale;
+ Shell.ShowToast(L["settings.scale.reset.done"]);
+ }
+
public bool AutostartSupported => new Bydlo.Platform.AutostartService().IsSupported;
[ObservableProperty] private bool _startWithSystem;
diff --git a/src/Bydlo.App/ViewModels/ToolsViewModel.cs b/src/Bydlo.App/ViewModels/ToolsViewModel.cs
index 32ef8318..d4ad9fab 100644
--- a/src/Bydlo.App/ViewModels/ToolsViewModel.cs
+++ b/src/Bydlo.App/ViewModels/ToolsViewModel.cs
@@ -56,6 +56,8 @@ public ToolsViewModel(MainViewModel shell)
_tgCfFallback = s.TgWsProxy.CfProxyFallback;
_tgVerbose = s.TgWsProxy.Verbose;
_tgCfDomains = string.Join('\n', s.TgWsProxy.CfProxyDomains);
+ _tgProxyProtocol = s.TgWsProxy.ProxyProtocol;
+ _tgProxyProtocolSources = string.Join('\n', s.TgWsProxy.ProxyProtocolTrustedSources);
LoadSelection();
shell.PropertyChanged += OnShellChanged;
L.PropertyChanged += (_, _) =>
@@ -149,6 +151,10 @@ private async Task InstallOpenVpnDriver()
&& !Services.Privileges.IsElevated
&& Services.Privileges.CanRestartElevated;
+ public bool ShowZapretHelperSetup => ZapretNeedsElevation
+ && !Services.Privileges.IsElevated
+ && Shell.Settings.HelperSupported && !Shell.Settings.HelperInstalled;
+
// ---------- TgWsProxy ----------
[ObservableProperty]
@@ -172,6 +178,12 @@ private async Task InstallOpenVpnDriver()
[ObservableProperty]
private string _tgCfDomains;
+ [ObservableProperty]
+ private bool _tgProxyProtocol;
+
+ [ObservableProperty]
+ private string _tgProxyProtocolSources;
+
[ObservableProperty]
private string _tgLink = "";
@@ -212,6 +224,8 @@ public void ReloadSettings()
TgCfFallback = s.TgWsProxy.CfProxyFallback;
TgVerbose = s.TgWsProxy.Verbose;
TgCfDomains = string.Join('\n', s.TgWsProxy.CfProxyDomains);
+ TgProxyProtocol = s.TgWsProxy.ProxyProtocol;
+ TgProxyProtocolSources = string.Join('\n', s.TgWsProxy.ProxyProtocolTrustedSources);
}
finally { _loadingSettings = false; }
}
@@ -234,6 +248,24 @@ private async Task ToggleZapret()
SaveZapretSettings();
await Shell.Guard(() => Services.Connections.StartZapretAsync(Services.EffectiveSettings));
+ if (Services.Connections.Zapret.ErrorLocalizationKey == "error.engine.zapret.admin")
+ {
+ // Also expose recovery when activation came from the tray.
+ Shell.Navigate("tools");
+ }
+ }
+
+ [RelayCommand]
+ private async Task InstallZapretHelper()
+ {
+ if (!ShowZapretHelperSetup || !Shell.Settings.CanManageHelper) { return; }
+ var installed = await Shell.Settings.InstallHelperForZapretAsync();
+ RefreshListEditing();
+ OnPropertyChanged(nameof(ShowZapretHelperSetup));
+ if (installed && Services.UsesPrivilegedHelper)
+ {
+ await ToggleZapret();
+ }
}
[RelayCommand]
@@ -429,6 +461,17 @@ private bool SaveTgSettings()
return false;
}
+ var sources = TgProxyProtocolSources.Split('\n', ',', ' ').Select(x => x.Trim()).Where(x => x.Length > 0).ToList();
+ try
+ {
+ TgWsProxyOptions.ParseTrustedSources(sources);
+ }
+ catch (EngineException ex)
+ {
+ Shell.ShowToast(Loc.Error(ex.Message, ex.LocalizationKey), isError: true);
+ return false;
+ }
+
var t = Services.Settings.TgWsProxy;
t.Host = string.IsNullOrWhiteSpace(TgHost) ? "127.0.0.1" : TgHost.Trim();
t.Port = TgPort;
@@ -437,6 +480,8 @@ private bool SaveTgSettings()
t.CfProxyFallback = TgCfFallback;
t.Verbose = TgVerbose;
t.CfProxyDomains = [.. TgCfDomains.Split('\n', ',', ' ').Select(x => x.Trim()).Where(x => x.Length > 0)];
+ t.ProxyProtocol = TgProxyProtocol;
+ t.ProxyProtocolTrustedSources = sources;
_ = Services.SaveSettingsAsync();
return true;
}
@@ -557,6 +602,7 @@ private void OnShellChanged(object? sender, PropertyChangedEventArgs e)
OnPropertyChanged(nameof(ZapretError));
OnPropertyChanged(nameof(ZapretNeedsElevation));
OnPropertyChanged(nameof(ShowRestartElevated));
+ OnPropertyChanged(nameof(ShowZapretHelperSetup));
}
else if (e.PropertyName == nameof(MainViewModel.Tg))
{
diff --git a/src/Bydlo.App/Views/AppearanceSettingsView.axaml b/src/Bydlo.App/Views/AppearanceSettingsView.axaml
index 21532974..461f12a9 100644
--- a/src/Bydlo.App/Views/AppearanceSettingsView.axaml
+++ b/src/Bydlo.App/Views/AppearanceSettingsView.axaml
@@ -17,6 +17,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Bydlo.App/Views/ConnectionsView.axaml b/src/Bydlo.App/Views/ConnectionsView.axaml
index cfb7546f..93baeffd 100644
--- a/src/Bydlo.App/Views/ConnectionsView.axaml
+++ b/src/Bydlo.App/Views/ConnectionsView.axaml
@@ -44,7 +44,6 @@
-
@@ -87,7 +86,7 @@
-
+
+
-
-
-
-
-
-
@@ -201,20 +205,29 @@
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Bydlo.App/Views/HomeView.axaml b/src/Bydlo.App/Views/HomeView.axaml
index b663a01c..93ebefcd 100644
--- a/src/Bydlo.App/Views/HomeView.axaml
+++ b/src/Bydlo.App/Views/HomeView.axaml
@@ -17,35 +17,38 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
@@ -92,8 +95,6 @@
-
diff --git a/src/Bydlo.App/Views/HomeView.axaml.cs b/src/Bydlo.App/Views/HomeView.axaml.cs
index 98f774b5..1be4298e 100644
--- a/src/Bydlo.App/Views/HomeView.axaml.cs
+++ b/src/Bydlo.App/Views/HomeView.axaml.cs
@@ -1,5 +1,7 @@
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Avalonia.Threading;
namespace Bydlo.App.Views;
@@ -7,6 +9,15 @@ public sealed partial class HomeView : UserControl
{
public HomeView() => InitializeComponent();
+ ///
+ /// Closes the "Add server" menu after the chosen import flow starts. The hide is deferred so the
+ /// command binding is still alive when the menu item finishes its click.
+ ///
+ private void OnImportSourceClick(object? sender, RoutedEventArgs e)
+ {
+ Dispatcher.UIThread.Post(() => AddServerEntry.Flyout?.Hide(), DispatcherPriority.Background);
+ }
+
protected override void OnSizeChanged(SizeChangedEventArgs e)
{
base.OnSizeChanged(e);
diff --git a/src/Bydlo.App/Views/MainView.axaml b/src/Bydlo.App/Views/MainView.axaml
index f5fba25b..5e419a11 100644
--- a/src/Bydlo.App/Views/MainView.axaml
+++ b/src/Bydlo.App/Views/MainView.axaml
@@ -36,276 +36,280 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
diff --git a/src/Bydlo.App/Views/MainView.axaml.cs b/src/Bydlo.App/Views/MainView.axaml.cs
index e29682e4..14dade16 100644
--- a/src/Bydlo.App/Views/MainView.axaml.cs
+++ b/src/Bydlo.App/Views/MainView.axaml.cs
@@ -3,6 +3,7 @@
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
+using Bydlo.App.Services;
using Bydlo.Core.Import;
using Bydlo.App.ViewModels;
@@ -11,7 +12,7 @@ namespace Bydlo.App.Views;
public sealed partial class MainView : UserControl
{
/// Below this width the sidebar collapses into bottom navigation (phones, narrow windows).
- public const double CompactWidth = 760;
+ public const double CompactWidth = LayoutMetrics.CompactWidth;
public MainView()
{
@@ -107,7 +108,9 @@ protected override void OnSizeChanged(SizeChangedEventArgs e)
base.OnSizeChanged(e);
if (DataContext is MainViewModel vm)
{
- vm.IsCompact = e.NewSize.Width < CompactWidth;
+ // The interface scale shrinks the layout width, so the shell reports its scaled width
+ // and the view model compares the effective unscaled width (issue #477).
+ vm.LayoutWidth = e.NewSize.Width;
}
}
}
diff --git a/src/Bydlo.App/Views/RoutingView.axaml b/src/Bydlo.App/Views/RoutingView.axaml
index 18506a9d..43abcc90 100644
--- a/src/Bydlo.App/Views/RoutingView.axaml
+++ b/src/Bydlo.App/Views/RoutingView.axaml
@@ -131,7 +131,7 @@
-
+
@@ -159,15 +159,15 @@
-
+
-
-
-
-
+
+
+
+
diff --git a/src/Bydlo.App/Views/ToolsView.axaml b/src/Bydlo.App/Views/ToolsView.axaml
index 7d4c1561..cb89b454 100644
--- a/src/Bydlo.App/Views/ToolsView.axaml
+++ b/src/Bydlo.App/Views/ToolsView.axaml
@@ -52,6 +52,13 @@
+
+
+
+
+
+
+
@@ -271,6 +278,15 @@
+
+
+
+
+
+
+
+
+
diff --git a/src/Bydlo.Core/Backup/BackupArchive.cs b/src/Bydlo.Core/Backup/BackupArchive.cs
index c20a3173..abf6c635 100644
--- a/src/Bydlo.Core/Backup/BackupArchive.cs
+++ b/src/Bydlo.Core/Backup/BackupArchive.cs
@@ -1,3 +1,5 @@
+using System.Buffers;
+using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Bydlo.Core.Models;
@@ -32,52 +34,147 @@ public static class BackupArchive
public const int MaximumFileSize = 32 * 1024 * 1024;
internal const int Overhead = 8 + 16 + 12 + 16;
- public static BackupImportSession OpenImport(byte[] file, string password) => BackupImportSession.Open(file, password);
+ public static BackupImportSession OpenImport(byte[] file, string password) => BackupImportSession.Open(file, password, copy: true);
+
+ ///
+ /// Opens an archive read with . Ownership of
+ /// moves to the session: it is not copied again and is cleared when the session is disposed (issue #394).
+ ///
+ public static BackupImportSession OpenImportOwned(byte[] file, string password) => BackupImportSession.Open(file, password, copy: false);
+
+ ///
+ /// Reads an archive with a hard size limit (issue #394). A stream with a known length gets one
+ /// exactly sized buffer after the limit check; an unknown length grows geometrically but never
+ /// past + 1 bytes.
+ ///
+ public static async Task ReadFileAsync(Stream stream, CancellationToken ct = default)
+ {
+ ArgumentNullException.ThrowIfNull(stream);
+ long? known = null;
+ try { if (stream.CanSeek) { known = stream.Length - stream.Position; } }
+ catch (NotSupportedException) { }
+ if (known is { } length)
+ {
+ if (length > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); }
+ var exact = new byte[length];
+ try { await stream.ReadExactlyAsync(exact, ct).ConfigureAwait(false); }
+ catch (EndOfStreamException ex) { throw new InvalidDataException("Backup changed while reading.", ex); }
+ var probe = new byte[1];
+ if (await stream.ReadAsync(probe, ct).ConfigureAwait(false) != 0)
+ { throw new InvalidDataException("Backup changed while reading."); }
+ return exact;
+ }
+ var buffer = new byte[Math.Min(64 * 1024, MaximumFileSize + 1)];
+ var count = 0;
+ while (true)
+ {
+ if (count == buffer.Length)
+ {
+ if (buffer.Length > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); }
+ Array.Resize(ref buffer, (int)Math.Min((long)buffer.Length * 2, MaximumFileSize + 1L));
+ }
+ var read = await stream.ReadAsync(buffer.AsMemory(count), ct).ConfigureAwait(false);
+ if (read == 0) { break; }
+ count += read;
+ if (count > MaximumFileSize) { throw new InvalidDataException("Backup is too large."); }
+ }
+ return count == buffer.Length ? buffer : buffer.AsSpan(0, count).ToArray();
+ }
public static byte[] Encrypt(BackupData data, string password)
{
ArgumentException.ThrowIfNullOrWhiteSpace(password);
Validate(data);
- var plaintext = JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info());
+ // Cheap lower bound first: large raw configs fail before any buffer is allocated.
+ if (MinimumPayloadSize(data) > MaximumFileSize - Overhead) { throw new InvalidDataException("Backup is too large."); }
+ // Serialize straight after the header into one pooled buffer, enforcing the limit while
+ // writing, then encrypt in place (issue #394). The buffer holds plaintext until encrypted,
+ // so it is always cleared before it returns to the pool.
+ using var buffer = new BoundedBuffer(Overhead, MaximumFileSize);
byte[]? key = null;
try
{
- if (plaintext.Length > MaximumFileSize - Overhead) { throw new InvalidDataException("Backup is too large."); }
- var output = new byte[Overhead + plaintext.Length];
+ using (var writer = new Utf8JsonWriter(buffer, new JsonWriterOptions { Encoder = JsonDefaults.Options.Encoder, Indented = JsonDefaults.Options.WriteIndented }))
+ {
+ JsonSerializer.Serialize(writer, data, JsonDefaults.Options.Info());
+ }
+ var total = buffer.WrittenCount;
+ var output = buffer.Array.AsSpan(0, total);
Header.CopyTo(output);
- RandomNumberGenerator.Fill(output.AsSpan(8, 16));
- RandomNumberGenerator.Fill(output.AsSpan(24, 12));
- key = Rfc2898DeriveBytes.Pbkdf2(password, output.AsSpan(8, 16), Iterations, HashAlgorithmName.SHA256, 32);
+ RandomNumberGenerator.Fill(output.Slice(8, 16));
+ RandomNumberGenerator.Fill(output.Slice(24, 12));
+ key = Rfc2898DeriveBytes.Pbkdf2(password, output.Slice(8, 16), Iterations, HashAlgorithmName.SHA256, 32);
using var aes = new AesGcm(key, 16);
- aes.Encrypt(output.AsSpan(24, 12), plaintext, output.AsSpan(Overhead), output.AsSpan(36, 16), output.AsSpan(0, 24));
- return output;
+ var body = output[Overhead..];
+ aes.Encrypt(output.Slice(24, 12), body, body, output.Slice(36, 16), output[..24]);
+ return output.ToArray();
}
finally
{
- CryptographicOperations.ZeroMemory(plaintext);
if (key is not null) { CryptographicOperations.ZeroMemory(key); }
}
}
+ ///
+ /// Lower bound of the serialized size: every string value appears at least once in UTF-8.
+ /// Escaping and property names only add bytes, so exceeding the limit here is conclusive.
+ ///
+ internal static long MinimumPayloadSize(BackupData data)
+ {
+ long total = 0;
+ static long Bytes(string? value) => value is null ? 0 : System.Text.Encoding.UTF8.GetByteCount(value);
+ static long Dictionary(Dictionary? values) =>
+ values?.Sum(entry => Bytes(entry.Key) + Bytes(entry.Value)) ?? 0;
+ foreach (var item in data.Profiles)
+ {
+ total += Dictionary(item.Secrets.Values) + Dictionary(item.Profile.Options)
+ + Bytes(item.Profile.Name) + Bytes(item.Profile.Host);
+ }
+ foreach (var sub in data.Subscriptions)
+ {
+ total += Bytes(sub.Url) + Bytes(sub.Subscription.Name)
+ + (sub.Subscription.SourceOptions?.Values.Sum(Dictionary) ?? 0);
+ }
+ return total + Dictionary(data.ToolSecrets.Values);
+ }
+
public static BackupData Decrypt(byte[] file, string password)
{
ArgumentException.ThrowIfNullOrWhiteSpace(password);
if (file.Length < Overhead || file.Length > MaximumFileSize || !file.AsSpan(0, 8).SequenceEqual(Header))
{ throw new InvalidDataException("Unsupported backup."); }
var key = Rfc2898DeriveBytes.Pbkdf2(password, file.AsSpan(8, 16), Iterations, HashAlgorithmName.SHA256, 32);
- var plaintext = new byte[file.Length - Overhead];
+ try
+ {
+ return DecryptWith(key, file, plaintext =>
+ {
+ var data = JsonSerializer.Deserialize(plaintext.Span, JsonDefaults.Options.Info()) ?? throw new InvalidDataException("Invalid backup.");
+ Validate(data);
+ return data;
+ });
+ }
+ finally { CryptographicOperations.ZeroMemory(key); }
+ }
+
+ ///
+ /// Authenticates and decrypts into a pooled buffer that is cleared on every path. The reader only
+ /// sees plaintext after the tag has been verified and must not retain the span.
+ ///
+ internal static T DecryptWith(byte[] key, byte[] archive, Func, T> read)
+ {
+ var length = archive.Length - Overhead;
+ var rented = ArrayPool.Shared.Rent(Math.Max(length, 1));
+ var plaintext = rented.AsMemory(0, length);
try
{
using var aes = new AesGcm(key, 16);
- aes.Decrypt(file.AsSpan(24, 12), file.AsSpan(Overhead), file.AsSpan(36, 16), plaintext, file.AsSpan(0, 24));
- var data = JsonSerializer.Deserialize(plaintext, JsonDefaults.Options.Info()) ?? throw new InvalidDataException("Invalid backup.");
- Validate(data);
- return data;
+ aes.Decrypt(archive.AsSpan(24, 12), archive.AsSpan(Overhead), archive.AsSpan(36, 16), plaintext.Span, archive.AsSpan(0, 24));
+ return read(plaintext);
}
finally
{
- CryptographicOperations.ZeroMemory(key);
- CryptographicOperations.ZeroMemory(plaintext);
+ CryptographicOperations.ZeroMemory(plaintext.Span);
+ ArrayPool.Shared.Return(rented);
}
}
@@ -96,7 +193,7 @@ public static BackupPreview Preview(BackupData data, ProfileStore store, BackupI
public static AppSettings ImportSettings(BackupData data, AppSettings current, BackupImportMode mode)
{
- var settings = Clone(data.Settings);
+ var settings = BackupCopy.Copy(data.Settings);
// Device integration is never activated or changed by restoring a backup.
settings.EnginePaths = new(current.EnginePaths, StringComparer.OrdinalIgnoreCase);
settings.Zapret.InstallPath = current.Zapret.InstallPath;
@@ -111,6 +208,8 @@ public static AppSettings ImportSettings(BackupData data, AppSettings current, B
settings.ConsentsInitialized = current.ConsentsInitialized;
// Custom theme files live next to the data directory and are not part of the backup.
settings.CustomThemeId = current.CustomThemeId;
+ // The interface scale is a display preference, so a restored value is snapped to a supported step.
+ settings.NormalizeInterfaceScale();
settings.MigrateLegacyTheme();
if (settings.Theme == ThemePreference.Custom && settings.CustomThemeId is null)
{
@@ -135,13 +234,6 @@ public static AppSettings ImportSettings(BackupData data, AppSettings current, B
private static List Union(List current, List incoming) =>
[.. current.Concat(incoming).Distinct(StringComparer.OrdinalIgnoreCase)];
- internal static T Clone(T value)
- {
- var bytes = JsonSerializer.SerializeToUtf8Bytes(value, JsonDefaults.Options.Info());
- try { return JsonSerializer.Deserialize(bytes, JsonDefaults.Options.Info())!; }
- finally { CryptographicOperations.ZeroMemory(bytes); }
- }
-
///
/// Secret keys a profile must carry (issue #344). An empty list means the protocol
/// allows credential-free profiles (plain HTTP/SOCKS5, Hysteria2 without auth): an
@@ -182,6 +274,12 @@ internal static void Validate(BackupData data)
if (data.Version != 1 || data.Settings is null || data.Profiles is null || data.Subscriptions is null || data.ToolSecrets?.Values is null || data.Chains is null)
{ throw new InvalidDataException("Invalid backup."); }
var s = data.Settings;
+ // Every collection the import path enumerates must be present: a null list passed validation
+ // and threw later in ImportSettings or after it was persisted.
+ if (s.ServerGroups is null || s.Contributors is null ||
+ s.ServerGroups.Any(g => g is null || g.Id == Guid.Empty || g.Name is null || g.ProfileIds is null || g.ProbeUrl is null) ||
+ s.Contributors.Any(c => c is null || c.Login is null))
+ { throw new InvalidDataException("Invalid settings."); }
if (s.Routing is null || s.DpiDefaults is null || s.Zapret is null || s.TgWsProxy is null || s.EnginePaths is null ||
s.Routing.DirectDomains is null || s.Routing.ProxyDomains is null || s.Routing.BlockDomains is null ||
s.Routing.DirectCidrs is null || s.Routing.DirectProcesses is null || s.Routing.OrderedRules is null ||
@@ -191,8 +289,11 @@ s.Routing.RemoteDnsRuleSets is null || s.Routing.DirectDnsRuleSets is null || s.
!Enum.IsDefined(s.Routing.Preset) || !Enum.IsDefined(s.Routing.RemoteDnsTransport) || !Enum.IsDefined(s.Routing.DirectDnsTransport) ||
s.Zapret.TestTargets is null || s.Zapret.GameFilter is not ("disabled" or "all" or "tcp" or "udp") ||
s.TgWsProxy.DcIps is null || s.TgWsProxy.CfProxyDomains is null || s.TgWsProxy.Host is null || s.TgWsProxy.FakeTlsDomain is null ||
+ s.TgWsProxy.ProxyProtocolTrustedSources is null ||
+ s.TgWsProxy.ProxyProtocolTrustedSources.Any(value => !IPAddress.TryParse(value ?? "", out _)) ||
s.LocalProxyUsername is null ||
s.LocalProxyPort is < 1 or > 65534 || s.TgWsProxy.Port is < 1 or > 65535 ||
+ s.InterfaceScale is < AppSettings.MinInterfaceScale or > AppSettings.MaxInterfaceScale ||
!Enum.IsDefined(s.Theme) || !Enum.IsDefined(s.Mode) || !Enum.IsDefined(s.MockScenario) || !Enum.IsDefined(s.IpCheckProvider) ||
s.Language is not ("auto" or "en" or "ru"))
{ throw new InvalidDataException("Invalid settings."); }
diff --git a/src/Bydlo.Core/Backup/BackupCopy.cs b/src/Bydlo.Core/Backup/BackupCopy.cs
new file mode 100644
index 00000000..47256a35
--- /dev/null
+++ b/src/Bydlo.Core/Backup/BackupCopy.cs
@@ -0,0 +1,186 @@
+using Bydlo.Core.Models;
+using Bydlo.Core.Storage;
+
+namespace Bydlo.Core.Backup;
+
+///
+/// Typed deep copy of backup snapshots (issue #393). Replaces a JSON round-trip that
+/// produced an extra plaintext buffer with every secret. Mutable containers and models
+/// are copied; strings and immutable records are shared. BackupCopyTests fails
+/// when a model gains a property that is not copied here.
+///
+internal static class BackupCopy
+{
+ public static BackupData Copy(BackupData source) => new()
+ {
+ Version = source.Version,
+ Settings = source.Settings is null ? null! : Copy(source.Settings),
+ Profiles = source.Profiles?.Select(p => p is null ? null! : new ImportedProfile(Copy(p.Profile), Copy(p.Secrets))).ToList()!,
+ Subscriptions = source.Subscriptions?.Select(s => s is null ? null! : new BackupSubscription(Copy(s.Subscription), s.Url)).ToList()!,
+ ToolSecrets = Copy(source.ToolSecrets),
+ Chains = source.Chains?.Select(c => Copy(c)).ToList()!,
+ };
+
+ public static ProfileSecrets Copy(ProfileSecrets source) => source is null ? null! : new()
+ {
+ Values = source.Values is null ? null! : new(source.Values, source.Values.Comparer),
+ };
+
+ public static Profile Copy(Profile source) => source is null ? null! : new()
+ {
+ Id = source.Id,
+ Name = source.Name,
+ Protocol = source.Protocol,
+ Host = source.Host,
+ Port = source.Port,
+ Options = source.Options is null ? null! : new(source.Options, source.Options.Comparer),
+ SubscriptionId = source.SubscriptionId,
+ PreferredEngine = source.PreferredEngine,
+ AddedAt = source.AddedAt,
+ IsFavorite = source.IsFavorite,
+ };
+
+ public static Subscription Copy(Subscription source) => source is null ? null! : new()
+ {
+ Id = source.Id,
+ Name = source.Name,
+ LastUpdated = source.LastUpdated,
+ Upload = source.Upload,
+ Download = source.Download,
+ Total = source.Total,
+ Expires = source.Expires,
+ Title = source.Title,
+ UpdateIntervalHours = source.UpdateIntervalHours,
+ SupportUrl = source.SupportUrl,
+ Announce = source.Announce,
+ UserAgent = source.UserAgent,
+ Mode = source.Mode,
+ SourceOptions = source.SourceOptions?.ToDictionary(
+ entry => entry.Key,
+ entry => entry.Value is null ? null! : new Dictionary(entry.Value, entry.Value.Comparer)),
+ };
+
+ public static ProxyChain Copy(ProxyChain source) => source is null ? null! : new()
+ {
+ Id = source.Id,
+ Name = source.Name,
+ ProfileIds = source.ProfileIds is null ? null! : [.. source.ProfileIds],
+ PreferredEngine = source.PreferredEngine,
+ AddedAt = source.AddedAt,
+ IsFavorite = source.IsFavorite,
+ };
+
+ public static ServerGroup Copy(ServerGroup source) => source is null ? null! : new()
+ {
+ Id = source.Id,
+ Name = source.Name,
+ ProfileIds = source.ProfileIds is null ? null! : [.. source.ProfileIds],
+ SubscriptionId = source.SubscriptionId,
+ SelectedProfileId = source.SelectedProfileId,
+ Engine = source.Engine,
+ Mode = source.Mode,
+ ProbeUrl = source.ProbeUrl,
+ IntervalSeconds = source.IntervalSeconds,
+ ToleranceMs = source.ToleranceMs,
+ };
+
+ public static AppSettings Copy(AppSettings source) => new()
+ {
+ ServerGroups = source.ServerGroups?.Select(g => Copy(g)).ToList()!,
+ StartWithSystem = source.StartWithSystem,
+ ConnectOnStartup = source.ConnectOnStartup,
+ MinimizeToTray = source.MinimizeToTray,
+ ShowNotifications = source.ShowNotifications,
+ SuggestClipboardLinks = source.SuggestClipboardLinks,
+ Theme = source.Theme,
+ ReduceMotion = source.ReduceMotion,
+ InterfaceScale = source.InterfaceScale,
+ CustomThemeId = source.CustomThemeId,
+ Language = source.Language,
+ OnboardingCompleted = source.OnboardingCompleted,
+ ConsentAutomaticUpdates = source.ConsentAutomaticUpdates,
+ ConsentNotifications = source.ConsentNotifications,
+ ConsentThemes = source.ConsentThemes,
+ ConsentsInitialized = source.ConsentsInitialized,
+ MockMode = source.MockMode,
+ MockScenario = source.MockScenario,
+ LastProfileId = source.LastProfileId,
+ Mode = source.Mode,
+ LocalProxyPort = source.LocalProxyPort,
+ AllowLan = source.AllowLan,
+ LocalProxyUsername = source.LocalProxyUsername,
+ IpCheckProvider = source.IpCheckProvider,
+ SetSystemProxy = source.SetSystemProxy,
+ RunElevatedOnStartup = source.RunElevatedOnStartup,
+ KillSwitch = source.KillSwitch,
+ AutoReconnect = source.AutoReconnect,
+ ShowAdvanced = source.ShowAdvanced,
+ SubscriptionAutoUpdate = source.SubscriptionAutoUpdate,
+ SubscriptionUpdateIntervalHours = source.SubscriptionUpdateIntervalHours,
+ CheckForUpdates = source.CheckForUpdates,
+ AutoUpdateApp = source.AutoUpdateApp,
+ LastAutomaticUpdateCheck = source.LastAutomaticUpdateCheck,
+ LastUpdateCheck = source.LastUpdateCheck,
+ PendingUpdate = source.PendingUpdate,
+ Contributors = source.Contributors is null ? null! : [.. source.Contributors],
+ LastContributorsCheck = source.LastContributorsCheck,
+ DismissedNoticeId = source.DismissedNoticeId,
+ Routing = source.Routing is null ? null! : Copy(source.Routing),
+ DpiDefaults = source.DpiDefaults,
+ Zapret = source.Zapret is null ? null! : Copy(source.Zapret),
+ TgWsProxy = source.TgWsProxy is null ? null! : Copy(source.TgWsProxy),
+ EnginePaths = source.EnginePaths is null ? null! : new(source.EnginePaths, source.EnginePaths.Comparer),
+ };
+
+ private static List List(List source) => source is null ? null! : [.. source];
+
+ public static RoutingSettings Copy(RoutingSettings source) => new()
+ {
+ PreserveMeshVpnRanges = source.PreserveMeshVpnRanges,
+ BypassPrivateNetworks = source.BypassPrivateNetworks,
+ OrderedRules = List(source.OrderedRules),
+ RuleSetSources = List(source.RuleSetSources),
+ Preset = source.Preset,
+ PresetCountry = source.PresetCountry,
+ RemoteDns = source.RemoteDns,
+ DirectDns = source.DirectDns,
+ RemoteDnsTransport = source.RemoteDnsTransport,
+ DirectDnsTransport = source.DirectDnsTransport,
+ RemoteDnsThroughProxy = source.RemoteDnsThroughProxy,
+ DirectDnsThroughProxy = source.DirectDnsThroughProxy,
+ FakeIp = source.FakeIp,
+ FakeIpExceptions = List(source.FakeIpExceptions),
+ RemoteDnsDomains = List(source.RemoteDnsDomains),
+ DirectDnsDomains = List(source.DirectDnsDomains),
+ RemoteDnsRuleSets = List(source.RemoteDnsRuleSets),
+ DirectDnsRuleSets = List(source.DirectDnsRuleSets),
+ DirectDomains = List(source.DirectDomains),
+ ProxyDomains = List(source.ProxyDomains),
+ BlockDomains = List(source.BlockDomains),
+ DirectCidrs = List(source.DirectCidrs),
+ ProxyOnlyListed = source.ProxyOnlyListed,
+ DirectProcesses = List(source.DirectProcesses),
+ ProxyOnlyListedProcesses = source.ProxyOnlyListedProcesses,
+ };
+
+ public static ZapretSettings Copy(ZapretSettings source) => new()
+ {
+ TestTargets = List(source.TestTargets),
+ InstallPath = source.InstallPath,
+ Strategy = source.Strategy,
+ GameFilter = source.GameFilter,
+ };
+
+ public static TgWsProxySettings Copy(TgWsProxySettings source) => new()
+ {
+ Host = source.Host,
+ Port = source.Port,
+ DcIps = List(source.DcIps),
+ FakeTlsDomain = source.FakeTlsDomain,
+ Verbose = source.Verbose,
+ CfProxyFallback = source.CfProxyFallback,
+ CfProxyDomains = List(source.CfProxyDomains),
+ ProxyProtocol = source.ProxyProtocol,
+ ProxyProtocolTrustedSources = List(source.ProxyProtocolTrustedSources),
+ };
+}
diff --git a/src/Bydlo.Core/Backup/BackupImportSession.cs b/src/Bydlo.Core/Backup/BackupImportSession.cs
index 152f4803..f2d68dda 100644
--- a/src/Bydlo.Core/Backup/BackupImportSession.cs
+++ b/src/Bydlo.Core/Backup/BackupImportSession.cs
@@ -26,14 +26,15 @@ public sealed class BackupImportSession : IDisposable
private BackupImportSession(byte[] archive, byte[] key) { _archive = archive; _key = key; }
- internal static BackupImportSession Open(byte[] file, string password)
+ internal static BackupImportSession Open(byte[] file, string password, bool copy)
{
ArgumentException.ThrowIfNullOrWhiteSpace(password);
if (file.Length < BackupArchive.Overhead || file.Length > BackupArchive.MaximumFileSize ||
!file.AsSpan(0, 8).SequenceEqual(BackupArchive.Header))
{ throw new InvalidDataException("Unsupported backup."); }
- // Never retain a caller-owned array that can change after authentication.
- var archive = file.ToArray();
+ // Never retain a caller-owned array that can change after authentication; an owned
+ // array (OpenImportOwned) is already exclusive to the session.
+ var archive = copy ? file.ToArray() : file;
var key = Rfc2898DeriveBytes.Pbkdf2(password, archive.AsSpan(8, 16), BackupArchive.Iterations, HashAlgorithmName.SHA256, 32);
var session = new BackupImportSession(archive, key);
try
@@ -78,7 +79,7 @@ public BackupData Materialize()
ObjectDisposedException.ThrowIf(_disposed, this);
return ReadPlaintext(plaintext =>
{
- var data = JsonSerializer.Deserialize(plaintext, JsonDefaults.Options.Info())
+ var data = JsonSerializer.Deserialize(plaintext.Span, JsonDefaults.Options.Info())
?? throw new InvalidDataException("Invalid backup.");
BackupArchive.Validate(data);
return data;
@@ -86,25 +87,14 @@ public BackupData Materialize()
}
}
- private T ReadPlaintext(Func read)
- {
- var plaintext = new byte[_archive.Length - BackupArchive.Overhead];
- try
- {
- using var aes = new AesGcm(_key, 16);
- aes.Decrypt(_archive.AsSpan(24, 12), _archive.AsSpan(BackupArchive.Overhead),
- _archive.AsSpan(36, 16), plaintext, _archive.AsSpan(0, 24));
- return read(plaintext);
- }
- finally { CryptographicOperations.ZeroMemory(plaintext); }
- }
+ private T ReadPlaintext(Func, T> read) => BackupArchive.DecryptWith(_key, _archive, read);
- private static BackupData ReadMetadata(byte[] plaintext)
+ private static BackupData ReadMetadata(ReadOnlyMemory plaintext)
{
using var sanitized = new MemoryStream();
using (var writer = new Utf8JsonWriter(sanitized))
{
- var reader = new Utf8JsonReader(plaintext);
+ var reader = new Utf8JsonReader(plaintext.Span);
if (!reader.Read()) { throw new InvalidDataException("Invalid backup."); }
CopyValue(ref reader, writer, false, false);
if (reader.Read()) { throw new InvalidDataException("Invalid backup."); }
diff --git a/src/Bydlo.Core/Backup/BoundedBuffer.cs b/src/Bydlo.Core/Backup/BoundedBuffer.cs
new file mode 100644
index 00000000..08a1f6a6
--- /dev/null
+++ b/src/Bydlo.Core/Backup/BoundedBuffer.cs
@@ -0,0 +1,69 @@
+using System.Buffers;
+using System.Security.Cryptography;
+
+namespace Bydlo.Core.Backup;
+
+///
+/// Pooled with a reserved prefix and a hard size limit (issue #394).
+/// The limit is enforced while writing, so an oversized export fails before the result grows
+/// without bound. Every buffer is cleared before it returns to the pool because it may hold plaintext.
+///
+internal sealed class BoundedBuffer : IBufferWriter, IDisposable
+{
+ private readonly int _limit;
+ private byte[] _buffer;
+ private int _written;
+
+ public BoundedBuffer(int prefix, int limit)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(prefix);
+ ArgumentOutOfRangeException.ThrowIfLessThan(limit, prefix);
+ _limit = limit;
+ _buffer = ArrayPool.Shared.Rent(Math.Min(Math.Max(prefix + 4096, 64 * 1024), limit));
+ _written = prefix;
+ }
+
+ /// Prefix plus everything written so far.
+ public int WrittenCount => _written;
+
+ /// Backing array; only the first bytes are meaningful.
+ public byte[] Array => _buffer;
+
+ public void Advance(int count)
+ {
+ ArgumentOutOfRangeException.ThrowIfNegative(count);
+ if ((long)_written + count > _buffer.Length) { throw new InvalidOperationException("Advanced past the buffer."); }
+ if ((long)_written + count > _limit) { throw new InvalidDataException("Backup is too large."); }
+ _written += count;
+ }
+
+ public Memory GetMemory(int sizeHint = 0) { Ensure(sizeHint); return _buffer.AsMemory(_written); }
+
+ public Span GetSpan(int sizeHint = 0) { Ensure(sizeHint); return _buffer.AsSpan(_written); }
+
+ private void Ensure(int sizeHint)
+ {
+ if (_written >= _limit) { throw new InvalidDataException("Backup is too large."); }
+ var needed = (long)_written + Math.Max(sizeHint, 1);
+ if (needed <= _buffer.Length) { return; }
+ // Writers over-request for worst-case escaping, so the buffer may exceed the limit by one
+ // hint; Advance still rejects any data past the limit. The hint itself stays bounded.
+ if (needed > (long)_limit * 8) { throw new InvalidDataException("Backup is too large."); }
+ var size = (int)Math.Min(Math.Max(needed, (long)_buffer.Length * 2), Math.Max(needed, _limit));
+ var next = ArrayPool.Shared.Rent(size);
+ _buffer.AsSpan(0, _written).CopyTo(next);
+ CryptographicOperations.ZeroMemory(_buffer);
+ ArrayPool.Shared.Return(_buffer);
+ _buffer = next;
+ }
+
+ public void Dispose()
+ {
+ if (_buffer.Length == 0) { return; }
+ // Clear the whole array: a writer may have produced bytes it never advanced over.
+ CryptographicOperations.ZeroMemory(_buffer);
+ ArrayPool.Shared.Return(_buffer);
+ _buffer = [];
+ _written = 0;
+ }
+}
diff --git a/src/Bydlo.Core/Diagnostics/AptRepositorySource.cs b/src/Bydlo.Core/Diagnostics/AptRepositorySource.cs
new file mode 100644
index 00000000..dff42ed3
--- /dev/null
+++ b/src/Bydlo.Core/Diagnostics/AptRepositorySource.cs
@@ -0,0 +1,129 @@
+namespace Bydlo.Core.Diagnostics;
+
+///
+/// Read-only detection of a configured BYDLO apt source (issue #488). The application never runs apt
+/// and never writes to /etc: it only reads the source files to decide which update text to show.
+///
+public static class AptRepositorySource
+{
+ /// Public apt repository published by the release workflow to GitHub Pages.
+ public const string RepositoryUri = "https://endercodezz.github.io/BYDLO/";
+
+ /// Directory with the deb822 *.sources and one-line *.list files.
+ public const string DefaultSourcesDirectory = "/etc/apt/sources.list.d";
+
+ /// Main source list; a repository added here counts as configured too.
+ public const string DefaultSourcesListFile = "/etc/apt/sources.list";
+
+ private static readonly Uri Repository = new(RepositoryUri, UriKind.Absolute);
+
+ private static readonly string RepositoryPath = Repository.AbsolutePath.TrimEnd('/');
+
+ ///
+ /// True when any enabled apt source points at the BYDLO repository. Unreadable or missing files mean
+ /// "not configured", so the UI never promises apt updates it cannot verify.
+ ///
+ public static bool IsConfigured(
+ string sourcesDirectory = DefaultSourcesDirectory,
+ string? sourcesListFile = DefaultSourcesListFile)
+ {
+ try
+ {
+ if (sourcesListFile is not null && MentionsRepository(ReadOrNull(sourcesListFile)))
+ {
+ return true;
+ }
+ if (!Directory.Exists(sourcesDirectory))
+ {
+ return false;
+ }
+ foreach (var file in Directory.EnumerateFiles(sourcesDirectory))
+ {
+ var name = Path.GetFileName(file);
+ if (!name.EndsWith(".sources", StringComparison.OrdinalIgnoreCase) &&
+ !name.EndsWith(".list", StringComparison.OrdinalIgnoreCase))
+ {
+ continue;
+ }
+ if (MentionsRepository(ReadOrNull(file)))
+ {
+ return true;
+ }
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ return false;
+ }
+
+ ///
+ /// True when the text of a source file names the BYDLO repository. Commented-out lines and deb822
+ /// stanzas with Enabled: no are ignored, because apt ignores them as well.
+ ///
+ public static bool MentionsRepository(string? text)
+ {
+ if (string.IsNullOrWhiteSpace(text))
+ {
+ return false;
+ }
+ foreach (var stanza in text.Replace("\r\n", "\n", StringComparison.Ordinal)
+ .Split("\n\n", StringSplitOptions.RemoveEmptyEntries))
+ {
+ var lines = stanza.Split('\n').Select(StripComment).ToArray();
+ if (lines.Any(IsDisabledLine))
+ {
+ continue;
+ }
+ foreach (var token in lines.SelectMany(line =>
+ line.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries)))
+ {
+ if (IsRepositoryUri(token))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static string StripComment(string line)
+ {
+ var comment = line.IndexOf('#', StringComparison.Ordinal);
+ return comment >= 0 ? line[..comment] : line;
+ }
+
+ private static bool IsDisabledLine(string line)
+ {
+ var trimmed = line.Trim();
+ return trimmed.StartsWith("Enabled:", StringComparison.OrdinalIgnoreCase) &&
+ trimmed[(trimmed.IndexOf(':') + 1)..].Trim().Equals("no", StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static bool IsRepositoryUri(string token)
+ {
+ var value = token.Trim('"', '\'', ',', ';');
+ if (!Uri.TryCreate(value, UriKind.Absolute, out var uri) ||
+ (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
+ {
+ return false;
+ }
+ var path = uri.AbsolutePath.TrimEnd('/');
+ return uri.Host.Equals(Repository.Host, StringComparison.OrdinalIgnoreCase) &&
+ (path.Equals(RepositoryPath, StringComparison.OrdinalIgnoreCase) ||
+ path.StartsWith(RepositoryPath + "/", StringComparison.OrdinalIgnoreCase));
+ }
+
+ private static string? ReadOrNull(string path)
+ {
+ try
+ {
+ return File.Exists(path) ? File.ReadAllText(path) : null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+}
diff --git a/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs b/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs
index 2cba2bd1..3045413e 100644
--- a/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs
+++ b/src/Bydlo.Core/Diagnostics/AutomaticAppUpdater.cs
@@ -6,6 +6,10 @@ namespace Bydlo.Core.Diagnostics;
public interface IAppUpdateBackend
{
bool IsInstalled { get; }
+
+ /// Version of the package that installs on the next exit, if one is downloaded (issue #412).
+ string? PendingVersion { get; }
+
Task DownloadLatestAsync(IProgress? progress, CancellationToken ct);
void ApplyOnExit();
}
@@ -34,6 +38,12 @@ public static bool HasSeparateDataDirectory(string applicationDirectory, string
/// Who owns updates for this copy. Only a Velopack install may update itself.
public AppUpdateOwner Owner => AppUpdateOwnership.OwnerOf(InstallKind);
+ ///
+ /// Local recovery protocol (issue #412). When it is set, a package is applied only after the journal and
+ /// the user-data snapshot exist, and a failed confirmation stops automatic updates.
+ ///
+ public UpdateRecovery? Recovery { get; set; }
+
/// Single user-visible state shared by the release check and the packaged updater.
public AppUpdateState State { get; private set; }
@@ -119,6 +129,8 @@ public async Task DownloadIfDueAsync(AppSettings settings, bool blocked,
public Task DownloadNowAsync(AppSettings settings, bool blocked,
IProgress? progress = null, CancellationToken ct = default)
{
+ // An explicit request is the only way out of a failed-confirmation block (issue #412).
+ Recovery?.ClearBlock();
if (!AllowsUpdates(settings) || blocked || _busy) { return Task.FromResult(false); }
return DownloadAsync(settings, progress, ct);
}
@@ -126,9 +138,11 @@ public Task DownloadNowAsync(AppSettings settings, bool blocked,
///
/// The packaged update needs both the explicit GitHub consent and the download opt-in (issue #438).
/// Revoking either one stops future downloads and blocks a package that is already staged.
+ /// A failed confirmation of the previous version also stops automatic updates (issue #412).
///
- private static bool AllowsUpdates(AppSettings settings) =>
- settings.AutoUpdateApp && FeatureConsent.From(settings).Allows(OptionalFeature.AutomaticUpdates);
+ private bool AllowsUpdates(AppSettings settings) =>
+ settings.AutoUpdateApp && FeatureConsent.From(settings).Allows(OptionalFeature.AutomaticUpdates) &&
+ Recovery?.AutoApplyBlocked != true;
private async Task DownloadAsync(AppSettings settings, IProgress? progress, CancellationToken ct)
{
@@ -165,6 +179,12 @@ private async Task DownloadAsync(AppSettings settings, IProgress? pro
State = AvailableVersion is null ? AppUpdateState.Idle : AppUpdateState.Available;
return false;
}
+ // A package without a recovery journal and snapshot is never applied (issue #412).
+ if (Recovery is not null && !Recovery.Stage(backend.PendingVersion))
+ {
+ State = AppUpdateState.Deferred;
+ return false;
+ }
// Turning the opt-in off during the download keeps the package but never applies it.
State = settings.AutoUpdateApp && !ct.IsCancellationRequested
? AppUpdateState.Ready
@@ -190,6 +210,11 @@ public AppUpdateApplyResult ApplyOnExit(AppSettings settings, bool blocked)
}
try
{
+ // Without a durable journal and snapshot the package stays downloaded (issue #412).
+ if (Recovery is not null && (!Recovery.CanApply(_backend!.PendingVersion) || !Recovery.MarkApplying()))
+ {
+ return AppUpdateApplyResult.Deferred;
+ }
_backend!.ApplyOnExit();
}
catch (Exception)
diff --git a/src/Bydlo.Core/Diagnostics/UpdateRecovery.cs b/src/Bydlo.Core/Diagnostics/UpdateRecovery.cs
new file mode 100644
index 00000000..e0066711
--- /dev/null
+++ b/src/Bydlo.Core/Diagnostics/UpdateRecovery.cs
@@ -0,0 +1,609 @@
+using System.Text.Json;
+using Bydlo.Core.Serialization;
+using Bydlo.Core.Storage;
+
+namespace Bydlo.Core.Diagnostics;
+
+/// Phase of the local update recovery journal (issue #412).
+public enum UpdateRecoveryPhase
+{
+ /// The package is downloaded and verified, the snapshot exists, no file was replaced yet.
+ Staged,
+
+ /// The package was handed to the installer and this process is exiting.
+ Applying,
+
+ /// The new version started but has not confirmed readiness yet.
+ PendingConfirmation,
+
+ /// The new version started, the UI came up, user data loaded and the components match.
+ Confirmed,
+
+ ///
+ /// The protocol returned to the last known-good state: the previous version is running again or the
+ /// snapshot was restored. BYDLO never replaces application files itself, so this is not a binary rollback.
+ ///
+ RolledBack,
+}
+
+/// Why the protocol stopped trying (issue #412).
+public enum UpdateRecoveryReason
+{
+ None,
+
+ /// The installer never replaced the files: the previous version started again.
+ Interrupted,
+
+ /// The new version started but failed the readiness check too many times.
+ NotReady,
+}
+
+/// What the startup recovery decided; drives the localized message and the auto-apply guard.
+public enum UpdateRecoveryStartup
+{
+ /// This copy is not a Velopack install: recovery never touches it.
+ Ignored,
+
+ /// No journal, or the last update was already confirmed.
+ Nothing,
+
+ /// The new version is running and waits for the UI to confirm readiness.
+ AwaitingConfirmation,
+
+ /// The installer did not replace the files; the previous version is running.
+ Interrupted,
+
+ /// The attempt budget is exhausted: automatic updates stay off until the user asks explicitly.
+ Blocked,
+}
+
+/// Outcome of .
+public enum UpdateRecoveryConfirmation
+{
+ /// No confirmation was pending.
+ Nothing,
+
+ /// The new version is proven and the snapshot was dropped.
+ Confirmed,
+
+ /// The check failed but the attempt budget is not exhausted; the next start retries.
+ Retry,
+
+ /// The budget is exhausted: automatic updates are paused and the next start restores the snapshot.
+ RolledBack,
+}
+
+///
+/// Durable record of one update transition (issue #412). Written atomically before the installer runs and
+/// updated at every phase, so an interrupted write or a crash at any step leaves a readable state.
+///
+public sealed class UpdateRecoveryJournal
+{
+ public int Version { get; set; } = 1;
+
+ public UpdateRecoveryPhase Phase { get; set; }
+
+ public UpdateRecoveryReason Reason { get; set; }
+
+ /// Version that was running when the package was staged.
+ public string? FromVersion { get; set; }
+
+ /// Version the staged package installs.
+ public string? ToVersion { get; set; }
+
+ /// Hash of the pinned engine lock the staged package was built with.
+ public string? EngineBundleVersion { get; set; }
+
+ /// Starts of the new version that did not confirm readiness, or interrupted applies.
+ public int Attempts { get; set; }
+
+ /// Automatic downloads and installs stay off until the user asks explicitly.
+ public bool AutoApplyBlocked { get; set; }
+
+ /// Directory of the user-data snapshot taken before the first run of the new version.
+ public string? SnapshotDirectory { get; set; }
+
+ public DateTimeOffset UpdatedAt { get; set; }
+
+ /// Blocking readiness checks that failed, as short identifiers.
+ public List FailedChecks { get; set; } = [];
+
+ /// Informational findings, e.g. an outdated privileged helper.
+ public List Notes { get; set; } = [];
+}
+
+///
+/// Local readiness of a freshly installed version (issue #412). Only local state is inspected: no tunnel,
+/// engine, driver, service or network request is involved.
+///
+public sealed class UpdateReadiness
+{
+ public UpdateReadiness(bool uiStarted, bool userDataLoaded, bool componentsConsistent, bool helperCompatible)
+ {
+ UiStarted = uiStarted;
+ UserDataLoaded = userDataLoaded;
+ ComponentsConsistent = componentsConsistent;
+ HelperCompatible = helperCompatible;
+ var failures = new List();
+ if (!uiStarted) { failures.Add("ui"); }
+ if (!userDataLoaded) { failures.Add("user-data"); }
+ if (!componentsConsistent) { failures.Add("components"); }
+ Failures = failures;
+ // An outdated helper degrades privileged features but never blocks the app: it is reported, not fatal.
+ Notes = helperCompatible ? [] : ["helper"];
+ }
+
+ public bool UiStarted { get; }
+
+ /// Settings and profiles parsed without falling back to an empty document.
+ public bool UserDataLoaded { get; }
+
+ /// Running application and pinned engine bundle match the versions recorded at staging.
+ public bool ComponentsConsistent { get; }
+
+ /// Installed privileged helper matches this build, or no helper is installed.
+ public bool HelperCompatible { get; }
+
+ public bool IsReady => UiStarted && UserDataLoaded && ComponentsConsistent;
+
+ public IReadOnlyList Failures { get; }
+
+ public IReadOnlyList Notes { get; }
+}
+
+///
+/// Answers whether the installer kept a full package of another version next to the application (issue #412).
+/// BYDLO mentions that path only when the file is really there and never runs the installer itself.
+///
+public interface IUpdateRollbackProbe
+{
+ bool HasPreviousPackage(string applicationDirectory, string currentVersion);
+}
+
+/// Read-only directory probe; a missing or unreadable folder means "no previous package".
+public sealed class FileSystemRollbackProbe : IUpdateRollbackProbe
+{
+ public bool HasPreviousPackage(string applicationDirectory, string currentVersion)
+ {
+ // Without the application directory the layout is unknown, so no rollback path is promised.
+ if (!Directory.Exists(applicationDirectory)) { return false; }
+ // Windows keeps /current next to /packages; other layouts simply have no such folder.
+ foreach (var directory in new[]
+ {
+ Path.Combine(applicationDirectory, "packages"),
+ Path.Combine(applicationDirectory, "..", "packages"),
+ })
+ {
+ try
+ {
+ if (!Directory.Exists(directory)) { continue; }
+ foreach (var file in Directory.EnumerateFiles(directory, "*-full.nupkg"))
+ {
+ if (!Path.GetFileName(file).Contains("-" + currentVersion + "-", StringComparison.OrdinalIgnoreCase))
+ {
+ return true;
+ }
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ }
+ }
+ return false;
+ }
+}
+
+///
+/// Copies the user data files the updater must never lose (issue #412). Secrets live in the secret store,
+/// which the updater does not touch, so they are not copied here.
+///
+public sealed class UpdateSnapshot(string directoryPath)
+{
+ public const string SettingsFileName = "settings.json";
+
+ public const string ProfilesFileName = "profiles.json";
+
+ private static readonly string[] Files = [SettingsFileName, ProfilesFileName];
+
+ public string DirectoryPath { get; } = directoryPath;
+
+ /// Copies the user data files that exist. False means the snapshot could not be written.
+ public bool TryCreate(string dataDirectory)
+ {
+ try
+ {
+ Directory.CreateDirectory(DirectoryPath);
+ foreach (var name in Files)
+ {
+ var source = Path.Combine(dataDirectory, name);
+ if (File.Exists(source))
+ {
+ File.Copy(source, Path.Combine(DirectoryPath, name), overwrite: true);
+ }
+ }
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// Restores only files that are missing or no longer parse. A readable file is never overwritten, so
+ /// changes made in the new version are not silently discarded.
+ ///
+ public IReadOnlyList RestoreMissingOrBroken(string dataDirectory)
+ {
+ var restored = new List();
+ foreach (var name in Files)
+ {
+ var source = Path.Combine(DirectoryPath, name);
+ if (!File.Exists(source)) { continue; }
+ var target = Path.Combine(dataDirectory, name);
+ if (File.Exists(target) && Parses(target)) { continue; }
+ try
+ {
+ File.Copy(source, target, overwrite: true);
+ restored.Add(name);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ }
+ }
+ return restored;
+ }
+
+ public void Delete()
+ {
+ try
+ {
+ if (Directory.Exists(DirectoryPath)) { Directory.Delete(DirectoryPath, recursive: true); }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ }
+ }
+
+ private static bool Parses(string path)
+ {
+ try
+ {
+ using var stream = File.OpenRead(path);
+ using var document = JsonDocument.Parse(stream);
+ return true;
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ }
+}
+
+///
+/// Atomic, corruption-tolerant journal file (issue #412). A missing, truncated or unreadable file means
+/// "no journal": recovery then does nothing instead of guessing, and the broken file is kept for diagnostics.
+///
+public sealed class UpdateRecoveryStore(string path)
+{
+ /// Journal format this build understands. A newer file is ignored instead of guessed.
+ public const int CurrentVersion = 1;
+
+ public string Path { get; } = path;
+
+ public UpdateRecoveryJournal? Load()
+ {
+ try
+ {
+ if (!File.Exists(Path)) { return null; }
+ using var stream = File.OpenRead(Path);
+ var journal = JsonSerializer.Deserialize(stream, JsonDefaults.Options.Info());
+ return journal is { Version: > 0 and <= CurrentVersion, ToVersion.Length: > 0 } ? journal : null;
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
+ {
+ JsonDefaults.SaveCorruptCopy(Path);
+ return null;
+ }
+ }
+
+ /// Writes through a temporary file and a rename: a crash leaves the old or the new file, never half of it.
+ public bool TrySave(UpdateRecoveryJournal journal)
+ {
+ var tmp = Path + ".tmp";
+ try
+ {
+ Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path)!);
+ using (var stream = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
+ {
+ JsonSerializer.Serialize(stream, journal, JsonDefaults.Options.Info());
+ stream.Flush(flushToDisk: true);
+ }
+ File.Move(tmp, Path, overwrite: true);
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ try { File.Delete(tmp); }
+ catch (Exception cleanup) when (cleanup is IOException or UnauthorizedAccessException) { }
+ return false;
+ }
+ }
+}
+
+///
+/// Minimal recovery protocol around the existing Velopack updater (issue #412). It never installs anything
+/// itself: it records the transition, snapshots user data, confirms the new version locally and stops
+/// automatic updates when the new version does not come up. Package-manager installs are never touched.
+///
+public sealed class UpdateRecovery
+{
+ /// Starts of an unconfirmed version (or interrupted applies) before automatic updates stop.
+ public const int MaxAttempts = 2;
+
+ public const string JournalFileName = "update-recovery.json";
+
+ public const string SnapshotDirectoryName = "update-recovery";
+
+ public const string SnapshotFolderName = "snapshot";
+
+ private readonly UpdateRecoveryStore _store;
+ private readonly UpdateSnapshot _snapshot;
+ private readonly IUpdateRollbackProbe _rollback;
+ private readonly TimeProvider _time;
+ private readonly AppInstallKind _installKind;
+ private readonly string _applicationDirectory;
+ private readonly string _currentVersion;
+ private readonly string _engineBundleVersion;
+ private bool? _previousPackageAvailable;
+
+ public UpdateRecovery(string dataDirectory, string applicationDirectory, AppInstallKind installKind,
+ string currentVersion, string engineBundleVersion, IUpdateRollbackProbe? rollback = null,
+ TimeProvider? time = null)
+ {
+ DataDirectory = dataDirectory;
+ _applicationDirectory = applicationDirectory;
+ _installKind = installKind;
+ _currentVersion = currentVersion;
+ _engineBundleVersion = engineBundleVersion;
+ _rollback = rollback ?? new FileSystemRollbackProbe();
+ _time = time ?? TimeProvider.System;
+ _store = new UpdateRecoveryStore(Path.Combine(dataDirectory, JournalFileName));
+ _snapshot = new UpdateSnapshot(Path.Combine(dataDirectory, SnapshotDirectoryName, SnapshotFolderName));
+ }
+
+ public string DataDirectory { get; }
+
+ public UpdateRecoveryJournal? Journal { get; private set; }
+
+ /// What decided for this start.
+ public UpdateRecoveryStartup Startup { get; private set; } = UpdateRecoveryStartup.Nothing;
+
+ /// Only a Velopack install may run the protocol; deb, Arch and Nix copies are owned by their manager.
+ public bool IsOwned => _installKind == AppInstallKind.Velopack;
+
+ public bool AutoApplyBlocked => Journal?.AutoApplyBlocked == true;
+
+ /// True while the running version still has to confirm readiness.
+ public bool IsPending => Journal?.Phase == UpdateRecoveryPhase.PendingConfirmation;
+
+ /// True only when the installer really kept a package of another version next to the app.
+ public bool PreviousPackageAvailable => _previousPackageAvailable ??=
+ IsOwned && _rollback.HasPreviousPackage(_applicationDirectory, _currentVersion);
+
+ ///
+ /// Runs before any user data is read. Decides the phase for this start, counts the attempt and, when the
+ /// budget is exhausted, restores the snapshot so the app starts from the last known-good data.
+ ///
+ public UpdateRecoveryStartup PrepareStartup()
+ {
+ if (!IsOwned)
+ {
+ Startup = UpdateRecoveryStartup.Ignored;
+ return Startup;
+ }
+
+ Journal = _store.Load();
+ if (Journal is not { } journal)
+ {
+ Startup = UpdateRecoveryStartup.Nothing;
+ return Startup;
+ }
+
+ if (journal.Phase == UpdateRecoveryPhase.Confirmed)
+ {
+ Startup = UpdateRecoveryStartup.Nothing;
+ return Startup;
+ }
+
+ if (journal.Phase == UpdateRecoveryPhase.RolledBack)
+ {
+ // The restore always happens here, before user data is read, so the app starts from the snapshot.
+ if (journal.AutoApplyBlocked && _snapshot.RestoreMissingOrBroken(DataDirectory).Count > 0)
+ {
+ journal.Notes.Add("snapshot-restored");
+ Save(journal);
+ }
+ Startup = journal.AutoApplyBlocked ? UpdateRecoveryStartup.Blocked : UpdateRecoveryStartup.Nothing;
+ return Startup;
+ }
+
+ var runningTarget = SameVersion(journal.ToVersion, _currentVersion);
+ if (journal.Phase == UpdateRecoveryPhase.Staged && !runningTarget)
+ {
+ // The package is downloaded but the installer never ran: nothing was replaced and nothing is lost.
+ Startup = UpdateRecoveryStartup.Nothing;
+ return Startup;
+ }
+
+ if ((journal.Phase is UpdateRecoveryPhase.Staged or UpdateRecoveryPhase.Applying) && runningTarget)
+ {
+ // The new version is running; the UI confirms readiness later in this start.
+ journal.Phase = UpdateRecoveryPhase.PendingConfirmation;
+ journal.Attempts = 1;
+ Save(journal);
+ Startup = UpdateRecoveryStartup.AwaitingConfirmation;
+ return Startup;
+ }
+
+ if (journal.Phase == UpdateRecoveryPhase.Applying)
+ {
+ // The installer ran but the previous version started again.
+ return RollBack(journal, UpdateRecoveryReason.Interrupted);
+ }
+
+ if (!runningTarget)
+ {
+ // PendingConfirmation for another version: the new one never started.
+ return RollBack(journal, UpdateRecoveryReason.Interrupted);
+ }
+
+ // Another start of the version that still has not confirmed readiness.
+ journal.Attempts++;
+ if (journal.Attempts > MaxAttempts)
+ {
+ return RollBack(journal, UpdateRecoveryReason.NotReady);
+ }
+ Save(journal);
+ Startup = UpdateRecoveryStartup.AwaitingConfirmation;
+ return Startup;
+ }
+
+ ///
+ /// Records a verified package and snapshots user data before anything is replaced. False means the journal
+ /// or the snapshot could not be written: the package must then never be applied.
+ ///
+ public bool Stage(string? toVersion)
+ {
+ if (!IsOwned || string.IsNullOrWhiteSpace(toVersion)) { return false; }
+ if (!_snapshot.TryCreate(DataDirectory)) { return false; }
+ // An interrupted apply keeps its count, so a package that never replaces the files cannot loop forever.
+ var previous = Journal ?? _store.Load();
+ var attempts = previous is { Phase: UpdateRecoveryPhase.RolledBack, Reason: UpdateRecoveryReason.Interrupted }
+ ? previous.Attempts
+ : 0;
+ var journal = new UpdateRecoveryJournal
+ {
+ Phase = UpdateRecoveryPhase.Staged,
+ FromVersion = _currentVersion,
+ ToVersion = toVersion,
+ EngineBundleVersion = _engineBundleVersion,
+ Attempts = attempts,
+ SnapshotDirectory = _snapshot.DirectoryPath,
+ UpdatedAt = _time.GetUtcNow(),
+ };
+ if (!_store.TrySave(journal)) { return false; }
+ Journal = journal;
+ return true;
+ }
+
+ ///
+ /// Marks the hand-over to the installer. False means the journal cannot be written, so the package must not
+ /// be applied: without a durable journal there is no recovery.
+ ///
+ public bool MarkApplying()
+ {
+ if (!IsOwned || Journal is not { } journal || journal.Phase != UpdateRecoveryPhase.Staged) { return false; }
+ journal.Phase = UpdateRecoveryPhase.Applying;
+ journal.UpdatedAt = _time.GetUtcNow();
+ return _store.TrySave(journal);
+ }
+
+ /// True only when a staged journal and its snapshot exist for the package that is about to install.
+ public bool CanApply(string? pendingVersion)
+ {
+ if (!IsOwned || Journal is not { } journal || journal.Phase != UpdateRecoveryPhase.Staged) { return false; }
+ if (pendingVersion is { Length: > 0 } && !SameVersion(journal.ToVersion, pendingVersion))
+ {
+ return false;
+ }
+ return journal.SnapshotDirectory is { Length: > 0 } && Directory.Exists(journal.SnapshotDirectory);
+ }
+
+ /// Compares the running build with the versions recorded when the package was staged.
+ public bool ComponentsConsistent(string appVersion, string engineBundleVersion) =>
+ Journal is not { } journal ||
+ (SameVersion(journal.ToVersion, appVersion) &&
+ string.Equals(journal.EngineBundleVersion, engineBundleVersion, StringComparison.Ordinal));
+
+ /// Records the local readiness result of the running version.
+ public UpdateRecoveryConfirmation Confirm(UpdateReadiness readiness)
+ {
+ if (!IsOwned || Journal is not { } journal || journal.Phase != UpdateRecoveryPhase.PendingConfirmation)
+ {
+ return UpdateRecoveryConfirmation.Nothing;
+ }
+
+ journal.FailedChecks = [.. readiness.Failures];
+ journal.Notes = [.. readiness.Notes];
+ if (readiness.IsReady)
+ {
+ journal.Phase = UpdateRecoveryPhase.Confirmed;
+ journal.Reason = UpdateRecoveryReason.None;
+ journal.Attempts = 0;
+ journal.AutoApplyBlocked = false;
+ Save(journal);
+ // The new version is proven; the snapshot of the previous one is no longer needed.
+ _snapshot.Delete();
+ Startup = UpdateRecoveryStartup.Nothing;
+ return UpdateRecoveryConfirmation.Confirmed;
+ }
+
+ if (journal.Attempts >= MaxAttempts)
+ {
+ journal.Phase = UpdateRecoveryPhase.RolledBack;
+ journal.Reason = UpdateRecoveryReason.NotReady;
+ journal.AutoApplyBlocked = true;
+ // The snapshot is restored by the next start, before any user data is read.
+ Save(journal);
+ Startup = UpdateRecoveryStartup.Blocked;
+ return UpdateRecoveryConfirmation.RolledBack;
+ }
+
+ Save(journal);
+ return UpdateRecoveryConfirmation.Retry;
+ }
+
+ /// Explicit user request: allows automatic updates again after a failed confirmation.
+ public void ClearBlock()
+ {
+ if (Journal is not { AutoApplyBlocked: true } journal) { return; }
+ journal.AutoApplyBlocked = false;
+ Save(journal);
+ Startup = UpdateRecoveryStartup.Nothing;
+ }
+
+ private UpdateRecoveryStartup RollBack(UpdateRecoveryJournal journal, UpdateRecoveryReason reason)
+ {
+ journal.Phase = UpdateRecoveryPhase.RolledBack;
+ journal.Reason = reason;
+ journal.Attempts++;
+ journal.AutoApplyBlocked = journal.Attempts >= MaxAttempts;
+ if (journal.AutoApplyBlocked && _snapshot.RestoreMissingOrBroken(DataDirectory).Count > 0)
+ {
+ journal.Notes.Add("snapshot-restored");
+ }
+ Save(journal);
+ Startup = journal.AutoApplyBlocked ? UpdateRecoveryStartup.Blocked : UpdateRecoveryStartup.Interrupted;
+ return Startup;
+ }
+
+ private void Save(UpdateRecoveryJournal journal)
+ {
+ journal.UpdatedAt = _time.GetUtcNow();
+ // A failed write keeps the previous phase, which is safe: the next start re-evaluates the same state.
+ _store.TrySave(journal);
+ }
+
+ ///
+ /// Velopack reports 0.4.5 while the assembly may report 0.4.5.0; both name the same release.
+ ///
+ private static bool SameVersion(string? left, string? right)
+ {
+ if (string.Equals(left, right, StringComparison.Ordinal)) { return true; }
+ return Version.TryParse(left, out var a) && Version.TryParse(right, out var b) &&
+ a.Major == b.Major && a.Minor == b.Minor &&
+ Math.Max(a.Build, 0) == Math.Max(b.Build, 0) &&
+ Math.Max(a.Revision, 0) == Math.Max(b.Revision, 0);
+ }
+}
diff --git a/src/Bydlo.Core/Models/AppSettings.cs b/src/Bydlo.Core/Models/AppSettings.cs
index 2e57c123..77bbbad6 100644
--- a/src/Bydlo.Core/Models/AppSettings.cs
+++ b/src/Bydlo.Core/Models/AppSettings.cs
@@ -53,6 +53,52 @@ public sealed class AppSettings
public bool ReduceMotion { get; set; }
+ ///
+ /// Interface scale in percent (issue #477). The shell applies it once through a layout transform,
+ /// so text, buttons, fields, paddings and icons grow together and stay vector-sharp.
+ ///
+ public int InterfaceScale { get; set; } = DefaultInterfaceScale;
+
+ public const int DefaultInterfaceScale = 100;
+
+ public const int MinInterfaceScale = 80;
+
+ public const int MaxInterfaceScale = 150;
+
+ public const int InterfaceScaleStep = 10;
+
+ /// Every selectable scale, ascending. The default is in the middle of the list.
+ public static IReadOnlyList InterfaceScaleSteps { get; } =
+ [.. Enumerable.Range(0, (MaxInterfaceScale - MinInterfaceScale) / InterfaceScaleStep + 1)
+ .Select(index => MinInterfaceScale + index * InterfaceScaleStep)];
+
+ ///
+ /// Clamps a stored, imported or hand-edited scale to the supported range and snaps it to the
+ /// nearest step, so the UI never shows a value it cannot offer.
+ ///
+ public static int ClampInterfaceScale(int value)
+ {
+ var clamped = Math.Clamp(value, MinInterfaceScale, MaxInterfaceScale);
+ var steps = (clamped - MinInterfaceScale + InterfaceScaleStep / 2) / InterfaceScaleStep;
+ return MinInterfaceScale + steps * InterfaceScaleStep;
+ }
+
+ /// Layout multiplier for ; 1.0 is 100%.
+ [System.Text.Json.Serialization.JsonIgnore]
+ public double InterfaceScaleFactor => ClampInterfaceScale(InterfaceScale) / 100.0;
+
+ /// Repairs a scale written by an older build or edited by hand. Returns true when changed.
+ public bool NormalizeInterfaceScale()
+ {
+ var clamped = ClampInterfaceScale(InterfaceScale);
+ if (clamped == InterfaceScale)
+ {
+ return false;
+ }
+ InterfaceScale = clamped;
+ return true;
+ }
+
/// Installed custom theme id (file themes/<id>.json). Used only when is Custom.
public string? CustomThemeId { get; set; }
@@ -311,4 +357,13 @@ public sealed class TgWsProxySettings
/// Own Cloudflare-proxied domains for the fallback. Empty uses the list maintained by Flowseal.
public List CfProxyDomains { get; set; } = [];
+
+ ///
+ /// Accept a PROXY protocol v1 header before the client handshake (upstream --proxy-protocol).
+ /// Only for a listener placed behind a trusted reverse proxy; off by default.
+ ///
+ public bool ProxyProtocol { get; set; }
+
+ /// Peers allowed to send the header. Empty means loopback only, the default.
+ public List ProxyProtocolTrustedSources { get; set; } = ["127.0.0.1", "::1"];
}
diff --git a/src/Bydlo.Core/Serialization/BydloJson.cs b/src/Bydlo.Core/Serialization/BydloJson.cs
index f4fa04a4..c033cb13 100644
--- a/src/Bydlo.Core/Serialization/BydloJson.cs
+++ b/src/Bydlo.Core/Serialization/BydloJson.cs
@@ -71,6 +71,7 @@ internal sealed partial class CoreJsonContext : JsonSerializerContext;
[JsonSerializable(typeof(ProxyChain))]
[JsonSerializable(typeof(ProfileDocument))]
[JsonSerializable(typeof(BackupData))]
+[JsonSerializable(typeof(UpdateRecoveryJournal))]
internal sealed partial class CoreStoreJsonContext : JsonSerializerContext;
/// De-duplication key of an imported profile (property order is the serialized identity).
diff --git a/src/Bydlo.Core/Storage/JsonFileStore.cs b/src/Bydlo.Core/Storage/JsonFileStore.cs
index 63c489f7..9973a20c 100644
--- a/src/Bydlo.Core/Storage/JsonFileStore.cs
+++ b/src/Bydlo.Core/Storage/JsonFileStore.cs
@@ -191,6 +191,7 @@ public async Task LoadAsync(CancellationToken ct = default)
LoadStatus = status;
var result = settings ?? new AppSettings();
result.MigrateLegacyTheme();
+ result.NormalizeInterfaceScale();
return result;
}
diff --git a/src/Bydlo.Core/Storage/ProfileStore.Backup.cs b/src/Bydlo.Core/Storage/ProfileStore.Backup.cs
index 722ca212..8f08b9cb 100644
--- a/src/Bydlo.Core/Storage/ProfileStore.Backup.cs
+++ b/src/Bydlo.Core/Storage/ProfileStore.Backup.cs
@@ -12,7 +12,7 @@ public async Task CaptureBackupAsync(AppSettings settings, Cancellat
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
- var data = new BackupData { Settings = BackupArchive.Clone(settings), ToolSecrets = await CaptureToolSecretsAsync(ct).ConfigureAwait(false) };
+ var data = new BackupData { Settings = BackupCopy.Copy(settings), ToolSecrets = await CaptureToolSecretsAsync(ct).ConfigureAwait(false) };
data.Settings.EnginePaths.Clear();
data.Settings.Zapret.InstallPath = null;
foreach (var profile in _doc.Profiles)
@@ -31,7 +31,7 @@ public async Task CaptureBackupAsync(AppSettings settings, Cancellat
{
throw new Security.SecretAccessException(secretId);
}
- data.Profiles.Add(new(BackupArchive.Clone(profile), loaded));
+ data.Profiles.Add(new(BackupCopy.Copy(profile), loaded));
}
foreach (var sub in _doc.Subscriptions)
{
@@ -48,10 +48,10 @@ public async Task CaptureBackupAsync(AppSettings settings, Cancellat
{
throw new Security.SecretAccessException($"subscription:{sub.Id}");
}
- data.Subscriptions.Add(new(BackupArchive.Clone(sub), url));
+ data.Subscriptions.Add(new(BackupCopy.Copy(sub), url));
}
foreach (var chain in _doc.Chains)
- { data.Chains.Add(BackupArchive.Clone(chain)); }
+ { data.Chains.Add(BackupCopy.Copy(chain)); }
return data;
}
finally { _gate.Release(); }
@@ -60,7 +60,7 @@ public async Task CaptureBackupAsync(AppSettings settings, Cancellat
/// Restores credentials and the document together; rolls back on a storage failure.
public async Task RestoreBackupAsync(BackupData data, BackupImportMode mode, CancellationToken ct = default)
{
- data = BackupArchive.Clone(data);
+ data = BackupCopy.Copy(data);
BackupArchive.Validate(data);
// Old archives keep XHTTP headers in plain options: move them to secrets
// before anything is persisted (issue #338).
diff --git a/src/Bydlo.Engines/TgWsProxy/FakeTls.cs b/src/Bydlo.Engines/TgWsProxy/FakeTls.cs
index 216f2aa3..c91a6566 100644
--- a/src/Bydlo.Engines/TgWsProxy/FakeTls.cs
+++ b/src/Bydlo.Engines/TgWsProxy/FakeTls.cs
@@ -348,6 +348,12 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo
internal sealed class FakeTlsStream(Stream inner) : Stream
{
private readonly byte[] _header = new byte[5];
+ /// Write-side record buffer; only touches it.
+ private byte[]? _record;
+
+ /// Read-side scratch for skipped ChangeCipherSpec payloads (a record length is at most 65535).
+ private byte[]? _discard;
+
private int _recordLeft;
public override bool CanRead => true;
@@ -380,7 +386,9 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation
{
if (length > 0)
{
- await inner.ReadExactlyAsync(new byte[length], cancellationToken).ConfigureAwait(false);
+ // Reads and writes run concurrently, so the discarded CCS payload never uses the write buffer.
+ _discard ??= new byte[ushort.MaxValue];
+ await inner.ReadExactlyAsync(_discard.AsMemory(0, length), cancellationToken).ConfigureAwait(false);
}
continue;
@@ -404,8 +412,29 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation
return n;
}
- public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) =>
- await inner.WriteAsync(Wrap(buffer.Span), cancellationToken).ConfigureAwait(false);
+ ///
+ /// Writes records through one reusable buffer instead of allocating the wrapped payload (issue #359).
+ /// The bytes on the wire are identical to .
+ ///
+ public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ _record ??= new byte[5 + FakeTls.MaxRecordPayload];
+ for (var offset = 0; offset < buffer.Length; offset += FakeTls.MaxRecordPayload)
+ {
+ var length = WriteRecord(buffer.Span.Slice(offset, Math.Min(FakeTls.MaxRecordPayload, buffer.Length - offset)), _record);
+ await inner.WriteAsync(_record.AsMemory(0, length), cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private static int WriteRecord(ReadOnlySpan chunk, Span output)
+ {
+ output[0] = FakeTls.RecordApplicationData;
+ output[1] = 0x03;
+ output[2] = 0x03;
+ BinaryPrimitives.WriteUInt16BigEndian(output[3..], (ushort)chunk.Length);
+ chunk.CopyTo(output[5..]);
+ return 5 + chunk.Length;
+ }
public static byte[] Wrap(ReadOnlySpan data)
{
diff --git a/src/Bydlo.Engines/TgWsProxy/MtProto.cs b/src/Bydlo.Engines/TgWsProxy/MtProto.cs
index 5536991a..4ba8025f 100644
--- a/src/Bydlo.Engines/TgWsProxy/MtProto.cs
+++ b/src/Bydlo.Engines/TgWsProxy/MtProto.cs
@@ -155,21 +155,31 @@ internal sealed class MsgSplitter(uint protoTag)
private int _length;
private bool _disabled;
- public List Split(ReadOnlySpan cipher, ReadOnlySpan plain)
+ private int _pending;
+
+ ///
+ /// Appends a chunk and reports the whole packets now available, without allocating (issue #359):
+ /// the packets are contiguous in the returned memory and receives
+ /// their sizes. The memory stays valid only until the next call to this splitter.
+ ///
+ public ReadOnlyMemory SplitInto(ReadOnlySpan cipher, ReadOnlySpan plain, List lengths)
{
- var parts = new List();
+ lengths.Clear();
+ Consume(_pending);
+ _pending = 0;
if (cipher.IsEmpty)
{
- return parts;
+ return ReadOnlyMemory.Empty;
}
+ Append(cipher, plain);
if (_disabled)
{
- parts.Add(cipher.ToArray());
- return parts;
+ lengths.Add(_length);
+ _pending = _length;
+ return _cipher.AsMemory(0, _length);
}
- Append(cipher, plain);
var offset = 0;
while (offset < _length)
{
@@ -182,22 +192,40 @@ public List Split(ReadOnlySpan cipher, ReadOnlySpan plain)
if (packet <= 0)
{
// Unknown framing: stop splitting and pass everything through as is.
- parts.Add(_cipher.AsSpan(offset, _length - offset).ToArray());
+ lengths.Add(_length - offset);
offset = _length;
_disabled = true;
break;
}
- parts.Add(_cipher.AsSpan(offset, packet.Value).ToArray());
+ lengths.Add(packet.Value);
offset += packet.Value;
}
- Consume(offset);
+ _pending = offset;
+ return _cipher.AsMemory(0, offset);
+ }
+
+ /// Allocating form of , kept for tests and rare paths.
+ public List Split(ReadOnlySpan cipher, ReadOnlySpan plain)
+ {
+ var lengths = new List();
+ var packets = SplitInto(cipher, plain, lengths).Span;
+ var parts = new List(lengths.Count);
+ var at = 0;
+ foreach (var length in lengths)
+ {
+ parts.Add(packets.Slice(at, length).ToArray());
+ at += length;
+ }
+
return parts;
}
public byte[]? Flush()
{
+ Consume(_pending);
+ _pending = 0;
if (_length == 0)
{
return null;
diff --git a/src/Bydlo.Engines/TgWsProxy/ProxyProtocol.cs b/src/Bydlo.Engines/TgWsProxy/ProxyProtocol.cs
new file mode 100644
index 00000000..22efa712
--- /dev/null
+++ b/src/Bydlo.Engines/TgWsProxy/ProxyProtocol.cs
@@ -0,0 +1,154 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+
+namespace Bydlo.Engines.TgWsProxy;
+
+/// Source address reported by a PROXY protocol v1 header.
+/// The address family token of the header: TCP4, TCP6 or UNKNOWN.
+/// The client address, or null for UNKNOWN.
+/// The client port, or 0 for UNKNOWN.
+internal sealed record ProxyProtocolHeader(string Family, IPAddress? Source, int SourcePort)
+{
+ /// Log label of the real client, or when the header carries no address.
+ public string Describe(string fallback) => Source is null
+ ? fallback
+ : Source.AddressFamily == AddressFamily.InterNetworkV6 ? $"[{Source}]:{SourcePort}" : $"{Source}:{SourcePort}";
+}
+
+///
+/// PROXY protocol v1 (text) header, the only version Flowseal tg-ws-proxy 1.11.4 accepts: with
+/// --proxy-protocol it reads one line before the client handshake and uses the address for the log label.
+/// Upstream has no v2 support, so the binary v2 signature is rejected instead of parsed.
+///
+internal static class ProxyProtocol
+{
+ /// Longest v1 header the specification allows, CRLF included.
+ public const int MaxHeaderLength = 107;
+
+ /// How long a trusted peer may take to send the header; upstream waits 10 s.
+ public static readonly TimeSpan ReadTimeout = TimeSpan.FromSeconds(10);
+
+ private const string Prefix = "PROXY ";
+
+ /// Binary v2 signature. Upstream never parses v2, so a connection that starts with it is refused.
+ private static ReadOnlySpan V2Signature => "\r\n\r\n\0\r\nQUIT\n"u8;
+
+ /// True when may send a header; IPv4-mapped IPv6 peers match their IPv4 form.
+ public static bool IsTrustedSource(IPAddress? peer, IReadOnlyList trusted)
+ {
+ if (peer is null)
+ {
+ return false;
+ }
+
+ var normalized = Normalize(peer);
+ foreach (var candidate in trusted)
+ {
+ if (Normalize(candidate).GetAddressBytes().AsSpan().SequenceEqual(normalized.GetAddressBytes()))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ /// Reads one v1 header. Returns null when it is malformed, oversized, incomplete or not sent within
+ /// ; the caller then closes the connection without touching the handshake.
+ ///
+ public static async Task ReadAsync(Stream stream, TimeSpan timeout, CancellationToken ct)
+ {
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ deadline.CancelAfter(timeout);
+ var buffer = new byte[MaxHeaderLength];
+ var length = 0;
+ try
+ {
+ // One byte at a time: the header ends at LF and the next bytes already belong to the client handshake,
+ // so nothing may be read past it.
+ while (length < buffer.Length)
+ {
+ if (await stream.ReadAsync(buffer.AsMemory(length, 1), deadline.Token).ConfigureAwait(false) == 0)
+ {
+ return null;
+ }
+
+ length++;
+ if (length <= V2Signature.Length && V2Signature[..length].SequenceEqual(buffer.AsSpan(0, length)))
+ {
+ if (length == V2Signature.Length)
+ {
+ // A v2 header: upstream never parses it, so the connection is refused instead.
+ return null;
+ }
+
+ continue;
+ }
+
+ if (buffer[length - 1] == (byte)'\n')
+ {
+ return Parse(buffer.AsSpan(0, length));
+ }
+ }
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ return null;
+ }
+
+ // No LF within the v1 limit.
+ return null;
+ }
+
+ private static ProxyProtocolHeader? Parse(ReadOnlySpan line)
+ {
+ // "PROXY ...\r\n": the line must end with CRLF and carry printable ASCII only.
+ if (line.Length < Prefix.Length + 3 || line[^2] != (byte)'\r' || line[..^2].ContainsAnyExceptInRange((byte)0x20, (byte)0x7E))
+ {
+ return null;
+ }
+
+ var text = Encoding.ASCII.GetString(line[..^2]);
+ if (!text.StartsWith(Prefix, StringComparison.Ordinal))
+ {
+ return null;
+ }
+
+ // Fields are separated by single spaces; a double space yields an empty field and is rejected.
+ var parts = text.Split(' ');
+ if (parts.Length < 2)
+ {
+ return null;
+ }
+
+ var family = parts[1];
+ if (family == "UNKNOWN")
+ {
+ // The specification requires receivers to ignore everything after UNKNOWN.
+ return new ProxyProtocolHeader(family, null, 0);
+ }
+
+ if (family is not ("TCP4" or "TCP6") || parts.Length != 6)
+ {
+ return null;
+ }
+
+ var expected = family == "TCP4" ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
+ if (!IPAddress.TryParse(parts[2], out var source) || source.AddressFamily != expected
+ || !IPAddress.TryParse(parts[3], out var destination) || destination.AddressFamily != expected
+ || !TryParsePort(parts[4], out var sourcePort) || !TryParsePort(parts[5], out _))
+ {
+ return null;
+ }
+
+ return new ProxyProtocolHeader(family, source, sourcePort);
+ }
+
+ private static bool TryParsePort(string value, out int port) =>
+ int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out port) && port is >= 0 and <= 65535;
+
+ private static IPAddress Normalize(IPAddress address) => address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address;
+}
diff --git a/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs b/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs
index 9d8f0d18..8189ae50 100644
--- a/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs
+++ b/src/Bydlo.Engines/TgWsProxy/RawWebSocket.cs
@@ -31,6 +31,8 @@ internal sealed class RawWebSocket : IAsyncDisposable
private readonly Stream _stream;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private readonly byte[] _header = new byte[14];
+ private readonly int[] _single = new int[1];
+ private byte[] _writeBuffer = new byte[16 * 1024];
private readonly Channel _messages = Channel.CreateBounded(new BoundedChannelOptions(16) { SingleReader = true, SingleWriter = true });
private readonly CancellationTokenSource _stopPump = new();
private readonly Task _pump;
@@ -77,16 +79,25 @@ internal static async Task UpgradeAsync(Stream stream, string doma
await stream.WriteAsync(Encoding.ASCII.GetBytes(request), ct).ConfigureAwait(false);
await stream.FlushAsync(ct).ConfigureAwait(false);
- var statusLine = await ReadResponseHeadAsync(stream, ct).ConfigureAwait(false);
+ var (statusLine, rest) = await ReadResponseHeadAsync(stream, ct).ConfigureAwait(false);
var parts = statusLine.Split(' ', 3);
var status = parts.Length >= 2 && int.TryParse(parts[1], out var code) ? code : 0;
- return status == 101 ? new RawWebSocket(stream) : throw new WsHandshakeException(status, statusLine);
+ if (status != 101)
+ {
+ throw new WsHandshakeException(status, statusLine);
+ }
+
+ return new RawWebSocket(rest.Length == 0 ? stream : new PrefixedStream(rest, stream));
}
- public Task SendAsync(ReadOnlyMemory data, CancellationToken ct) => WriteFramesAsync([data], OpBinary, ct);
+ public Task SendAsync(ReadOnlyMemory data, CancellationToken ct) => WriteFramesAsync(data, null, OpBinary, ct);
- public Task SendBatchAsync(IReadOnlyList parts, CancellationToken ct) =>
- WriteFramesAsync([.. parts.Select(p => (ReadOnlyMemory)p)], OpBinary, ct);
+ ///
+ /// Sends contiguous as one binary frame per entry of ,
+ /// built in a reusable buffer and written at once (issue #359).
+ ///
+ public Task SendPacketsAsync(ReadOnlyMemory data, IReadOnlyList lengths, CancellationToken ct) =>
+ WriteFramesAsync(data, lengths, OpBinary, ct);
/// Next binary message, or null once the server closed the connection.
public async Task ReceiveAsync(CancellationToken ct)
@@ -109,7 +120,7 @@ public async ValueTask DisposeAsync()
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
- await WriteFramesAsync([ReadOnlyMemory.Empty], OpClose, cts.Token, force: true).ConfigureAwait(false);
+ await WriteFramesAsync(ReadOnlyMemory.Empty, null, OpClose, cts.Token, force: true).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException or OperationCanceledException or NotSupportedException) { }
}
@@ -134,11 +145,11 @@ private async Task PumpAsync()
{
case OpClose:
Interlocked.Exchange(ref _closed, 1);
- try { await WriteFramesAsync([payload.AsMemory(0, Math.Min(2, payload.Length))], OpClose, ct, force: true).ConfigureAwait(false); }
+ try { await WriteFramesAsync(payload.AsMemory(0, Math.Min(2, payload.Length)), null, OpClose, ct, force: true).ConfigureAwait(false); }
catch (Exception ex) when (ex is IOException or ObjectDisposedException or OperationCanceledException) { }
return;
case OpPing:
- try { await WriteFramesAsync([payload], OpPong, ct).ConfigureAwait(false); }
+ try { await WriteFramesAsync(payload, null, OpPong, ct).ConfigureAwait(false); }
catch (Exception ex) when (ex is IOException or ObjectDisposedException) { }
continue;
case OpContinuation or OpText or OpBinary:
@@ -182,11 +193,20 @@ private async Task PumpAsync()
}
}
+ private static int HeaderLength(int length, bool mask) =>
+ 2 + (length < 126 ? 0 : length < 65536 ? 2 : 8) + (mask ? 4 : 0);
+
internal static byte[] BuildFrame(byte opcode, ReadOnlySpan data, bool mask)
+ {
+ var frame = new byte[HeaderLength(data.Length, mask) + data.Length];
+ WriteFrame(opcode, data, mask, frame);
+ return frame;
+ }
+
+ /// Writes one frame into and returns its length.
+ private static int WriteFrame(byte opcode, ReadOnlySpan data, bool mask, Span frame)
{
var length = data.Length;
- var headerLength = 2 + (length < 126 ? 0 : length < 65536 ? 2 : 8) + (mask ? 4 : 0);
- var frame = new byte[headerLength + length];
frame[0] = (byte)(0x80 | opcode);
var maskBit = mask ? (byte)0x80 : (byte)0;
var at = 2;
@@ -197,28 +217,28 @@ internal static byte[] BuildFrame(byte opcode, ReadOnlySpan data, bool mas
else if (length < 65536)
{
frame[1] = (byte)(maskBit | 126);
- BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(2), (ushort)length);
+ BinaryPrimitives.WriteUInt16BigEndian(frame[2..], (ushort)length);
at = 4;
}
else
{
frame[1] = (byte)(maskBit | 127);
- BinaryPrimitives.WriteUInt64BigEndian(frame.AsSpan(2), (ulong)length);
+ BinaryPrimitives.WriteUInt64BigEndian(frame[2..], (ulong)length);
at = 10;
}
if (!mask)
{
- data.CopyTo(frame.AsSpan(at));
- return frame;
+ data.CopyTo(frame[at..]);
+ return at + length;
}
- var key = frame.AsSpan(at, 4);
+ var key = frame.Slice(at, 4);
RandomNumberGenerator.Fill(key);
- var payload = frame.AsSpan(at + 4);
+ var payload = frame.Slice(at + 4, length);
data.CopyTo(payload);
ApplyMask(payload, key);
- return frame;
+ return at + 4 + length;
}
private static void ApplyMask(Span payload, ReadOnlySpan key)
@@ -229,44 +249,77 @@ private static void ApplyMask(Span payload, ReadOnlySpan key)
}
}
- private static async Task ReadResponseHeadAsync(Stream stream, CancellationToken ct)
+ ///
+ /// Reads the HTTP response head in blocks (issue #359). Bytes that arrive after the blank line
+ /// already belong to the WebSocket and are returned as Leftover.
+ ///
+ private static async Task<(string StatusLine, byte[] Leftover)> ReadResponseHeadAsync(Stream stream, CancellationToken ct)
{
- // Byte by byte so nothing after the header block is consumed.
- var head = new List(256);
- var one = new byte[1];
- while (head.Count < 16 * 1024)
+ const int Limit = 16 * 1024;
+ var head = new byte[Limit];
+ var count = 0;
+ var end = -1;
+ while (count < Limit)
{
- if (await stream.ReadAsync(one, ct).ConfigureAwait(false) == 0)
+ var n = await stream.ReadAsync(head.AsMemory(count), ct).ConfigureAwait(false);
+ if (n == 0)
{
break;
}
- head.Add(one[0]);
- var n = head.Count;
- if (n >= 4 && head[n - 4] == '\r' && head[n - 3] == '\n' && head[n - 2] == '\r' && head[n - 1] == '\n')
+ var from = Math.Max(0, count - 3);
+ count += n;
+ var found = head.AsSpan(from, count - from).IndexOf("\r\n\r\n"u8);
+ if (found >= 0)
{
+ end = from + found + 4;
break;
}
}
- var text = Encoding.UTF8.GetString([.. head]);
+ var text = Encoding.UTF8.GetString(head, 0, end >= 0 ? end : count);
var firstLine = text.Split('\n', 2)[0].Trim();
- return firstLine.Length == 0 ? throw new WsHandshakeException(0, "empty response") : firstLine;
+ var rest = end >= 0 && end < count ? head.AsSpan(end, count - end).ToArray() : [];
+ return firstLine.Length == 0 ? throw new WsHandshakeException(0, "empty response") : (firstLine, rest);
}
- private async Task WriteFramesAsync(IReadOnlyList> payloads, byte opcode, CancellationToken ct, bool force = false)
+ private async Task WriteFramesAsync(ReadOnlyMemory data, IReadOnlyList? lengths, byte opcode, CancellationToken ct, bool force = false)
{
if (IsClosed && !force)
{
throw new IOException("WebSocket is closed.");
}
- var frames = payloads.Select(p => BuildFrame(opcode, p.Span, mask: true)).ToArray();
- var buffer = frames.Length == 1 ? frames[0] : [.. frames.SelectMany(f => f)];
await _writeLock.WaitAsync(ct).ConfigureAwait(false);
try
{
- await _stream.WriteAsync(buffer, ct).ConfigureAwait(false);
+ // The shared buffers are only touched under the write lock.
+ if (lengths is null)
+ {
+ _single[0] = data.Length;
+ lengths = _single;
+ }
+
+ var total = 0;
+ for (var i = 0; i < lengths.Count; i++)
+ {
+ total += HeaderLength(lengths[i], mask: true) + lengths[i];
+ }
+
+ if (_writeBuffer.Length < total)
+ {
+ _writeBuffer = new byte[Math.Max(total, _writeBuffer.Length * 2)];
+ }
+
+ var written = 0;
+ var offset = 0;
+ for (var i = 0; i < lengths.Count; i++)
+ {
+ written += WriteFrame(opcode, data.Span.Slice(offset, lengths[i]), mask: true, _writeBuffer.AsSpan(written));
+ offset += lengths[i];
+ }
+
+ await _stream.WriteAsync(_writeBuffer.AsMemory(0, written), ct).ConfigureAwait(false);
await _stream.FlushAsync(ct).ConfigureAwait(false);
}
finally
@@ -298,7 +351,7 @@ private async Task WriteFramesAsync(IReadOnlyList> payloads
throw new IOException($"WebSocket frame too large: {length} bytes.");
}
- var key = new byte[4];
+ var key = _header.AsMemory(10, 4);
if (masked)
{
await _stream.ReadExactlyAsync(key, ct).ConfigureAwait(false);
@@ -308,9 +361,75 @@ private async Task WriteFramesAsync(IReadOnlyList> payloads
await _stream.ReadExactlyAsync(payload, ct).ConfigureAwait(false);
if (masked)
{
- ApplyMask(payload, key);
+ ApplyMask(payload, key.Span);
}
return (opcode, payload, fin);
}
}
+
+/// Replays bytes read past the HTTP head before continuing with the inner stream.
+internal sealed class PrefixedStream(byte[] prefix, Stream inner) : Stream
+{
+ private int _offset;
+
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => inner.CanWrite;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ if (_offset < prefix.Length && !buffer.IsEmpty)
+ {
+ var n = Math.Min(buffer.Length, prefix.Length - _offset);
+ prefix.AsSpan(_offset, n).CopyTo(buffer.Span);
+ _offset += n;
+ return ValueTask.FromResult(n);
+ }
+
+ return inner.ReadAsync(buffer, cancellationToken);
+ }
+
+ public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
+ ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
+
+ public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
+
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) =>
+ inner.WriteAsync(buffer, cancellationToken);
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
+ inner.WriteAsync(buffer, offset, count, cancellationToken);
+
+ public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
+
+ public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
+
+ public override void Flush() => inner.Flush();
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override async ValueTask DisposeAsync()
+ {
+ await inner.DisposeAsync().ConfigureAwait(false);
+ await base.DisposeAsync().ConfigureAwait(false);
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ inner.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+}
diff --git a/src/Bydlo.Engines/TgWsProxy/TgNetwork.cs b/src/Bydlo.Engines/TgWsProxy/TgNetwork.cs
index 2cf55208..275b7b96 100644
--- a/src/Bydlo.Engines/TgWsProxy/TgNetwork.cs
+++ b/src/Bydlo.Engines/TgWsProxy/TgNetwork.cs
@@ -23,7 +23,11 @@ public interface ITgNetwork
/// The local listening socket. throws once the socket is dead.
public interface ITgListener : IDisposable
{
- Task<(Stream Stream, string Label)> AcceptAsync(CancellationToken ct);
+ ///
+ /// Waits for the next client. RemoteAddress is the peer address, or null when the transport
+ /// cannot report it; the PROXY protocol trust check refuses a header from an unknown peer.
+ ///
+ Task<(Stream Stream, string Label, IPAddress? RemoteAddress)> AcceptAsync(CancellationToken ct);
}
/// Real sockets. Every call checks , so nothing connects in development.
@@ -114,13 +118,14 @@ private static TcpListener Bind(string host, int port)
internal sealed class SystemTgListener(TcpListener listener, int bufferSize) : ITgListener
{
- public async Task<(Stream Stream, string Label)> AcceptAsync(CancellationToken ct)
+ public async Task<(Stream Stream, string Label, IPAddress? RemoteAddress)> AcceptAsync(CancellationToken ct)
{
var socket = await listener.AcceptSocketAsync(ct).ConfigureAwait(false);
socket.NoDelay = true;
socket.ReceiveBufferSize = bufferSize;
socket.SendBufferSize = bufferSize;
- return (new NetworkStream(socket, ownsSocket: true), socket.RemoteEndPoint?.ToString() ?? "?");
+ var remote = socket.RemoteEndPoint as IPEndPoint;
+ return (new NetworkStream(socket, ownsSocket: true), remote?.ToString() ?? "?", remote?.Address);
}
public void Dispose()
diff --git a/src/Bydlo.Engines/TgWsProxy/TgWsProxyOptions.cs b/src/Bydlo.Engines/TgWsProxy/TgWsProxyOptions.cs
index 7f00d9bc..13f9aeda 100644
--- a/src/Bydlo.Engines/TgWsProxy/TgWsProxyOptions.cs
+++ b/src/Bydlo.Engines/TgWsProxy/TgWsProxyOptions.cs
@@ -61,6 +61,15 @@ public sealed record TgWsProxyOptions
/// Port 80 instead of TLS for the Cloudflare paths (upstream --no-secure).
public bool DisableSecure { get; init; }
+ /// Accept a PROXY protocol v1 header before the client handshake (upstream --proxy-protocol).
+ public bool ProxyProtocol { get; init; }
+
+ /// Peers allowed to send that header. Loopback only unless configured otherwise.
+ public IReadOnlyList ProxyProtocolTrustedSources { get; init; } = DefaultTrustedSources;
+
+ /// Loopback, the only sender trusted by default.
+ public static readonly IReadOnlyList DefaultTrustedSources = [IPAddress.Loopback, IPAddress.IPv6Loopback];
+
public static TgWsProxyOptions From(TgWsProxySettings settings, string secretHex) => new()
{
Host = string.IsNullOrWhiteSpace(settings.Host) ? "127.0.0.1" : settings.Host.Trim(),
@@ -71,8 +80,33 @@ public sealed record TgWsProxyOptions
CfProxyFallback = settings.CfProxyFallback,
CfProxyDomains = TgWsProxy.CfProxyDomains.Normalize(settings.CfProxyDomains),
Verbose = settings.Verbose,
+ ProxyProtocol = settings.ProxyProtocol,
+ ProxyProtocolTrustedSources = ParseTrustedSources(settings.ProxyProtocolTrustedSources),
};
+ /// Parses the trusted PROXY protocol senders; an empty list keeps the loopback default.
+ public static IReadOnlyList ParseTrustedSources(IEnumerable entries)
+ {
+ var result = new List();
+ foreach (var raw in entries)
+ {
+ var entry = raw.Trim();
+ if (entry.Length == 0)
+ {
+ continue;
+ }
+
+ if (!IPAddress.TryParse(entry, out var ip))
+ {
+ throw new EngineException($"Invalid trusted PROXY protocol source '{entry}'.", localizationKey: "error.engine.tg.proxyprotocol");
+ }
+
+ result.Add(ip);
+ }
+
+ return result.Count > 0 ? result : DefaultTrustedSources;
+ }
+
/// Parses DC:IP lines (IPv4 only, as upstream).
public static Dictionary ParseDcIps(IEnumerable entries)
{
diff --git a/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs b/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs
index f157c670..74304d78 100644
--- a/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs
+++ b/src/Bydlo.Engines/TgWsProxy/TgWsProxyServer.cs
@@ -1,5 +1,6 @@
using System.Buffers.Binary;
using System.Collections.Concurrent;
+using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
@@ -141,13 +142,13 @@ public async ValueTask DisposeAsync()
}
/// Serves one accepted client connection (exposed for in-memory tests).
- internal async Task HandleClientAsync(Stream client, string label)
+ internal async Task HandleClientAsync(Stream client, string label, IPAddress? remoteAddress = null)
{
Stats.Opened();
var ct = _stop.Token;
try
{
- var init = await ReadClientInitAsync(client, label, ct).ConfigureAwait(false);
+ var init = await ReadClientInitAsync(client, label, remoteAddress, ct).ConfigureAwait(false);
if (init is null)
{
return;
@@ -212,8 +213,30 @@ internal async Task HandleClientAsync(Stream client, string label)
}
}
- private async Task<(byte[] Handshake, Stream Stream)?> ReadClientInitAsync(Stream client, string label, CancellationToken ct)
+ private async Task<(byte[] Handshake, Stream Stream)?> ReadClientInitAsync(Stream client, string label, IPAddress? remoteAddress, CancellationToken ct)
{
+ if (Options.ProxyProtocol)
+ {
+ if (!ProxyProtocol.IsTrustedSource(remoteAddress, Options.ProxyProtocolTrustedSources))
+ {
+ // Bytes of an untrusted peer are never interpreted as a header: they stay client data.
+ _context.Log(TgLogLevel.Debug, $"[{label}] PROXY protocol header not expected from this peer");
+ }
+ else
+ {
+ var header = await ProxyProtocol.ReadAsync(client, ProxyProtocol.ReadTimeout, ct).ConfigureAwait(false);
+ if (header is null)
+ {
+ Stats.Bad();
+ _context.Log(TgLogLevel.Warning, $"[{label}] invalid PROXY protocol header, closing");
+ return null;
+ }
+
+ label = header.Describe(label);
+ _context.Log(TgLogLevel.Debug, $"[{label}] PROXY protocol v1 header accepted ({header.Family})");
+ }
+ }
+
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(HandshakeTimeout);
var first = new byte[1];
@@ -380,6 +403,7 @@ async Task ClientToWs()
{
var buffer = new byte[ReadBufferSize];
var plain = new byte[ReadBufferSize];
+ var lengths = new List();
try
{
while (true)
@@ -399,14 +423,11 @@ async Task ClientToWs()
up += n;
upPackets++;
crypto.Upstream(buffer.AsSpan(0, n), plain.AsSpan(0, n));
- var parts = splitter.Split(buffer.AsSpan(0, n), plain.AsSpan(0, n));
- if (parts.Count == 1)
+ // Packets stay in the splitter's buffer; frames are built in the socket's own buffer (#359).
+ var packets = splitter.SplitInto(buffer.AsSpan(0, n), plain.AsSpan(0, n), lengths);
+ if (lengths.Count > 0)
{
- await ws.SendAsync(parts[0], session.Token).ConfigureAwait(false);
- }
- else if (parts.Count > 1)
- {
- await ws.SendBatchAsync(parts, session.Token).ConfigureAwait(false);
+ await ws.SendPacketsAsync(packets, lengths, session.Token).ConfigureAwait(false);
}
}
}
@@ -598,11 +619,12 @@ private async Task AcceptLoopAsync()
Stream stream;
string label;
+ IPAddress? remoteAddress;
try
{
// The blocking AcceptAsync call itself stays outside the lock so
// DisposeAsync can still take the gate while we are waiting.
- (stream, label) = await snapshot.AcceptAsync(ct).ConfigureAwait(false);
+ (stream, label, remoteAddress) = await snapshot.AcceptAsync(ct).ConfigureAwait(false);
}
catch (Exception) when (ct.IsCancellationRequested)
{
@@ -625,7 +647,7 @@ private async Task AcceptLoopAsync()
continue;
}
- var task = HandleClientAsync(stream, label);
+ var task = HandleClientAsync(stream, label, remoteAddress);
_clients.TryAdd(task, 0);
_ = task.ContinueWith(t => _clients.TryRemove(t, out _), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
@@ -772,6 +794,11 @@ private void LogBanner()
_context.Log(TgLogLevel.Info, Options.CfProxyFallback
? $"CF proxy: enabled ({(Options.CfProxyDomains.Count > 0 ? "custom domains" : "auto")})"
: "CF proxy: disabled");
+ if (Options.ProxyProtocol)
+ {
+ _context.Log(TgLogLevel.Info, "PROXY protocol v1: enabled, trusted sources "
+ + string.Join(", ", Options.ProxyProtocolTrustedSources));
+ }
}
private sealed record Route(string Label, int Dc, bool IsMedia, bool IsTestDc, string MediaTag);
diff --git a/src/Bydlo.Engines/Zapret/TestZapretProbe.cs b/src/Bydlo.Engines/Zapret/TestZapretProbe.cs
index cb478355..86f59447 100644
--- a/src/Bydlo.Engines/Zapret/TestZapretProbe.cs
+++ b/src/Bydlo.Engines/Zapret/TestZapretProbe.cs
@@ -9,7 +9,7 @@
namespace Bydlo.Engines.Zapret;
///
-/// Managed port of the standard HTTP/TLS suite in Flowseal Test Zapret 1.10.3 (MIT).
+/// Managed port of the standard HTTP/TLS suite in Flowseal Test Zapret 1.10.4 (MIT).
/// The interactive upstream process/ipset manager is deliberately not executed.
/// Each curl is owned by IProcessRunner, with real response codes and measured successful latency.
///
diff --git a/src/Bydlo.Platform/HelperInstallBundle.cs b/src/Bydlo.Platform/HelperInstallBundle.cs
new file mode 100644
index 00000000..89bc654f
--- /dev/null
+++ b/src/Bydlo.Platform/HelperInstallBundle.cs
@@ -0,0 +1,51 @@
+namespace Bydlo.Platform;
+
+/// Copies an AppImage payload off its user-owned FUSE mount before elevation.
+internal sealed class HelperInstallBundle : IDisposable
+{
+ private HelperInstallBundle(string directory) { DirectoryPath = directory; }
+
+ internal string DirectoryPath { get; }
+ internal string Executable => Path.Combine(DirectoryPath, "helper", "Bydlo.Helper");
+
+ internal static HelperInstallBundle Stage(string applicationDirectory, bool install)
+ {
+ var bundle = new HelperInstallBundle(Directory.CreateTempSubdirectory("bydlo-helper-").FullName);
+ try
+ {
+ CopyTree(Path.Combine(applicationDirectory, "helper"), Path.Combine(bundle.DirectoryPath, "helper"));
+ if (install)
+ {
+ CopyTree(Path.Combine(applicationDirectory, "engines"), Path.Combine(bundle.DirectoryPath, "engines"));
+ }
+ return bundle;
+ }
+ catch { bundle.Dispose(); throw; }
+ }
+
+ private static void CopyTree(string source, string destination)
+ {
+ if ((File.GetAttributes(source) & FileAttributes.ReparsePoint) != 0)
+ { throw new IOException("Linked helper bundle paths are forbidden."); }
+ Directory.CreateDirectory(destination);
+ if (!OperatingSystem.IsWindows())
+ {
+ File.SetUnixFileMode(destination, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
+ }
+ foreach (var entry in Directory.EnumerateFileSystemEntries(source))
+ {
+ var attributes = File.GetAttributes(entry);
+ if ((attributes & FileAttributes.ReparsePoint) != 0)
+ { throw new IOException("Linked helper bundle files are forbidden."); }
+ var target = Path.Combine(destination, Path.GetFileName(entry));
+ if ((attributes & FileAttributes.Directory) != 0) { CopyTree(entry, target); }
+ else
+ {
+ File.Copy(entry, target);
+ if (!OperatingSystem.IsWindows()) { File.SetUnixFileMode(target, File.GetUnixFileMode(entry)); }
+ }
+ }
+ }
+
+ public void Dispose() => Directory.Delete(DirectoryPath, recursive: true);
+}
diff --git a/src/Bydlo.Platform/HelperManagement.cs b/src/Bydlo.Platform/HelperManagement.cs
index 05346ca7..a454adef 100644
--- a/src/Bydlo.Platform/HelperManagement.cs
+++ b/src/Bydlo.Platform/HelperManagement.cs
@@ -48,13 +48,17 @@ public static bool IsInstalled
}
}
- /// Only explicit Settings buttons invoke this method; Windows supplies the UAC consent prompt.
+ /// Explicit installation actions invoke the OS administrator consent prompt.
public static async Task ChangeAsync(bool install, bool userConsent, CancellationToken ct = default)
{
if (!userConsent) { return false; }
NetworkSafetyGuard.EnsureAllowed("manage the privileged helper");
+ ct.ThrowIfCancellationRequested();
if (!IsSupported) { throw new PlatformNotSupportedException(); }
- var executable = Path.Combine(AppContext.BaseDirectory, "helper", OperatingSystem.IsWindows() ? "Bydlo.Helper.exe" : "Bydlo.Helper");
+ // Root cannot access a normal user's AppImage FUSE mount. Stage before invoking PolKit.
+ using var staged = OperatingSystem.IsLinux() && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPIMAGE"))
+ ? HelperInstallBundle.Stage(AppContext.BaseDirectory, install) : null;
+ var executable = staged?.Executable ?? Path.Combine(AppContext.BaseDirectory, "helper", OperatingSystem.IsWindows() ? "Bydlo.Helper.exe" : "Bydlo.Helper");
if (!File.Exists(executable)) { throw new FileNotFoundException("Helper is missing from this release."); }
ProcessStartInfo info;
if (OperatingSystem.IsWindows())
@@ -89,7 +93,8 @@ public static async Task ChangeAsync(bool install, bool userConsent, Cance
{
using var process = Process.Start(info);
if (process is null) { return false; }
- await process.WaitForExitAsync(ct).ConfigureAwait(false);
+ // A staged payload must remain available until the elevated installer finishes reading it.
+ await process.WaitForExitAsync(staged is null ? ct : CancellationToken.None).ConfigureAwait(false);
return process.ExitCode == 0;
}
catch (System.ComponentModel.Win32Exception) { return false; }
diff --git a/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs b/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs
index 38d2d3cf..3c31fd92 100644
--- a/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs
+++ b/tests/Bydlo.Tests/AppUpdateOwnershipTests.cs
@@ -280,6 +280,18 @@ public async Task Apply_failure_is_reported_as_failed()
public void Guidance_points_at_the_owning_package_manager(AppInstallKind kind, string expected) =>
Assert.Equal(expected, UpdateGuidance.KeyFor(kind));
+ [Fact]
+ public void Debian_guidance_switches_when_the_apt_repository_is_configured()
+ {
+ // Issue #488: only a configured source may promise apt upgrade; every other kind is unaffected.
+ Assert.Equal("settings.update.manual.deb.repository", UpdateGuidance.KeyFor(AppInstallKind.Debian, true));
+ Assert.Equal("settings.update.manual.deb", UpdateGuidance.KeyFor(AppInstallKind.Debian, false));
+ foreach (var kind in Enum.GetValues().Where(kind => kind != AppInstallKind.Debian))
+ {
+ Assert.Equal(UpdateGuidance.KeyFor(kind), UpdateGuidance.KeyFor(kind, true));
+ }
+ }
+
[Fact]
public void Guidance_strings_exist_in_both_languages()
{
@@ -287,6 +299,7 @@ public void Guidance_strings_exist_in_both_languages()
var en = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "en.json"));
var ru = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "ru.json"));
var keys = Enum.GetValues().Select(UpdateGuidance.KeyFor)
+ .Concat(new[] { "settings.update.manual.deb.repository" })
.Concat(new[] { "settings.update.deferred", "settings.update.ready", "settings.update.downloading", "settings.update.error" })
.Distinct(StringComparer.Ordinal);
foreach (var key in keys)
@@ -352,6 +365,8 @@ private sealed class FakeBackend : IAppUpdateBackend
{
public bool IsInstalled { get; set; } = true;
+ public string? PendingVersion { get; set; } = "0.4.4";
+
public int Applied { get; private set; }
public Exception? ApplyError { get; set; }
diff --git a/tests/Bydlo.Tests/AptRepositorySourceTests.cs b/tests/Bydlo.Tests/AptRepositorySourceTests.cs
new file mode 100644
index 00000000..747085b3
--- /dev/null
+++ b/tests/Bydlo.Tests/AptRepositorySourceTests.cs
@@ -0,0 +1,178 @@
+using Bydlo.Core.Diagnostics;
+
+namespace Bydlo.Tests;
+
+///
+/// Issue #488: the app only reads the apt configuration to decide which update text to show.
+/// Every case runs against a temporary directory; nothing under /etc is read or written and apt is
+/// never executed.
+///
+public sealed class AptRepositorySourceTests : IDisposable
+{
+ private readonly string _root = Path.Combine(Path.GetTempPath(), "bydlo-apt-" + Guid.NewGuid().ToString("N"));
+
+ private string SourcesDirectory => Path.Combine(_root, "sources.list.d");
+
+ private string SourcesListFile => Path.Combine(_root, "sources.list");
+
+ public AptRepositorySourceTests() => Directory.CreateDirectory(SourcesDirectory);
+
+ public void Dispose()
+ {
+ try
+ {
+ Directory.Delete(_root, true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // A leftover temporary directory must never fail the suite.
+ }
+ }
+
+ [Fact]
+ public void Deb822_source_with_the_repository_uri_is_detected()
+ {
+ Write("bydlo.sources", """
+ Types: deb
+ URIs: https://endercodezz.github.io/BYDLO/
+ Suites: stable
+ Components: main
+ Architectures: amd64 arm64
+ Signed-By: /etc/apt/keyrings/bydlo.gpg
+ """);
+
+ Assert.True(IsConfigured());
+ }
+
+ [Fact]
+ public void One_line_list_source_with_the_repository_uri_is_detected()
+ {
+ Write("bydlo.list",
+ "deb [signed-by=/etc/apt/keyrings/bydlo.gpg] https://endercodezz.github.io/BYDLO/ stable main\n");
+
+ Assert.True(IsConfigured());
+ }
+
+ [Fact]
+ public void Repository_uri_without_a_trailing_slash_or_with_a_sub_path_is_detected()
+ {
+ Write("bydlo.sources", "Types: deb\nURIs: https://endercodezz.github.io/BYDLO\nSuites: stable\n");
+ Assert.True(IsConfigured());
+
+ Write("bydlo.sources", "Types: deb\nURIs: https://endercodezz.github.io/BYDLO/apt\nSuites: stable\n");
+ Assert.True(IsConfigured());
+ }
+
+ [Fact]
+ public void Host_comparison_ignores_case()
+ {
+ Write("bydlo.list", "deb https://Endercodezz.GitHub.io/bydlo/ stable main\n");
+
+ Assert.True(IsConfigured());
+ }
+
+ [Fact]
+ public void Repository_in_the_main_sources_list_is_detected()
+ {
+ File.WriteAllText(SourcesListFile, "deb https://endercodezz.github.io/BYDLO/ stable main\n");
+
+ Assert.True(IsConfigured());
+ }
+
+ [Fact]
+ public void Commented_out_source_is_not_configured()
+ {
+ Write("bydlo.list", "# deb https://endercodezz.github.io/BYDLO/ stable main\n");
+ Assert.False(IsConfigured());
+
+ Write("bydlo.sources", "# URIs: https://endercodezz.github.io/BYDLO/\nTypes: deb\n");
+ Assert.False(IsConfigured());
+ }
+
+ [Fact]
+ public void Disabled_deb822_stanza_is_not_configured()
+ {
+ Write("bydlo.sources", """
+ Types: deb
+ URIs: https://endercodezz.github.io/BYDLO/
+ Suites: stable
+ Enabled: no
+ """);
+
+ Assert.False(IsConfigured());
+ }
+
+ [Fact]
+ public void Enabled_stanza_next_to_a_disabled_one_is_detected()
+ {
+ Write("bydlo.sources", """
+ Types: deb
+ URIs: https://endercodezz.github.io/BYDLO/
+ Suites: stable
+ Enabled: no
+
+ Types: deb
+ URIs: https://endercodezz.github.io/BYDLO/
+ Suites: stable
+ Enabled: yes
+ """);
+
+ Assert.True(IsConfigured());
+ }
+
+ [Fact]
+ public void Unrelated_repositories_are_not_detected()
+ {
+ Write("debian.sources", "Types: deb\nURIs: https://deb.debian.org/debian\nSuites: trixie\n");
+ Write("vendor.list", "deb https://packages.example.com/apt stable main\n");
+ // A lookalike host must not count as the BYDLO repository.
+ Write("lookalike.list", "deb https://endercodezz.github.io/BYDLO-mirror/ stable main\n");
+
+ Assert.False(IsConfigured());
+ }
+
+ [Fact]
+ public void Files_that_apt_does_not_read_are_ignored()
+ {
+ Write("bydlo.sources.bak", "Types: deb\nURIs: https://endercodezz.github.io/BYDLO/\n");
+ Write("README", "https://endercodezz.github.io/BYDLO/\n");
+
+ Assert.False(IsConfigured());
+ }
+
+ [Fact]
+ public void Missing_configuration_is_not_configured()
+ {
+ Assert.False(AptRepositorySource.IsConfigured(Path.Combine(_root, "absent"), null));
+ Assert.False(AptRepositorySource.IsConfigured(SourcesDirectory, Path.Combine(_root, "absent.list")));
+ }
+
+ [Fact]
+ public void Directory_entry_named_like_a_source_file_is_ignored()
+ {
+ // Only regular files are apt sources; a stray directory must not break detection.
+ Directory.CreateDirectory(Path.Combine(SourcesDirectory, "bydlo.sources"));
+
+ Assert.False(IsConfigured());
+ }
+
+ [Fact]
+ public void Empty_text_is_not_configured()
+ {
+ Assert.False(AptRepositorySource.MentionsRepository(null));
+ Assert.False(AptRepositorySource.MentionsRepository(""));
+ Assert.False(AptRepositorySource.MentionsRepository(" \n\n "));
+ }
+
+ [Fact]
+ public void Published_repository_uri_matches_the_documented_one()
+ {
+ Assert.Equal("https://endercodezz.github.io/BYDLO/", AptRepositorySource.RepositoryUri);
+ Assert.True(AptRepositorySource.MentionsRepository($"URIs: {AptRepositorySource.RepositoryUri}"));
+ }
+
+ private bool IsConfigured() => AptRepositorySource.IsConfigured(SourcesDirectory, SourcesListFile);
+
+ private void Write(string name, string content) =>
+ File.WriteAllText(Path.Combine(SourcesDirectory, name), content);
+}
diff --git a/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs b/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs
index b640e109..98d0831e 100644
--- a/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs
+++ b/tests/Bydlo.Tests/AutomaticAppUpdaterTests.cs
@@ -185,6 +185,7 @@ public async Task Unpackaged_build_never_downloads_or_applies()
private sealed class FakeBackend : IAppUpdateBackend
{
public bool IsInstalled { get; set; } = true;
+ public string? PendingVersion { get; set; } = "0.4.4";
public int Downloads { get; private set; }
public int Applied { get; private set; }
public IProgress? Progress { get; private set; }
diff --git a/tests/Bydlo.Tests/BackupBufferTests.cs b/tests/Bydlo.Tests/BackupBufferTests.cs
new file mode 100644
index 00000000..46f59dd3
--- /dev/null
+++ b/tests/Bydlo.Tests/BackupBufferTests.cs
@@ -0,0 +1,206 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using Bydlo.Core.Backup;
+using Bydlo.Core.Models;
+using Bydlo.Core.Serialization;
+using Bydlo.Core.Storage;
+
+namespace Bydlo.Tests;
+
+/// Allocation measurements share ArrayPool.Shared, which parallel tests can drain or Gen2 GC can trim.
+[CollectionDefinition(nameof(AllocationMeasurements), DisableParallelization = true)]
+public sealed class AllocationMeasurements;
+
+/// Bounded backup buffers (issue #394): same format, fewer copies, limits enforced early.
+[Collection(nameof(AllocationMeasurements))]
+public sealed class BackupBufferTests
+{
+ private const string Password = "a long backup password for buffers";
+
+ private sealed class UnknownLengthStream(byte[] data) : Stream
+ {
+ private int _position;
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => false;
+ public override long Length => throw new NotSupportedException();
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ // Short reads exercise fragmented accumulation.
+ var n = Math.Min(Math.Min(count, 7919), data.Length - _position);
+ Array.Copy(data, _position, buffer, offset, n);
+ _position += n;
+ return n;
+ }
+ public override void Flush() { }
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ }
+
+ /// Reports a length that does not match its content (file changed while reading).
+ private sealed class LyingLengthStream(byte[] data, long reported) : MemoryStream(data)
+ {
+ public override long Length => reported;
+ }
+
+ private static BackupData Data() => new()
+ {
+ Profiles = [new(new Profile { Name = "Buffer server", Protocol = ProtocolKind.Vless, Host = "h.example", Port = 443 },
+ new ProfileSecrets { Values = { [Keys.Uuid] = "buffer-uuid" } })],
+ ToolSecrets = new ProfileSecrets { Values = { ["secret"] = "buffer-tool-secret" } },
+ };
+
+ [Theory]
+ [InlineData(true, 0)]
+ [InlineData(true, 1)]
+ [InlineData(true, BackupArchive.MaximumFileSize)]
+ [InlineData(false, 0)]
+ [InlineData(false, 100_000)]
+ [InlineData(false, BackupArchive.MaximumFileSize)]
+ public async Task Reads_up_to_the_exact_limit(bool seekable, int size)
+ {
+ var bytes = new byte[size];
+ Random.Shared.NextBytes(bytes);
+ Stream stream = seekable ? new MemoryStream(bytes) : new UnknownLengthStream(bytes);
+ var read = await BackupArchive.ReadFileAsync(stream);
+ Assert.Equal(bytes, read);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task Rejects_one_byte_over_the_limit(bool seekable)
+ {
+ var bytes = new byte[BackupArchive.MaximumFileSize + 1];
+ Stream stream = seekable ? new MemoryStream(bytes) : new UnknownLengthStream(bytes);
+ await Assert.ThrowsAsync(() => BackupArchive.ReadFileAsync(stream));
+ }
+
+ [Theory]
+ [InlineData(10, 5)]
+ [InlineData(10, 20)]
+ public async Task Rejects_streams_whose_length_changes_while_reading(int actual, long reported)
+ {
+ await Assert.ThrowsAsync(() =>
+ BackupArchive.ReadFileAsync(new LyingLengthStream(new byte[actual], reported)));
+ }
+
+ [Fact]
+ public async Task New_archives_are_read_by_the_previous_format_and_vice_versa()
+ {
+ var data = Data();
+ var current = BackupArchive.Encrypt(data, Password);
+ var legacyRead = JsonSerializer.Deserialize(LegacyDecrypt(current, Password), JsonDefaults.Options.Info())!;
+ Assert.Equal("buffer-uuid", legacyRead.Profiles[0].Secrets[Keys.Uuid]);
+
+ var legacy = LegacyEncrypt(data, Password);
+ Assert.Equal("buffer-tool-secret", BackupArchive.Decrypt(legacy, Password).ToolSecrets["secret"]);
+ var file = await BackupArchive.ReadFileAsync(new UnknownLengthStream(legacy));
+ using var session = BackupArchive.OpenImportOwned(file, Password);
+ Assert.Equal("Buffer server", Assert.Single(session.Profiles).Name);
+ }
+
+ [Fact]
+ public void Owned_session_rejects_wrong_password_tampering_and_truncation()
+ {
+ var archive = BackupArchive.Encrypt(Data(), Password);
+ Assert.ThrowsAny(() => BackupArchive.OpenImportOwned(archive.ToArray(), "a different long password"));
+ var tampered = archive.ToArray();
+ tampered[^1] ^= 1;
+ Assert.ThrowsAny(() => BackupArchive.OpenImportOwned(tampered, Password));
+ Assert.Throws(() => BackupArchive.OpenImportOwned(archive[..(BackupArchive.Overhead - 1)], Password));
+ }
+
+ [Fact]
+ public void Owned_archive_is_cleared_when_the_session_is_disposed()
+ {
+ var archive = BackupArchive.Encrypt(Data(), Password);
+ var session = BackupArchive.OpenImportOwned(archive, Password);
+ session.Dispose();
+ Assert.All(archive, b => Assert.Equal(0, b));
+ }
+
+ [Fact]
+ public void Bounded_buffer_accepts_the_limit_and_rejects_one_more_byte()
+ {
+ using var buffer = new BoundedBuffer(52, 1000);
+ buffer.GetSpan(948);
+ buffer.Advance(948);
+ Assert.Equal(1000, buffer.WrittenCount);
+ Assert.Throws(() => buffer.GetSpan(1));
+ }
+
+ [Fact]
+ public void Oversized_export_fails_while_serializing()
+ {
+ var data = new BackupData();
+ var config = new string('x', 1024 * 1024);
+ for (var i = 0; i < 40; i++)
+ {
+ data.Profiles.Add(new(new Profile { Name = "p" + i, Protocol = ProtocolKind.WireGuard, Host = "h", Port = 1 },
+ new ProfileSecrets { Values = { [Keys.RawConfig] = config } }));
+ }
+ Assert.Throws(() => BackupArchive.Encrypt(data, Password)); // warm the pool
+ var start = GC.GetAllocatedBytesForCurrentThread();
+ Assert.Throws(() => BackupArchive.Encrypt(data, Password));
+ var current = GC.GetAllocatedBytesForCurrentThread() - start;
+ start = GC.GetAllocatedBytesForCurrentThread();
+ // The previous implementation serialized the whole payload before checking the limit.
+ JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info());
+ var legacy = GC.GetAllocatedBytesForCurrentThread() - start;
+ Assert.True(current * 2 < legacy, $"current={current} legacy={legacy}");
+ }
+
+ [Fact]
+ public void Export_allocates_less_than_the_previous_implementation()
+ {
+ var data = new BackupData();
+ var config = new string('x', 128 * 1024);
+ for (var i = 0; i < 200; i++)
+ {
+ data.Profiles.Add(new(new Profile { Name = "p" + i, Protocol = ProtocolKind.WireGuard, Host = "h", Port = 1 },
+ new ProfileSecrets { Values = { [Keys.RawConfig] = config + i } }));
+ }
+ // Best of three: a single run can lose its pooled buffer to a GC trim (flaky on busy CI runners).
+ var current = long.MaxValue;
+ var legacy = long.MaxValue;
+ for (var attempt = 0; attempt < 3; attempt++)
+ {
+ BackupArchive.Encrypt(data, Password); // warm the pool
+ var start = GC.GetAllocatedBytesForCurrentThread();
+ BackupArchive.Encrypt(data, Password);
+ current = Math.Min(current, GC.GetAllocatedBytesForCurrentThread() - start);
+ start = GC.GetAllocatedBytesForCurrentThread();
+ LegacyEncrypt(data, Password);
+ legacy = Math.Min(legacy, GC.GetAllocatedBytesForCurrentThread() - start);
+ }
+
+ Assert.True(current * 3 < legacy * 2, $"current={current} legacy={legacy}");
+ }
+
+ // Verbatim copies of the v1 implementation before issue #394, used as the compatibility oracle.
+ private static byte[] LegacyEncrypt(BackupData data, string password)
+ {
+ var plaintext = JsonSerializer.SerializeToUtf8Bytes(data, JsonDefaults.Options.Info());
+ var output = new byte[BackupArchive.Overhead + plaintext.Length];
+ "BYDLOBK\x01"u8.CopyTo(output);
+ RandomNumberGenerator.Fill(output.AsSpan(8, 16));
+ RandomNumberGenerator.Fill(output.AsSpan(24, 12));
+ var key = Rfc2898DeriveBytes.Pbkdf2(password, output.AsSpan(8, 16), 600_000, HashAlgorithmName.SHA256, 32);
+ using var aes = new AesGcm(key, 16);
+ aes.Encrypt(output.AsSpan(24, 12), plaintext, output.AsSpan(BackupArchive.Overhead), output.AsSpan(36, 16), output.AsSpan(0, 24));
+ return output;
+ }
+
+ private static byte[] LegacyDecrypt(byte[] file, string password)
+ {
+ Assert.True(file.AsSpan(0, 8).SequenceEqual("BYDLOBK\x01"u8));
+ var key = Rfc2898DeriveBytes.Pbkdf2(password, file.AsSpan(8, 16), 600_000, HashAlgorithmName.SHA256, 32);
+ var plaintext = new byte[file.Length - BackupArchive.Overhead];
+ using var aes = new AesGcm(key, 16);
+ aes.Decrypt(file.AsSpan(24, 12), file.AsSpan(BackupArchive.Overhead), file.AsSpan(36, 16), plaintext, file.AsSpan(0, 24));
+ return plaintext;
+ }
+}
diff --git a/tests/Bydlo.Tests/BackupCopyTests.cs b/tests/Bydlo.Tests/BackupCopyTests.cs
new file mode 100644
index 00000000..ae8f8be3
--- /dev/null
+++ b/tests/Bydlo.Tests/BackupCopyTests.cs
@@ -0,0 +1,177 @@
+using System.Collections;
+using System.Reflection;
+using System.Text.Json;
+using Bydlo.Core.Backup;
+using Bydlo.Core.Diagnostics;
+using Bydlo.Core.Models;
+using Bydlo.Core.Routing;
+using Bydlo.Core.Serialization;
+using Bydlo.Core.Storage;
+
+namespace Bydlo.Tests;
+
+/// Typed backup copy (issue #393): every field survives and no mutable state is shared.
+[Collection(nameof(AllocationMeasurements))]
+public sealed class BackupCopyTests
+{
+ [Fact]
+ public void Copy_preserves_every_serialized_field()
+ {
+ var original = Filled();
+ var copy = BackupCopy.Copy(original);
+ Assert.Equal(Json(original), Json(copy));
+ }
+
+ [Fact]
+ public void Copy_shares_no_mutable_container_or_model()
+ {
+ var original = Filled();
+ var copy = BackupCopy.Copy(original);
+ AssertNoSharedMutableState(original, copy, "BackupData");
+ }
+
+ [Fact]
+ public void Mutating_either_snapshot_does_not_change_the_other()
+ {
+ var original = Filled();
+ var copy = BackupCopy.Copy(original);
+ var before = Json(original);
+ copy.Profiles[0].Secrets.Values["uuid"] = "changed";
+ copy.Profiles[0].Profile.Options["sni"] = "changed";
+ copy.Subscriptions[0].Subscription.SourceOptions!.First().Value["k"] = "changed";
+ copy.Chains[0].ProfileIds.Add(Guid.NewGuid());
+ copy.Settings.Routing.DirectDomains.Add("changed.example");
+ copy.Settings.ServerGroups[0].ProfileIds.Clear();
+ copy.Settings.EnginePaths["x"] = "changed";
+ copy.ToolSecrets.Values["secret"] = "changed";
+ Assert.Equal(before, Json(original));
+
+ original.Settings.TgWsProxy.DcIps.Add("9:1.1.1.1");
+ Assert.DoesNotContain("9:1.1.1.1", copy.Settings.TgWsProxy.DcIps);
+ }
+
+ [Fact]
+ public void Copy_keeps_case_insensitive_dictionaries()
+ {
+ var copy = BackupCopy.Copy(Filled());
+ Assert.Same(StringComparer.OrdinalIgnoreCase, copy.Profiles[0].Profile.Options.Comparer);
+ Assert.Same(StringComparer.OrdinalIgnoreCase, copy.Profiles[0].Secrets.Values.Comparer);
+ Assert.Same(StringComparer.OrdinalIgnoreCase, copy.Settings.EnginePaths.Comparer);
+ }
+
+ [Fact]
+ public void Copy_tolerates_null_members_so_validation_still_rejects_them()
+ {
+ var data = new BackupData { Settings = null!, Profiles = null!, Subscriptions = null!, ToolSecrets = null!, Chains = null! };
+ var copy = BackupCopy.Copy(data);
+ Assert.Throws(() => BackupArchive.Validate(copy));
+ }
+
+ [Fact]
+ public void Copy_allocates_far_less_than_a_json_round_trip()
+ {
+ // Repeatable allocation benchmark from issue #393: 200 profiles with 128 KiB configs.
+ var data = new BackupData();
+ var config = new string('x', 128 * 1024);
+ for (var i = 0; i < 200; i++)
+ {
+ data.Profiles.Add(new(new Profile { Name = "p" + i, Protocol = ProtocolKind.WireGuard, Host = "h", Port = 1 },
+ new ProfileSecrets { Values = { [Keys.RawConfig] = config + i } }));
+ }
+ BackupCopy.Copy(data);
+ var start = GC.GetAllocatedBytesForCurrentThread();
+ BackupCopy.Copy(data);
+ var typed = GC.GetAllocatedBytesForCurrentThread() - start;
+
+ var info = JsonDefaults.Options.Info();
+ start = GC.GetAllocatedBytesForCurrentThread();
+ JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(data, info), info);
+ var json = GC.GetAllocatedBytesForCurrentThread() - start;
+
+ Assert.True(typed * 20 < json, $"typed={typed} json={json}");
+ }
+
+ private static string Json(BackupData data) => JsonSerializer.Serialize(data, JsonDefaults.Options.Info());
+
+ // ---- reflection helpers -------------------------------------------------------------
+
+ private static BackupData Filled() => (BackupData)Fill(typeof(BackupData), 0);
+
+ private static object Fill(Type type, int depth)
+ {
+ if (type == typeof(string)) { return "v" + depth; }
+ if (type == typeof(bool)) { return true; }
+ if (type == typeof(int)) { return 7; }
+ if (type == typeof(long)) { return 7L; }
+ if (type == typeof(Guid)) { return Guid.NewGuid(); }
+ if (type == typeof(DateTimeOffset)) { return new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); }
+ if (type == typeof(Uri)) { return new Uri("https://example.test/list"); }
+ if (type.IsEnum) { var values = Enum.GetValues(type); return values.GetValue(values.Length - 1)!; }
+ if (Nullable.GetUnderlyingType(type) is { } inner) { return Fill(inner, depth); }
+ if (type == typeof(DpiSettings)) { return new DpiSettings { Fragment = "tls", Mux = "smux", Padding = true }; }
+ if (type == typeof(OrderedRoutingRule)) { return new OrderedRoutingRule(RoutingCondition.Domain, "a.example", RoutingAction.Direct); }
+ if (type == typeof(RuleSetSource)) { return new RuleSetSource("tag", new Uri("https://example.test/r.srs"), new string('a', 64), 1024); }
+ if (type == typeof(GitHubRelease)) { return new GitHubRelease("v9", "https://example.test/r"); }
+ if (type == typeof(Contributor)) { return new Contributor("someone", 3); }
+ if (type == typeof(ImportedProfile)) { return new ImportedProfile((Profile)Fill(typeof(Profile), depth + 1), (ProfileSecrets)Fill(typeof(ProfileSecrets), depth + 1)); }
+ if (type == typeof(BackupSubscription)) { return new BackupSubscription((Subscription)Fill(typeof(Subscription), depth + 1), "https://example.test/sub"); }
+ if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
+ {
+ var list = (IList)Activator.CreateInstance(type)!;
+ list.Add(Fill(type.GetGenericArguments()[0], depth + 1));
+ return list;
+ }
+ if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
+ {
+ var args = type.GetGenericArguments();
+ var dict = (IDictionary)Activator.CreateInstance(type)!;
+ dict.Add(Fill(args[0], depth + 1), Fill(args[1], depth + 1));
+ return dict;
+ }
+ var instance = Activator.CreateInstance(type)
+ ?? throw new InvalidOperationException($"Cannot create {type}");
+ foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
+ {
+ if (property.SetMethod is null || property.GetIndexParameters().Length > 0) { continue; }
+ var value = Fill(property.PropertyType, depth + 1);
+ if (property.GetValue(instance) is IDictionary existing && value is IDictionary filled)
+ {
+ existing.Clear();
+ foreach (DictionaryEntry entry in filled) { existing.Add(entry.Key, entry.Value); }
+ continue;
+ }
+ property.SetValue(instance, value);
+ }
+ return instance;
+ }
+
+ private static bool IsImmutable(Type type) =>
+ type.IsValueType || type == typeof(string) || type == typeof(Uri)
+ // Positional records with only immutable members may be shared by design.
+ || type == typeof(DpiSettings) || type == typeof(OrderedRoutingRule) || type == typeof(RuleSetSource)
+ || type == typeof(GitHubRelease) || type == typeof(Contributor);
+
+ private static void AssertNoSharedMutableState(object? left, object? right, string path)
+ {
+ if (left is null || right is null) { return; }
+ var type = left.GetType();
+ if (IsImmutable(type)) { return; }
+ Assert.False(ReferenceEquals(left, right), $"{path} is shared between snapshots");
+ if (left is IDictionary leftDict && right is IDictionary rightDict)
+ {
+ foreach (DictionaryEntry entry in leftDict)
+ { AssertNoSharedMutableState(entry.Value, rightDict[entry.Key], $"{path}[{entry.Key}]"); }
+ return;
+ }
+ if (left is IList leftList && right is IList rightList)
+ {
+ for (var i = 0; i < leftList.Count; i++) { AssertNoSharedMutableState(leftList[i], rightList[i], $"{path}[{i}]"); }
+ return;
+ }
+ foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
+ {
+ if (property.GetIndexParameters().Length > 0) { continue; }
+ AssertNoSharedMutableState(property.GetValue(left), property.GetValue(right), $"{path}.{property.Name}");
+ }
+ }
+}
diff --git a/tests/Bydlo.Tests/BackupImportSessionTests.cs b/tests/Bydlo.Tests/BackupImportSessionTests.cs
index 41bb8af6..ad88c3cb 100644
--- a/tests/Bydlo.Tests/BackupImportSessionTests.cs
+++ b/tests/Bydlo.Tests/BackupImportSessionTests.cs
@@ -48,13 +48,13 @@ public void Metadata_contains_only_ids_names_relationships_and_caller_cannot_cha
public void Dispose_is_idempotent_and_clears_owned_arrays_and_failed_read_plaintext()
{
var session = BackupArchive.OpenImport(BackupArchive.Encrypt(Data(), Password), Password);
- byte[]? plaintext = null;
+ ReadOnlyMemory? plaintext = null;
var read = typeof(BackupImportSession).GetMethod("ReadPlaintext", BindingFlags.Instance | BindingFlags.NonPublic)!.MakeGenericMethod(typeof(bool));
- var error = Assert.Throws(() => read.Invoke(session, [new Func(bytes =>
+ var error = Assert.Throws(() => read.Invoke(session, [new Func, bool>(bytes =>
{ plaintext = bytes; throw new IOException("Synthetic read failure"); })]));
Assert.IsType(error.InnerException);
Assert.NotNull(plaintext);
- Assert.All(plaintext, value => Assert.Equal(0, value));
+ Assert.All(plaintext.Value.ToArray(), value => Assert.Equal(0, value));
var key = Buffer(session, "_key");
var archive = Buffer(session, "_archive");
Assert.Contains(key, value => value != 0);
@@ -97,7 +97,7 @@ public void Sanitizer_removes_escaped_secret_values_and_legacy_headers_before_de
try
{
var method = typeof(BackupImportSession).GetMethod("ReadMetadata", BindingFlags.NonPublic | BindingFlags.Static)!;
- var sanitized = (BackupData)method.Invoke(null, [plaintext])!;
+ var sanitized = (BackupData)method.Invoke(null, [new ReadOnlyMemory(plaintext)])!;
Assert.Equal("x", sanitized.Profiles[0].Secrets[Keys.Password]);
Assert.Equal("x", sanitized.Profiles[0].Secrets[Keys.RawConfig]);
Assert.Equal("x", sanitized.Profiles[0].Profile.Options[Keys.XhttpHeaders]);
diff --git a/tests/Bydlo.Tests/BackupSettingsValidationTests.cs b/tests/Bydlo.Tests/BackupSettingsValidationTests.cs
index 1f36a11b..af60fe21 100644
--- a/tests/Bydlo.Tests/BackupSettingsValidationTests.cs
+++ b/tests/Bydlo.Tests/BackupSettingsValidationTests.cs
@@ -19,6 +19,39 @@ public void Rejects_null_dns_collections(string property)
Assert.Throws(() => BackupArchive.Validate(data));
}
+ [Fact]
+ public void Rejects_null_server_groups_and_contributors()
+ {
+ // A null list used to pass validation and throw later in ImportSettings (Merge) or after saving.
+ var data = new BackupData();
+ data.Settings.ServerGroups = null!;
+ Assert.Throws(() => BackupArchive.Validate(data));
+ Assert.Throws(() => BackupArchive.Encrypt(data, "a long backup password"));
+
+ data = new BackupData();
+ data.Settings.ServerGroups = [null!];
+ Assert.Throws(() => BackupArchive.Validate(data));
+
+ data = new BackupData();
+ data.Settings.ServerGroups = [new ServerGroup { Name = "g", ProfileIds = null! }];
+ Assert.Throws(() => BackupArchive.Validate(data));
+
+ data = new BackupData();
+ data.Settings.Contributors = null!;
+ Assert.Throws(() => BackupArchive.Validate(data));
+ }
+
+ [Fact]
+ public void Valid_server_groups_still_merge()
+ {
+ var data = new BackupData();
+ var group = new ServerGroup { Name = "g" };
+ data.Settings.ServerGroups = [group];
+ BackupArchive.Validate(data);
+ var merged = BackupArchive.ImportSettings(data, new AppSettings { ServerGroups = [new ServerGroup { Name = "local" }] }, BackupImportMode.Merge);
+ Assert.Equal(2, merged.ServerGroups.Count);
+ }
+
[Theory]
[InlineData("RemoteDnsTransport")]
[InlineData("DirectDnsTransport")]
@@ -54,4 +87,28 @@ public void Accepts_settings_from_before_the_new_dns_and_dpi_fields()
Assert.Equal(DnsTransport.Https, data.Settings.Routing.RemoteDnsTransport);
Assert.Equal("off", data.Settings.DpiDefaults.Fragment);
}
+
+ [Fact]
+ public void Rejects_null_or_invalid_proxy_protocol_trusted_sources()
+ {
+ var data = new BackupData();
+ data.Settings.TgWsProxy.ProxyProtocolTrustedSources = null!;
+ Assert.Throws(() => BackupArchive.Validate(data));
+
+ data.Settings.TgWsProxy.ProxyProtocolTrustedSources = ["127.0.0.1", "not-an-ip"];
+ Assert.Throws(() => BackupArchive.Validate(data));
+
+ data.Settings.TgWsProxy.ProxyProtocolTrustedSources = ["127.0.0.1", "::1"];
+ data.Settings.TgWsProxy.ProxyProtocol = true;
+ BackupArchive.Validate(data);
+ }
+
+ [Fact]
+ public void Accepts_settings_from_before_the_proxy_protocol_fields()
+ {
+ var data = System.Text.Json.JsonSerializer.Deserialize("""{"Settings":{"TgWsProxy":{"Port":1443}}}""")!;
+ BackupArchive.Validate(data);
+ Assert.False(data.Settings.TgWsProxy.ProxyProtocol);
+ Assert.Equal(new[] { "127.0.0.1", "::1" }, data.Settings.TgWsProxy.ProxyProtocolTrustedSources.ToArray());
+ }
}
diff --git a/tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs b/tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs
new file mode 100644
index 00000000..8f0741f7
--- /dev/null
+++ b/tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs
@@ -0,0 +1,68 @@
+using Bydlo.Engines.TgWsProxy;
+
+namespace Bydlo.Tests;
+
+/// FakeTlsStream is read and written by two bridge workers at the same time.
+public sealed class FakeTlsConcurrencyTests
+{
+ /// Serves scripted bytes to reads; holds every write until released and records it.
+ private sealed class GatedStream(byte[] incoming) : Stream
+ {
+ private int _offset;
+ public TaskCompletionSource WriteEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public TaskCompletionSource ReleaseWrite { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ public MemoryStream Written { get; } = new();
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => true;
+ public override long Length => throw new NotSupportedException();
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ var n = Math.Min(buffer.Length, incoming.Length - _offset);
+ incoming.AsSpan(_offset, n).CopyTo(buffer.Span);
+ _offset += n;
+ return ValueTask.FromResult(n);
+ }
+
+ public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ WriteEntered.TrySetResult();
+ await ReleaseWrite.Task.WaitAsync(cancellationToken);
+ // Copy only now: a buffer reused by a concurrent read would show up here.
+ Written.Write(buffer.Span);
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ public override void Flush() { }
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ }
+
+ [Fact]
+ public async Task Skipping_a_change_cipher_spec_does_not_corrupt_a_pending_write()
+ {
+ // Incoming: a 200-byte CCS record (0xEE), then an ApplicationData record "ok".
+ var ccs = new byte[200];
+ ccs.AsSpan().Fill(0xEE);
+ byte[] incoming = [0x14, 0x03, 0x03, 0x00, 200, .. ccs, 0x17, 0x03, 0x03, 0x00, 0x02, (byte)'o', (byte)'k'];
+ var inner = new GatedStream(incoming);
+ var tls = new FakeTlsStream(inner);
+
+ var payload = new byte[300];
+ Random.Shared.NextBytes(payload);
+ var write = tls.WriteAsync(payload.AsMemory()).AsTask();
+ await inner.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(10));
+
+ // The write is parked inside the inner stream while the reader skips the CCS payload.
+ var buffer = new byte[16];
+ var read = await tls.ReadAsync(buffer.AsMemory()).AsTask().WaitAsync(TimeSpan.FromSeconds(10));
+ Assert.Equal("ok"u8.ToArray(), buffer[..read]);
+
+ inner.ReleaseWrite.SetResult();
+ await write.WaitAsync(TimeSpan.FromSeconds(10));
+ Assert.Equal(FakeTlsStream.Wrap(payload), inner.Written.ToArray());
+ }
+}
diff --git a/tests/Bydlo.Tests/FirstRunConsentTests.cs b/tests/Bydlo.Tests/FirstRunConsentTests.cs
index 9e4411ff..ca9ca03c 100644
--- a/tests/Bydlo.Tests/FirstRunConsentTests.cs
+++ b/tests/Bydlo.Tests/FirstRunConsentTests.cs
@@ -292,6 +292,8 @@ private sealed class FakeBackend : IAppUpdateBackend
{
public bool IsInstalled => true;
+ public string? PendingVersion => "0.4.4";
+
public int Downloads { get; private set; }
public int Applied { get; private set; }
diff --git a/tests/Bydlo.Tests/HelperInstallBundleTests.cs b/tests/Bydlo.Tests/HelperInstallBundleTests.cs
new file mode 100644
index 00000000..c0b4651c
--- /dev/null
+++ b/tests/Bydlo.Tests/HelperInstallBundleTests.cs
@@ -0,0 +1,57 @@
+using Bydlo.Platform;
+
+namespace Bydlo.Tests;
+
+public sealed class HelperInstallBundleTests
+{
+ [UnixFact]
+ public void Rejects_linked_payloads_without_touching_the_link_target()
+ {
+ var source = Directory.CreateTempSubdirectory("helper-link-source-").FullName;
+ try
+ {
+ Directory.CreateDirectory(Path.Combine(source, "helper"));
+ var target = Path.Combine(source, "foreign-file");
+ File.WriteAllText(target, "unchanged");
+ File.CreateSymbolicLink(Path.Combine(source, "helper", "Bydlo.Helper"), target);
+ Assert.Throws(() => HelperInstallBundle.Stage(source, install: false));
+ Assert.Equal("unchanged", File.ReadAllText(target));
+ }
+ finally { Directory.Delete(source, recursive: true); }
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void Stages_helper_and_required_engines_without_executing_them(bool install)
+ {
+ var source = Directory.CreateTempSubdirectory("helper-source-").FullName;
+ string stagedPath;
+ try
+ {
+ Directory.CreateDirectory(Path.Combine(source, "helper"));
+ Directory.CreateDirectory(Path.Combine(source, "engines", "zapret"));
+ var helper = Path.Combine(source, "helper", "Bydlo.Helper");
+ File.WriteAllText(helper, "inert helper fixture");
+ File.WriteAllText(Path.Combine(source, "engines", "zapret", "nfqws"), "inert engine fixture");
+ if (!OperatingSystem.IsWindows())
+ {
+ File.SetUnixFileMode(helper, UnixFileMode.UserRead | UnixFileMode.UserExecute);
+ }
+ using (var bundle = HelperInstallBundle.Stage(source, install))
+ {
+ stagedPath = bundle.DirectoryPath;
+ Assert.NotEqual(source, stagedPath);
+ Assert.Equal("inert helper fixture", File.ReadAllText(bundle.Executable));
+ Assert.Equal(install, File.Exists(Path.Combine(stagedPath, "engines", "zapret", "nfqws")));
+ if (!OperatingSystem.IsWindows())
+ {
+ Assert.Equal(File.GetUnixFileMode(helper), File.GetUnixFileMode(bundle.Executable));
+ }
+ }
+ Assert.False(Directory.Exists(stagedPath));
+ Assert.True(File.Exists(helper));
+ }
+ finally { Directory.Delete(source, recursive: true); }
+ }
+}
diff --git a/tests/Bydlo.Tests/InterfaceScaleTests.cs b/tests/Bydlo.Tests/InterfaceScaleTests.cs
new file mode 100644
index 00000000..f48d1519
--- /dev/null
+++ b/tests/Bydlo.Tests/InterfaceScaleTests.cs
@@ -0,0 +1,238 @@
+using System.Text.Json;
+using Bydlo.App.Services;
+using Bydlo.App.Views;
+using Bydlo.Core.Backup;
+using Bydlo.Core.Models;
+using Bydlo.Core.Storage;
+
+namespace Bydlo.Tests;
+
+/// Issue #477: interface scale setting, persistence, backup validation and the navigation breakpoint.
+public class InterfaceScaleTests
+{
+ [Fact]
+ public void Fresh_settings_use_100_percent()
+ {
+ var settings = new AppSettings();
+ Assert.Equal(100, settings.InterfaceScale);
+ Assert.Equal(1.0, settings.InterfaceScaleFactor);
+ Assert.Equal(AppSettings.DefaultInterfaceScale, settings.InterfaceScale);
+ }
+
+ [Fact]
+ public void Selectable_steps_cover_the_supported_range()
+ {
+ var steps = AppSettings.InterfaceScaleSteps;
+ Assert.Equal(AppSettings.MinInterfaceScale, steps[0]);
+ Assert.Equal(AppSettings.MaxInterfaceScale, steps[^1]);
+ Assert.Contains(AppSettings.DefaultInterfaceScale, steps);
+ Assert.All(steps, step => Assert.Equal(0, (step - AppSettings.MinInterfaceScale) % AppSettings.InterfaceScaleStep));
+ Assert.Equal(steps.Count, steps.Distinct().Count());
+ Assert.Equal(steps.Order(), steps);
+ }
+
+ [Theory]
+ [InlineData(0, 80)]
+ [InlineData(-40, 80)]
+ [InlineData(79, 80)]
+ [InlineData(80, 80)]
+ [InlineData(84, 80)]
+ [InlineData(85, 90)]
+ [InlineData(100, 100)]
+ [InlineData(104, 100)]
+ [InlineData(105, 110)]
+ [InlineData(130, 130)]
+ [InlineData(149, 150)]
+ [InlineData(150, 150)]
+ [InlineData(151, 150)]
+ [InlineData(1000, 150)]
+ public void Out_of_range_values_are_clamped_and_snapped(int stored, int expected)
+ {
+ Assert.Equal(expected, AppSettings.ClampInterfaceScale(stored));
+ Assert.Contains(expected, AppSettings.InterfaceScaleSteps);
+ }
+
+ [Fact]
+ public void Normalize_repairs_a_hand_edited_value()
+ {
+ var settings = new AppSettings { InterfaceScale = 999 };
+ Assert.True(settings.NormalizeInterfaceScale());
+ Assert.Equal(150, settings.InterfaceScale);
+ Assert.False(settings.NormalizeInterfaceScale());
+
+ settings.InterfaceScale = 0;
+ Assert.True(settings.NormalizeInterfaceScale());
+ Assert.Equal(80, settings.InterfaceScale);
+ }
+
+ [Fact]
+ public async Task Scale_survives_a_settings_round_trip()
+ {
+ var path = Path.Combine(TestDirs.New("interface-scale"), "settings.json");
+ await new SettingsStore(path).SaveAsync(new AppSettings { InterfaceScale = 130 });
+ var reloaded = await new SettingsStore(path).LoadAsync();
+ Assert.Equal(130, reloaded.InterfaceScale);
+ Assert.Equal(1.3, reloaded.InterfaceScaleFactor, 3);
+ }
+
+ [Fact]
+ public async Task Loading_repairs_an_unsupported_stored_scale()
+ {
+ var path = Path.Combine(TestDirs.New("interface-scale-repair"), "settings.json");
+ await File.WriteAllTextAsync(path, """{"InterfaceScale": 500}""");
+ var reloaded = await new SettingsStore(path).LoadAsync();
+ Assert.Equal(AppSettings.MaxInterfaceScale, reloaded.InterfaceScale);
+ }
+
+ [Fact]
+ public async Task Settings_without_the_field_keep_the_default()
+ {
+ var path = Path.Combine(TestDirs.New("interface-scale-legacy"), "settings.json");
+ await File.WriteAllTextAsync(path, """{"LocalProxyPort": 2080}""");
+ var reloaded = await new SettingsStore(path).LoadAsync();
+ Assert.Equal(AppSettings.DefaultInterfaceScale, reloaded.InterfaceScale);
+ }
+
+ [Theory]
+ [InlineData(80)]
+ [InlineData(100)]
+ [InlineData(150)]
+ public void Backup_validation_accepts_supported_scales(int scale)
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = scale;
+ BackupArchive.Validate(data);
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(79)]
+ [InlineData(151)]
+ [InlineData(1000)]
+ public void Backup_validation_rejects_out_of_range_scales(int scale)
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = scale;
+ Assert.Throws(() => BackupArchive.Validate(data));
+ }
+
+ [Fact]
+ public void Backup_import_copies_the_scale()
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = 120;
+ var restored = BackupArchive.ImportSettings(data, new AppSettings { InterfaceScale = 80 }, BackupImportMode.Replace);
+ Assert.Equal(120, restored.InterfaceScale);
+ }
+
+ [Fact]
+ public void Backup_import_snaps_an_unsupported_scale()
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = 145;
+ var restored = BackupArchive.ImportSettings(data, new AppSettings(), BackupImportMode.Merge);
+ Assert.Equal(150, restored.InterfaceScale);
+ }
+
+ [Fact]
+ public void Backup_round_trip_keeps_the_scale()
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = 90;
+ var decrypted = BackupArchive.Decrypt(BackupArchive.Encrypt(data, "correct horse battery staple"), "correct horse battery staple");
+ Assert.Equal(90, decrypted.Settings.InterfaceScale);
+ }
+
+ [Theory]
+ [InlineData(1180, 1.0, false)]
+ [InlineData(760, 1.0, false)]
+ [InlineData(759, 1.0, true)]
+ [InlineData(1180, 1.5, false)]
+ [InlineData(1140, 1.5, false)]
+ [InlineData(1139, 1.5, true)]
+ [InlineData(1180, 0.8, false)]
+ [InlineData(608, 0.8, false)]
+ [InlineData(607, 0.8, true)]
+ public void Navigation_switch_uses_the_effective_unscaled_width(double windowWidth, double scale, bool compact)
+ {
+ var effective = LayoutMetrics.EffectiveWidth(windowWidth, scale);
+ Assert.Equal(compact, LayoutMetrics.IsCompact(effective));
+ }
+
+ [Fact]
+ public void Effective_width_ignores_a_broken_scale()
+ {
+ Assert.Equal(900, LayoutMetrics.EffectiveWidth(900, 0));
+ Assert.Equal(900, LayoutMetrics.EffectiveWidth(900, double.NaN));
+ Assert.Equal(900, LayoutMetrics.EffectiveWidth(900, double.PositiveInfinity));
+ }
+
+ [Fact]
+ public void Shell_recomputes_the_navigation_switch_when_the_scale_changes()
+ {
+ // 1180 at 100% is a sidebar layout; the same window at 150% leaves 786 unscaled units,
+ // and 1140 at 150% lands exactly on the breakpoint.
+ Assert.False(LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(1180, 1.0)));
+ Assert.False(LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(1180, 1.5)));
+ Assert.True(LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(1100, 1.5)));
+ Assert.Equal(MainView.CompactWidth, LayoutMetrics.CompactWidth);
+ }
+
+ [Fact]
+ public void Shell_applies_the_scale_as_a_layout_transform()
+ {
+ var root = RepositoryRoot();
+ var view = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "MainView.axaml"));
+ Assert.Contains("", view, StringComparison.Ordinal);
+ Assert.Contains("", view, StringComparison.Ordinal);
+ // The transform must wrap the whole shell, not a single page.
+ Assert.True(view.IndexOf(" new ScaleTransform(", shell, StringComparison.Ordinal);
+ Assert.Contains("LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(LayoutWidth, InterfaceScaleFactor))", shell, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Appearance_page_offers_the_scale_and_a_reset()
+ {
+ var root = RepositoryRoot();
+ var view = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "AppearanceSettingsView.axaml"));
+ Assert.Contains("ItemsSource=\"{x:Static vm:SettingsViewModel.InterfaceScales}\"", view, StringComparison.Ordinal);
+ Assert.Contains("SelectedItem=\"{Binding InterfaceScale}\"", view, StringComparison.Ordinal);
+ Assert.Contains("Command=\"{Binding ResetInterfaceScaleCommand}\"", view, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Scale_strings_exist_in_both_languages()
+ {
+ var root = RepositoryRoot();
+ var en = JsonSerializer.Deserialize>(
+ File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "en.json")))!;
+ var ru = JsonSerializer.Deserialize>(
+ File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "ru.json")))!;
+ string[] keys = ["settings.scale", "settings.scale.hint", "settings.scale.reset", "settings.scale.reset.done"];
+ foreach (var key in keys)
+ {
+ Assert.True(en.TryGetValue(key, out var english) && !string.IsNullOrWhiteSpace(english), "Missing en: " + key);
+ Assert.True(ru.TryGetValue(key, out var russian) && !string.IsNullOrWhiteSpace(russian), "Missing ru: " + key);
+ }
+ }
+
+ private static string RepositoryRoot()
+ {
+ for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
+ {
+ if (File.Exists(Path.Combine(dir.FullName, "BYDLO.slnx")))
+ {
+ return dir.FullName;
+ }
+ }
+ throw new DirectoryNotFoundException("Repository root not found.");
+ }
+}
diff --git a/tests/Bydlo.Tests/SessionSecretsCleanupTests.cs b/tests/Bydlo.Tests/SessionSecretsCleanupTests.cs
index 4f892014..48954399 100644
--- a/tests/Bydlo.Tests/SessionSecretsCleanupTests.cs
+++ b/tests/Bydlo.Tests/SessionSecretsCleanupTests.cs
@@ -71,7 +71,8 @@ public async Task SingBox_config_is_removed_after_failed_start()
var engine = SingBox(runner);
var work = TestDirs.New("sb-clean-fail");
var start = engine.StartAsync(SingBoxRequest(work));
- await Task.Delay(100);
+ // Wait for the fake process instead of a fixed delay: a slow runner made runner.Last null.
+ await WaitForAsync(() => runner.Last is not null);
runner.Last!.Crash(1);
await Assert.ThrowsAsync(() => start);
Assert.False(File.Exists(Path.Combine(work, "sing-box.json")));
@@ -84,7 +85,8 @@ public async Task Xray_config_is_removed_after_failed_start()
var engine = Xray(runner);
var work = TestDirs.New("xray-clean-fail");
var start = engine.StartAsync(XrayRequest(work));
- await Task.Delay(100);
+ // Wait for the fake process instead of a fixed delay: a slow runner made runner.Last null.
+ await WaitForAsync(() => runner.Last is not null);
runner.Last!.Crash(1);
await Assert.ThrowsAsync(() => start);
Assert.False(File.Exists(Path.Combine(work, "xray.json")));
diff --git a/tests/Bydlo.Tests/TgWsProxyAllocationTests.cs b/tests/Bydlo.Tests/TgWsProxyAllocationTests.cs
new file mode 100644
index 00000000..8b1e0705
--- /dev/null
+++ b/tests/Bydlo.Tests/TgWsProxyAllocationTests.cs
@@ -0,0 +1,148 @@
+using System.Buffers.Binary;
+using Bydlo.Engines.TgWsProxy;
+
+namespace Bydlo.Tests;
+
+/// Allocation-free upstream path (issue #359); wire bytes are unchanged.
+public sealed class TgWsProxyAllocationTests
+{
+ /// Answers the upgrade once (optionally with trailing frame bytes), then idles; writes are recorded or discarded.
+ private sealed class ScriptedStream(byte[] response, bool record) : Stream
+ {
+ private int _offset;
+ public MemoryStream Written { get; } = new();
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => true;
+ public override long Length => throw new NotSupportedException();
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ if (_offset < response.Length)
+ {
+ var n = Math.Min(buffer.Length, response.Length - _offset);
+ response.AsSpan(_offset, n).CopyTo(buffer.Span);
+ _offset += n;
+ return n;
+ }
+
+ await Task.Delay(Timeout.Infinite, cancellationToken);
+ return 0;
+ }
+
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default)
+ {
+ if (record) { Written.Write(buffer.Span); }
+ return ValueTask.CompletedTask;
+ }
+
+ public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+ public override void Write(byte[] buffer, int offset, int count) => WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
+ public override void Flush() { }
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ }
+
+ private static readonly byte[] Upgrade = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n\r\n"u8.ToArray();
+
+ private static byte[] Packet(int payload, byte fill)
+ {
+ var packet = new byte[4 + payload];
+ BinaryPrimitives.WriteUInt32LittleEndian(packet, (uint)payload);
+ packet.AsSpan(4).Fill(fill);
+ return packet;
+ }
+
+ /// Decodes masked client frames back to payloads.
+ private static List Unframe(ReadOnlySpan wire)
+ {
+ var payloads = new List();
+ while (!wire.IsEmpty)
+ {
+ Assert.Equal(0x82, wire[0]);
+ Assert.True((wire[1] & 0x80) != 0);
+ int length = wire[1] & 0x7F, at = 2;
+ if (length == 126) { length = BinaryPrimitives.ReadUInt16BigEndian(wire[2..]); at = 4; }
+ else if (length == 127) { length = (int)BinaryPrimitives.ReadUInt64BigEndian(wire[2..]); at = 10; }
+ var key = wire.Slice(at, 4);
+ var payload = wire.Slice(at + 4, length).ToArray();
+ for (var i = 0; i < payload.Length; i++) { payload[i] ^= key[i & 3]; }
+ payloads.Add(payload);
+ wire = wire[(at + 4 + length)..];
+ }
+
+ return payloads;
+ }
+
+ [Fact]
+ public async Task Frame_bytes_arriving_with_the_upgrade_head_are_not_lost()
+ {
+ byte[] frame = [0x82, 0x02, (byte)'x', (byte)'y'];
+ var stream = new ScriptedStream([.. Upgrade, .. frame], record: false);
+ await using var ws = await RawWebSocket.UpgradeAsync(stream, "kws2.web.telegram.org", "/apiws", CancellationToken.None);
+ Assert.Equal("xy"u8.ToArray(), await ws.ReceiveAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10)));
+ }
+
+ [Fact]
+ public async Task Packets_go_out_as_one_frame_each_with_the_same_payloads()
+ {
+ var stream = new ScriptedStream(Upgrade, record: true);
+ await using var ws = await RawWebSocket.UpgradeAsync(stream, "kws2.web.telegram.org", "/apiws", CancellationToken.None);
+ stream.Written.SetLength(0);
+ var splitter = new MsgSplitter(MtProto.Intermediate);
+ var lengths = new List();
+ byte[][] packets = [Packet(8, 1), Packet(200, 2), Packet(70_000, 3)];
+ byte[] chunk = [.. packets.SelectMany(p => p), .. Packet(16, 4).AsSpan(0, 10)];
+ var data = splitter.SplitInto(chunk, chunk, lengths);
+ Assert.Equal(packets.Select(p => p.Length), lengths);
+ await ws.SendPacketsAsync(data, lengths, CancellationToken.None);
+ Assert.Equal(packets, Unframe(stream.Written.ToArray()));
+
+ // The partial packet is completed by the next chunk.
+ var rest = Packet(16, 4)[10..];
+ data = splitter.SplitInto(rest, rest, lengths);
+ Assert.Equal([Packet(16, 4)], [data.ToArray()]);
+ }
+
+ [Fact]
+ public async Task Upstream_path_allocates_under_a_fifth_of_a_byte_per_byte()
+ {
+ var stream = new ScriptedStream(Upgrade, record: false);
+ await using var ws = await RawWebSocket.UpgradeAsync(stream, "kws2.web.telegram.org", "/apiws", CancellationToken.None);
+ var splitter = new MsgSplitter(MtProto.Intermediate);
+ var lengths = new List();
+ // Four packets per 16 KiB read, the last one split across reads.
+ byte[] stream16 = [.. Packet(4092, 1), .. Packet(4092, 2), .. Packet(4092, 3), .. Packet(4092, 4)];
+ var chunk = stream16.AsMemory(0, 16 * 1024 - 100);
+ var tail = stream16.AsMemory(16 * 1024 - 100);
+
+ async Task Round()
+ {
+ var a = splitter.SplitInto(chunk.Span, chunk.Span, lengths);
+ await ws.SendPacketsAsync(a, lengths, CancellationToken.None);
+ var b = splitter.SplitInto(tail.Span, tail.Span, lengths);
+ await ws.SendPacketsAsync(b, lengths, CancellationToken.None);
+ }
+
+ for (var i = 0; i < 50; i++) { await Round(); }
+ const int Rounds = 1000;
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < Rounds; i++) { await Round(); }
+ var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+ var traffic = (double)Rounds * stream16.Length;
+ Assert.True(allocated / traffic < 0.2, $"{allocated / traffic:0.000} B per byte");
+ }
+
+ [Fact]
+ public async Task Fake_tls_writes_match_the_reference_wrapping()
+ {
+ var sink = new MemoryStream();
+ var tls = new FakeTlsStream(sink);
+ var payload = new byte[40_000];
+ Random.Shared.NextBytes(payload);
+ await tls.WriteAsync(payload.AsMemory());
+ Assert.Equal(FakeTlsStream.Wrap(payload), sink.ToArray());
+ }
+}
diff --git a/tests/Bydlo.Tests/TgWsProxyListenerRaceTests.cs b/tests/Bydlo.Tests/TgWsProxyListenerRaceTests.cs
index c2739986..9218b594 100644
--- a/tests/Bydlo.Tests/TgWsProxyListenerRaceTests.cs
+++ b/tests/Bydlo.Tests/TgWsProxyListenerRaceTests.cs
@@ -1,4 +1,5 @@
using System.IO;
+using System.Net;
using Bydlo.Engines.TgWsProxy;
namespace Bydlo.Tests;
@@ -99,7 +100,7 @@ public RaceListener(Action? onDisposed = null, bool blockForever = false)
public bool Disposed => Volatile.Read(ref _disposed) != 0;
- public async Task<(Stream Stream, string Label)> AcceptAsync(CancellationToken ct)
+ public async Task<(Stream Stream, string Label, IPAddress? RemoteAddress)> AcceptAsync(CancellationToken ct)
{
if (_blockForever)
{
diff --git a/tests/Bydlo.Tests/TgWsProxyProxyProtocolTests.cs b/tests/Bydlo.Tests/TgWsProxyProxyProtocolTests.cs
new file mode 100644
index 00000000..d4b12965
--- /dev/null
+++ b/tests/Bydlo.Tests/TgWsProxyProxyProtocolTests.cs
@@ -0,0 +1,393 @@
+using System.Collections.Concurrent;
+using System.Net;
+using System.Text;
+using Bydlo.Core.Engines;
+using Bydlo.Core.Models;
+using Bydlo.Engines.TgWsProxy;
+
+namespace Bydlo.Tests;
+
+///
+/// Issue #425: the optional PROXY protocol v1 header of Flowseal tg-ws-proxy 1.11.4. Every case runs over
+/// in-memory streams; no socket is opened and no engine is started.
+///
+public partial class TgWsProxyTests
+{
+ private const string ValidHeader = "PROXY TCP4 203.0.113.7 198.51.100.1 51234 443\r\n";
+
+ [Fact]
+ public async Task Valid_v1_header_is_consumed_before_the_client_handshake()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ using var client = new RecordingStream([.. Encoding.ASCII.GetBytes(ValidHeader), .. telegram.Init]);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("PROXY protocol v1 header accepted (TCP4)", StringComparison.Ordinal));
+ // The header address becomes the log label of the real client.
+ Assert.Contains(logs, l => l.Contains("[203.0.113.7:51234]", StringComparison.Ordinal));
+ // The handshake right after the header still parses: the header did not disturb MTProto.
+ Assert.Contains(logs, l => l.Contains("handshake ok: DC2", StringComparison.Ordinal));
+ Assert.Equal(ValidHeader.Length + MtProto.HandshakeLength, client.BytesRead);
+ Assert.Contains("bad=0", proxy.Stats.Summary());
+ }
+
+ [Fact]
+ public async Task Valid_v1_header_with_unknown_family_keeps_the_peer_label()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ using var client = new RecordingStream([.. "PROXY UNKNOWN\r\n"u8, .. telegram.Init]);
+
+ await proxy.HandleClientAsync(client, "peer-label", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("PROXY protocol v1 header accepted (UNKNOWN)", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("[peer-label]", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("handshake ok: DC2", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Valid_v1_header_from_ipv6_loopback_is_accepted()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ using var client = new RecordingStream([.. "PROXY TCP6 2001:db8::7 2001:db8::1 51234 443\r\n"u8, .. telegram.Init]);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.IPv6Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("[2001:db8::7]:51234", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("handshake ok: DC2", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Fragmented_header_is_reassembled()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ // One byte per read: the header arrives in as many pieces as it has bytes.
+ using var client = new RecordingStream([.. Encoding.ASCII.GetBytes(ValidHeader), .. telegram.Init], chunk: 1);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("PROXY protocol v1 header accepted (TCP4)", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("handshake ok: DC2", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Binary_v2_header_is_rejected_because_upstream_has_no_v2_support()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ // v2 signature followed by a minimal LOCAL command header.
+ byte[] v2 = [0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A, 0x20, 0x00, 0x00, 0x00];
+ using var client = new RecordingStream(v2);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("invalid PROXY protocol header", StringComparison.Ordinal));
+ Assert.DoesNotContain(logs, l => l.Contains("handshake", StringComparison.Ordinal));
+ // Rejected as soon as the 12-byte signature is complete, without scanning for a line end.
+ Assert.Equal(12, client.BytesRead);
+ Assert.Contains("bad=1", proxy.Stats.Summary());
+ Assert.Equal(0, proxy.Stats.ActiveConnections);
+ }
+
+ [Theory]
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234\r\n")] // missing destination port
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234 443 7\r\n")] // extra field
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234 99999\r\n")] // port out of range
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234 -1\r\n")] // negative port
+ [InlineData("PROXY TCP4 2001:db8::7 2001:db8::1 51234 443\r\n")] // family does not match the address
+ [InlineData("PROXY TCP6 203.0.113.7 198.51.100.1 51234 443\r\n")]
+ [InlineData("PROXY TCP9 203.0.113.7 198.51.100.1 51234 443\r\n")] // unknown family
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234 443\n")] // LF without CR
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234 443\r\n")] // double space
+ [InlineData("PROXY\r\n")]
+ [InlineData("GET / HTTP/1.1\r\n")] // not a PROXY header at all
+ [InlineData("PROXY TCP4 203.0.113.7 198.51.100.1 51234 443\rX")] // no LF, garbage tail
+ public async Task Malformed_header_closes_the_connection(string header)
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var client = new RecordingStream(Encoding.ASCII.GetBytes(header));
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("invalid PROXY protocol header", StringComparison.Ordinal));
+ Assert.DoesNotContain(logs, l => l.Contains("handshake", StringComparison.Ordinal));
+ Assert.True(client.Disposed, "The connection must be closed after a bad header.");
+ Assert.Equal(0, proxy.Stats.ActiveConnections);
+ }
+
+ [Fact]
+ public async Task Non_ascii_header_is_rejected()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ byte[] header = [.. "PROXY TCP4 203.0.113.7 198.51.100.1 51234 443"u8, 0xFF, (byte)'\r', (byte)'\n'];
+ using var client = new RecordingStream(header);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("invalid PROXY protocol header", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Oversized_header_is_rejected_without_reading_past_the_limit()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var client = new RecordingStream(Encoding.ASCII.GetBytes(new string('A', 4096)));
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("invalid PROXY protocol header", StringComparison.Ordinal));
+ Assert.Equal(ProxyProtocol.MaxHeaderLength, client.BytesRead);
+ Assert.True(client.Disposed);
+ }
+
+ [Fact]
+ public async Task Incomplete_header_is_rejected_when_the_peer_disconnects()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var client = new RecordingStream("PROXY TCP4 203.0.113.7"u8.ToArray());
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("invalid PROXY protocol header", StringComparison.Ordinal));
+ Assert.True(client.Disposed);
+ }
+
+ [Fact]
+ public async Task Header_read_times_out()
+ {
+ using var silent = new BlockingStream();
+ var started = DateTime.UtcNow;
+
+ var header = await ProxyProtocol.ReadAsync(silent, TimeSpan.FromMilliseconds(50), CancellationToken.None);
+
+ Assert.Null(header);
+ Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(5), "The read must end at the timeout, not hang.");
+ }
+
+ [Fact]
+ public async Task Shutdown_cancels_a_pending_header_read_and_releases_the_client()
+ {
+ var (proxy, _) = ProxyProtocolServer();
+ using var client = new BlockingStream();
+ var handling = proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback);
+
+ await proxy.DisposeAsync();
+ await handling.WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.True(client.Disposed, "The client stream must be released when shutdown cancels the header read.");
+ Assert.Equal(0, proxy.Stats.ActiveConnections);
+ }
+
+ [Fact]
+ public async Task Disabled_option_treats_header_bytes_as_client_data()
+ {
+ var logs = new ConcurrentQueue();
+ var options = new TgWsProxyOptions { Secret = Secret, PoolSize = 0, CfProxyFallback = false, Verbose = true };
+ await using var proxy = new TgWsProxyServer(options, new FakeTgNetwork(), (_, m) => logs.Enqueue(m));
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ using var client = new RecordingStream([.. Encoding.ASCII.GetBytes(ValidHeader), .. telegram.Init]);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Loopback).WaitAsync(TimeSpan.FromSeconds(5));
+
+ // Nothing is parsed as a header: the first 64 bytes of the stream are the handshake.
+ Assert.DoesNotContain(logs, l => l.Contains("PROXY protocol", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("bad handshake", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Header_from_an_untrusted_peer_is_treated_as_client_data()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ using var client = new RecordingStream([.. Encoding.ASCII.GetBytes(ValidHeader), .. telegram.Init]);
+
+ await proxy.HandleClientAsync(client, "proxy-test", IPAddress.Parse("203.0.113.5")).WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("PROXY protocol header not expected from this peer", StringComparison.Ordinal));
+ Assert.DoesNotContain(logs, l => l.Contains("header accepted", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("bad handshake", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task Header_from_a_peer_without_a_known_address_is_treated_as_client_data()
+ {
+ var (proxy, logs) = ProxyProtocolServer();
+ await using var _ = proxy;
+ using var telegram = new TelegramClient(Secret, MtProto.Intermediate, 2);
+ using var client = new RecordingStream([.. Encoding.ASCII.GetBytes(ValidHeader), .. telegram.Init]);
+
+ await proxy.HandleClientAsync(client, "proxy-test").WaitAsync(TimeSpan.FromSeconds(5));
+
+ Assert.Contains(logs, l => l.Contains("PROXY protocol header not expected from this peer", StringComparison.Ordinal));
+ Assert.Contains(logs, l => l.Contains("bad handshake", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Trusted_sources_match_ipv4_mapped_ipv6_peers()
+ {
+ var trusted = new[] { IPAddress.Loopback, IPAddress.IPv6Loopback };
+
+ Assert.True(ProxyProtocol.IsTrustedSource(IPAddress.Loopback, trusted));
+ Assert.True(ProxyProtocol.IsTrustedSource(IPAddress.IPv6Loopback, trusted));
+ Assert.True(ProxyProtocol.IsTrustedSource(IPAddress.Parse("::ffff:127.0.0.1"), trusted));
+ Assert.False(ProxyProtocol.IsTrustedSource(IPAddress.Parse("203.0.113.5"), trusted));
+ Assert.False(ProxyProtocol.IsTrustedSource(null, trusted));
+ Assert.False(ProxyProtocol.IsTrustedSource(IPAddress.Loopback, []));
+ }
+
+ [Fact]
+ public void Trusted_sources_default_to_loopback_and_reject_garbage()
+ {
+ Assert.Equal(TgWsProxyOptions.DefaultTrustedSources.ToArray(), TgWsProxyOptions.ParseTrustedSources([]).ToArray());
+ Assert.Equal(TgWsProxyOptions.DefaultTrustedSources.ToArray(), TgWsProxyOptions.ParseTrustedSources([" ", ""]).ToArray());
+ Assert.Equal(new[] { IPAddress.Parse("10.0.0.2") }, TgWsProxyOptions.ParseTrustedSources([" 10.0.0.2 "]).ToArray());
+
+ var error = Assert.Throws(() => TgWsProxyOptions.ParseTrustedSources(["not-an-ip"]));
+ Assert.Equal("error.engine.tg.proxyprotocol", error.LocalizationKey);
+ }
+
+ [Fact]
+ public void Options_carry_the_proxy_protocol_settings_and_stay_off_by_default()
+ {
+ var defaults = TgWsProxyOptions.From(new TgWsProxySettings(), "0123456789abcdef0123456789abcdef");
+ Assert.False(defaults.ProxyProtocol);
+ Assert.Equal(TgWsProxyOptions.DefaultTrustedSources.ToArray(), defaults.ProxyProtocolTrustedSources.ToArray());
+
+ var configured = TgWsProxyOptions.From(new TgWsProxySettings
+ {
+ ProxyProtocol = true,
+ ProxyProtocolTrustedSources = ["10.0.0.2"],
+ }, "0123456789abcdef0123456789abcdef");
+ Assert.True(configured.ProxyProtocol);
+ Assert.Equal(new[] { IPAddress.Parse("10.0.0.2") }, configured.ProxyProtocolTrustedSources.ToArray());
+ }
+
+ private static (TgWsProxyServer Proxy, ConcurrentQueue Logs) ProxyProtocolServer()
+ {
+ var logs = new ConcurrentQueue();
+ var options = new TgWsProxyOptions
+ {
+ Secret = Secret,
+ PoolSize = 0,
+ CfProxyFallback = false,
+ Verbose = true,
+ ProxyProtocol = true,
+ };
+ return (new TgWsProxyServer(options, new FakeTgNetwork(), (_, m) => logs.Enqueue(m)), logs);
+ }
+
+ /// Replays a fixed input, optionally one byte per read, and records how much was consumed.
+ private sealed class RecordingStream(byte[] input, int chunk = int.MaxValue) : Stream
+ {
+ private readonly MemoryStream _input = new(input);
+
+ public int BytesRead { get; private set; }
+
+ public bool Disposed { get; private set; }
+
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => true;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ await Task.Yield();
+ cancellationToken.ThrowIfCancellationRequested();
+ var n = _input.Read(buffer.Span[..Math.Min(buffer.Length, chunk)]);
+ BytesRead += n;
+ return n;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) =>
+ ValueTask.CompletedTask;
+
+ public override void Write(byte[] buffer, int offset, int count) { }
+
+ public override void Flush() { }
+
+ public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ Disposed = true;
+ _input.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+
+ /// Never delivers data; only cancellation ends a read.
+ private sealed class BlockingStream : Stream
+ {
+ public bool Disposed { get; private set; }
+
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => true;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
+
+ public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)
+ {
+ await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false);
+ return 0;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) =>
+ ValueTask.CompletedTask;
+
+ public override void Write(byte[] buffer, int offset, int count) { }
+
+ public override void Flush() { }
+
+ public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ Disposed = true;
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+}
diff --git a/tests/Bydlo.Tests/TgWsProxyTests.cs b/tests/Bydlo.Tests/TgWsProxyTests.cs
index 4e393edd..e95a1f53 100644
--- a/tests/Bydlo.Tests/TgWsProxyTests.cs
+++ b/tests/Bydlo.Tests/TgWsProxyTests.cs
@@ -1,6 +1,7 @@
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.IO.Pipelines;
+using System.Net;
using System.Security.Cryptography;
using System.Text;
using Bydlo.Core.Engines;
@@ -744,11 +745,11 @@ public void Fail(Exception error)
_incoming.Writer.TryComplete();
}
- public async Task<(Stream Stream, string Label)> AcceptAsync(CancellationToken ct)
+ public async Task<(Stream Stream, string Label, IPAddress? RemoteAddress)> AcceptAsync(CancellationToken ct)
{
try
{
- return (await _incoming.Reader.ReadAsync(ct), "fake");
+ return (await _incoming.Reader.ReadAsync(ct), "fake", IPAddress.Loopback);
}
catch (System.Threading.Channels.ChannelClosedException) when (_failure is not null)
{
diff --git a/tests/Bydlo.Tests/UpdateRecoveryTests.cs b/tests/Bydlo.Tests/UpdateRecoveryTests.cs
new file mode 100644
index 00000000..af4ebc82
--- /dev/null
+++ b/tests/Bydlo.Tests/UpdateRecoveryTests.cs
@@ -0,0 +1,482 @@
+using Bydlo.Core.Diagnostics;
+using Bydlo.Core.Models;
+
+namespace Bydlo.Tests;
+
+///
+/// Issue #412: the local recovery protocol around the Velopack updater. Every test uses a temporary directory
+/// and fakes; no installer, engine, driver or network request is involved.
+///
+public sealed class UpdateRecoveryTests
+{
+ private const string OldVersion = "0.4.4";
+ private const string NewVersion = "0.4.5";
+ private const string Bundle = "bundle-a";
+
+ private static UpdateRecovery Recovery(string dataDirectory, string currentVersion = OldVersion,
+ AppInstallKind kind = AppInstallKind.Velopack, bool previousPackage = false) =>
+ new(dataDirectory, Path.Combine(dataDirectory, "app"), kind, currentVersion, Bundle,
+ new FakeRollbackProbe(previousPackage));
+
+ private static UpdateReadiness Ready() => new(uiStarted: true, userDataLoaded: true,
+ componentsConsistent: true, helperCompatible: true);
+
+ private static UpdateReadiness NotReady() => new(uiStarted: false, userDataLoaded: true,
+ componentsConsistent: true, helperCompatible: true);
+
+ private static string JournalPath(string dataDirectory) =>
+ Path.Combine(dataDirectory, UpdateRecovery.JournalFileName);
+
+ [Fact]
+ public void Journal_round_trip_is_atomic_and_leaves_no_temporary_file()
+ {
+ var dir = TestDirs.New("recovery-roundtrip");
+ var store = new UpdateRecoveryStore(JournalPath(dir));
+ var journal = new UpdateRecoveryJournal
+ {
+ Phase = UpdateRecoveryPhase.PendingConfirmation,
+ FromVersion = OldVersion,
+ ToVersion = NewVersion,
+ EngineBundleVersion = Bundle,
+ Attempts = 1,
+ SnapshotDirectory = Path.Combine(dir, "snapshot"),
+ };
+
+ Assert.True(store.TrySave(journal));
+ var loaded = store.Load();
+ Assert.NotNull(loaded);
+ Assert.Equal(UpdateRecoveryPhase.PendingConfirmation, loaded.Phase);
+ Assert.Equal(NewVersion, loaded.ToVersion);
+ Assert.Equal(1, loaded.Attempts);
+ Assert.False(File.Exists(store.Path + ".tmp"));
+ }
+
+ [Fact]
+ public async Task Truncated_journal_is_ignored_and_kept_for_diagnostics()
+ {
+ var dir = TestDirs.New("recovery-truncated");
+ // Fault injection: the process died in the middle of the journal write.
+ await File.WriteAllTextAsync(JournalPath(dir), "{\"Version\":1,\"Phase\":\"Appli");
+
+ var recovery = Recovery(dir);
+ Assert.Equal(UpdateRecoveryStartup.Nothing, recovery.PrepareStartup());
+ Assert.Null(recovery.Journal);
+ Assert.Single(Directory.GetFiles(dir, UpdateRecovery.JournalFileName + ".corrupt-*"));
+
+ // The next download replaces the broken file instead of failing forever.
+ Assert.True(recovery.Stage(NewVersion));
+ Assert.Equal(UpdateRecoveryPhase.Staged, new UpdateRecoveryStore(JournalPath(dir)).Load()!.Phase);
+ }
+
+ [Fact]
+ public async Task Leftover_temporary_file_does_not_break_the_journal()
+ {
+ var dir = TestDirs.New("recovery-tmp");
+ await File.WriteAllTextAsync(JournalPath(dir) + ".tmp", "{\"Version\":1,\"Phase\":\"Appl");
+
+ var recovery = Recovery(dir);
+ Assert.Equal(UpdateRecoveryStartup.Nothing, recovery.PrepareStartup());
+ Assert.True(recovery.Stage(NewVersion));
+ Assert.False(File.Exists(JournalPath(dir) + ".tmp"));
+ }
+
+ [Fact]
+ public async Task Journal_from_a_newer_format_is_ignored_instead_of_guessed()
+ {
+ var dir = TestDirs.New("recovery-newer");
+ await File.WriteAllTextAsync(JournalPath(dir),
+ "{\"Version\":99,\"Phase\":\"Applying\",\"ToVersion\":\"0.4.5\"}");
+
+ var recovery = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.Nothing, recovery.PrepareStartup());
+ Assert.Null(recovery.Journal);
+ // The unknown file is left untouched for the version that wrote it.
+ Assert.Contains("\"Version\":99", await File.ReadAllTextAsync(JournalPath(dir)), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Package_is_applied_only_with_a_staged_journal_and_snapshot()
+ {
+ var dir = TestDirs.New("recovery-canapply");
+ var recovery = Recovery(dir);
+
+ Assert.False(recovery.CanApply(NewVersion));
+ Assert.True(recovery.Stage(NewVersion));
+ Assert.True(recovery.CanApply(NewVersion));
+ Assert.True(recovery.CanApply("0.4.5.0"));
+ Assert.False(recovery.CanApply("0.4.6"));
+ Assert.True(recovery.MarkApplying());
+ Assert.False(recovery.CanApply(NewVersion));
+
+ // A deleted snapshot removes the recovery guarantee, so the package must not install.
+ var second = Recovery(dir);
+ Assert.True(second.Stage(NewVersion));
+ Directory.Delete(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName), recursive: true);
+ Assert.False(second.CanApply(NewVersion));
+ }
+
+ [Fact]
+ public async Task New_version_confirms_readiness_and_drops_the_snapshot()
+ {
+ var dir = TestDirs.New("recovery-confirm");
+ await File.WriteAllTextAsync(Path.Combine(dir, "settings.json"), "{}");
+
+ var old = Recovery(dir);
+ Assert.True(old.Stage(NewVersion));
+ Assert.True(old.MarkApplying());
+
+ var next = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, next.PrepareStartup());
+ Assert.True(next.ComponentsConsistent(NewVersion, Bundle));
+ Assert.Equal(UpdateRecoveryConfirmation.Confirmed, next.Confirm(Ready()));
+ Assert.Equal(UpdateRecoveryPhase.Confirmed, next.Journal!.Phase);
+ Assert.Equal(0, next.Journal.Attempts);
+ Assert.False(next.AutoApplyBlocked);
+ Assert.False(Directory.Exists(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName, UpdateRecovery.SnapshotFolderName)));
+
+ // A later start of the confirmed version does nothing.
+ Assert.Equal(UpdateRecoveryStartup.Nothing, Recovery(dir, NewVersion).PrepareStartup());
+ }
+
+ [Fact]
+ public void Failed_confirmation_is_bounded_and_stops_automatic_updates()
+ {
+ var dir = TestDirs.New("recovery-fail");
+ var old = Recovery(dir);
+ Assert.True(old.Stage(NewVersion));
+ Assert.True(old.MarkApplying());
+
+ // First start of the new version: one attempt, the check fails, the next start retries.
+ var first = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, first.PrepareStartup());
+ Assert.Equal(UpdateRecoveryConfirmation.Retry, first.Confirm(NotReady()));
+ Assert.Equal(1, first.Journal!.Attempts);
+ Assert.False(first.AutoApplyBlocked);
+
+ // Second start: the budget is exhausted, the protocol stops and blocks automatic updates.
+ var second = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, second.PrepareStartup());
+ Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady()));
+ Assert.Equal(UpdateRecoveryPhase.RolledBack, second.Journal!.Phase);
+ Assert.Equal(UpdateRecoveryReason.NotReady, second.Journal.Reason);
+ Assert.True(second.AutoApplyBlocked);
+
+ // Third start: no further attempt, no loop, and a late success cannot silently unblock.
+ var third = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.Blocked, third.PrepareStartup());
+ Assert.Equal(UpdateRecoveryConfirmation.Nothing, third.Confirm(Ready()));
+ Assert.Equal(2, third.Journal!.Attempts);
+ Assert.True(third.AutoApplyBlocked);
+ }
+
+ [Fact]
+ public void Interrupted_apply_returns_to_the_previous_version_and_is_bounded()
+ {
+ var dir = TestDirs.New("recovery-interrupted");
+ var old = Recovery(dir);
+ Assert.True(old.Stage(NewVersion));
+ Assert.True(old.MarkApplying());
+
+ // The installer never replaced the files: the previous version starts again.
+ var again = Recovery(dir);
+ Assert.Equal(UpdateRecoveryStartup.Interrupted, again.PrepareStartup());
+ Assert.Equal(UpdateRecoveryPhase.RolledBack, again.Journal!.Phase);
+ Assert.Equal(UpdateRecoveryReason.Interrupted, again.Journal.Reason);
+ Assert.False(again.AutoApplyBlocked);
+
+ // A second interrupted apply exhausts the budget instead of retrying forever.
+ Assert.True(again.Stage(NewVersion));
+ Assert.Equal(1, again.Journal!.Attempts);
+ Assert.True(again.MarkApplying());
+ var twice = Recovery(dir);
+ Assert.Equal(UpdateRecoveryStartup.Blocked, twice.PrepareStartup());
+ Assert.True(twice.AutoApplyBlocked);
+ }
+
+ [Fact]
+ public async Task Snapshot_restores_missing_or_broken_user_data_only()
+ {
+ var dir = TestDirs.New("recovery-snapshot");
+ var settings = Path.Combine(dir, "settings.json");
+ var profiles = Path.Combine(dir, "profiles.json");
+ await File.WriteAllTextAsync(settings, "{\"Language\":\"ru\"}");
+ await File.WriteAllTextAsync(profiles, "{\"Version\":1,\"Profiles\":[]}");
+
+ var old = Recovery(dir);
+ Assert.True(old.Stage(NewVersion));
+ Assert.True(old.MarkApplying());
+
+ // The new version breaks the settings file and loses the profile list.
+ await File.WriteAllTextAsync(settings, "{ broken");
+ File.Delete(profiles);
+
+ var first = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, first.PrepareStartup());
+ Assert.Equal(UpdateRecoveryConfirmation.Retry, first.Confirm(NotReady()));
+ // Nothing is restored while the budget is not exhausted.
+ Assert.Equal("{ broken", await File.ReadAllTextAsync(settings));
+
+ var second = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.AwaitingConfirmation, second.PrepareStartup());
+ Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady()));
+ // The restore happens on the next start, before any user data is read.
+ Assert.Equal("{ broken", await File.ReadAllTextAsync(settings));
+
+ var third = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.Blocked, third.PrepareStartup());
+ Assert.Contains("snapshot-restored", third.Journal!.Notes);
+ Assert.Contains("ru", await File.ReadAllTextAsync(settings));
+ Assert.Contains("Profiles", await File.ReadAllTextAsync(profiles));
+ }
+
+ [Fact]
+ public async Task Readable_user_data_is_never_overwritten_by_the_snapshot()
+ {
+ var dir = TestDirs.New("recovery-snapshot-keep");
+ var settings = Path.Combine(dir, "settings.json");
+ await File.WriteAllTextAsync(settings, "{\"Language\":\"ru\"}");
+
+ var old = Recovery(dir);
+ Assert.True(old.Stage(NewVersion));
+ Assert.True(old.MarkApplying());
+
+ // The user changed a setting in the new version; the file is readable, so it must survive the rollback.
+ await File.WriteAllTextAsync(settings, "{\"Language\":\"en\"}");
+ var first = Recovery(dir, NewVersion);
+ first.PrepareStartup();
+ first.Confirm(NotReady());
+ var second = Recovery(dir, NewVersion);
+ second.PrepareStartup();
+ Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady()));
+ var third = Recovery(dir, NewVersion);
+ Assert.Equal(UpdateRecoveryStartup.Blocked, third.PrepareStartup());
+
+ Assert.Equal("{\"Language\":\"en\"}", await File.ReadAllTextAsync(settings));
+ }
+
+ [Fact]
+ public void Package_manager_install_never_runs_recovery()
+ {
+ var dir = TestDirs.New("recovery-deb");
+ var deb = Recovery(dir, kind: AppInstallKind.Debian);
+ Assert.False(deb.Stage(NewVersion));
+ Assert.Equal(UpdateRecoveryStartup.Ignored, deb.PrepareStartup());
+ Assert.False(Directory.Exists(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName)));
+
+ // A journal left by a Velopack install is not touched by a package-manager copy.
+ var velopack = Recovery(dir);
+ Assert.True(velopack.Stage(NewVersion));
+ Assert.True(velopack.MarkApplying());
+ var debAgain = Recovery(dir, NewVersion, AppInstallKind.Debian);
+ Assert.Equal(UpdateRecoveryStartup.Ignored, debAgain.PrepareStartup());
+ Assert.Null(debAgain.Journal);
+ Assert.Contains("Applying", File.ReadAllText(JournalPath(dir)), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Readiness_requires_ui_user_data_and_matching_components()
+ {
+ Assert.True(Ready().IsReady);
+ Assert.False(new UpdateReadiness(false, true, true, true).IsReady);
+ Assert.False(new UpdateReadiness(true, false, true, true).IsReady);
+ Assert.False(new UpdateReadiness(true, true, false, true).IsReady);
+ Assert.Equal(["ui", "user-data", "components"], new UpdateReadiness(false, false, false, true).Failures);
+
+ // An outdated privileged helper is reported but never blocks the app and is never reinstalled.
+ var helper = new UpdateReadiness(true, true, true, helperCompatible: false);
+ Assert.True(helper.IsReady);
+ Assert.Equal(["helper"], helper.Notes);
+ }
+
+ [Fact]
+ public void Components_must_match_the_staged_package()
+ {
+ var dir = TestDirs.New("recovery-components");
+ var recovery = Recovery(dir);
+ Assert.True(recovery.Stage(NewVersion));
+
+ Assert.True(recovery.ComponentsConsistent(NewVersion, Bundle));
+ Assert.False(recovery.ComponentsConsistent(OldVersion, Bundle));
+ Assert.False(recovery.ComponentsConsistent(NewVersion, "bundle-b"));
+ }
+
+ [Fact]
+ public async Task Updater_stages_the_journal_and_requires_it_before_applying()
+ {
+ var dir = TestDirs.New("recovery-updater");
+ var recovery = Recovery(dir);
+ var backend = new FakeBackend();
+ var updater = new AutomaticAppUpdater(() => backend)
+ {
+ InstallKind = AppInstallKind.Velopack,
+ Recovery = recovery,
+ };
+ var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true };
+
+ Assert.True(await updater.DownloadIfDueAsync(settings, false));
+ Assert.Equal(UpdateRecoveryPhase.Staged, recovery.Journal!.Phase);
+ Assert.Equal(OldVersion, recovery.Journal.FromVersion);
+ Assert.Equal(NewVersion, recovery.Journal.ToVersion);
+ Assert.Equal(AppUpdateApplyResult.Applied, updater.ApplyOnExit(settings, false));
+ Assert.Equal(UpdateRecoveryPhase.Applying, recovery.Journal.Phase);
+ Assert.Equal(1, backend.Applied);
+ }
+
+ [Fact]
+ public async Task Updater_does_not_apply_when_the_snapshot_is_missing()
+ {
+ var dir = TestDirs.New("recovery-updater-nosnapshot");
+ var recovery = Recovery(dir);
+ var backend = new FakeBackend();
+ var updater = new AutomaticAppUpdater(() => backend)
+ {
+ InstallKind = AppInstallKind.Velopack,
+ Recovery = recovery,
+ };
+ var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true };
+
+ Assert.True(await updater.DownloadIfDueAsync(settings, false));
+ Directory.Delete(Path.Combine(dir, UpdateRecovery.SnapshotDirectoryName), recursive: true);
+ Assert.Equal(AppUpdateApplyResult.Deferred, updater.ApplyOnExit(settings, false));
+ Assert.Equal(0, backend.Applied);
+ }
+
+ [Fact]
+ public async Task Package_is_not_applied_when_the_snapshot_cannot_be_written()
+ {
+ var dir = TestDirs.New("recovery-nosnapshot");
+ var data = Path.Combine(dir, "data");
+ // Fault injection: the data directory is a file, so neither the snapshot nor the journal can be written.
+ await File.WriteAllTextAsync(data, "not a directory");
+ var recovery = new UpdateRecovery(data, Path.Combine(dir, "app"), AppInstallKind.Velopack,
+ OldVersion, Bundle, new FakeRollbackProbe(false));
+ var backend = new FakeBackend();
+ var updater = new AutomaticAppUpdater(() => backend)
+ {
+ InstallKind = AppInstallKind.Velopack,
+ Recovery = recovery,
+ };
+ var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true };
+
+ Assert.False(await updater.DownloadIfDueAsync(settings, false));
+ Assert.Equal(AppUpdateState.Deferred, updater.State);
+ Assert.Equal(AppUpdateApplyResult.Deferred, updater.ApplyOnExit(settings, false));
+ Assert.Equal(0, backend.Applied);
+ }
+
+ [Fact]
+ public async Task Blocked_recovery_stops_automatic_updates_until_an_explicit_request()
+ {
+ var dir = TestDirs.New("recovery-blocked");
+ var old = Recovery(dir);
+ Assert.True(old.Stage(NewVersion));
+ Assert.True(old.MarkApplying());
+ var first = Recovery(dir, NewVersion);
+ first.PrepareStartup();
+ first.Confirm(NotReady());
+ var second = Recovery(dir, NewVersion);
+ second.PrepareStartup();
+ Assert.Equal(UpdateRecoveryConfirmation.RolledBack, second.Confirm(NotReady()));
+ Assert.True(second.AutoApplyBlocked);
+
+ var backend = new FakeBackend();
+ var updater = new AutomaticAppUpdater(() => backend)
+ {
+ InstallKind = AppInstallKind.Velopack,
+ Recovery = second,
+ };
+ var settings = new AppSettings { AutoUpdateApp = true, ConsentAutomaticUpdates = true };
+
+ Assert.False(await updater.DownloadIfDueAsync(settings, false));
+ Assert.Equal(0, backend.Downloads);
+ Assert.Equal(AppUpdateApplyResult.Nothing, updater.ApplyOnExit(settings, false));
+ Assert.Equal(0, backend.Applied);
+
+ // Only an explicit user request clears the block.
+ Assert.True(await updater.DownloadNowAsync(settings, false));
+ Assert.False(second.AutoApplyBlocked);
+ Assert.Equal(1, backend.Downloads);
+ }
+
+ [Fact]
+ public void Previous_package_is_reported_only_when_the_probe_finds_one()
+ {
+ var dir = TestDirs.New("recovery-probe");
+ Assert.True(Recovery(dir, NewVersion, previousPackage: true).PreviousPackageAvailable);
+ Assert.False(Recovery(dir, NewVersion, previousPackage: false).PreviousPackageAvailable);
+ // A package-manager copy never offers a rollback path.
+ Assert.False(Recovery(dir, NewVersion, AppInstallKind.Debian, previousPackage: true).PreviousPackageAvailable);
+ }
+
+ [Fact]
+ public async Task File_system_probe_finds_a_kept_package_next_to_the_application()
+ {
+ var root = TestDirs.New("recovery-packages");
+ var application = Path.Combine(root, "current");
+ Directory.CreateDirectory(application);
+ var packages = Path.Combine(root, "packages");
+ Directory.CreateDirectory(packages);
+ await File.WriteAllTextAsync(Path.Combine(packages, "BydloDesktop-0.4.4-full.nupkg"), "package");
+
+ var probe = new FileSystemRollbackProbe();
+ Assert.True(probe.HasPreviousPackage(application, NewVersion));
+ Assert.False(probe.HasPreviousPackage(application, OldVersion));
+ Assert.False(probe.HasPreviousPackage(Path.Combine(root, "missing"), NewVersion));
+ }
+
+ [Fact]
+ public void Recovery_strings_exist_in_both_languages()
+ {
+ var root = RepositoryRoot();
+ var en = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "en.json"));
+ var ru = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "ru.json"));
+ foreach (var key in new[]
+ {
+ "settings.update.recovery.blocked",
+ "settings.update.recovery.previous",
+ "settings.update.recovery.manual",
+ "update.recovery.blocked",
+ "update.recovery.interrupted",
+ })
+ {
+ Assert.Contains($"\"{key}\"", en, StringComparison.Ordinal);
+ Assert.Contains($"\"{key}\"", ru, StringComparison.Ordinal);
+ }
+ }
+
+ private static string RepositoryRoot()
+ {
+ for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
+ {
+ if (File.Exists(Path.Combine(dir.FullName, "BYDLO.slnx")))
+ {
+ return dir.FullName;
+ }
+ }
+ throw new DirectoryNotFoundException("Repository root not found.");
+ }
+
+ private sealed class FakeRollbackProbe(bool hasPreviousPackage) : IUpdateRollbackProbe
+ {
+ public bool HasPreviousPackage(string applicationDirectory, string currentVersion) => hasPreviousPackage;
+ }
+
+ private sealed class FakeBackend : IAppUpdateBackend
+ {
+ public bool IsInstalled { get; set; } = true;
+
+ public string? PendingVersion { get; set; } = NewVersion;
+
+ public int Downloads { get; private set; }
+
+ public int Applied { get; private set; }
+
+ public Task DownloadLatestAsync(IProgress? progress, CancellationToken ct)
+ {
+ Downloads++;
+ return Task.FromResult(true);
+ }
+
+ public void ApplyOnExit() => Applied++;
+ }
+}
diff --git a/tests/Bydlo.Tests/UxSimplificationTests.cs b/tests/Bydlo.Tests/UxSimplificationTests.cs
new file mode 100644
index 00000000..cdcee506
--- /dev/null
+++ b/tests/Bydlo.Tests/UxSimplificationTests.cs
@@ -0,0 +1,167 @@
+using System.Xml.Linq;
+
+namespace Bydlo.Tests;
+
+/// Issue #436: one primary action per screen, secondary actions behind one menu.
+public class UxSimplificationTests
+{
+ private static readonly XNamespace Ns = "https://github.com/avaloniaui";
+ private static readonly XNamespace X = "http://schemas.microsoft.com/winfx/2006/xaml";
+
+ private static readonly string[] ImportSources = ["link", "file", "qr", "clipboard", "subscription", "catalog", "manual"];
+
+ [Fact]
+ public void Home_empty_state_has_one_add_server_entry()
+ {
+ var entry = AddServerEntry();
+ Assert.Equal("primary", (string?)entry.Attribute("Classes"));
+ Assert.Equal("{l:T wizard.title}", (string?)entry.Attribute("AutomationProperties.Name"));
+ Assert.NotNull(entry.Element(Ns + "Button.Flyout"));
+ }
+
+ [Fact]
+ public void Home_import_sources_live_inside_the_add_server_menu()
+ {
+ var menu = AddServerEntry().Element(Ns + "Button.Flyout")!.Element(Ns + "Flyout")!.Element(Ns + "StackPanel")!;
+ var items = menu.Elements(Ns + "Button").ToArray();
+ Assert.Equal(ImportSources, items.Select(item => (string)item.Attribute("CommandParameter")!).ToArray());
+ Assert.All(items, item =>
+ {
+ Assert.Equal("{Binding Shell.OpenImportCommand}", (string?)item.Attribute("Command"));
+ Assert.Equal("menu-item", (string?)item.Attribute("Classes"));
+ });
+ }
+
+ [Fact]
+ public void Home_has_no_directly_visible_import_shortcuts()
+ {
+ var shortcuts = Load("HomeView.axaml").Descendants(Ns + "Button")
+ .Where(button => (string?)button.Attribute("Command") == "{Binding Shell.OpenImportCommand}")
+ .ToArray();
+ Assert.NotEmpty(shortcuts);
+ Assert.All(shortcuts, button => Assert.Contains(button.Ancestors(), ancestor => ancestor.Name == Ns + "Flyout"));
+
+ var view = File.ReadAllText(Path.Combine(Root(), "src", "Bydlo.App", "Views", "HomeView.axaml"));
+ Assert.DoesNotContain("home.import.options", view, StringComparison.Ordinal);
+ Assert.DoesNotContain("empty-actions", view, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Home_keeps_the_primary_connection_action_and_server_picker()
+ {
+ var view = File.ReadAllText(Path.Combine(Root(), "src", "Bydlo.App", "Views", "HomeView.axaml"));
+ Assert.Contains("Classes=\"primary connect-action\"", view, StringComparison.Ordinal);
+ Assert.Contains("Command=\"{Binding ToggleConnectionCommand}\"", view, StringComparison.Ordinal);
+ Assert.Contains("SelectedItem=\"{Binding Shell.SelectedProfile}\"", view, StringComparison.Ordinal);
+ Assert.Contains("Text=\"{Binding StatusText}\"", view, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Server_and_chain_cards_show_three_actions()
+ {
+ var actions = Load("ConnectionsView.axaml").Descendants(Ns + "StackPanel")
+ .Where(panel => (string?)panel.Attribute("Classes") == "profile-actions")
+ .ToArray();
+ Assert.Equal(2, actions.Length);
+ Assert.All(actions, panel => Assert.Equal(3, panel.Elements(Ns + "Button").Count()));
+ }
+
+ [Fact]
+ public void Server_delete_stays_a_separate_confirmed_action()
+ {
+ var buttons = Load("ConnectionsView.axaml").Descendants(Ns + "Button").ToArray();
+ foreach (var (name, command) in new[]
+ {
+ ("{l:T connections.delete}", "DeleteCommand"),
+ ("{l:T chain.delete}", "DeleteChainCommand"),
+ })
+ {
+ var delete = buttons.Single(button => (string?)button.Attribute("AutomationProperties.Name") == name);
+ Assert.Null(delete.Attribute("Command"));
+ var confirm = delete.Element(Ns + "Button.Flyout")!.Element(Ns + "Flyout")!
+ .Descendants(Ns + "Button").Single();
+ Assert.Contains(command, (string)confirm.Attribute("Command")!, StringComparison.Ordinal);
+ }
+ }
+
+ [Fact]
+ public void Favorite_and_edit_actions_moved_into_the_card_menu()
+ {
+ var menuItems = Load("ConnectionsView.axaml").Descendants(Ns + "Button")
+ .Where(button => (string?)button.Attribute("Classes") == "menu-item")
+ .ToArray();
+ Assert.NotEmpty(menuItems);
+ Assert.All(menuItems, item => Assert.Contains(item.Ancestors(), ancestor => ancestor.Name == Ns + "Flyout"));
+ Assert.Contains(menuItems, item => (string?)item.Attribute("Content") == "{l:T chain.edit}");
+ Assert.Contains(menuItems, item => (string?)item.Attribute("AutomationProperties.Name") == "{l:T connections.favorite}");
+ Assert.Contains(menuItems, item => (string?)item.Attribute("Content") == "{l:T profile.edit.title}");
+ }
+
+ [Fact]
+ public void Connections_has_one_add_entry_and_no_duplicate_catalog_button()
+ {
+ var buttons = Load("ConnectionsView.axaml").Descendants(Ns + "Button").ToArray();
+ Assert.DoesNotContain(buttons, button => (string?)button.Attribute("CommandParameter") == "catalog");
+ Assert.Contains(buttons, button => (string?)button.Attribute("Command") == "{Binding Shell.OpenAddServerCommand}");
+ }
+
+ [Fact]
+ public void Import_command_keeps_every_source_parameter()
+ {
+ var vm = File.ReadAllText(Path.Combine(Root(), "src", "Bydlo.App", "ViewModels", "MainViewModel.cs"));
+ foreach (var source in new[] { "catalog", "file", "qr", "manual", "subscription" })
+ {
+ Assert.Contains($"case \"{source}\":", vm, StringComparison.Ordinal);
+ }
+
+ // "link" and "clipboard" stay on the default branch.
+ Assert.Contains("default:", vm, StringComparison.Ordinal);
+ Assert.Contains("source == \"clipboard\"", vm, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Import_menu_labels_exist_in_both_languages()
+ {
+ var keys = new[]
+ {
+ "wizard.title", "wizard.manual", "import.link.title", "home.import.file", "home.import.qr",
+ "home.import.clipboard", "home.import.subscription", "home.import.drop", "catalog.title",
+ "connections.actions", "connections.favorite", "chain.actions",
+ };
+ foreach (var language in new[] { "en", "ru" })
+ {
+ var json = File.ReadAllText(Path.Combine(Root(), "src", "Bydlo.App", "Assets", "Strings", language + ".json"));
+ foreach (var key in keys)
+ {
+ Assert.Contains($"\"{key}\"", json, StringComparison.Ordinal);
+ }
+ }
+ }
+
+ [Fact]
+ public void Inventory_document_lists_the_moved_buttons()
+ {
+ var doc = File.ReadAllText(Path.Combine(Root(), "docs", "UX-SIMPLIFICATION.md"));
+ Assert.Contains("Публичные серверы", doc, StringComparison.Ordinal);
+ Assert.Contains("Другие способы импорта", doc, StringComparison.Ordinal);
+ Assert.Contains("избранное", doc, StringComparison.OrdinalIgnoreCase);
+ Assert.Contains("удаление", doc, StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static XElement AddServerEntry() => Load("HomeView.axaml").Descendants(Ns + "Button")
+ .Single(button => (string?)button.Attribute(X + "Name") == "AddServerEntry");
+
+ private static XDocument Load(string view) => XDocument.Load(Path.Combine(Root(), "src", "Bydlo.App", "Views", view));
+
+ private static string Root()
+ {
+ for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
+ {
+ if (File.Exists(Path.Combine(dir.FullName, "BYDLO.slnx")))
+ {
+ return dir.FullName;
+ }
+ }
+ throw new DirectoryNotFoundException("Repository root not found.");
+ }
+}
diff --git a/tests/Bydlo.Tests/WindowScalingTests.cs b/tests/Bydlo.Tests/WindowScalingTests.cs
index 12b5edb5..f4e5dc7f 100644
--- a/tests/Bydlo.Tests/WindowScalingTests.cs
+++ b/tests/Bydlo.Tests/WindowScalingTests.cs
@@ -8,7 +8,7 @@ public class WindowScalingTests
{
private static double ReadCompactWidth(string root)
{
- var code = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "MainView.axaml.cs"));
+ var code = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Services", "LayoutMetrics.cs"));
var m = Regex.Match(code, @"CompactWidth\s*=\s*(\d+(?:\.\d+)?)");
Assert.True(m.Success);
return double.Parse(m.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
@@ -20,8 +20,9 @@ public void Compact_breakpoint_parsed_from_code_and_used_for_iscompact()
var root = RepositoryRoot();
var width = ReadCompactWidth(root);
Assert.Equal(760, width);
+ // The shell reports its scaled width; the view model compares the effective unscaled width (issue #477).
var code = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "MainView.axaml.cs"));
- Assert.Contains("IsCompact = e.NewSize.Width < CompactWidth", code, StringComparison.Ordinal);
+ Assert.Contains("vm.LayoutWidth = e.NewSize.Width", code, StringComparison.Ordinal);
// Real condition, not literals: just below switches, at and above do not.
Assert.True(759 < width);
Assert.False(760 < width);
diff --git a/tests/Bydlo.Tests/ZapretAndTelegramTests.cs b/tests/Bydlo.Tests/ZapretAndTelegramTests.cs
index 3e251d14..007fc9b6 100644
--- a/tests/Bydlo.Tests/ZapretAndTelegramTests.cs
+++ b/tests/Bydlo.Tests/ZapretAndTelegramTests.cs
@@ -25,6 +25,11 @@ public void Flowseal_strategy_is_parsed_into_winws_arguments(string fixture)
var hostlist = args.First(a => a.StartsWith("--hostlist=", StringComparison.Ordinal));
Assert.True(Path.IsPathRooted(hostlist["--hostlist=".Length..]));
Assert.Contains(Path.Combine(root, "lists", "list-general.txt"), hostlist, StringComparison.Ordinal);
+
+ // Flowseal 1.10.4 (issue #421): every fake payload file resolves inside the installation's bin directory.
+ var fakes = args.Where(a => a.StartsWith("--dpi-desync-fake-", StringComparison.Ordinal) && a.Contains(".bin", StringComparison.Ordinal)).ToList();
+ Assert.NotEmpty(fakes);
+ Assert.All(fakes, a => Assert.StartsWith(Path.Combine(root, "bin") + Path.DirectorySeparatorChar, a[(a.IndexOf('=') + 1)..], StringComparison.Ordinal));
}
[Fact]
diff --git a/tests/Bydlo.Tests/ZapretPlatformTests.cs b/tests/Bydlo.Tests/ZapretPlatformTests.cs
index db0b12fc..b3659559 100644
--- a/tests/Bydlo.Tests/ZapretPlatformTests.cs
+++ b/tests/Bydlo.Tests/ZapretPlatformTests.cs
@@ -40,8 +40,8 @@ public void Bundled_then_managed_then_custom_installation_and_default_strategy()
// This fixture models a Windows x64 package even when the test host is macOS ARM64.
var installer = new EngineInstaller(http, engineLock, Path.Combine(data, "engines"), packagePlatform: platform);
var locator = new EngineLocator(installer, platform, bundle);
- var bundledRoot = CreateFlowseal(Path.Combine(bundle, "engines", "zapret", entry.Version, "zapret-discord-youtube-1.10.3"));
- var managedRoot = CreateFlowseal(Path.Combine(installer.InstallDirectory("zapret", entry.Version), "zapret-discord-youtube-1.10.3"));
+ var bundledRoot = CreateFlowseal(Path.Combine(bundle, "engines", "zapret", entry.Version, "zapret-discord-youtube-1.10.4"));
+ var managedRoot = CreateFlowseal(Path.Combine(installer.InstallDirectory("zapret", entry.Version), "zapret-discord-youtube-1.10.4"));
var customRoot = CreateFlowseal(Path.Combine(root, "custom"));
var engine = new ZapretEngine(new FakeProcessRunner(), new LogRedactor(), locator, new FakePrivileges(true));
var settings = new AppSettings { Zapret = new() { InstallPath = customRoot } };
diff --git a/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs b/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs
index b8a89439..48033d64 100644
--- a/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs
+++ b/tools/Bydlo.Screenshots/AutomaticUpdateVerification.cs
@@ -83,6 +83,8 @@ public static void Run(MainViewModel shell, string output)
///
private static void VerifyManualGuidance(MainViewModel shell, string output)
{
+ // The screenshots show the plain .deb text; a configured apt source is a separate case (issue #488).
+ shell.Services.AptRepositoryConfigured = false;
foreach (var kind in new[]
{
AppInstallKind.Debian, AppInstallKind.Arch, AppInstallKind.Nix, AppInstallKind.Portable, AppInstallKind.Unknown,
diff --git a/tools/Bydlo.Screenshots/DesktopVerification.cs b/tools/Bydlo.Screenshots/DesktopVerification.cs
index 72ca5e51..99450930 100644
--- a/tools/Bydlo.Screenshots/DesktopVerification.cs
+++ b/tools/Bydlo.Screenshots/DesktopVerification.cs
@@ -43,6 +43,37 @@ public static void Run(MainViewModel shell, AppServices services, string output)
Until(() => services.Connections.Primary.Status == ConnectionStatus.Disconnected);
Pump(50);
if (clock.IsEnabled) { throw new InvalidOperationException("Disconnected duration clock did not stop."); }
+ RequireSameMenus();
+ Wait(shell.Tools.ToggleZapretCommand.ExecuteAsync(null));
+ Pump(50);
+ RequireSameMenus();
+ Wait(shell.Tools.ToggleZapretCommand.ExecuteAsync(null));
+ Pump(50);
+ RequireSameMenus();
+ var language = Loc.Instance.Language;
+ Loc.Instance.SetLanguage(language == "ru" ? "en" : "ru");
+ Pump(50);
+ RequireSameMenus();
+ Loc.Instance.SetLanguage(language);
+ var profileCount = shell.Profiles.Count;
+ Wait(shell.Connections.ImportTextAsync("socks5://127.0.0.1:1081#Second-tray-server"));
+ Pump(50);
+ RequireSameMenus();
+ if (servers.Items.Count != profileCount + 1)
+ { throw new InvalidOperationException("Stable tray submenu did not update profiles."); }
+ var select = (NativeMenuItem)servers.Items[^1];
+ select.Command!.Execute(null);
+ Pump(50);
+ if (!select.IsChecked || ((NativeMenuItem)servers.Items[0]).IsChecked)
+ { throw new InvalidOperationException("Tray radio selection did not refresh."); }
+ // Editing a profile replaces its item without renaming it; the tray must select the current item,
+ // not the one captured when the submenu was built, or it connects with pre-edit settings.
+ shell.ReloadProfiles();
+ Pump(50);
+ ((NativeMenuItem)servers.Items[0]).Command!.Execute(null);
+ Pump(50);
+ if (!ReferenceEquals(shell.SelectedProfile, shell.Profiles[0]))
+ { throw new InvalidOperationException("Tray selected a stale profile item after a reload."); }
// Registration must remain blocked in developer sessions without touching the OS.
shell.Settings.StartWithSystem = true;
@@ -74,6 +105,13 @@ public static void Run(MainViewModel shell, AppServices services, string output)
window.Close();
Until(() => !window.IsVisible);
Console.WriteLine("Desktop integration: mock startup connection, tray state/menu, disconnect, settings, registration guard and explicit exit passed.");
+
+ void RequireSameMenus()
+ {
+ if (!ReferenceEquals(menu, tray.Menu) || !ReferenceEquals(servers, ((NativeMenuItem)tray.Menu!.Items[3]).Menu)
+ || !ReferenceEquals(disconnect, tray.Menu.Items[2]))
+ { throw new InvalidOperationException("Tray refresh replaced an exported menu or command item."); }
+ }
}
private static void Until(Func condition)
diff --git a/tools/Bydlo.Screenshots/InterfaceScaleVerification.cs b/tools/Bydlo.Screenshots/InterfaceScaleVerification.cs
new file mode 100644
index 00000000..c9b573e9
--- /dev/null
+++ b/tools/Bydlo.Screenshots/InterfaceScaleVerification.cs
@@ -0,0 +1,126 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Threading;
+using Avalonia.VisualTree;
+using Bydlo.App.Services;
+using Bydlo.App.ViewModels;
+using Bydlo.App.Views;
+
+///
+/// Issue #477: the interface scale is one layout transform at the shell root, so the content keeps
+/// working in unscaled units and the navigation breakpoint does not move with the setting.
+/// Runs in Mock Mode only; no engine, no network.
+///
+internal static class InterfaceScaleVerification
+{
+ public static void Run(MainViewModel shell, string output)
+ {
+ shell.FinishOnboardingCommand.Execute(null);
+ Wait(shell.Connections.ImportTextAsync("trojan://pw@scale.example.invalid:443#Scale"));
+ Require(shell.Profiles.Count >= 1, "A mock profile is listed");
+
+ foreach (var scale in new[] { 80, 100, 150 })
+ {
+ shell.Settings.InterfaceScale = scale;
+ Pump();
+ Require(shell.InterfaceScale == scale, "The setting reaches the shell: " + scale);
+ Require(shell.Services.Settings.InterfaceScale == scale, "The setting is persisted: " + scale);
+
+ var window = Open(shell, 1180, 780);
+ var content = Content(window);
+ var expected = window.ClientSize.Width / (scale / 100.0);
+ Require(Math.Abs(content.Bounds.Width - expected) < 2,
+ $"The layout transform divides the width at {scale}%: {content.Bounds.Width:0.#} vs {expected:0.#}");
+ Require(!shell.IsCompact, "A 1180-wide window keeps the sidebar at " + scale + "%");
+ Require(ConnectAction(window).IsEffectivelyVisible, "The connect action stays visible at " + scale + "%");
+ Shoot(window, Path.Combine(output, $"interface-scale-{scale}.png"));
+ window.Close();
+ }
+
+ // The breakpoint compares the unscaled width: 1140 / 1.5 = 760 keeps the sidebar, 1139 switches.
+ shell.Settings.InterfaceScale = 150;
+ Pump();
+ var wide = Open(shell, 1140, 780);
+ Require(!shell.IsCompact, "1140 at 150% is exactly the breakpoint and keeps the sidebar");
+ wide.Close();
+ var narrow = Open(shell, 1139, 780);
+ Require(shell.IsCompact, "1139 at 150% switches to bottom navigation");
+ Require(BottomNavigation(narrow).IsEffectivelyVisible, "Bottom navigation is visible below the breakpoint");
+ Shoot(narrow, Path.Combine(output, "interface-scale-150-compact.png"));
+ narrow.Close();
+
+ // 80% must not switch earlier than 100%: the same window keeps the sidebar at both scales.
+ shell.Settings.InterfaceScale = 80;
+ Pump();
+ var small = Open(shell, 700, 780);
+ Require(!shell.IsCompact, "700 at 80% leaves 875 unscaled units and keeps the sidebar");
+ small.Close();
+
+ // The appearance page must offer the scale and the reset at the largest scale, keyboard included.
+ shell.Settings.InterfaceScale = 150;
+ shell.Navigate("settings");
+ Pump();
+ var settings = Open(shell, 1180, 780);
+ var picker = settings.GetVisualDescendants().OfType()
+ .Single(combo => ReferenceEquals(combo.ItemsSource, SettingsViewModel.InterfaceScales));
+ Require(picker.IsEffectivelyVisible && picker.Focusable, "The scale picker is visible and focusable");
+ Require(Equals(picker.SelectedItem, 150), "The scale picker shows the saved value");
+ var reset = settings.GetVisualDescendants().OfType()
+ .Single(button => ReferenceEquals(button.Command, shell.Settings.ResetInterfaceScaleCommand));
+ Require(reset.IsEffectivelyVisible && reset.Focusable, "The reset button is visible and focusable");
+ Shoot(settings, Path.Combine(output, "interface-scale-150-settings.png"));
+ settings.Close();
+
+ shell.Settings.ResetInterfaceScaleCommand.Execute(null);
+ Pump();
+ Require(shell.InterfaceScale == 100, "Reset returns the shell to 100%");
+ Require(shell.Services.Settings.InterfaceScale == 100, "Reset persists 100%");
+
+ Console.WriteLine("Interface scale verification passed: layout transform, breakpoint and reset (Mock Mode, no network).");
+ }
+
+ private static Window Open(MainViewModel shell, double width, double height)
+ {
+ var window = new Window { Width = width, Height = height, Content = new MainView { DataContext = shell } };
+ window.Show();
+ Pump();
+ return window;
+ }
+
+ private static Control Content(Window window) =>
+ window.GetVisualDescendants().OfType().Single().Child
+ ?? throw new InvalidOperationException("The shell root has no scaled content.");
+
+ private static Button ConnectAction(Window window) =>
+ window.GetVisualDescendants().OfType().Single(button => button.Classes.Contains("connect-action"));
+
+ private static RadioButton BottomNavigation(Window window) =>
+ window.GetVisualDescendants().OfType().First(button => button.Classes.Contains("navbottom"));
+
+ private static void Shoot(Window window, string path)
+ {
+ using var frame = window.CaptureRenderedFrame() ?? throw new InvalidOperationException("No rendered frame: " + path);
+ frame.Save(path);
+ Console.WriteLine("saved " + Path.GetFileName(path));
+ }
+
+ private static void Pump()
+ {
+ using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(400));
+ Dispatcher.UIThread.MainLoop(timeout.Token);
+ }
+
+ private static void Wait(Task task)
+ {
+ var until = DateTime.UtcNow.AddSeconds(15);
+ while (!task.IsCompleted && DateTime.UtcNow < until) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(10); }
+ Require(task.IsCompleted, "Operation completes");
+ task.GetAwaiter().GetResult();
+ }
+
+ private static void Require(bool condition, string message)
+ {
+ if (!condition) { throw new InvalidOperationException(message); }
+ }
+}
diff --git a/tools/Bydlo.Screenshots/Program.cs b/tools/Bydlo.Screenshots/Program.cs
index 82fb6655..479071cf 100644
--- a/tools/Bydlo.Screenshots/Program.cs
+++ b/tools/Bydlo.Screenshots/Program.cs
@@ -20,13 +20,13 @@
{
Environment.SetEnvironmentVariable("BYDLO_DATA_DIR", Path.Combine(output, "appdata"));
}
-if (args.Contains("--verify-overhaul", StringComparer.Ordinal) || args.Contains("--verify-settings-navigation", StringComparer.Ordinal))
+if (args.Contains("--verify-overhaul", StringComparer.Ordinal) || args.Contains("--verify-settings-navigation", StringComparer.Ordinal) || args.Contains("--verify-zapret-helper", StringComparer.Ordinal))
{
Environment.SetEnvironmentVariable("BYDLO_DATA_DIR", Path.Combine(output, "appdata"));
}
if (args.Contains("--verify-server-groups", StringComparer.Ordinal) || args.Contains("--verify-simple-ui", StringComparer.Ordinal) || args.Contains("--verify-wizard", StringComparer.Ordinal) || args.Contains("--verify-backup", StringComparer.Ordinal) || args.Contains("--verify-import", StringComparer.Ordinal) || args.Contains("--verify-share", StringComparer.Ordinal) ||
args.Contains("--verify-updates", StringComparer.Ordinal) || args.Contains("--verify-speed", StringComparer.Ordinal) || args.Contains("--verify-themes", StringComparer.Ordinal) || args.Contains("--verify-theme-gallery", StringComparer.Ordinal) || args.Contains("--verify-active-connections", StringComparer.Ordinal) || args.Contains("--verify-routing-rules", StringComparer.Ordinal) || args.Contains("--verify-routing-picker", StringComparer.Ordinal) || args.Contains("--verify-connect-switch", StringComparer.Ordinal) ||
- args.Contains("--verify-zapret-selection", StringComparer.Ordinal) || args.Contains("--verify-desktop", StringComparer.Ordinal) || args.Contains("--verify-bundled-engines", StringComparer.Ordinal) || args.Contains("--verify-contributors", StringComparer.Ordinal) || args.Contains("--verify-elevation", StringComparer.Ordinal) ||
+ args.Contains("--verify-zapret-selection", StringComparer.Ordinal) || args.Contains("--verify-desktop", StringComparer.Ordinal) || args.Contains("--verify-bundled-engines", StringComparer.Ordinal) || args.Contains("--verify-contributors", StringComparer.Ordinal) || args.Contains("--verify-elevation", StringComparer.Ordinal) || args.Contains("--verify-interface-scale", StringComparer.Ordinal) ||
Environment.GetEnvironmentVariable("BYDLO_DATA_DIR") is null)
{
Environment.SetEnvironmentVariable("BYDLO_DATA_DIR", Path.Combine(output, "appdata"));
@@ -59,6 +59,12 @@
var services = app.Services!;
Bydlo.App.Services.Loc.Instance.SetLanguage(lang);
+if (args.Contains("--verify-zapret-helper", StringComparer.Ordinal))
+{
+ ZapretHelperVerification.Run(output);
+ return;
+}
+
if (args.Contains("--verify-elevation", StringComparer.Ordinal))
{
ElevationVerification.Run(output);
@@ -153,6 +159,11 @@
ImportVerification.Run(shell, output);
return;
}
+if (args.Contains("--verify-interface-scale", StringComparer.Ordinal))
+{
+ InterfaceScaleVerification.Run(shell, output);
+ return;
+}
// The UI thread is this thread: never block on a task, pump the dispatcher until it completes.
void Wait(Task task)
@@ -406,15 +417,22 @@ static void AssertRows(Window window, int expected)
.Single(button => ReferenceEquals(button.Command, shell.Tools.OpenInTelegramCommand));
if (!telegramToggle.IsEffectivelyVisible || telegramButton.IsEffectivelyVisible)
throw new InvalidOperationException("The Telegram switch must be visible and its open button hidden until the proxy runs.");
- var publicServers = homeWindow.GetVisualDescendants().OfType()
+ // Issue #436: the empty home exposes one "Add server" entry; every import source lives in its menu.
+ var addServer = homeWindow.GetVisualDescendants().OfType().Single(button => button.Name == "AddServerEntry");
+ if (!addServer.IsEffectivelyVisible || !addServer.Focusable || addServer.Flyout is not Flyout addServerMenu)
+ throw new InvalidOperationException("The empty home must expose one focusable Add server entry.");
+ addServerMenu.ShowAt(addServer);
+ Pump(100);
+ var publicServers = ((StackPanel)addServerMenu.Content!).Children.OfType()
.Single(button => Equals(button.CommandParameter, "catalog"));
if (!publicServers.IsEffectivelyVisible || !publicServers.Focusable)
- throw new InvalidOperationException("Public servers must be directly accessible from the empty home.");
+ throw new InvalidOperationException("Public servers must stay reachable from the Add server menu.");
Wait(shell.OpenImportCommand.ExecuteAsync(publicServers.CommandParameter));
if (!shell.IsAddServerOpen || !shell.AddServerWizard.IsCatalog)
throw new InvalidOperationException("Public servers must open the catalog directly.");
Shoot("simple-public-servers-380", 380, 760);
shell.AddServerWizard.CloseCommand.Execute(null);
+ addServerMenu.Hide();
homeWindow.Width = 380;
Pump(100);
var shortcut = homeWindow.GetVisualDescendants().OfType().Single(b => b.Name == "ToolShortcut");
diff --git a/tools/Bydlo.Screenshots/ZapretHelperVerification.cs b/tools/Bydlo.Screenshots/ZapretHelperVerification.cs
new file mode 100644
index 00000000..4607479b
--- /dev/null
+++ b/tools/Bydlo.Screenshots/ZapretHelperVerification.cs
@@ -0,0 +1,77 @@
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Threading;
+using Avalonia.VisualTree;
+using Bydlo.App.Services;
+using Bydlo.App.ViewModels;
+using Bydlo.App.Views;
+using Bydlo.Core.Connection;
+using Bydlo.Core.Models;
+using Bydlo.Core.Platform;
+using Bydlo.Core.Security;
+
+internal static class ZapretHelperVerification
+{
+ public static void Run(string output)
+ {
+ Require(NetworkSafetyGuard.IsLocked, "Safety lock is required");
+ var services = Wait(AppServices.CreateAsync(["--mock"], new UnelevatedPrivileges()));
+ var shell = new MainViewModel(services);
+ shell.FinishOnboardingCommand.Execute(null);
+ shell.Zapret = new SessionSnapshot(ConnectionManager.ZapretKey, ConnectionStatus.Error,
+ null, null, true, null, "Zapret needs administrator / root rights.", null)
+ { ErrorLocalizationKey = "error.engine.zapret.admin" };
+ Require(shell.Tools.ShowZapretHelperSetup, "Missing privilege exposes helper setup");
+ Require(!shell.Tools.ShowRestartElevated, "Linux-style privilege service cannot restart the UI as root");
+ var window = new Window();
+ window.Show();
+ foreach (var language in new[] { "ru", "en" })
+ foreach (var theme in new[] { ThemePreference.Light, ThemePreference.Oled })
+ foreach (var width in new[] { 1000, 400 })
+ {
+ shell.Settings.Language = language;
+ shell.Settings.Theme = theme;
+ window.Content = new ToolsView { DataContext = shell.Tools };
+ window.Width = width;
+ window.Height = 900;
+ using var timeout = new CancellationTokenSource(TimeSpan.FromMilliseconds(150));
+ Dispatcher.UIThread.MainLoop(timeout.Token);
+ var button = window.GetVisualDescendants().OfType().Single(b =>
+ ReferenceEquals(b.Command, shell.Tools.InstallZapretHelperCommand));
+ Require(button.IsEffectivelyVisible && !button.IsEffectivelyEnabled,
+ "Recovery is visible and installation is disabled under the safety lock");
+ Require(button.Content is TextBlock label && label.Text == Loc.Instance["tools.zapret.helper.install"],
+ $"Recovery action is localized: requested={language}, current={Loc.Instance.Language}, actual={(button.Content as TextBlock)?.Text}, expected={Loc.Instance["tools.zapret.helper.install"]}");
+ Wait(shell.Tools.InstallZapretHelperCommand.ExecuteAsync(null));
+ Require(services.Connections.Zapret.Status == ConnectionStatus.Disconnected,
+ "Guarded install never starts an engine");
+ Require(!shell.Settings.HelperBusy, "Guarded install never manages a service");
+ using var frame = window.CaptureRenderedFrame() ?? throw new InvalidOperationException("No frame");
+ frame.Save(Path.Combine(output, $"zapret-helper-{language}-{theme}-{width}.png"));
+ }
+ shell.Zapret = shell.Zapret with { ErrorLocalizationKey = "error.engine.zapret.missing" };
+ Require(!shell.Tools.ShowZapretHelperSetup, "Unrelated errors do not offer privilege installation");
+ window.Close();
+ Wait(services.ShutdownAsync());
+ Console.WriteLine("Zapret helper recovery: localized action, desktop/compact Light/Oled, unrelated error and safety guards passed.");
+ }
+
+ private static T Wait(Task task) { Wait((Task)task); return task.GetAwaiter().GetResult(); }
+ private static void Wait(Task task)
+ {
+ var deadline = DateTime.UtcNow.AddSeconds(15);
+ while (!task.IsCompleted && DateTime.UtcNow < deadline) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(10); }
+ Require(task.IsCompleted, "Operation completes");
+ task.GetAwaiter().GetResult();
+ }
+ private static void Require(bool condition, string message)
+ {
+ if (!condition) { throw new InvalidOperationException(message); }
+ }
+ private sealed class UnelevatedPrivileges : IPrivilegeService
+ {
+ public bool IsElevated => false;
+ public bool CanRestartElevated => false;
+ public bool TryRestartElevated(IReadOnlyList args) => throw new InvalidOperationException("Unexpected elevation");
+ }
+}