diff --git a/CHANGELOG.md b/CHANGELOG.md index e726fda..6c31003 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,28 @@ Все заметные изменения проекта. Формат — [Keep a Changelog](https://keepachangelog.com/ru/1.1.0/), версии — [SemVer](https://semver.org/lang/ru/). +## [2.3.3] — 2026-12-03 + +flowseal-zapret 2.0.0 снова скачивается и работает: приложение понимает новый движок обхода. + +### Добавлено + +- Настройка «YouTube через WebSocket»: три режима на случай, когда YouTube открывается + нестабильно. По умолчанию — обычный. + +### Исправлено + +- Обновление flowseal-zapret 2.0.0 больше не заканчивается ошибкой «Скачанный архив не содержит + корректный runtime». +- Обход запускается и на новом движке, и на прежнем — откат на старую версию остаётся рабочим. +- Проверка и подбор стратегий работают с 2.0.0; неподходящие профили отсекаются до запуска службы, + а не оставляют её упавшей. +- Если сохранённая стратегия исчезла из нового релиза, включается «general», а не остаётся пустота. + +### Удалено + +- Обход Flashscore: отдельные профили для этих сайтов больше не добавляются к стратегиям. + ## [2.3.2] — 2026-11-25 VPN больше не остаётся выключенным после перезагрузки, если системе помешал нужный ему порт. diff --git a/README.md b/README.md index 3833302..a843f2d 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,10 @@ VPN и Telegram настраиваются отдельно и не нужны проверки») по умолчанию выключено — включает пользователь. - **Обновление flowseal-zapret** из GitHub. Ваши списки `*-user.txt` и собственные `.bat` сохраняются, правки в официальных файлах — нет: их заменяет новая версия. +- **Новый движок zapret 2.0.0** поддерживается наравне с прежним; старая версия остаётся рабочим + вариантом отката. +- **YouTube через WebSocket** — настройка для случаев, когда YouTube открывается нестабильно: + DPI режет WebSocket-потоки по размеру окна. По умолчанию включён обычный режим, отключается там же. - Если после применения обход перестал работать, приложение через минуту вернёт прежнюю стратегию. diff --git a/package-lock.json b/package-lock.json index a23b0fb..271109c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "splitline", - "version": "2.3.2", + "version": "2.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "splitline", - "version": "2.3.2", + "version": "2.3.3", "license": "MIT", "dependencies": { "@fontsource-variable/inter": "^5.3.0", @@ -2866,9 +2866,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz", + "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==", "dev": true, "license": "MIT", "dependencies": { @@ -5333,9 +5333,9 @@ } }, "node_modules/ws": { - "version": "8.22.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", - "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz", + "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==", "dev": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index c023072..ec80a67 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "splitline", "private": true, - "version": "2.3.2", + "version": "2.3.3", "description": "Windows 10/11 GUI manager for flowseal-zapret (zapret-discord-youtube by Flowseal)", "author": "Dezuron", "license": "MIT", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 7f62b70..fdd2c47 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5477,7 +5477,7 @@ dependencies = [ [[package]] name = "zapret-ui" -version = "2.3.2" +version = "2.3.3" dependencies = [ "base64 0.22.1", "dirs 5.0.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 79a5d73..fc8f7c2 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "zapret-ui" -version = "2.3.2" +version = "2.3.3" description = "Windows 10/11 GUI manager for flowseal-zapret (zapret-discord-youtube by Flowseal)" authors = ["Dezuron"] license = "MIT" diff --git a/src-tauri/src/bench.rs b/src-tauri/src/bench.rs index b2dc804..593abed 100644 --- a/src-tauri/src/bench.rs +++ b/src-tauri/src/bench.rs @@ -108,27 +108,34 @@ pub struct BenchSummary { } /// Everything the bench needs from the outside world. The production harness -/// spawns `winws.exe` and shells out to `curl`; tests substitute a fake one. +/// spawns the engine (`winws.exe` or `winws2.exe`) and shells out to `curl`; +/// tests substitute a fake one. pub trait Harness { fn start(&self, args: &[String]) -> Result<(), String>; fn stop(&self); fn probe(&self, targets: &[Target], timeout: Duration) -> Vec; } -/// Production harness: runs each candidate as a short-lived `winws.exe` process -/// instead of reinstalling the Windows service for every strategy. +/// Production harness: runs each candidate as a short-lived engine process +/// (`winws.exe` on 1.x, `winws2.exe` on 2.0.0+) instead of reinstalling the +/// Windows service for every strategy. pub struct WinwsHarness { pub exe: String, + /// Engine file name, used in user-facing progress errors. + pub label: String, } impl WinwsHarness { pub fn new(runtime_dir: &std::path::Path) -> Self { + let path = crate::runtime::engine_binary(runtime_dir) + .unwrap_or_else(|| runtime_dir.join("bin").join(crate::runtime::LEGACY_ENGINE)); + let label = path + .file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_else(|| "движок обхода".to_string()); Self { - exe: runtime_dir - .join("bin") - .join("winws.exe") - .to_string_lossy() - .to_string(), + exe: path.to_string_lossy().to_string(), + label, } } } @@ -139,12 +146,12 @@ impl Harness for WinwsHarness { crate::engine::Engine::kill_by_image(); crate::engine::Engine::spawn_transient(&self.exe, args)?; if !crate::engine::Engine::wait_winws_ready(Duration::from_secs(3)) { - return Err("winws.exe не запустился".into()); + return Err(format!("{} не запустился", self.label)); } // Give the driver a moment to attach its filters before probing. std::thread::sleep(Duration::from_millis(500)); if !crate::engine::Engine::is_any_winws_running() { - return Err("winws.exe завершился сразу после запуска".into()); + return Err(format!("{} завершился сразу после запуска", self.label)); } Ok(()) } diff --git a/src-tauri/src/bench_live_tests.rs b/src-tauri/src/bench_live_tests.rs index e98c43c..1c04434 100644 --- a/src-tauri/src/bench_live_tests.rs +++ b/src-tauri/src/bench_live_tests.rs @@ -25,27 +25,27 @@ mod tests { dir: PathBuf, previous: String, game_filter: GameFilter, - flashscore: bool, + youtube_ws: crate::config::YoutubeWsMode, } impl Drop for ServiceRestore { fn drop(&mut self) { engine::Engine::kill_by_image(); std::thread::sleep(Duration::from_millis(300)); - let Some(found) = strategy::discover_strategies(&self.dir, self.game_filter) - .into_iter() - .find(|s| s.name == self.previous || s.file_name == self.previous) + let Some(found) = + strategy::discover_strategies(&self.dir, self.game_filter, self.youtube_ws) + .into_iter() + .find(|s| s.name == self.previous || s.file_name == self.previous) else { eprintln!("restore: стратегия «{}» не найдена", self.previous); return; }; - let args = if self.flashscore { - strategy::with_flashscore_section(&found.args, &self.dir) - } else { - found.args + let args = found.args; + let Some(engine) = crate::runtime::engine_binary(&self.dir) else { + eprintln!("restore: движок обхода не найден"); + return; }; - let winws = self.dir.join("bin").join("winws.exe"); - match engine::Engine::install(&winws.to_string_lossy(), &args, &found.name) { + match engine::Engine::install(&engine.to_string_lossy(), &args, &found.name) { Ok(()) => println!( "restore: служба zapret поднята со стратегией «{}»", found.name @@ -60,7 +60,7 @@ mod tests { fn live_bench() { let dir = config::runtime_dir(); assert!( - dir.join("bin").join("winws.exe").exists(), + crate::runtime::engine_binary(&dir).is_some(), "runtime отсутствует" ); let cfg = config::load_config(); @@ -77,16 +77,17 @@ mod tests { .ok() .and_then(|value| value.parse().ok()) .unwrap_or(2); - let candidates: Vec = strategy::discover_strategies(&dir, cfg.game_filter) - .into_iter() - .take(limit) - .map(|s| Candidate { - name: s.name, - parent: None, - args: s.args, - source: CandidateSource::Official, - }) - .collect(); + let candidates: Vec = + strategy::discover_strategies(&dir, cfg.game_filter, cfg.youtube_ws_mode()) + .into_iter() + .take(limit) + .map(|s| Candidate { + name: s.name, + parent: None, + args: s.args, + source: CandidateSource::Official, + }) + .collect(); assert!(candidates.len() >= 2, "нужно минимум две стратегии"); // Restores the service on success, failure and panic. @@ -94,7 +95,7 @@ mod tests { dir: dir.clone(), previous: cfg.last_strategy.clone(), game_filter: cfg.game_filter, - flashscore: cfg.flashscore_bypass, + youtube_ws: cfg.youtube_ws_mode(), }; let _ = engine::Engine::remove(); diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 5c3150e..faa09fa 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1,6 +1,6 @@ use crate::autostart; use crate::bench::{self, BaselineGate, BenchSummary, Candidate, CandidateSource, Verdict}; -use crate::config::{self, AppConfig, GameFilter}; +use crate::config::{self, AppConfig, GameFilter, YoutubeWsMode}; use crate::engine; use crate::generator::{self, GeneratedStrategy, Seed}; use crate::lock_config; @@ -194,8 +194,12 @@ pub struct ConfigView { pub autostart: bool, pub check_updates: bool, pub check_app_updates: bool, - pub flashscore_bypass: bool, pub game_filter: String, + /// YouTube-over-WebSocket mode: `disabled`, `ws-fake`, `ws-disorder` or + /// `ws-disorder2`. + pub youtube_ws: String, + /// False for the 1.x runtime, which has no Lua engine and no WS profile. + pub youtube_ws_supported: bool, pub runtime_version: String, pub runtime_path: String, pub theme: String, @@ -270,8 +274,9 @@ fn preview_args(args: &[String]) -> String { pub fn get_state(state: State<'_, AppState>) -> AppResult { let cfg = lock_config(&state); let game_filter = game_filter_of(&cfg); + let youtube_ws = cfg.youtube_ws_mode(); let dir = config::runtime_dir(); - let strategies = strategy::discover_strategies(&dir, game_filter); + let strategies = strategy::discover_strategies(&dir, game_filter, youtube_ws); let current = cfg.last_strategy.clone(); drop(cfg); @@ -316,8 +321,9 @@ pub fn get_config(state: State<'_, AppState>) -> AppResult { autostart: cfg.autostart, check_updates: cfg.check_updates, check_app_updates: cfg.check_app_updates, - flashscore_bypass: cfg.flashscore_bypass, game_filter: cfg.game_filter.as_str().to_string(), + youtube_ws: cfg.youtube_ws_mode().as_str().to_string(), + youtube_ws_supported: crate::runtime::is_lua_engine(&config::runtime_dir()), runtime_version: cfg.runtime_version.clone(), runtime_path: config::runtime_dir().to_string_lossy().to_string(), theme: cfg.theme.clone(), diff --git a/src-tauri/src/commands/benchmark.rs b/src-tauri/src/commands/benchmark.rs index fc3aaed..10fd17f 100644 --- a/src-tauri/src/commands/benchmark.rs +++ b/src-tauri/src/commands/benchmark.rs @@ -1,13 +1,14 @@ use super::*; -/// Bench candidates are built from the raw strategy arguments. The Flashscore -/// profiles the app injects at start-up are hostlist-scoped and cannot affect -/// Discord/YouTube, so leaving them out keeps the measured args identical to the -/// parsed `.bat` and avoids injecting them twice into generated candidates. +/// Bench candidates are built from the raw strategy arguments, exactly as the +/// `.bat` files produce them. fn official_candidates(state: &AppState) -> Vec { - let game_filter = lock_config(state).game_filter; + let cfg = lock_config(state); + let game_filter = cfg.game_filter; + let youtube_ws = cfg.youtube_ws_mode(); + drop(cfg); let dir = config::runtime_dir(); - strategy::discover_strategies(&dir, game_filter) + strategy::discover_strategies(&dir, game_filter, youtube_ws) .into_iter() .map(|s| Candidate { name: s.name, @@ -56,9 +57,8 @@ fn execute_candidates( candidates: &[Candidate], ) -> Result { let dir = config::runtime_dir(); - let winws = dir.join("bin").join("winws.exe"); - if !winws.exists() { - return Err("winws.exe не найден в runtime. Сначала обновите runtime.".into()); + if runtime::engine_binary(&dir).is_none() { + return Err("Движок обхода не найден в runtime. Сначала обновите runtime.".into()); } let targets = probe::load_targets(&dir); if targets.is_empty() { diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs index 9d164d1..5365fe3 100644 --- a/src-tauri/src/commands/settings.rs +++ b/src-tauri/src/commands/settings.rs @@ -100,14 +100,28 @@ pub fn set_theme( } #[tauri::command] -pub fn set_flashscore_bypass(state: State<'_, AppState>, enabled: bool) -> AppResult<()> { +pub fn set_youtube_ws(state: State<'_, AppState>, mode: String) -> AppResult<()> { ensure_idle(&state)?; + let Some(mode) = YoutubeWsMode::parse(&mode) else { + return Err("Неизвестный режим YouTube WS.".into()); + }; + let dir = config::runtime_dir(); + if !crate::runtime::is_lua_engine(&dir) { + return Err( + "YouTube WS появился в flowseal-zapret 2.0.0 — сначала обновите runtime.".into(), + ); + } { let mut cfg = lock_config(&state); - cfg.flashscore_bypass = enabled; + cfg.youtube_ws = Some(mode); config::save_config(&cfg).map_err(|e| e.to_string())?; } - // Apply immediately so the toggle takes effect without a manual restart. + // The file drives the runtime's own menu. A failure there must not block the + // setting: the app builds strategies from its config, not from this file. + if let Err(err) = crate::youtube_ws::write_mode(&dir, mode) { + eprintln!("youtube-ws: {err}"); + } + // Apply immediately so the mode takes effect without a manual restart. if current_running(&state) { start_inner(&state, None)?; } @@ -311,11 +325,11 @@ async fn restart_services( pub fn settings_commands() -> CommandSet { command_set![ set_game_filter, + set_youtube_ws, set_autostart, set_check_updates, set_runtime_path, set_theme, - set_flashscore_bypass, export_settings, inspect_backup, import_settings, diff --git a/src-tauri/src/commands/strategies.rs b/src-tauri/src/commands/strategies.rs index 9354925..7e3a52b 100644 --- a/src-tauri/src/commands/strategies.rs +++ b/src-tauri/src/commands/strategies.rs @@ -6,8 +6,9 @@ pub fn set_strategy(state: State<'_, AppState>, name: String) -> AppResult<()> { let previous = lock_config(&state).last_strategy.clone(); let was_running = current_running(&state); let game_filter = lock_config(&state).game_filter; + let youtube_ws = lock_config(&state).youtube_ws_mode(); // Resolve before persisting: a typo must not survive as `last_strategy`. - let (resolved, _args, _) = resolve_strategy(&name, game_filter)?; + let (resolved, _args, _) = resolve_strategy(&name, game_filter, youtube_ws)?; { let mut cfg = lock_config(&state); cfg.last_strategy = resolved.clone(); @@ -39,9 +40,10 @@ pub fn set_strategy(state: State<'_, AppState>, name: String) -> AppResult<()> { fn resolve_strategy( name: &str, game_filter: GameFilter, + youtube_ws: YoutubeWsMode, ) -> Result<(String, Vec, bool), String> { let dir = config::runtime_dir(); - if let Some(found) = strategy::discover_strategies(&dir, game_filter) + if let Some(found) = strategy::discover_strategies(&dir, game_filter, youtube_ws) .into_iter() .find(|s| s.name == name || s.file_name == name) { @@ -61,19 +63,30 @@ pub(crate) fn start_inner(state: &AppState, name: Option<&str>) -> Result<(), St .map(|s| s.to_string()) .unwrap_or_else(|| cfg.last_strategy.clone()); let game_filter = game_filter_of(&cfg); - let flashscore_bypass = cfg.flashscore_bypass; + let youtube_ws = cfg.youtube_ws_mode(); drop(cfg); let dir = config::runtime_dir(); let (resolved_name, strategy_args, is_generated) = - resolve_strategy(&strategy_name, game_filter)?; + resolve_strategy(&strategy_name, game_filter, youtube_ws)?; - let winws = dir.join("bin").join("winws.exe"); - if !winws.exists() { - return Err("winws.exe не найден в runtime. Сначала обновите runtime.".into()); + // 2.0.0 ships `winws2.exe`; 1.x keeps `winws.exe` as the rollback path. + let Some(engine_path) = runtime::engine_binary(&dir) else { + return Err( + "Движок обхода не найден в папке flowseal-zapret. Сначала обновите runtime.".into(), + ); + }; + let engine_exe = engine_path.to_string_lossy().to_string(); + + // Keep the runtime's own menu in sync with the app's choice (best effort: + // the app parses strategies from its config, so a failure is not fatal). + if runtime::is_lua_engine(&dir) { + if let Err(err) = crate::youtube_ws::write_mode(&dir, youtube_ws) { + eprintln!("youtube-ws: {err}"); + } } - // Make sure the user-list files exist (winws exits if a referenced list is missing). + // Make sure the user-list files exist (the engine exits if a referenced list is missing). ensure_user_lists(&dir); // generated.json is user-writable; re-validate it at apply time instead of @@ -84,14 +97,18 @@ pub(crate) fn start_inner(state: &AppState, name: Option<&str>) -> Result<(), St })?; } - let args = if flashscore_bypass { - strategy::with_flashscore_section(&strategy_args, &dir) - } else { - strategy_args - }; + let args = strategy_args; + + // The Lua engine only reports bad arguments at startup, and a rejected + // profile means a service that dies immediately. `--dry-run` catches that + // before the service exists and keeps the error readable. + if runtime::is_lua_engine(&dir) { + engine::Engine::verify_args(&engine_exe, &args) + .map_err(|err| format!("Движок обхода отклонил стратегию «{resolved_name}»: {err}"))?; + } - // Install and start winws as the "zapret" Windows service (like service.bat). - engine::Engine::install(&winws.to_string_lossy(), &args, &resolved_name)?; + // Install and start the engine as the "zapret" Windows service (like service.bat). + engine::Engine::install(&engine_exe, &args, &resolved_name)?; { let mut cfg = lock_config(state); diff --git a/src-tauri/src/commands/updates.rs b/src-tauri/src/commands/updates.rs index 111968f..8cce717 100644 --- a/src-tauri/src/commands/updates.rs +++ b/src-tauri/src/commands/updates.rs @@ -1,6 +1,10 @@ use super::*; use crate::AppResult; +/// Shipped with every release since 1.x; used to restore the bypass when the +/// strategy saved before the update disappeared from the new runtime. +const DEFAULT_STRATEGY: &str = "general"; + #[tauri::command] pub fn set_check_app_updates(state: State<'_, AppState>, enabled: bool) -> AppResult<()> { let mut cfg = lock_config(&state); @@ -67,7 +71,10 @@ pub async fn check_update() -> AppResult { } #[tauri::command] -pub async fn apply_update(state: State<'_, AppState>, app: tauri::AppHandle) -> AppResult<()> { +pub async fn apply_update( + state: State<'_, AppState>, + app: tauri::AppHandle, +) -> AppResult> { ensure_idle(&state)?; let flag = state.update_running.clone(); if flag.swap(true, Ordering::SeqCst) { @@ -89,12 +96,12 @@ pub async fn apply_update(state: State<'_, AppState>, app: tauri::AppHandle) -> .map_err(|e| e.to_string())?; match joined { - Ok(restarted) => { + Ok(outcome) => { // If it was running and not restarted inside, restart it now. - if was_running && !restarted && !old_strategy.is_empty() { + if was_running && !outcome.restarted && !old_strategy.is_empty() { start_inner(&state, Some(&old_strategy))?; } - Ok(()) + Ok(outcome.notice) } Err(err) => { // The update stops the bypass before swapping files. Restore it only @@ -109,12 +116,79 @@ pub async fn apply_update(state: State<'_, AppState>, app: tauri::AppHandle) -> } } -/// Returns true if the strategy was restarted inside the blocking call. +/// What the blocking part of an update did, so the UI can tell the user when the +/// saved strategy had to be replaced. +struct UpdateOutcome { + /// The bypass was already restarted inside the blocking call. + restarted: bool, + /// User-facing note about a strategy that the new release no longer has. + notice: Option, +} + +/// Restarts the bypass after an update. A release can rename or drop strategy +/// files; leaving the machine without a bypass is worse than switching to the +/// default one — but the user has to be told, otherwise the choice would look +/// ignored. +fn restart_after_update( + previous: &str, + mut start: impl FnMut(&str) -> Result<(), String>, +) -> Result<(bool, Option), String> { + match start(previous) { + Ok(()) => Ok((true, None)), + Err(err) => { + if previous == DEFAULT_STRATEGY { + return Err(err); + } + match start(DEFAULT_STRATEGY) { + Ok(()) => Ok(( + true, + Some(format!( + "Не удалось включить «{previous}» после обновления — включена \ + «{DEFAULT_STRATEGY}»." + )), + )), + Err(fallback) => Err(format!( + "{err} (не удалось включить «{DEFAULT_STRATEGY}»: {fallback})" + )), + } + } + } +} + +/// Picks `general` when the strategy saved before the update no longer exists in +/// the new runtime. Generated strategies live in `generated.json` and survive the +/// swap, so they count as present. +fn ensure_saved_strategy(runtime_dir: &std::path::Path, cfg: &mut AppConfig) -> Option { + let saved = cfg.last_strategy.trim().to_string(); + if saved.is_empty() { + return None; + } + let strategies = + strategy::discover_strategies(runtime_dir, cfg.game_filter, cfg.youtube_ws_mode()); + let still_there = strategies + .iter() + .any(|found| found.name == saved || found.file_name == saved) + || generator::find_generated(&saved).is_some(); + if still_there { + return None; + } + if !strategies + .iter() + .any(|found| found.name == DEFAULT_STRATEGY) + { + return None; + } + cfg.last_strategy = DEFAULT_STRATEGY.to_string(); + Some(format!( + "Стратегии «{saved}» больше нет в новой версии — выбрана «{DEFAULT_STRATEGY}»." + )) +} + fn apply_update_blocking( app: &tauri::AppHandle, was_running: bool, old_strategy: &str, -) -> Result { +) -> Result { let release = runtime::fetch_latest_release()?; let Some(asset) = runtime::find_zip_asset(&release) else { return Err("В последнем релизе нет zip-архива с runtime.".into()); @@ -191,8 +265,23 @@ fn apply_update_blocking( if let Some(v) = runtime::installed_version(&runtime_dir) { cfg.runtime_version = v; } + // When the bypass is off it is not restarted, so the saved strategy still has + // to be checked here: the next "Enable" would otherwise fail with "strategy + // not found" after a release that renamed it. + let mut notice = None; + if !(was_running && !old_strategy.is_empty()) { + notice = ensure_saved_strategy(&runtime_dir, &mut cfg); + } config::save_config(&cfg).map_err(|e| e.to_string())?; + // Mirror the app's YouTube WS choice into the new runtime, whose own menu + // reads `utils\youtube_ws.enabled` (the fresh archive has no such file). + if runtime::is_lua_engine(&runtime_dir) { + if let Err(err) = crate::youtube_ws::write_mode(&runtime_dir, cfg.youtube_ws_mode()) { + eprintln!("youtube-ws: {err}"); + } + } + // Sync in-memory state with the new config { let state = app.state::(); @@ -205,10 +294,14 @@ fn apply_update_blocking( // Restart strategy if it was running if was_running && !old_strategy.is_empty() { let state = app.state::(); - start_inner(&state, Some(old_strategy))?; - return Ok(true); + let (restarted, notice) = + restart_after_update(old_strategy, |name| start_inner(&state, Some(name)))?; + return Ok(UpdateOutcome { restarted, notice }); } - Ok(false) + Ok(UpdateOutcome { + restarted: false, + notice, + }) } #[tauri::command] @@ -232,3 +325,96 @@ pub fn updates_commands() -> CommandSet { } // ---------- strategy checks ---------- + +#[cfg(test)] +mod tests { + use super::{ensure_saved_strategy, restart_after_update, DEFAULT_STRATEGY}; + use crate::config::AppConfig; + use std::fs; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn temp_dir(name: &str) -> std::path::PathBuf { + let uniq = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let dir = std::env::temp_dir().join(format!("zapret-ui-update-{name}-{uniq}")); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("bin")).unwrap(); + dir + } + + fn general_bat() -> &'static str { + "@echo off\nstart \"zapret\" /min \"%BIN%winws.exe\" --filter-tcp=443\n" + } + + #[test] + fn a_missing_saved_strategy_is_replaced_when_the_bypass_is_off() { + let dir = temp_dir("saved-missing"); + fs::write(dir.join("general.bat"), general_bat()).unwrap(); + let mut cfg = AppConfig { + last_strategy: "custom".into(), + ..AppConfig::default() + }; + + let notice = ensure_saved_strategy(&dir, &mut cfg).expect("notice"); + assert_eq!(cfg.last_strategy, DEFAULT_STRATEGY); + assert!(notice.contains("custom"), "{notice}"); + assert!(notice.contains(DEFAULT_STRATEGY), "{notice}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_existing_saved_strategy_is_left_alone() { + let dir = temp_dir("saved-present"); + fs::write(dir.join("general.bat"), general_bat()).unwrap(); + let mut cfg = AppConfig { + last_strategy: "general".into(), + ..AppConfig::default() + }; + + assert!(ensure_saved_strategy(&dir, &mut cfg).is_none()); + assert_eq!(cfg.last_strategy, "general"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_working_strategy_is_restarted_silently() { + let (restarted, notice) = restart_after_update("general (ALT2)", |_| Ok(())).unwrap(); + assert!(restarted); + assert!(notice.is_none(), "nothing to tell the user"); + } + + #[test] + fn a_missing_strategy_falls_back_to_general_with_a_notice() { + let mut tried = Vec::new(); + let (restarted, notice) = restart_after_update("general (ALT1)", |name| { + tried.push(name.to_string()); + if name == DEFAULT_STRATEGY { + Ok(()) + } else { + Err("стратегия не найдена".into()) + } + }) + .unwrap(); + + assert!(restarted); + assert_eq!( + tried, + vec!["general (ALT1)".to_string(), DEFAULT_STRATEGY.to_string()] + ); + let notice = notice.expect("the user must be told about the switch"); + assert!(notice.contains("general (ALT1)"), "{notice}"); + assert!(notice.contains(DEFAULT_STRATEGY), "{notice}"); + } + + #[test] + fn a_missing_default_strategy_is_an_error() { + let err = restart_after_update(DEFAULT_STRATEGY, |_| Err("нет такой".into())).unwrap_err(); + assert!(err.contains("нет такой"), "{err}"); + + let err = restart_after_update("custom", |_| Err("нет такой".into())).unwrap_err(); + assert!(err.contains("нет такой"), "{err}"); + assert!(err.contains(DEFAULT_STRATEGY), "{err}"); + } +} diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 5e8f7e8..eae077c 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -47,6 +47,58 @@ impl GameFilter { } } +/// YouTube-over-WebSocket handling of flowseal-zapret 2.0.0. The mode names and +/// their meaning are the runtime's own (`service.bat`, menu item "YouTube WS"); +/// the app mirrors them instead of inventing a second vocabulary. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum YoutubeWsMode { + Disabled, + /// Fake ClientHello plus a disordered split of the ClientHello. + #[serde(rename = "ws-fake")] + Fake, + /// Disordered split; the runtime's default. + #[default] + #[serde(rename = "ws-disorder")] + Disorder, + /// Disordered split at a second set of positions. + #[serde(rename = "ws-disorder2")] + Disorder2, +} + +impl YoutubeWsMode { + pub fn as_str(self) -> &'static str { + match self { + YoutubeWsMode::Disabled => "disabled", + YoutubeWsMode::Fake => "ws-fake", + YoutubeWsMode::Disorder => "ws-disorder", + YoutubeWsMode::Disorder2 => "ws-disorder2", + } + } + + /// Accepts any spelling the runtime file or a hand-edited config may contain. + /// The config field uses it through [`deserialize_youtube_ws`], so one unknown + /// word cannot discard the whole `config.json`. + pub fn parse(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "disabled" | "off" => Some(YoutubeWsMode::Disabled), + "ws-fake" | "fake" => Some(YoutubeWsMode::Fake), + "ws-disorder" | "disorder" | "on" => Some(YoutubeWsMode::Disorder), + "ws-disorder2" | "disorder2" => Some(YoutubeWsMode::Disorder2), + _ => None, + } + } +} + +/// Lenient deserializer for the stored mode: an unknown value becomes `None` +/// (adopt the runtime file) instead of failing the whole config struct. +fn deserialize_youtube_ws<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer)?; + Ok(value.and_then(|text| YoutubeWsMode::parse(&text))) +} + /// Settings of the bundled Telegram MTProto-over-WebSocket proxy /// (headless build of Flowseal/tg-ws-proxy). /// @@ -238,8 +290,12 @@ pub struct AppConfig { /// False until the session flags were seeded from the old autostart settings. pub session_initialized: bool, pub check_updates: bool, - pub flashscore_bypass: bool, pub game_filter: GameFilter, + /// YouTube-over-WebSocket mode. `None` means "not chosen in the app yet": the + /// value saved by the runtime's own menu (`utils\youtube_ws.enabled`) is + /// adopted on load. + #[serde(default, deserialize_with = "deserialize_youtube_ws")] + pub youtube_ws: Option, pub runtime_version: String, /// How many mutants `run_search` generates. pub bench_budget: usize, @@ -266,8 +322,8 @@ impl Default for AppConfig { session_zapret: false, session_initialized: false, check_updates: true, - flashscore_bypass: true, game_filter: GameFilter::Disabled, + youtube_ws: None, runtime_version: String::new(), bench_budget: 40, apply_auto_rollback: true, @@ -282,6 +338,13 @@ impl Default for AppConfig { } } +impl AppConfig { + /// Stored YouTube WS mode, or the upstream default before the user chose one. + pub fn youtube_ws_mode(&self) -> YoutubeWsMode { + self.youtube_ws.unwrap_or_default() + } +} + pub fn app_dir() -> PathBuf { let base = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from(".")); // The override exists for `scripts/shot.ps1` only. Release builds keep the @@ -306,7 +369,13 @@ pub fn config_path() -> PathBuf { } pub fn runtime_dir() -> PathBuf { - resolve_runtime_dir(&app_dir(), &load_config().runtime_path) + runtime_dir_from(&load_config()) +} + +/// Same as [`runtime_dir`] for a config that is already in memory: `load_config` +/// needs it to find the runtime settings, so the two must not call each other. +fn runtime_dir_from(cfg: &AppConfig) -> PathBuf { + resolve_runtime_dir(&app_dir(), &cfg.runtime_path) } /// Folder that holds the headless Telegram proxy binary, its log and its @@ -351,7 +420,7 @@ pub fn prepare_runtime_dir(path: &std::path::Path) -> Result<(), String> { fs::write(&probe, b"").map_err(|e| format!("Папка недоступна для записи: {e}"))?; let _ = fs::remove_file(&probe); - let has_runtime = path.join("bin").join("winws.exe").exists(); + let has_runtime = crate::runtime::engine_binary(path).is_some(); if !has_runtime { let non_empty = fs::read_dir(path) .map_err(|e| e.to_string())? @@ -420,10 +489,16 @@ pub fn theme_is_dark(_theme: &str) -> bool { } pub fn load_config() -> AppConfig { - match fs::read_to_string(config_path()) { + let mut cfg = match fs::read_to_string(config_path()) { Ok(text) => parse_config(&text).unwrap_or_default(), Err(_) => AppConfig::default(), + }; + // A config written before the 2.0.0 runtime has no stored choice. Adopt the + // mode the runtime's own menu saved instead of silently overriding it. + if cfg.youtube_ws.is_none() { + cfg.youtube_ws = Some(crate::youtube_ws::read_mode(&runtime_dir_from(&cfg))); } + cfg } pub fn save_config(cfg: &AppConfig) -> Result<(), String> { @@ -543,6 +618,15 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn prepare_accepts_the_2_0_runtime_layout() { + let dir = temp_dir("runtime-2"); + fs::create_dir_all(dir.join("bin")).unwrap(); + fs::write(dir.join("bin").join(crate::runtime::LUA_ENGINE), b"exe").unwrap(); + assert!(prepare_runtime_dir(&dir).is_ok()); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn prepare_rejects_an_unrelated_non_empty_folder() { let dir = temp_dir("foreign"); @@ -558,6 +642,18 @@ mod tests { assert!(config.check_app_updates); } + #[test] + fn unknown_youtube_ws_value_does_not_reset_the_config() { + let config = parse_config(r#"{"bench_budget": 37, "youtube_ws": "on"}"#).unwrap(); + assert_eq!(config.youtube_ws_mode(), YoutubeWsMode::Disorder); + assert_eq!(config.bench_budget, 37); + + // An unknown word is "not chosen yet", not a broken config. + let config = parse_config(r#"{"bench_budget": 37, "youtube_ws": "bogus"}"#).unwrap(); + assert_eq!(config.youtube_ws, None); + assert_eq!(config.bench_budget, 37); + } + #[test] fn clean_install_has_no_whats_new_marker() { assert!(AppConfig::default().last_run_version.is_empty()); diff --git a/src-tauri/src/engine.rs b/src-tauri/src/engine.rs index 0702bc5..06b58df 100644 --- a/src-tauri/src/engine.rs +++ b/src-tauri/src/engine.rs @@ -20,6 +20,55 @@ fn wide(text: &str) -> Vec { text.encode_utf16().chain(std::iter::once(0)).collect() } +/// The `binPath=` fragment for `sc.exe create`. Two quoting layers are required: +/// arguments are quoted the way `Command::args` quotes them (`--name=Domain Quic` +/// stays one argument), then every quote in that value is escaped so +/// `CommandLineToArgvW` hands `sc.exe` exactly the intended string. Without the +/// second layer `sc` sees `--name=Domain` plus a stray `Quic`, refuses the line, +/// and the service is never created. +fn service_bin_path(exe: &str, args: &[String]) -> String { + let mut command = format!("\"{exe}\""); + for arg in args { + command.push(' '); + command.push_str("e_arg(arg)); + } + format!("\"{}\"", command.replace('"', "\\\"")) +} + +/// Quotes one argument for the service `binPath` the way `CommandLineToArgvW` +/// parses it: arguments with spaces or tabs are wrapped, backslashes before a +/// quote are doubled, and a trailing backslash cannot escape the closing quote. +/// `Command::args` uses the same rules, so a dry-run and the installed service +/// receive identical arguments. +fn quote_arg(arg: &str) -> String { + if !arg.contains([' ', '\t']) { + return arg.to_string(); + } + let mut out = String::with_capacity(arg.len() + 2); + out.push('"'); + let mut backslashes = 0usize; + for ch in arg.chars() { + match ch { + '\\' => { + backslashes += 1; + out.push('\\'); + } + '"' => { + out.push_str(&"\\".repeat(backslashes + 1)); + out.push('"'); + backslashes = 0; + } + _ => { + backslashes = 0; + out.push(ch); + } + } + } + out.push_str(&"\\".repeat(backslashes)); + out.push('"'); + out +} + /// Current state of a service, read through the Service Control Manager. /// `None` means the service does not exist (or cannot be queried). /// @@ -133,6 +182,76 @@ pub(crate) fn image_running(image: &str) -> bool { } } +/// Result of one `--dry-run` attempt. +enum Check { + /// The engine rejected the command line and said why. + Rejected(String), + /// The process ended without printing a verdict (loader/antivirus glitch). + NoVerdict(String), +} + +/// One `winws2 --dry-run` attempt: the engine exits in milliseconds, so a hang is +/// capped instead of blocking the synchronous command that started it. +fn verify_once(exe: &str, args: &[String]) -> Result<(), Check> { + let mut cmd = Command::new(exe); + // `--wf-dup-check=0`: the engine refuses to start when another instance uses the + // same WinDivert filter. That is exactly the case when the app verifies the next + // strategy while the current one is still running, so the check is meaningless + // for a dry run — every official strategy shares the same filter. + cmd.arg("--dry-run") + .arg("--debug=0") + .arg("--wf-dup-check=0") + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + sys::hidden(&mut cmd); + + let mut child = cmd + .spawn() + .map_err(|e| Check::Rejected(format!("Не удалось проверить аргументы движка: {e}")))?; + let deadline = std::time::Instant::now() + Duration::from_secs(10); + loop { + match child.try_wait() { + Ok(Some(_)) => break, + Ok(None) if std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(50)); + } + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(Check::Rejected( + "Движок обхода не ответил за 10 секунд — проверка аргументов прервана." + .to_string(), + )); + } + Err(e) => { + return Err(Check::Rejected(format!( + "Не удалось проверить аргументы движка: {e}" + ))) + } + } + } + + let output = child + .wait_with_output() + .map_err(|e| Check::NoVerdict(format!("не удалось прочитать ответ: {e}")))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + let text = if stderr.trim().is_empty() { + stdout + } else { + stderr + }; + match text.lines().map(str::trim).rfind(|line| !line.is_empty()) { + Some(detail) => Err(Check::Rejected(detail.to_string())), + None => Err(Check::NoVerdict(format!("код выхода {}", output.status))), + } +} + /// Manages the DPI bypass as the Windows service `zapret` — the same principle as /// service.bat "Install Service" / "Remove Services". pub struct Engine; @@ -154,8 +273,9 @@ impl Engine { .unwrap_or(false) } - /// Install winws as the `zapret` Windows service (start=auto) and start it. - /// Mirrors service.bat: cleanup -> sc create -> sc start -> remember strategy. + /// Install the engine (1.x `winws.exe` or 2.0.0 `winws2.exe`) as the `zapret` + /// Windows service (start=auto) and start it. Mirrors service.bat: + /// cleanup -> sc create -> sc start -> remember strategy. pub fn install(exe: &str, args: &[String], strategy: &str) -> Result<(), String> { // `sc.exe`/`netsh.exe` cannot start while the session is ending: the // loader fails with 0xc0000142 and Windows shows an error dialog. @@ -171,9 +291,7 @@ impl Engine { &["interface", "tcp", "set", "global", "timestamps=enabled"], ); - // binPath value must be a single sc argument: outer quotes wrapping the - // inner-quoted exe path and the arguments. - let bin_path = format!("\"\\\"{exe}\\\" {}\"", args.join(" ")); + let bin_path = service_bin_path(exe, args); // `sc delete` is asynchronous: the service is only "marked for deletion" // until its last handle closes, so `sc create` can briefly fail with 1072. @@ -275,14 +393,53 @@ impl Engine { let _ = stop_service_named(SERVICE_NAME); } - /// Kill any winws.exe process by image name (fallback for orphaned processes). + /// Kill any engine process by image name (fallback for orphaned processes). + /// Both names are covered: 1.x runs `winws.exe`, 2.0.0 runs `winws2.exe`, and + /// a stale process of either one holds WinDivert and blocks the next start. /// Runs synchronously: the bench has to be sure the previous candidate is gone /// before the next one starts. pub fn kill_by_image() { - let _ = Self::run("taskkill.exe", &["/IM", "winws.exe", "/F"]); + let _ = Self::run( + "taskkill.exe", + &[ + "/IM", + crate::runtime::LEGACY_ENGINE, + "/IM", + crate::runtime::LUA_ENGINE, + "/F", + ], + ); } - /// Start `winws.exe` as an invisible child process with the given arguments. + /// Dry-runs the engine with the given arguments. Only the Lua engine supports + /// `--dry-run`; it verifies options, profiles and Lua initialisation without + /// touching WinDivert, so a rejected profile is caught before a service is + /// created (a service that dies on start looks like a broken bypass). + /// + /// A rejected command line always comes with a message from the engine. When + /// the process dies without printing anything (the Cygwin loader occasionally + /// fails with `0xC0000142` under load), that is not a verdict on the arguments: + /// the check is retried and then given up, letting the service report its own + /// failure instead of refusing a strategy that may be fine. + pub fn verify_args(exe: &str, args: &[String]) -> Result<(), String> { + let mut last = String::new(); + for attempt in 0..3 { + match verify_once(exe, args) { + Ok(()) => return Ok(()), + Err(Check::Rejected(message)) => return Err(message), + Err(Check::NoVerdict(message)) => { + last = message; + if attempt < 2 { + std::thread::sleep(Duration::from_millis(150)); + } + } + } + } + eprintln!("dry-run: движок не сообщил результат ({last}), аргументы не проверены"); + Ok(()) + } + + /// Start the engine as an invisible child process with the given arguments. /// Used by the bench, which runs candidates without touching the service: /// recreating the service (and the WinDivert driver) for every candidate /// would be slow and fragile. @@ -296,15 +453,19 @@ impl Engine { if let Some(dir) = std::path::Path::new(exe).parent() { cmd.current_dir(dir); } - let child = cmd - .spawn() - .map_err(|e| format!("Не удалось запустить winws.exe: {e}"))?; + let child = cmd.spawn().map_err(|e| { + let name = std::path::Path::new(exe) + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| exe.to_string()); + format!("Не удалось запустить {name}: {e}") + })?; // Dies with the app even if it is terminated during shutdown. crate::job::adopt(&child); Ok(()) } - /// Wait until any winws.exe process appears, or the timeout elapses. + /// Wait until an engine process appears, or the timeout elapses. pub fn wait_winws_ready(timeout: Duration) -> bool { let started = std::time::Instant::now(); while started.elapsed() < timeout { @@ -316,10 +477,10 @@ impl Engine { false } - /// Whether any winws.exe process is running (snapshot fallback: the bench - /// spawns transient processes that are not a service). + /// Whether any engine process is running (snapshot fallback: the bench spawns + /// transient processes that are not a service, and 2.0.0 uses another image). pub fn is_any_winws_running() -> bool { - image_running("winws.exe") + image_running(crate::runtime::LEGACY_ENGINE) || image_running(crate::runtime::LUA_ENGINE) } } @@ -327,6 +488,34 @@ impl Engine { mod tests { use super::*; + /// Parses a command line the way Windows hands it to a process, so the quoting + /// of `service_bin_path` is checked by the real parser, not by an assertion + /// that repeats its own rules. + fn parse_command_line(command: &str) -> Vec { + use windows_sys::Win32::Foundation::LocalFree; + use windows_sys::Win32::UI::Shell::CommandLineToArgvW; + + let wide: Vec = command.encode_utf16().chain(std::iter::once(0)).collect(); + let mut count = 0i32; + unsafe { + let argv = CommandLineToArgvW(wide.as_ptr(), &mut count); + assert!(!argv.is_null(), "CommandLineToArgvW failed"); + let mut out = Vec::with_capacity(count.max(0) as usize); + for index in 0..count { + let ptr = *argv.add(index as usize); + let mut len = 0usize; + while *ptr.add(len) != 0 { + len += 1; + } + out.push(String::from_utf16_lossy(std::slice::from_raw_parts( + ptr, len, + ))); + } + LocalFree(argv as *mut core::ffi::c_void); + out + } + } + #[test] fn service_state_comes_from_the_scm() { // `EventLog` ships with Windows and is always running. @@ -352,4 +541,67 @@ mod tests { // disable the user's bypass. assert!(stop_service_named("zapret-ui-nonexistent-service").is_ok()); } + + #[test] + fn service_command_line_survives_both_quoting_layers() { + let exe = r"C:\rt with space\bin\winws2.exe"; + let args = vec![ + "--filter-tcp=443".to_string(), + "--name=Domain Quic".to_string(), + r"--hostlist=C:\rt with space\lists\list-general.txt".to_string(), + ]; + let fragment = service_bin_path(exe, &args); + + // `sc.exe` receives `binPath= `; emulate that exact command line + // (a leading program name matters: Windows parses argv[0] differently). + let argv = parse_command_line(&format!("sc.exe binPath= {fragment}")); + assert_eq!(argv.len(), 3, "sc must see one binPath value: {argv:?}"); + assert_eq!(argv[1], "binPath="); + + // The service then splits that value into the exe and the original args. + assert_eq!( + parse_command_line(&argv[2]), + vec![ + exe.to_string(), + "--filter-tcp=443".to_string(), + "--name=Domain Quic".to_string(), + r"--hostlist=C:\rt with space\lists\list-general.txt".to_string(), + ] + ); + + // And `sc.exe` itself must accept the line. 1060 is "service does not + // exist": the parameters were parsed, nothing was created. Broken quoting + // returns 1639 (invalid parameters) instead. + let status = Command::new("sc.exe") + .arg("config") + .arg("zapret-ui-nonexistent-service") + .arg("binPath=") + .raw_arg(&fragment) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .expect("run sc.exe"); + assert_eq!( + status.code(), + Some(1060), + "sc.exe rejected the binPath quoting: {status}" + ); + } + + #[test] + fn arguments_with_spaces_are_quoted_for_the_service() { + // 2.0.0 profiles are named `--name=Domain Quic`: unquoted, the engine would + // see two arguments and name the profile `Domain`. + assert_eq!(quote_arg("--filter-tcp=443"), "--filter-tcp=443"); + assert_eq!(quote_arg("--name=Domain Quic"), r#""--name=Domain Quic""#); + assert_eq!( + quote_arg(r"C:\rt with space\lua\blobs.lua"), + r#""C:\rt with space\lua\blobs.lua""# + ); + // A trailing backslash must not escape the closing quote. + assert_eq!(quote_arg(r"dir with space\"), r#""dir with space\\""#); + // Quotes inside an argument are escaped, not closed. + assert_eq!(quote_arg(r#"say "hi" now"#), r#""say \"hi\" now""#); + } } diff --git a/src-tauri/src/generator.rs b/src-tauri/src/generator.rs index 59f2124..c87075f 100644 --- a/src-tauri/src/generator.rs +++ b/src-tauri/src/generator.rs @@ -67,6 +67,7 @@ enum MutKind { Ttl, Desync, FakeFile, + LuaDesync, } fn mutable_kind(key: &str) -> Option { @@ -82,6 +83,8 @@ fn mutable_kind(key: &str) -> Option { | "--dpi-desync-fake-http" | "--dpi-desync-fake-syndata" | "--dpi-desync-split-seqovl-pattern" => Some(MutKind::FakeFile), + // 2.0.0 has no `--dpi-desync*`: a whole Lua call is one token. + "--lua-desync" => Some(MutKind::LuaDesync), _ => None, } } @@ -139,6 +142,7 @@ pub fn generate( } let mut rng = Rng::new(rng_seed); + let blobs = lua_blob_names(runtime_dir); let desync_values: Vec = { let mut set = HashSet::new(); for seed in seeds { @@ -163,7 +167,7 @@ pub fn generate( attempts += 1; let seed = &seeds[rng.below(seeds.len())]; let mut args = seed.args.clone(); - let descriptions = mutate(&mut args, &mut rng, &desync_values, runtime_dir); + let descriptions = mutate(&mut args, &mut rng, &desync_values, &blobs, runtime_dir); if descriptions.is_empty() { continue; } @@ -201,6 +205,7 @@ fn mutate( args: &mut [String], rng: &mut Rng, desync_values: &[String], + blobs: &[String], runtime_dir: &Path, ) -> Vec { let mutable: Vec = args @@ -262,6 +267,14 @@ fn mutate( None } } + MutKind::LuaDesync => { + let Some((new_value, description)) = mutate_lua_desync(&old, rng, blobs) else { + continue; + }; + args[index] = format!("{key}={new_value}"); + descriptions.push(description); + continue; + } }; let Some(new_value) = new_value else { continue; @@ -302,6 +315,80 @@ fn fake_files(runtime_dir: &Path, prefix: &str) -> Vec { files } +fn lua_blob_names(runtime_dir: &Path) -> Vec { + // blobs.lua is a plain table of `NAME = "file.bin",` lines. Reading the names + // from there keeps mutations inside the blobs the runtime actually ships. + let text = + std::fs::read_to_string(runtime_dir.join("lua").join("blobs.lua")).unwrap_or_default(); + let mut names: Vec = text + .lines() + .map(str::trim) + .filter(|line| !line.starts_with("--")) + .filter_map(|line| { + let (name, value) = line.split_once('=')?; + let name = name.trim(); + let known = !name.is_empty() + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + && value.trim().ends_with(".bin\","); + known.then(|| name.to_string()) + }) + .collect(); + names.sort(); + names.dedup(); + names +} + +/// Mutates one `--lua-desync` call: the function stays, one of its parameters gets +/// a new value from the pools. Unknown functions and parameters are left alone, so +/// a candidate never turns a valid call into a different action. +fn mutate_lua_desync(value: &str, rng: &mut Rng, blobs: &[String]) -> Option<(String, String)> { + let mut parts: Vec = value.split(':').map(str::to_string).collect(); + if parts.len() < 2 { + return None; + } + let params: Vec = (1..parts.len()) + .filter(|index| parts[*index].contains('=')) + .collect(); + if params.is_empty() { + return None; + } + + // A parameter may already hold the pool value; retry instead of giving up. + for _ in 0..4 { + let index = params[rng.below(params.len())]; + let Some((key, old)) = parts[index].split_once('=') else { + continue; + }; + let key = key.to_string(); + let old = old.to_string(); + let new = match key.as_str() { + "pos" => pick_other(rng, SPLIT_POS_VALUES, &old), + "seqovl" => pick_other(rng, SEQOVL_VALUES, &old), + "repeats" => pick_other(rng, REPEATS_VALUES, &old), + "blob" | "seqovl_pattern" => pick_other(rng, blobs, &old), + _ => None, + }; + let Some(new) = new else { + continue; + }; + parts[index] = format!("{key}={new}"); + return Some((parts.join(":"), format!("lua-desync {key}: {old} → {new}"))); + } + None +} + +fn pick_other<'a, T: AsRef>(rng: &mut Rng, pool: &'a [T], current: &str) -> Option<&'a str> { + let choices: Vec<&T> = pool + .iter() + .filter(|value| value.as_ref() != current) + .collect(); + if choices.is_empty() { + None + } else { + Some(choices[rng.below(choices.len())].as_ref()) + } +} + pub fn validate_args(args: &[String]) -> Result<(), String> { if args.is_empty() { return Err("Пустые аргументы стратегии.".into()); @@ -325,6 +412,16 @@ pub fn validate_args(args: &[String]) -> Result<(), String> { let Some((key, value)) = arg.split_once('=') else { continue; }; + // `--lua-init=@file` loads a script; `--lua-init=` is inline Lua and + // has nothing to check on disk. + if key == "--lua-init" { + if let Some(path) = value.strip_prefix('@') { + if !path.is_empty() && !Path::new(path).exists() { + return Err(format!("Файл Lua не найден: {path}")); + } + } + continue; + } if PATH_KEYS.contains(&key) && !value.is_empty() && !Path::new(value).exists() { return Err(format!("Файл не найден: {value}")); } @@ -588,6 +685,95 @@ mod tests { assert!(validate_args(&args).is_err()); } + fn lua_seed(runtime: &Path) -> Seed { + let lists = runtime.join("lists"); + Seed { + name: "general".into(), + args: vec![ + "--wf-tcp-out=80,443".to_string(), + "--wf-udp-out=443".to_string(), + format!( + "--lua-init=@{}", + runtime.join("lua").join("blobs.lua").to_string_lossy() + ), + "--template=i".to_string(), + "--new".to_string(), + "--filter-tcp=443".to_string(), + format!( + "--hostlist={}", + lists.join("list-general.txt").to_string_lossy() + ), + "--payload=tls_client_hello".to_string(), + "--lua-desync=multisplit:pos=1:seqovl=568:seqovl_pattern=tls_4pda".to_string(), + "--new".to_string(), + "--filter-udp=443".to_string(), + "--lua-desync=fake:blob=quic_google:repeats=6".to_string(), + ], + } + } + + #[test] + fn mutates_lua_desync_for_the_new_engine() { + let runtime = fixture_runtime("lua"); + fs::create_dir_all(runtime.join("lua")).unwrap(); + fs::write( + runtime.join("lua").join("blobs.lua"), + "local blobs = {\n\ + \ttls_4pda = \"tls_clienthello_4pda_to.bin\",\n\ + \ttls_google = \"tls_clienthello_www_google_com.bin\",\n\ + \tquic_google = \"quic_initial_www_google_com.bin\",\n\ + }\n", + ) + .unwrap(); + + let generated = generate(&[lua_seed(&runtime)], 10, &runtime, 11, &HashSet::new()); + assert_eq!(generated.len(), 10, "should reach the budget"); + + for candidate in &generated { + assert!( + validate_args(&candidate.args).is_ok(), + "invalid candidate: {:?}", + validate_args(&candidate.args) + ); + assert!( + !candidate.args.iter().any(|a| a.starts_with("--dpi-desync")), + "legacy options must not appear: {:?}", + candidate.args + ); + assert!( + candidate.mutation.contains("lua-desync"), + "mutation must name the Lua call: {}", + candidate.mutation + ); + assert_eq!(candidate.args[0], "--wf-tcp-out=80,443"); + assert_eq!( + candidate + .args + .iter() + .filter(|a| a.starts_with("--filter-")) + .count(), + 2, + "both profiles must remain" + ); + } + + let _ = fs::remove_dir_all(&runtime); + } + + #[test] + fn validate_rejects_missing_lua_init() { + let runtime = fixture_runtime("lua-missing"); + let args = vec![ + "--filter-tcp=443".to_string(), + format!( + "--lua-init=@{}", + runtime.join("lua").join("nope.lua").to_string_lossy() + ), + ]; + assert!(validate_args(&args).is_err()); + let _ = fs::remove_dir_all(&runtime); + } + #[test] fn merge_keeps_existing_and_dedupes_by_args() { let dir = std::env::temp_dir().join(format!( diff --git a/src-tauri/src/job.rs b/src-tauri/src/job.rs index d947329..d535a92 100644 --- a/src-tauri/src/job.rs +++ b/src-tauri/src/job.rs @@ -1,7 +1,8 @@ //! Kernel-level ownership of the child processes the app spawns. //! -//! The Telegram proxy and the short-lived `winws.exe` instances of a strategy -//! search must never outlive the app, but the cleanup itself must not depend on +//! The Telegram proxy and the short-lived engine processes (`winws.exe` or +//! `winws2.exe`) of a strategy search must never outlive the app, but the +//! cleanup itself must not depend on //! external tools. During Windows shutdown a freshly created process can no //! longer initialize its DLLs and dies with `0xc0000142` — that is the //! "taskkill.exe — Ошибка приложения" dialog a user sees on logoff. A job diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bb68598..b9dd031 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -22,6 +22,7 @@ mod tray; mod updater; mod whats_new; mod xray; +mod youtube_ws; #[cfg(test)] mod bench_live_tests; diff --git a/src-tauri/src/runtime.rs b/src-tauri/src/runtime.rs index f6abe7d..344b5fa 100644 --- a/src-tauri/src/runtime.rs +++ b/src-tauri/src/runtime.rs @@ -8,6 +8,29 @@ use std::time::Duration; pub const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/Flowseal/zapret-discord-youtube/releases/latest"; +/// 2.0.0 replaced the C engine with the Lua-based one and renamed the binary. +/// Both names are supported: 1.x runtimes stay usable as a rollback path. +pub const LUA_ENGINE: &str = "winws2.exe"; +pub const LEGACY_ENGINE: &str = "winws.exe"; + +/// The bypass engine shipped by the runtime. `winws2.exe` wins when both are +/// present: it is the engine the current `.bat` files are written for. +pub fn engine_binary(runtime_dir: &Path) -> Option { + for name in [LUA_ENGINE, LEGACY_ENGINE] { + let path = runtime_dir.join("bin").join(name); + if path.exists() { + return Some(path); + } + } + None +} + +/// True for the 2.0.0+ runtime, whose strategies speak `--lua-desync` and reject +/// the old `--dpi-desync*` options. +pub fn is_lua_engine(runtime_dir: &Path) -> bool { + runtime_dir.join("bin").join(LUA_ENGINE).exists() +} + /// Hard ceiling for a runtime archive: a release is ~10 MB, so anything close to /// this is either a mistake or a zip bomb. const MAX_ARCHIVE_BYTES: u64 = 256 * 1024 * 1024; @@ -213,9 +236,9 @@ pub fn extract_zip(zip_path: &Path, dest: &Path) -> Result<(), String> { Ok(()) } -/// Check if a runtime looks valid (bin/winws.exe exists). +/// Check if a runtime looks valid (one of the supported engine binaries exists). pub fn is_runtime_valid(runtime_dir: &Path) -> bool { - runtime_dir.join("bin").join("winws.exe").exists() + engine_binary(runtime_dir).is_some() } pub fn runtime_tmp_dir() -> PathBuf { @@ -278,6 +301,33 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn runtime_is_valid_for_both_engines() { + let legacy = temp_dir("engine-legacy"); + fs::create_dir_all(legacy.join("bin")).unwrap(); + fs::write(legacy.join("bin").join(LEGACY_ENGINE), b"exe").unwrap(); + assert!(is_runtime_valid(&legacy)); + assert!(!is_lua_engine(&legacy)); + + let lua = temp_dir("engine-lua"); + fs::create_dir_all(lua.join("bin")).unwrap(); + fs::write(lua.join("bin").join(LUA_ENGINE), b"exe").unwrap(); + assert!(is_runtime_valid(&lua)); + assert!(is_lua_engine(&lua)); + assert_eq!( + engine_binary(&lua).and_then(|p| p.file_name()?.to_str().map(str::to_string)), + Some(LUA_ENGINE.to_string()) + ); + + let empty = temp_dir("engine-none"); + assert!(!is_runtime_valid(&empty)); + assert!(engine_binary(&empty).is_none()); + + for dir in [&legacy, &lua, &empty] { + let _ = fs::remove_dir_all(dir); + } + } + #[test] fn find_zip_asset_picks_zip() { let release = ReleaseInfo { diff --git a/src-tauri/src/strategy.rs b/src-tauri/src/strategy.rs index aba2315..6537007 100644 --- a/src-tauri/src/strategy.rs +++ b/src-tauri/src/strategy.rs @@ -1,4 +1,4 @@ -use crate::config::GameFilter; +use crate::config::{GameFilter, YoutubeWsMode}; use std::fs; use std::path::{Path, PathBuf}; @@ -10,7 +10,11 @@ pub struct Strategy { pub args: Vec, } -pub fn discover_strategies(runtime_dir: &Path, game_filter: GameFilter) -> Vec { +pub fn discover_strategies( + runtime_dir: &Path, + game_filter: GameFilter, + youtube_ws: YoutubeWsMode, +) -> Vec { let mut out: Vec = Vec::new(); let Ok(entries) = fs::read_dir(runtime_dir) else { return out; @@ -23,7 +27,7 @@ pub fn discover_strategies(runtime_dir: &Path, game_filter: GameFilter) -> Vec Vec Vec { - let lists = runtime_dir.join("lists"); - let bin = runtime_dir.join("bin"); - let excludes: Vec = ["list-exclude.txt", "list-exclude-user.txt"] - .iter() - .map(|name| format!("--hostlist-exclude={}", lists.join(name).to_string_lossy())) - .collect(); - - let reorder_profile = [ - "--dpi-desync=multidisorder".to_string(), - "--dpi-desync-split-pos=1,midsld".to_string(), - "--dpi-desync-fooling=ts".to_string(), - "--dpi-desync-repeats=4".to_string(), - ]; - let pattern = bin.join(FAKE_TLS_CLIENTHELLO); - let pattern_path = pattern.to_string_lossy().to_string(); - let fake_split_profile = if pattern.exists() { - vec![ - "--dpi-desync=fake,multisplit".to_string(), - "--dpi-desync-split-pos=1".to_string(), - "--dpi-desync-split-seqovl=664".to_string(), - "--dpi-desync-fooling=ts".to_string(), - "--dpi-desync-repeats=8".to_string(), - format!("--dpi-desync-split-seqovl-pattern={pattern_path}"), - format!("--dpi-desync-fake-tls={pattern_path}"), - ] - } else { - // winws exits when a referenced desync file is missing, which would take the - // whole bypass down. Fall back to the file-free reorder profile instead. - reorder_profile.to_vec() - }; - - let mut section = vec![ - "--filter-tcp=80,443".to_string(), - format!("--hostlist-domains={FLASHSCORE_REORDER_DOMAINS}"), - ]; - section.extend(excludes.iter().cloned()); - section.extend(reorder_profile); - section.push("--new".to_string()); - section.push("--filter-tcp=80,443".to_string()); - section.push(format!( - "--hostlist-domains={FLASHSCORE_FAKE_SPLIT_DOMAINS}" - )); - section.extend(excludes); - section.extend(fake_split_profile); - - match args.iter().position(|a| a.starts_with("--filter-")) { - Some(idx) => { - let mut out = Vec::with_capacity(args.len() + section.len() + 1); - out.extend_from_slice(&args[..idx]); - out.append(&mut section); - out.push("--new".to_string()); - out.extend_from_slice(&args[idx..]); - out - } - None => { - let mut out = args.to_vec(); - if !out.is_empty() { - out.push("--new".to_string()); - } - out.append(&mut section); - out - } - } -} - pub fn parse_strategy_args( bat_path: &Path, runtime_dir: &Path, game_filter: GameFilter, + youtube_ws: YoutubeWsMode, ) -> Option> { let content = fs::read_to_string(bat_path).ok()?; - let joined = join_continuations(&content); + let body = engine_body(&content)?; + let rest = body.trim_start_matches('"').trim_start().to_string(); - let start = joined.find("winws.exe")?; - let mut rest = joined[start + "winws.exe".len()..].to_string(); - // strip the closing quote of the path and following whitespace - rest = rest.trim_start_matches('"').trim_start().to_string(); - - // Match bat semantics: BIN/LISTS/%~dp0 end with a trailing backslash. + // Match bat semantics: BIN/LISTS/LUA/%~dp0 end with a trailing backslash. let bin = format!("{}\\", runtime_dir.join("bin").to_string_lossy()); let lists = format!("{}\\", runtime_dir.join("lists").to_string_lossy()); + let lua = format!("{}\\", runtime_dir.join("lua").to_string_lossy()); let root = format!("{}\\", runtime_dir.to_string_lossy()); + let ws = crate::youtube_ws::args(runtime_dir, youtube_ws); let mut expanded = rest .replace("%BIN%", &bin) .replace("%LISTS%", &lists) + .replace("%LUA%", &lua) + .replace("%YoutubeWSOptions%", &ws.options) + .replace("%YoutubeWSProfile%", &ws.profile) .replace("%GameFilterTCP%", game_filter.tcp_value()) .replace("%GameFilterUDP%", game_filter.udp_value()) .replace("%~dp0", &root) .replace("^!", "!") .replace("^^", "^"); - // cmd line continuations: a trailing '^' followed by nothing continues next line. - // handled in join_continuations already; remaining '^' escapes are resolved above. - expanded = expanded.trim().to_string(); Some(tokenize(&expanded)) } -/// Join lines where a line ends with `^` (cmd line continuation). -fn join_continuations(content: &str) -> String { - let mut out = String::new(); - for line in content.lines() { - let trimmed_end = line.trim_end(); - let text = trimmed_end.strip_suffix('^').unwrap_or(line); - out.push_str(text); - out.push(' '); +/// The engine command line of a `.bat`: everything after the executable name on +/// the `start` line, including the `^` continuations that follow it. +/// +/// Scanning for the `start` line instead of the first `winws*.exe` mention keeps a +/// commented-out or documented engine name (`:: winws2.exe ...`) from shifting the +/// arguments. +fn engine_body(content: &str) -> Option { + let mut lines = content.lines(); + while let Some(line) = lines.next() { + let trimmed = line.trim_start().trim_start_matches('@'); + let is_start = trimmed + .get(..5) + .map(|prefix| prefix.eq_ignore_ascii_case("start")) + .unwrap_or(false); + if !is_start { + continue; + } + let Some(end) = engine_end(line) else { + continue; + }; + + // `service.bat` parses the launch line with `for /f`, which skips blank + // lines, and an official 2.0.0 `.bat` has one right after `start ... ^`. + // A blank line therefore must not end the command: only a line without a + // trailing caret does. + let mut body = String::new(); + let mut piece = line[end..].to_string(); + loop { + let trimmed_end = piece.trim_end(); + let continued = trimmed_end.ends_with('^'); + // Exactly one caret is the continuation marker; a `^^` pair is a + // literal caret and stays. + let text = trimmed_end.strip_suffix('^').unwrap_or(trimmed_end); + if !text.trim().is_empty() { + body.push_str(text); + body.push(' '); + } + if !continued { + break; + } + loop { + match lines.next() { + Some(next) if next.trim().is_empty() => continue, + Some(next) => { + piece = next.to_string(); + break; + } + None => return Some(body), + } + } + } + return Some(body); } - out + None +} + +/// Offset right after the engine executable name. +/// 1.x ships `winws.exe`, 2.0.0 renamed it to `winws2.exe`. +fn engine_end(line: &str) -> Option { + let mut best: Option<(usize, usize)> = None; + for marker in [crate::runtime::LUA_ENGINE, crate::runtime::LEGACY_ENGINE] { + if let Some(pos) = line.find(marker) { + if best.map(|(found, _)| pos < found).unwrap_or(true) { + best = Some((pos, marker.len())); + } + } + } + best.map(|(pos, len)| pos + len) } /// Tokenize respecting double quotes; strip quote chars, keep `key=value` intact. diff --git a/src-tauri/src/strategy_tests.rs b/src-tauri/src/strategy_tests.rs index a17723c..65ced3d 100644 --- a/src-tauri/src/strategy_tests.rs +++ b/src-tauri/src/strategy_tests.rs @@ -1,6 +1,7 @@ #[cfg(test)] mod tests { use crate::config::GameFilter; + use crate::config::YoutubeWsMode; use crate::strategy; use std::fs; use std::time::{SystemTime, UNIX_EPOCH}; @@ -14,6 +15,23 @@ cd /d %BIN% start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-udp=443,%GameFilterUDP% ^ --filter-udp=443 --hostlist="%LISTS%list-general.txt" --hostlist="%LISTS%list-general-user.txt" ^ --filter-tcp=80,443 --hostlist="%LISTS%list-general.txt" --dpi-desync=multisplit --dpi-desync-split-seqovl=568 --dpi-desync-split-pos=1 --dpi-desync-split-seqovl-pattern="%BIN%tls_clienthello_4pda_to.bin" +"#; + + const ZAPRET_2_BAT: &str = r#"@echo off +chcp 65001 > nul +cd /d "%~dp0" +set "BIN=%~dp0bin\" +set "LISTS=%~dp0lists\" +set "LUA=%~dp0lua\" +start "zapret: %~n0" /min "%BIN%winws2.exe" --wf-tcp-out=80,443,%GameFilterTCP% --wf-udp-out=443,%GameFilterUDP% %YoutubeWSOptions% ^ + +--lua-init=@"%LUA%blobs.lua" ^ +--lua-init=@"%LUA%zapret-lib.lua" ^ +--template=i ^ +--ipset-exclude="%LISTS%ipset-exclude.txt" --new ^ +--template=h --hostlist-exclude="%LISTS%list-exclude.txt" --import=i --new ^ +%YoutubeWSProfile% ^ +--name="Domain TLS" --filter-tcp=80,443 --hostlist="%LISTS%list-general.txt" --lua-desync=multisplit:pos=1 "#; const SERVICE_BAT: &str = r#"@echo off @@ -30,13 +48,6 @@ echo menu let _ = fs::remove_dir_all(&dir); fs::create_dir_all(dir.join("bin")).unwrap(); fs::create_dir_all(dir.join("lists")).unwrap(); - // The runtime ships the fake/overlap ClientHello used by the Flashscore - // fake-split profile. - fs::write( - dir.join("bin").join("tls_clienthello_max_ru.bin"), - b"fake-clienthello", - ) - .unwrap(); fs::write(dir.join("general.bat"), GENERAL_BAT).unwrap(); fs::write(dir.join("service.bat"), SERVICE_BAT).unwrap(); dir @@ -49,6 +60,7 @@ echo menu &runtime.join("general.bat"), &runtime, GameFilter::Disabled, + YoutubeWsMode::Disabled, ) .expect("parse"); assert!(args.len() > 5, "expected many args, got {}", args.len()); @@ -78,147 +90,182 @@ echo menu #[test] fn parse_substitutes_game_filter_all() { let runtime = fixture_runtime(); - let args = - strategy::parse_strategy_args(&runtime.join("general.bat"), &runtime, GameFilter::All) - .expect("parse"); + let args = strategy::parse_strategy_args( + &runtime.join("general.bat"), + &runtime, + GameFilter::All, + YoutubeWsMode::Disabled, + ) + .expect("parse"); assert!(args[0].ends_with("1024-65535"), "got {}", args[0]); assert!(args[1].ends_with("1024-65535"), "got {}", args[1]); let _ = fs::remove_dir_all(&runtime); } + fn fixture_runtime_v2() -> std::path::PathBuf { + let uniq = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let dir = std::env::temp_dir().join(format!("zapret-ui-strategy-v2-{uniq}")); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("bin")).unwrap(); + fs::create_dir_all(dir.join("lists")).unwrap(); + fs::create_dir_all(dir.join("lua")).unwrap(); + fs::write(dir.join("bin").join("winws2.exe"), b"exe").unwrap(); + fs::write(dir.join("lua").join("blobs.lua"), b"local blobs = {}\n").unwrap(); + fs::write(dir.join("general.bat"), ZAPRET_2_BAT).unwrap(); + fs::write(dir.join("service.bat"), SERVICE_BAT).unwrap(); + dir + } + #[test] - fn flashscore_section_is_inserted_before_first_filter() { - let runtime = fixture_runtime(); + fn parse_zapret_2_bat_expands_lua_and_ws_variables() { + let runtime = fixture_runtime_v2(); let args = strategy::parse_strategy_args( &runtime.join("general.bat"), &runtime, GameFilter::Disabled, + YoutubeWsMode::Disorder, ) .expect("parse"); - let with = strategy::with_flashscore_section(&args, &runtime); - // Global winws options stay in front of the injected profile. - assert_eq!(with[0], args[0]); - assert_eq!(with[1], args[1]); + assert!(args[0].starts_with("--wf-tcp-out="), "got {}", args[0]); + assert!(args[0].ends_with(",12"), "got {}", args[0]); - // The flashscore profiles become the first two filter profiles. - assert_eq!(with[2], "--filter-tcp=80,443"); - assert_eq!( - with[3], - "--hostlist-domains=flashscorekz.com,flashscore.com.ua,flashscore.ninja" + let lua_init = args + .iter() + .find(|a| a.starts_with("--lua-init=@") && a.contains("blobs.lua")) + .expect("lua init"); + assert!(lua_init.contains("blobs.lua"), "got {lua_init}"); + assert!( + lua_init.contains(&runtime.to_string_lossy().to_string()), + "lua path must point into the runtime: {lua_init}" ); - assert!(with.contains(&"--dpi-desync=multidisorder".to_string())); - assert!(with.contains(&"--dpi-desync-split-pos=1,midsld".to_string())); - assert!(with.contains(&"--dpi-desync-fooling=ts".to_string())); - assert!(with.contains(&"--dpi-desync-repeats=4".to_string())); assert!( - !with.iter().any(|a| a.contains("hostfakesplit")), - "hostfakesplit is RST-ed by the current DPI" + args.iter().any(|a| a == "--name=GooglevideoWS"), + "YouTube WS profile missing: {args:?}" ); - - // Second profile: the Cloudflare/Google hosts (logos, flags, icons). - assert!(with.contains(&"--hostlist-domains=flashscore.com".to_string())); - assert!(with.contains(&"--dpi-desync=fake,multisplit".to_string())); - assert!(with.contains(&"--dpi-desync-split-seqovl=664".to_string())); - assert!(with.contains(&"--dpi-desync-repeats=8".to_string())); - let pattern = with + assert!(args .iter() - .find(|a| a.starts_with("--dpi-desync-split-seqovl-pattern=")) - .expect("seqovl pattern"); + .any(|a| a.contains("--lua-desync=multidisorder:pos=1,midsld-1"))); assert!( - pattern.contains("tls_clienthello_max_ru.bin"), - "got {pattern}" + !args.iter().any(|a| a.contains('%')), + "placeholder left: {args:?}" ); assert!( - pattern.contains(&runtime.to_string_lossy().to_string()), - "pattern path must point into runtime: {pattern}" + !args.iter().any(|a| a.contains('"')), + "quote left in arg: {args:?}" ); - let fake = with - .iter() - .find(|a| a.starts_with("--dpi-desync-fake-tls=")) - .expect("fake tls"); - assert!(fake.contains("tls_clienthello_max_ru.bin"), "got {fake}"); - - let excludes: Vec<&String> = with - .iter() - .filter(|a| a.starts_with("--hostlist-exclude=")) - .collect(); - assert_eq!(excludes.len(), 4, "two exclude lists per profile expected"); - for e in excludes { - assert!( - e.contains(&runtime.to_string_lossy().to_string()), - "exclude path must point into runtime: {e}" - ); - } - - // The injected profile ends with --new, and the original filter chain survives. - let orig_filter = args - .iter() - .position(|a| a.starts_with("--filter-")) - .expect("original filter"); - let tail_start = with - .iter() - .skip(2) - .position(|a| a.starts_with("--filter-") && a != "--filter-tcp=80,443") - .map(|i| i + 2) - .expect("original filter after injection"); - assert_eq!(with[tail_start - 1], "--new"); - assert_eq!(&with[tail_start..], &args[orig_filter..]); + // A blank line after `start ... ^` must not cut the command: every profile + // and every Lua initialiser has to survive. + assert!( + args.iter().filter(|a| a.starts_with("--filter-")).count() >= 2, + "profiles lost: {args:?}" + ); + assert!( + args.iter() + .filter(|a| a.starts_with("--lua-init=@")) + .count() + >= 3, + "lua init lost: {args:?}" + ); + assert!(args.len() > 20, "command truncated: {args:?}"); - for a in &with { - assert!(!a.contains('"'), "quote left in arg: {a}"); - } + // Disabled keeps the strategy free of the WS profile entirely. + let plain = strategy::parse_strategy_args( + &runtime.join("general.bat"), + &runtime, + GameFilter::Disabled, + YoutubeWsMode::Disabled, + ) + .expect("parse"); + assert!( + !plain + .iter() + .any(|a| a.starts_with("--name=GooglevideoWS") || a.contains("wssize")), + "disabled WS must not inject its profile: {plain:?}" + ); let _ = fs::remove_dir_all(&runtime); } + /// End-to-end check against a real 2.0.0 runtime: parses every `.bat` and asks + /// the engine to verify the arguments. + /// Manual run (needs the unpacked release): + /// `$env:ZAPRET_RUNTIME_2="...\zapret-discord-youtube-2.0.0"; cargo test real_2_0 -- --ignored` #[test] - fn flashscore_section_appended_when_no_filter_exists() { - let runtime = fixture_runtime(); - let args = vec!["--wf-tcp=80,443".to_string()]; - let with = strategy::with_flashscore_section(&args, &runtime); + #[ignore] + fn real_2_0_strategies_pass_the_engine_dry_run() { + let Ok(dir) = std::env::var("ZAPRET_RUNTIME_2") else { + eprintln!("ZAPRET_RUNTIME_2 is not set"); + return; + }; + let runtime = std::path::PathBuf::from(dir); + let engine = crate::runtime::engine_binary(&runtime).expect("2.0.0 engine"); + // The app creates these before every start; a fresh archive does not have + // them and the engine refuses a missing ipset/hostlist file. + let lists = runtime.join("lists"); + for name in [ + "list-general-user.txt", + "list-exclude-user.txt", + "ipset-exclude-user.txt", + ] { + let path = lists.join(name); + if !path.exists() { + fs::write(path, "").unwrap(); + } + } + let strategies = + strategy::discover_strategies(&runtime, GameFilter::Disabled, YoutubeWsMode::Disorder); + assert!(strategies.len() >= 10, "expected a full strategy list"); - assert_eq!(with[0], "--wf-tcp=80,443"); - assert_eq!(with[1], "--new"); - assert_eq!(with[2], "--filter-tcp=80,443"); - assert_eq!( - with[3], - "--hostlist-domains=flashscorekz.com,flashscore.com.ua,flashscore.ninja" - ); - // Both profiles are injected and the section ends with the fake TLS record. - let second = with - .iter() - .position(|a| a == "--hostlist-domains=flashscore.com") - .expect("second (fake-split) profile"); - assert_eq!(with[second - 1], "--filter-tcp=80,443"); - assert!( - with.last() - .map(|a| a.starts_with("--dpi-desync-fake-tls=")) - .unwrap_or(false), - "section must end with the fake TLS record" - ); - let _ = fs::remove_dir_all(&runtime); + for found in &strategies { + let args = &found.args; + assert!( + !args.iter().any(|a| a.starts_with("--dpi-desync")), + "{}: legacy option leaked", + found.name + ); + // Without those, the args look plausible to `--dry-run` but the service + // runs without a single profile (a blank line used to cut the command). + assert!( + args.iter().any(|a| a.starts_with("--filter-")), + "{}: no profile parsed: {args:?}", + found.name + ); + assert!( + args.iter() + .filter(|a| a.starts_with("--lua-init=@")) + .count() + >= 3, + "{}: lua initialisers lost: {args:?}", + found.name + ); + crate::engine::Engine::verify_args(&engine.to_string_lossy(), args) + .unwrap_or_else(|err| panic!("{}: {err}\n{args:?}", found.name)); + } } #[test] - fn flashscore_falls_back_to_reorder_without_pattern_file() { - let runtime = fixture_runtime(); - fs::remove_file(runtime.join("bin").join("tls_clienthello_max_ru.bin")).unwrap(); - let args = vec!["--wf-tcp=80,443".to_string()]; - let with = strategy::with_flashscore_section(&args, &runtime); + fn a_commented_engine_name_does_not_shift_the_arguments() { + let runtime = fixture_runtime_v2(); + let bat = ZAPRET_2_BAT.replace( + "@echo off", + "@echo off\r\n:: winws2.exe runs the bypass\r\n:: do not run winws.exe here", + ); + fs::write(runtime.join("commented.bat"), bat).unwrap(); - // The com hosts are still covered, but without referencing the missing file: - // winws refuses to start on a missing desync file. - assert!(with.contains(&"--hostlist-domains=flashscore.com".to_string())); - assert!(!with - .iter() - .any(|a| a.contains("tls_clienthello_max_ru.bin"))); - assert!(!with.iter().any(|a| a.starts_with("--dpi-desync-fake-tls="))); - assert_eq!( - with.iter() - .filter(|a| a.as_str() == "--dpi-desync=multidisorder") - .count(), - 2, - "both profiles should fall back to the reorder desync" + let args = strategy::parse_strategy_args( + &runtime.join("commented.bat"), + &runtime, + GameFilter::Disabled, + YoutubeWsMode::Disabled, + ) + .expect("parse"); + assert_eq!(args[0], "--wf-tcp-out=80,443,12", "got {:?}", args[0]); + assert!( + !args.iter().any(|a| a.contains("start")), + "the launch command leaked into the arguments: {args:?}" ); let _ = fs::remove_dir_all(&runtime); } @@ -241,7 +288,8 @@ echo menu ) .unwrap(); - let list = strategy::discover_strategies(&runtime, GameFilter::Disabled); + let list = + strategy::discover_strategies(&runtime, GameFilter::Disabled, YoutubeWsMode::Disabled); // service.bat must be skipped assert!( !list.iter().any(|s| s.name == "service"), diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs index e0f63b0..39cd717 100644 --- a/src-tauri/src/tray.rs +++ b/src-tauri/src/tray.rs @@ -98,7 +98,7 @@ impl TrayState { } /// The same "is it on" the UI shows: the service, or a benchmark's temporary -/// `winws.exe`. +/// engine process (`winws.exe` or `winws2.exe`). fn zapret_running() -> bool { engine::Engine::is_running() || engine::Engine::is_any_winws_running() } diff --git a/src-tauri/src/youtube_ws.rs b/src-tauri/src/youtube_ws.rs new file mode 100644 index 0000000..4526ae7 --- /dev/null +++ b/src-tauri/src/youtube_ws.rs @@ -0,0 +1,230 @@ +//! YouTube-over-WebSocket profiles introduced by flowseal-zapret 2.0.0. +//! +//! Google serves googlevideo.com over WebSocket for part of the traffic, and the +//! DPI drops those flows by their window sizes. A plain TLS/QUIC desync does not +//! help there, so upstream ships a dedicated profile for `googlevideo.com` that +//! adjusts the TCP window (`lua/wssize-compensate.lua`, `lua/wssize-retry.lua`). +//! +//! `general.bat` in 2.0.0 does not spell the profile out: it references +//! `%YoutubeWSOptions%` and `%YoutubeWSProfile%`, which `service.bat` builds from +//! `utils\youtube_ws.enabled` (menu item "YouTube WS"). The app parses `.bat` +//! directly, so it builds the same values from the mode stored in its config and +//! mirrors that mode back into the runtime file for the upstream menu. +//! +//! Mode names and arguments are copied from `service.bat` (`:youtube_ws_status`) +//! of release 2.0.0; keep them in sync when the runtime changes them. + +use crate::config::YoutubeWsMode; +use std::fs; +use std::path::Path; + +const SETTINGS_FILE: &str = "youtube_ws.enabled"; + +/// Global options required by both YouTube WS Lua scripts. +const WS_OPTIONS: &str = "--wf-tcp-empty=1 --ipcache-hostname=1"; + +/// Everything before the mode-specific desync actions. +const WS_PROFILE_HEAD: &str = "--name=GooglevideoWS --filter-tcp=443 \ +--hostlist-domains=googlevideo.com --payload=all --in-range=-s1 \ +--lua-desync=wssize_first_retry --lua-desync=wssize_compensate --in-range=x \ +--lua-desync=wssize:wsize=1:scale=1 --payload=tls_client_hello"; + +pub struct YoutubeArgs { + /// Value for `%YoutubeWSOptions%` (global options, empty when disabled). + pub options: String, + /// Value for `%YoutubeWSProfile%` (a whole profile, empty when disabled). + pub profile: String, +} + +/// Mode saved by the runtime's own menu. A missing file means the runtime never +/// wrote one, and `service.bat` then defaults to `ws-disorder`; an unreadable or +/// unknown value means "disabled" there. +pub fn read_mode(runtime_dir: &Path) -> YoutubeWsMode { + let Ok(text) = fs::read_to_string(runtime_dir.join("utils").join(SETTINGS_FILE)) else { + return YoutubeWsMode::Disorder; + }; + for line in text.lines() { + let line = line.trim().trim_start_matches('\u{feff}'); + let Some((key, value)) = line.split_once('=') else { + continue; + }; + // `findstr /i` matches the key and the value case-insensitively. + if !key.trim().eq_ignore_ascii_case("mode") { + continue; + } + let value = value.trim().to_ascii_lowercase(); + // Same shape as `findstr /r /x /c:"mode=[a-z][a-z0-9-]*"`. + let valid = value + .chars() + .next() + .map(|c| c.is_ascii_lowercase()) + .unwrap_or(false) + && value + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); + if !valid { + continue; + } + return YoutubeWsMode::parse(&value).unwrap_or(YoutubeWsMode::Disabled); + } + // A file without a usable `mode=` line ends as `disabled` in service.bat too. + YoutubeWsMode::Disabled +} + +/// Writes the mode in the format `service.bat` reads, so its menu shows the same +/// state as the app. Failure is not fatal: the app parses strategies from its own +/// config and does not depend on this file. +pub fn write_mode(runtime_dir: &Path, mode: YoutubeWsMode) -> Result<(), String> { + let dir = runtime_dir.join("utils"); + fs::create_dir_all(&dir) + .map_err(|e| format!("Не удалось создать папку настроек runtime: {e}"))?; + fs::write( + dir.join(SETTINGS_FILE), + format!("mode={}\r\n", mode.as_str()), + ) + .map_err(|e| format!("Не удалось сохранить настройку YouTube WS: {e}")) +} + +pub fn args(runtime_dir: &Path, mode: YoutubeWsMode) -> YoutubeArgs { + let (actions, extra) = match mode { + YoutubeWsMode::Disabled => return disabled(), + YoutubeWsMode::Fake => ( + "--lua-desync=fake:blob=gz:tcp_seq=-10000:tcp_ack=-66000:ip_id=zero:repeats=5 \ +--lua-desync=multidisorder:pos=1,midsld:ip_id=zero", + Some("--blob=gz:0x00000000"), + ), + YoutubeWsMode::Disorder => ("--lua-desync=multidisorder:pos=1,midsld-1:ip_id=zero", None), + YoutubeWsMode::Disorder2 => ( + "--lua-desync=multidisorder:pos=1,sld+2,midsld+2,endhost-3:ip_id=zero", + None, + ), + }; + + // `service.bat` writes `..\lua\...` because both launch paths change the + // working directory to bin\. The app passes absolute paths instead. + let lua = runtime_dir.join("lua"); + let mut options = format!( + "{WS_OPTIONS} --lua-init=@{} --lua-init=@{}", + lua.join("wssize-compensate.lua").to_string_lossy(), + lua.join("wssize-retry.lua").to_string_lossy() + ); + if let Some(extra) = extra { + options.push(' '); + options.push_str(extra); + } + + YoutubeArgs { + options, + profile: format!("{WS_PROFILE_HEAD} {actions} --new"), + } +} + +fn disabled() -> YoutubeArgs { + YoutubeArgs { + options: String::new(), + profile: String::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + use std::time::{SystemTime, UNIX_EPOCH}; + + fn temp_runtime(name: &str) -> PathBuf { + let uniq = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let dir = std::env::temp_dir().join(format!("zapret-ui-ws-{name}-{uniq}")); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("utils")).unwrap(); + dir + } + + fn write_mode_text(dir: &Path, text: &str) { + fs::write(dir.join("utils").join(SETTINGS_FILE), text).unwrap(); + } + + #[test] + fn missing_settings_default_to_ws_disorder() { + let dir = temp_runtime("default"); + assert_eq!(read_mode(&dir), YoutubeWsMode::Disorder); + let args = args(&dir, YoutubeWsMode::Disorder); + assert!(args.profile.contains("--filter-tcp=443")); + assert!(args.profile.contains("multidisorder:pos=1,midsld-1")); + assert!(args.options.contains("wssize-compensate.lua")); + assert!(args.options.contains(&dir.to_string_lossy().to_string())); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn settings_round_trip_through_the_runtime_file() { + let dir = temp_runtime("roundtrip"); + for mode in [ + YoutubeWsMode::Disabled, + YoutubeWsMode::Fake, + YoutubeWsMode::Disorder, + YoutubeWsMode::Disorder2, + ] { + write_mode(&dir, mode).unwrap(); + assert_eq!( + read_mode(&dir), + mode, + "mode {} must round trip", + mode.as_str() + ); + let text = fs::read_to_string(dir.join("utils").join(SETTINGS_FILE)).unwrap(); + assert_eq!(text.trim(), format!("mode={}", mode.as_str())); + } + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn disabled_mode_removes_the_profile() { + let dir = temp_runtime("disabled"); + write_mode_text(&dir, "mode=disabled\n"); + let args = args(&dir, read_mode(&dir)); + assert!(args.profile.is_empty()); + assert!(args.options.is_empty()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn unknown_mode_behaves_like_service_bat() { + let dir = temp_runtime("unknown"); + write_mode_text(&dir, "mode=ws-unknown\n"); + assert_eq!(read_mode(&dir), YoutubeWsMode::Disabled); + + // A file without a usable mode line also ends as disabled. + write_mode_text(&dir, "garbage\n"); + assert_eq!(read_mode(&dir), YoutubeWsMode::Disabled); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn ws_fake_adds_the_zero_blob() { + let dir = temp_runtime("fake"); + write_mode_text(&dir, "mode=ws-fake\n"); + let args = args(&dir, read_mode(&dir)); + assert!(args.options.contains("--blob=gz:0x00000000")); + assert!(args.profile.contains("--lua-desync=fake:blob=gz")); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn mode_line_is_matched_exactly() { + let dir = temp_runtime("exact"); + write_mode_text(&dir, "[settings]\nmode=ws-disorder2\nextra=1\n"); + assert_eq!(read_mode(&dir), YoutubeWsMode::Disorder2); + assert!(args(&dir, YoutubeWsMode::Disorder2) + .profile + .contains("sld+2")); + + // `findstr /i` in service.bat accepts another case. + write_mode_text(&dir, "MODE=WS-FAKE\n"); + assert_eq!(read_mode(&dir), YoutubeWsMode::Fake); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 4bf4e2c..edf5cac 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Splitline", - "version": "2.3.2", + "version": "2.3.3", "identifier": "com.zapret.ui", "mainBinaryName": "Splitline", "build": { diff --git a/src/components/MaintenancePanel.vue b/src/components/MaintenancePanel.vue index 3dd8e93..792b9cf 100644 --- a/src/components/MaintenancePanel.vue +++ b/src/components/MaintenancePanel.vue @@ -37,6 +37,7 @@ import { setCheckAppUpdates, setGameFilter, setTheme, + setYoutubeWs, status, tgwsBusy, tgwsChecking, @@ -45,7 +46,6 @@ import { tgwsUpdate, toggleAutostart, toggleCheckUpdates, - toggleFlashscore, updateInfo, updateProgress, } from "../store"; @@ -256,13 +256,6 @@ onMounted(() => { :checked="config?.check_updates" @change="toggleCheckUpdates" /> - { + +
Папка flowseal-zapret {{ runtimePath }} diff --git a/src/components/SetupWizard.vue b/src/components/SetupWizard.vue index 3f5d441..d45a564 100644 --- a/src/components/SetupWizard.vue +++ b/src/components/SetupWizard.vue @@ -54,9 +54,9 @@ onUnmounted(() => window.removeEventListener("keydown", onKeydown));

Где хранить flowseal-zapret?

- В выбранной папке будут стратегии .bat, списки и bin/winws.exe. - Можно оставить путь по умолчанию или выбрать другую папку — например, рядом с портативным - exe. + В выбранной папке будут стратегии .bat, списки и движок обхода + bin/winws2.exe. Можно оставить путь по умолчанию или выбрать другую папку — + например, рядом с портативным exe.

{{ runtimePath || "Путь по умолчанию" }}
diff --git a/src/store/actions.test.ts b/src/store/actions.test.ts index 17e5361..4c172c7 100644 --- a/src/store/actions.test.ts +++ b/src/store/actions.test.ts @@ -39,8 +39,9 @@ const configFixture: ConfigView = { autostart: true, check_updates: true, check_app_updates: true, - flashscore_bypass: true, game_filter: "disabled", + youtube_ws: "ws-disorder", + youtube_ws_supported: true, runtime_version: "1.10.4", runtime_path: "C:\\old\\path", theme: "dark", diff --git a/src/store/actions.ts b/src/store/actions.ts index 0354283..d41f5c8 100644 --- a/src/store/actions.ts +++ b/src/store/actions.ts @@ -904,10 +904,13 @@ export async function applyUpdate() { busy.value = true; try { - await invoke("apply_update"); + const notice = await invoke("apply_update"); updateInfo.value = null; await refreshInternal(true); toast("success", "flowseal-zapret обновлён."); + // The new release may not have the saved strategy; the backend switched to + // the default and explains it here. + if (notice) toast("warning", notice); } catch (error) { toast("error", String(error)); } finally { @@ -926,9 +929,10 @@ export async function installRuntime() { toast("warning", "Не удалось найти обновление flowseal-zapret."); return; } - await invoke("apply_update"); + const notice = await invoke("apply_update"); await refreshInternal(true); toast("success", "flowseal-zapret установлен."); + if (notice) toast("warning", notice); } catch (error) { toast("error", String(error)); } finally { @@ -1033,27 +1037,28 @@ export async function toggleCheckUpdates(enabled: boolean) { } } -export async function toggleFlashscore(enabled: boolean) { +export async function setAutoApply(enabled: boolean) { try { - await invoke("set_flashscore_bypass", { enabled }); + await invoke("set_bench_auto_apply", { enabled }); await refreshInternal(true); } catch (error) { toast("error", String(error)); } } -export async function setAutoApply(enabled: boolean) { +export async function setGameFilter(mode: string) { try { - await invoke("set_bench_auto_apply", { enabled }); + await invoke("set_game_filter", { mode }); await refreshInternal(true); } catch (error) { toast("error", String(error)); } } -export async function setGameFilter(mode: string) { +/** `disabled`, `ws-fake`, `ws-disorder` or `ws-disorder2` (flowseal-zapret 2.0.0). */ +export async function setYoutubeWs(mode: string) { try { - await invoke("set_game_filter", { mode }); + await invoke("set_youtube_ws", { mode }); await refreshInternal(true); } catch (error) { toast("error", String(error)); diff --git a/src/types.ts b/src/types.ts index c1313b8..becfef7 100644 --- a/src/types.ts +++ b/src/types.ts @@ -27,8 +27,11 @@ export interface ConfigView { autostart: boolean; check_updates: boolean; check_app_updates: boolean; - flashscore_bypass: boolean; game_filter: string; + /** `disabled`, `ws-fake`, `ws-disorder` or `ws-disorder2`. */ + youtube_ws: string; + /** False for the 1.x runtime, which has no YouTube-over-WebSocket profile. */ + youtube_ws_supported: boolean; runtime_version: string; runtime_path: string; theme: string;