diff --git a/mcp/index.js b/mcp/index.js index 0cedc3cf8..52f47c980 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(), @@ -435,6 +435,8 @@ server.tool( name: z.string().optional(), country: z.string().optional(), notes: z.string().optional(), + change_ip_url: z.string().optional(), + vless: z.record(z.string(), z.unknown()).optional(), }, async (args) => text(await api("/proxies", { method: "POST", body: args })), ); diff --git a/openapi.yaml b/openapi.yaml index 5349829a3..da8e3ef2c 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -2469,15 +2469,15 @@ components: AddProxyRequest: type: object - description: A proxy string OR explicit fields (string wins). + description: A proxy string OR explicit fields (if `proxy` is set, it wins and `vless` is ignored). 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 } + username: { type: string, description: "Proxy username, or VLESS UUID when `kind` is `vless`." } password: { type: string } name: { type: string } country: { type: string } @@ -2485,6 +2485,35 @@ 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`; only `encryption=none` is supported). + 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 } + pinned_peer_cert_sha256: { type: string } + verify_peer_cert_by_name: { type: string } + 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 +2521,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 +2557,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..60e50c0e1 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", "HTTP/2", "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/scripts/lib/class-rules.mjs b/scripts/lib/class-rules.mjs index 2728094b5..ff11055d4 100644 --- a/scripts/lib/class-rules.mjs +++ b/scripts/lib/class-rules.mjs @@ -5,7 +5,10 @@ // text, so scripts/check-classes.test.mjs can test every rule without // Tailwind. import { readFileSync, readdirSync, statSync } from "node:fs"; -import { join, relative } from "node:path"; +import { join, relative, sep } from "node:path"; + +/** Repo-relative path with forward slashes, so allowlists match on Windows. */ +const repoPath = (root, p) => relative(root, p).split(sep).join("/"); /** Class-like tokens in one string. */ export const tokensOf = (s) => s.match(/[^\s"'`{}<;]+/g) ?? []; @@ -209,7 +212,7 @@ export function scanRules(root) { const walk = (dir) => { for (const name of readdirSync(dir)) { const p = join(dir, name); - const rel = relative(root, p); + const rel = repoPath(root, p); if (SKIP.some((re) => re.test(rel))) continue; if (statSync(p).isDirectory()) walk(p); else if (/\.(tsx?|jsx?)$/.test(name)) { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 5716dd815..a5b988a1f 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -6777,6 +6777,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-socks" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7e2948f60dbe26b35f2c7fb74ac2854c1fddded0fe9d7548fcc674a246f7615" +dependencies = [ + "either", + "futures-util", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -8846,6 +8858,7 @@ dependencies = [ "socket2", "tokio", "tokio-btls", + "tokio-socks", "tower", "tower-http", "url", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 37fef147d..23f971ade 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -37,7 +37,7 @@ tauri-build = { version = "2", features = [] } # Optional: only the automation runner uses them. # `cookies` is what makes a session a session; the decompressors are what makes # a real site's answer readable. -wreq = { version = "0.16.1", optional = true, features = ["cookies", "gzip", "brotli", "deflate", "zstd"] } +wreq = { version = "0.16.1", optional = true, features = ["cookies", "gzip", "brotli", "deflate", "zstd", "socks"] } wreq-util = { version = "0.2.0", optional = true, features = ["emulation", "emulation-serde"] } # Extra database drivers for the automation runner (SQLite is rusqlite above, # always present). Optional + behind the automation feature so a non-automation diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index 03cb375c8..6db4774e8 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. @@ -790,22 +792,48 @@ async fn add_proxy(Extension(t): Extension, Json(body): Json crate::space::proxy::ProxyKind::Socks5, Some("http") => crate::space::proxy::ProxyKind::Http, Some("https") => crate::space::proxy::ProxyKind::Https, - _ => crate::space::proxy::ProxyKind::Socks5, + Some("vless") => crate::space::proxy::ProxyKind::Vless, + Some(other) => { + return Err(err( + StatusCode::BAD_REQUEST, + format!("unsupported proxy kind `{other}`; expected socks5, http, https, or vless"), + )); + } + }; + let host_trimmed = host.trim().to_string(); + if host_trimmed.is_empty() { + return Err(err(StatusCode::BAD_REQUEST, "`host` must not be empty")); + } + if port == 0 { + return Err(err(StatusCode::BAD_REQUEST, "`port` must be between 1 and 65535")); + } + 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 { + let entry = crate::space::proxy::ProxyEntry { id: String::new(), - name: String::new(), + name: format!("{host_trimmed}:{port}"), kind, - host, + host: host_trimmed, port, username: body.username.clone().unwrap_or_default(), password: body.password.clone().unwrap_or_default(), country: String::new(), notes: String::new(), + vless, + subscription_id: None, + }; + if matches!(entry.kind, crate::space::proxy::ProxyKind::Vless) { + crate::vless::build_xray_config(&entry, 1080) + .map_err(|e| err(StatusCode::BAD_REQUEST, format!("{e:#}")))?; } + entry }; // metadata overrides (applied to parsed entries too). if let Some(n) = body.name.filter(|s| !s.is_empty()) { diff --git a/src-tauri/src/launch.rs b/src-tauri/src/launch.rs index 1ce601788..871425fad 100644 --- a/src-tauri/src/launch.rs +++ b/src-tauri/src/launch.rs @@ -590,6 +590,7 @@ struct Ready<'a> { 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,14 +608,47 @@ 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()); + let is_vless = input + .proxy + .as_ref() + .is_some_and(|orig| matches!(orig.kind, proxy::ProxyKind::Vless)); + let display_host = input + .proxy + .as_ref() + .map(|orig| orig.host.as_str()) + .or_else(|| effective_proxy.as_ref().map(|p| p.host.as_str())) + .unwrap_or(""); + let display_target = input + .proxy + .as_ref() + .map(|orig| format!("{}:{}", orig.host, orig.port)); + // 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) => { - eprintln!("[launcher] UDP relay OK ({ms} ms) for proxy {}", p.host); + eprintln!("[launcher] UDP relay OK ({ms} ms) for proxy {display_host}"); true } + Err(e) if is_vless => { + // For VLESS, Chromium sends UDP only over loopback to Xray; a failed + // loopback probe definitively means this VLESS bridge cannot carry UDP. + // Never probe direct host STUN here (it leaks host traffic and falsely + // assumes a per-app VPN on censored networks). + eprintln!("[launcher] UDP relay unavailable for VLESS proxy {display_host}: {e}"); + false + } Err(e) => { // A failed probe does not mean the proxy has no relay. Some // VPNs pass UDP for one application and drop it for another, @@ -632,17 +666,15 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> launcher is not.", ); eprintln!( - "[launcher] UDP probe failed for proxy {} ({e}), and this \ - process cannot send UDP at all — leaving UDP enabled", - p.host + "[launcher] UDP probe failed for proxy {display_host} ({e}), and this \ + process cannot send UDP at all — leaving UDP enabled" ); true } else { let cached = proxy::latest_test(&p.id).and_then(|s| s.udp_ms).is_some(); eprintln!( - "[launcher] UDP probe failed for proxy {} ({e}) while this \ - process CAN send UDP, so the proxy has no relay; cached={cached}", - p.host + "[launcher] UDP probe failed for proxy {display_host} ({e}) while this \ + process CAN send UDP, so the proxy has no relay; cached={cached}" ); cached } @@ -668,7 +700,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; + let resolved_geo = resolve_auto_fields(&mut raw, effective_proxy.as_ref(), display_target.as_deref()).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 @@ -757,8 +789,10 @@ async fn start_browser(bin: &Path, input: LaunchInput, opts: &LaunchOpts<'_>) -> Err(e) => eprintln!("[launcher] bookmarks skipped: {e}"), } - // Live geo for ICE-candidate spoofing, cached snapshot as fallback. - let proxy_public_ip: Option = if let Some(p) = input.proxy.as_ref() { + // Live geo for ICE-candidate spoofing (reuse auto-field geo if available), cached snapshot as fallback. + let proxy_public_ip: Option = if let Some(ip) = resolved_geo.and_then(|g| (!g.ip.is_empty()).then_some(g.ip)) { + Some(ip) + } else 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 +814,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 +858,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 +1007,12 @@ fn command_line( } if let Some(p) = input.proxy.as_ref() { - args.push(format!("--proxy-server={}", p.to_proxy_server_arg())); + let server_arg = match ready.proxy_server_arg { + Some(arg) => arg.to_string(), + None if matches!(p.kind, proxy::ProxyKind::Vless) => "socks5://127.0.0.1:0".to_string(), + None => 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 { @@ -1124,7 +1164,8 @@ async fn read_devtools_endpoint(udd: &Path) -> Option { async fn resolve_auto_fields( cfg: &mut serde_json::Map, proxy_opt: Option<&proxy::ProxyEntry>, -) { + display_target: Option<&str>, +) -> Option { let want_tz_auto = cfg.get("timezone").and_then(|v| v.as_str()) == Some("auto"); let want_lang_auto = cfg .get("navigator") @@ -1137,7 +1178,7 @@ async fn resolve_auto_fields( ); if !(want_tz_auto || want_lang_auto || want_geo_auto) { - return; + return None; } eprintln!( @@ -1145,7 +1186,10 @@ async fn resolve_auto_fields( want_tz_auto, want_lang_auto, want_geo_auto, - proxy_opt.map(|p| format!("{}:{}", p.host, p.port)).unwrap_or_else(|| "(direct)".into()), + display_target + .map(str::to_string) + .or_else(|| proxy_opt.map(|p| format!("{}:{}", p.host, p.port))) + .unwrap_or_else(|| "(direct)".into()), ); // ---- geo source ---- @@ -1301,6 +1345,7 @@ async fn resolve_auto_fields( cfg.remove("geolocation"); } } + geo } /// Version string as numbers, so "4.10.2891.0" sorts above "4.9.9999.0". @@ -1831,6 +1876,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 +1897,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..152d52957 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; @@ -976,6 +977,12 @@ async fn automation_call( #[cfg(feature = "automation")] { space::cdp_pass(&profile_id)?; + if method == "Traffic.setProxy" { + let raw = params.get("proxy").and_then(|v| v.as_str()).unwrap_or(""); + return runner::swap_browser_proxy(&profile_id, raw) + .await + .map_err(|e| e.to_string()); + } return cdp::page_call(&profile_id, &method, params) .await .map_err(|e| e.to_string()); @@ -1731,9 +1738,10 @@ fn proxy_last_test(id: String) -> Option { #[tauri::command] async fn proxy_bulk_import(text: String, kind: String, epoch: Option) -> Result { let t = ticket(epoch)?; - let default_kind = match kind.as_str() { + let default_kind = match kind.trim().to_ascii_lowercase().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); @@ -1743,14 +1751,80 @@ async fn proxy_bulk_import(text: String, kind: String, epoch: Option) -> Re /// Parse bulk-import text without saving (preview list with per-row test). #[tauri::command] fn proxy_bulk_parse(text: String, kind: String) -> Vec { - let default_kind = match kind.as_str() { + let default_kind = match kind.trim().to_ascii_lowercase().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] +async fn vless_status(path: Option) -> Result { + tauri::async_runtime::spawn_blocking(move || vless::status_for(path.as_deref())) + .await + .map_err(|e| e.to_string()) +} + +#[tauri::command] +async fn vless_ensure() -> Result { + vless::ensure_xray_binary().await.map_err(|e| e.to_string())?; + vless_status(None).await +} + +#[tauri::command] +async fn proxy_subscription_list() -> Result, String> { + space::ready().await; + space::proxy_subscription::list().map_err(|e| e.to_string()) +} + +#[tauri::command] +async fn proxy_subscription_add( + url: String, + name: Option, + auto_update: Option, + update_interval_hours: Option, +) -> Result { + space::ready().await; + let res = space::proxy_subscription::add(url, name, auto_update, update_interval_hours) + .await + .map_err(|e| e.to_string())?; + notify_store_changed("proxies"); + Ok(res) +} + +#[tauri::command] +async fn proxy_subscription_refresh( + id: String, +) -> Result { + space::ready().await; + let res = space::proxy_subscription::refresh(&id) + .await + .map_err(|e| e.to_string())?; + notify_store_changed("proxies"); + Ok(res) +} + +#[tauri::command] +async fn proxy_subscription_update( + id: String, + patch: space::proxy_subscription::SubscriptionUpdatePatch, +) -> Result { + space::ready().await; + let sub = space::proxy_subscription::update(&id, patch).map_err(|e| e.to_string())?; + notify_store_changed("proxies"); + Ok(sub) +} + +#[tauri::command] +async fn proxy_subscription_delete(id: String, remove_proxies: bool) -> Result { + space::ready().await; + let removed = space::proxy_subscription::delete(&id, remove_proxies).map_err(|e| e.to_string())?; + notify_store_changed("proxies"); + Ok(removed) +} + /// Persist pre-tested proxies (bulk dialog). #[tauri::command] async fn proxy_bulk_save(entries: Vec, epoch: Option) -> Result { @@ -2898,6 +2972,13 @@ pub fn run() { proxy_bulk_import, proxy_bulk_parse, proxy_bulk_save, + vless_status, + vless_ensure, + proxy_subscription_list, + proxy_subscription_add, + proxy_subscription_refresh, + proxy_subscription_update, + proxy_subscription_delete, launch, settings_get, settings_save, @@ -3127,30 +3208,40 @@ pub fn run() { if reset::active() && code != Some(tauri::RESTART_EXIT_CODE) { api.prevent_exit(); notify_warning(reset::WAIT); - } else if (space::open::any_open() || space::profile::any_unsealed()) && code != Some(tauri::RESTART_EXIT_CODE) { + } else if (space::open::any_open() + || space::profile::any_unsealed() + || process::Tracker::shared().has_vless()) + && code != Some(tauri::RESTART_EXIT_CODE) + { api.prevent_exit(); exit_app(app, code.unwrap_or(0)); } + } else if let tauri::RunEvent::Exit = event { + vless::shutdown_all(); } }); } -/// Exit, once the team profiles open here are closed, sent back and wiped. +/// Exit, once the team, synced, protected, and VLESS-bridged profiles open here close. 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() { + let has_vless = process::Tracker::shared().has_vless(); + if !space::open::any_open() && !space::profile::any_unsealed() && !has_vless { + vless::shutdown_all(); app.exit(code); return; } if CLOSING.swap(true, SeqCst) { return; } - notify_warning("Saving the team, synced and protected profiles open here before quitting…"); + notify_warning("Closing VLESS-bridged and synced profiles open here before quitting…"); let app = app.clone(); tauri::async_runtime::spawn(async move { + process::Tracker::shared().close_vless(space::open::QUIT_WAIT).await; 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..32a481407 100644 --- a/src-tauri/src/process.rs +++ b/src-tauri/src/process.rs @@ -56,6 +56,8 @@ struct ChildEntry { started_at: Instant, /// Library extensions it started with: their folders are not swapped under it. extensions: Vec, + /// Held local Xray bridge lease for VLESS profiles (swappable via `proxy.swap`). + vless: Option, } /// What is done once a browser has closed for good. @@ -114,6 +116,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); @@ -124,7 +127,15 @@ impl Tracker { let mut g = self.inner.lock().unwrap(); let previous = g.insert( profile_id.clone(), - ChildEntry { pid, gen, killer: tx, cdp: None, started_at: Instant::now(), extensions }, + ChildEntry { + pid, + gen, + killer: tx, + cdp: None, + started_at: Instant::now(), + extensions, + vless, + }, ); // Replacing the entry drops the old killer and orphans that browser. // `launch` refuses a second launch up front; this is the backstop. @@ -215,6 +226,35 @@ impl Tracker { self.inner.lock().ok()?.get(profile_id)?.cdp.clone() } + pub fn set_vless_lease(&self, profile_id: &str, lease: Option) { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(entry) = g.get_mut(profile_id) { + entry.vless = lease; + } + } + + pub fn has_vless(&self) -> bool { + let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.values().any(|e| e.vless.is_some()) + } + + pub async fn close_vless(&self, limit: Duration) { + let ids: Vec = { + let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.iter() + .filter(|(_, e)| e.vless.is_some()) + .map(|(id, _)| id.clone()) + .collect() + }; + for id in &ids { + let _ = self.kill(id).await; + } + let until = std::time::Instant::now() + limit; + while self.has_vless() && std::time::Instant::now() < until { + tokio::time::sleep(Duration::from_millis(150)).await; + } + } + /// Profiles running with library extension `lib_id`. pub fn users_of(&self, lib_id: &str) -> Vec { let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); @@ -748,7 +788,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 +919,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..34375dba1 100644 --- a/src-tauri/src/psapi.rs +++ b/src-tauri/src/psapi.rs @@ -186,6 +186,8 @@ 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, + subscription_id: None, }); } @@ -417,6 +419,8 @@ pub async fn residential_proxy(req: ResiRequest<'_>) -> Result { .map(|c| c.trim().to_uppercase()) .unwrap_or_default(), notes: format!("ProxyShard residential ({plan})"), + vless: None, + subscription_id: None, }) } diff --git a/src-tauri/src/requests.rs b/src-tauri/src/requests.rs index 9216a9fcc..bfcf3fd21 100644 --- a/src-tauri/src/requests.rs +++ b/src-tauri/src/requests.rs @@ -23,11 +23,16 @@ use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; use std::time::Duration; +struct SessionEntry { + client: wreq::Client, + _vless_lease: Option, +} + /// Clients held open by name. Never keyed on the URL: a session is the /// operator's idea of "the same visitor", and only they know which calls /// belong to one. -fn sessions() -> &'static Mutex> { - static S: OnceLock>> = OnceLock::new(); +fn sessions() -> &'static Mutex> { + static S: OnceLock>> = OnceLock::new(); S.get_or_init(|| Mutex::new(HashMap::new())) } @@ -61,6 +66,7 @@ pub struct Request { pub fingerprint: Option, pub session: Option, pub proxy: Option, + pub vless_lease: Option, pub timeout_s: f64, } @@ -98,7 +104,7 @@ pub async fn send(req: Request) -> Result { .lock() .map_err(|_| anyhow!("session lock poisoned"))? .get(name) - .cloned(); + .map(|e| e.client.clone()); match existing { Some(c) => c, None => { @@ -111,7 +117,13 @@ pub async fn send(req: Request) -> Result { sessions() .lock() .map_err(|_| anyhow!("session lock poisoned"))? - .insert(name.to_string(), c.clone()); + .insert( + name.to_string(), + SessionEntry { + client: c.clone(), + _vless_lease: req.vless_lease, + }, + ); c } } diff --git a/src-tauri/src/reset.rs b/src-tauri/src/reset.rs index d7c04d6c2..a6723f59a 100644 --- a/src-tauri/src/reset.rs +++ b/src-tauri/src/reset.rs @@ -45,6 +45,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; const CONFIG_ENTRIES: &[&str] = &[ "proxies.json", "proxies-history.json", + "proxy-rotation.json", + "proxy-subscriptions.json", + "proxy-subscriptions.json.tmp", "bookmarks.json", "tags.json", "tags.json.tmp", @@ -1257,6 +1260,7 @@ async fn stop_everything() -> Result<()> { } } if running.is_empty() && runs == 0 { + crate::vless::shutdown_all(); return Ok(()); } if Instant::now() >= deadline { diff --git a/src-tauri/src/runner.rs b/src-tauri/src/runner.rs index 56c6d70e1..7d175d122 100644 --- a/src-tauri/src/runner.rs +++ b/src-tauri/src/runner.rs @@ -1452,25 +1452,48 @@ async fn run_block( // Out through the profile's own proxy unless told otherwise: a // 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, - "profile" if !bound.id.is_empty() => { - run.space.still()?; - let stored = profile::load_raw(&bound.id)?; - let bound_proxy = stored - .meta - .proxy_id - .as_deref() - .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, + let via_raw = expand(param(p, "via").unwrap_or("profile"), vars); + let via = via_raw.trim(); + let (proxy, vless_lease) = match via { + "host" => (None, None), + "" | "profile" => { + if bound.id.is_empty() { + (None, None) + } else { + run.space.still()?; + let bound_proxy = if run.space.team().is_some() { + let meta = crate::space::profile::list_all()? + .into_iter() + .find(|m| m.id == bound.id); + meta.and_then(|m| m.proxy_id) + .and_then(|id| crate::space::proxy::get(&id).ok().flatten()) + } else { + let stored = profile::load_raw(&bound.id)?; + stored + .meta + .proxy_id + .as_deref() + .and_then(|id| proxy::get(id).ok().flatten()) + .or(stored.meta.inline_proxy) + }; + match bound_proxy { + Some(pr) => { + let (resolved, lease) = proxy::resolve_transport(&pr).await?; + (Some(resolved.to_socks5h_proxy_url()), lease) + } + None => (None, None), + } } } - "profile" => None, - other => Some(expand(other, vars)), + "custom" => { + let raw = expand(param(p, "proxy").unwrap_or(""), vars); + let trimmed = raw.trim(); + if trimmed.is_empty() { + anyhow::bail!("http.request with via = custom requires a proxy address"); + } + resolve_http_proxy(trimmed).await? + } + other => resolve_http_proxy(other).await?, }; let out = crate::requests::send(crate::requests::Request { @@ -1481,6 +1504,7 @@ async fn run_block( fingerprint, session, proxy, + vless_lease, timeout_s: param_f64(p, "timeout", vars).unwrap_or(30.0), }) .await?; @@ -1710,14 +1734,9 @@ async fn run_block( } "proxy.swap" => { // Hot-swap the profile's proxy through the core, no restart. Empty - // proxy = direct. Full URL scheme://user:pass@host:port. + // proxy = direct. Accepts `vless://...` or `scheme://user:pass@host:port`. let proxy = param(p, "proxy").map(|s| expand(s, vars)).unwrap_or_default(); - let args = if proxy.trim().is_empty() { - json!({}) - } else { - json!({ "proxy": proxy }) - }; - cdp::page_call(profile, "Traffic.setProxy", args).await?; + swap_browser_proxy(profile, &proxy).await?; run.log("swapped the proxy"); return Ok(Flow::Next); } @@ -2666,6 +2685,34 @@ async fn run_worker( } } +async fn resolve_http_proxy(raw: &str) -> Result<(Option, Option)> { + if let Some(pr) = proxy::parse_single(raw) { + let (resolved, lease) = proxy::resolve_transport(&pr).await?; + Ok((Some(resolved.to_socks5h_proxy_url()), lease)) + } else if let Some(rest) = raw.strip_prefix("socks5://") { + Ok((Some(format!("socks5h://{rest}")), None)) + } else { + Ok((Some(raw.to_string()), None)) + } +} + +/// Hot-swap the proxy for a running automated browser, bridging `vless://` URIs +/// through local Xray-core and storing/replacing the live `VlessLease` on `Tracker`. +pub async fn swap_browser_proxy(profile_id: &str, raw_proxy: &str) -> Result { + let trimmed = raw_proxy.trim(); + let (args, lease) = if trimmed.is_empty() { + (json!({}), None) + } else if let Some(parsed) = proxy::parse_single(trimmed) { + let (resolved, lease) = proxy::resolve_transport(&parsed).await?; + (json!({ "proxy": resolved.to_proxy_server_arg() }), lease) + } else { + (json!({ "proxy": trimmed }), None) + }; + let out = cdp::page_call(profile_id, "Traffic.setProxy", args).await?; + crate::process::Tracker::shared().set_vless_lease(profile_id, lease); + Ok(out) +} + pub async fn start(project_id: &str) -> Result<()> { if migrate::in_progress() { return Err(anyhow!("profiles are being moved — try again when that finishes")); 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..babec400d 100644 --- a/src-tauri/src/space/doors.rs +++ b/src-tauri/src/space/doors.rs @@ -268,6 +268,13 @@ const RULES: &[(&str, Need)] = &[ ("proxy_bulk_import", CREATE_T), ("proxy_bulk_save", CREATE_T), ("proxy_bulk_parse", Machine), + ("vless_status", Machine), + ("vless_ensure", Machine), + ("proxy_subscription_list", Off), + ("proxy_subscription_add", Off), + ("proxy_subscription_refresh", Off), + ("proxy_subscription_update", Off), + ("proxy_subscription_delete", Off), // #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/mod.rs b/src-tauri/src/space/local/mod.rs index fc0f1006e..b2f05fb12 100644 --- a/src-tauri/src/space/local/mod.rs +++ b/src-tauri/src/space/local/mod.rs @@ -10,6 +10,7 @@ pub(in crate::space) mod profile; pub(in crate::space) mod protect; pub(in crate::space) mod proxy; pub(in crate::space) mod seal; +pub(in crate::space) mod subscriptions; pub(in crate::space) mod tags; pub(in crate::space) mod templates; pub(in crate::space) mod trash; diff --git a/src-tauri/src/space/local/protect.rs b/src-tauri/src/space/local/protect.rs index 0b822fb2e..64d8ceb0e 100644 --- a/src-tauri/src/space/local/protect.rs +++ b/src-tauri/src/space/local/protect.rs @@ -187,7 +187,10 @@ pub(in crate::space) fn save_full(full: &StoredProfile, key: &DataKey) -> Result next.meta.last_launched_at = existing.meta.last_launched_at.clone(); next.meta.total_runtime_ms = existing.meta.total_runtime_ms; let before = full_of(&existing, key)?; - next.meta.rev = if before.config == next.config && before.meta.proxy_id == next.meta.proxy_id { + next.meta.rev = if before.config == next.config + && before.meta.proxy_id == next.meta.proxy_id + && before.meta.inline_proxy == next.meta.inline_proxy + { existing.meta.rev } else { existing.meta.rev.wrapping_add(1) diff --git a/src-tauri/src/space/local/proxy.rs b/src-tauri/src/space/local/proxy.rs index c20e6eefb..7783ca3ee 100644 --- a/src-tauri/src/space/local/proxy.rs +++ b/src-tauri/src/space/local/proxy.rs @@ -12,9 +12,129 @@ pub enum ProxyKind { Socks5, Http, Https, + Vless, } -#[derive(Debug, Clone, Serialize, Deserialize)] +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 pinned_peer_cert_sha256: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub verify_peer_cert_by_name: String, + #[serde(rename = "host", alias = "host_header", 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(), + "xtls" => "tls".to_string(), + other => other.to_string(), + }; + let alpn = self + .alpn + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect::>() + .join(","); + let pinned_peer_cert_sha256 = self + .pinned_peer_cert_sha256 + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .collect::>() + .join(","); + let verify_peer_cert_by_name = self + .verify_peer_cert_by_name + .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_ascii_lowercase(), + spider_x: self.spider_x.trim().to_string(), + pqv: self.pqv.trim().to_string(), + alpn, + allow_insecure: self.allow_insecure, + pinned_peer_cert_sha256, + verify_peer_cert_by_name, + 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, PartialEq, Eq, Serialize, Deserialize)] pub struct ProxyEntry { #[serde(default)] pub id: String, @@ -32,20 +152,90 @@ pub struct ProxyEntry { /// Free-form note. #[serde(default)] pub notes: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vless: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subscription_id: 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("pcs", &cfg.pinned_peer_cert_sha256); + push_kv("vcn", &cfg.verify_peer_cert_by_name); + 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 +244,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() { @@ -66,6 +257,17 @@ impl ProxyEntry { ) } } + + /// Build a `socks5h://` / `http://` / `https://` URL for HTTP clients so + /// SOCKS5 hostname resolution always executes through the remote proxy. + pub fn to_socks5h_proxy_url(&self) -> String { + let arg = self.to_proxy_server_arg(); + if let Some(rest) = arg.strip_prefix("socks5://") { + format!("socks5h://{rest}") + } else { + arg + } + } } /// A username or password as it may appear inside a proxy URL. @@ -136,7 +338,26 @@ pub(in crate::space) fn load() -> Result { Ok(serde_json::from_str(&body).unwrap_or_default()) } -fn save(s: &ProxyStore) -> Result<()> { +/// Extract an ISO 3166-1 alpha-2 country code from the first Unicode +/// regional-indicator flag emoji (e.g. `🇳🇱` -> `"NL"`). +pub fn extract_flag_country(text: &str) -> String { + let mut prev: Option = None; + for ch in text.chars() { + let code = ch as u32; + if (0x1F1E6..=0x1F1FF).contains(&code) { + let letter = char::from_u32((code - 0x1F1E6) + ('A' as u32)).unwrap(); + if let Some(first) = prev { + return format!("{first}{letter}"); + } + prev = Some(letter); + } else { + prev = None; + } + } + String::new() +} + +pub(in crate::space::local) fn save(s: &ProxyStore) -> Result<()> { let body = serde_json::to_string_pretty(s)?; fs::write(store::proxies_path()?, body)?; Ok(()) @@ -195,6 +416,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 @@ -217,9 +439,21 @@ pub(in crate::space) fn delete(id: &str) -> Result<()> { let mut s = load()?; s.proxies.retain(|p| p.id != id); save(&s)?; - // Also wipe persisted test history. + purge_history(&[id.to_string()])?; + Ok(()) +} + +pub(in crate::space::local) fn purge_history(ids: &[String]) -> Result<()> { + if ids.is_empty() { + return Ok(()); + } with_history(|hs| { - let gone = hs.by_proxy.remove(id).is_some(); + let mut gone = false; + for id in ids { + if hs.by_proxy.remove(id).is_some() { + gone = true; + } + } Ok(((), gone)) })?; Ok(()) @@ -350,6 +584,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 +604,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 +642,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 +726,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 +734,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 +746,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,18 +789,138 @@ 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") || val.eq_ignore_ascii_case("yes"); + } + "pcs" | "pinnedpeercertsha256" => cfg.pinned_peer_cert_sha256 = val, + "vcn" | "verifypeercertbyname" => cfg.verify_peer_cert_by_name = val, + "ed" => { + let trimmed_ed = val.trim(); + if !trimmed_ed.is_empty() && trimmed_ed.chars().all(|c| c.is_ascii_digit()) { + let base = if cfg.path.trim().is_empty() { "/" } else { cfg.path.trim() }; + if !base.contains("ed=") { + let sep = if base.contains('?') { '&' } else { '?' }; + cfg.path = format!("{base}{sep}ed={trimmed_ed}"); + } + } + } + "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}")); + let country = extract_flag_country(&name); + + Some(ProxyEntry { + id: uuid::Uuid::new_v4().to_string(), + name, + kind: ProxyKind::Vless, + host: host.to_string(), + port, + username: uuid, + password: String::new(), + country, + notes: String::new(), + vless: Some(cfg.normalized()), + subscription_id: None, + }) +} + 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("://") { + return line + .split_once('@') + .filter(|(u, _)| !u.is_empty() && !u.contains(':')) + .and_then(|_| parse_vless_uri(&format!("vless://{line}"))); + } // Optional trailing `# country=US note=foo`. let (main, comment) = match line.find('#') { Some(i) => (line[..i].trim(), Some(line[i + 1..].trim())), None => (line, None), }; - let (kind, rest) = if let Some(r) = main.strip_prefix("socks5://") { - (ProxyKind::Socks5, r) - } else if let Some(r) = main.strip_prefix("https://") { - (ProxyKind::Https, r) - } else if let Some(r) = main.strip_prefix("http://") { - (ProxyKind::Http, r) + let (kind, rest) = if line.get(..9).is_some_and(|p| p.eq_ignore_ascii_case("socks5h://")) { + (ProxyKind::Socks5, &main[10..]) + } else if line.get(..9).is_some_and(|p| p.eq_ignore_ascii_case("socks5://")) { + (ProxyKind::Socks5, &main[9..]) + } else if line.get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) { + (ProxyKind::Https, &main[8..]) + } else if line.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("http://")) { + (ProxyKind::Http, &main[7..]) } else { (default_kind.clone(), main) }; @@ -550,19 +955,23 @@ fn parse_one(line: &str, default_kind: &ProxyKind) -> Option { let mut country = String::new(); let mut notes = String::new(); // The comment is the name; `key=value` is only for lines older builds wrote. - let mut name_parts: Vec<&str> = Vec::new(); + let mut name_parts: Vec = Vec::new(); if let Some(c) = comment { - for kv in c.split_whitespace() { + let decoded = percent_decode_userinfo(c); + for kv in decoded.split_whitespace() { if let Some(v) = kv.strip_prefix("country=") { country = v.to_string(); } else if let Some(v) = kv.strip_prefix("note=") { notes = v.to_string(); } else { - name_parts.push(kv.trim_start_matches('#')); + name_parts.push(kv.trim_start_matches('#').to_string()); } } } let name = name_parts.join(" "); + if country.is_empty() { + country = extract_flag_country(&name); + } Some(ProxyEntry { // ID assigned now so pre-save test snapshots key under the kept uuid. id: uuid::Uuid::new_v4().to_string(), @@ -574,6 +983,8 @@ fn parse_one(line: &str, default_kind: &ProxyKind) -> Option { password: pass, country, notes, + vless: None, + subscription_id: None, }) } @@ -646,7 +1057,10 @@ async fn resolve_stun_ipv4() -> Result<(std::net::Ipv4Addr, u16)> { } } } - anyhow::bail!("no STUN server resolved to IPv4") + // Fallback to Cloudflare's public anycast STUN IP when host DNS fails (e.g. poisoned/censored local DNS). + let fallback = (std::net::Ipv4Addr::new(162, 159, 207, 55), 3478); + let _ = STUN_ADDR.set(fallback); + Ok(fallback) } /// Can THIS process send UDP at all? Answers the question the relay probe @@ -675,6 +1089,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 +1329,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 +1348,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 +1370,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 +1466,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 +1881,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 +1916,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 +2248,80 @@ 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)); + + // Wire key "host" and legacy "host_header", xtls alias, pcs/vcn/ed parity + let from_wire: VlessConfig = serde_json::from_str(r#"{"network":"ws","host":"cdn.wire.example","pinned_peer_cert_sha256":"AA","verify_peer_cert_by_name":"alt.example"}"#).unwrap(); + let serialized_wire = serde_json::to_value(&from_wire).unwrap(); + assert_eq!(serialized_wire["host"], "cdn.wire.example"); + assert!(serialized_wire.get("host_header").is_none()); + let from_legacy: VlessConfig = serde_json::from_str(r#"{"host_header":"legacy.example"}"#).unwrap(); + assert_eq!(from_legacy.host_header, "legacy.example"); + + let xtls_ed = parse_single("vless://11111111-2222-3333-4444-555555555555@e.example.com:443?security=xtls&type=ws&ed=2048&pcs=0011&vcn=cert.example&allowInsecure=yes&sid=ABcD").unwrap(); + let xtls_cfg = xtls_ed.vless.as_ref().unwrap(); + assert_eq!(xtls_cfg.security, "tls"); + assert_eq!(xtls_cfg.path, "/?ed=2048"); + assert_eq!(xtls_cfg.pinned_peer_cert_sha256, "0011"); + assert_eq!(xtls_cfg.verify_peer_cert_by_name, "cert.example"); + assert!(xtls_cfg.allow_insecure); + assert_eq!(xtls_cfg.short_id, "abcd"); + + // Bulk parse with ProxyKind::Vless ignores non-VLESS lines instead of making UUID-less Vless entries + assert!(parse_bulk("192.0.2.1:1080\nuser:pass@192.0.2.2:1080", ProxyKind::Vless).is_empty()); + } + + #[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/local/subscriptions.rs b/src-tauri/src/space/local/subscriptions.rs new file mode 100644 index 000000000..a5fc52647 --- /dev/null +++ b/src-tauri/src/space/local/subscriptions.rs @@ -0,0 +1,1097 @@ +use crate::store; +use anyhow::{Context, Result}; +use base64::{ + engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD}, + Engine as _, +}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fs; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use url::Url; + +use super::proxy::{ + self, parse_single, percent_decode_userinfo, purge_history, rotation_set, ProxyEntry, + ProxyKind, +}; + +const MAX_BODY_BYTES: usize = 8 * 1024 * 1024; +const DEFAULT_INTERVAL_HOURS: u32 = 12; + +/// Serializes read-modify-write across `proxy-subscriptions.json` and `proxies.json`. +/// Never held across an `.await`. +static STORE_LOCK: Mutex<()> = Mutex::new(()); + +fn lock_store() -> Result> { + STORE_LOCK + .lock() + .map_err(|_| anyhow::anyhow!("subscription store lock poisoned")) +} + +fn now_stamp() -> String { + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + format!("@{secs}") +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProxySubscription { + pub id: String, + pub url: String, + pub name: String, + #[serde(default)] + pub name_override: bool, + #[serde(default = "default_auto_update")] + pub auto_update: bool, + #[serde(default = "default_interval_hours")] + pub update_interval_hours: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub upload_bytes: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub download_bytes: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub total_bytes: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub expire_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub web_page_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub support_url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub announce: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub announce_url: Option, + #[serde(default)] + pub node_count: usize, + #[serde(default)] + pub skipped_count: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_updated: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_error: Option, +} + +fn default_auto_update() -> bool { + true +} + +fn default_interval_hours() -> u32 { + DEFAULT_INTERVAL_HOURS +} + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct SubscriptionStore { + #[serde(default)] + pub subscriptions: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SubscriptionSyncResult { + pub subscription: ProxySubscription, + pub added: usize, + pub updated: usize, + pub removed: usize, + pub skipped: usize, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct SubscriptionUpdatePatch { + pub name: Option, + pub url: Option, + pub auto_update: Option, + pub update_interval_hours: Option, +} + +#[derive(Debug, Clone)] +pub struct ParsedSubscription { + pub title: Option, + pub update_interval_hours: Option, + pub upload_bytes: Option, + pub download_bytes: Option, + pub total_bytes: Option, + pub expire_at: Option, + pub web_page_url: Option, + pub support_url: Option, + pub announce: Option, + pub announce_url: Option, + pub entries: Vec, + pub skipped_count: usize, +} + +fn load_store_unlocked() -> Result { + let path = store::subscriptions_path()?; + if !path.exists() { + return Ok(SubscriptionStore::default()); + } + let body = fs::read_to_string(&path)?; + if body.trim().is_empty() { + return Ok(SubscriptionStore::default()); + } + let store_data: SubscriptionStore = serde_json::from_str(&body) + .with_context(|| format!("could not parse {}", path.display()))?; + Ok(store_data) +} + +fn save_store_unlocked(s: &SubscriptionStore) -> Result<()> { + let path = store::subscriptions_path()?; + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let tmp = path.with_extension("json.tmp"); + let body = serde_json::to_string_pretty(s)?; + fs::write(&tmp, &body)?; + if fs::rename(&tmp, &path).is_err() { + fs::write(&path, &body)?; + let _ = fs::remove_file(&tmp); + } + Ok(()) +} + +pub fn validate_subscription_url(raw: &str) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() { + anyhow::bail!("subscription URL is required"); + } + let parsed = Url::parse(trimmed).context("subscription URL is not valid")?; + if !matches!(parsed.scheme(), "http" | "https") { + anyhow::bail!("subscription URL must start with http:// or https://"); + } + if parsed.host_str().is_none_or(str::is_empty) { + anyhow::bail!("subscription URL must include a host"); + } + Ok(parsed.to_string()) +} + +fn same_subscription_url(a: &str, b: &str) -> bool { + match (Url::parse(a.trim()), Url::parse(b.trim())) { + (Ok(ua), Ok(ub)) => ua == ub, + _ => a.trim().eq_ignore_ascii_case(b.trim()), + } +} + +pub fn sanitize_http_url(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return None; + } + let parsed = Url::parse(trimmed).ok()?; + if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none_or(str::is_empty) { + return None; + } + Some(parsed.to_string()) +} + +fn try_decode_base64(input: &str) -> Option { + let compact: String = input.chars().filter(|c| !c.is_whitespace()).collect(); + if compact.is_empty() { + 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()?; + String::from_utf8(bytes).ok() +} + +pub fn decode_header_value(raw: &str) -> String { + let trimmed = raw.trim(); + if let Some(rest) = trimmed + .strip_prefix("base64:") + .or_else(|| trimmed.strip_prefix("BASE64:")) + { + if let Some(decoded) = try_decode_base64(rest.trim()) { + return decoded.replace("\r\n", "\n").trim().to_string(); + } + } + // Check case-insensitive prefix cleanly as well (e.g., Base64:) + if trimmed.len() >= 7 && trimmed[..7].eq_ignore_ascii_case("base64:") { + if let Some(decoded) = try_decode_base64(trimmed[7..].trim()) { + return decoded.replace("\r\n", "\n").trim().to_string(); + } + } + percent_decode_userinfo(trimmed) + .replace("\r\n", "\n") + .trim() + .to_string() +} + +pub fn parse_userinfo(raw: &str) -> (Option, Option, Option, Option) { + let mut upload = None; + let mut download = None; + let mut total = None; + let mut expire = None; + for part in raw.split(';') { + let Some((k, v)) = part.split_once('=') else { + continue; + }; + let key = k.trim().to_ascii_lowercase(); + let val = v.trim(); + match key.as_str() { + "upload" => upload = val.parse::().ok(), + "download" => download = val.parse::().ok(), + "total" => total = val.parse::().ok().filter(|&n| n > 0), + "expire" => expire = val.parse::().ok().filter(|&n| n > 0), + _ => {} + } + } + (upload, download, total, expire) +} + +pub fn parse_content_disposition_filename(raw: &str) -> Option { + for part in raw.split(';') { + let p = part.trim(); + if let Some((k, v)) = p.split_once('=') { + let key = k.trim().to_ascii_lowercase(); + let val = v.trim().trim_matches('"'); + if key == "filename*" { + let encoded = val + .split_once("''") + .map(|(_, rest)| rest) + .unwrap_or(val); + let decoded = percent_decode_userinfo(encoded) + .trim_end_matches(".txt") + .trim_end_matches(".yaml") + .trim_end_matches(".yml") + .trim() + .to_string(); + if !decoded.is_empty() { + return Some(decoded); + } + } else if key == "filename" { + let decoded = percent_decode_userinfo(val) + .trim_end_matches(".txt") + .trim_end_matches(".yaml") + .trim_end_matches(".yml") + .trim() + .to_string(); + if !decoded.is_empty() { + return Some(decoded); + } + } + } + } + None +} + +fn contains_known_scheme(text: &str) -> bool { + let lower = text.to_ascii_lowercase(); + [ + "vless://", + "socks5://", + "socks5h://", + "http://", + "https://", + "vmess://", + "trojan://", + "ss://", + "ssr://", + "hysteria://", + "hysteria2://", + "hy2://", + "tuic://", + "wireguard://", + ] + .iter() + .any(|s| lower.contains(s)) +} + +pub fn decode_subscription_body(raw: &str) -> String { + let trimmed = raw.trim(); + if trimmed.is_empty() || contains_known_scheme(trimmed) { + return raw.to_string(); + } + if let Some(decoded) = try_decode_base64(trimmed) { + if contains_known_scheme(&decoded) + || decoded.lines().any(|l| { + let t = l.trim(); + t.starts_with('#') || t.contains(':') + }) + { + return decoded; + } + } + raw.to_string() +} + +fn is_supported_scheme(line: &str) -> bool { + if !line.contains("://") { + return true; + } + let lower = line.to_ascii_lowercase(); + lower.starts_with("vless://") + || lower.starts_with("socks5://") + || lower.starts_with("socks5h://") + || lower.starts_with("http://") + || lower.starts_with("https://") +} + +fn header_lookup<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> { + headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) +} + +pub fn derive_default_name(url: &str) -> String { + Url::parse(url) + .ok() + .and_then(|u| u.host_str().map(str::to_string)) + .filter(|h| !h.is_empty()) + .unwrap_or_else(|| "Subscription".to_string()) +} + +pub fn parse_subscription_payload( + url: &str, + headers: &[(String, String)], + body_raw: &str, +) -> ParsedSubscription { + let mut title = header_lookup(headers, "profile-title") + .map(decode_header_value) + .filter(|s| !s.is_empty()) + .or_else(|| { + header_lookup(headers, "content-disposition") + .and_then(parse_content_disposition_filename) + }); + let mut update_interval_hours = header_lookup(headers, "profile-update-interval") + .and_then(|v| v.trim().parse::().ok()) + .map(|h| h.clamp(1, 720)); + let mut userinfo = header_lookup(headers, "subscription-userinfo") + .map(parse_userinfo) + .unwrap_or((None, None, None, None)); + let mut web_page_url = + header_lookup(headers, "profile-web-page-url").and_then(sanitize_http_url); + let mut support_url = header_lookup(headers, "support-url").and_then(sanitize_http_url); + let mut announce = header_lookup(headers, "announce") + .map(decode_header_value) + .filter(|s| !s.is_empty()); + let mut announce_url = header_lookup(headers, "announce-url").and_then(sanitize_http_url); + + let decoded_body = decode_subscription_body(body_raw); + let mut entries: Vec = Vec::new(); + let mut skipped_count = 0usize; + + for raw in decoded_body.lines() { + let line = raw.trim(); + if line.is_empty() { + continue; + } + if let Some(comment) = line.strip_prefix('#') { + let trimmed_comment = comment.trim(); + if let Some((directive, val)) = trimmed_comment.split_once(':') { + let dkey = directive.trim().to_ascii_lowercase(); + let dval = val.trim(); + match dkey.as_str() { + "profile-title" if title.is_none() => { + let v = decode_header_value(dval); + if !v.is_empty() { + title = Some(v); + } + } + "profile-update-interval" if update_interval_hours.is_none() => { + update_interval_hours = + dval.parse::().ok().map(|h| h.clamp(1, 720)); + } + "subscription-userinfo" + if userinfo == (None, None, None, None) => + { + userinfo = parse_userinfo(dval); + } + "profile-web-page-url" if web_page_url.is_none() => { + web_page_url = sanitize_http_url(dval); + } + "support-url" if support_url.is_none() => { + support_url = sanitize_http_url(dval); + } + "announce" if announce.is_none() => { + let v = decode_header_value(dval); + if !v.is_empty() { + announce = Some(v); + } + } + "announce-url" if announce_url.is_none() => { + announce_url = sanitize_http_url(dval); + } + _ => {} + } + } + continue; + } + + if !is_supported_scheme(line) { + skipped_count += 1; + continue; + } + + if let Some(entry) = parse_single(line) { + if !entries.iter().any(|x| x.same_proxy(&entry)) { + entries.push(entry); + } + } else { + skipped_count += 1; + } + } + + if title.is_none() { + title = Some(derive_default_name(url)); + } + + ParsedSubscription { + title, + update_interval_hours, + upload_bytes: userinfo.0, + download_bytes: userinfo.1, + total_bytes: userinfo.2, + expire_at: userinfo.3, + web_page_url, + support_url, + announce, + announce_url, + entries, + skipped_count, + } +} + +async fn fetch_subscription(url: &str) -> Result { + let valid_url = validate_subscription_url(url)?; + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(20)) + .redirect(reqwest::redirect::Policy::limited(5)) + .user_agent("ShardBrowser/2.1 (v2rayN; Clash; Hiddify)") + .build() + .context("could not build subscription HTTP client")?; + let resp = client + .get(&valid_url) + .send() + .await + .with_context(|| format!("could not fetch subscription from {valid_url}"))?; + let status = resp.status(); + if !status.is_success() { + anyhow::bail!("subscription server returned HTTP {}", status.as_u16()); + } + let headers: Vec<(String, String)> = resp + .headers() + .iter() + .filter_map(|(k, v)| { + v.to_str() + .ok() + .map(|s| (k.as_str().to_ascii_lowercase(), s.to_string())) + }) + .collect(); + let bytes = resp + .bytes() + .await + .context("could not read subscription response body")?; + if bytes.len() > MAX_BODY_BYTES { + anyhow::bail!("subscription response exceeded 8 MiB limit"); + } + let body = String::from_utf8_lossy(&bytes).into_owned(); + Ok(parse_subscription_payload(&valid_url, &headers, &body)) +} + +fn sync_proxies_unlocked( + sub_id: &str, + parsed: Vec, +) -> Result<(usize, usize, usize, Vec)> { + let mut proxy_store = proxy::load()?; + let mut existing_sub: Vec = Vec::new(); + let mut other_proxies: Vec = Vec::new(); + for p in proxy_store.proxies { + if p.subscription_id.as_deref() == Some(sub_id) { + existing_sub.push(p); + } else { + other_proxies.push(p); + } + } + + let mut used = vec![false; existing_sub.len()]; + let mut matched_idx: Vec> = vec![None; parsed.len()]; + + // Pass 1: exact same_proxy match + for (pi, p) in parsed.iter().enumerate() { + if let Some(ei) = existing_sub + .iter() + .enumerate() + .find(|(idx, old)| !used[*idx] && old.same_proxy(p)) + .map(|(idx, _)| idx) + { + used[ei] = true; + matched_idx[pi] = Some(ei); + } + } + + // Count endpoint keys across existing unused + incoming unmatched so ambiguous session-routed gateways don't cross-bind + let endpoint_key = |p: &ProxyEntry| { + ( + matches!(p.kind, ProxyKind::Vless), + format!("{:?}", p.kind), + p.host.clone(), + p.port, + p.username.clone(), + ) + }; + let mut old_key_counts: HashMap<_, usize> = HashMap::new(); + for (ei, old) in existing_sub.iter().enumerate() { + if !used[ei] { + *old_key_counts.entry(endpoint_key(old)).or_insert(0) += 1; + } + } + + // Pass 2: endpoint match when unique (keeps proxy id & profile bindings if node params/name changed) + for (pi, p) in parsed.iter().enumerate() { + if matched_idx[pi].is_some() { + continue; + } + let k = endpoint_key(p); + if old_key_counts.get(&k).copied().unwrap_or(0) == 1 { + if let Some(ei) = existing_sub + .iter() + .enumerate() + .find(|(idx, old)| !used[*idx] && endpoint_key(old) == k) + .map(|(idx, _)| idx) + { + used[ei] = true; + matched_idx[pi] = Some(ei); + } + } + } + + let mut added = 0usize; + let mut updated = 0usize; + let mut synced: Vec = Vec::with_capacity(parsed.len()); + + for (pi, mut p) in parsed.into_iter().enumerate() { + p.subscription_id = Some(sub_id.to_string()); + if let Some(ei) = matched_idx[pi] { + let old = &existing_sub[ei]; + p.id = old.id.clone(); + if p.notes.is_empty() && !old.notes.is_empty() { + p.notes = old.notes.clone(); + } + if p.country.is_empty() && !old.country.is_empty() { + p.country = old.country.clone(); + } + updated += 1; + } else { + if p.id.is_empty() { + p.id = uuid::Uuid::new_v4().to_string(); + } + added += 1; + } + synced.push(p); + } + + let removed_ids: Vec = existing_sub + .into_iter() + .enumerate() + .filter(|(idx, _)| !used[*idx]) + .map(|(_, old)| old.id) + .collect(); + let removed = removed_ids.len(); + + other_proxies.extend(synced); + proxy_store.proxies = other_proxies; + proxy::save(&proxy_store)?; + + Ok((added, updated, removed, removed_ids)) +} + +fn cleanup_proxy_metadata(ids: &[String]) { + if ids.is_empty() { + return; + } + let _ = purge_history(ids); + for id in ids { + let _ = rotation_set(id, None); + } +} + +pub(in crate::space) fn list() -> Result> { + let _guard = lock_store()?; + Ok(load_store_unlocked()?.subscriptions) +} + +pub(in crate::space) async fn add( + url: String, + name: Option, + auto_update: Option, + update_interval_hours: Option, +) -> Result { + let valid_url = validate_subscription_url(&url)?; + { + let _guard = lock_store()?; + let store_data = load_store_unlocked()?; + if store_data + .subscriptions + .iter() + .any(|s| same_subscription_url(&s.url, &valid_url)) + { + anyhow::bail!("a subscription with this URL already exists"); + } + } + + let parsed = fetch_subscription(&valid_url).await?; + let skipped = parsed.skipped_count; + let node_count = parsed.entries.len(); + let custom_name = name.map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + let sub_id = uuid::Uuid::new_v4().to_string(); + let interval = update_interval_hours + .or(parsed.update_interval_hours) + .unwrap_or(DEFAULT_INTERVAL_HOURS) + .clamp(1, 720); + + let sub = ProxySubscription { + id: sub_id.clone(), + url: valid_url.clone(), + name: custom_name + .clone() + .or_else(|| parsed.title.clone()) + .unwrap_or_else(|| derive_default_name(&valid_url)), + name_override: custom_name.is_some(), + auto_update: auto_update.unwrap_or(true), + update_interval_hours: interval, + upload_bytes: parsed.upload_bytes, + download_bytes: parsed.download_bytes, + total_bytes: parsed.total_bytes, + expire_at: parsed.expire_at, + web_page_url: parsed.web_page_url, + support_url: parsed.support_url, + announce: parsed.announce, + announce_url: parsed.announce_url, + node_count, + skipped_count: skipped, + last_updated: Some(now_stamp()), + last_error: None, + }; + + let (added, updated, removed, removed_ids) = { + let _guard = lock_store()?; + let mut store_data = load_store_unlocked()?; + if store_data + .subscriptions + .iter() + .any(|s| same_subscription_url(&s.url, &valid_url)) + { + anyhow::bail!("a subscription with this URL already exists"); + } + let sync_res = sync_proxies_unlocked(&sub_id, parsed.entries)?; + store_data.subscriptions.push(sub.clone()); + save_store_unlocked(&store_data)?; + sync_res + }; + cleanup_proxy_metadata(&removed_ids); + + Ok(SubscriptionSyncResult { + subscription: sub, + added, + updated, + removed, + skipped, + }) +} + +pub(in crate::space) async fn refresh(id: &str) -> Result { + let url = { + let _guard = lock_store()?; + let store_data = load_store_unlocked()?; + let sub = store_data + .subscriptions + .iter() + .find(|s| s.id == id) + .with_context(|| format!("no subscription with id {id}"))?; + sub.url.clone() + }; + + let parsed = match fetch_subscription(&url).await { + Ok(p) => p, + Err(err) => { + let msg = format!("{err:#}"); + if let Ok(_guard) = lock_store() { + if let Ok(mut store_data) = load_store_unlocked() { + if let Some(slot) = store_data.subscriptions.iter_mut().find(|s| s.id == id) { + slot.last_error = Some(msg); + let _ = save_store_unlocked(&store_data); + } + } + } + return Err(err); + } + }; + + let skipped = parsed.skipped_count; + let node_count = parsed.entries.len(); + + let (updated_sub, added, updated, removed, removed_ids) = { + let _guard = lock_store()?; + let mut store_data = load_store_unlocked()?; + let slot = store_data + .subscriptions + .iter_mut() + .find(|s| s.id == id) + .with_context(|| format!("no subscription with id {id}"))?; + + if !slot.name_override { + if let Some(title) = parsed.title.clone() { + slot.name = title; + } + } + if let Some(interval) = parsed.update_interval_hours { + slot.update_interval_hours = interval; + } + slot.upload_bytes = parsed.upload_bytes; + slot.download_bytes = parsed.download_bytes; + slot.total_bytes = parsed.total_bytes; + slot.expire_at = parsed.expire_at; + slot.web_page_url = parsed.web_page_url; + slot.support_url = parsed.support_url; + slot.announce = parsed.announce; + slot.announce_url = parsed.announce_url; + slot.node_count = node_count; + slot.skipped_count = skipped; + slot.last_updated = Some(now_stamp()); + slot.last_error = None; + let out_sub = slot.clone(); + + let (added, updated, removed, removed_ids) = + sync_proxies_unlocked(id, parsed.entries)?; + save_store_unlocked(&store_data)?; + (out_sub, added, updated, removed, removed_ids) + }; + cleanup_proxy_metadata(&removed_ids); + + Ok(SubscriptionSyncResult { + subscription: updated_sub, + added, + updated, + removed, + skipped, + }) +} + +pub(in crate::space) fn update( + id: &str, + patch: SubscriptionUpdatePatch, +) -> Result { + let _guard = lock_store()?; + let mut store_data = load_store_unlocked()?; + + let validated_url = match patch.url { + Some(ref u) => Some(validate_subscription_url(u)?), + None => None, + }; + if let Some(ref new_url) = validated_url { + if store_data + .subscriptions + .iter() + .any(|s| s.id != id && same_subscription_url(&s.url, new_url)) + { + anyhow::bail!("a subscription with this URL already exists"); + } + } + + let slot = store_data + .subscriptions + .iter_mut() + .find(|s| s.id == id) + .with_context(|| format!("no subscription with id {id}"))?; + + if let Some(new_url) = validated_url { + slot.url = new_url; + } + if let Some(name) = patch.name { + let trimmed = name.trim(); + if trimmed.is_empty() { + slot.name = derive_default_name(&slot.url); + slot.name_override = false; + } else { + slot.name = trimmed.to_string(); + slot.name_override = true; + } + } + if let Some(auto_update) = patch.auto_update { + slot.auto_update = auto_update; + } + if let Some(hours) = patch.update_interval_hours { + slot.update_interval_hours = hours.clamp(1, 720); + } + let out = slot.clone(); + save_store_unlocked(&store_data)?; + Ok(out) +} + +pub(in crate::space) fn delete(id: &str, remove_proxies: bool) -> Result { + let removed_ids = { + let _guard = lock_store()?; + let mut store_data = load_store_unlocked()?; + let before = store_data.subscriptions.len(); + store_data.subscriptions.retain(|s| s.id != id); + if store_data.subscriptions.len() == before { + anyhow::bail!("no subscription with id {id}"); + } + + let mut proxy_store = proxy::load()?; + let mut ids_to_purge = Vec::new(); + if remove_proxies { + proxy_store.proxies.retain(|p| { + let matches = p.subscription_id.as_deref() == Some(id); + if matches { + ids_to_purge.push(p.id.clone()); + } + !matches + }); + } else { + for p in &mut proxy_store.proxies { + if p.subscription_id.as_deref() == Some(id) { + p.subscription_id = None; + } + } + } + proxy::save(&proxy_store)?; + save_store_unlocked(&store_data)?; + ids_to_purge + }; + cleanup_proxy_metadata(&removed_ids); + Ok(removed_ids.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::store; + + fn sample_vless(uuid: &str, host: &str, port: u16, label: &str) -> String { + format!( + "vless://{uuid}@{host}:{port}?encryption=none&flow=xtls-rprx-vision&security=reality&fp=chrome&pbk=mA1-key&sid=a1b2&sni=example.com&type=tcp#{label}" + ) + } + + #[test] + fn decodes_base64_header_and_userinfo_and_content_disposition() { + assert_eq!( + decode_header_value("base64:8J+UpSBTaGFyZE5ldCBWUE4="), + "🔥 ShardNet VPN" + ); + assert_eq!(decode_header_value("ShardNet%20Global"), "ShardNet Global"); + + assert_eq!( + parse_userinfo("upload=123; download=4567; total=536870912000; expire=1802000000"), + (Some(123), Some(4567), Some(536870912000), Some(1802000000)) + ); + assert_eq!( + parse_userinfo("upload=0; download=0; total=0; expire=0"), + (Some(0), Some(0), None, None) + ); + assert_eq!( + parse_content_disposition_filename("attachment; filename*=UTF-8''My%20Sub%20Name.txt"), + Some("My Sub Name".to_string()) + ); + assert_eq!( + parse_content_disposition_filename("attachment; filename=\"demo-feed.txt\""), + Some("demo-feed".to_string()) + ); + } + + #[test] + fn validates_urls_and_sanitizes_metadata_links() { + assert!(validate_subscription_url("https://sub.example.com/feed/abc").is_ok()); + assert!(validate_subscription_url("http://127.0.0.1:8080/sub").is_ok()); + assert!(validate_subscription_url("file:///etc/passwd").is_err()); + assert!(validate_subscription_url("javascript:alert(1)").is_err()); + + assert_eq!(sanitize_http_url("javascript:alert(1)"), None); + assert_eq!( + sanitize_http_url("https://support.example.com/help"), + Some("https://support.example.com/help".to_string()) + ); + } + + #[test] + fn parses_base64_and_plaintext_bodies_and_extracts_flags_and_skipped_count() { + let body_plain = [ + sample_vless("11111111-1111-4111-8111-111111111111", "nl.example.net", 443, "🇳🇱%20Amsterdam%2001"), + sample_vless("22222222-2222-4222-8222-222222222222", "de.example.net", 443, "🇩🇪 Frankfurt 02"), + "hysteria2://secret@hy.example.net:443#DE%20Hysteria".to_string(), + "trojan://pass@tr.example.net:443#SE%20Trojan".to_string(), + "socks5://user:pass@se.example.net:1080#🇸🇪%20Stockholm".to_string(), + ] + .join("\n"); + let b64_body = STANDARD.encode(&body_plain); + + let headers = vec![ + ("profile-title".into(), "base64:U2hhcmROZXQgVGVzdA==".into()), + ("profile-update-interval".into(), "6".into()), + ("subscription-userinfo".into(), "upload=100; download=2000; total=10000; expire=1900000000".into()), + ("profile-web-page-url".into(), "https://example.com".into()), + ("support-url".into(), "https://example.com/support".into()), + ("announce".into(), "base64:TGluZSAxCkxpbmUgMg==".into()), + ("announce-url".into(), "https://example.com/news".into()), + ]; + + let parsed = parse_subscription_payload("https://sub.example.com/token", &headers, &b64_body); + assert_eq!(parsed.title.as_deref(), Some("ShardNet Test")); + assert_eq!(parsed.update_interval_hours, Some(6)); + assert_eq!(parsed.upload_bytes, Some(100)); + assert_eq!(parsed.download_bytes, Some(2000)); + assert_eq!(parsed.total_bytes, Some(10000)); + assert_eq!(parsed.expire_at, Some(1900000000)); + assert_eq!(parsed.announce.as_deref(), Some("Line 1\nLine 2")); + assert_eq!(parsed.entries.len(), 3); + assert_eq!(parsed.skipped_count, 2); + assert_eq!(parsed.entries[0].country, "NL"); + assert_eq!(parsed.entries[0].name, "🇳🇱 Amsterdam 01"); + assert_eq!(parsed.entries[1].country, "DE"); + assert_eq!(parsed.entries[2].country, "SE"); + assert_eq!(parsed.entries[2].kind, ProxyKind::Socks5); + } + + #[test] + fn sync_preserves_ids_notes_and_manual_proxies_and_handles_delete_modes() { + let _dir = store::test_root("subs_sync_test"); + let _guard = lock_store().unwrap(); + + let manual = ProxyEntry { + id: "manual-1".into(), + name: "Manual SOCKS".into(), + kind: ProxyKind::Socks5, + host: "127.0.0.1".into(), + port: 1080, + username: String::new(), + password: String::new(), + country: "US".into(), + notes: "keep me".into(), + vless: None, + subscription_id: None, + }; + proxy::save(&proxy::ProxyStore { + proxies: vec![manual.clone()], + }) + .unwrap(); + + let sub_id = "sub-1"; + let e1 = parse_single(&sample_vless("11111111-1111-4111-8111-111111111111", "a.example.net", 443, "🇳🇱 Node A")).unwrap(); + let e2 = parse_single(&sample_vless("22222222-2222-4222-8222-222222222222", "b.example.net", 443, "🇩🇪 Node B")).unwrap(); + let (added, updated, removed, _) = sync_proxies_unlocked(sub_id, vec![e1, e2]).unwrap(); + assert_eq!((added, updated, removed), (2, 0, 0)); + + let stored_after_first = proxy::load().unwrap().proxies; + assert_eq!(stored_after_first.len(), 3); + let id_a = stored_after_first.iter().find(|p| p.host == "a.example.net").unwrap().id.clone(); + + // Add note on Node A, then refresh with Node A renamed, Node B removed, Node C added. + let mut with_note = proxy::load().unwrap(); + with_note.proxies.iter_mut().find(|p| p.id == id_a).unwrap().notes = "custom note".into(); + proxy::save(&with_note).unwrap(); + + let e1_renamed = parse_single(&sample_vless("11111111-1111-4111-8111-111111111111", "a.example.net", 443, "🇳🇱 Node A v2")).unwrap(); + let e3 = parse_single(&sample_vless("33333333-3333-4333-8333-333333333333", "c.example.net", 443, "🇸🇪 Node C")).unwrap(); + let (added2, updated2, removed2, _) = sync_proxies_unlocked(sub_id, vec![e1_renamed, e3]).unwrap(); + assert_eq!((added2, updated2, removed2), (1, 1, 1)); + + let after_second = proxy::load().unwrap().proxies; + assert_eq!(after_second.len(), 3); + let kept_a = after_second.iter().find(|p| p.id == id_a).unwrap(); + assert_eq!(kept_a.name, "🇳🇱 Node A v2"); + assert_eq!(kept_a.notes, "custom note"); + assert!(after_second.iter().any(|p| p.id == "manual-1" && p.subscription_id.is_none())); + assert!(!after_second.iter().any(|p| p.host == "b.example.net")); + + // Save subscription record, test delete(remove_proxies = false) converts nodes to manual. + save_store_unlocked(&SubscriptionStore { + subscriptions: vec![ProxySubscription { + id: sub_id.into(), + url: "https://example.com/sub".into(), + name: "Example".into(), + name_override: false, + auto_update: true, + update_interval_hours: 12, + upload_bytes: None, + download_bytes: None, + total_bytes: None, + expire_at: None, + web_page_url: None, + support_url: None, + announce: None, + announce_url: None, + node_count: 2, + skipped_count: 0, + last_updated: None, + last_error: None, + }], + }) + .unwrap(); + drop(_guard); + + let detached = delete(sub_id, false).unwrap(); + assert_eq!(detached, 0); + let after_detach = proxy::load().unwrap().proxies; + assert_eq!(after_detach.len(), 3); + assert!(after_detach.iter().all(|p| p.subscription_id.is_none())); + + // Re-attach and test delete(remove_proxies = true) removes all nodes of the subscription. + { + let _g = lock_store().unwrap(); + let e_del = parse_single(&sample_vless("44444444-4444-4444-8444-444444444444", "d.example.net", 443, "🇳🇱 Node D")).unwrap(); + sync_proxies_unlocked("sub-2", vec![e_del]).unwrap(); + save_store_unlocked(&SubscriptionStore { + subscriptions: vec![ProxySubscription { + id: "sub-2".into(), + url: "https://example.com/sub2".into(), + name: "Example 2".into(), + name_override: false, + auto_update: false, + update_interval_hours: 24, + upload_bytes: None, + download_bytes: None, + total_bytes: None, + expire_at: None, + web_page_url: None, + support_url: None, + announce: None, + announce_url: None, + node_count: 1, + skipped_count: 0, + last_updated: None, + last_error: None, + }], + }) + .unwrap(); + } + let wiped = delete("sub-2", true).unwrap(); + assert_eq!(wiped, 1); + assert!(!proxy::load().unwrap().proxies.iter().any(|p| p.host == "d.example.net")); + } + + #[test] + #[ignore] + fn live_subscription_fetch_and_delete() { + let url = std::env::var("SHARDX_TEST_SUB_URL") + .expect("SHARDX_TEST_SUB_URL must be set to run live subscription test"); + let _dir = store::test_root("subs_live_smoke"); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + rt.block_on(async { + let res = add(url, None, Some(true), None).await.expect("live add succeeds"); + assert!( + res.subscription.node_count > 0, + "expected at least one supported proxy node, got 0" + ); + assert!(res.added > 0); + let listed = list().unwrap(); + assert_eq!(listed.len(), 1); + let sub_id = res.subscription.id.clone(); + let refreshed = refresh(&sub_id).await.expect("live refresh succeeds"); + assert_eq!(refreshed.removed, 0); + assert_eq!(refreshed.added, 0); + assert_eq!(refreshed.updated, res.subscription.node_count); + let deleted = delete(&sub_id, true).expect("live delete succeeds"); + assert_eq!(deleted, res.subscription.node_count); + assert!(list().unwrap().is_empty()); + }); + } +} diff --git a/src-tauri/src/space/mod.rs b/src-tauri/src/space/mod.rs index d3122ea6d..ba2e24f5c 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 @@ -801,6 +801,46 @@ pub mod proxy { } } +pub mod proxy_subscription { + use super::local::subscriptions as local; + use super::{personal_only, team_now}; + use anyhow::Result; + + pub use local::{ProxySubscription, SubscriptionSyncResult, SubscriptionUpdatePatch}; + + pub fn list() -> Result> { + if team_now().is_some() { + return Ok(Vec::new()); + } + local::list() + } + + pub async fn add( + url: String, + name: Option, + auto_update: Option, + update_interval_hours: Option, + ) -> Result { + personal_only()?; + local::add(url, name, auto_update, update_interval_hours).await + } + + pub async fn refresh(id: &str) -> Result { + personal_only()?; + local::refresh(id).await + } + + pub fn update(id: &str, patch: SubscriptionUpdatePatch) -> Result { + personal_only()?; + local::update(id, patch) + } + + pub fn delete(id: &str, remove_proxies: bool) -> Result { + personal_only()?; + local::delete(id, remove_proxies) + } +} + pub mod tags { use super::local::tags as local; use super::{cache, items, team_now, write, Door, Ticket, NOT_IN_TEAM}; diff --git a/src-tauri/src/space/remote.rs b/src-tauri/src/space/remote.rs index d525e342e..a17e9759c 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,8 @@ pub fn proxy(row: &ProxyRow, login: Option<&str>) -> ProxyEntry { password: String::new(), country: String::new(), notes: String::new(), + vless: None, + subscription_id: None, }); e.id = row.id.clone(); e.name = row.name.clone(); diff --git a/src-tauri/src/space/write.rs b/src-tauri/src/space/write.rs index 82712bdb6..7a1430272 100644 --- a/src-tauri/src/space/write.rs +++ b/src-tauri/src/space/write.rs @@ -448,7 +448,12 @@ pub async fn save_proxy_for_binding( } let own = bound_id.filter(|b| !b.is_empty()).and_then(|b| { held.into_iter().find(|p| { - p.id == b && p.kind == entry.kind && p.host == entry.host && p.port == entry.port && p.username == entry.username + p.id == b + && p.kind == entry.kind + && p.host == entry.host + && p.port == entry.port + && p.username == entry.username + && !matches!(entry.kind, super::proxy::ProxyKind::Vless) }) }); match own { diff --git a/src-tauri/src/store.rs b/src-tauri/src/store.rs index 1442f087b..006ea8446 100644 --- a/src-tauri/src/store.rs +++ b/src-tauri/src/store.rs @@ -150,6 +150,10 @@ pub fn proxies_path() -> Result { Ok(config_root()?.join("proxies.json")) } +pub fn subscriptions_path() -> Result { + Ok(config_root()?.join("proxy-subscriptions.json")) +} + pub fn settings_path() -> Result { Ok(config_root()?.join("settings.json")) } diff --git a/src-tauri/src/vless.rs b/src-tauri/src/vless.rs new file mode 100644 index 000000000..1c7ab2523 --- /dev/null +++ b/src-tauri/src/vless.rs @@ -0,0 +1,1502 @@ +//! 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 sha2::{Digest, Sha256}; +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::{AtomicBool, AtomicU32, AtomicU64, 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 (override/Settings -> local cache -> PATH). +pub fn resolve_existing_xray() -> Option { + resolve_existing_xray_with(None) +} + +fn configured_xray_path(override_path: Option<&str>) -> Option { + match override_path { + Some(raw) => { + let trimmed = raw.trim(); + (!trimmed.is_empty()).then(|| PathBuf::from(trimmed)) + } + None => settings::load() + .ok() + .and_then(|s| s.xray_path) + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .map(PathBuf::from), + } +} + +pub fn resolve_existing_xray_with(override_path: Option<&str>) -> Option { + if let Some(p) = configured_xray_path(override_path) { + if p.is_file() { + return Some(p); + } + return None; + } + 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 { + status_for(None) +} + +pub fn status_for(override_path: Option<&str>) -> VlessStatus { + if let Some(custom) = configured_xray_path(override_path) { + if !custom.is_file() { + return VlessStatus { + installed: false, + path: Some(custom.display().to_string()), + version: None, + }; + } + } + match resolve_existing_xray_with(override_path) { + 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" + )) +} + +struct DownloadSpec { + url: String, + dgst_url: Option, + api_sha256: Option, +} + +fn normalize_sha256_hex(raw: &str) -> Option { + let trimmed = raw.trim().strip_prefix("sha256:").unwrap_or(raw.trim()); + (trimmed.len() == 64 && trimmed.chars().all(|c| c.is_ascii_hexdigit())) + .then(|| trimmed.to_ascii_lowercase()) +} + +fn parse_sha256_dgst(text: &str) -> Option { + for line in text.lines() { + let l = line.trim(); + if l.is_empty() { + continue; + } + if let Some((_, rest)) = l.split_once('=') { + let lower = l.to_ascii_lowercase(); + if lower.contains("256") { + if let Some(hex) = rest.split_whitespace().next().and_then(normalize_sha256_hex) { + return Some(hex); + } + } + } else if let Some(token) = l.split_whitespace().next() { + if let Some(hex) = normalize_sha256_hex(token) { + return Some(hex); + } + } + } + None +} + +async fn resolve_download_spec(client: &reqwest::Client, asset_name: &str) -> DownloadSpec { + let dgst_name = format!("{asset_name}.dgst"); + 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 { + let mut found_url: Option = None; + let mut api_sha256: Option = None; + let mut dgst_url: Option = None; + 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(u) = url { + found_url = Some(u.to_string()); + api_sha256 = asset + .get("digest") + .and_then(|v| v.as_str()) + .and_then(normalize_sha256_hex); + } + } else if name == Some(dgst_name.as_str()) { + if let Some(u) = url { + dgst_url = Some(u.to_string()); + } + } + } + } + if let Some(url) = found_url { + return DownloadSpec { + dgst_url: dgst_url.or_else(|| Some(format!("{url}.dgst"))), + url, + api_sha256, + }; + } + if let Some(tag) = json.get("tag_name").and_then(|v| v.as_str()) { + let url = format!( + "https://github.com/XTLS/Xray-core/releases/download/{tag}/{asset_name}" + ); + return DownloadSpec { + dgst_url: Some(format!("{url}.dgst")), + url, + api_sha256: None, + }; + } + } + } + } + let url = format!( + "https://github.com/XTLS/Xray-core/releases/download/{XRAY_FALLBACK_TAG}/{asset_name}" + ); + DownloadSpec { + dgst_url: Some(format!("{url}.dgst")), + url, + api_sha256: None, + } +} + +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 backup = dest.with_extension("old"); + let _ = std::fs::remove_file(&backup); + let backed_up = std::fs::rename(dest, &backup).is_ok(); + if let Err(e) = std::fs::rename(&staging, dest) { + if backed_up { + let _ = std::fs::rename(&backup, dest); + } + return Err(e).with_context(|| format!("install Xray-core to {}", dest.display())); + } + if backed_up { + let _ = std::fs::remove_file(&backup); + } + } else { + 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(custom) = configured_xray_path(None) { + if !custom.is_file() { + bail!( + "Configured Xray-core binary was not found at {}", + custom.display() + ); + } + return Ok(custom); + } + 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(custom) = configured_xray_path(None) { + if !custom.is_file() { + bail!( + "Configured Xray-core binary was not found at {}", + custom.display() + ); + } + return Ok(custom); + } + 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 spec = resolve_download_spec(&client, asset_name).await; + let expected_sha256 = if let Some(sha) = spec.api_sha256 { + sha + } else if let Some(dgst_url) = &spec.dgst_url { + let dgst_text = client + .get(dgst_url) + .timeout(std::time::Duration::from_secs(10)) + .send() + .await + .with_context(|| format!("download Xray-core checksum from {dgst_url}"))? + .error_for_status() + .with_context(|| format!("Xray-core checksum request failed ({dgst_url})"))? + .text() + .await + .context("read Xray-core checksum body")?; + parse_sha256_dgst(&dgst_text) + .with_context(|| format!("missing SHA2-256 digest in {dgst_url}"))? + } else { + bail!("No SHA-256 checksum available to verify Xray-core download"); + }; + + eprintln!("[vless] downloading Xray-core from {}", spec.url); + let resp = client + .get(&spec.url) + .send() + .await + .with_context(|| format!("download Xray-core from {}", spec.url))? + .error_for_status() + .with_context(|| format!("Xray-core release download failed ({})", spec.url))?; + let bytes = resp.bytes().await.context("read Xray-core download stream")?; + + let actual_sha256 = format!("{:x}", Sha256::digest(&bytes)); + if actual_sha256 != expected_sha256 { + bail!( + "Xray-core archive SHA-256 mismatch (expected {expected_sha256}, got {actual_sha256})" + ); + } + + 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(); + + 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() + }; + + if matches!(network, "http" | "h2" | "h3" | "quic") { + bail!( + "VLESS transport `{network}` was removed in Xray-core 26; convert this proxy to `xhttp`, `ws`, `grpc`, or `tcp`" + ); + } + + if 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)"); + } + if !matches!(network, "tcp" | "raw" | "xhttp" | "splithttp" | "grpc") { + bail!( + "VLESS REALITY only supports `tcp`, `xhttp`, and `grpc` transports (got `{network}`)" + ); + } + } + + 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 mut stream = serde_json::Map::new(); + stream.insert("network".into(), json!(network)); + stream.insert("security".into(), json!(security)); + + match security { + "none" => {} + "tls" => { + if cfg.allow_insecure && cfg.pinned_peer_cert_sha256.is_empty() { + bail!("Xray-core 26 removed allowInsecure; set `pcs` (pinnedPeerCertSha256) to pin the server certificate or disable allowInsecure"); + } + 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)); + if !cfg.pinned_peer_cert_sha256.is_empty() { + tls.insert( + "pinnedPeerCertSha256".into(), + json!(cfg.pinned_peer_cert_sha256), + ); + } + if !cfg.verify_peer_cert_by_name.is_empty() { + tls.insert( + "verifyPeerCertByName".into(), + json!(cfg.verify_peer_cert_by_name), + ); + } + 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)); + } + 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 mut vless = entry.vless.clone().unwrap_or_default().normalized(); + if vless.security == "reality" && vless.spider_x.is_empty() { + vless.spider_x = "/".to_string(); + } + let key = CanonicalKey { + host: entry.host.trim(), + port: entry.port, + uuid: entry.username.trim(), + vless, + }; + serde_json::to_string(&key).unwrap_or_else(|_| format!("{}:{}:{}", key.host, key.port, key.uuid)) +} + +struct TunnelEntry { + addr: SocketAddr, + pid: Arc, + refs: Arc, + stop_tx: Option>, + dead: Arc, +} + +struct RegistryInner { + tunnels: Mutex>, + create_lock: tokio::sync::Mutex<()>, + shutdown_epoch: AtomicU64, +} + +impl RegistryInner { + fn new() -> Self { + Self { + tunnels: Mutex::new(HashMap::new()), + create_lock: tokio::sync::Mutex::new(()), + shutdown_epoch: AtomicU64::new(0), + } + } + + 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) { + self.shutdown_epoch.fetch_add(1, Ordering::SeqCst); + 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.load(Ordering::SeqCst)); + } + } +} + +async fn check_socks5_ready(addr: SocketAddr) -> bool { + let connect = tokio::time::timeout( + std::time::Duration::from_millis(400), + tokio::net::TcpStream::connect(addr), + ) + .await; + let Ok(Ok(mut stream)) = connect else { + return false; + }; + let handshake = tokio::time::timeout(std::time::Duration::from_millis(400), async { + stream.write_all(&[0x05, 0x01, 0x00]).await?; + let mut reply = [0u8; 2]; + stream.read_exact(&mut reply).await?; + Ok::(reply == [0x05, 0x00]) + }) + .await; + matches!(handshake, Ok(Ok(true))) +} + +/// 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 epoch_at_start = self.inner.shutdown_epoch.load(Ordering::SeqCst); + + let candidate = { + 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) { + Some(( + existing.addr, + Arc::clone(&existing.refs), + Arc::clone(&existing.dead), + )) + } else { + g.remove(&key); + None + } + } else { + None + } + }; + + if let Some((addr, refs, dead)) = candidate { + if check_socks5_ready(addr).await && !dead.load(Ordering::SeqCst) { + let g = self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + if self.inner.shutdown_epoch.load(Ordering::SeqCst) == epoch_at_start { + if let Some(cur) = g.get(&key) { + if Arc::ptr_eq(&cur.refs, &refs) && !cur.dead.load(Ordering::SeqCst) { + cur.refs.fetch_add(1, Ordering::SeqCst); + return Ok(VlessLease { + inner: Arc::clone(&self.inner), + key, + addr, + refs, + }); + } + } + } + } else { + let stale = { + let mut g = self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + if g.get(&key).is_some_and(|cur| Arc::ptr_eq(&cur.refs, &refs)) { + g.remove(&key) + } else { + None + } + }; + if let Some(mut entry) = stale { + if let Some(tx) = entry.stop_tx.take() { + let _ = tx.send(()); + } + RegistryInner::force_kill_pid(entry.pid.load(Ordering::SeqCst)); + } + } + } + + 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, Arc::clone(&self.inner), epoch_at_start).await { + Ok(tunnel) => { + let refs = Arc::clone(&tunnel.refs); + let mut g = self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + if self.inner.shutdown_epoch.load(Ordering::SeqCst) != epoch_at_start { + let mut aborted = tunnel; + if let Some(tx) = aborted.stop_tx.take() { + let _ = tx.send(()); + } + RegistryInner::force_kill_pid(aborted.pid.load(Ordering::SeqCst)); + bail!("Xray-core manager is shutting down"); + } + 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_xray_process( + xray_bin: &Path, + config_bytes: &[u8], + stderr_buf: &Arc>, +) -> Result<(tokio::process::Child, crate::process::Tie)> { + 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()))?; + + 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; + } + + drain_pipe(child.stdout.take(), stderr_buf); + drain_pipe(child.stderr.take(), stderr_buf); + Ok((child, tie)) +} + +async fn spawn_tunnel( + entry: &ProxyEntry, + xray_bin: &Path, + addr: SocketAddr, + port: u16, + registry: Arc, + epoch_at_start: u64, +) -> Result { + let config = build_xray_config(entry, port)?; + let config_bytes = serde_json::to_vec(&config)?; + let stderr_buf = Arc::new(Mutex::new(String::new())); + let (mut child, mut tie) = spawn_xray_process(xray_bin, &config_bytes, &stderr_buf).await?; + + let pid = Arc::new(AtomicU32::new(child.id().unwrap_or(0))); + let pid_sup = Arc::clone(&pid); + let refs = Arc::new(AtomicUsize::new(1)); + let refs_sup = Arc::clone(&refs); + let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel::<()>(); + let dead = Arc::new(AtomicBool::new(false)); + let dead_sup = Arc::clone(&dead); + let startup_done = Arc::new(AtomicBool::new(false)); + let startup_sup = Arc::clone(&startup_done); + let bin_sup = xray_bin.to_path_buf(); + let cfg_sup = config_bytes.clone(); + let stderr_sup = Arc::clone(&stderr_buf); + + tokio::spawn(async move { + let mut restarts = 0u32; + loop { + let _tie_guard = tie; + tokio::select! { + _ = child.wait() => { + if !startup_sup.load(Ordering::SeqCst) + || refs_sup.load(Ordering::SeqCst) == 0 + || registry.shutdown_epoch.load(Ordering::SeqCst) != epoch_at_start + || restarts >= 5 + { + break; + } + restarts += 1; + tokio::select! { + _ = tokio::time::sleep(std::time::Duration::from_millis(250)) => {} + _ = &mut stop_rx => break, + } + if refs_sup.load(Ordering::SeqCst) == 0 + || registry.shutdown_epoch.load(Ordering::SeqCst) != epoch_at_start + { + break; + } + match spawn_xray_process(&bin_sup, &cfg_sup, &stderr_sup).await { + Ok((next_child, next_tie)) => { + pid_sup.store(next_child.id().unwrap_or(0), Ordering::SeqCst); + child = next_child; + tie = next_tie; + eprintln!("[vless] respawned Xray-core on {addr} (attempt {restarts})"); + } + Err(e) => { + eprintln!("[vless] respawn failed on {addr}: {e:#}"); + break; + } + } + } + _ = &mut stop_rx => { + let _ = child.kill().await; + let _ = child.wait().await; + break; + } + } + } + pid_sup.store(0, Ordering::SeqCst); + dead_sup.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 check_socks5_ready(addr).await && !dead.load(Ordering::SeqCst) { + 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; + } + + startup_done.store(true, Ordering::SeqCst); + Ok(TunnelEntry { + addr, + pid, + refs, + 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, + subscription_id: 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; + { + let mut g = self.inner.tunnels.lock().unwrap_or_else(|e| e.into_inner()); + 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&pcs=abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789&vcn=alt.example.com#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"]["pinnedPeerCertSha256"], + "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789" + ); + assert_eq!( + ws_cfg["outbounds"][0]["streamSettings"]["tlsSettings"]["verifyPeerCertByName"], + "alt.example.com" + ); + assert_eq!( + ws_cfg["outbounds"][0]["streamSettings"]["tlsSettings"]["alpn"], + json!(["h2", "http/1.1"]) + ); + + let insecure_without_pin = parse_single( + "vless://11111111-2222-3333-4444-555555555555@ws.example.com:443?type=ws&security=tls&sni=ws.example.com&allowInsecure=1", + ) + .unwrap(); + assert!(build_xray_config(&insecure_without_pin, 10809).is_err()); + + let h2_removed = parse_single( + "vless://11111111-2222-3333-4444-555555555555@h2.example.com:443?type=h2&security=tls&sni=h2.example.com", + ) + .unwrap(); + assert!(build_xray_config(&h2_removed, 10809).is_err()); + + 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&pcs=abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789&vcn=ws.example.com", + "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..96d87f381 100644 --- a/src/dev/mock/fixtures.ts +++ b/src/dev/mock/fixtures.ts @@ -10,7 +10,7 @@ import type { MockSync } from "./syncServer"; import type { SpaceData } from "./spaces"; import type { ProfileSync } from "../../entities/sync/model/types"; import type { ProfileMeta } from "../../entities/profile/model/types"; -import type { ProxyEntry, ProxyTestSnapshot } from "../../entities/proxy/model/types"; +import type { ProxyEntry, ProxySubscription, ProxyTestSnapshot } from "../../entities/proxy/model/types"; import type { FingerprintEntry } from "../../entities/fingerprint/model/types"; import type { ExtensionEntry, ExtensionUpdate } from "../../entities/extension/model/types"; import type { Bookmark } from "../../entities/bookmark/model/types"; @@ -20,7 +20,7 @@ import type { ModuleInfo, Project } from "../../entities/automation/model/types" import type { PsOrder, PsProduct, PsActiveProxy } from "../../entities/proxyshard/model/types"; /** Bump when the seed changes shape so stale localStorage state is dropped. */ -export const SEED_VERSION = 7; +export const SEED_VERSION = 8; export const DEFAULT_BLOCKED_PORTS = [3389, 5900, 5901, 5800, 7070, 6568, 5938, 1080, 8080, 3128, 3030]; @@ -90,6 +90,7 @@ export type MockState = { /** Insertion order, which is what profile_list returns. */ order: string[]; proxies: ProxyEntry[]; + subscriptions?: ProxySubscription[]; snapshots: Record; /** #162: change-IP links by proxy id, outside the proxies as in the backend. */ rotation?: Record; @@ -345,8 +346,177 @@ const PROXIES: ProxyEntry[] = [ // below, so `proxyStatus` sees no history at all — the one seed proxy // whose Test result is genuinely "Not tested", not just "failed". { id: "px-new", name: "New DC Warsaw", kind: "socks5", host: "192.0.2.44", port: 1080, username: "shard", password: "mock-pass-7", country: "PL", notes: "Not tested yet" }, + { + id: "px-vless-1", + name: "VLESS REALITY Amsterdam", + kind: "vless", + host: "198.51.100.77", + port: 443, + username: "11111111-2222-3333-4444-555555555555", + password: "", + country: "NL", + notes: "Demo VLESS REALITY + Vision node", + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "www.cloudflare.com", + fingerprint: "chrome", + public_key: "mA1-2b3C4d5E6f7G8h9I0j1K2l3M4n5O6p7Q8r9S0tU", + short_id: "a1b2", + spider_x: "/", + }, + }, ]; +const DEMO_SUB_ID = "sub-shardnet"; + +const SUB_PROXIES: ProxyEntry[] = [ + { + id: "px-sub-nl-1", + name: "🇳🇱 Amsterdam 10G REALITY", + kind: "vless", + host: "nl1.shardnet.example", + port: 443, + username: "22222222-1111-4444-8888-111111111101", + password: "", + country: "NL", + notes: "", + subscription_id: DEMO_SUB_ID, + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "www.microsoft.com", + fingerprint: "chrome", + public_key: "demoPubKeyNL10G9x8y7z6w5v4u3t2s1r0q9p8o7n6m5", + short_id: "c4d2", + spider_x: "/", + }, + }, + { + id: "px-sub-de-1", + name: "🇩🇪 Frankfurt LTE Auto", + kind: "vless", + host: "de1.shardnet.example", + port: 443, + username: "22222222-1111-4444-8888-111111111102", + password: "", + country: "DE", + notes: "", + subscription_id: DEMO_SUB_ID, + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "www.apple.com", + fingerprint: "chrome", + public_key: "demoPubKeyDElte8x7y6z5w4v3u2t1s0r9q8p7o6n5m4", + short_id: "91ab", + spider_x: "/", + }, + }, + { + id: "px-sub-se-1", + name: "🇸🇪 Stockholm REALITY", + kind: "vless", + host: "se1.shardnet.example", + port: 443, + username: "22222222-1111-4444-8888-111111111103", + password: "", + country: "SE", + notes: "", + subscription_id: DEMO_SUB_ID, + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "aws.amazon.com", + fingerprint: "firefox", + public_key: "demoPubKeySE4437x6y5z4w3v2u1t0s9r8q7p6o5n4m3", + short_id: "7f01", + spider_x: "/", + }, + }, + { + id: "px-sub-sg-1", + name: "🇸🇬 Singapore XHTTP", + kind: "vless", + host: "sg1.shardnet.example", + port: 443, + username: "22222222-1111-4444-8888-111111111104", + password: "", + country: "SG", + notes: "", + subscription_id: DEMO_SUB_ID, + vless: { + encryption: "none", + flow: "", + network: "xhttp", + security: "reality", + sni: "www.cloudflare.com", + fingerprint: "chrome", + public_key: "demoPubKeySGxhttp6y5z4w3v2u1t0s9r8q7p6o5n4m2", + short_id: "3e19", + path: "/stream", + }, + }, + { + id: "px-sub-us-1", + name: "🇺🇸 Ashburn Vision", + kind: "vless", + host: "us1.shardnet.example", + port: 443, + username: "22222222-1111-4444-8888-111111111105", + password: "", + country: "US", + notes: "", + subscription_id: DEMO_SUB_ID, + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "www.bing.com", + fingerprint: "chrome", + public_key: "demoPubKeyUSvision5z4w3v2u1t0s9r8q7p6o5n4m1", + short_id: "8c04", + spider_x: "/", + }, + }, +]; + +function demoSubscriptions(): ProxySubscription[] { + const nowSecs = Math.floor(Date.now() / 1000); + return [ + { + id: DEMO_SUB_ID, + url: "https://sub.shardx.example/v1/demo-token", + name: "ShardNet Global", + name_override: false, + auto_update: true, + update_interval_hours: 3, + upload_bytes: 1_480_000_000, + download_bytes: 142_600_000_000, + total_bytes: 536_870_912_000, + expire_at: nowSecs + 42 * 86_400, + web_page_url: "https://shardx.com", + support_url: "https://shardx.com/support", + announce: + "European VLESS REALITY relays upgraded to 10 Gbps.\nAuto-routing is active for NL, DE, SE, SG and US nodes.", + announce_url: "https://shardx.com/status", + node_count: SUB_PROXIES.length, + skipped_count: 2, + last_updated: `@${nowSecs - 12 * 60}`, + last_error: null, + }, + ]; +} + function snapshot(p: ProxyEntry, minutesAgo: number, ok = true): ProxyTestSnapshot { const geo: Record = { US: ["United States", "New York", "New York", "Verizon Fios", "America/New_York", 40.7128, -74.006], @@ -354,6 +524,8 @@ function snapshot(p: ProxyEntry, minutesAgo: number, ok = true): ProxyTestSnapsh JP: ["Japan", "Tokyo", "Tokyo", "NTT Communications", "Asia/Tokyo", 35.6762, 139.6503], GB: ["United Kingdom", "England", "Manchester", "EE Limited", "Europe/London", 53.4808, -2.2426], NL: ["Netherlands", "North Holland", "Amsterdam", "WorldStream", "Europe/Amsterdam", 52.3676, 4.9041], + SE: ["Sweden", "Stockholm", "Stockholm", "Bahnhof AB", "Europe/Stockholm", 59.3293, 18.0686], + SG: ["Singapore", "Central Singapore", "Singapore", "M1 Fiber", "Asia/Singapore", 1.3521, 103.8198], }; const g = geo[p.country] ?? geo.US; const t = `@${Math.floor((Date.now() - minutesAgo * 60_000) / 1000)}`; @@ -371,8 +543,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 === "vless" || (p.kind === "socks5" && /proxyshard|shardx\./.test(p.host))) ? 52 + base * 2 : null, + udp_error: ok && !(p.kind === "vless" || (p.kind === "socks5" && /proxyshard|shardx\./.test(p.host))) ? "SOCKS5 UDP ASSOCIATE refused" : null, geo_error: ok ? null : "connect timed out after 8000 ms", provider: "ip-api.com", }; @@ -681,7 +853,8 @@ export function seed(): MockState { if (s.running) running[s.id] = { pid: pid++, started: Date.now() - (s.id === "a78a0eea" ? 2 * 3600_000 + 14 * 60_000 : 27 * 60_000) }; } const snapshots: Record = {}; - for (const p of empty ? [] : PROXIES) { + const allProxies = empty ? [] : [...PROXIES, ...SUB_PROXIES]; + for (const p of allProxies) { if (p.id === "px-dead") snapshots[p.id] = [snapshot(p, 14 * 24 * 60, true), snapshot(p, 35, false)]; else if (p.id === "px-new") continue; else snapshots[p.id] = [snapshot(p, 3 * 24 * 60), snapshot(p, 26 * 60), snapshot(p, 12)]; @@ -690,7 +863,8 @@ export function seed(): MockState { version: SEED_VERSION, profiles, order, - proxies: empty ? [] : [...PROXIES.map((p) => ({ ...p })), ...extraProxies()], + proxies: empty ? [] : [...PROXIES.map((p) => ({ ...p })), ...SUB_PROXIES.map((p) => ({ ...p })), ...extraProxies()], + subscriptions: empty ? [] : demoSubscriptions(), snapshots, fingerprints, extensions: empty ? [] : EXTENSIONS.map((e) => ({ ...e })), diff --git a/src/dev/mock/handlers.ts b/src/dev/mock/handlers.ts index 0f7973574..8d73ed38f 100644 --- a/src/dev/mock/handlers.ts +++ b/src/dev/mock/handlers.ts @@ -20,7 +20,9 @@ import { AUTOMATION_REFUSALS } from "../../shared/api/automationRefusals"; import { NOT_IN_TEAM, profileFromFingerprint, settle, spaceStateOf, teamInUse, teamUnreachable, told } from "./spaces"; 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 type { ProxyEntry, ProxySubscription, ProxyTestSnapshot, SubscriptionSyncResult, SubscriptionUpdatePatch } 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 === "vless" || (entry.kind === "socks5" && /proxyshard|shardx\./.test(entry.host)); const base = 30 + Math.round(Math.random() * 120); return { // The backend stamps "@", as it does everywhere. @@ -156,12 +158,41 @@ function testSnapshot(entry: ProxyEntry, previous?: ProxyTestSnapshot): ProxyTes }; } -/** `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("@") && !line.slice(0, line.indexOf("@")).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; + } + if (kind === "vless" && !line.includes("://")) continue; let k = kind; let rest = line; const scheme = /^(socks5|https?):\/\//i.exec(rest); @@ -189,7 +220,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 +1290,159 @@ 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: (args) => { + const custom = typeof args?.path === "string" ? args.path.trim() : ""; + if (custom) { + const ok = custom.endsWith("xray") || custom.endsWith("xray.exe") || custom.startsWith("/mock/"); + return ok + ? { installed: true, path: custom, version: "Xray 26.11.9 (mock)" } + : { installed: false, path: custom, version: null }; + } + return { installed: true, path: "/mock/xray", version: "Xray 26.11.9 (mock)" }; + }, + vless_ensure: () => ({ installed: true, path: "/mock/xray", version: "Xray 26.11.9 (mock)" }), + + proxy_subscription_list: (_a, { state }) => (teamInUse(state) ? [] : state.subscriptions ?? []), + proxy_subscription_add: async ({ url, name, autoUpdate, updateIntervalHours }, ctx): Promise => { + if (teamInUse(ctx.state)) throw NOT_IN_TEAM; + const rawUrl = String(url ?? "").trim(); + let host = "subscription.example"; + try { + const u = new URL(rawUrl); + if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("scheme"); + host = u.hostname; + } catch { + throw "subscription URL must start with http:// or https://"; + } + const list = (ctx.state.subscriptions ??= []); + if (list.some((s) => s.url === rawUrl)) throw "a subscription with this URL already exists"; + await sleep(350); + const id = `sub-${newId().slice(0, 6)}`; + const nowSecs = Math.floor(Date.now() / 1000); + const subNodes: ProxyEntry[] = [ + { + id: `px-${newId().slice(0, 6)}`, + name: `🇳🇱 ${host} Node 01`, + kind: "vless", + host, + port: 443, + username: "33333333-1111-4444-8888-111111111101", + password: "", + country: "NL", + notes: "", + subscription_id: id, + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "www.cloudflare.com", + fingerprint: "chrome", + public_key: "mockPubKeySubAdd01", + short_id: "a1b2", + }, + }, + { + id: `px-${newId().slice(0, 6)}`, + name: `🇩🇪 ${host} Node 02`, + kind: "vless", + host, + port: 8443, + username: "33333333-1111-4444-8888-111111111102", + password: "", + country: "DE", + notes: "", + subscription_id: id, + vless: { + encryption: "none", + flow: "xtls-rprx-vision", + network: "tcp", + security: "reality", + sni: "www.microsoft.com", + fingerprint: "chrome", + public_key: "mockPubKeySubAdd02", + short_id: "c3d4", + }, + }, + ]; + for (const node of subNodes) { + ctx.state.proxies.push(node); + ctx.state.snapshots[node.id] = [testSnapshot(node)]; + } + const trimmedName = typeof name === "string" ? name.trim() : ""; + const sub: ProxySubscription = { + id, + url: rawUrl, + name: trimmedName || host, + name_override: !!trimmedName, + auto_update: autoUpdate !== false, + update_interval_hours: Number(updateIntervalHours) || 12, + upload_bytes: 0, + download_bytes: 2_400_000_000, + total_bytes: 107_374_182_400, + expire_at: nowSecs + 30 * 86_400, + web_page_url: `https://${host}`, + support_url: null, + announce: null, + announce_url: null, + node_count: subNodes.length, + skipped_count: 0, + last_updated: nowStamp(), + last_error: null, + }; + list.push(sub); + ctx.save(); + return { subscription: sub, added: subNodes.length, updated: 0, removed: 0, skipped: 0 }; + }, + proxy_subscription_refresh: async ({ id }, ctx): Promise => { + if (teamInUse(ctx.state)) throw NOT_IN_TEAM; + const sub = (ctx.state.subscriptions ?? []).find((s) => s.id === id); + if (!sub) throw `no subscription with id ${id}`; + await sleep(300); + sub.last_updated = nowStamp(); + sub.last_error = null; + const count = ctx.state.proxies.filter((p) => p.subscription_id === id).length; + sub.node_count = count; + ctx.save(); + return { subscription: { ...sub }, added: 0, updated: count, removed: 0, skipped: sub.skipped_count }; + }, + proxy_subscription_update: ({ id, patch }, ctx): ProxySubscription => { + if (teamInUse(ctx.state)) throw NOT_IN_TEAM; + const sub = (ctx.state.subscriptions ?? []).find((s) => s.id === id); + if (!sub) throw `no subscription with id ${id}`; + const p = (patch ?? {}) as SubscriptionUpdatePatch; + if (typeof p.url === "string" && p.url.trim()) sub.url = p.url.trim(); + if (typeof p.name === "string") { + const trimmed = p.name.trim(); + if (trimmed) { sub.name = trimmed; sub.name_override = true; } + else { + sub.name_override = false; + try { sub.name = new URL(sub.url).hostname; } catch { /* keep */ } + } + } + if (typeof p.auto_update === "boolean") sub.auto_update = p.auto_update; + if (typeof p.update_interval_hours === "number") sub.update_interval_hours = p.update_interval_hours; + ctx.save(); + return { ...sub }; + }, + proxy_subscription_delete: ({ id, removeProxies }, ctx): number => { + if (teamInUse(ctx.state)) throw NOT_IN_TEAM; + const list = ctx.state.subscriptions ?? []; + if (!list.some((s) => s.id === id)) throw `no subscription with id ${id}`; + ctx.state.subscriptions = list.filter((s) => s.id !== id); + let removed = 0; + if (removeProxies) { + const before = ctx.state.proxies.length; + ctx.state.proxies = ctx.state.proxies.filter((p) => p.subscription_id !== id); + removed = before - ctx.state.proxies.length; + } else { + for (const p of ctx.state.proxies) { + if (p.subscription_id === id) p.subscription_id = undefined; + } + } + ctx.save(); + return removed; + }, // ---- Tauri plugins ------------------------------------------------------------ "plugin:app|version": () => "2.0.3", diff --git a/src/entities/automation/model/palette.ts b/src/entities/automation/model/palette.ts index e360cb9fb..09e49bb08 100644 --- a/src/entities/automation/model/palette.ts +++ b/src/entities/automation/model/palette.ts @@ -732,9 +732,16 @@ export const PALETTE: Category[] = [ name: "via", label: "palette.text.label", kind: "select", - options: ["profile", "host"], + options: ["profile", "host", "custom"], default: "profile", }, + { + name: "proxy", + label: "palette.httpRequest.proxy.label", + kind: "text", + hint: "palette.httpRequest.proxy.hint", + secret: true, + }, { name: "into", label: "palette.select.into.label", kind: "text", hint: "palette.select.into.hint" }, { name: "timeout", label: "palette.select.timeout.label", kind: "number", default: 30 }, ], diff --git a/src/entities/proxy/index.ts b/src/entities/proxy/index.ts index 5ce294907..9d67b62e3 100644 --- a/src/entities/proxy/index.ts +++ b/src/entities/proxy/index.ts @@ -7,3 +7,5 @@ export * from "./lib/status"; export * from "./lib/labels"; export * from "./lib/identity"; export * from "./lib/rotation"; +export * from "./lib/vless"; +export * from "./lib/subscriptionUrl"; 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/selectors.ts b/src/entities/proxy/lib/selectors.ts index dd700fc45..54af569eb 100644 --- a/src/entities/proxy/lib/selectors.ts +++ b/src/entities/proxy/lib/selectors.ts @@ -9,10 +9,11 @@ export function useFilteredProxies() { const search = useProxy((s) => s.search); const filters = useProxy((s) => s.filters); const sort = useProxy((s) => s.sort); + const activeSubscription = useProxy((s) => s.activeSubscription); const used = useProfileCountByProxy(); return useMemo( - () => sortProxies(filterProxies(proxies, snapshots, search, filters, used), sort, snapshots, used), - [proxies, snapshots, search, filters, sort, used], + () => sortProxies(filterProxies(proxies, snapshots, search, filters, used, activeSubscription), sort, snapshots, used), + [proxies, snapshots, search, filters, sort, activeSubscription, used], ); } diff --git a/src/entities/proxy/lib/subscriptionUrl.test.ts b/src/entities/proxy/lib/subscriptionUrl.test.ts new file mode 100644 index 000000000..92e9b6195 --- /dev/null +++ b/src/entities/proxy/lib/subscriptionUrl.test.ts @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { isSubscriptionUrlLine, splitBulkInput } from "./subscriptionUrl.ts"; + +test("recognizes subscription URLs including query params and explicit port with path", () => { + assert.equal(isSubscriptionUrlLine("https://provider.example/sub/token123"), true); + assert.equal(isSubscriptionUrlLine("https://provider.example/sub?token=abc&flag=1"), true); + assert.equal(isSubscriptionUrlLine("http://127.0.0.1:8080/sub/feed"), true); + assert.equal(isSubscriptionUrlLine("https://provider.example"), true); +}); + +test("rejects proxy endpoints, auth URLs, vless/socks5 URIs, comments, and base64", () => { + assert.equal(isSubscriptionUrlLine("http://user:pass@198.51.100.7:8080"), false); + assert.equal(isSubscriptionUrlLine("http://198.51.100.7:8080"), false); + assert.equal(isSubscriptionUrlLine("https://192.0.2.66:443/"), false); + assert.equal(isSubscriptionUrlLine("socks5://user:pass@host:1080"), false); + assert.equal(isSubscriptionUrlLine("vless://uuid@host:443?security=reality#node"), false); + assert.equal(isSubscriptionUrlLine("# https://provider.example/sub"), false); + assert.equal(isSubscriptionUrlLine("198.51.100.7:8080:user:pass"), false); +}); + +test("splitBulkInput separates single, multiple, mixed, and base64 inputs cleanly", () => { + const single = splitBulkInput(" https://provider.example/feed/1 "); + assert.deepEqual(single.subscriptionUrls, ["https://provider.example/feed/1"]); + assert.equal(single.proxyText, ""); + + const multi = splitBulkInput( + "https://a.example/sub\nhttps://a.example/sub\nhttps://b.example/sub?x=1", + ); + assert.deepEqual(multi.subscriptionUrls, [ + "https://a.example/sub", + "https://b.example/sub?x=1", + ]); + assert.equal(multi.proxyText, ""); + + const mixed = splitBulkInput( + "https://a.example/sub\nvless://11111111-1111-4111-8111-111111111111@host:443#nl\n198.51.100.7:8080", + ); + assert.deepEqual(mixed.subscriptionUrls, ["https://a.example/sub"]); + assert.equal( + mixed.proxyText, + "vless://11111111-1111-4111-8111-111111111111@host:443#nl\n198.51.100.7:8080", + ); + + const b64 = splitBulkInput("dmxlc3M6Ly91dWlkQGhvc3Q6NDQz"); + assert.deepEqual(b64.subscriptionUrls, []); + assert.equal(b64.proxyText, "dmxlc3M6Ly91dWlkQGhvc3Q6NDQz"); +}); diff --git a/src/entities/proxy/lib/subscriptionUrl.ts b/src/entities/proxy/lib/subscriptionUrl.ts new file mode 100644 index 000000000..bb35f52ae --- /dev/null +++ b/src/entities/proxy/lib/subscriptionUrl.ts @@ -0,0 +1,47 @@ +/** Returns true when a single trimmed line is a proxy subscription URL (rather than an HTTP/HTTPS proxy endpoint). */ +export function isSubscriptionUrlLine(line: string): boolean { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#") || /\s/.test(trimmed)) return false; + if (!/^https?:\/\/\S+$/i.test(trimmed)) return false; + let u: URL; + try { + u = new URL(trimmed); + } catch { + return false; + } + if (!u.hostname) return false; + // HTTP/HTTPS proxies with embedded credentials: http://user:pass@host:port + if (u.username || u.password) return false; + // Bare host:port without path/query (e.g. http://198.51.100.7:8080 or https://192.0.2.66:443) + // Note: WHATWG URL clears default ports (:80 / :443) in `u.port`, so inspect the raw authority. + const authority = trimmed.replace(/^https?:\/\//i, "").split(/[/?#]/)[0] ?? ""; + const hasExplicitPort = /:\d+$/.test(authority); + if ((u.pathname === "" || u.pathname === "/") && !u.search && hasExplicitPort) return false; + return true; +} + +/** Splits pasted text into deduplicated subscription URLs and remaining proxy lines. */ +export function splitBulkInput(text: string): { subscriptionUrls: string[]; proxyText: string } { + const trimmed = text.trim(); + if (!trimmed || !trimmed.includes("://")) { + return { subscriptionUrls: [], proxyText: text }; + } + const seen = new Set(); + const subscriptionUrls: string[] = []; + const proxyLines: string[] = []; + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim(); + if (isSubscriptionUrlLine(line)) { + if (!seen.has(line)) { + seen.add(line); + subscriptionUrls.push(line); + } + } else if (line.length > 0) { + proxyLines.push(raw); + } + } + return { + subscriptionUrls, + proxyText: proxyLines.join("\n"), + }; +} diff --git a/src/entities/proxy/lib/useProxy.tsx b/src/entities/proxy/lib/useProxy.tsx index 4886b7be3..27e5289ff 100644 --- a/src/entities/proxy/lib/useProxy.tsx +++ b/src/entities/proxy/lib/useProxy.tsx @@ -1,7 +1,25 @@ import { create } from 'zustand' -import { ProxyEntry, ProxyTestSnapshot } from '../model/types' -import { proxyFullTest, proxyLastTest, proxyList, proxyDelete, proxySave, proxyBulkImport } from '../model/api'; -import { onProxy, teamRefusal } from '../../space'; +import { + ProxyEntry, + ProxySubscription, + ProxyTestSnapshot, + SubscriptionSyncResult, + SubscriptionUpdatePatch, +} from '../model/types' +import { + proxyFullTest, + proxyLastTest, + proxyList, + proxyDelete, + proxySave, + proxyBulkImport, + proxySubscriptionList, + proxySubscriptionAdd, + proxySubscriptionRefresh, + proxySubscriptionUpdate, + proxySubscriptionDelete, +} from '../model/api'; +import { inTeam, onProxy, teamRefusal } from '../../space'; import { toast } from '../../../shared/model/toast'; import { clip, copySecret } from '../../../shared/lib/clipboard'; import { deferDelete } from '../../../shared/lib/deferDelete'; @@ -10,9 +28,12 @@ import { storeBus } from '../../../shared/lib/storeBus'; import { onSpaceMoved } from '../../../shared/api/invoke'; import { markArrived } from '../../../shared/lib/arrival'; import { eachReporting } from '../../../shared/lib/eachReporting'; +import { stampMs } from '../../../shared/lib/utils'; import { t } from '../../../shared/i18n'; import { ProfileMeta } from '../../profile/model/types'; import { proxyStatus } from './status'; +import { formatVlessUri } from './vless'; +import { splitBulkInput } from './subscriptionUrl'; // The delete toast's "Assign replacements…" opens Assign proxies for the // profiles that used the deleted proxies. That dialog belongs to the @@ -103,7 +124,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; }; @@ -136,10 +157,13 @@ export function filterProxies( filters: ProxyFilters = emptyProxyFilters(), /** Proxy id to how many profiles use it. */ used: Record = {}, + subscriptionId: string = 'all', ): ProxyEntry[] { const q = search.trim().toLowerCase(); - if (!q && countActiveProxyFilters(filters) === 0) return proxies; + if (!q && countActiveProxyFilters(filters) === 0 && subscriptionId === 'all') return proxies; return proxies.filter((p) => { + if (subscriptionId === 'manual' && p.subscription_id) return false; + if (subscriptionId !== 'all' && subscriptionId !== 'manual' && p.subscription_id !== subscriptionId) return false; const snap = snapshots[p.id]; if (filters.status !== 'any' && testStateOf(snap) !== filters.status) return false; if (filters.used === 'used' && !(used[p.id] > 0)) return false; @@ -149,11 +173,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) @@ -187,9 +215,9 @@ export function usedByProxy(profiles: readonly ProfileMeta[]): Record): ProxyEntry[] { +function listFor(s: Pick): ProxyEntry[] { const used = usedByProxy(s.profiles); - return sortProxies(filterProxies(s.proxies, s.snapshots, s.search, s.filters, used), s.sort, s.snapshots, used); + return sortProxies(filterProxies(s.proxies, s.snapshots, s.search, s.filters, used, s.activeSubscription), s.sort, s.snapshots, used); } /** The ids of the proxies the list shows, in its order. */ @@ -223,6 +251,10 @@ export type ProxyStore = { proxyTesting: Record, proxies: ProxyEntry[], + subscriptions: ProxySubscription[], + activeSubscription: string, + subRefreshing: Record, + editingSubscriptionId: string | null, snapshots: Record, proxySel: Set, /** The Profiles store's own list (the same array), kept in step by @@ -293,6 +325,14 @@ export type ProxyStore = { /** Copies the given proxies, or the selection the list shows, in the import format. */ bulkExport: (ids?: string[]) => void, bulkImportClipboard: () => Promise, + + setActiveSubscription: (id: string) => void, + openEditSubscription: (id: string) => void, + closeSubscriptionDialog: () => void, + addSubscription: (args: { url: string; name?: string | null; autoUpdate?: boolean; updateIntervalHours?: number | null }) => Promise, + refreshSubscription: (id: string, quiet?: boolean) => Promise, + updateSubscription: (id: string, patch: SubscriptionUpdatePatch) => Promise, + deleteSubscription: (id: string, removeProxies: boolean) => Promise, } /** About the rows of a tall window: their test results load first. */ const FIRST_SCREEN = 40; @@ -330,11 +370,34 @@ const lastTestRead = new Set(); /** The bus listener goes on with the first list, once. */ let listening = false; +const subAutoRefreshed = new Set(); + +function maybeAutoRefreshSubscriptions( + subs: ProxySubscription[], + refresh: (id: string, quiet?: boolean) => Promise, +) { + if (inTeam()) return; + const now = Date.now(); + for (const sub of subs) { + if (!sub.auto_update || subAutoRefreshed.has(sub.id)) continue; + const lastMs = stampMs(sub.last_updated); + const intervalMs = Math.max(1, sub.update_interval_hours || 12) * 3600_000; + if (!lastMs || now - lastMs >= intervalMs) { + subAutoRefreshed.add(sub.id); + void refresh(sub.id, true); + } + } +} + export const useProxy = create((set, get) => ({ status: 'idle', error: null, proxyTesting: {}, proxies: new Array(), + subscriptions: new Array(), + activeSubscription: 'all', + subRefreshing: {}, + editingSubscriptionId: null, snapshots: {}, proxySel: new Set(), profiles: new Array(), @@ -407,14 +470,21 @@ export const useProxy = create((set, get) => ({ set({ status: 'loading' }); try { // One call: the profiles come from the Profiles store (src/app/wireStores.ts, PERF-21). - const proxies = (await proxyList()).filter((p) => !pendingProxyIds.has(p.id)); - set({ proxies, status: 'ready' }); + const [rawProxies, subscriptions] = await Promise.all([ + proxyList(), + inTeam() ? Promise.resolve([] as ProxySubscription[]) : proxySubscriptionList().catch(() => [] as ProxySubscription[]), + ]); + const proxies = rawProxies.filter((p) => !pendingProxyIds.has(p.id)); + const curTab = get().activeSubscription; + const keepTab = curTab === 'all' || curTab === 'manual' || subscriptions.some((s) => s.id === curTab); + set({ proxies, subscriptions, ...(keepTab ? {} : { activeSubscription: 'all' }), status: 'ready' }); // A proxy saved here is already in this list: only another store's change reloads it. // Once: a new space starts the list over. if (!listening) { listening = true; storeBus.on('proxies', (from) => { if (from !== 'proxies') void get().reloadProxies(); }); } + maybeAutoRefreshSubscriptions(subscriptions, get().refreshSubscription); await loadSnapshots(set, get); } catch (e) { set({ status: 'error', error: String(e) }); @@ -428,11 +498,22 @@ export const useProxy = create((set, get) => ({ const had = get().status === 'ready' ? new Set(get().proxies.map((p) => p.id)) : null; try { // One waiting behind its Undo toast stays hidden. - const proxies = (await proxyList()).filter((p) => !pendingProxyIds.has(p.id)); + const [rawProxies, subscriptions] = await Promise.all([ + proxyList(), + inTeam() ? Promise.resolve([] as ProxySubscription[]) : proxySubscriptionList().catch(() => [] as ProxySubscription[]), + ]); + const proxies = rawProxies.filter((p) => !pendingProxyIds.has(p.id)); // A proxy deleted elsewhere leaves the selection too. const ids = new Set(proxies.map((p) => p.id)); const kept = [...get().proxySel].filter((id) => ids.has(id)); - set({ proxies, ...(kept.length !== get().proxySel.size ? { proxySel: new Set(kept) } : {}) }); + const curTab = get().activeSubscription; + const keepTab = curTab === 'all' || curTab === 'manual' || subscriptions.some((s) => s.id === curTab); + set({ + proxies, + subscriptions, + ...(keepTab ? {} : { activeSubscription: 'all' }), + ...(kept.length !== get().proxySel.size ? { proxySel: new Set(kept) } : {}), + }); if (had) markArrived(() => get().arrived, (arrived) => set({ arrived }), proxies.filter((p) => !had.has(p.id) && !comingBack.has(p.id)).map((p) => p.id)); } catch (e) { toast.fail({ title: t("useProxy.refreshFailed"), detail: e }); } }, @@ -574,6 +655,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 +665,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 }), @@ -601,19 +683,103 @@ export const useProxy = create((set, get) => ({ if (!text.trim()) { toast.err(t("useProxy.clipboardEmpty")); return; } const tooBig = clipboardTooBig(text); if (tooBig) { toast.err(tooBig); return; } - const n = await proxyBulkImport(text, "socks5"); - get().reload(); - storeBus.emit('proxies', 'proxies'); - toast.ok(n === 1 ? t("useProxy.importedOne", { n }) : t("useProxy.importedMany", { n })); + const { subscriptionUrls, proxyText } = inTeam() + ? { subscriptionUrls: [] as string[], proxyText: text } + : splitBulkInput(text); + for (const url of subscriptionUrls) { + await get().addSubscription({ url }); + } + if (proxyText.trim()) { + const n = await proxyBulkImport(proxyText, "socks5"); + get().reload(); + storeBus.emit('proxies', 'proxies'); + toast.ok(n === 1 ? t("useProxy.importedOne", { n }) : t("useProxy.importedMany", { n })); + } } catch (e) { toast.fail({ title: t("useProxy.importFailed"), detail: e }); } }, + + setActiveSubscription: (activeSubscription) => set({ activeSubscription }), + openEditSubscription: (id) => set({ editingSubscriptionId: id }), + closeSubscriptionDialog: () => set({ editingSubscriptionId: null }), + + addSubscription: async (args) => { + try { + const res = await proxySubscriptionAdd(args); + await get().reloadProxies(); + set({ activeSubscription: res.subscription.id }); + storeBus.emit('proxies', 'proxies'); + void loadSnapshots(set, get); + toast.ok(t("proxySub.addedToast", { name: res.subscription.name, n: res.subscription.node_count })); + return res; + } catch (e) { + toast.fail({ title: t("proxySub.addFailed"), detail: e }); + return null; + } + }, + + refreshSubscription: async (id, quiet) => { + const prev = get().subscriptions.find((s) => s.id === id); + set({ subRefreshing: { ...get().subRefreshing, [id]: true } }); + try { + const res = await proxySubscriptionRefresh(id); + await get().reloadProxies(); + storeBus.emit('proxies', 'proxies'); + void loadSnapshots(set, get); + if (!quiet) { + toast.ok(t("proxySub.updatedToast", { name: res.subscription.name, added: res.added, updated: res.updated, removed: res.removed })); + } + return true; + } catch (e) { + const subscriptions = await proxySubscriptionList().catch(() => get().subscriptions); + set({ subscriptions }); + if (!quiet) { + toast.fail({ title: t("proxySub.refreshFailed", { name: prev?.name ?? "" }), detail: e }); + } + return false; + } finally { + set({ subRefreshing: { ...get().subRefreshing, [id]: false } }); + } + }, + + updateSubscription: async (id, patch) => { + try { + const updated = await proxySubscriptionUpdate(id, patch); + set({ subscriptions: get().subscriptions.map((s) => (s.id === id ? updated : s)) }); + storeBus.emit('proxies', 'proxies'); + toast.ok(t("proxySub.savedToast", { name: updated.name })); + return updated; + } catch (e) { + toast.fail({ title: t("proxySub.saveFailed"), detail: e }); + return null; + } + }, + + deleteSubscription: async (id, removeProxies) => { + try { + await proxySubscriptionDelete(id, removeProxies); + const nextSubs = get().subscriptions.filter((s) => s.id !== id); + set({ + subscriptions: nextSubs, + activeSubscription: get().activeSubscription === id ? 'all' : get().activeSubscription, + }); + await get().reloadProxies(); + storeBus.emit('proxies', 'proxies'); + toast.ok(t("proxySub.deletedToast")); + return true; + } catch (e) { + toast.fail({ title: t("proxySub.deleteFailed"), detail: e }); + return false; + } + }, })) // Another space: its proxies are read afresh; nothing picked or open in the old one stays. onSpaceMoved(() => { const was = useProxy.getState().status; + subAutoRefreshed.clear(); useProxy.setState({ - status: 'idle', error: null, proxies: [], proxySel: new Set(), anchorId: null, activeId: null, + status: 'idle', error: null, proxies: [], subscriptions: [], activeSubscription: 'all', + subRefreshing: {}, editingSubscriptionId: null, proxySel: new Set(), anchorId: null, activeId: null, activeByPointer: false, peekId: null, arrived: {}, bulkOpen: false, proxyTesting: {}, }); if (was !== 'idle') void useProxy.getState().init(); diff --git a/src/entities/proxy/lib/vless.test.ts b/src/entities/proxy/lib/vless.test.ts new file mode 100644 index 000000000..f7c677efe --- /dev/null +++ b/src/entities/proxy/lib/vless.test.ts @@ -0,0 +1,99 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + emptyVlessConfig, + formatVlessUri, + isValidUuid, + 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", + ]); + assert.deepEqual(vlessSummaryTags({ security: "none", network: "tcp" }, { plain: "Обычный" }), [ + "Обычный", + "TCP", + ]); +}); + +test("handles case-insensitive params, h2/xtls, pcs/vcn, ed, and parity normalization", () => { + const parsed = parseVlessUri( + "vless://11111111-2222-3333-4444-555555555555@cdn.example.com:443?Security=XTLS&Type=H2&Sni=CDN.Example.COM&FP=Chrome&ALPN=h2,%20http/1.1&AllowInsecure=YES&ServiceName=grpcSvc&HeaderType=Http&PCS=AA11&VCN=alt.example&ED=2048&SID=AbCd#cdn.example.com:443", + ); + assert.ok(parsed); + assert.equal(parsed.vless?.security, "tls"); + assert.equal(parsed.vless?.network, "http"); + assert.equal(parsed.vless?.fingerprint, "chrome"); + assert.equal(parsed.vless?.alpn, "h2,http/1.1"); + assert.equal(parsed.vless?.allow_insecure, true); + assert.equal(parsed.vless?.service_name, "grpcSvc"); + assert.equal(parsed.vless?.header_type, "http"); + assert.equal(parsed.vless?.pinned_peer_cert_sha256, "AA11"); + assert.equal(parsed.vless?.verify_peer_cert_by_name, "alt.example"); + assert.equal(parsed.vless?.path, "/?ed=2048"); + assert.equal(parsed.vless?.short_id, "abcd"); + + const uri = formatVlessUri({ name: parsed.name, host: parsed.host, port: parsed.port, username: parsed.username, vless: parsed.vless }); + assert.match(uri, /pcs=AA11/); + assert.match(uri, /vcn=alt\.example/); + assert.ok(!uri.includes("#"), "default host:port name is omitted cleanly"); + + assert.equal(parseVlessUri("vless://uuid@example.com:0x1f"), null); + assert.equal(parseVlessUri("vless://uuid@example.com:1e3"), null); + assert.equal(isValidUuid("11111111-2222-3333-4444-555555555555"), true); + assert.equal(isValidUuid("not-a-uuid"), false); +}); diff --git a/src/entities/proxy/lib/vless.ts b/src/entities/proxy/lib/vless.ts new file mode 100644 index 000000000..50e38575c --- /dev/null +++ b/src/entities/proxy/lib/vless.ts @@ -0,0 +1,379 @@ +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" }, + { value: "http", label: "HTTP/2" }, +]; + +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, + pinned_peer_cert_sha256: "", + verify_peer_cert_by_name: "", + 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"; + if (s === "h2") return "http"; + return s; +} + +function normSecurity(raw?: string): string { + const s = (raw ?? "").trim().toLowerCase(); + if (!s) return "none"; + if (s === "xtls") return "tls"; + return s; +} + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function isValidUuid(raw?: string | null): boolean { + return UUID_RE.test((raw ?? "").trim()); +} + +const commaTrim = (raw?: string): string => + (raw ?? "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean) + .join(","); + +export function normalizeVlessConfig(raw?: Partial | null): VlessConfig { + const enc = (raw?.encryption ?? "").trim(); + const v: VlessConfig = { + encryption: !enc || enc.toLowerCase() === "none" ? "none" : enc, + flow: (raw?.flow ?? "").trim(), + network: normNetwork(raw?.network), + security: normSecurity(raw?.security), + sni: (raw?.sni ?? "").trim(), + fingerprint: (raw?.fingerprint ?? "").trim().toLowerCase(), + public_key: (raw?.public_key ?? "").trim(), + short_id: (raw?.short_id ?? "").trim().toLowerCase(), + spider_x: (raw?.spider_x ?? "").trim(), + pqv: (raw?.pqv ?? "").trim(), + alpn: commaTrim(raw?.alpn), + allow_insecure: Boolean(raw?.allow_insecure), + pinned_peer_cert_sha256: commaTrim(raw?.pinned_peer_cert_sha256), + verify_peer_cert_by_name: commaTrim(raw?.verify_peer_cert_by_name), + host: (raw?.host ?? "").trim(), + path: (raw?.path ?? "").trim(), + service_name: (raw?.service_name ?? "").trim(), + authority: (raw?.authority ?? "").trim(), + mode: (raw?.mode ?? "").trim().toLowerCase(), + header_type: (raw?.header_type ?? "").trim().toLowerCase(), + 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", + "pinned_peer_cert_sha256", + "verify_peer_cert_by_name", + "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.lastIndexOf("@"); + 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 trimmedPort = portStr.trim(); + if (!/^\d{1,5}$/.test(trimmedPort)) return null; + const port = Number(trimmedPort); + if (!host || /\s/.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) return null; + + const cfg = emptyVlessConfig(); + let edVal = ""; + 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.toLowerCase()) { + 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 "pcs": + case "pinnedpeercertsha256": + cfg.pinned_peer_cert_sha256 = v; + break; + case "vcn": + case "verifypeercertbyname": + cfg.verify_peer_cert_by_name = v; + break; + case "ed": + edVal = v; + 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; + } + } + } + if (edVal && /^\d+$/.test(edVal)) { + const base = (cfg.path ?? "").trim() || "/"; + if (!base.includes("ed=")) { + cfg.path = `${base}${base.includes("?") ? "&" : "?"}ed=${edVal}`; + } + } + + 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("pcs", cfg.pinned_peer_cert_sha256); + push("vcn", cfg.verify_peer_cert_by_name); + 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}`; + const trimmedName = proxy.name.trim(); + return trimmedName && trimmedName !== `${proxy.host}:${proxy.port}` ? `${base}#${encodeURIComponent(trimmedName)}` : base; +} + +export function vlessSummaryTags( + vless?: Partial | null, + labels?: { plain?: string; vision?: string }, +): 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(labels?.plain ?? "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") ? (labels?.vision ?? "Vision") : cfg.flow); + return tags; +} diff --git a/src/entities/proxy/model/api.ts b/src/entities/proxy/model/api.ts index 0ad691ff0..f3bfa7c37 100644 --- a/src/entities/proxy/model/api.ts +++ b/src/entities/proxy/model/api.ts @@ -1,5 +1,11 @@ import { invoke } from "../../../shared/api/invoke"; -import type { ProxyEntry, ProxyTestSnapshot } from "./types"; +import type { + ProxyEntry, + ProxySubscription, + ProxyTestSnapshot, + SubscriptionSyncResult, + SubscriptionUpdatePatch, +} from "./types"; export const proxyList = () => invoke("proxy_list"); export const proxySave = (entry: ProxyEntry) => invoke("proxy_save", { entry }); @@ -34,3 +40,33 @@ 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 = (path?: string | null) => + invoke("vless_status", { path: path?.trim() ? path.trim() : null }); +export const vlessEnsure = () => invoke("vless_ensure"); + +export const proxySubscriptionList = () => + invoke("proxy_subscription_list"); +export const proxySubscriptionAdd = (args: { + url: string; + name?: string | null; + autoUpdate?: boolean; + updateIntervalHours?: number | null; +}) => + invoke("proxy_subscription_add", { + url: args.url, + name: args.name ?? null, + autoUpdate: args.autoUpdate ?? null, + updateIntervalHours: args.updateIntervalHours ?? null, + }); +export const proxySubscriptionRefresh = (id: string) => + invoke("proxy_subscription_refresh", { id }); +export const proxySubscriptionUpdate = (id: string, patch: SubscriptionUpdatePatch) => + invoke("proxy_subscription_update", { id, patch }); +export const proxySubscriptionDelete = (id: string, removeProxies: boolean) => + invoke("proxy_subscription_delete", { id, removeProxies }); diff --git a/src/entities/proxy/model/types.ts b/src/entities/proxy/model/types.ts index f974aadf7..aef76029b 100644 --- a/src/entities/proxy/model/types.ts +++ b/src/entities/proxy/model/types.ts @@ -1,13 +1,78 @@ +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; + pinned_peer_cert_sha256?: string; + verify_peer_cert_by_name?: string; + 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; + subscription_id?: string | null; +}; + +export type ProxySubscription = { + id: string; + url: string; + name: string; + name_override: boolean; + auto_update: boolean; + update_interval_hours: number; + upload_bytes?: number | null; + download_bytes?: number | null; + total_bytes?: number | null; + expire_at?: number | null; + web_page_url?: string | null; + support_url?: string | null; + announce?: string | null; + announce_url?: string | null; + node_count: number; + skipped_count: number; + last_updated?: string | null; + last_error?: string | null; +}; + +export type SubscriptionSyncResult = { + subscription: ProxySubscription; + added: number; + updated: number; + removed: number; + skipped: number; +}; + +export type SubscriptionUpdatePatch = { + name?: string; + url?: string; + auto_update?: boolean; + update_interval_hours?: number; }; 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/automation-review/lib/review.ts b/src/features/automation-review/lib/review.ts index a9c8fba0f..4777ad175 100644 --- a/src/features/automation-review/lib/review.ts +++ b/src/features/automation-review/lib/review.ts @@ -120,6 +120,7 @@ export function reviewLines(blocks: Block[], rules: TrafficRule[] = [], modules: const what = via === "profile" ? t("automationReview.http", { method, url }) : via === "host" || via.trim() === "" ? t("automationReview.httpViaHost", { method, url }) : + via === "custom" ? t("automationReview.httpViaProxy", { method, url, via: text(p.proxy) }) : t("automationReview.httpViaProxy", { method, url, via: text(via) }); out.push({ step, what }); } else if (b.kind === "db.open") { diff --git a/src/features/manage-proxies/index.ts b/src/features/manage-proxies/index.ts index 031e722e0..be22f4c14 100644 --- a/src/features/manage-proxies/index.ts +++ b/src/features/manage-proxies/index.ts @@ -1,6 +1,7 @@ export { ProxyBulkImporter } from "./ui/ProxyBulkImporter"; export { NewProxyButton } from "./ui/NewProxyButton"; export { EditProxyDialog } from "./ui/EditProxyDialog"; +export { SubscriptionDialog } from "./ui/SubscriptionDialog"; export { ProxiesMoreMenu } from "./ui/ProxiesMoreMenu"; export { buyProxies } from "./lib/buyProxies"; export { ProxyFilterBar } from "./ui/ProxyFilterBar"; diff --git a/src/features/manage-proxies/lib/filterFields.tsx b/src/features/manage-proxies/lib/filterFields.tsx index d327381ac..2f071b59f 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) { @@ -28,6 +28,7 @@ export function useProxyFilterFields(enabled: boolean): FilterField[] { const search = useProxy((s) => s.search); const filters = useProxy((s) => s.filters); const setFilters = useProxy((s) => s.setFilters); + const activeSubscription = useProxy((s) => s.activeSubscription); const used = useProfileCountByProxy(); return useMemo(() => { if (!enabled) return []; @@ -36,7 +37,7 @@ export function useProxyFilterFields(enabled: boolean): FilterField[] { const ccOf = (id: string) => (snapshots[id]?.country_code || byId.get(id)?.country || "").toUpperCase(); const count = (key: K, off: ProxyFilters[K], valueOf: (id: string) => string) => { const m = new Map(); - for (const p of filterProxies(proxies, snapshots, search, { ...filters, [key]: off }, used)) { + for (const p of filterProxies(proxies, snapshots, search, { ...filters, [key]: off }, used, activeSubscription)) { const v = valueOf(p.id); if (v) m.set(v, (m.get(v) ?? 0) + 1); } diff --git a/src/features/manage-proxies/ui/EditProxyDialog.tsx b/src/features/manage-proxies/ui/EditProxyDialog.tsx index a93a21f1d..673873474 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,23 @@ 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, + isValidUuid, + 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 +53,9 @@ 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 [shownUuid, setShownUuid] = 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 +74,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 @@ -68,9 +94,26 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo onClose(); }, [open, gone, dirty, opened, onClose, t]); + const vless = normalizeVlessConfig(draft?.vless); const hostOk = !!draft?.host.trim(); + const uuidEmpty = draft?.kind === "vless" && !draft.username.trim(); + const uuidFormatOk = draft?.kind !== "vless" || isValidUuid(draft.username); + const uuidOk = !uuidEmpty && uuidFormatOk; + const realityOk = draft?.kind !== "vless" || vless.security !== "reality" || (!!vless.public_key?.trim() && !!vless.sni?.trim()); + const httpRemoved = draft?.kind === "vless" && vless.network === "http"; + const insecurePinOk = draft?.kind !== "vless" || vless.security !== "tls" || !vless.allow_insecure || !!vless.pinned_peer_cert_sha256?.trim(); + const extraOk = (() => { + if (draft?.kind !== "vless" || vless.network !== "xhttp" || !vless.extra?.trim()) return true; + try { + const val = JSON.parse(vless.extra); + return val !== null && typeof val === "object" && !Array.isArray(val); + } catch { + return false; + } + })(); + const vlessPasteOk = !vlessPasteBad && (!vlessPaste.trim() || !!parseVlessUri(vlessPaste.trim())); const saving = status === "saving"; - const canSave = !!draft && hostOk && !portBad && linkOk && dirty && !saving; + const canSave = !!draft && hostOk && uuidOk && realityOk && !httpRemoved && insecurePinOk && extraOk && vlessPasteOk && !portBad && linkOk && dirty && !saving; const name = opened ? opened.name || `${opened.host}:${opened.port}` : ""; const patch = (changes: Partial) => { @@ -78,21 +121,71 @@ 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) => { + const trimmed = raw.trim(); + if (!trimmed) { + setVlessPasteBad(false); + return; + } + const parsed = parseVlessUri(trimmed); + if (parsed && draft) { + const prevDefaultName = `${draft.host}:${draft.port}`; + const keepName = !!draft.name.trim() && draft.name.trim() !== prevDefaultName; + const incoming = parsed.vless ?? emptyVlessConfig(); + const nonEmptyIncoming = Object.fromEntries( + Object.entries(incoming).filter(([, val]) => val !== "" && val !== false && val !== undefined), + ) as Partial; + patch({ + host: parsed.host, + port: parsed.port, + username: parsed.username, + password: "", + name: keepName ? draft.name : parsed.name || draft.name, + vless: normalizeVlessConfig({ ...(draft.vless ?? emptyVlessConfig()), ...nonEmptyIncoming }), + }); + setVlessPaste(""); + setVlessPasteBad(false); + toast.ok(t("editProxy.vlessPasted")); + } else { + setVlessPasteBad(true); + } + }; + /** 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 || !realityOk || httpRemoved || !insecurePinOk || !extraOk || !vlessPasteOk || 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") { + if (vlessChanged || base.kind !== "vless") { + merged.vless = { ...(base.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(); @@ -130,6 +223,13 @@ function EditProxyBody({ id, open, onClose }: { id: string; open: boolean; onClo {t("editProxy.saveFailed")} ) : saving ? null : !hostOk ? t("editProxy.hostRequired") + : uuidEmpty ? t("editProxy.uuidRequired") + : !uuidFormatOk ? t("editProxy.uuidInvalid") + : !realityOk ? t("editProxy.vlessRealityRequired") + : httpRemoved ? t("editProxy.vlessHttpRemoved") + : !insecurePinOk ? t("editProxy.vlessPinRequiredForInsecure") + : !extraOk ? t("editProxy.vlessExtraInvalid") + : !vlessPasteOk ? t("editProxy.vlessPasteBad") : portBad ? t("numField.invalidRange", { min: 1, max: 65535 }) : !dirty ? t("editProxy.noChanges") : null; @@ -162,15 +262,43 @@ 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" && ( + { setVlessPaste(e.target.value); setVlessPasteBad(false); }} + onPaste={(e) => { + const pasted = e.clipboardData.getData("text"); + if (pasted.trim()) { + e.preventDefault(); + setVlessPaste(pasted); + applyVlessUri(pasted); + } + }} + onKeyDown={(e) => { + if (e.key === "Enter" && vlessPaste.trim()) { + e.preventDefault(); + applyVlessUri(vlessPaste); + } + }} + onBlur={() => { if (vlessPaste.trim()) applyVlessUri(vlessPaste); }} + /> + )}
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={() => setShownUuid((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 })} /> +
+ patchVless({ allow_insecure })} + /> +
+
+
+ patchVless({ pinned_peer_cert_sha256 })} + /> + patchVless({ verify_peer_cert_by_name })} + /> +
+ + )} + {httpRemoved && ( +

{t("editProxy.vlessHttpRemoved")}

+ )} + {vless.network === "tcp" && ( +
+ patchVless({ flow })} + options={optList(VLESS_FLOWS, () => t("proxyPeek.none"))} + /> + patchVless({ header_type })} /> +
+ )} + {(vless.network === "ws" || vless.network === "httpupgrade" || vless.network === "xhttp" || vless.network === "http" || (vless.network === "tcp" && vless.header_type === "http")) && ( +
+ 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. */} ("socks5"); const [rows, setRows] = useState([]); const [busy, setBusy] = useState(false); + const [subName, setSubName] = useState(""); + const [subAutoUpdate, setSubAutoUpdate] = useState(true); + const [pendingSubUrls, setPendingSubUrls] = useState([]); // A second press while the first is saving would save it again. const adding = useRef(false); // Closed while Add saved (Esc, the backdrop, Cancel): the proxies are @@ -24,15 +29,53 @@ export function ProxyBulkImporter({ open, onClose }: { open: boolean; onClose: ( const openRef = useRef(open); openRef.current = open; + const detected = useMemo( + () => (inTeam() ? { subscriptionUrls: [], proxyText: text } : splitBulkInput(text)), + [text], + ); + const hasSub = rows.length === 0 && detected.subscriptionUrls.length > 0; + const subOnly = hasSub && !detected.proxyText.trim(); + const mixedInput = hasSub && detected.proxyText.trim().length > 0; + const parse = async () => { if (!text.trim()) { toast.err(t("proxyBulkImporter.nothingToParse")); return; } + const source = mixedInput ? detected.proxyText : text; try { - const parsed = await proxyBulkParse(text, kind); + const parsed = await proxyBulkParse(source, kind); if (parsed.length === 0) { toast.err(t("proxyBulkImporter.noValidLines")); return; } + setPendingSubUrls(mixedInput ? detected.subscriptionUrls : []); setRows(parsed.map((e) => ({ entry: e, selected: true, status: "idle" }))); } catch (e) { toast.fail({ title: t("proxyBulkImporter.previewFailed"), detail: e }); } }; + const addDetectedSubscriptions = async () => { + if (adding.current || detected.subscriptionUrls.length === 0) return; + adding.current = true; + setBusy(true); + try { + const { addSubscription } = useProxy.getState(); + const single = detected.subscriptionUrls.length === 1; + let anyAdded = false; + for (const url of detected.subscriptionUrls) { + const res = await addSubscription({ + url, + name: single ? subName.trim() || null : null, + autoUpdate: single ? subAutoUpdate : true, + }); + if (res) anyAdded = true; + } + if (anyAdded && openRef.current) { + setText(""); + setSubName(""); + setPendingSubUrls([]); + onClose(); + } + } finally { + adding.current = false; + setBusy(false); + } + }; + // Test results wait in a buffer and reach the rows once per frame: "Test // all" over 1,000 lines renders about once a frame, not once per result // over every row (PERF-19). @@ -102,6 +145,10 @@ export function ProxyBulkImporter({ open, onClose }: { open: boolean; onClose: ( setBusy(true); try { const n = await proxyBulkSave(entries); + for (const url of pendingSubUrls) { + await useProxy.getState().addSubscription({ url }); + } + setPendingSubUrls([]); await useProxy.getState().reload(); // The entry keeps the id it was parsed with; one the save skipped (an // identical proxy was already there) opens that proxy instead. Never @@ -140,11 +187,19 @@ export function ProxyBulkImporter({ open, onClose }: { open: boolean; onClose: ( {/* Cancel cannot stop a save that has started (Esc and the backdrop close without a Peek). */} {rows.length === 0 ? ( - + subOnly ? ( + + ) : ( + + ) ) : ( - )} @@ -154,31 +209,83 @@ export function ProxyBulkImporter({ open, onClose }: { open: boolean; onClose: (
{rows.length === 0 ? ( <> - setKind(v as ProxyEntry["kind"])} + options={[ + { value: "socks5", label: "SOCKS5" }, + { value: "http", label: "HTTP" }, + { value: "https", label: "HTTPS" }, + { value: "vless", label: "VLESS" }, + ]} + /> + )}