From 68d34859a39c0e23fa12fb1aa0dc3b2b782124ee Mon Sep 17 00:00:00 2001 From: OGRYZOK Date: Mon, 30 Nov 2026 09:15:12 +0300 Subject: [PATCH 1/4] feat: add VLESS proxy support via managed Xray-core bridge --- mcp/index.js | 4 +- openapi.yaml | 37 +- scripts/check-i18n.mjs | 5 +- src-tauri/src/api.rs | 13 +- src-tauri/src/launch.rs | 28 +- src-tauri/src/lib.rs | 20 + src-tauri/src/process.rs | 8 +- src-tauri/src/psapi.rs | 2 + src-tauri/src/runner.rs | 25 +- src-tauri/src/settings.rs | 4 + src-tauri/src/space/client.rs | 3 +- src-tauri/src/space/doors.rs | 2 + src-tauri/src/space/local/extensions.rs | 18 +- .../src/space/local/extensions/usage/tests.rs | 2 +- .../src/space/local/extensions/widevine.rs | 9 +- src-tauri/src/space/local/proxy.rs | 438 +++++- src-tauri/src/space/mod.rs | 4 +- src-tauri/src/space/remote.rs | 2 + src-tauri/src/vless.rs | 1190 +++++++++++++++++ src/dev/mock/fixtures.ts | 4 +- src/dev/mock/handlers.ts | 38 +- src/entities/proxy/index.ts | 1 + src/entities/proxy/lib/identity.ts | 18 +- src/entities/proxy/lib/useProxy.tsx | 10 +- src/entities/proxy/lib/vless.test.ts | 66 + src/entities/proxy/lib/vless.ts | 332 +++++ src/entities/proxy/model/api.ts | 8 + src/entities/proxy/model/types.ts | 28 +- src/entities/settings/model/types.ts | 2 + .../manage-proxies/lib/filterFields.tsx | 4 +- .../manage-proxies/ui/EditProxyDialog.tsx | 264 +++- .../manage-proxies/ui/ProxyBulkImporter.tsx | 17 +- .../profile-form/ui/fields/ProxyRow.tsx | 6 +- .../settings/sections/ProfileDefaults.tsx | 65 +- src/shared/i18n/locales/en.json | 48 +- src/shared/i18n/locales/ru.json | 48 +- src/shared/i18n/locales/zh.json | 48 +- src/widgets/ProxyPeek/Details.tsx | 86 +- src/widgets/ProxyPeek/ProxyPeek.tsx | 2 +- 39 files changed, 2767 insertions(+), 142 deletions(-) create mode 100644 src-tauri/src/vless.rs create mode 100644 src/entities/proxy/lib/vless.test.ts create mode 100644 src/entities/proxy/lib/vless.ts diff --git a/mcp/index.js b/mcp/index.js index 0cedc3cf8..91ad5140d 100644 --- a/mcp/index.js +++ b/mcp/index.js @@ -424,10 +424,10 @@ server.tool("list_proxies", "List stored proxies (no credentials).", {}, async ( server.tool( "add_proxy", - "Add a proxy to the store. Pass `proxy` as a string (scheme://user:pass@host:port) or explicit fields.", + "Add a proxy to the store. Pass `proxy` as a string (vless://uuid@host:port?..., scheme://user:pass@host:port) or explicit fields.", { proxy: z.string().optional(), - kind: z.enum(["socks5", "http", "https"]).optional(), + kind: z.enum(["socks5", "http", "https", "vless"]).optional(), host: z.string().optional(), port: z.number().optional(), username: z.string().optional(), diff --git a/openapi.yaml b/openapi.yaml index 5349829a3..bef0a7366 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -2473,8 +2473,8 @@ components: properties: proxy: type: string - description: "`scheme://user:pass@host:port` or `host:port:user:pass`." - kind: { type: string, enum: [socks5, http, https] } + description: "`vless://uuid@host:port?...`, `scheme://user:pass@host:port` or `host:port:user:pass`." + kind: { type: string, enum: [socks5, http, https, vless] } host: { type: string } port: { type: integer } username: { type: string } @@ -2485,6 +2485,33 @@ components: change_ip_url: type: string description: "The provider's change-IP link (http/https). Kept on this computer only, never returned." + vless: + $ref: "#/components/schemas/VlessConfig" + + VlessConfig: + type: object + description: Extra transport and security parameters for VLESS proxies (the UUID sits in `username`). + properties: + encryption: { type: string, default: none } + flow: { type: string } + network: { type: string, default: tcp } + security: { type: string, default: none } + sni: { type: string } + fingerprint: { type: string } + public_key: { type: string } + short_id: { type: string } + spider_x: { type: string } + pqv: { type: string } + alpn: { type: string } + allow_insecure: { type: boolean } + host: { type: string } + path: { type: string } + service_name: { type: string } + authority: { type: string } + mode: { type: string } + header_type: { type: string } + seed: { type: string } + extra: { type: string } ProxySummary: type: object @@ -2492,7 +2519,7 @@ components: properties: id: { type: string } name: { type: string } - kind: { type: string, enum: [socks5, http, https] } + kind: { type: string, enum: [socks5, http, https, vless] } host: { type: string } port: { type: integer } country: { type: string, description: Informational tag (e.g. "US"). } @@ -2528,13 +2555,15 @@ components: properties: id: { type: string } name: { type: string } - kind: { type: string, enum: [socks5, http, https] } + kind: { type: string, enum: [socks5, http, https, vless] } host: { type: string } port: { type: integer } username: { type: string } password: { type: string } country: { type: string } notes: { type: string } + vless: + $ref: "#/components/schemas/VlessConfig" AutomationBranch: description: | diff --git a/scripts/check-i18n.mjs b/scripts/check-i18n.mjs index 09ddb141a..69c1646dd 100644 --- a/scripts/check-i18n.mjs +++ b/scripts/check-i18n.mjs @@ -26,8 +26,9 @@ const TEXT_PROPS = new Set([ // picker's own entries, and samples of code or headers. const KEEP = new Set([ "ShardBrowser", "ShardBrowser Launcher", "ProxyShard", "ShardX", "Shard Helper", "GitHub", "MCP", "GPU", "CPU", - "URL", "SQL", "UDP", "TCP", "HTTP", "HTTPS", "SOCKS5", "Canvas", "WebGL", - "WebGPU", "WebRTC", "TLS", "CDP", "API", "JSON", "Cookie", "User-Agent", + "URL", "SQL", "UDP", "TCP", "HTTP", "HTTPS", "SOCKS5", "VLESS", "REALITY", "WebSocket", "XHTTP", "HTTPUpgrade", "Canvas", "WebGL", + "WebGPU", "WebRTC", "TLS", "CDP", "API", "JSON", "Cookie", "User-Agent", "h2,http/1.1", + "Chrome", "Firefox", "Safari", "Edge", "QQ", "macOS", "MacOS", "Windows", "Windows 10", "Windows 11", "Linux", "Android", "iOS", "IOS", "X", "Y", "ISP", "Do Not Track", "Esc", "Enter", "Ctrl", "Space", "Home", "End", "Delete", "Shift", "Authorization: Bearer …", "Content-Type: application/json", diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 03cb375c8..c5116f574 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -762,9 +762,9 @@ async fn list_fingerprints() -> ApiResult { #[derive(Deserialize)] struct AddProxyReq { - /// "scheme://user:pass@host:port" or "host:port:user:pass"; wins over fields. + /// "vless://uuid@host:port?...", "scheme://user:pass@host:port" or "host:port:user:pass"; wins over fields. proxy: Option, - /// socks5 | http | https (default socks5). + /// socks5 | http | https | vless (default socks5). kind: Option, host: Option, port: Option, @@ -775,6 +775,8 @@ struct AddProxyReq { notes: Option, /// #162: the provider's change-IP link; kept on this computer, never returned. change_ip_url: Option, + #[serde(default)] + vless: Option, } /// Add proxy (an identical one already stored is reused); returns summary. @@ -793,8 +795,14 @@ async fn add_proxy(Extension(t): Extension, Json(body): Json crate::space::proxy::ProxyKind::Http, Some("https") => crate::space::proxy::ProxyKind::Https, + Some("vless") => crate::space::proxy::ProxyKind::Vless, _ => crate::space::proxy::ProxyKind::Socks5, }; + let vless = if kind == crate::space::proxy::ProxyKind::Vless { + Some(body.vless.as_ref().map(|v| v.normalized()).unwrap_or_default()) + } else { + None + }; crate::space::proxy::ProxyEntry { id: String::new(), name: String::new(), @@ -805,6 +813,7 @@ async fn add_proxy(Extension(t): Extension, Json(body): Json { icon: Option<&'a Path>, /// The profile as the engine reads it: no `_meta`, "auto" resolved. raw: &'a serde_json::Map, + proxy_server_arg: Option<&'a str>, proxy_udp_ok: bool, proxy_public_ip: Option<&'a str>, use_real_screen: bool, @@ -607,8 +608,18 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> let bin = bin.to_path_buf(); tokio::task::spawn_blocking(move || crate::runtime::engine_loads_extensions_alone(&bin)) }); + // Start a local Xray SOCKS5 bridge before probing/launching VLESS profiles. + let (effective_proxy, vless_lease) = match input.proxy.as_ref() { + Some(p) => { + let (resolved, lease) = proxy::resolve_transport(p).await?; + check_cancel(&input.profile_id)?; + (Some(resolved), lease) + } + None => (None, None), + }; + let proxy_server_arg = effective_proxy.as_ref().map(|p| p.to_proxy_server_arg()); // Live UDP probe; QUIC/WebRTC gating uses current capability not stale cache. - let proxy_udp_ok = if let Some(p) = input.proxy.as_ref() { + let proxy_udp_ok = if let Some(p) = effective_proxy.as_ref() { if matches!(p.kind, proxy::ProxyKind::Socks5) { match proxy::probe_udp(p).await { Ok(ms) => { @@ -668,7 +679,7 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> // Strip `_meta` wrapper and resolve "auto" sentinels before serialising. let mut raw = engine_config(&input.stored); - resolve_auto_fields(&mut raw, input.proxy.as_ref()).await; + resolve_auto_fields(&mut raw, effective_proxy.as_ref()).await; // A version Chrome could not report never reaches the engine, wherever the profile came from. crate::settle_platform_version(&mut raw); // The proxy probe and the geo lookup are the slow part: a cancel made @@ -758,7 +769,7 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> } // Live geo for ICE-candidate spoofing, cached snapshot as fallback. - let proxy_public_ip: Option = if let Some(p) = input.proxy.as_ref() { + let proxy_public_ip: Option = if let Some(p) = effective_proxy.as_ref() { match proxy::geo_check(p, None).await { Ok(g) if !g.ip.is_empty() => Some(g.ip), _ => proxy::latest_test(&p.id) @@ -780,6 +791,7 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> fp_file: &fp_file, icon: icon.as_deref(), raw: &raw, + proxy_server_arg: proxy_server_arg.as_deref(), proxy_udp_ok, proxy_public_ip: proxy_public_ip.as_deref(), use_real_screen, @@ -823,7 +835,7 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> Some(_) => process::spawn_tied(cmd).await.context("start the ShardBrowser engine")?, None => (cmd.spawn().context("start the ShardBrowser engine")?, process::Tie::default()), }; - let pid = Tracker::shared().track(profile_id.clone(), child, udd.clone(), exit, ext_ids); + let pid = Tracker::shared().track(profile_id.clone(), child, udd.clone(), exit, ext_ids, vless_lease); if let Some(s) = &remote { s.spawned(tie, pid); @@ -972,7 +984,11 @@ fn command_line( } if let Some(p) = input.proxy.as_ref() { - args.push(format!("--proxy-server={}", p.to_proxy_server_arg())); + let server_arg = ready + .proxy_server_arg + .map(str::to_string) + .unwrap_or_else(|| p.to_proxy_server_arg()); + args.push(format!("--proxy-server={server_arg}")); // QUIC: enable only when proxy UDP relay verified; rely on Alt-Svc upgrade path. if ready.proxy_udp_ok { @@ -1831,6 +1847,7 @@ mod tests { fp_file: &fp, icon: Some(&icon), raw: &raw, + proxy_server_arg: None, proxy_udp_ok: false, proxy_public_ip: None, use_real_screen: false, @@ -1851,6 +1868,7 @@ mod tests { fp_file: &fp, icon: None, raw: &raw, + proxy_server_arg: None, proxy_udp_ok: false, proxy_public_ip: None, use_real_screen: false, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cc42f1ada..4f77e72af 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -25,6 +25,7 @@ mod team; mod space; mod ext_updates; mod launcher_update; +pub mod vless; // A live end-to-end check against a real team server and engine, run by hand (macOS, Linux). #[cfg(all(test, unix))] mod live_e2e; @@ -1734,6 +1735,7 @@ async fn proxy_bulk_import(text: String, kind: String, epoch: Option) -> Re let default_kind = match kind.as_str() { "http" => space::proxy::ProxyKind::Http, "https" => space::proxy::ProxyKind::Https, + "vless" => space::proxy::ProxyKind::Vless, _ => space::proxy::ProxyKind::Socks5, }; let parsed = space::proxy::parse_bulk(&text, default_kind); @@ -1746,11 +1748,23 @@ fn proxy_bulk_parse(text: String, kind: String) -> Vec let default_kind = match kind.as_str() { "http" => space::proxy::ProxyKind::Http, "https" => space::proxy::ProxyKind::Https, + "vless" => space::proxy::ProxyKind::Vless, _ => space::proxy::ProxyKind::Socks5, }; space::proxy::parse_bulk(&text, default_kind) } +#[tauri::command] +fn vless_status() -> vless::VlessStatus { + vless::status() +} + +#[tauri::command] +async fn vless_ensure() -> Result { + vless::ensure_xray_binary().await.map_err(|e| e.to_string())?; + Ok(vless::status()) +} + /// Persist pre-tested proxies (bulk dialog). #[tauri::command] async fn proxy_bulk_save(entries: Vec, epoch: Option) -> Result { @@ -2898,6 +2912,8 @@ pub fn run() { proxy_bulk_import, proxy_bulk_parse, proxy_bulk_save, + vless_status, + vless_ensure, launch, settings_get, settings_save, @@ -3131,6 +3147,8 @@ pub fn run() { api.prevent_exit(); exit_app(app, code.unwrap_or(0)); } + } else if let tauri::RunEvent::Exit = event { + vless::shutdown_all(); } }); } @@ -3140,6 +3158,7 @@ fn exit_app(app: &tauri::AppHandle, code: i32) { use std::sync::atomic::Ordering::SeqCst; static CLOSING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !space::open::any_open() && !space::profile::any_unsealed() { + vless::shutdown_all(); app.exit(code); return; } @@ -3151,6 +3170,7 @@ fn exit_app(app: &tauri::AppHandle, code: i32) { tauri::async_runtime::spawn(async move { space::open::close_all(space::open::QUIT_WAIT).await; space::profile::close_unsealed(space::open::QUIT_WAIT).await; + vless::shutdown_all(); CLOSING.store(false, SeqCst); app.exit(code); }); diff --git a/src-tauri/src/process.rs b/src-tauri/src/process.rs index 2d25d08b5..9feee1dc4 100644 --- a/src-tauri/src/process.rs +++ b/src-tauri/src/process.rs @@ -114,6 +114,7 @@ impl Tracker { udd: PathBuf, exit: ExitHook, extensions: Vec, + vless: Option, ) -> u32 { static GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let pid = child.id().unwrap_or(0); @@ -144,6 +145,7 @@ impl Tracker { // whole time, so a channel nobody reads is a button that does nothing. let started_at = Instant::now(); tokio::spawn(async move { + let _vless = vless; watch_child(&profile_id, &udd, &mut child, &mut rx).await; // The process we started is gone — which is not the same as the // browser being gone. @@ -748,7 +750,7 @@ mod tests { let id = format!("watch-{}", uuid::Uuid::new_v4().simple()); let udd = tmp_udd(); let child = tokio::process::Command::new("true").spawn().unwrap(); - super::Tracker::shared().track(id.clone(), child, udd.clone(), super::ExitHook::Local, Vec::new()); + super::Tracker::shared().track(id.clone(), child, udd.clone(), super::ExitHook::Local, Vec::new(), None); tokio::time::timeout(std::time::Duration::from_secs(20), async { while super::Tracker::shared().is_running(&id) { tokio::time::sleep(std::time::Duration::from_millis(20)).await; @@ -879,10 +881,10 @@ mod tests { let t = super::Tracker::shared(); let first = tokio::process::Command::new("sleep").arg("60").spawn().unwrap(); let first_pid = first.id().unwrap(); - t.track(id.clone(), first, a.clone(), super::ExitHook::Temporary, Vec::new()); + t.track(id.clone(), first, a.clone(), super::ExitHook::Temporary, Vec::new(), None); let second = tokio::process::Command::new("sleep").arg("60").spawn().unwrap(); let second_pid = second.id().unwrap(); - t.track(id.clone(), second, b.clone(), super::ExitHook::Temporary, Vec::new()); + t.track(id.clone(), second, b.clone(), super::ExitHook::Temporary, Vec::new(), None); for _ in 0..100 { if !pid_alive(first_pid) { break; diff --git a/src-tauri/src/psapi.rs b/src-tauri/src/psapi.rs index 958455f0f..2028bc152 100644 --- a/src-tauri/src/psapi.rs +++ b/src-tauri/src/psapi.rs @@ -186,6 +186,7 @@ pub async fn import_order_proxies(t: &crate::space::Ticket, order_id: i64, kind: password: s(&it, "password"), country: String::new(), notes: format!("ProxyShard order {order_id}"), + vless: None, }); } @@ -417,6 +418,7 @@ pub async fn residential_proxy(req: ResiRequest<'_>) -> Result { .map(|c| c.trim().to_uppercase()) .unwrap_or_default(), notes: format!("ProxyShard residential ({plan})"), + vless: None, }) } diff --git a/src-tauri/src/runner.rs b/src-tauri/src/runner.rs index 56c6d70e1..9fc52345e 100644 --- a/src-tauri/src/runner.rs +++ b/src-tauri/src/runner.rs @@ -1453,8 +1453,8 @@ async fn run_block( // call that leaves on the host address beside a browser that did // not is two visitors, and the site can see both. let via = param(p, "via").unwrap_or("profile"); - let proxy = match via { - "host" => None, + let (proxy, _vless_lease) = match via { + "host" => (None, None), "profile" if !bound.id.is_empty() => { run.space.still()?; let stored = profile::load_raw(&bound.id)?; @@ -1465,12 +1465,25 @@ async fn run_block( .and_then(|id| proxy::get(id).ok().flatten()) .or(stored.meta.inline_proxy); match bound_proxy { - Some(pr) => Some(pr.to_proxy_server_arg()), - None => None, + Some(pr) => { + let (resolved, lease) = proxy::resolve_transport(&pr).await?; + (Some(resolved.to_proxy_server_arg()), lease) + } + None => (None, None), + } + } + "profile" => (None, None), + other => { + let expanded = expand(other, vars); + if expanded.trim_start().to_ascii_lowercase().starts_with("vless://") { + let pr = proxy::parse_single(&expanded) + .context("invalid VLESS proxy URI in http.request")?; + let (resolved, lease) = proxy::resolve_transport(&pr).await?; + (Some(resolved.to_proxy_server_arg()), lease) + } else { + (Some(expanded), None) } } - "profile" => None, - other => Some(expand(other, vars)), }; let out = crate::requests::send(crate::requests::Request { diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index 391cba66b..dba6bef59 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -8,6 +8,9 @@ use std::sync::Mutex; pub struct Settings { /// Absolute path to the ShardX executable. pub browser_path: Option, + /// Optional path to a custom Xray-core executable for VLESS proxies. + #[serde(default)] + pub xray_path: Option, /// Theme: "dark" (default) or "light". #[serde(default = "default_theme")] pub theme: String, @@ -108,6 +111,7 @@ static LOAD_ERROR: Mutex> = Mutex::new(None); fn defaults() -> Settings { Settings { browser_path: None, + xray_path: None, theme: default_theme(), geo_checker: Some("ip-api.com".into()), geo_custom_url: None, diff --git a/src-tauri/src/space/client.rs b/src-tauri/src/space/client.rs index d2fc9e085..1f063abce 100644 --- a/src-tauri/src/space/client.rs +++ b/src-tauri/src/space/client.rs @@ -1486,7 +1486,7 @@ mod tests { } /// Files that talk HTTP or open sockets for something other than a team. - const OTHER_TRAFFIC: [(&str, &str); 11] = [ + const OTHER_TRAFFIC: [(&str, &str); 12] = [ ("process/close.rs", "Stop's Browser.close on a launched browser's own devtools"), ("live_e2e.rs", "the live end-to-end harness, run by hand: a test site, a proxy, CDP, the server raw"), ("runtime.rs", "engine and launcher downloads"), @@ -1498,6 +1498,7 @@ mod tests { ("space/local/proxy.rs", "proxy checks"), ("space/local/extensions.rs", "extension downloads"), ("space/local/extensions/widevine.rs", "the Widevine CDM from Google's component updater"), + ("vless.rs", "downloads Xray-core from GitHub and connects to the local Xray bridge"), ]; const TALKS: [&str; 6] = ["reqwest", "tungstenite", "wreq", "TcpStream::connect", "hyper", "rustls"]; diff --git a/src-tauri/src/space/doors.rs b/src-tauri/src/space/doors.rs index c553fb437..d755c2a92 100644 --- a/src-tauri/src/space/doors.rs +++ b/src-tauri/src/space/doors.rs @@ -268,6 +268,8 @@ const RULES: &[(&str, Need)] = &[ ("proxy_bulk_import", CREATE_T), ("proxy_bulk_save", CREATE_T), ("proxy_bulk_parse", Machine), + ("vless_status", Machine), + ("vless_ensure", Machine), // #162: the change-IP link is this computer's; using it moves the exit for // everyone on the proxy, so that needs Edit. ("proxy_rotation_ids", Machine), diff --git a/src-tauri/src/space/local/extensions.rs b/src-tauri/src/space/local/extensions.rs index b1f47572c..01b428106 100644 --- a/src-tauri/src/space/local/extensions.rs +++ b/src-tauri/src/space/local/extensions.rs @@ -490,13 +490,13 @@ pub(crate) fn store_proxy_chosen() -> bool { /// A client for `url` through the proxy chosen for the Web Store (#154), never /// straight from this computer. A loopback address (tests, a local mirror) goes direct. -fn store_client(url: &str, ua: &str) -> std::result::Result { +async fn store_client(url: &str, ua: &str) -> std::result::Result<(reqwest::ClientBuilder, Option), String> { let builder = reqwest::Client::builder().user_agent(ua); let loopback = url::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_string)).is_some_and(|h| { h == "localhost" || h.trim_matches(['[', ']']).parse::().is_ok_and(|ip| ip.is_loopback()) }); if loopback { - return Ok(builder.no_proxy()); + return Ok((builder.no_proxy(), None)); } let id = crate::settings::load().ok().and_then(|s| s.store_proxy).filter(|id| !id.trim().is_empty()); let id = id.ok_or_else(|| NO_STORE_PROXY.to_string())?; @@ -505,8 +505,9 @@ fn store_client(url: &str, ua: &str) -> std::result::Result Result<()> { use tokio::io::AsyncWriteExt; - let client = store_client(url, ua) - .map_err(|e| anyhow::anyhow!(e))? + let (builder, _vless_lease) = store_client(url, ua) + .await + .map_err(|e| anyhow::anyhow!(e))?; + let client = builder .connect_timeout(std::time::Duration::from_secs(10)) .build()?; let resp = tokio::time::timeout(STALL, client.get(url).send()) @@ -577,7 +580,8 @@ pub(in crate::space) async fn get_small(url: &str, ua: &str, timeout: std::time: format!("could not reach the Web Store: {e}") } }; - let client = store_client(url, ua)? + let (builder, _vless_lease) = store_client(url, ua).await?; + let client = builder .connect_timeout(std::time::Duration::from_secs(10).min(timeout)) .timeout(timeout) .build() diff --git a/src-tauri/src/space/local/extensions/usage/tests.rs b/src-tauri/src/space/local/extensions/usage/tests.rs index 8d58b4383..a61c449f1 100644 --- a/src-tauri/src/space/local/extensions/usage/tests.rs +++ b/src-tauri/src/space/local/extensions/usage/tests.rs @@ -94,7 +94,7 @@ async fn a_running_profile_defers_the_swap_and_its_close_lets_it_in() { std::fs::create_dir_all(&udd).unwrap(); let child = tokio::process::Command::new("sleep").arg("30").spawn().unwrap(); let tracker = crate::process::Tracker::shared(); - tracker.track(profile.clone(), child, udd, crate::process::ExitHook::Local, vec![id.clone()]); + tracker.track(profile.clone(), child, udd, crate::process::ExitHook::Local, vec![id.clone()], None); let out = try_apply(&Tracked, &l.lib, &id, &Ops::quick()).unwrap(); assert_eq!(out, Outcome::Deferred { profiles: vec![profile.clone()] }); diff --git a/src-tauri/src/space/local/extensions/widevine.rs b/src-tauri/src/space/local/extensions/widevine.rs index 0c1ddc9e0..8c87a97ad 100644 --- a/src-tauri/src/space/local/extensions/widevine.rs +++ b/src-tauri/src/space/local/extensions/widevine.rs @@ -190,7 +190,14 @@ fn client(proxy: Option<&ProxyEntry>, chrome: &str) -> Result { /// Fetches the current CDM into `cache` when the server has a newer one than /// `have`. Returns the version put there, or None when `have` is current. pub async fn fetch(proxy: Option<&ProxyEntry>, chrome: &str, have: Option<&str>, cache: &Path, background: bool) -> Result> { - let client = client(proxy, chrome)?; + let (local_proxy, _vless_lease) = match proxy { + Some(p) => { + let (resolved, lease) = crate::space::proxy::resolve_transport(p).await?; + (Some(resolved), lease) + } + None => (None, None), + }; + let client = client(local_proxy.as_ref(), chrome)?; let resp = client .post(UPDATE_URL) .header("Content-Type", "application/json") diff --git a/src-tauri/src/space/local/proxy.rs b/src-tauri/src/space/local/proxy.rs index c20e6eefb..c5a208a10 100644 --- a/src-tauri/src/space/local/proxy.rs +++ b/src-tauri/src/space/local/proxy.rs @@ -12,6 +12,105 @@ pub enum ProxyKind { Socks5, Http, Https, + Vless, +} + +fn is_false(b: &bool) -> bool { + !*b +} + +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +pub struct VlessConfig { + #[serde(default, skip_serializing_if = "String::is_empty")] + pub encryption: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub flow: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub network: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub security: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub sni: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub fingerprint: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub public_key: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub short_id: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub spider_x: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub pqv: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub alpn: String, + #[serde(default, skip_serializing_if = "is_false")] + pub allow_insecure: bool, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub host_header: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub path: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub service_name: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub authority: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub mode: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub header_type: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub seed: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub extra: String, +} + +impl VlessConfig { + pub fn normalized(&self) -> Self { + let enc_trimmed = self.encryption.trim(); + let encryption = if enc_trimmed.is_empty() || enc_trimmed.eq_ignore_ascii_case("none") { + "none".to_string() + } else { + enc_trimmed.to_string() + }; + let network = match self.network.trim().to_ascii_lowercase().as_str() { + "" | "raw" => "tcp".to_string(), + "splithttp" => "xhttp".to_string(), + "h2" => "http".to_string(), + other => other.to_string(), + }; + let security = match self.security.trim().to_ascii_lowercase().as_str() { + "" => "none".to_string(), + other => other.to_string(), + }; + let alpn = self + .alpn + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect::>() + .join(","); + Self { + encryption, + flow: self.flow.trim().to_string(), + network, + security, + sni: self.sni.trim().to_string(), + fingerprint: self.fingerprint.trim().to_ascii_lowercase(), + public_key: self.public_key.trim().to_string(), + short_id: self.short_id.trim().to_string(), + spider_x: self.spider_x.trim().to_string(), + pqv: self.pqv.trim().to_string(), + alpn, + allow_insecure: self.allow_insecure, + host_header: self.host_header.trim().to_string(), + path: self.path.trim().to_string(), + service_name: self.service_name.trim().to_string(), + authority: self.authority.trim().to_string(), + mode: self.mode.trim().to_ascii_lowercase(), + header_type: self.header_type.trim().to_ascii_lowercase(), + seed: self.seed.trim().to_string(), + extra: self.extra.trim().to_string(), + } + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -32,20 +131,86 @@ pub struct ProxyEntry { /// Free-form note. #[serde(default)] pub notes: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vless: Option, } impl ProxyEntry { - /// The same proxy as `other`: one kind, host, port, user and password. + /// The same proxy as `other`: one kind, host, port, user and password + /// (plus normalized VLESS settings when `kind` is `Vless`). /// The password counts: providers that carry a session or routing /// parameters in it (a sticky session, a country) serve different exits /// from one host, port and user, so those are different proxies. Only an /// identical one is skipped on import. pub fn same_proxy(&self, other: &ProxyEntry) -> bool { - self.kind == other.kind + let base = self.kind == other.kind && self.host == other.host && self.port == other.port && self.username == other.username - && self.password == other.password + && self.password == other.password; + if !base { + return false; + } + if matches!(self.kind, ProxyKind::Vless) { + self.vless.clone().unwrap_or_default().normalized() + == other.vless.clone().unwrap_or_default().normalized() + } else { + true + } + } + + /// Encode this VLESS proxy into a standard `vless://` share link. + pub fn to_vless_uri(&self) -> String { + let cfg = self.vless.clone().unwrap_or_default().normalized(); + let host = if self.host.contains(':') && !self.host.starts_with('[') { + format!("[{}]", self.host) + } else { + self.host.clone() + }; + let mut params: Vec = Vec::new(); + let mut push_kv = |k: &str, v: &str| { + if !v.is_empty() { + params.push(format!("{k}={}", percent_encode_userinfo(v))); + } + }; + push_kv("encryption", &cfg.encryption); + push_kv("security", &cfg.security); + push_kv("type", &cfg.network); + push_kv("flow", &cfg.flow); + push_kv("sni", &cfg.sni); + push_kv("fp", &cfg.fingerprint); + push_kv("pbk", &cfg.public_key); + push_kv("sid", &cfg.short_id); + push_kv("spx", &cfg.spider_x); + push_kv("pqv", &cfg.pqv); + push_kv("alpn", &cfg.alpn); + if cfg.allow_insecure { + push_kv("allowInsecure", "1"); + } + push_kv("host", &cfg.host_header); + push_kv("path", &cfg.path); + push_kv("serviceName", &cfg.service_name); + push_kv("authority", &cfg.authority); + push_kv("mode", &cfg.mode); + push_kv("headerType", &cfg.header_type); + push_kv("seed", &cfg.seed); + push_kv("extra", &cfg.extra); + + let mut uri = format!( + "vless://{}@{}:{}", + percent_encode_userinfo(&self.username), + host, + self.port + ); + if !params.is_empty() { + uri.push('?'); + uri.push_str(¶ms.join("&")); + } + if !self.name.is_empty() && self.name != format!("{}:{}", self.host, self.port) { + uri.push('#'); + uri.push_str(&percent_encode_userinfo(&self.name)); + } + uri } /// Build `--proxy-server=://[user:pass@]host:port` for ShardX. @@ -54,6 +219,7 @@ impl ProxyEntry { ProxyKind::Socks5 => "socks5", ProxyKind::Http => "http", ProxyKind::Https => "https", + ProxyKind::Vless => return self.to_vless_uri(), }; let host_port = format!("{}:{}", self.host, self.port); if self.username.is_empty() && self.password.is_empty() { @@ -195,6 +361,7 @@ pub(in crate::space) fn upsert_for_binding(mut entry: ProxyEntry, bound_id: Opti if let Some(slot) = s.proxies.iter_mut().find(|p| { p.id == bound && p.kind == entry.kind + && !matches!(entry.kind, ProxyKind::Vless) && p.host == entry.host && p.port == entry.port && p.username == entry.username @@ -350,6 +517,18 @@ where Ok(()) } +pub async fn resolve_transport(entry: &ProxyEntry) -> Result<(ProxyEntry, Option)> { + if matches!(entry.kind, ProxyKind::Vless) { + let lease = crate::vless::acquire(entry).await?; + let mut local = lease.local_socks5(); + local.id = entry.id.clone(); + local.country = entry.country.clone(); + Ok((local, Some(lease))) + } else { + Ok((entry.clone(), None)) + } +} + /// SOCKS5/HTTP CONNECT probe; returns RTT in ms on success. /// /// The handshake alone proves only that the proxy let us in. A gateway whose @@ -358,6 +537,11 @@ where /// call such a proxy reachable. Every kind now ends with a real CONNECT to /// `PROBE_HOST`, and only the answer to that decides. pub async fn probe(entry: &ProxyEntry) -> Result { + let (effective, _lease) = resolve_transport(entry).await?; + probe_direct(&effective).await +} + +async fn probe_direct(entry: &ProxyEntry) -> Result { // One deadline over the whole exchange as well as one per step. A proxy // that answers every read just inside the step timeout could otherwise // string them together and hold a test slot far longer than any of them. @@ -391,6 +575,9 @@ async fn probe_inner(entry: &ProxyEntry) -> Result { } return Ok(started.elapsed().as_millis()); } + if matches!(entry.kind, ProxyKind::Vless) { + anyhow::bail!("VLESS proxy must be bridged before probing"); + } let started = Instant::now(); let addr = format!("{}:{}", entry.host, entry.port); @@ -472,6 +659,7 @@ async fn probe_inner(entry: &ProxyEntry) -> Result { anyhow::bail!("CONNECT failed: {first_line}"); } } + ProxyKind::Vless => unreachable!("handled above"), } Ok(started.elapsed().as_millis()) } @@ -479,7 +667,8 @@ async fn probe_inner(entry: &ProxyEntry) -> Result { // ---- Bulk import ---- // // Accepted: socks5://user:pass@host:port, user:pass@host:port, host:port:user:pass, -// host:port@user:pass, host:port. A trailing `#` is the proxy's name +// host:port@user:pass, host:port, vless://uuid@host:port?params#name, +// or base64-encoded VLESS subscriptions. A trailing `#` is the proxy's name // (`#facebook`); `country=X` and `note=Y` there are still read, for // lines exported by older builds, but the country a proxy reports is // filled in by its test. Whole-line `#` comments are skipped. @@ -490,9 +679,38 @@ pub fn parse_single(line: &str) -> Option { parse_one(line.trim(), &ProxyKind::Socks5) } +fn maybe_decode_vless_subscription(text: &str) -> Option { + use base64::{ + engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD}, + Engine as _, + }; + let trimmed = text.trim(); + if trimmed.is_empty() || trimmed.contains("://") || trimmed.contains(':') { + return None; + } + let compact: String = trimmed.chars().filter(|c| !c.is_whitespace()).collect(); + if compact.len() < 12 { + return None; + } + let bytes = STANDARD + .decode(&compact) + .or_else(|_| STANDARD_NO_PAD.decode(&compact)) + .or_else(|_| URL_SAFE.decode(&compact)) + .or_else(|_| URL_SAFE_NO_PAD.decode(&compact)) + .ok()?; + let decoded = String::from_utf8(bytes).ok()?; + if decoded.to_ascii_lowercase().contains("vless://") { + Some(decoded) + } else { + None + } +} + pub fn parse_bulk(text: &str, default_kind: ProxyKind) -> Vec { + let decoded = maybe_decode_vless_subscription(text); + let source = decoded.as_deref().unwrap_or(text); let mut out = Vec::new(); - for raw in text.lines() { + for raw in source.lines() { let line = raw.trim(); if line.is_empty() || line.starts_with('#') { continue; @@ -504,7 +722,109 @@ pub fn parse_bulk(text: &str, default_kind: ProxyKind) -> Vec { out } +pub fn parse_vless_uri(raw: &str) -> Option { + let trimmed = raw.trim(); + if !trimmed + .get(..8) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("vless://")) + { + return None; + } + let body = &trimmed[8..]; + let (before_frag, frag) = match body.find('#') { + Some(i) => (&body[..i], Some(body[i + 1..].trim())), + None => (body, None), + }; + let (authority, query) = match before_frag.find('?') { + Some(i) => (&before_frag[..i], Some(&before_frag[i + 1..])), + None => (before_frag, None), + }; + let (uuid_raw, hostport_raw) = authority.rsplit_once('@')?; + let uuid = percent_decode_userinfo(uuid_raw).trim().to_string(); + if uuid.is_empty() { + return None; + } + let hostport = hostport_raw.trim().trim_end_matches('/'); + let (host, port) = if let Some(rest) = hostport.strip_prefix('[') { + let end = rest.find(']')?; + let h = &rest[..end]; + let p_str = rest[end + 1..].strip_prefix(':')?; + (h.trim(), p_str.trim().parse::().ok()?) + } else { + let (h, p_str) = hostport.rsplit_once(':')?; + (h.trim(), p_str.trim().parse::().ok()?) + }; + if host.is_empty() || port == 0 || host.chars().any(char::is_whitespace) { + return None; + } + + let mut cfg = VlessConfig::default(); + if let Some(q) = query { + for pair in q.split('&') { + if pair.is_empty() { + continue; + } + let (k, v) = pair.split_once('=').unwrap_or((pair, "")); + let val = percent_decode_userinfo(v); + match k.trim().to_ascii_lowercase().as_str() { + "encryption" => cfg.encryption = val, + "flow" => cfg.flow = val, + "type" | "net" | "method" => cfg.network = val, + "security" => cfg.security = val, + "sni" | "peer" => cfg.sni = val, + "fp" => cfg.fingerprint = val, + "pbk" => cfg.public_key = val, + "sid" => cfg.short_id = val, + "spx" => cfg.spider_x = val, + "pqv" => cfg.pqv = val, + "alpn" => cfg.alpn = val, + "allowinsecure" | "insecure" => { + cfg.allow_insecure = val == "1" || val.eq_ignore_ascii_case("true"); + } + "host" => cfg.host_header = val, + "path" => cfg.path = val, + "servicename" => cfg.service_name = val, + "authority" => cfg.authority = val, + "mode" => cfg.mode = val, + "headertype" => cfg.header_type = val, + "seed" => cfg.seed = val, + "extra" => cfg.extra = val, + _ => {} + } + } + } + + let name = frag + .map(|f| percent_decode_userinfo(f).trim().to_string()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| format!("{host}:{port}")); + + Some(ProxyEntry { + id: uuid::Uuid::new_v4().to_string(), + name, + kind: ProxyKind::Vless, + host: host.to_string(), + port, + username: uuid, + password: String::new(), + country: String::new(), + notes: String::new(), + vless: Some(cfg.normalized()), + }) +} + fn parse_one(line: &str, default_kind: &ProxyKind) -> Option { + if line + .get(..8) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("vless://")) + { + return parse_vless_uri(line); + } + if matches!(default_kind, ProxyKind::Vless) && !line.contains("://") && line.contains('@') { + if let Some(p) = parse_vless_uri(&format!("vless://{line}")) { + return Some(p); + } + } // Optional trailing `# country=US note=foo`. let (main, comment) = match line.find('#') { Some(i) => (line[..i].trim(), Some(line[i + 1..].trim())), @@ -574,6 +894,7 @@ fn parse_one(line: &str, default_kind: &ProxyKind) -> Option { password: pass, country, notes, + vless: None, }) } @@ -675,6 +996,11 @@ pub async fn can_send_udp_directly() -> bool { } pub async fn probe_udp(entry: &ProxyEntry) -> Result { + let (effective, _lease) = resolve_transport(entry).await?; + probe_udp_direct(&effective).await +} + +async fn probe_udp_direct(entry: &ProxyEntry) -> Result { tokio::time::timeout(TEST_DEADLINE, probe_udp_inner(entry)) .await .map_err(|_| anyhow::anyhow!("the proxy did not finish the UDP exchange in time"))? @@ -910,6 +1236,7 @@ pub struct ChangeIp { /// little after it answers. A refusal is reported, not retried — rotation is /// rate-limited. pub(in crate::space) async fn change_ip(entry: &ProxyEntry, url: &str, before: Option) -> Result { + let (effective, _lease) = resolve_transport(entry).await?; let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(20)) .connect_timeout(std::time::Duration::from_secs(8)) @@ -928,7 +1255,7 @@ pub(in crate::space) async fn change_ip(entry: &ProxyEntry, url: &str, before: O let mut after = None; for _ in 0..8 { tokio::time::sleep(std::time::Duration::from_secs(3)).await; - if let Ok(geo) = geo_check(entry, None).await { + if let Ok(geo) = geo_check_via_direct(Some(&effective), None).await { let moved = before.as_deref().map_or(true, |b| b != geo.ip); after = Some(geo); if moved { @@ -950,6 +1277,7 @@ pub(in crate::space) fn reqwest_proxy(entry: &ProxyEntry) -> Result "socks5h", ProxyKind::Http => "http", ProxyKind::Https => "https", + ProxyKind::Vless => anyhow::bail!("VLESS proxy must be bridged before HTTP client use"), }; let proxy_url = if entry.username.is_empty() && entry.password.is_empty() { format!("{scheme}://{}:{}", entry.host, entry.port) @@ -1045,6 +1373,17 @@ fn parse_any_geo(text: &str, provider: &str) -> Result { /// Probe geo through `entry` if Some, else direct. Tries the chosen provider, /// then the others; the error carries what each one said. pub async fn geo_check_via(entry: Option<&ProxyEntry>, provider_override: Option) -> Result { + let (effective_owned, _lease) = match entry { + Some(e) if matches!(e.kind, ProxyKind::Vless) => { + let (local, lease) = resolve_transport(e).await?; + (Some(local), lease) + } + _ => (None, None), + }; + geo_check_via_direct(effective_owned.as_ref().or(entry), provider_override).await +} + +async fn geo_check_via_direct(entry: Option<&ProxyEntry>, provider_override: Option) -> Result { let chosen = provider_override .filter(|s| !s.is_empty()) .unwrap_or_else(|| settings::load().ok().and_then(|s| s.geo_checker).unwrap_or_else(|| "ip-api.com".into())); @@ -1449,10 +1788,33 @@ pub(in crate::space) async fn full_test(entry: &ProxyEntry) -> Result TestSnapshot { let now = unix_now(); + let (effective, _lease) = match resolve_transport(entry).await { + Ok(v) => v, + Err(e) => { + return TestSnapshot { + first_seen: String::new(), + last_seen: now, + ip: String::new(), + country_code: String::new(), + country: String::new(), + region: String::new(), + city: String::new(), + isp: String::new(), + timezone: String::new(), + latitude: 0.0, + longitude: 0.0, + tcp_ms: None, + udp_ms: None, + udp_error: None, + geo_error: Some(format!("VLESS tunnel failed: {e:#}")), + provider: String::new(), + }; + } + }; let udp_fut = async { - if matches!(entry.kind, ProxyKind::Socks5) { - Some(probe_udp(entry).await) + if matches!(effective.kind, ProxyKind::Socks5) { + Some(probe_udp_direct(&effective).await) } else { None } @@ -1461,11 +1823,11 @@ pub(in crate::space) async fn measure(entry: &ProxyEntry) -> TestSnapshot { // else still shows how long a round trip through it takes. let geo_fut = async { let started = std::time::Instant::now(); - let res = geo_check(entry, None).await; + let res = geo_check_via_direct(Some(&effective), None).await; (res, started.elapsed().as_millis()) }; let (tcp_res, udp_res, (geo_res, geo_ms)) = - tokio::join!(probe(entry), udp_fut, geo_fut); + tokio::join!(probe_direct(&effective), udp_fut, geo_fut); // An answer from a geo service IS the proxy working: the request went out // through it and came back. So its address is kept whenever it arrived, @@ -1793,4 +2155,60 @@ mod tests { assert_eq!((g.ip.as_str(), g.country_code.as_str()), ("9.9.9.9", "")); assert!(parse_any_geo("blocked", "custom").is_err()); } + + #[test] + fn parses_vless_reality_ws_xhttp_ipv6_and_preserves_plus() { + let link = "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?encryption=none&security=reality&type=tcp&flow=xtls-rprx-vision&sni=www.cloudflare.com&fp=chrome&pbk=AbC+dEf/123=&sid=0a1b2c&spx=%2Fsearch%3Fq%3D1&pqv=pq+key%3D1#NL%20Node%201"; + let p = parse_single(link).expect("parses vless reality"); + assert_eq!(p.kind, ProxyKind::Vless); + assert_eq!(p.host, "198.51.100.10"); + assert_eq!(p.port, 443); + assert_eq!(p.username, "11111111-2222-3333-4444-555555555555"); + assert_eq!(p.password, ""); + assert_eq!(p.name, "NL Node 1"); + let cfg = p.vless.as_ref().unwrap(); + assert_eq!(cfg.security, "reality"); + assert_eq!(cfg.network, "tcp"); + assert_eq!(cfg.flow, "xtls-rprx-vision"); + assert_eq!(cfg.sni, "www.cloudflare.com"); + assert_eq!(cfg.fingerprint, "chrome"); + assert_eq!(cfg.public_key, "AbC+dEf/123="); + assert_eq!(cfg.short_id, "0a1b2c"); + assert_eq!(cfg.spider_x, "/search?q=1"); + assert_eq!(cfg.pqv, "pq+key=1"); + + // Round-trip via to_vless_uri() + let exported = p.to_vless_uri(); + let back = parse_single(&exported).expect("round-trips"); + assert!(p.same_proxy(&back)); + assert_eq!(back.name, "NL Node 1"); + + // IPv6 host + WebSocket + allowInsecure + let v6 = parse_single("vless://aaaa-bbbb@[2001:db8::1]:8443?type=ws&security=tls&sni=cdn.example.com&host=ws.example.com&path=%2Fws&allowInsecure=1#v6").expect("parses ipv6"); + assert_eq!(v6.host, "2001:db8::1"); + assert_eq!(v6.port, 8443); + assert!(v6.to_vless_uri().contains("@[2001:db8::1]:8443?")); + let v6_cfg = v6.vless.as_ref().unwrap(); + assert_eq!(v6_cfg.network, "ws"); + assert_eq!(v6_cfg.security, "tls"); + assert!(v6_cfg.allow_insecure); + + // XHTTP / SplitHTTP alias normalization + let split = parse_single("vless://u@example.com:443?type=splithttp&security=none&mode=packet-up").unwrap(); + let xhttp = parse_single("vless://u@example.com:443?type=xhttp&mode=packet-up").unwrap(); + assert!(split.same_proxy(&xhttp)); + } + + #[test] + fn parses_base64_vless_subscription_bulk() { + use base64::{engine::general_purpose::STANDARD, Engine as _}; + let raw = "vless://11111111-2222-3333-4444-555555555555@1.1.1.1:443?security=reality&pbk=pub&sni=example.com#Node1\nvless://22222222-2222-3333-4444-555555555555@2.2.2.2:443?type=ws&security=tls&sni=ws.example.com#Node2"; + let sub = STANDARD.encode(raw.as_bytes()); + let parsed = parse_bulk(&sub, ProxyKind::Socks5); + assert_eq!(parsed.len(), 2); + assert_eq!(parsed[0].kind, ProxyKind::Vless); + assert_eq!(parsed[0].name, "Node1"); + assert_eq!(parsed[1].host, "2.2.2.2"); + assert_eq!(parsed[1].name, "Node2"); + } } diff --git a/src-tauri/src/space/mod.rs b/src-tauri/src/space/mod.rs index d3122ea6d..b9149489b 100644 --- a/src-tauri/src/space/mod.rs +++ b/src-tauri/src/space/mod.rs @@ -684,8 +684,8 @@ pub mod proxy { pub use local::{ can_send_udp_directly, country_to_locale, country_to_timezone, geo_check, geo_check_via, - parse_bulk, parse_single, probe, probe_udp, rotation_get, rotation_ids, rotation_set, ChangeIp, - GeoInfo, ProxyEntry, ProxyKind, TestSnapshot, + parse_bulk, parse_single, probe, probe_udp, resolve_transport, rotation_get, rotation_ids, + rotation_set, ChangeIp, GeoInfo, ProxyEntry, ProxyKind, TestSnapshot, VlessConfig, }; /// Opens `id`'s change-IP link and reads the new exit (#162); the proxy's diff --git a/src-tauri/src/space/remote.rs b/src-tauri/src/space/remote.rs index d525e342e..ef4bf87db 100644 --- a/src-tauri/src/space/remote.rs +++ b/src-tauri/src/space/remote.rs @@ -195,6 +195,7 @@ fn kind(raw: &str) -> Option { "socks5" => Some(ProxyKind::Socks5), "http" => Some(ProxyKind::Http), "https" => Some(ProxyKind::Https), + "vless" => Some(ProxyKind::Vless), _ => None, } } @@ -218,6 +219,7 @@ pub fn proxy(row: &ProxyRow, login: Option<&str>) -> ProxyEntry { password: String::new(), country: String::new(), notes: String::new(), + vless: None, }); e.id = row.id.clone(); e.name = row.name.clone(); diff --git a/src-tauri/src/vless.rs b/src-tauri/src/vless.rs new file mode 100644 index 000000000..7ee31c4ba --- /dev/null +++ b/src-tauri/src/vless.rs @@ -0,0 +1,1190 @@ +//! Managed Xray-core VLESS bridge: resolves or downloads Xray-core and +//! runs refcounted local SOCKS5 tunnels (`127.0.0.1:`, TCP + UDP) for +//! `ProxyKind::Vless` entries. + +use crate::space::proxy::{ProxyEntry, ProxyKind, VlessConfig}; +use crate::{settings, store}; +use anyhow::{bail, Context, Result}; +use serde::Serialize; +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::process::Command; + +const XRAY_RELEASE_API: &str = "https://api.github.com/repos/XTLS/Xray-core/releases/latest"; +const XRAY_FALLBACK_TAG: &str = "v26.11.9"; + +#[cfg(target_os = "windows")] +const XRAY_BIN_NAME: &str = "xray.exe"; +#[cfg(not(target_os = "windows"))] +const XRAY_BIN_NAME: &str = "xray"; + +#[derive(Debug, Clone, Serialize)] +pub struct VlessStatus { + pub installed: bool, + pub path: Option, + pub version: Option, +} + +fn xray_install_dir() -> Result { + Ok(store::local_root()?.join("xray")) +} + +fn cached_xray_path() -> Result { + Ok(xray_install_dir()?.join(XRAY_BIN_NAME)) +} + +fn find_in_path(bin: &str) -> Option { + let paths = std::env::var_os("PATH")?; + for dir in std::env::split_paths(&paths) { + let candidate = dir.join(bin); + if candidate.is_file() { + return Some(candidate); + } + } + None +} + +/// Resolve an already-present Xray binary (Settings override -> local cache -> PATH). +pub fn resolve_existing_xray() -> Option { + if let Ok(Some(configured)) = settings::load().map(|s| s.xray_path) { + let trimmed = configured.trim(); + if !trimmed.is_empty() { + let p = PathBuf::from(trimmed); + if p.is_file() { + return Some(p); + } + } + } + if let Ok(cached) = cached_xray_path() { + if cached.is_file() { + return Some(cached); + } + } + find_in_path(XRAY_BIN_NAME) +} + +fn read_xray_version(bin: &Path) -> Option { + let mut cmd = std::process::Command::new(bin); + cmd.arg("version") + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + #[cfg(target_os = "windows")] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x08000000); + } + let out = cmd.output().ok()?; + if !out.status.success() { + return None; + } + let text = String::from_utf8_lossy(&out.stdout); + let first = text.lines().next()?.trim(); + if first.is_empty() { + None + } else { + Some(first.to_string()) + } +} + +pub fn status() -> VlessStatus { + match resolve_existing_xray() { + Some(path) => { + let version = read_xray_version(&path); + VlessStatus { + installed: true, + path: Some(path.display().to_string()), + version, + } + } + None => VlessStatus { + installed: false, + path: None, + version: None, + }, + } +} + +fn host_asset_name() -> Result<&'static str> { + #[cfg(all(target_os = "windows", target_arch = "x86_64"))] + return Ok("Xray-windows-64.zip"); + #[cfg(all(target_os = "windows", target_arch = "aarch64"))] + return Ok("Xray-windows-arm64-v8a.zip"); + #[cfg(all(target_os = "macos", target_arch = "x86_64"))] + return Ok("Xray-macos-64.zip"); + #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + return Ok("Xray-macos-arm64-v8a.zip"); + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + return Ok("Xray-linux-64.zip"); + #[cfg(all(target_os = "linux", target_arch = "aarch64"))] + return Ok("Xray-linux-arm64-v8a.zip"); + #[allow(unreachable_code)] + Err(anyhow::anyhow!( + "VLESS Xray-core auto-download is not supported on this OS/architecture; set xray_path in Settings" + )) +} + +async fn resolve_download_url(client: &reqwest::Client, asset_name: &str) -> String { + if let Ok(resp) = client + .get(XRAY_RELEASE_API) + .timeout(std::time::Duration::from_secs(10)) + .send() + .await + { + if resp.status().is_success() { + if let Ok(json) = resp.json::().await { + if let Some(assets) = json.get("assets").and_then(|v| v.as_array()) { + for asset in assets { + let name = asset.get("name").and_then(|v| v.as_str()); + let url = asset.get("browser_download_url").and_then(|v| v.as_str()); + if name == Some(asset_name) { + if let Some(url) = url { + return url.to_string(); + } + } + } + } + if let Some(tag) = json.get("tag_name").and_then(|v| v.as_str()) { + return format!( + "https://github.com/XTLS/Xray-core/releases/download/{tag}/{asset_name}" + ); + } + } + } + } + format!( + "https://github.com/XTLS/Xray-core/releases/download/{XRAY_FALLBACK_TAG}/{asset_name}" + ) +} + +fn extract_xray_from_zip(zip_bytes: &[u8], dest: &Path) -> Result<()> { + let reader = std::io::Cursor::new(zip_bytes); + let mut archive = zip::ZipArchive::new(reader).context("open Xray-core zip archive")?; + for i in 0..archive.len() { + let mut file = archive.by_index(i)?; + if file.is_dir() { + continue; + } + let name = file.name(); + let file_name = Path::new(name) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(""); + if file_name.eq_ignore_ascii_case(XRAY_BIN_NAME) { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + let staging = dest.with_extension("incoming"); + let _ = std::fs::remove_file(&staging); + { + let mut out = std::fs::File::create(&staging) + .with_context(|| format!("create {}", staging.display()))?; + let mut buf = [0u8; 64 * 1024]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + out.write_all(&buf[..n])?; + } + out.sync_all()?; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o755))?; + } + if dest.exists() { + let _ = std::fs::remove_file(dest); + } + std::fs::rename(&staging, dest) + .with_context(|| format!("install Xray-core to {}", dest.display()))?; + return Ok(()); + } + } + bail!("Xray-core archive did not contain {XRAY_BIN_NAME}") +} + +/// Ensure Xray-core is installed locally, downloading it from GitHub Releases if absent. +pub async fn ensure_xray_binary() -> Result { + if let Some(existing) = resolve_existing_xray() { + return Ok(existing); + } + + static DOWNLOAD_LOCK: OnceLock> = OnceLock::new(); + let _guard = DOWNLOAD_LOCK + .get_or_init(|| tokio::sync::Mutex::new(())) + .lock() + .await; + + if let Some(existing) = resolve_existing_xray() { + return Ok(existing); + } + + let asset_name = host_asset_name()?; + let dest = cached_xray_path()?; + let client = reqwest::Client::builder() + .user_agent("ShardBrowser") + .no_proxy() + .connect_timeout(std::time::Duration::from_secs(15)) + .timeout(std::time::Duration::from_secs(180)) + .build()?; + + let url = resolve_download_url(&client, asset_name).await; + eprintln!("[vless] downloading Xray-core from {url}"); + let resp = client + .get(&url) + .send() + .await + .with_context(|| format!("download Xray-core from {url}"))? + .error_for_status() + .with_context(|| format!("Xray-core release download failed ({url})"))?; + let bytes = resp.bytes().await.context("read Xray-core download stream")?; + let dest_clone = dest.clone(); + tokio::task::spawn_blocking(move || extract_xray_from_zip(&bytes, &dest_clone)) + .await + .context("extract Xray-core task panicked")??; + eprintln!("[vless] Xray-core installed at {}", dest.display()); + Ok(dest) +} + +fn split_alpn(raw: &str) -> Vec { + raw.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect() +} + +/// Build an isolated Xray-core JSON configuration that exposes a local SOCKS5 +/// listener (TCP + UDP) forwarding exclusively through the VLESS outbound. +/// No `freedom`/direct outbound is defined so traffic cannot leak direct. +pub fn build_xray_config(entry: &ProxyEntry, listen_port: u16) -> Result { + if !matches!(entry.kind, ProxyKind::Vless) { + bail!("expected a VLESS proxy entry"); + } + let host = entry.host.trim(); + if host.is_empty() { + bail!("VLESS proxy host is empty"); + } + if entry.port == 0 { + bail!("VLESS proxy port must be > 0"); + } + let uuid = entry.username.trim(); + if uuid.is_empty() { + bail!("VLESS proxy UUID is empty"); + } + + let cfg = entry.vless.clone().unwrap_or_default().normalized(); + + if cfg.security == "reality" { + if cfg.public_key.is_empty() { + bail!("VLESS REALITY proxy requires a public key (pbk)"); + } + if cfg.sni.is_empty() { + bail!("VLESS REALITY proxy requires an SNI (sni)"); + } + } + + let mut user = json!({ + "id": uuid, + "encryption": if cfg.encryption.is_empty() { "none" } else { cfg.encryption.as_str() }, + }); + if !cfg.flow.is_empty() { + user["flow"] = json!(cfg.flow); + } + + let network = if cfg.network.is_empty() { + "tcp" + } else { + cfg.network.as_str() + }; + let security = if cfg.security.is_empty() { + "none" + } else { + cfg.security.as_str() + }; + + let mut stream = serde_json::Map::new(); + stream.insert("network".into(), json!(network)); + stream.insert("security".into(), json!(security)); + + match security { + "none" => {} + "tls" => { + let mut tls = serde_json::Map::new(); + let sni = if !cfg.sni.is_empty() { + cfg.sni.as_str() + } else if !cfg.host_header.is_empty() { + cfg.host_header.as_str() + } else { + host + }; + tls.insert("serverName".into(), json!(sni)); + // Xray-core 26+ removed `tlsSettings.allowInsecure` (fatal startup error); + // keep `allow_insecure` in the proxy entry for share-link round-trips only. + if !cfg.fingerprint.is_empty() { + tls.insert("fingerprint".into(), json!(cfg.fingerprint)); + } + let alpn = split_alpn(&cfg.alpn); + if !alpn.is_empty() { + tls.insert("alpn".into(), json!(alpn)); + } + stream.insert("tlsSettings".into(), Value::Object(tls)); + } + "reality" => { + let fp = if cfg.fingerprint.is_empty() { + "chrome" + } else { + cfg.fingerprint.as_str() + }; + let spx = if cfg.spider_x.is_empty() { + "/" + } else { + cfg.spider_x.as_str() + }; + let mut reality = serde_json::Map::new(); + reality.insert("serverName".into(), json!(cfg.sni)); + reality.insert("fingerprint".into(), json!(fp)); + reality.insert("publicKey".into(), json!(cfg.public_key)); + reality.insert("shortId".into(), json!(cfg.short_id)); + reality.insert("spiderX".into(), json!(spx)); + if !cfg.pqv.is_empty() { + reality.insert("mldsa65Verify".into(), json!(cfg.pqv)); + } + stream.insert("realitySettings".into(), Value::Object(reality)); + } + other => bail!("unsupported VLESS security `{other}`"), + } + + match network { + "tcp" | "raw" => { + if cfg.header_type == "http" { + let mut req = serde_json::Map::new(); + if !cfg.path.is_empty() { + req.insert("path".into(), json!([cfg.path])); + } + if !cfg.host_header.is_empty() { + req.insert( + "headers".into(), + json!({ "Host": [cfg.host_header] }), + ); + } + stream.insert( + "tcpSettings".into(), + json!({ + "header": { + "type": "http", + "request": Value::Object(req), + } + }), + ); + } + } + "ws" => { + let mut ws = serde_json::Map::new(); + if !cfg.path.is_empty() { + ws.insert("path".into(), json!(cfg.path)); + } + if !cfg.host_header.is_empty() { + ws.insert("host".into(), json!(cfg.host_header)); + } + stream.insert("wsSettings".into(), Value::Object(ws)); + } + "grpc" => { + let mut grpc = serde_json::Map::new(); + if !cfg.service_name.is_empty() { + grpc.insert("serviceName".into(), json!(cfg.service_name)); + } + if !cfg.authority.is_empty() { + grpc.insert("authority".into(), json!(cfg.authority)); + } + if cfg.mode == "multi" { + grpc.insert("multiMode".into(), json!(true)); + } + stream.insert("grpcSettings".into(), Value::Object(grpc)); + } + "xhttp" | "splithttp" => { + let mut xhttp = serde_json::Map::new(); + if !cfg.path.is_empty() { + xhttp.insert("path".into(), json!(cfg.path)); + } + if !cfg.host_header.is_empty() { + xhttp.insert("host".into(), json!(cfg.host_header)); + } + if !cfg.mode.is_empty() { + xhttp.insert("mode".into(), json!(cfg.mode)); + } + if !cfg.extra.is_empty() { + let extra_val: Value = serde_json::from_str(&cfg.extra) + .context("VLESS xhttp `extra` must be valid JSON")?; + xhttp.insert("extra".into(), extra_val); + } + stream.insert("xhttpSettings".into(), Value::Object(xhttp)); + } + "httpupgrade" => { + let mut hu = serde_json::Map::new(); + if !cfg.path.is_empty() { + hu.insert("path".into(), json!(cfg.path)); + } + if !cfg.host_header.is_empty() { + hu.insert("host".into(), json!(cfg.host_header)); + } + stream.insert("httpupgradeSettings".into(), Value::Object(hu)); + } + "kcp" => { + let mut kcp = serde_json::Map::new(); + let header_type = if cfg.header_type.is_empty() { + "none" + } else { + cfg.header_type.as_str() + }; + kcp.insert("header".into(), json!({ "type": header_type })); + if !cfg.seed.is_empty() { + kcp.insert("seed".into(), json!(cfg.seed)); + } + stream.insert("kcpSettings".into(), Value::Object(kcp)); + } + "http" | "h2" => { + let mut http = serde_json::Map::new(); + if !cfg.path.is_empty() { + http.insert("path".into(), json!(cfg.path)); + } + if !cfg.host_header.is_empty() { + http.insert("host".into(), json!([cfg.host_header])); + } + stream.insert("httpSettings".into(), Value::Object(http)); + } + other => bail!("unsupported VLESS transport network `{other}`"), + } + + Ok(json!({ + "log": { + "loglevel": "warning" + }, + "inbounds": [ + { + "tag": "socks-in", + "listen": "127.0.0.1", + "port": listen_port, + "protocol": "socks", + "settings": { + "auth": "noauth", + "udp": true, + "ip": "127.0.0.1" + } + } + ], + "outbounds": [ + { + "tag": "proxy", + "protocol": "vless", + "settings": { + "vnext": [ + { + "address": host, + "port": entry.port, + "users": [user] + } + ] + }, + "streamSettings": Value::Object(stream) + } + ] + })) +} + +#[derive(Serialize)] +struct CanonicalKey<'a> { + host: &'a str, + port: u16, + uuid: &'a str, + vless: VlessConfig, +} + +fn canonical_key(entry: &ProxyEntry) -> String { + let key = CanonicalKey { + host: entry.host.trim(), + port: entry.port, + uuid: entry.username.trim(), + vless: entry.vless.clone().unwrap_or_default().normalized(), + }; + serde_json::to_string(&key).unwrap_or_else(|_| format!("{}:{}:{}", key.host, key.port, key.uuid)) +} + +struct TunnelEntry { + addr: SocketAddr, + pid: u32, + refs: Arc, + stop_tx: Option>, + dead: Arc, +} + +struct RegistryInner { + tunnels: Mutex>, + create_lock: tokio::sync::Mutex<()>, +} + +impl RegistryInner { + fn new() -> Self { + Self { + tunnels: Mutex::new(HashMap::new()), + create_lock: tokio::sync::Mutex::new(()), + } + } + + fn force_kill_pid(pid: u32) { + if pid == 0 { + return; + } + #[cfg(unix)] + { + unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }; + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + let _ = std::process::Command::new("taskkill") + .args(["/F", "/T", "/PID", &pid.to_string()]) + .creation_flags(0x08000000) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + } + + fn shutdown_all(&self) { + let entries: Vec = { + let mut g = self.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + g.drain().map(|(_, v)| v).collect() + }; + for mut entry in entries { + if let Some(tx) = entry.stop_tx.take() { + let _ = tx.send(()); + } + Self::force_kill_pid(entry.pid); + } + } +} + +/// Manages refcounted local Xray-core SOCKS5 bridges for VLESS proxies. +pub struct VlessManager { + inner: Arc, +} + +impl VlessManager { + pub fn new() -> Self { + Self { + inner: Arc::new(RegistryInner::new()), + } + } + + pub fn shared() -> &'static VlessManager { + static INSTANCE: OnceLock = OnceLock::new(); + INSTANCE.get_or_init(VlessManager::new) + } + + pub async fn acquire(&self, entry: &ProxyEntry) -> Result { + let bin = ensure_xray_binary().await?; + self.acquire_with_binary(entry, &bin).await + } + + pub async fn acquire_with_binary(&self, entry: &ProxyEntry, xray_bin: &Path) -> Result { + if !matches!(entry.kind, ProxyKind::Vless) { + bail!("VlessManager::acquire called for non-VLESS proxy"); + } + let key = canonical_key(entry); + let _creating = self.inner.create_lock.lock().await; + + { + let mut g = self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(existing) = g.get(&key) { + if !existing.dead.load(Ordering::SeqCst) { + existing.refs.fetch_add(1, Ordering::SeqCst); + return Ok(VlessLease { + inner: Arc::clone(&self.inner), + key, + addr: existing.addr, + refs: Arc::clone(&existing.refs), + }); + } + g.remove(&key); + } + } + + let mut last_err = None; + for attempt in 0..3 { + let listener = std::net::TcpListener::bind("127.0.0.1:0") + .context("bind ephemeral port for local VLESS bridge")?; + let addr = listener.local_addr()?; + let port = addr.port(); + drop(listener); + + match spawn_tunnel(entry, xray_bin, addr, port).await { + Ok(tunnel) => { + let refs = Arc::clone(&tunnel.refs); + let mut g = self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + g.insert(key.clone(), tunnel); + return Ok(VlessLease { + inner: Arc::clone(&self.inner), + key, + addr, + refs, + }); + } + Err(e) => { + eprintln!("[vless] start attempt {} on port {port} failed: {e:#}", attempt + 1); + last_err = Some(e); + } + } + } + Err(last_err.unwrap_or_else(|| anyhow::anyhow!("failed to start local VLESS bridge"))) + } + + pub fn shutdown_all(&self) { + self.inner.shutdown_all(); + } + + #[cfg(test)] + fn active_count(&self) -> usize { + self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()).len() + } +} + +fn drain_pipe(pipe: Option, into: &Arc>) { + let Some(mut reader) = pipe else { return }; + let buf = Arc::clone(into); + tokio::spawn(async move { + let mut chunk = [0u8; 512]; + loop { + match reader.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + let s = String::from_utf8_lossy(&chunk[..n]); + let mut g = buf.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() < 4096 { + let avail = 4096 - g.len(); + let snippet: String = s.chars().take(avail).collect(); + g.push_str(&snippet); + } + } + } + } + }); +} + +async fn spawn_tunnel( + entry: &ProxyEntry, + xray_bin: &Path, + addr: SocketAddr, + port: u16, +) -> Result { + let config = build_xray_config(entry, port)?; + let config_bytes = serde_json::to_vec(&config)?; + + let mut cmd = Command::new(xray_bin); + cmd.args(["run", "-c", "stdin:"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + + let (mut child, tie) = crate::process::spawn_tied(cmd) + .await + .with_context(|| format!("spawn Xray-core ({})", xray_bin.display()))?; + let pid = child.id().unwrap_or(0); + + if let Some(mut stdin) = child.stdin.take() { + stdin + .write_all(&config_bytes) + .await + .context("write config to Xray-core stdin")?; + let _ = stdin.shutdown().await; + } + + let stderr_buf = Arc::new(Mutex::new(String::new())); + drain_pipe(child.stdout.take(), &stderr_buf); + drain_pipe(child.stderr.take(), &stderr_buf); + + let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel::<()>(); + let dead = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let dead_flag = Arc::clone(&dead); + + tokio::spawn(async move { + let _tie = tie; + tokio::select! { + _ = child.wait() => {} + _ = &mut stop_rx => { + let _ = child.kill().await; + let _ = child.wait().await; + } + } + dead_flag.store(true, Ordering::SeqCst); + }); + + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3); + loop { + if dead.load(Ordering::SeqCst) { + let err_text = stderr_buf + .lock() + .unwrap_or_else(|e| e.into_inner()) + .trim() + .to_string(); + if err_text.is_empty() { + bail!("Xray-core exited before opening local SOCKS5 port {port}"); + } + bail!("Xray-core failed: {err_text}"); + } + if tokio::net::TcpStream::connect(addr).await.is_ok() { + break; + } + if tokio::time::Instant::now() >= deadline { + let _ = stop_tx.send(()); + let err_text = stderr_buf + .lock() + .unwrap_or_else(|e| e.into_inner()) + .trim() + .to_string(); + if err_text.is_empty() { + bail!("Xray-core did not open local SOCKS5 port {port} in time"); + } + bail!("Xray-core timed out: {err_text}"); + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + + Ok(TunnelEntry { + addr, + pid, + refs: Arc::new(AtomicUsize::new(1)), + stop_tx: Some(stop_tx), + dead, + }) +} + +/// Active lease on a refcounted local Xray-core SOCKS5 bridge. +/// Dropping the last lease terminates the underlying Xray-core process. +pub struct VlessLease { + inner: Arc, + key: String, + addr: SocketAddr, + refs: Arc, +} + +impl VlessLease { + pub fn addr(&self) -> SocketAddr { + self.addr + } + + pub fn proxy_server_arg(&self) -> String { + format!("socks5://{}", self.addr) + } + + pub fn local_socks5(&self) -> ProxyEntry { + ProxyEntry { + id: String::new(), + name: format!("vless-bridge-{}", self.addr.port()), + kind: ProxyKind::Socks5, + host: self.addr.ip().to_string(), + port: self.addr.port(), + username: String::new(), + password: String::new(), + country: String::new(), + notes: String::new(), + vless: None, + } + } +} + +impl Drop for VlessLease { + fn drop(&mut self) { + let prev = self.refs.fetch_sub(1, Ordering::SeqCst); + if prev != 1 { + return; + } + let mut removed = None; + if let Ok(mut g) = self.inner.tunnels.lock() { + if let Some(cur) = g.get(&self.key) { + if cur.refs.load(Ordering::SeqCst) == 0 && Arc::ptr_eq(&cur.refs, &self.refs) { + removed = g.remove(&self.key); + } + } + } + if let Some(mut entry) = removed { + if let Some(tx) = entry.stop_tx.take() { + let _ = tx.send(()); + } + } + } +} + +pub async fn acquire(entry: &ProxyEntry) -> Result { + VlessManager::shared().acquire(entry).await +} + +pub fn shutdown_all() { + VlessManager::shared().shutdown_all(); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::space::proxy::parse_single; + + #[test] + fn builds_reality_config_with_no_direct_outbound() { + let entry = parse_single( + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?security=reality&encryption=none&pbk=abc123PUBKEY&headerType=none&fp=chrome&type=tcp&flow=xtls-rprx-vision&sni=www.cloudflare.com&sid=a1b2&spx=%2F#EU-REALITY", + ) + .expect("parses"); + let cfg = build_xray_config(&entry, 10808).unwrap(); + + assert_eq!(cfg["inbounds"][0]["protocol"], "socks"); + assert_eq!(cfg["inbounds"][0]["listen"], "127.0.0.1"); + assert_eq!(cfg["inbounds"][0]["port"], 10808); + assert_eq!(cfg["inbounds"][0]["settings"]["udp"], true); + + let outbounds = cfg["outbounds"].as_array().unwrap(); + assert_eq!(outbounds.len(), 1, "must not contain a freedom/direct fallback outbound"); + assert_eq!(outbounds[0]["protocol"], "vless"); + assert_eq!(outbounds[0]["settings"]["vnext"][0]["address"], "198.51.100.10"); + assert_eq!(outbounds[0]["settings"]["vnext"][0]["port"], 443); + assert_eq!( + outbounds[0]["settings"]["vnext"][0]["users"][0]["id"], + "11111111-2222-3333-4444-555555555555" + ); + assert_eq!( + outbounds[0]["settings"]["vnext"][0]["users"][0]["flow"], + "xtls-rprx-vision" + ); + assert_eq!(outbounds[0]["streamSettings"]["network"], "tcp"); + assert_eq!(outbounds[0]["streamSettings"]["security"], "reality"); + assert_eq!( + outbounds[0]["streamSettings"]["realitySettings"]["publicKey"], + "abc123PUBKEY" + ); + assert_eq!( + outbounds[0]["streamSettings"]["realitySettings"]["serverName"], + "www.cloudflare.com" + ); + assert_eq!( + outbounds[0]["streamSettings"]["realitySettings"]["shortId"], + "a1b2" + ); + assert_eq!( + outbounds[0]["streamSettings"]["realitySettings"]["fingerprint"], + "chrome" + ); + } + + #[test] + fn builds_ws_xhttp_grpc_and_httpupgrade_configs() { + let ws = parse_single( + "vless://11111111-2222-3333-4444-555555555555@ws.example.com:443?type=ws&security=tls&sni=ws.example.com&host=cdn.example.com&path=%2Fws%3Fed%3D2048&alpn=h2,http/1.1&allowInsecure=1#WS", + ) + .unwrap(); + let ws_cfg = build_xray_config(&ws, 10809).unwrap(); + assert_eq!(ws_cfg["outbounds"][0]["streamSettings"]["network"], "ws"); + assert_eq!(ws_cfg["outbounds"][0]["streamSettings"]["wsSettings"]["path"], "/ws?ed=2048"); + assert_eq!(ws_cfg["outbounds"][0]["streamSettings"]["wsSettings"]["host"], "cdn.example.com"); + assert!(ws_cfg["outbounds"][0]["streamSettings"]["tlsSettings"].get("allowInsecure").is_none()); + assert_eq!( + ws_cfg["outbounds"][0]["streamSettings"]["tlsSettings"]["alpn"], + json!(["h2", "http/1.1"]) + ); + + let xhttp = parse_single( + "vless://11111111-2222-3333-4444-555555555555@x.example.com:443?type=xhttp&security=reality&sni=apple.com&pbk=pub&mode=packet-up&path=%2Fxhttp&host=x.example.com#XHTTP", + ) + .unwrap(); + let xhttp_cfg = build_xray_config(&xhttp, 10810).unwrap(); + assert_eq!(xhttp_cfg["outbounds"][0]["streamSettings"]["network"], "xhttp"); + assert_eq!( + xhttp_cfg["outbounds"][0]["streamSettings"]["xhttpSettings"]["mode"], + "packet-up" + ); + assert_eq!( + xhttp_cfg["outbounds"][0]["streamSettings"]["xhttpSettings"]["path"], + "/xhttp" + ); + + let grpc = parse_single( + "vless://11111111-2222-3333-4444-555555555555@g.example.com:443?type=grpc&security=tls&sni=g.example.com&serviceName=tunSvc&mode=multi#gRPC", + ) + .unwrap(); + let grpc_cfg = build_xray_config(&grpc, 10811).unwrap(); + assert_eq!( + grpc_cfg["outbounds"][0]["streamSettings"]["grpcSettings"]["serviceName"], + "tunSvc" + ); + assert_eq!( + grpc_cfg["outbounds"][0]["streamSettings"]["grpcSettings"]["multiMode"], + true + ); + + let hu = parse_single( + "vless://11111111-2222-3333-4444-555555555555@h.example.com:443?type=httpupgrade&security=tls&sni=h.example.com&path=%2Fup#HU", + ) + .unwrap(); + let hu_cfg = build_xray_config(&hu, 10812).unwrap(); + assert_eq!( + hu_cfg["outbounds"][0]["streamSettings"]["httpupgradeSettings"]["path"], + "/up" + ); + } + + #[test] + fn rejects_invalid_reality_and_missing_uuid() { + let mut entry = parse_single( + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?security=reality&sni=example.com", + ) + .unwrap(); + assert!(build_xray_config(&entry, 10808).is_err(), "missing pbk"); + + entry.vless.as_mut().unwrap().public_key = "pbk".into(); + entry.vless.as_mut().unwrap().sni.clear(); + assert!(build_xray_config(&entry, 10808).is_err(), "missing sni"); + + entry.vless.as_mut().unwrap().sni = "example.com".into(); + entry.username.clear(); + assert!(build_xray_config(&entry, 10808).is_err(), "missing uuid"); + } + + #[test] + fn canonical_key_ignores_display_name_and_normalizes_defaults() { + let a = parse_single( + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?type=raw&security=none#One", + ) + .unwrap(); + let b = parse_single( + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?type=tcp&encryption=none#Two", + ) + .unwrap(); + assert_eq!(canonical_key(&a), canonical_key(&b)); + } + + #[tokio::test] + #[ignore = "downloads Xray-core from GitHub Releases and tests live VLESS TCP+UDP tunnels"] + async fn live_xray_vless_tcp_and_udp_roundtrip() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, UdpSocket}; + + let _root = crate::store::test_root("vless-live"); + let bin = ensure_xray_binary().await.expect("ensure Xray-core"); + assert!(bin.is_file(), "xray binary exists at {}", bin.display()); + + // 1. Validate generated JSON schemas across major VLESS modes via `xray run -test -c stdin:`. + let samples = [ + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?security=reality&encryption=none&pbk=mA1-2b3C4d5E6f7G8h9I0j1K2l3M4n5O6p7Q8r9S0tU&fp=chrome&type=tcp&flow=xtls-rprx-vision&sni=www.cloudflare.com&sid=a1b2&spx=%2F", + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?type=ws&security=tls&sni=ws.example.com&host=cdn.example.com&path=%2Fws&alpn=h2,http/1.1&allowInsecure=1", + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?type=grpc&security=tls&sni=g.example.com&serviceName=tunSvc&mode=multi", + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?type=xhttp&security=reality&sni=www.apple.com&pbk=mA1-2b3C4d5E6f7G8h9I0j1K2l3M4n5O6p7Q8r9S0tU&mode=auto&path=%2Fxhttp", + "vless://11111111-2222-3333-4444-555555555555@198.51.100.10:443?type=httpupgrade&security=tls&sni=h.example.com&path=%2Fup", + "vless://11111111-2222-3333-4444-555555555555@127.0.0.1:10086?type=tcp&security=none&encryption=none", + ]; + for sample in samples { + let entry = parse_single(sample).expect("parses sample"); + let cfg = build_xray_config(&entry, 18999).expect("builds config"); + let mut cmd = std::process::Command::new(&bin); + cmd.args(["run", "-test", "-c", "stdin:"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = cmd.spawn().expect("spawn xray -test"); + child + .stdin + .take() + .unwrap() + .write_all(&serde_json::to_vec(&cfg).unwrap()) + .unwrap(); + let out = child.wait_with_output().unwrap(); + assert!( + out.status.success(), + "xray -test failed for {sample}:\nstdout={}\nstderr={}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + } + + // 2. Spin up local HTTP target server and local UDP echo/STUN server. + let http_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let http_port = http_listener.local_addr().unwrap().port(); + let http_task = tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = http_listener.accept().await else { break }; + tokio::spawn(async move { + let mut req_buf = [0u8; 1024]; + let _ = sock.read(&mut req_buf).await; + let body = r#"{"ip":"198.51.100.77","country_code":"NL","city":"Amsterdam"}"#; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = sock.write_all(resp.as_bytes()).await; + }); + } + }); + + let udp_sock = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let udp_port = udp_sock.local_addr().unwrap().port(); + let udp_task = tokio::spawn(async move { + let mut buf = [0u8; 1500]; + loop { + let Ok((n, peer)) = udp_sock.recv_from(&mut buf).await else { break }; + let mut reply = b"PONG:".to_vec(); + reply.extend_from_slice(&buf[..n]); + let _ = udp_sock.send_to(&reply, peer).await; + } + }); + + // 3. Start a real Xray VLESS server inbound on localhost. + let srv_probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let srv_port = srv_probe.local_addr().unwrap().port(); + drop(srv_probe); + + let uuid = "11111111-2222-3333-4444-555555555555"; + let server_cfg = json!({ + "log": { "loglevel": "warning" }, + "inbounds": [ + { + "listen": "127.0.0.1", + "port": srv_port, + "protocol": "vless", + "settings": { + "clients": [{ "id": uuid }], + "decryption": "none" + }, + "streamSettings": { + "network": "tcp", + "security": "none" + } + } + ], + "outbounds": [ + { + "protocol": "freedom", + "settings": { + "finalRules": [ + { + "action": "allow", + "network": "tcp,udp", + "ip": ["127.0.0.1/32"] + } + ] + } + } + ] + }); + + let mut srv_cmd = Command::new(&bin); + srv_cmd + .args(["run", "-c", "stdin:"]) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + let (mut srv_child, _srv_tie) = crate::process::spawn_tied(srv_cmd).await.unwrap(); + { + let mut stdin = srv_child.stdin.take().unwrap(); + stdin + .write_all(&serde_json::to_vec(&server_cfg).unwrap()) + .await + .unwrap(); + let _ = stdin.shutdown().await; + } + let srv_addr: SocketAddr = format!("127.0.0.1:{srv_port}").parse().unwrap(); + let mut srv_ready = false; + for _ in 0..80 { + if tokio::net::TcpStream::connect(srv_addr).await.is_ok() { + srv_ready = true; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + assert!(srv_ready, "mock Xray VLESS server did not start on {srv_addr}"); + + // 4. Acquire VLESS client bridge via VlessManager and verify refcounting + TCP + UDP! + let vless_uri = format!("vless://{uuid}@127.0.0.1:{srv_port}?type=tcp&security=none&encryption=none#LiveTest"); + let entry = parse_single(&vless_uri).unwrap(); + let mgr = VlessManager::new(); + let lease1 = mgr.acquire_with_binary(&entry, &bin).await.expect("acquire lease1"); + let lease2 = mgr.acquire_with_binary(&entry, &bin).await.expect("acquire lease2"); + assert_eq!(lease1.addr(), lease2.addr(), "refcounted sharing reuses one tunnel"); + assert_eq!(mgr.active_count(), 1); + + // 5. Real HTTP request over reqwest -> local SOCKS5 -> Xray VLESS client -> Xray VLESS server -> local HTTP server. + let client = reqwest::Client::builder() + .proxy(reqwest::Proxy::all(&format!("socks5h://{}", lease1.addr())).unwrap()) + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap(); + let body = client + .get(&format!("http://127.0.0.1:{http_port}/geo")) + .send() + .await + .expect("HTTP through VLESS tunnel") + .text() + .await + .unwrap(); + assert!(body.contains("198.51.100.77"), "unexpected HTTP body: {body}"); + + // 6. Real SOCKS5 UDP_ASSOCIATE datagram through the VLESS bridge. + let mut socks_tcp = tokio::net::TcpStream::connect(lease1.addr()).await.unwrap(); + socks_tcp.write_all(&[0x05, 0x01, 0x00]).await.unwrap(); + let mut greet = [0u8; 2]; + socks_tcp.read_exact(&mut greet).await.unwrap(); + assert_eq!(greet, [0x05, 0x00]); + socks_tcp + .write_all(&[0x05, 0x03, 0x00, 0x01, 0, 0, 0, 0, 0, 0]) + .await + .unwrap(); + let mut udp_hdr = [0u8; 10]; + socks_tcp.read_exact(&mut udp_hdr).await.unwrap(); + assert_eq!(udp_hdr[1], 0x00, "UDP_ASSOCIATE succeeded"); + let relay_port = u16::from_be_bytes([udp_hdr[8], udp_hdr[9]]); + let relay_addr: SocketAddr = format!("127.0.0.1:{relay_port}").parse().unwrap(); + + let client_udp = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let mut pkt = vec![0u8, 0, 0, 0x01, 127, 0, 0, 1]; + pkt.extend_from_slice(&udp_port.to_be_bytes()); + pkt.extend_from_slice(b"HELLO_VLESS_UDP"); + client_udp.send_to(&pkt, relay_addr).await.unwrap(); + + let mut recv_buf = [0u8; 1500]; + let (rn, _) = tokio::time::timeout( + std::time::Duration::from_secs(5), + client_udp.recv_from(&mut recv_buf), + ) + .await + .expect("UDP reply timeout") + .unwrap(); + assert!( + String::from_utf8_lossy(&recv_buf[..rn]).contains("PONG:HELLO_VLESS_UDP"), + "unexpected UDP reply: {:?}", + &recv_buf[..rn] + ); + drop(socks_tcp); + + // 7. Refcount cleanup: dropping lease1 keeps tunnel alive; dropping lease2 tears it down. + let bridge_addr = lease1.addr(); + drop(lease1); + assert_eq!(mgr.active_count(), 1); + assert!(tokio::net::TcpStream::connect(bridge_addr).await.is_ok()); + drop(lease2); + assert_eq!(mgr.active_count(), 0); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + assert!( + tokio::net::TcpStream::connect(bridge_addr).await.is_err(), + "bridge port closed after last lease dropped" + ); + + let _ = srv_child.kill().await; + http_task.abort(); + udp_task.abort(); + } +} diff --git a/src/dev/mock/fixtures.ts b/src/dev/mock/fixtures.ts index e6d600b0b..152c594d5 100644 --- a/src/dev/mock/fixtures.ts +++ b/src/dev/mock/fixtures.ts @@ -371,8 +371,8 @@ function snapshot(p: ProxyEntry, minutesAgo: number, ok = true): ProxyTestSnapsh latitude: ok ? g[5] : 0, longitude: ok ? g[6] : 0, tcp_ms: ok ? 38 + base * 2 : null, - udp_ms: ok && p.kind === "socks5" && /proxyshard|shardx\./.test(p.host) ? 52 + base * 2 : null, - udp_error: ok && !(p.kind === "socks5" && /proxyshard|shardx\./.test(p.host)) ? "SOCKS5 UDP ASSOCIATE refused" : null, + udp_ms: ok && (p.kind === "socks5" || p.kind === "vless") && /proxyshard|shardx\.|vless/.test(p.host) ? 52 + base * 2 : null, + udp_error: ok && !((p.kind === "socks5" || p.kind === "vless") && /proxyshard|shardx\.|vless/.test(p.host)) ? `${p.kind === "vless" ? "VLESS" : "SOCKS5"} UDP ASSOCIATE refused` : null, geo_error: ok ? null : "connect timed out after 8000 ms", provider: "ip-api.com", }; diff --git a/src/dev/mock/handlers.ts b/src/dev/mock/handlers.ts index 0f7973574..a1224a11d 100644 --- a/src/dev/mock/handlers.ts +++ b/src/dev/mock/handlers.ts @@ -21,6 +21,8 @@ import { NOT_IN_TEAM, profileFromFingerprint, settle, spaceStateOf, teamInUse, t import { SYNC_REFUSALS } from "../../entities/sync/model/types"; import { TEAM_REFUSALS } from "../../shared/api/teamRefusals"; import type { ProxyEntry, ProxyTestSnapshot } from "../../entities/proxy/model/types"; +import { sameProxy } from "../../entities/proxy/lib/identity"; +import { parseVlessUri } from "../../entities/proxy/lib/vless"; import type { FingerprintEntry } from "../../entities/fingerprint/model/types"; import type { Project, RunState, ModuleInfo } from "../../entities/automation/model/types"; import type { ProfileTemplate } from "../../entities/template/model/types"; @@ -133,7 +135,7 @@ function cloneProfile(src: StoredProfile, name: string): StoredProfile { function testSnapshot(entry: ProxyEntry, previous?: ProxyTestSnapshot): ProxyTestSnapshot { const dead = !entry.host || entry.name.toLowerCase().includes("expired"); - const isShard = entry.kind === "socks5" && /proxyshard|shardx\./.test(entry.host); + const isShard = (entry.kind === "socks5" || entry.kind === "vless") && /proxyshard|shardx\.|vless/.test(entry.host); const base = 30 + Math.round(Math.random() * 120); return { // The backend stamps "@", as it does everywhere. @@ -150,18 +152,42 @@ function testSnapshot(entry: ProxyEntry, previous?: ProxyTestSnapshot): ProxyTes longitude: dead ? 0 : previous?.longitude ?? 0, tcp_ms: dead ? null : base, udp_ms: dead ? null : isShard ? base + 14 : null, - udp_error: dead ? null : isShard ? null : "SOCKS5 UDP ASSOCIATE refused", + udp_error: dead ? null : isShard ? null : `${entry.kind === "vless" ? "VLESS" : "SOCKS5"} UDP ASSOCIATE refused`, geo_error: dead ? "connect timed out after 8000 ms" : null, provider: "ip-api.com", }; } -/** `host:port`, `host:port:user:pass`, `user:pass@host:port`, `socks5://user:pass@host:port`. */ +function maybeDecodeSubscription(raw: string): string { + const trimmed = raw.trim(); + if (!trimmed || trimmed.includes("\n") || trimmed.includes("://")) return raw; + const std = trimmed.replace(/-/g, "+").replace(/_/g, "/"); + try { + const decoded = atob(std); + if (/^(?:vless|socks5|https?):\/\//im.test(decoded)) return decoded; + } catch { /* not base64 subscription */ } + return raw; +} + +/** `vless://...`, `host:port`, `host:port:user:pass`, `user:pass@host:port`, `socks5://user:pass@host:port`. */ function parseProxyLines(text: string, kind: ProxyEntry["kind"]): ProxyEntry[] { const out: ProxyEntry[] = []; - for (const raw of text.split(/\r?\n/)) { + for (const raw of maybeDecodeSubscription(text).split(/\r?\n/)) { const line = raw.trim(); if (!line || line.startsWith("#")) continue; + const vlessInput = + /^vless:\/\//i.test(line) ? line : kind === "vless" && !line.includes("://") && line.includes("@") ? `vless://${line}` : null; + if (vlessInput) { + const parsed = parseVlessUri(vlessInput); + if (parsed) { + out.push({ + ...parsed, + id: `px-${newId().slice(0, 6)}`, + name: parsed.name || `${parsed.host}:${parsed.port}`, + }); + } + continue; + } let k = kind; let rest = line; const scheme = /^(socks5|https?):\/\//i.exec(rest); @@ -189,7 +215,7 @@ function parseProxyLines(text: string, kind: ProxyEntry["kind"]): ProxyEntry[] { function addProxies(entries: ProxyEntry[], ctx: Ctx): number { let n = 0; for (const e of entries) { - const same = ctx.state.proxies.some((p) => p.kind === e.kind && p.host === e.host && p.port === e.port && p.username === e.username && p.password === e.password); + const same = ctx.state.proxies.some((p) => sameProxy(p, e)); if (same) continue; handlers.proxy_save({ entry: { ...e, id: e.id && !ctx.state.proxies.some((p) => p.id === e.id) ? e.id : "" } }, ctx); n++; @@ -1259,6 +1285,8 @@ export const handlers: Record = { automation_export: ({ projectId }, { state }) => { const p = state.automation.find((x) => x.id === projectId); if (!p) throw `project ${projectId} not found`; return { format: 1, exported_at: Math.floor(Date.now() / 1000), project: p, modules: [], needs: p.blocks.filter((b) => b.secrets.length).map((b) => ({ block_id: b.id, label: b.label, params: b.secrets })) }; }, automation_import: ({ bundle }, ctx) => { const p: Project = JSON.parse(JSON.stringify(bundle.project)); p.id = `proj-${newId().slice(0, 6)}`; ctx.state.automation.push(teamNew(ctx.state, p)); ctx.save(); return p; }, automation_display: () => ({ server: hostPlatform() === "macOS" ? "quartz" : "x11", limited: false, note: "", browser_placement: true, panels: true }), + vless_status: () => ({ installed: true, path: "/mock/xray", version: "Xray 26.11.9 (mock)" }), + vless_ensure: () => ({ installed: true, path: "/mock/xray", version: "Xray 26.11.9 (mock)" }), // ---- Tauri plugins ------------------------------------------------------------ "plugin:app|version": () => "2.0.3", diff --git a/src/entities/proxy/index.ts b/src/entities/proxy/index.ts index 5ce294907..ae3bd59e1 100644 --- a/src/entities/proxy/index.ts +++ b/src/entities/proxy/index.ts @@ -7,3 +7,4 @@ export * from "./lib/status"; export * from "./lib/labels"; export * from "./lib/identity"; export * from "./lib/rotation"; +export * from "./lib/vless"; diff --git a/src/entities/proxy/lib/identity.ts b/src/entities/proxy/lib/identity.ts index 18a5b830d..4a085af8f 100644 --- a/src/entities/proxy/lib/identity.ts +++ b/src/entities/proxy/lib/identity.ts @@ -1,11 +1,17 @@ import type { ProxyEntry } from "../model/types"; +import { sameVlessConfig } from "./vless"; -type Identity = Pick; +type Identity = Pick; /// The same proxy, as the backend decides it on import (`same_proxy` in -/// proxy.rs): one kind, host, port, user and password. The password counts: -/// providers that carry a session or routing parameters in it serve -/// different exits from one host, port and user, so those are different -/// proxies. Only an identical one is skipped. +/// proxy.rs): one kind, host, port, user and password (and VLESS transport +/// parameters). The password counts: providers that carry a session or +/// routing parameters in it serve different exits from one host, port and +/// user, so those are different proxies. Only an identical one is skipped. export const sameProxy = (a: Identity, b: Identity): boolean => - a.kind === b.kind && a.host === b.host && a.port === b.port && a.username === b.username && a.password === b.password; + a.kind === b.kind && + a.host === b.host && + a.port === b.port && + a.username === b.username && + a.password === b.password && + (a.kind !== "vless" || sameVlessConfig(a.vless, b.vless)); diff --git a/src/entities/proxy/lib/useProxy.tsx b/src/entities/proxy/lib/useProxy.tsx index 4886b7be3..d3bf0d12d 100644 --- a/src/entities/proxy/lib/useProxy.tsx +++ b/src/entities/proxy/lib/useProxy.tsx @@ -13,6 +13,7 @@ import { eachReporting } from '../../../shared/lib/eachReporting'; import { t } from '../../../shared/i18n'; import { ProfileMeta } from '../../profile/model/types'; import { proxyStatus } from './status'; +import { formatVlessUri } from './vless'; // The delete toast's "Assign replacements…" opens Assign proxies for the // profiles that used the deleted proxies. That dialog belongs to the @@ -103,7 +104,7 @@ export type ProxyFilters = { status: 'any' | 'working' | 'failed' | 'untested'; /** Whether a profile uses it. */ used: 'any' | 'used' | 'unused'; - kind: '' | 'socks5' | 'http' | 'https'; + kind: '' | 'socks5' | 'http' | 'https' | 'vless'; /** An upper-case country code. */ country: string; }; @@ -149,11 +150,15 @@ export function filterProxies( if (!q) return true; return ( p.name.toLowerCase().includes(q) || + p.kind.includes(q) || p.host.toLowerCase().includes(q) || String(p.port).includes(q) || p.country.toLowerCase().includes(q) || p.notes.toLowerCase().includes(q) || p.username.toLowerCase().includes(q) || + (p.vless?.sni ?? '').toLowerCase().includes(q) || + (p.vless?.network ?? '').toLowerCase().includes(q) || + (p.vless?.security ?? '').toLowerCase().includes(q) || (snap?.ip ?? '').toLowerCase().includes(q) || (snap?.city ?? '').toLowerCase().includes(q) || (snap?.isp ?? '').toLowerCase().includes(q) @@ -574,6 +579,7 @@ export const useProxy = create((set, get) => ({ const targets = get().proxies.filter((p) => wanted.has(p.id)); if (targets.length === 0) return; const lines = targets.map((p) => { + if (p.kind === "vless") return formatVlessUri(p); const auth = p.username || p.password ? `${p.username}:${p.password}@` : ""; const base = `${p.kind}://${auth}${p.host}:${p.port}`; // Only the name: the country is derived by the test on import, so @@ -583,7 +589,7 @@ export const useProxy = create((set, get) => ({ }); const text = lines.join("\n"); // Lines with credentials leave the clipboard after a minute (SEC-11). - const secret = targets.some((p) => p.username || p.password); + const secret = targets.some((p) => p.kind === "vless" || p.username || p.password); (secret ? copySecret(text) : clip.write(text)).then( () => toast.ok( targets.length === 1 ? t("useProxy.copiedOne") : t("useProxy.copiedMany", { n: targets.length }), diff --git a/src/entities/proxy/lib/vless.test.ts b/src/entities/proxy/lib/vless.test.ts new file mode 100644 index 000000000..21994fbbc --- /dev/null +++ b/src/entities/proxy/lib/vless.test.ts @@ -0,0 +1,66 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + emptyVlessConfig, + formatVlessUri, + normalizeVlessConfig, + parseVlessUri, + sameVlessConfig, + vlessSummaryTags, +} from "./vless.ts"; + +test("parses REALITY Vision URI and preserves literal + in base64 keys", () => { + const uri = + "vless://11111111-2222-3333-4444-555555555555@edge.example.com:443?encryption=none&flow=xtls-rprx-vision&security=reality&sni=www.microsoft.com&fp=chrome&pbk=abc+def/ghi=&sid=6ba85179e30d4fc2&spx=/#%F0%9F%87%A9%F0%9F%87%AA%20Frankfurt"; + const parsed = parseVlessUri(uri); + assert.ok(parsed); + assert.equal(parsed.kind, "vless"); + assert.equal(parsed.host, "edge.example.com"); + assert.equal(parsed.port, 443); + assert.equal(parsed.username, "11111111-2222-3333-4444-555555555555"); + assert.equal(parsed.name, "🇩🇪 Frankfurt"); + assert.equal(parsed.vless?.security, "reality"); + assert.equal(parsed.vless?.network, "tcp"); + assert.equal(parsed.vless?.flow, "xtls-rprx-vision"); + assert.equal(parsed.vless?.sni, "www.microsoft.com"); + assert.equal(parsed.vless?.public_key, "abc+def/ghi="); + assert.equal(parsed.vless?.short_id, "6ba85179e30d4fc2"); +}); + +test("parses IPv6 host, splithttp/raw aliases, and XHTTP/gRPC/WS fields", () => { + const parsed = parseVlessUri( + "vless://uuid-1@[2001:db8::1]:8443?security=tls&type=splithttp&host=cdn.example.com&path=/xhttp&mode=packet-up&alpn=h2,http/1.1&allowInsecure=1#IPv6%20XHTTP", + ); + assert.ok(parsed); + assert.equal(parsed.host, "2001:db8::1"); + assert.equal(parsed.port, 8443); + assert.equal(parsed.vless?.network, "xhttp"); + assert.equal(parsed.vless?.security, "tls"); + assert.equal(parsed.vless?.host, "cdn.example.com"); + assert.equal(parsed.vless?.path, "/xhttp"); + assert.equal(parsed.vless?.mode, "packet-up"); + assert.equal(parsed.vless?.allow_insecure, true); + + const formatted = formatVlessUri({ + name: parsed.name, + host: parsed.host, + port: parsed.port, + username: parsed.username, + vless: parsed.vless, + }); + assert.match(formatted, /@\[2001:db8::1\]:8443\?/); + const reparsed = parseVlessUri(formatted); + assert.ok(reparsed); + assert.equal(sameVlessConfig(parsed.vless, reparsed.vless), true); +}); + +test("compares normalized configs accurately", () => { + const a = normalizeVlessConfig({ ...emptyVlessConfig(), network: "raw", security: "" }); + const b = normalizeVlessConfig({ network: "tcp", security: "none" }); + assert.equal(sameVlessConfig(a, b), true); + assert.deepEqual(vlessSummaryTags({ security: "reality", network: "xhttp", flow: "xtls-rprx-vision" }), [ + "REALITY", + "XHTTP", + "Vision", + ]); +}); diff --git a/src/entities/proxy/lib/vless.ts b/src/entities/proxy/lib/vless.ts new file mode 100644 index 000000000..ee85de28a --- /dev/null +++ b/src/entities/proxy/lib/vless.ts @@ -0,0 +1,332 @@ +import type { ProxyEntry, VlessConfig } from "../model/types"; + +export type VlessOption = { + value: string; + label?: string; +}; + +export const VLESS_NETWORKS: readonly VlessOption[] = [ + { value: "tcp", label: "TCP" }, + { value: "ws", label: "WebSocket" }, + { value: "grpc", label: "gRPC" }, + { value: "xhttp", label: "XHTTP" }, + { value: "httpupgrade", label: "HTTPUpgrade" }, + { value: "kcp", label: "mKCP" }, +]; + +export const VLESS_SECURITIES: readonly VlessOption[] = [ + { value: "none" }, + { value: "tls", label: "TLS" }, + { value: "reality", label: "REALITY" }, +]; + +export const VLESS_FLOWS: readonly VlessOption[] = [ + { value: "" }, + { value: "xtls-rprx-vision", label: "xtls-rprx-vision" }, + { value: "xtls-rprx-vision-udp443", label: "xtls-rprx-vision-udp443" }, +]; + +export const VLESS_FINGERPRINTS: readonly VlessOption[] = [ + { value: "" }, + { value: "chrome", label: "Chrome" }, + { value: "firefox", label: "Firefox" }, + { value: "safari", label: "Safari" }, + { value: "ios", label: "iOS" }, + { value: "android", label: "Android" }, + { value: "edge", label: "Edge" }, + { value: "360", label: "360" }, + { value: "qq", label: "QQ" }, + { value: "random" }, + { value: "randomized" }, +]; + +export function emptyVlessConfig(): VlessConfig { + return { + encryption: "none", + flow: "", + network: "tcp", + security: "none", + sni: "", + fingerprint: "", + public_key: "", + short_id: "", + spider_x: "", + pqv: "", + alpn: "", + allow_insecure: false, + host: "", + path: "", + service_name: "", + authority: "", + mode: "", + header_type: "", + seed: "", + extra: "", + }; +} + +function normNetwork(raw?: string): string { + const s = (raw ?? "").trim().toLowerCase(); + if (!s || s === "raw") return "tcp"; + if (s === "splithttp") return "xhttp"; + return s; +} + +function normSecurity(raw?: string): string { + const s = (raw ?? "").trim().toLowerCase(); + if (!s) return "none"; + if (s === "xtls") return "tls"; + return s; +} + +export function normalizeVlessConfig(raw?: Partial | null): VlessConfig { + const enc = (raw?.encryption ?? "").trim(); + const v: VlessConfig = { + encryption: enc || "none", + flow: (raw?.flow ?? "").trim(), + network: normNetwork(raw?.network), + security: normSecurity(raw?.security), + sni: (raw?.sni ?? "").trim(), + fingerprint: (raw?.fingerprint ?? "").trim(), + public_key: (raw?.public_key ?? "").trim(), + short_id: (raw?.short_id ?? "").trim(), + spider_x: (raw?.spider_x ?? "").trim(), + pqv: (raw?.pqv ?? "").trim(), + alpn: (raw?.alpn ?? "").trim(), + allow_insecure: Boolean(raw?.allow_insecure), + host: (raw?.host ?? "").trim(), + path: (raw?.path ?? "").trim(), + service_name: (raw?.service_name ?? "").trim(), + authority: (raw?.authority ?? "").trim(), + mode: (raw?.mode ?? "").trim(), + header_type: (raw?.header_type ?? "").trim(), + seed: (raw?.seed ?? "").trim(), + extra: (raw?.extra ?? "").trim(), + }; + return v; +} + +const VLESS_KEYS: (keyof VlessConfig)[] = [ + "encryption", + "flow", + "network", + "security", + "sni", + "fingerprint", + "public_key", + "short_id", + "spider_x", + "pqv", + "alpn", + "allow_insecure", + "host", + "path", + "service_name", + "authority", + "mode", + "header_type", + "seed", + "extra", +]; + +export function sameVlessConfig(a?: Partial | null, b?: Partial | null): boolean { + const na = normalizeVlessConfig(a); + const nb = normalizeVlessConfig(b); + return VLESS_KEYS.every((k) => na[k] === nb[k]); +} + +function decodePctKeepPlus(raw: string): string { + try { + return decodeURIComponent(raw); + } catch { + return raw; + } +} + +/** Parse `vless://uuid@host:port?query#name` (preserving `+` in base64 keys). */ +export function parseVlessUri(rawLine: string): Omit | null { + const s = rawLine.trim(); + if (!/^vless:\/\//i.test(s)) return null; + let rest = s.slice("vless://".length); + + let name = ""; + const hashIdx = rest.indexOf("#"); + if (hashIdx >= 0) { + name = decodePctKeepPlus(rest.slice(hashIdx + 1)).trim(); + rest = rest.slice(0, hashIdx); + } + + let query = ""; + const qIdx = rest.indexOf("?"); + if (qIdx >= 0) { + query = rest.slice(qIdx + 1); + rest = rest.slice(0, qIdx); + } + + // Authority may include trailing `/` before `?` + rest = rest.replace(/\/+$/, ""); + const atIdx = rest.indexOf("@"); + if (atIdx < 0) return null; + const uuid = decodePctKeepPlus(rest.slice(0, atIdx)).trim(); + const hostPort = rest.slice(atIdx + 1).trim(); + if (!uuid || !hostPort) return null; + + let host = ""; + let portStr = ""; + if (hostPort.startsWith("[")) { + const closeIdx = hostPort.indexOf("]"); + if (closeIdx < 0) return null; + host = hostPort.slice(1, closeIdx).trim(); + const after = hostPort.slice(closeIdx + 1); + if (!after.startsWith(":")) return null; + portStr = after.slice(1); + } else { + const colonIdx = hostPort.lastIndexOf(":"); + if (colonIdx < 0) return null; + host = hostPort.slice(0, colonIdx).trim(); + portStr = hostPort.slice(colonIdx + 1); + } + + const port = Number(portStr); + if (!host || !Number.isInteger(port) || port < 1 || port > 65535) return null; + + const cfg = emptyVlessConfig(); + if (query) { + for (const part of query.split("&")) { + if (!part) continue; + const eqIdx = part.indexOf("="); + const k = (eqIdx >= 0 ? decodePctKeepPlus(part.slice(0, eqIdx)) : decodePctKeepPlus(part)).trim(); + const v = (eqIdx >= 0 ? decodePctKeepPlus(part.slice(eqIdx + 1)) : "").trim(); + switch (k) { + case "encryption": + cfg.encryption = v || "none"; + break; + case "flow": + cfg.flow = v; + break; + case "type": + case "net": + case "method": + cfg.network = normNetwork(v); + break; + case "security": + cfg.security = normSecurity(v); + break; + case "sni": + case "peer": + cfg.sni = v; + break; + case "fp": + cfg.fingerprint = v; + break; + case "pbk": + cfg.public_key = v; + break; + case "sid": + cfg.short_id = v; + break; + case "spx": + cfg.spider_x = v; + break; + case "pqv": + cfg.pqv = v; + break; + case "alpn": + cfg.alpn = v; + break; + case "allowInsecure": + case "insecure": + cfg.allow_insecure = v === "1" || v.toLowerCase() === "true" || v.toLowerCase() === "yes"; + break; + case "host": + cfg.host = v; + break; + case "path": + cfg.path = v; + break; + case "serviceName": + cfg.service_name = v; + break; + case "authority": + cfg.authority = v; + break; + case "mode": + cfg.mode = v; + break; + case "headerType": + cfg.header_type = v; + break; + case "seed": + cfg.seed = v; + break; + case "extra": + cfg.extra = v; + break; + } + } + } + + return { + name, + kind: "vless", + host, + port, + username: uuid, + password: "", + country: "", + notes: "", + vless: normalizeVlessConfig(cfg), + }; +} + +/** Format a `ProxyEntry` back into a `vless://uuid@host:port?...#name` share link. */ +export function formatVlessUri( + proxy: Pick, +): string { + const cfg = normalizeVlessConfig(proxy.vless); + const host = proxy.host.includes(":") && !proxy.host.startsWith("[") ? `[${proxy.host}]` : proxy.host; + const params: [string, string][] = [ + ["encryption", cfg.encryption || "none"], + ["security", cfg.security || "none"], + ["type", cfg.network || "tcp"], + ]; + const push = (k: string, val?: string) => { + const trimmed = val?.trim(); + if (trimmed) params.push([k, trimmed]); + }; + push("flow", cfg.flow); + push("sni", cfg.sni); + push("fp", cfg.fingerprint); + push("pbk", cfg.public_key); + push("sid", cfg.short_id); + push("spx", cfg.spider_x); + push("pqv", cfg.pqv); + push("alpn", cfg.alpn); + if (cfg.allow_insecure) params.push(["allowInsecure", "1"]); + push("host", cfg.host); + push("path", cfg.path); + push("serviceName", cfg.service_name); + push("authority", cfg.authority); + push("mode", cfg.mode); + push("headerType", cfg.header_type); + push("seed", cfg.seed); + push("extra", cfg.extra); + + const qs = params.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join("&"); + const base = `vless://${encodeURIComponent(proxy.username)}@${host}:${proxy.port}?${qs}`; + return proxy.name.trim() ? `${base}#${encodeURIComponent(proxy.name.trim())}` : base; +} + +export function vlessSummaryTags(vless?: Partial | null): string[] { + const cfg = normalizeVlessConfig(vless); + const tags: string[] = []; + if (cfg.security === "reality") tags.push("REALITY"); + else if (cfg.security === "tls") tags.push("TLS"); + else tags.push("Plain"); + + const net = cfg.network ?? "tcp"; + const netLabel = VLESS_NETWORKS.find((n) => n.value === net)?.label ?? net.toUpperCase(); + tags.push(netLabel); + if (cfg.flow) tags.push(cfg.flow.includes("vision") ? "Vision" : cfg.flow); + return tags; +} diff --git a/src/entities/proxy/model/api.ts b/src/entities/proxy/model/api.ts index 0ad691ff0..8a4610a97 100644 --- a/src/entities/proxy/model/api.ts +++ b/src/entities/proxy/model/api.ts @@ -34,3 +34,11 @@ export type ChangeIpResult = { changed: boolean; }; export const proxyChangeIp = (id: string) => invoke("proxy_change_ip", { id }); + +export type VlessStatus = { + installed: boolean; + path: string | null; + version: string | null; +}; +export const vlessStatus = () => invoke("vless_status"); +export const vlessEnsure = () => invoke("vless_ensure"); diff --git a/src/entities/proxy/model/types.ts b/src/entities/proxy/model/types.ts index f974aadf7..195cd888a 100644 --- a/src/entities/proxy/model/types.ts +++ b/src/entities/proxy/model/types.ts @@ -1,13 +1,39 @@ +export type ProxyKind = "socks5" | "http" | "https" | "vless"; + +export interface VlessConfig { + encryption?: string; + flow?: string; + network?: string; + security?: string; + sni?: string; + fingerprint?: string; + public_key?: string; + short_id?: string; + spider_x?: string; + pqv?: string; + alpn?: string; + allow_insecure?: boolean; + host?: string; + path?: string; + service_name?: string; + authority?: string; + mode?: string; + header_type?: string; + seed?: string; + extra?: string; +} + export type ProxyEntry = { id: string; name: string; - kind: "socks5" | "http" | "https"; + kind: ProxyKind; host: string; port: number; username: string; password: string; country: string; notes: string; + vless?: VlessConfig; }; export type ProxyTestSnapshot = { diff --git a/src/entities/settings/model/types.ts b/src/entities/settings/model/types.ts index e7b463267..ff92d52eb 100644 --- a/src/entities/settings/model/types.ts +++ b/src/entities/settings/model/types.ts @@ -31,6 +31,8 @@ export type Settings = { ext_update_check?: boolean; /** #154: the saved proxy the launcher reaches the Web Store through; none, it does not. */ store_proxy?: string | null; + /** Optional override path to the Xray-core binary used for VLESS proxies. */ + xray_path?: string | null; }; /** Where profiles, user-data, extensions and the trash live. */ diff --git a/src/features/manage-proxies/lib/filterFields.tsx b/src/features/manage-proxies/lib/filterFields.tsx index d327381ac..e55948827 100644 --- a/src/features/manage-proxies/lib/filterFields.tsx +++ b/src/features/manage-proxies/lib/filterFields.tsx @@ -6,8 +6,8 @@ import { useT } from "../../../shared/i18n"; import type { FilterChip, FilterField } from "../../../shared/ui/filters"; const STATES = ["working", "failed", "untested"] as const; -const KINDS = ["socks5", "http", "https"] as const; -const KIND_LABEL = { socks5: "SOCKS5", http: "HTTP", https: "HTTPS" } as const; +const KINDS = ["socks5", "http", "https", "vless"] as const; +const KIND_LABEL = { socks5: "SOCKS5", http: "HTTP", https: "HTTPS", vless: "VLESS" } as const; /** The field and value words, called literally so the i18n check sees every key. */ function words(t: (k: string) => string) { diff --git a/src/features/manage-proxies/ui/EditProxyDialog.tsx b/src/features/manage-proxies/ui/EditProxyDialog.tsx index a93a21f1d..f2f91f09b 100644 --- a/src/features/manage-proxies/ui/EditProxyDialog.tsx +++ b/src/features/manage-proxies/ui/EditProxyDialog.tsx @@ -1,5 +1,5 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { DialogModal, IconButton, Input, useLatched } from "@proxyshard/shardx-ui-kit"; +import { DialogModal, IconButton, Input, Switch, useLatched } from "@proxyshard/shardx-ui-kit"; import { EyeIcon, EyeOffIcon } from "../../../shared/icons"; import { isMod } from "../../../shared/lib/keyboard"; import { commitFocusedField } from "../../../shared/lib/commitField"; @@ -10,7 +10,22 @@ import { Field } from "../../../shared/ui/Field"; import { NumField } from "../../../shared/ui/NumField"; import { SelectField } from "../../../shared/ui/SelectField"; import { useT } from "../../../shared/i18n"; -import { proxyRotationGet, proxyRotationSet, useProxy, useRotation, type ProxyEntry } from "../../../entities/proxy"; +import { + emptyVlessConfig, + normalizeVlessConfig, + parseVlessUri, + proxyRotationGet, + proxyRotationSet, + sameVlessConfig, + useProxy, + useRotation, + VLESS_FINGERPRINTS, + VLESS_FLOWS, + VLESS_NETWORKS, + VLESS_SECURITIES, + type ProxyEntry, + type VlessConfig, +} from "../../../entities/proxy"; const FIELDS = ["name", "kind", "host", "port", "username", "password", "country", "notes"] as const; @@ -37,6 +52,8 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo const [blurred, setBlurred] = useState(false); const [tried, setTried] = useState(false); const [shownPassword, setShownPassword] = useState(false); + const [vlessPaste, setVlessPaste] = useState(""); + const [vlessPasteBad, setVlessPasteBad] = useState(false); // The port field shows text that is not a port (emptied, a letter): the // draft keeps the last good one, which is not what the field shows, so // Save waits until it is a port again. @@ -55,7 +72,14 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo const linkOk = link.trim() === "" || /^https?:\/\/\S+$/i.test(link.trim()); const changed = opened && draft ? FIELDS.filter((k) => draft[k] !== opened[k]) : []; - const dirty = changed.length > 0 || linkChanged; + const vlessChanged = !!( + opened && + draft && + (draft.kind === "vless" || opened.kind === "vless") && + !sameVlessConfig(draft.vless, opened.vless) + ); + const entryDirty = changed.length > 0 || vlessChanged; + const dirty = entryDirty || linkChanged; // Gone before it opened, or while it is open (deleted elsewhere): saving // would bring it back, so the dialog closes and says why. "Could not be @@ -69,8 +93,9 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo }, [open, gone, dirty, opened, onClose, t]); const hostOk = !!draft?.host.trim(); + const uuidOk = draft?.kind !== "vless" || !!draft.username.trim(); const saving = status === "saving"; - const canSave = !!draft && hostOk && !portBad && linkOk && dirty && !saving; + const canSave = !!draft && hostOk && uuidOk && !portBad && linkOk && dirty && !saving; const name = opened ? opened.name || `${opened.host}:${opened.port}` : ""; const patch = (changes: Partial) => { @@ -78,21 +103,59 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo if (status === "error") setStatus("idle"); }; + const patchVless = (changes: Partial) => { + setDraft((d) => d && { ...d, vless: { ...(d.vless ?? emptyVlessConfig()), ...changes } }); + if (status === "error") setStatus("idle"); + }; + const optList = ( + items: readonly { value: string; label?: string }[], + fallback: (value: string) => string = (value) => value, + ) => items.map((o) => ({ value: o.value, label: o.label ?? fallback(o.value) })); + + const applyVlessUri = (raw: string) => { + setVlessPaste(raw); + const trimmed = raw.trim(); + if (!trimmed) { + setVlessPasteBad(false); + return; + } + const parsed = parseVlessUri(trimmed); + if (parsed && draft) { + patch({ + host: parsed.host, + port: parsed.port, + username: parsed.username, + password: "", + name: parsed.name || draft.name, + vless: normalizeVlessConfig(parsed.vless), + }); + setVlessPaste(""); + setVlessPasteBad(false); + toast.ok(t("editProxy.vlessPasted")); + } + }; + /** Saves what was changed over the proxy as it is now, so a change made * elsewhere meanwhile (a test filling in the country) survives. True when written. */ const save = async (): Promise => { if (!opened || !draft || busy.current) return false; - if (!hostOk || portBad || !linkOk) { setTried(true); return false; } + if (!hostOk || !uuidOk || portBad || !linkOk) { setTried(true); return false; } if (!dirty) return true; const base = useProxy.getState().proxies.find((p) => p.id === id); if (!base) return false; busy.current = true; setStatus("saving"); const merged = { ...base, ...Object.fromEntries(changed.map((k) => [k, draft[k]])) } as ProxyEntry; + if (merged.kind === "vless") { + merged.vless = normalizeVlessConfig(draft.vless); + merged.password = ""; + } else { + delete merged.vless; + } // A pasted value often carries a stray space, and the proxy then fails // for no visible reason (WIG-03). The password stays as typed. const entry = { ...merged, host: merged.host.trim(), username: merged.username.trim(), country: merged.country.trim().toUpperCase() }; - let ok = changed.length === 0 || await saveProxy(entry); + let ok = !entryDirty || await saveProxy(entry); if (ok && linkChanged) { ok = await proxyRotationSet(id, link.trim() || null).then(() => true, () => false); void useRotation.getState().load(); @@ -126,10 +189,12 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo }, [open]); if (!draft) return null; + const vless = normalizeVlessConfig(draft.vless); const note = status === "error" ? ( {t("editProxy.saveFailed")} ) : saving ? null : !hostOk ? t("editProxy.hostRequired") + : !uuidOk ? t("editProxy.uuidRequired") : portBad ? t("numField.invalidRange", { min: 1, max: 65535 }) : !dirty ? t("editProxy.noChanges") : null; @@ -162,15 +227,29 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo patch({ kind })} + onChange={(kind) => patch(kind === "vless" ? { kind, vless: draft.vless ?? emptyVlessConfig() } : { kind })} options={[ { value: "socks5" as const, label: "SOCKS5" }, { value: "http" as const, label: "HTTP" }, { value: "https" as const, label: "HTTPS" }, + { value: "vless" as const, label: "VLESS" }, ]} /> patch({ country })} /> + {draft.kind === "vless" && ( + applyVlessUri(e.target.value)} + onBlur={() => setVlessPasteBad(!!vlessPaste.trim() && !parseVlessUri(vlessPaste.trim()))} + /> + )}
patch({ port })} onInvalid={setPortBad} />
-
- patch({ username })} /> - {/* The eye sits inside the field, so the field keeps the column's - trailing edge (LAYOUT-15). One name, "Show password"; whether it - is shown is `aria-pressed` (PC-073). One ring, never cut off - (Pair 18 review, I2): while the eye has focus the field's own - ring stands down, and the eye draws the 2 px ring inside its box, - within the field's frame. */} - patch({ password: e.target.value })} - rightIcon={ - : } - onClick={() => setShownPassword((v) => !v)} + {draft.kind === "vless" ? ( + <> + patch({ username: e.target.value })} + rightIcon={ + : } + onClick={() => setShownPassword((v) => !v)} + /> + } + /> +
+ patchVless({ security })} + options={optList(VLESS_SECURITIES, () => t("proxyPeek.none"))} /> - } - /> -
+ patchVless({ network })} + options={optList(VLESS_NETWORKS)} + /> +
+ {vless.security !== "none" && ( +
+ patchVless({ sni })} /> + patchVless({ fingerprint })} + options={optList(VLESS_FINGERPRINTS, (v) => + v === "random" ? t("proxyEditor.optRandom") + : v === "randomized" ? t("proxyEditor.optRandomized") + : t("proxyEditor.optDefault"), + )} + /> +
+ )} + {vless.security === "reality" && ( + <> +
+ patchVless({ public_key })} /> + patchVless({ short_id })} /> +
+
+ patchVless({ spider_x })} /> + patchVless({ pqv })} /> +
+ + )} + {vless.security === "tls" && ( +
+ patchVless({ alpn })} /> + +
+ )} + {vless.network === "tcp" && ( +
+ patchVless({ flow })} + options={optList(VLESS_FLOWS, () => t("proxyPeek.none"))} + /> + patchVless({ header_type })} /> +
+ )} + {(vless.network === "ws" || vless.network === "httpupgrade" || vless.network === "xhttp") && ( +
+ patchVless({ host })} /> + patchVless({ path })} /> +
+ )} + {vless.network === "xhttp" && ( +
+ patchVless({ mode })} /> + patchVless({ extra })} /> +
+ )} + {vless.network === "grpc" && ( +
+ patchVless({ service_name })} /> + patchVless({ authority })} /> + patchVless({ mode })} /> +
+ )} + {vless.network === "kcp" && ( +
+ patchVless({ header_type })} /> + patchVless({ seed })} /> +
+ )} + patchVless({ encryption })} /> + + ) : ( +
+ patch({ username })} /> + {/* The eye sits inside the field, so the field keeps the column's + trailing edge (LAYOUT-15). One name, "Show password"; whether it + is shown is `aria-pressed` (PC-073). One ring, never cut off + (Pair 18 review, I2): while the eye has focus the field's own + ring stands down, and the eye draws the 2 px ring inside its box, + within the field's frame. */} + patch({ password: e.target.value })} + rightIcon={ + : } + onClick={() => setShownPassword((v) => !v)} + /> + } + /> +
+ )} patch({ notes })} /> {/* #162: kept on this computer only, like a password; never sent to a team. */}