diff --git a/Cargo.lock b/Cargo.lock index 2012fa485..62be2ee95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1106,16 +1106,19 @@ dependencies = [ "async-trait", "backon", "base64 0.23.1", - "boa_engine", "bytes", "chrono", "clash-verge-backup-archive", + "clash-verge-config-render", "clash-verge-draft", "clash-verge-i18n", "clash-verge-limiter", "clash-verge-logging", "clash-verge-media-unlock", "clash-verge-profile", + "clash-verge-profile-script", + "clash-verge-proxy-view", + "clash-verge-runtime-bundle", "clash-verge-signal", "clash-verge-subscription", "clash-verge-task", @@ -1195,6 +1198,19 @@ dependencies = [ "zip", ] +[[package]] +name = "clash-verge-config-render" +version = "0.1.0" +dependencies = [ + "clash-verge-logging", + "log", + "serde", + "serde_json", + "serde_yaml_ng", + "tokio", + "tristr", +] + [[package]] name = "clash-verge-draft" version = "0.1.0" @@ -1259,6 +1275,42 @@ dependencies = [ "tristr", ] +[[package]] +name = "clash-verge-profile-script" +version = "0.1.0" +dependencies = [ + "boa_engine", + "clash-verge-logging", + "log", + "serde_json", + "serde_yaml_ng", + "tokio", + "tristr", +] + +[[package]] +name = "clash-verge-proxy-view" +version = "0.1.0" +dependencies = [ + "serde", + "specta", + "tristr", +] + +[[package]] +name = "clash-verge-runtime-bundle" +version = "0.1.0" +dependencies = [ + "clash-verge-logging", + "hex", + "log", + "serde_yaml_ng", + "sha2 0.11.2", + "thiserror 2.0.20", + "tokio", + "tristr", +] + [[package]] name = "clash-verge-signal" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 2b211583e..db9c4ed0b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,10 @@ members = [ "crates/clash-verge-i18n", "crates/clash-verge-limiter", "crates/clash-verge-subscription", + "crates/clash-verge-runtime-bundle", + "crates/clash-verge-config-render", + "crates/clash-verge-profile-script", + "crates/clash-verge-proxy-view", "crates/clash-verge-profile", "crates/clash-verge-backup-archive", ] @@ -56,6 +60,8 @@ muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdf tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "2745082c7f487c5e0c9568000b5a7ac24234d6e4" } [workspace.dependencies] +clash-verge-config-render = { path = "crates/clash-verge-config-render" } +clash-verge-profile-script = { path = "crates/clash-verge-profile-script" } clash-verge-draft = { path = "crates/clash-verge-draft" } clash-verge-task = { path = "crates/clash-verge-task" } clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" } @@ -64,8 +70,11 @@ clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-limiter = { path = "crates/clash-verge-limiter" } clash-verge-subscription = { path = "crates/clash-verge-subscription" } +clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" } +clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" } clash-verge-profile = { path = "crates/clash-verge-profile" } clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" } +clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" @@ -76,6 +85,7 @@ parking_lot = "0.13.0" anyhow = "1.0.105" thiserror = "2.0.20" zip = "9.9.0" +boa_engine = "0.22.0" futures = "0.3.34" loom = "0.7.3" proptest = "1.12.0" @@ -102,6 +112,7 @@ serde = { version = "1.0.229" } tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] } serde_json = { version = "1.0.154" } serde_yaml_ng = { version = "0.10.0" } +sha2 = "0.11.2" specta = "=2.0.0-rc.26" socket2 = "0.6.5" diff --git a/crates/clash-verge-config-render/Cargo.toml b/crates/clash-verge-config-render/Cargo.toml new file mode 100644 index 000000000..93a947d51 --- /dev/null +++ b/crates/clash-verge-config-render/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "clash-verge-config-render" +version = "0.1.0" +edition = "2024" + +[dependencies] +clash-verge-logging = { workspace = true } +log = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +serde_yaml_ng = { workspace = true } +tristr = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true } + +[lints] +workspace = true diff --git a/src-tauri/src/enhance/field.rs b/crates/clash-verge-config-render/src/field.rs similarity index 73% rename from src-tauri/src/enhance/field.rs rename to crates/clash-verge-config-render/src/field.rs index e37c49700..1b1690ae3 100644 --- a/src-tauri/src/enhance/field.rs +++ b/crates/clash-verge-config-render/src/field.rs @@ -18,19 +18,21 @@ pub const HANDLE_FIELDS: [&str; 12] = [ pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"]; -fn lowercase_key(key: &str) -> Value { - let mut key = String::from(key); - key.make_ascii_lowercase(); - Value::from(key.as_str()) -} - pub fn use_lowercase(config: Mapping) -> Mapping { let mut lowercased = Mapping::new(); for (key, value) in config { - if let Some(key_str) = key.as_str() { - lowercased.insert(lowercase_key(key_str), value); - } + let mut key = match key { + Value::String(key) => key, + key => { + let Some(key) = key.as_str() else { + continue; + }; + key.to_owned() + } + }; + key.make_ascii_lowercase(); + lowercased.insert(Value::String(key), value); } lowercased } @@ -39,7 +41,7 @@ pub fn use_sort(mut config: Mapping) -> Mapping { let mut sorted = Mapping::new(); HANDLE_FIELDS.into_iter().for_each(|key| { let key = Value::from(key); - if let Some(value) = config.remove(&key) { + if let Some(value) = config.shift_remove(&key) { sorted.insert(key, value); } }); @@ -66,8 +68,8 @@ pub fn use_sort(mut config: Mapping) -> Mapping { } #[inline] -pub fn use_keys<'a>(config: &'a Mapping) -> impl Iterator + 'a { - config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| { +pub(super) fn lowercase_config_keys(config: &Mapping) -> impl Iterator { + config.keys().filter_map(Value::as_str).map(|s: &str| { let mut s: String = s.into(); s.make_ascii_lowercase(); s diff --git a/crates/clash-verge-config-render/src/lib.rs b/crates/clash-verge-config-render/src/lib.rs new file mode 100644 index 000000000..9abb1f035 --- /dev/null +++ b/crates/clash-verge-config-render/src/lib.rs @@ -0,0 +1,1680 @@ +mod field; +mod merge; +mod script; +mod seq; +mod tun; + +pub use seq::SeqMap; + +use self::{ + field::{lowercase_config_keys, use_lowercase, use_sort}, + merge::use_merge, + script::use_script, + seq::use_seq, + tun::use_tun, +}; +use clash_verge_logging::{Type, logging}; +use serde_yaml_ng::{Mapping, Value}; +use std::collections::{HashMap, HashSet}; +use std::hash::{Hash as _, Hasher as _}; +use std::sync::Arc; +use tristr::alias::String; + +pub type ResultLog = Vec<(String, String)>; +pub type ScriptOutcome = (Result, ResultLog); + +pub const ITEM_SCRIPT: &str = "// Define main function (script entry) + +function main(config, profileName) { + return config; +} +"; + +#[derive(Debug)] +pub struct ChainItem { + pub uid: String, + pub data: ChainType, +} + +#[derive(Debug)] +pub enum ChainType { + Merge(Mapping), + Script(String), + Rules(SeqMap), + Proxies(SeqMap), + Groups(SeqMap), +} + +#[derive(Debug)] +pub struct RenderSettings { + pub clash_config: Mapping, + pub enable_tun: bool, + pub enable_builtin: bool, + pub socks_enabled: bool, + pub http_enabled: bool, + pub enable_external_controller: bool, + #[cfg(not(target_os = "windows"))] + pub redir_enabled: bool, + #[cfg(target_os = "linux")] + pub tproxy_enabled: bool, +} + +#[derive(Debug)] +pub struct RenderProfile { + pub config: Mapping, + pub merge_item: Arc, + pub script_item: Arc, + pub rules_item: Arc, + pub proxies_item: Arc, + pub groups_item: Arc, + pub global_merge: Arc, + pub global_script: Arc, + pub profile_name: String, +} + +pub struct RenderedConfig { + pub config: Mapping, + pub exists_keys: HashSet, + pub logs: HashMap, + pub discarded_keys: Vec, +} + +async fn apply_merge_and_script + Send>( + mut config: Mapping, + profile_keys: &mut HashSet, + chain_logs: &mut HashMap, + (merge_item, script_item): (Arc, Arc), + profile_name: &str, + authoritative: &AuthoritativeFields, + execute_script: &(impl Fn(String, serde_json::Value, String) -> Fut + Sync), +) -> Mapping { + if let ChainType::Merge(merge) = &merge_item.data { + profile_keys.extend(lowercase_config_keys(merge)); + let before = authoritative.current(&config); + config = use_merge(merge.clone(), config); + let notes: ResultLog = authoritative + .overridden(&before, &authoritative.current(&config)) + .into_iter() + .map(discarded_note) + .collect(); + if !notes.is_empty() { + chain_logs.entry(merge_item.uid.clone()).or_default().extend(notes); + } + } + + if let ChainType::Script(script) = &script_item.data { + let before = authoritative.current(&config); + let (res_config, changed_keys, mut logs) = + use_script(script.clone(), config, profile_name.into(), execute_script).await; + profile_keys.extend(changed_keys); + config = res_config; + logs.extend( + authoritative + .overridden(&before, &authoritative.current(&config)) + .into_iter() + .map(discarded_note), + ); + chain_logs.insert(script_item.uid.clone(), logs); + } + + config +} + +fn apply_sequence_overrides( + mut config: Mapping, + rules_item: Arc, + proxies_item: Arc, + groups_item: Arc, +) -> Mapping { + if let ChainType::Rules(rules) = &rules_item.data { + config = use_seq(rules.clone(), config, "rules"); + } + + if let ChainType::Proxies(proxies) = &proxies_item.data { + config = use_seq(proxies.clone(), config, "proxies"); + } + + if let ChainType::Groups(groups) = &groups_item.data { + config = use_seq(groups.clone(), config, "proxy-groups"); + } + + config +} + +/// App-owned control-plane keys; DNS settings are captured separately. +const CONTROL_PLANE_KEYS: &[&str] = &[ + "external-controller", + #[cfg(unix)] + "external-controller-unix", + #[cfg(windows)] + "external-controller-pipe", + "external-controller-cors", + "secret", + "mixed-port", + "socks-port", + "port", + #[cfg(not(target_os = "windows"))] + "redir-port", + #[cfg(target_os = "linux")] + "tproxy-port", + "mode", + "allow-lan", + "log-level", + "ipv6", + "unified-delay", +]; + +/// App-owned fields: captured after the app derives them, enforced after every override. +struct AuthoritativeFields { + control_plane: Mapping, + tun: Mapping, + dns: Mapping, + hosts: Option, + fingerprints: FieldFingerprints, +} + +#[derive(Default)] +struct FieldFingerprints { + control_plane: Vec>, + tun: Vec>, + dns: Vec>, + hosts: Option, +} + +fn fingerprint(value: Option<&Value>) -> Option { + let value = value?; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + value.hash(&mut hasher); + Some(hasher.finish()) +} + +impl AuthoritativeFields { + fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self { + let control_plane = snapshot_control_plane(config); + let tun = snapshot_tun(config, gui_tun_keys); + let dns = take_mapping(&mut dns_settings, "dns"); + let hosts = dns_settings.remove("hosts"); + let fingerprints = FieldFingerprints { + control_plane: CONTROL_PLANE_KEYS + .iter() + .map(|&key| fingerprint(control_plane.get(Value::from(key)))) + .collect(), + tun: tun.iter().map(|(_, value)| fingerprint(Some(value))).collect(), + dns: dns.iter().map(|(_, value)| fingerprint(Some(value))).collect(), + hosts: fingerprint(hosts.as_ref()), + }; + Self { + control_plane, + tun, + dns, + hosts, + fingerprints, + } + } + + fn enforce(self, config: Mapping) -> Mapping { + let config = enforce_control_plane(config, self.control_plane); + let mut config = enforce_tun(config, self.tun); + if !self.dns.is_empty() { + let mut dns = take_mapping(&mut config, "dns"); + dns.extend(self.dns); + config.insert("dns".into(), dns.into()); + } + if let Some(hosts) = self.hosts { + config.insert("hosts".into(), hosts); + } + config + } + + /// What `config` holds now, for diffing one override. + fn current(&self, config: &Mapping) -> FieldFingerprints { + let tun = config.get("tun").and_then(Value::as_mapping); + let dns = config.get("dns").and_then(Value::as_mapping); + FieldFingerprints { + control_plane: CONTROL_PLANE_KEYS + .iter() + .map(|&key| fingerprint(config.get(key))) + .collect(), + tun: self + .tun + .keys() + .map(|key| fingerprint(tun.and_then(|map| map.get(key)))) + .collect(), + dns: self + .dns + .keys() + .map(|key| fingerprint(dns.and_then(|map| map.get(key)))) + .collect(), + hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))), + } + } + + /// Owned keys an override moved off the app value; `enforce` discards those writes. + fn overridden(&self, before: &FieldFingerprints, after: &FieldFingerprints) -> Vec { + let mut keys = Vec::new(); + for (index, &key) in CONTROL_PLANE_KEYS.iter().enumerate() { + if before.control_plane[index] != after.control_plane[index] + && after.control_plane[index] != self.fingerprints.control_plane[index] + { + keys.push(key.into()); + } + } + for (index, key) in self.tun.keys().enumerate() { + if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] { + keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into()); + } + } + for (index, key) in self.dns.keys().enumerate() { + if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] { + keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into()); + } + } + if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.fingerprints.hosts { + keys.push("hosts".into()); + } + keys + } +} + +fn discarded_note(key: String) -> (String, String) { + ( + "warn".into(), + format!("`{key}` is managed by Settings; the value written here was discarded").into(), + ) +} + +/// 手动 merge/script 前保存 app 最终控制面值,只记录当前存在的键。 +fn snapshot_control_plane(config: &Mapping) -> Mapping { + let mut snapshot = Mapping::new(); + for &key in CONTROL_PLANE_KEYS { + let key = Value::from(key); + if let Some(value) = config.get(&key) { + snapshot.insert(key, value.clone()); + } + } + snapshot +} + +/// 手动覆盖后恢复控制面快照;快照缺失的控制面键从最终配置删除。 +fn enforce_control_plane(mut config: Mapping, snapshot: Mapping) -> Mapping { + for &key in CONTROL_PLANE_KEYS { + let key = Value::from(key); + if !snapshot.contains_key(&key) { + config.remove(&key); + } + } + config.extend(snapshot); + config +} + +/// Only saved GUI fields and the verge switch override profile settings. +fn gui_tun_keys(clash_config: &Mapping) -> Vec { + let mut keys = vec![Value::from("enable")]; + if let Some(Value::Mapping(tun)) = clash_config.get("tun") { + keys.extend( + tun::GUI_KEYS + .iter() + .filter(|key| tun.get(**key).is_some_and(|value| !value.is_null())) + .map(|key| Value::from(*key)), + ); + } + keys +} + +fn snapshot_tun(config: &Mapping, gui_tun_keys: &[Value]) -> Mapping { + let mut snapshot = Mapping::new(); + if let Some(Value::Mapping(tun)) = config.get("tun") { + for key in gui_tun_keys { + if let Some(value) = tun.get(key) { + snapshot.insert(key.clone(), value.clone()); + } + } + } + snapshot +} + +fn enforce_tun(mut config: Mapping, snapshot: Mapping) -> Mapping { + if snapshot.is_empty() { + return config; + } + let mut tun = take_mapping(&mut config, "tun"); + tun.extend(snapshot); + config.insert(Value::from("tun"), Value::Mapping(tun)); + config +} + +fn is_loopback_bind_address(addr: &str) -> bool { + let addr = addr.trim(); + let addr = addr.strip_circumfix('[', ']').unwrap_or(addr); + + addr.eq_ignore_ascii_case("localhost") + || addr.parse::().is_ok_and(|addr| addr.is_loopback()) + || is_ipv4_shorthand_loopback(addr) +} + +fn is_ipv4_shorthand_loopback(addr: &str) -> bool { + let parts = addr.split('.').map(str::parse::).collect::, _>>(); + + let Ok(parts) = parts else { + return false; + }; + + match parts.as_slice() { + [first, rest] => *first == 127 && *rest <= 0x00ff_ffff, + [first, second, rest] => *first == 127 && *second <= 0xff && *rest <= 0xffff, + [first, second, third, fourth] => *first == 127 && *second <= 0xff && *third <= 0xff && *fourth <= 0xff, + _ => false, + } +} + +fn ensure_lan_bind_address(mut config: Mapping) -> Mapping { + let allow_lan = config.get("allow-lan").and_then(Value::as_bool).unwrap_or(false); + + if allow_lan + && config + .get("bind-address") + .and_then(Value::as_str) + .is_some_and(is_loopback_bind_address) + { + config.insert(Value::from("bind-address"), Value::from("*")); + } + + config +} + +fn ensure_tun_default_mtu(mut config: Mapping) -> Mapping { + if let Some(Value::Mapping(tun)) = config.get_mut("tun") + && matches!(tun.get("mtu"), None | Some(Value::Null)) + { + tun.insert(Value::from("mtu"), Value::from(tun::DEFAULT_MTU)); + } + + config +} + +/// Merges the app's clash config over the profile; switches are parameters to keep it pure. +fn merge_default_config( + mut config: Mapping, + clash_config: Mapping, + socks_enabled: bool, + http_enabled: bool, + enable_external_controller: bool, + #[cfg(not(target_os = "windows"))] redir_enabled: bool, + #[cfg(target_os = "linux")] tproxy_enabled: bool, +) -> Mapping { + for (key, value) in clash_config.into_iter() { + if key.as_str() == Some("tun") { + if let Value::Mapping(patch_tun) = value { + let mut tun = take_mapping(&mut config, "tun"); + tun.extend(patch_tun.into_iter().filter(|(_, value)| !value.is_null())); + config.insert(Value::from("tun"), Value::Mapping(tun)); + } + } else { + if key.as_str() == Some("socks-port") && !socks_enabled { + config.remove("socks-port"); + continue; + } + if key.as_str() == Some("port") && !http_enabled { + config.remove("port"); + continue; + } + #[cfg(target_os = "windows")] + { + if key.as_str() == Some("redir-port") { + continue; + } + } + #[cfg(not(target_os = "windows"))] + { + if key.as_str() == Some("redir-port") && !redir_enabled { + config.remove("redir-port"); + continue; + } + } + #[cfg(target_os = "linux")] + { + if key.as_str() == Some("tproxy-port") && !tproxy_enabled { + config.remove("tproxy-port"); + continue; + } + } + #[cfg(not(target_os = "linux"))] + { + if key.as_str() == Some("tproxy-port") { + config.remove("tproxy-port"); + continue; + } + } + if key.as_str() == Some("external-controller") { + if enable_external_controller { + config.insert(key, value); + } else { + config.insert(key, "".into()); + } + } else { + config.insert(key, value); + } + } + } + + config +} + +fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping { + if enable_builtin { + // The JS path saw a lowercased view; lowercase once, only when the builtin runs. + config = use_lowercase(config); + logging!(debug, Type::Core, "run builtin script verge_hy_alpn"); + config = builtin_hy_alpn(config); + } + + config +} + +fn builtin_hy_alpn(mut config: Mapping) -> Mapping { + if let Some(Value::Sequence(proxies)) = config.get_mut("proxies") { + for proxy in proxies.iter_mut() { + let Some(proxy) = proxy.as_mapping_mut() else { continue }; + let is_hysteria = proxy.get("type").and_then(Value::as_str) == Some("hysteria"); + if is_hysteria + && let Some(alpn) = proxy.get_mut("alpn") + && let Value::String(text) = alpn + { + let text = std::mem::take(text); + *alpn = Value::Sequence(vec![Value::String(text)]); + } + } + } + + config +} + +fn cleanup_proxy_groups(mut config: Mapping) -> Mapping { + // built-in proxies docs: https://wiki.metacubex.one/config/proxies/built-in + const BUILTIN_POLICIES: &[&str] = &["DIRECT", "REJECT", "REJECT-DROP", "PASS", "PASS-RULE"]; + + let proxy_names = config + .get("proxies") + .and_then(|v| v.as_sequence()) + .map_or_default(|seq| { + seq.iter() + .filter_map(|item| match item { + Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(Into::into), + Value::String(name) => Some(name.as_str().into()), + _ => None, + }) + .collect::>() + }); + + let group_names = config + .get("proxy-groups") + .and_then(|v| v.as_sequence()) + .map_or_default(|seq| { + seq.iter() + .filter_map(|item| { + item.as_mapping() + .and_then(|map| map.get("name")) + .and_then(Value::as_str) + .map(std::convert::Into::into) + }) + .collect::>() + }); + + let provider_names = config + .get("proxy-providers") + .and_then(Value::as_mapping) + .map_or_default(|map| { + map.keys() + .filter_map(Value::as_str) + .map(std::convert::Into::into) + .collect::>() + }); + + let mut allowed_names = proxy_names; + allowed_names.extend(group_names); + allowed_names.extend(provider_names.iter().cloned()); + allowed_names.extend(BUILTIN_POLICIES.iter().map(|p| (*p).into())); + + let Some(Value::Sequence(groups)) = config.get_mut("proxy-groups") else { + return config; + }; + + for group_map in groups.iter_mut().filter_map(Value::as_mapping_mut) { + let mut has_valid_provider = false; + + if let Some(Value::Sequence(uses)) = group_map.get_mut("use") { + uses.retain(|provider| { + let Value::String(name) = provider else { + return false; + }; + let exists = provider_names.contains(name.as_str()); + has_valid_provider |= exists; + exists + }); + } + + if let Some(Value::Sequence(proxies)) = group_map.get_mut("proxies") { + proxies.retain(|proxy| match proxy { + Value::String(name) => allowed_names.contains(name.as_str()) || has_valid_provider, + _ => true, + }); + } + } + + config +} + +/// fake-ip + IPv6 缺少 `fake-ip-range6` 时补默认值,否则 AAAA 无法解析(#7373)。 +fn ensure_fake_ip_range6(dns: &mut Mapping) { + use serde_yaml_ng::Value; + + let ipv6_enabled = dns.get("ipv6").and_then(|v| v.as_bool()).unwrap_or(false); + let is_fake_ip = dns + .get("enhanced-mode") + .and_then(|v| v.as_str()) + .is_none_or(|m| m == "fake-ip"); + + // Hand-edited YAML may leave the key present but empty. + let range6_missing = dns + .get("fake-ip-range6") + .and_then(|v| v.as_str()) + .is_none_or(|s| s.trim().is_empty()); + + if ipv6_enabled && is_fake_ip && range6_missing { + dns.insert(Value::from("fake-ip-range6"), Value::from("2001:2::0/64")); + } +} + +/// On, non-blank text, or non-empty list/map; anything else keeps the profile's value. +fn is_set(value: &Value) -> bool { + match value { + Value::Null => false, + Value::Bool(on) => *on, + Value::String(text) => !text.trim().is_empty(), + Value::Sequence(items) => !items.is_empty(), + Value::Mapping(map) => !map.is_empty(), + Value::Number(_) | Value::Tagged(_) => true, + } +} + +fn take_mapping(config: &mut Mapping, key: &str) -> Mapping { + config + .get_mut(key) + .and_then(Value::as_mapping_mut) + .map_or_default(std::mem::take) +} + +fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, Mapping) { + let mut applied = Mapping::new(); + if let Some(Value::Mapping(hosts)) = dns_config.remove("hosts") + && !hosts.is_empty() + { + applied.insert("hosts".into(), hosts.clone().into()); + config.insert("hosts".into(), hosts.into()); + logging!(debug, Type::Core, "apply hosts configuration"); + } + + // Legacy layout: no `dns` root. + let dns_override = match dns_config.remove("dns") { + Some(Value::Mapping(dns)) => Some(dns), + Some(_) => None, + None => Some(dns_config), + }; + if let Some(mut dns_override) = dns_override { + dns_override.retain(|_, value| is_set(value)); + if !dns_override.is_empty() { + applied.insert("dns".into(), dns_override.clone().into()); + } + let mut dns = take_mapping(&mut config, "dns"); + dns.extend(dns_override); + ensure_fake_ip_range6(&mut dns); + config.insert("dns".into(), dns.into()); + logging!(debug, Type::Core, "apply dns_config.yaml"); + } + (config, applied) +} + +pub async fn render + Send>( + profile: RenderProfile, + settings: RenderSettings, + dns_config: Option, + execute_script: impl Fn(String, serde_json::Value, String) -> Fut + Send + Sync, +) -> RenderedConfig { + let RenderSettings { + clash_config, + enable_tun, + enable_builtin, + socks_enabled, + http_enabled, + enable_external_controller, + #[cfg(not(target_os = "windows"))] + redir_enabled, + #[cfg(target_os = "linux")] + tproxy_enabled, + } = settings; + let config = apply_sequence_overrides( + profile.config, + profile.rules_item, + profile.proxies_item, + profile.groups_item, + ); + let mut profile_keys = lowercase_config_keys(&config).collect(); + let mut chain_logs = HashMap::new(); + let gui_tun_keys = gui_tun_keys(&clash_config); + + let config = merge_default_config( + config, + clash_config, + socks_enabled, + http_enabled, + enable_external_controller, + #[cfg(not(target_os = "windows"))] + redir_enabled, + #[cfg(target_os = "linux")] + tproxy_enabled, + ); + + let config = apply_builtin_scripts(config, enable_builtin); + let config = use_tun(config, enable_tun); + let (mut config, dns_settings) = match dns_config { + Some(dns_config) => merge_dns_config(config, dns_config), + None => (config, Mapping::new()), + }; + + let authoritative = AuthoritativeFields::capture(&config, &gui_tun_keys, dns_settings); + + for overrides in [ + (profile.global_merge, profile.global_script), + (profile.merge_item, profile.script_item), + ] { + config = apply_merge_and_script( + config, + &mut profile_keys, + &mut chain_logs, + overrides, + &profile.profile_name, + &authoritative, + &execute_script, + ) + .await; + } + + let discarded_keys = authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config)); + let config = authoritative.enforce(config); + let config = ensure_tun_default_mtu(config); + let config = ensure_lan_bind_address(config); + + let config = cleanup_proxy_groups(config); + let config = use_sort(config); + + RenderedConfig { + config, + exists_keys: profile_keys, + logs: chain_logs, + discarded_keys, + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] +mod fake_ip_tests { + use super::{Mapping, Value, ensure_fake_ip_range6}; + + fn dns(pairs: &[(&str, Value)]) -> Mapping { + let mut map = Mapping::new(); + for (key, value) in pairs { + map.insert(Value::from(*key), value.clone()); + } + map + } + + const RANGE6: &str = "2001:2::0/64"; + + #[test] + fn an_ipv6_fake_ip_setup_missing_its_range_gets_one() { + let mut config = dns(&[("ipv6", Value::from(true)), ("enhanced-mode", Value::from("fake-ip"))]); + + ensure_fake_ip_range6(&mut config); + + assert_eq!(config.get(Value::from("fake-ip-range6")), Some(&Value::from(RANGE6))); + } + + #[test] + fn fake_ip_is_the_assumed_mode_when_unstated() { + let mut config = dns(&[("ipv6", Value::from(true))]); + + ensure_fake_ip_range6(&mut config); + + assert_eq!(config.get(Value::from("fake-ip-range6")), Some(&Value::from(RANGE6))); + } + + #[test] + fn a_hand_edited_empty_range_counts_as_missing() { + // Hand-edited YAML may leave the key present but empty. + for blank in ["", " "] { + let mut config = dns(&[ + ("ipv6", Value::from(true)), + ("enhanced-mode", Value::from("fake-ip")), + ("fake-ip-range6", Value::from(blank)), + ]); + + ensure_fake_ip_range6(&mut config); + + assert_eq!( + config.get(Value::from("fake-ip-range6")), + Some(&Value::from(RANGE6)), + "blank range {blank:?} should be filled in" + ); + } + } + + #[test] + fn an_existing_range_is_never_overwritten() { + let mut config = dns(&[ + ("ipv6", Value::from(true)), + ("enhanced-mode", Value::from("fake-ip")), + ("fake-ip-range6", Value::from("fc00::1/64")), + ]); + + ensure_fake_ip_range6(&mut config); + + assert_eq!( + config.get(Value::from("fake-ip-range6")), + Some(&Value::from("fc00::1/64")) + ); + } + + #[test] + fn nothing_is_added_without_ipv6_or_outside_fake_ip() { + let mut without_ipv6 = dns(&[("enhanced-mode", Value::from("fake-ip"))]); + ensure_fake_ip_range6(&mut without_ipv6); + assert!(!without_ipv6.contains_key(Value::from("fake-ip-range6"))); + + let mut redir_host = dns(&[ + ("ipv6", Value::from(true)), + ("enhanced-mode", Value::from("redir-host")), + ]); + ensure_fake_ip_range6(&mut redir_host); + assert!(!redir_host.contains_key(Value::from("fake-ip-range6"))); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] +mod use_tun_tests { + use super::{Mapping, Value, use_tun}; + + fn mapping(pairs: &[(&str, Value)]) -> Mapping { + let mut map = Mapping::new(); + for (key, value) in pairs { + map.insert(Value::from(*key), value.clone()); + } + map + } + + fn tun_of(config: &Mapping) -> &Mapping { + config + .get(Value::from("tun")) + .and_then(Value::as_mapping) + .expect("tun should be a mapping") + } + + fn dns_of(config: &Mapping) -> Option<&Mapping> { + config.get(Value::from("dns")).and_then(Value::as_mapping) + } + + #[tokio::test] + async fn the_switch_is_written_either_way() { + assert_eq!( + tun_of(&use_tun(Mapping::new(), true)).get(Value::from("enable")), + Some(&Value::from(true)) + ); + assert_eq!( + tun_of(&use_tun(Mapping::new(), false)).get(Value::from("enable")), + Some(&Value::from(false)) + ); + } + + #[tokio::test] + async fn existing_tun_keys_survive_being_switched_on() { + let config = mapping(&[("tun", Value::Mapping(mapping(&[("stack", Value::from("gvisor"))])))]); + + let result = use_tun(config, true); + + assert_eq!(tun_of(&result).get(Value::from("stack")), Some(&Value::from("gvisor"))); + } + + #[tokio::test] + async fn enabling_tun_sets_up_fake_ip_dns() { + let result = use_tun(Mapping::new(), true); + + let dns = dns_of(&result).expect("enabling tun should write dns settings"); + assert_eq!(dns.get(Value::from("enable")), Some(&Value::from(true))); + assert_eq!(dns.get(Value::from("enhanced-mode")), Some(&Value::from("fake-ip"))); + assert_eq!( + dns.get(Value::from("fake-ip-range")), + Some(&Value::from("198.18.0.1/16")) + ); + } + + #[tokio::test] + async fn a_deliberate_redir_host_setup_is_left_alone() { + // Only fake-ip DNS is ours to configure; someone who chose redir-host meant it. + let config = mapping(&[( + "dns", + Value::Mapping(mapping(&[("enhanced-mode", Value::from("redir-host"))])), + )]); + + let result = use_tun(config, true); + + let dns = dns_of(&result).expect("dns should still be present"); + assert_eq!(dns.get(Value::from("enhanced-mode")), Some(&Value::from("redir-host"))); + assert!(!dns.contains_key(Value::from("fake-ip-range"))); + } + + #[tokio::test] + async fn the_ipv6_fake_ip_range_follows_the_top_level_switch() { + let with_ipv6 = use_tun(mapping(&[("ipv6", Value::from(true))]), true); + let dns = dns_of(&with_ipv6).expect("dns should be written"); + assert_eq!(dns.get(Value::from("ipv6")), Some(&Value::from(true))); + assert_eq!( + dns.get(Value::from("fake-ip-range6")), + Some(&Value::from("2001:2::0/64")) + ); + + let blank_range = mapping(&[ + ("ipv6", Value::from(true)), + ("dns", Value::Mapping(mapping(&[("fake-ip-range6", Value::from(" "))]))), + ]); + assert_eq!( + use_tun(blank_range, true)["dns"]["fake-ip-range6"], + Value::from("2001:2::0/64") + ); + + let without_ipv6 = use_tun(Mapping::new(), true); + let dns = dns_of(&without_ipv6).expect("dns should be written"); + assert!(!dns.contains_key(Value::from("fake-ip-range6"))); + } + + #[tokio::test] + async fn switching_tun_off_leaves_dns_untouched() { + // TUN off must not rewrite the DNS the profile chose. + let config = mapping(&[("dns", Value::Mapping(mapping(&[("enable", Value::from(false))])))]); + + let result = use_tun(config, false); + + let dns = dns_of(&result).expect("dns should be untouched"); + assert_eq!(dns.get(Value::from("enable")), Some(&Value::from(false))); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] +mod use_sort_tests { + use super::{Mapping, Value, use_sort}; + + #[test] + fn every_key_survives_sorting() { + let mut config = Mapping::new(); + for key in ["rules", "mode", "proxies", "not-a-known-field", "log-level"] { + config.insert(Value::from(key), Value::from(key)); + } + let expected = config.len(); + + let sorted = use_sort(config); + + assert_eq!(sorted.len(), expected, "sorting must not drop or invent keys"); + for key in ["rules", "mode", "proxies", "not-a-known-field", "log-level"] { + assert_eq!(sorted.get(Value::from(key)), Some(&Value::from(key))); + } + } + + #[test] + fn the_bulky_list_fields_are_written_last() { + // Bulky list fields go last so the top of the file stays readable. + let mut config = Mapping::new(); + config.insert(Value::from("rules"), Value::from("rules")); + config.insert(Value::from("mode"), Value::from("rule")); + + let sorted = use_sort(config); + let order: Vec<_> = sorted.keys().filter_map(Value::as_str).collect(); + + let mode = order.iter().position(|key| *key == "mode"); + let rules = order.iter().position(|key| *key == "rules"); + assert!(mode < rules, "expected mode before rules, got {order:?}"); + } + + #[test] + fn sorting_is_stable_when_applied_twice() { + let mut config = Mapping::new(); + for key in ["mode", "dns", "tun", "hosts"] { + config.insert(Value::from(key), Value::from(1)); + } + + let once = use_sort(config); + let twice = use_sort(once.clone()); + + assert_eq!(once.keys().collect::>(), twice.keys().collect::>()); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] +mod merge_default_config_tests { + use super::{Mapping, Value, merge_default_config}; + + fn mapping(pairs: &[(&str, Value)]) -> Mapping { + let mut map = Mapping::new(); + for (key, value) in pairs { + map.insert(Value::from(*key), value.clone()); + } + map + } + + /// Call with every listener enabled, so a test only says what it is turning off. + fn merge(config: Mapping, clash_config: Mapping, external_controller: bool) -> Mapping { + merge_default_config( + config, + clash_config, + true, + true, + external_controller, + #[cfg(not(target_os = "windows"))] + true, + #[cfg(target_os = "linux")] + true, + ) + } + + fn merge_without_optional_listeners(config: Mapping, clash_config: Mapping) -> Mapping { + merge_default_config( + config, + clash_config, + false, + false, + true, + #[cfg(not(target_os = "windows"))] + false, + #[cfg(target_os = "linux")] + false, + ) + } + + #[test] + fn the_merge_config_overwrites_the_profile() { + let config = mapping(&[("mode", Value::from("rule"))]); + let clash_config = mapping(&[("mode", Value::from("global"))]); + + let merged = merge(config, clash_config, true); + + assert_eq!(merged.get(Value::from("mode")), Some(&Value::from("global"))); + } + + #[test] + fn keys_the_merge_config_says_nothing_about_survive() { + let config = mapping(&[("profile-only", Value::from(1))]); + + let merged = merge(config, Mapping::new(), true); + + assert_eq!(merged.get(Value::from("profile-only")), Some(&Value::from(1))); + } + + #[test] + fn a_disabled_listener_is_removed_rather_than_merged() { + // Removed, not skipped: the profile's own value must not reopen a disabled listener. + let config = mapping(&[("socks-port", Value::from(7891)), ("port", Value::from(7890))]); + let clash_config = mapping(&[("socks-port", Value::from(1080)), ("port", Value::from(8080))]); + + let merged = merge_without_optional_listeners(config, clash_config); + + assert!(!merged.contains_key(Value::from("socks-port"))); + assert!(!merged.contains_key(Value::from("port"))); + } + + #[test] + fn an_enabled_listener_takes_the_merge_config_value() { + let config = mapping(&[("socks-port", Value::from(7891))]); + let clash_config = mapping(&[("socks-port", Value::from(1080))]); + + let merged = merge(config, clash_config, true); + + assert_eq!(merged.get(Value::from("socks-port")), Some(&Value::from(1080))); + } + + #[test] + fn a_disabled_external_controller_is_blanked_rather_than_dropped() { + // Blanked, not removed: an absent key makes mihomo listen on its default. + let clash_config = mapping(&[("external-controller", Value::from("127.0.0.1:9090"))]); + + let merged = merge(Mapping::new(), clash_config, false); + + assert_eq!( + merged.get(Value::from("external-controller")), + Some(&Value::from("")), + "the key must remain, holding an empty value" + ); + } + + #[test] + fn an_enabled_external_controller_keeps_its_address() { + let clash_config = mapping(&[("external-controller", Value::from("127.0.0.1:9090"))]); + + let merged = merge(Mapping::new(), clash_config, true); + + assert_eq!( + merged.get(Value::from("external-controller")), + Some(&Value::from("127.0.0.1:9090")) + ); + } + + #[test] + fn tun_settings_are_merged_key_by_key_rather_than_replaced() { + // The profile's other tun keys have to survive a merge config that sets only one. + let config = mapping(&[( + "tun", + Value::Mapping(mapping(&[ + ("device", Value::from("utun9")), + ("stack", Value::from("system")), + ])), + )]); + let clash_config = mapping(&[("tun", Value::Mapping(mapping(&[("stack", Value::from("gvisor"))])))]); + + let merged = merge(config, clash_config, true); + + let tun = merged + .get(Value::from("tun")) + .and_then(Value::as_mapping) + .expect("tun should still be a mapping"); + assert_eq!(tun.get(Value::from("device")), Some(&Value::from("utun9"))); + assert_eq!(tun.get(Value::from("stack")), Some(&Value::from("gvisor"))); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] +mod authoritative_field_tests { + use super::{AuthoritativeFields, Mapping, Value}; + + fn config_with(pairs: &[(&str, Value)]) -> Mapping { + let mut config = Mapping::new(); + for (key, value) in pairs { + config.insert(Value::from(*key), value.clone()); + } + config + } + + fn dns_with_ipv6(enabled: bool) -> Value { + let mut dns = Mapping::new(); + dns.insert(Value::from("ipv6"), Value::from(enabled)); + dns.insert(Value::from("enable"), Value::from(true)); + Value::Mapping(dns) + } + + #[test] + fn an_override_cannot_change_a_field_the_app_owns() { + let derived = config_with(&[("mode", Value::from("rule")), ("secret", Value::from("ours"))]); + let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new()); + + let overridden = config_with(&[("mode", Value::from("global")), ("secret", Value::from("theirs"))]); + let result = authoritative.enforce(overridden); + + assert_eq!(result.get(Value::from("mode")), Some(&Value::from("rule"))); + assert_eq!(result.get(Value::from("secret")), Some(&Value::from("ours"))); + } + + #[test] + fn an_override_cannot_introduce_a_field_the_app_left_out() { + // The app decided not to expose the external controller; a profile must not re-add it. + let derived = Mapping::new(); + let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new()); + + let overridden = config_with(&[("external-controller", Value::from("0.0.0.0:9090"))]); + let result = authoritative.enforce(overridden); + + assert!(!result.contains_key(Value::from("external-controller"))); + } + + #[test] + fn fields_the_app_does_not_own_survive_an_override() { + let derived = config_with(&[("mode", Value::from("rule"))]); + let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new()); + + let overridden = config_with(&[("mode", Value::from("global")), ("profile-key", Value::from(1))]); + let result = authoritative.enforce(overridden); + + assert_eq!(result.get(Value::from("profile-key")), Some(&Value::from(1))); + } + + #[test] + fn dns_ipv6_is_only_reclaimed_when_the_dns_page_owns_it() { + let derived = config_with(&[("dns", dns_with_ipv6(true))]); + + let owned = AuthoritativeFields::capture(&derived, &[], derived.clone()); + let restored = owned.enforce(config_with(&[("dns", dns_with_ipv6(false))])); + assert_eq!( + restored.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")), + Some(&Value::from(true)), + "with the DNS page on, the app's value wins" + ); + + let unowned = AuthoritativeFields::capture(&derived, &[], Mapping::new()); + let left_alone = unowned.enforce(config_with(&[("dns", dns_with_ipv6(false))])); + assert_eq!( + left_alone.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")), + Some(&Value::from(false)), + "with the DNS page off, an override may set it" + ); + } + + #[test] + fn restoring_dns_settings_reinstates_a_removed_dns_block() { + let derived = config_with(&[("dns", dns_with_ipv6(true))]); + let authoritative = AuthoritativeFields::capture(&derived, &[], derived.clone()); + + let result = authoritative.enforce(Mapping::new()); + + assert_eq!(result["dns"], derived["dns"]); + } +} + +#[allow(clippy::expect_used)] +#[cfg(test)] +mod tests { + use super::{ + AuthoritativeFields, ChainItem, ChainType, Mapping, ScriptOutcome, String, apply_merge_and_script, + cleanup_proxy_groups, ensure_lan_bind_address, lowercase_config_keys, + }; + use std::collections::{HashMap, HashSet}; + use std::future::{Ready, ready}; + use std::sync::Arc; + + fn mapping(yaml: &str) -> serde_yaml_ng::Mapping { + serde_yaml_ng::from_str(yaml).expect("test config should be valid") + } + + fn apply_script_fixture(script: String, input: serde_json::Value, _: String) -> Ready { + let mut config: Mapping = serde_json::from_value(input).expect("script input should be a mapping"); + config.extend(mapping(script.as_str())); + ready((Ok(config), vec![])) + } + + #[tokio::test] + async fn dns_settings_override_only_filled_fields_after_merge_and_script() { + let profile = mapping( + "dns: {nameserver: [9.9.9.9], nameserver-policy: {profile.example: 9.9.9.9}}\n\ + hosts: {profile.example: 192.0.2.1}", + ); + let settings = mapping( + "dns: {ipv6: true, nameserver: [8.8.8.8], nameserver-policy: {settings.example: 8.8.8.8},\n\ + proxy-server-nameserver: [], fallback: null, listen: ' '}\n\ + hosts: {settings.example: 192.0.2.2}", + ); + let merge = mapping( + "dns: {ipv6: false, nameserver-policy: {merge.example: 1.1.1.1}}\n\ + hosts: {merge.example: 192.0.2.3}", + ); + let script = r#"dns: {ipv6: false, nameserver: ["4.4.4.4"], + nameserver-policy: {script.example: "4.4.4.4"}, + proxy-server-nameserver: ["4.4.4.4"], fallback: ["4.4.4.4"], + listen: "127.0.0.1:1053"} +hosts: {script.example: "192.0.2.4"}"#; + + for enabled in [false, true] { + let (config, dns_settings) = if enabled { + super::merge_dns_config(profile.clone(), settings.clone()) + } else { + (profile.clone(), Mapping::new()) + }; + let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); + let merge_item = |uid: &str| { + Arc::new(ChainItem { + uid: uid.into(), + data: ChainType::Merge(merge.clone()), + }) + }; + let profile_name = "test-profile"; + let mut keys = HashSet::new(); + let mut logs = HashMap::new(); + let config = apply_merge_and_script( + config, + &mut keys, + &mut logs, + ( + merge_item("global-merge"), + Arc::new(ChainItem { + uid: "global-script".into(), + data: ChainType::Script(script.into()), + }), + ), + profile_name, + &authoritative, + &apply_script_fixture, + ) + .await; + let config = apply_merge_and_script( + config, + &mut keys, + &mut logs, + ( + merge_item("profile-merge"), + Arc::new(ChainItem { + uid: "profile-script".into(), + data: ChainType::Script(script.into()), + }), + ), + profile_name, + &authoritative, + &apply_script_fixture, + ) + .await; + let manual = config.clone(); + let result = authoritative.enforce(config); + + let source = if enabled { &settings } else { &manual }; + assert_eq!(result["dns"]["nameserver-policy"], source["dns"]["nameserver-policy"]); + assert_eq!(result["hosts"], source["hosts"]); + assert_eq!(result["dns"]["nameserver"], source["dns"]["nameserver"]); + assert_eq!(result["dns"]["ipv6"], serde_yaml_ng::Value::from(enabled)); + for key in ["proxy-server-nameserver", "fallback", "listen"] { + assert_eq!(result["dns"][key], manual["dns"][key]); + } + if !enabled { + continue; + } + for uid in ["global-merge", "global-script", "profile-merge", "profile-script"] { + assert!( + logs[uid] + .iter() + .any(|(_, message)| message.contains("dns.nameserver-policy")) + ); + } + } + } + + #[tokio::test] + async fn manual_overrides_follow_expected_priority() { + let mut config = mapping( + r"{global-merge-wins: other, global-script-wins: other, profile-merge-wins: other, + profile-script-wins: other, nested: {winner: other}, dns: {enable: true}, tun: {enable: true}}", + ); + let mut exists_keys = lowercase_config_keys(&config).collect(); + config.insert("application-only".into(), true.into()); + + let global_merge = Arc::new(ChainItem { + uid: "Merge".into(), + data: ChainType::Merge(mapping( + r"{global-merge-wins: global-merge, global-script-wins: global-merge, + profile-merge-wins: global-merge, profile-script-wins: global-merge, + nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}", + )), + }); + let global_script = Arc::new(ChainItem { + uid: "Script".into(), + data: ChainType::Script( + r"{global-script-wins: global-script, profile-merge-wins: global-script, + profile-script-wins: global-script, nested: {winner: global-script}}" + .into(), + ), + }); + let profile_merge = Arc::new(ChainItem { + uid: "profile-merge".into(), + data: ChainType::Merge(mapping( + r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge, + nested: {winner: profile-merge}}", + )), + }); + let profile_script = Arc::new(ChainItem { + uid: "profile-script".into(), + data: ChainType::Script(r"{profile-script-wins: profile-script, nested: {winner: profile-script}}".into()), + }); + + let profile_name = "test-profile"; + let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new()); + let mut logs = HashMap::new(); + let config = apply_merge_and_script( + config, + &mut exists_keys, + &mut logs, + (global_merge, global_script), + profile_name, + &authoritative, + &apply_script_fixture, + ) + .await; + let config = apply_merge_and_script( + config, + &mut exists_keys, + &mut logs, + (profile_merge, profile_script), + profile_name, + &authoritative, + &apply_script_fixture, + ) + .await; + + let string_value = |key| config.get(key).and_then(serde_yaml_ng::Value::as_str); + assert_eq!(string_value("global-merge-wins"), Some("global-merge")); + assert_eq!(string_value("global-script-wins"), Some("global-script")); + assert_eq!(string_value("profile-merge-wins"), Some("profile-merge")); + assert_eq!(string_value("profile-script-wins"), Some("profile-script")); + assert_eq!( + config + .get("nested") + .and_then(|value| value.get("winner")) + .and_then(serde_yaml_ng::Value::as_str), + Some("profile-script") + ); + assert!(!exists_keys.contains("application-only")); + } + + #[test] + fn control_plane_survives_manual_overrides() { + let app_config = mapping( + r#"{external-controller: "", + external-controller-cors: {allow-origins: ["app-only"]}, + mixed-port: 7890, socks-port: 7891, secret: "app-secret", mode: rule, allow-lan: false, + log-level: info, ipv6: false, unified-delay: true, + dns: {proxy-server-nameserver: ["1.1.1.1"]}}"#, + ); + let snapshot = super::snapshot_control_plane(&app_config); + + let hijacked = mapping( + r#"{external-controller: "0.0.0.0:9090", + external-controller-cors: {allow-origins: ["*"]}, + mixed-port: 1080, socks-port: 1080, secret: "hijacked", mode: global, allow-lan: true, + log-level: debug, ipv6: true, unified-delay: false, + dns: {proxy-server-nameserver: ["8.8.8.8"]}}"#, + ); + + let result = super::enforce_control_plane(hijacked, snapshot); + + let as_str = |key| result.get(key).and_then(serde_yaml_ng::Value::as_str); + assert_eq!(as_str("external-controller"), Some("")); + assert_eq!( + result.get("mixed-port").and_then(serde_yaml_ng::Value::as_u64), + Some(7890) + ); + assert_eq!( + result.get("socks-port").and_then(serde_yaml_ng::Value::as_u64), + Some(7891) + ); + assert_eq!( + result + .get("external-controller-cors") + .and_then(|value| value.get("allow-origins")) + .and_then(serde_yaml_ng::Value::as_sequence) + .and_then(|seq| seq.first()) + .and_then(serde_yaml_ng::Value::as_str), + Some("app-only") + ); + assert_eq!(as_str("secret"), Some("app-secret")); + assert_eq!(as_str("mode"), Some("rule")); + assert_eq!( + result.get("allow-lan").and_then(serde_yaml_ng::Value::as_bool), + Some(false) + ); + assert_eq!(as_str("log-level"), Some("info")); + assert_eq!(result.get("ipv6").and_then(serde_yaml_ng::Value::as_bool), Some(false)); + assert_eq!( + result.get("unified-delay").and_then(serde_yaml_ng::Value::as_bool), + Some(true) + ); + + // DNS 数据面不属于顶层控制面。 + assert_eq!( + result + .get("dns") + .and_then(|value| value.get("proxy-server-nameserver")) + .and_then(serde_yaml_ng::Value::as_sequence) + .and_then(|seq| seq.first()) + .and_then(serde_yaml_ng::Value::as_str), + Some("8.8.8.8") + ); + } + + #[test] + fn lan_bind_address_loopback_is_widened() { + for bind_address in [ + "localhost", + "127.0.0.1", + "127.0.0.2", + "127.1", + "::1", + "[::1]", + "0:0:0:0:0:0:0:1", + ] { + let result = ensure_lan_bind_address(mapping(&format!( + r#"{{allow-lan: true, bind-address: "{bind_address}"}}"# + ))); + + assert_eq!( + result.get("bind-address").and_then(serde_yaml_ng::Value::as_str), + Some("*"), + "bind-address {bind_address} should be widened" + ); + } + } + + #[test] + fn lan_bind_address_preserves_custom_or_disabled() { + let custom = ensure_lan_bind_address(mapping(r#"{allow-lan: true, bind-address: "192.168.1.2"}"#)); + assert_eq!( + custom.get("bind-address").and_then(serde_yaml_ng::Value::as_str), + Some("192.168.1.2") + ); + + let disabled = ensure_lan_bind_address(mapping(r#"{allow-lan: false, bind-address: "127.0.0.1"}"#)); + assert_eq!( + disabled.get("bind-address").and_then(serde_yaml_ng::Value::as_str), + Some("127.0.0.1") + ); + } + + #[test] + fn control_plane_removes_reenabled_disabled_port() { + let app_config = mapping(r"{mixed-port: 7890, mode: rule}"); + let snapshot = super::snapshot_control_plane(&app_config); + + let hijacked = mapping(r"{mixed-port: 7890, mode: rule, socks-port: 1080}"); + let result = super::enforce_control_plane(hijacked, snapshot); + + assert!(!result.contains_key("socks-port")); + assert_eq!( + result.get("mixed-port").and_then(serde_yaml_ng::Value::as_u64), + Some(7890) + ); + } + + #[test] + fn empty_dns_settings_leave_inherited_fields_overridable() { + let app_config = mapping(r#"{dns: {ipv6: false, proxy-server-nameserver: ["1.1.1.1"]}}"#); + let (config, dns_settings) = + super::merge_dns_config(app_config, mapping("dns: {ipv6: false, proxy-server-nameserver: []}")); + let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); + + let hijacked = mapping(r#"{dns: {ipv6: true, proxy-server-nameserver: ["8.8.8.8"]}}"#); + let result = authoritative.enforce(hijacked); + + assert_eq!( + result + .get("dns") + .and_then(|value| value.get("ipv6")) + .and_then(serde_yaml_ng::Value::as_bool), + Some(true) + ); + assert_eq!( + result + .get("dns") + .and_then(|value| value.get("proxy-server-nameserver")) + .and_then(serde_yaml_ng::Value::as_sequence) + .and_then(|seq| seq.first()) + .and_then(serde_yaml_ng::Value::as_str), + Some("8.8.8.8") + ); + } + + #[test] + fn snapshot_control_plane_skips_absent_keys() { + let app_config = mapping(r"{mode: rule, mixed-port: 7890}"); + let snapshot = super::snapshot_control_plane(&app_config); + assert!(snapshot.contains_key("mode")); + assert!(snapshot.contains_key("mixed-port")); + assert!(!snapshot.contains_key("secret")); + assert!(!snapshot.contains_key("allow-lan")); + } + + #[test] + fn remove_missing_proxies_from_groups() { + let config_str = r#" +proxies: + - name: "alive-node" + type: ss +proxy-groups: + - name: "manual" + type: select + proxies: + - "alive-node" + - "missing-node" + - "DIRECT" + - name: "nested" + type: select + proxies: + - "manual" + - "ghost" +"#; + + let mut config: serde_yaml_ng::Mapping = + serde_yaml_ng::from_str(config_str).expect("Failed to parse test yaml"); + config = cleanup_proxy_groups(config); + + let groups = config + .get("proxy-groups") + .and_then(|v| v.as_sequence()) + .cloned() + .expect("proxy-groups should be a sequence"); + + let manual_group = groups + .iter() + .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("manual")) + .and_then(|group| group.as_mapping()) + .expect("manual group should exist"); + + let manual_proxies = manual_group + .get("proxies") + .and_then(|v| v.as_sequence()) + .expect("manual proxies should be a sequence"); + + assert_eq!(manual_proxies.len(), 2); + assert!(manual_proxies.iter().any(|p| p.as_str() == Some("alive-node"))); + assert!(manual_proxies.iter().any(|p| p.as_str() == Some("DIRECT"))); + + let nested_group = groups + .iter() + .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("nested")) + .and_then(|group| group.as_mapping()) + .expect("nested group should exist"); + + let nested_proxies = nested_group + .get("proxies") + .and_then(|v| v.as_sequence()) + .expect("nested proxies should be a sequence"); + + assert_eq!(nested_proxies.len(), 1); + assert_eq!(nested_proxies[0].as_str(), Some("manual")); + } + + #[test] + fn keep_provider_backed_groups_intact() { + let config_str = r#" +proxy-providers: + providerA: + type: http + url: https://example.com + path: ./providerA.yaml +proxies: [] +proxy-groups: + - name: "manual" + type: select + use: + - "providerA" + - "ghostProvider" + proxies: + - "dynamic-node" + - "DIRECT" +"#; + + let mut config: serde_yaml_ng::Mapping = + serde_yaml_ng::from_str(config_str).expect("Failed to parse test yaml"); + config = cleanup_proxy_groups(config); + + let groups = config + .get("proxy-groups") + .and_then(|v| v.as_sequence()) + .cloned() + .expect("proxy-groups should be a sequence"); + + let manual_group = groups + .iter() + .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("manual")) + .and_then(|group| group.as_mapping()) + .expect("manual group should exist"); + + let uses = manual_group + .get("use") + .and_then(|v| v.as_sequence()) + .expect("use should be a sequence"); + assert_eq!(uses.len(), 1); + assert_eq!(uses[0].as_str(), Some("providerA")); + + let proxies = manual_group + .get("proxies") + .and_then(|v| v.as_sequence()) + .expect("proxies should be a sequence"); + assert_eq!(proxies.len(), 2); + assert!(proxies.iter().any(|p| p.as_str() == Some("dynamic-node"))); + assert!(proxies.iter().any(|p| p.as_str() == Some("DIRECT"))); + } + + #[test] + fn prune_invalid_provider_and_proxies_without_provider() { + let config_str = r#" +proxy-groups: + - name: "manual" + type: select + use: + - "ghost-provider" + proxies: + - "ghost-node" + - "DIRECT" +"#; + + let mut config: serde_yaml_ng::Mapping = + serde_yaml_ng::from_str(config_str).expect("Failed to parse test yaml"); + config = cleanup_proxy_groups(config); + + let groups = config + .get("proxy-groups") + .and_then(|v| v.as_sequence()) + .cloned() + .expect("proxy-groups should be a sequence"); + + let manual_group = groups + .iter() + .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("manual")) + .and_then(|group| group.as_mapping()) + .expect("manual group should exist"); + + let uses = manual_group + .get("use") + .and_then(|v| v.as_sequence()) + .expect("use should be a sequence"); + assert_eq!(uses.len(), 0); + + let proxies = manual_group + .get("proxies") + .and_then(|v| v.as_sequence()) + .expect("proxies should be a sequence"); + assert_eq!(proxies.len(), 1); + assert_eq!(proxies[0].as_str(), Some("DIRECT")); + } +} diff --git a/src-tauri/src/enhance/merge.rs b/crates/clash-verge-config-render/src/merge.rs similarity index 98% rename from src-tauri/src/enhance/merge.rs rename to crates/clash-verge-config-render/src/merge.rs index 6c0ea375a..cd4d95c6e 100644 --- a/src-tauri/src/enhance/merge.rs +++ b/crates/clash-verge-config-render/src/merge.rs @@ -32,7 +32,7 @@ pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping { } #[test] -fn test_merge() -> anyhow::Result<()> { +fn test_merge() -> Result<(), serde_yaml_ng::Error> { let merge = r" prepend-rules: - prepend diff --git a/crates/clash-verge-config-render/src/script.rs b/crates/clash-verge-config-render/src/script.rs new file mode 100644 index 000000000..46254aad1 --- /dev/null +++ b/crates/clash-verge-config-render/src/script.rs @@ -0,0 +1,81 @@ +use super::{ResultLog, ScriptOutcome, field::use_lowercase}; +use serde_yaml_ng::Mapping; +use tristr::alias::String; + +type ScriptResult = (Mapping, Vec, ResultLog); + +/// Never fails: exceptions are logged and the input config is returned unchanged. +pub(super) async fn use_script + Send>( + script: String, + config: Mapping, + name: String, + execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send, +) -> ScriptResult { + // The template is identity-plus-lowercasing; skip the Boa round-trip. + if script == super::ITEM_SCRIPT { + return (use_lowercase(config), vec![], vec![]); + } + + let json = match serde_json::to_value(&config) { + Ok(mut json) => { + if let Some(map) = json.as_object_mut() { + let mut lowered = serde_json::Map::with_capacity(map.len()); + for (key, value) in std::mem::take(map) { + let mut key = key; + key.make_ascii_lowercase(); + lowered.insert(key, value); + } + *map = lowered; + } + json + } + Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]), + }; + + let (outcome, mut logs) = execute(script, json, name).await; + match outcome { + Ok(result) => { + let result = use_lowercase(result); + // Compared against the config as handed in, not the lowercased copy the script saw. + let changed_keys = result + .iter() + .filter(|(key, value)| config.get(key) != Some(value)) + .filter_map(|(key, _)| { + let mut key: String = key.as_str()?.into(); + key.make_ascii_lowercase(); + Some(key) + }) + .collect(); + (result, changed_keys, logs) + } + Err(reason) => { + logs.push(("exception".into(), reason.into())); + (config, vec![], logs) + } + } +} + +#[cfg(test)] +mod tests { + use std::future::ready; + + use super::{Mapping, use_script}; + + #[tokio::test] + async fn default_template_skips_the_executor() { + let mut called = false; + let mut config = Mapping::new(); + config.insert("MiXeD".into(), true.into()); + let (config, changed_keys, logs) = + use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| { + called = true; + ready((Ok(Mapping::new()), vec![])) + }) + .await; + + assert!(!called); + assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true)); + assert!(changed_keys.is_empty()); + assert!(logs.is_empty()); + } +} diff --git a/src-tauri/src/enhance/seq.rs b/crates/clash-verge-config-render/src/seq.rs similarity index 65% rename from src-tauri/src/enhance/seq.rs rename to crates/clash-verge-config-render/src/seq.rs index 11e083151..7e4dd4e38 100644 --- a/src-tauri/src/enhance/seq.rs +++ b/crates/clash-verge-config-render/src/seq.rs @@ -1,6 +1,7 @@ use serde::{Deserialize, Serialize}; use serde_yaml_ng::{Mapping, Sequence, Value}; use std::collections::HashSet; +use tristr::TriStr; #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct SeqMap { @@ -9,14 +10,12 @@ pub struct SeqMap { pub delete: Vec, } -fn collect_proxy_names(seq: &Sequence) -> Vec { - seq.iter() - .filter_map(|item| match item { - Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(str::to_owned), - Value::String(name) => Some(name.to_owned()), - _ => None, - }) - .collect() +fn proxy_name(proxy: &Value) -> Option<&str> { + match proxy { + Value::Mapping(proxy) => proxy.get("name").and_then(Value::as_str), + Value::String(name) => Some(name), + _ => None, + } } fn is_selector_group(group_map: &Mapping) -> bool { @@ -34,41 +33,34 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping { } = seq; let added_proxy_names = if field == "proxies" { - let mut names = collect_proxy_names(&prepend); - names.extend(collect_proxy_names(&append)); - let mut seen = HashSet::new(); - names - .into_iter() - .filter(|name| seen.insert(name.clone())) - .collect::>() + prepend + .iter() + .chain(&append) + .filter_map(proxy_name) + .map(TriStr::from) + .collect::>() } else { Vec::new() }; - let mut updated_items = Sequence::new(); - updated_items.extend(prepend); - - if let Some(Value::Sequence(existing_items)) = config.remove(field) { - // Filter out deleted items - let kept_items: Sequence = existing_items - .into_iter() - .filter(|item| { - if let Value::String(s) = item { - !delete.contains(s) - } else if let Value::Mapping(m) = item { - if let Some(Value::String(name)) = m.get("name") { - !delete.contains(name) - } else { - true - } - } else { - true - } - }) - .collect(); - updated_items.extend(kept_items); + let mut updated_items = match config.remove(field) { + Some(Value::Sequence(items)) => items, + _ => Sequence::new(), + }; + if !delete.is_empty() { + updated_items.retain(|item| { + let name = match item { + Value::String(name) => Some(name), + Value::Mapping(mapping) => match mapping.get("name") { + Some(Value::String(name)) => Some(name), + _ => None, + }, + _ => None, + }; + name.is_none_or(|name| !delete.contains(name)) + }); } - + updated_items.splice(..0, prepend); updated_items.extend(append); config.insert(Value::String(field.into()), Value::Sequence(updated_items)); @@ -80,66 +72,57 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping { return config; }; - let Value::Sequence(proxy_groups) = proxy_groups_value else { + let Value::Sequence(mut proxy_groups) = proxy_groups_value else { config.insert(Value::String("proxy-groups".into()), proxy_groups_value); return config; }; - let mut updated_groups = Sequence::new(); let mut appended_to_selector = false; - for group in proxy_groups { - if let Value::Mapping(mut group_map) = group { - let mut group_proxies = match group_map.remove("proxies") { - Some(Value::Sequence(proxies)) => Some( - proxies - .into_iter() - .filter(|p| { - if let Value::String(name) = p { - !delete.contains(name) - } else { - true - } - }) - .collect::(), - ), - Some(value) => { - group_map.insert(Value::String("proxies".into()), value); - None + for group in &mut proxy_groups { + let Value::Mapping(group_map) = group else { + continue; + }; + let mut group_proxies = match group_map.remove("proxies") { + Some(Value::Sequence(mut proxies)) => { + if !delete.is_empty() { + proxies.retain(|member| !matches!(member, Value::String(name) if delete.contains(name))); } - None => None, - }; - - if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(&group_map) { - let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new); - let mut merged_proxies = Sequence::new(); - let mut seen_proxy_names = HashSet::new(); - for name in &added_proxy_names { - if seen_proxy_names.insert(name.clone()) { - merged_proxies.push(Value::String(name.clone())); - } - } - for value in base_group_proxies { - if let Value::String(name) = &value - && !seen_proxy_names.insert(name.to_owned()) - { - continue; - } - - merged_proxies.push(value); - } - group_proxies = Some(merged_proxies); - appended_to_selector = true; + Some(proxies) } - - if let Some(group_proxies) = group_proxies { - group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies)); + Some(value) => { + group_map.insert(Value::String("proxies".into()), value); + None } - updated_groups.push(Value::Mapping(group_map)); - } else { - updated_groups.push(group); + None => None, + }; + + if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(group_map) { + let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new); + let mut merged_proxies = Sequence::new(); + let mut seen_proxy_names = HashSet::new(); + for name in &added_proxy_names { + if seen_proxy_names.insert(name.clone()) { + merged_proxies.push(Value::String(name.as_str().to_owned())); + } + } + for value in base_group_proxies { + if let Value::String(name) = &value + && !seen_proxy_names.insert(TriStr::from(name.as_str())) + { + continue; + } + + merged_proxies.push(value); + } + group_proxies = Some(merged_proxies); + appended_to_selector = true; + } + + if let Some(group_proxies) = group_proxies { + group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies)); } } - config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups)); + config.insert(Value::String("proxy-groups".into()), Value::Sequence(proxy_groups)); config } diff --git a/src-tauri/src/enhance/tun.rs b/crates/clash-verge-config-render/src/tun.rs similarity index 75% rename from src-tauri/src/enhance/tun.rs rename to crates/clash-verge-config-render/src/tun.rs index 61362c9b5..2deb05ebb 100644 --- a/src-tauri/src/enhance/tun.rs +++ b/crates/clash-verge-config-render/src/tun.rs @@ -32,9 +32,7 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping { revise!(dns_val, "fake-ip-range", "198.18.0.1/16"); } - if ipv6_val && !dns_val.contains_key(Value::from("fake-ip-range6")) { - revise!(dns_val, "fake-ip-range6", "2001:2::0/64"); - } + super::ensure_fake_ip_range6(&mut dns_val); } revise!(config, "dns", dns_val); @@ -45,3 +43,20 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping { config } + +pub(super) const DEFAULT_MTU: u16 = 1500; + +/// Saved dialog fields; `enable` belongs to the verge switch. +pub(super) const GUI_KEYS: &[&str] = &[ + "stack", + "device", + "auto-route", + "route-exclude-address", + #[cfg(target_os = "linux")] + "auto-redirect", + "auto-detect-interface", + "dns-hijack", + "dns-mode", + "strict-route", + "mtu", +]; diff --git a/crates/clash-verge-profile-script/Cargo.toml b/crates/clash-verge-profile-script/Cargo.toml new file mode 100644 index 000000000..6003b3c8d --- /dev/null +++ b/crates/clash-verge-profile-script/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "clash-verge-profile-script" +version = "0.1.0" +edition = "2024" + +[dependencies] +boa_engine = { workspace = true } +clash-verge-logging = { workspace = true } +log = { workspace = true } +serde_json = { workspace = true } +serde_yaml_ng = { workspace = true } +tokio = { workspace = true } +tristr = { workspace = true } + +[lints] +workspace = true diff --git a/src-tauri/src/enhance/script.rs b/crates/clash-verge-profile-script/src/lib.rs similarity index 54% rename from src-tauri/src/enhance/script.rs rename to crates/clash-verge-profile-script/src/lib.rs index 4cc366491..22e85942b 100644 --- a/src-tauri/src/enhance/script.rs +++ b/crates/clash-verge-profile-script/src/lib.rs @@ -1,79 +1,64 @@ -use crate::{process::AsyncHandler, utils::tmpl}; - -use super::field::use_lowercase; -use anyhow::Result; use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute}; use clash_verge_logging::{Type, logging}; -use parking_lot::Mutex; use serde_yaml_ng::Mapping; -use std::sync::Arc; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; use tristr::alias::String; const MAX_OUTPUTS: usize = 1000; const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB +const MAX_PROFILE_NAME_BYTES: usize = 1024; const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB const MAX_LOOP_ITERATIONS: u64 = 10_000_000; const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); -type ScriptResult = (Mapping, Vec, Vec<(String, String)>); -type EvalOutcome = (Result, Vec<(String, String)>); +/// Script logs are retained when evaluation or result conversion fails. +pub type ScriptLogs = Vec<(String, String)>; -/// Never fails: exceptions are logged and the input config is returned unchanged. -pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult { - // The template is identity-plus-lowercasing; skip the Boa round-trip. - if script == tmpl::ITEM_SCRIPT { - return (use_lowercase(config), vec![], vec![]); +type EvalOutcome = (Result, ScriptLogs); + +#[derive(Debug, PartialEq, Eq)] +pub enum MainDeclaration { + Present, + Missing, +} + +/// Evaluates the source and checks that the entry point is callable. +pub fn validate(source: &str) -> Result { + let mut context = Context::default(); + let _ = context.eval(Source::from_bytes( + "var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){},warn(...data){},table(...data){}});", + )); + context + .eval(Source::from_bytes(source)) + .map_err(|err| err.to_string())?; + let has_main = context + .eval(Source::from_bytes("typeof main === 'function'")) + .map_err(|err| err.to_string())? + .to_boolean(); + Ok(if has_main { + MainDeclaration::Present + } else { + MainDeclaration::Missing + }) +} + +/// Runs one script on the blocking pool. The timeout bounds waiting for its result. +pub async fn execute(script: String, config: serde_json::Value, name: String) -> EvalOutcome { + if json_approx_size(&config) > MAX_JSON_SIZE { + return ( + Err("Configuration size exceeds maximum allowed size".to_owned()), + vec![], + ); } - - let json = match serde_json::to_value(&config) { - Ok(mut json) => { - if let Some(map) = json.as_object_mut() { - let mut lowered = serde_json::Map::with_capacity(map.len()); - for (key, value) in std::mem::take(map) { - let mut key = key; - key.make_ascii_lowercase(); - lowered.insert(key, value); - } - *map = lowered; - } - if json_approx_size(&json) <= MAX_JSON_SIZE { - json - } else { - let message = "Configuration size exceeds maximum allowed size"; - return (config, vec![], vec![("exception".into(), message.into())]); - } - } - Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]), - }; - - let evaluated = AsyncHandler::spawn_blocking(move || eval_script(&script, &json, &name)); - let (outcome, mut logs) = match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await { + let evaluated = tokio::task::spawn_blocking(move || eval_script(&script, &config, &name)); + match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await { Ok(Ok(evaluated)) => evaluated, Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]), - Err(_elapsed) => ( + Err(_) => ( Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")), vec![], ), - }; - - match outcome { - Ok(result) => { - // Compared against the config as handed in, not the lowercased copy the script saw. - let changed_keys = result - .iter() - .filter(|(key, value)| config.get(key) != Some(value)) - .filter_map(|(key, _)| { - let mut key: String = key.as_str()?.into(); - key.make_ascii_lowercase(); - Some(key) - }) - .collect(); - (result, changed_keys, logs) - } - Err(reason) => { - logs.push(("exception".into(), reason.into())); - (config, vec![], logs) - } } } @@ -85,13 +70,11 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> .runtime_limits_mut() .set_loop_iteration_limit(MAX_LOOP_ITERATIONS); - let outputs = Arc::new(Mutex::new(vec![])); - let total_size = Arc::new(Mutex::new(0usize)); - - let outputs_clone = Arc::clone(&outputs); - let total_size_clone = Arc::clone(&total_size); - - let bail = |reason: std::string::String| (Err(reason), outputs.lock().to_vec()); + let logs = Rc::new(RefCell::new(Vec::new())); + let console_logs = Rc::clone(&logs); + let logged_bytes = Cell::new(0); + let take_logs = || logs.take(); + let bail = |reason: std::string::String| (Err(reason), take_logs()); let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe { NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| { @@ -111,23 +94,21 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into()) })?; - // 检查输出限制 - if outputs_clone.lock().len() >= MAX_OUTPUTS { + let mut entries = console_logs.borrow_mut(); + if entries.len() >= MAX_OUTPUTS { return Err(boa_engine::JsError::from_opaque( JsString::from("Maximum number of log outputs exceeded").into(), )); } - let mut size = total_size_clone.lock(); - let new_size = *size + level.len() + data.len(); + let new_size = logged_bytes.get() + level.len() + data.len(); if new_size > MAX_OUTPUT_SIZE { return Err(boa_engine::JsError::from_opaque( JsString::from("Maximum output size exceeded").into(), )); } - *size = new_size; - drop(size); - outputs_clone.lock().push((level.into(), data.into())); + logged_bytes.set(new_size); + entries.push((level.into(), data.into())); Ok(JsValue::undefined()) }) }); @@ -151,16 +132,14 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> return bail(format!("failed to bind config for script: {err}")); } - // 仅处理 name 参数中的特殊字符 - let safe_name = escape_js_string_for_single_quote(name); - if safe_name.len() > 1024 { + let Some(escaped_profile_name) = escape_profile_name(name) else { return bail("Name parameter too long".to_owned()); - } + }; let code = format!( r"try{{ {script}; - main(globalThis.__verge_config__,'{safe_name}') + main(globalThis.__verge_config__,'{escaped_profile_name}') }} catch(err) {{ `__error_flag__ ${{err.toString()}}` }}" @@ -214,7 +193,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> } match serde_json::from_value::(result) { - Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()), + Ok(config) => (Ok(config), take_logs()), Err(err) => { logging!( error, @@ -235,21 +214,92 @@ fn json_approx_size(value: &serde_json::Value) -> usize { .map(|(key, value)| key.len() + 4 + json_approx_size(value)) .sum(), serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(), - serde_json::Value::Number(n) => n.to_string().len(), + serde_json::Value::Number(n) => { + if let Some(n) = n.as_u64() { + n.checked_ilog10().unwrap_or(0) as usize + 1 + } else if let Some(n) = n.as_i64() { + n.unsigned_abs().checked_ilog10().unwrap_or(0) as usize + 2 + } else { + n.to_string().len() + } + } serde_json::Value::Bool(_) | serde_json::Value::Null => 4, } } -// 安全地转义字符串 -fn escape_js_string_for_single_quote(s: &str) -> String { - // 限制处理的字符串长度 - if s.len() > 10240 { - return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into(); +fn escape_profile_name(name: &str) -> Option { + if name.len() > MAX_PROFILE_NAME_BYTES { + return None; + } + let escaped = name + .replace('\\', "\\\\") + .replace('\'', "\\'") + .replace('\n', "\\n") + .replace('\r', "\\r"); + (escaped.len() <= MAX_PROFILE_NAME_BYTES).then(|| escaped.into()) +} + +#[cfg(test)] +mod tests { + use super::{MainDeclaration, eval_script, validate}; + + #[test] + fn profile_name_limit_counts_escaped_bytes() { + assert!(super::escape_profile_name(&"订阅".repeat(171)).is_none()); + assert!(super::escape_profile_name(&"'".repeat(512)).is_some()); + assert!(super::escape_profile_name(&"'".repeat(513)).is_none()); } - s.replace('\\', "\\\\") - .replace('\'', "\\'") - .replace('\n', "\\n") // 添加换行符转义 - .replace('\r', "\\r") // 添加回车转义 - .into() + #[test] + fn numeric_size_matches_the_rendered_number() { + for number in [ + 0.into(), + 10.into(), + (-10).into(), + i64::MIN.into(), + u64::MAX.into(), + serde_json::json!(1.25), + ] { + assert_eq!(super::json_approx_size(&number), number.to_string().len()); + } + } + + #[test] + fn console_entries_survive_a_script_error() { + let (result, logs) = eval_script( + "function main() { console.log(1); console.warn(2); throw Error(); }", + &serde_json::json!({}), + &"profile".into(), + ); + assert!(result.is_err()); + assert_eq!(logs, [("log".into(), "1".into()), ("warn".into(), "2".into())]); + } + + #[test] + fn validation_checks_the_evaluated_main_binding() { + assert_eq!( + validate("const main = config => config;"), + Ok(MainDeclaration::Present) + ); + assert_eq!(validate("// function main goes here"), Ok(MainDeclaration::Missing)); + assert_eq!(validate("const main = 42;"), Ok(MainDeclaration::Missing)); + } + + #[test] + fn validation_supports_console_methods_at_top_level() { + assert_eq!( + validate("console.warn('setup'); console.table([1]); function main(config) { return config; }"), + Ok(MainDeclaration::Present) + ); + } + + #[test] + fn validation_distinguishes_missing_main_from_evaluation_failure() { + assert_eq!( + validate("console.log('setup'); const main = config => config;"), + Ok(MainDeclaration::Present) + ); + assert_eq!(validate("console.log('setup');"), Ok(MainDeclaration::Missing)); + assert!(validate("throw new Error('setup failed'); function main(config) { return config; }").is_err()); + } } diff --git a/crates/clash-verge-proxy-view/Cargo.toml b/crates/clash-verge-proxy-view/Cargo.toml new file mode 100644 index 000000000..ba8531599 --- /dev/null +++ b/crates/clash-verge-proxy-view/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "clash-verge-proxy-view" +version = "0.1.0" +edition = "2024" + +[dependencies] +serde = { workspace = true, features = ["derive"] } +specta = { workspace = true, features = ["derive"] } +tristr = { workspace = true } + +[lints] +workspace = true diff --git a/src-tauri/src/core/proxy_view.rs b/crates/clash-verge-proxy-view/src/lib.rs similarity index 74% rename from src-tauri/src/core/proxy_view.rs rename to crates/clash-verge-proxy-view/src/lib.rs index f5dd8d092..0ba52d2b4 100644 --- a/src-tauri/src/core/proxy_view.rs +++ b/crates/clash-verge-proxy-view/src/lib.rs @@ -1,15 +1,40 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use serde::Serialize; -use tauri_plugin_mihomo::models::{ - DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType, -}; +use tristr::alias::String; pub struct ProxyViewInput { pub runtime_group_order: Vec, pub group_scopes: BTreeMap, - pub proxies: Proxies, - pub providers: Option, + pub proxies: HashMap, + pub providers: Option>, +} + +pub struct ProxySnapshot { + pub name: String, + pub proxy_type: String, + pub all: Option>, + pub fixed: Option, + pub hidden: Option, + pub icon: Option, + pub now: Option, + pub test_url: Option, + pub id: Option, + pub history: Vec, + pub capabilities: ProxyCapabilities, +} + +pub struct ProviderSnapshot { + pub vehicle_type: ProxyProviderVehicleType, + pub proxies: Vec, + pub updated_at: Option, + pub subscription_info: Option, +} + +#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] +pub struct DelayHistory { + pub time: String, + pub delay: u16, } /// The providers a group draws from (Mihomo order) and its `exclude-type` entries. @@ -18,8 +43,6 @@ pub struct GroupScope { pub exclude_types: Vec, } -pub struct ProxyViewBuilder; - #[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[serde(rename_all = "camelCase")] pub struct ProxyViewV1 { @@ -62,8 +85,7 @@ pub struct ProxyCapabilities { pub struct ProxyGroupView { pub name: String, #[serde(rename = "type")] - #[specta(type = String)] - pub proxy_type: ProxyType, + pub proxy_type: String, #[serde(skip_serializing_if = "Option::is_none")] pub now: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -74,7 +96,6 @@ pub struct ProxyGroupView { pub icon: Option, #[serde(skip_serializing_if = "Option::is_none")] pub test_url: Option, - #[specta(type = Vec)] pub history: Vec, #[serde(flatten)] pub capabilities: ProxyCapabilities, @@ -87,9 +108,7 @@ pub struct ProxyNodeView { pub record_id: String, pub name: String, #[serde(rename = "type")] - #[specta(type = String)] - pub proxy_type: ProxyType, - #[specta(type = Vec)] + pub proxy_type: String, pub history: Vec, #[serde(skip_serializing_if = "Option::is_none")] pub id: Option, @@ -190,8 +209,8 @@ struct MemberResolver<'a> { impl<'a> MemberResolver<'a> { /// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`. - fn scoped_candidates(&self, group: &str, name: &str) -> Vec<&'a String> { - let (Some(scope), Some(candidates)) = (self.group_scopes.get(group), self.provider_candidates.get(name)) else { + fn scoped_candidates(&self, group: &str, candidates: &'a [(String, String)]) -> Vec<&'a String> { + let Some(scope) = self.group_scopes.get(group) else { return Vec::new(); }; scope @@ -200,17 +219,23 @@ impl<'a> MemberResolver<'a> { .flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider)) .map(|(_, record_id)| record_id) .filter(|record_id| { - !self.records.get(*record_id).is_some_and(|node| { - scope - .exclude_types - .iter() - .any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str())) - }) + scope.exclude_types.is_empty() + || !self.records.get(*record_id).is_some_and(|node| { + scope + .exclude_types + .iter() + .any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str())) + }) }) .collect() } - fn resolve(&self, name: String, scoped: Option<&String>) -> ProxyMemberRef { + fn resolve( + &self, + group: &str, + name: String, + seen: &mut BTreeMap)>, + ) -> ProxyMemberRef { if self.group_names.contains(&name) { ProxyMemberRef::Group { name } } else if let Some(record_id) = self.core_node_ids.get(&name) { @@ -225,16 +250,30 @@ impl<'a> MemberResolver<'a> { } } else { let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice); - match (scoped, candidates) { - (Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node { + let record_id = match candidates { + [(_, record_id)] => Some(record_id), + [] => { + return ProxyMemberRef::Unresolved { + name, + reason: ProxyMemberUnresolvedReason::Missing, + }; + } + _ => { + // The n-th occurrence in Mihomo's member list selects the n-th scoped candidate. + let (occurrence, scoped) = seen + .entry(name.clone()) + .or_insert_with(|| (0, self.scoped_candidates(group, candidates))); + let record_id = scoped.get(*occurrence).or_else(|| scoped.first()).copied(); + *occurrence += 1; + record_id + } + }; + match record_id { + Some(record_id) => ProxyMemberRef::Node { name, record_id: record_id.clone(), }, - (None, []) => ProxyMemberRef::Unresolved { - name, - reason: ProxyMemberUnresolvedReason::Missing, - }, - (None, _) => ProxyMemberRef::Unresolved { + None => ProxyMemberRef::Unresolved { name, reason: ProxyMemberUnresolvedReason::Ambiguous, }, @@ -243,14 +282,14 @@ impl<'a> MemberResolver<'a> { } } -impl ProxyViewBuilder { - pub fn build(input: ProxyViewInput) -> ProxyViewV1 { - let ProxyViewInput { +impl ProxyViewInput { + pub fn into_view(self) -> ProxyViewV1 { + let Self { runtime_group_order, group_scopes, proxies, providers, - } = input; + } = self; let provider_state = if providers.is_some() { ProxyViewProviderState::Ready } else { @@ -270,7 +309,7 @@ impl ProxyViewBuilder { let global = core_groups .remove("GLOBAL") - .map(|proxy| build_group("GLOBAL".to_owned(), proxy, &resolver)); + .map(|proxy| build_group("GLOBAL".into(), proxy, &resolver)); let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver); let direct = core_node_ids.get("DIRECT").cloned(); let standalone = build_standalone(&core_node_ids); @@ -289,11 +328,13 @@ impl ProxyViewBuilder { } } -fn partition_core(proxies: Proxies) -> (BTreeMap, BTreeMap) { +fn partition_core( + proxies: HashMap, +) -> (BTreeMap, BTreeMap) { let mut groups = BTreeMap::new(); let mut nodes = BTreeMap::new(); - for (name, proxy) in proxies.proxies { + for (name, proxy) in proxies { if proxy.all.is_some() { groups.insert(name, proxy); } else { @@ -305,13 +346,13 @@ fn partition_core(proxies: Proxies) -> (BTreeMap, BTreeMap, + core_nodes: BTreeMap, ) -> (BTreeMap, BTreeMap) { let mut records = BTreeMap::new(); let mut ids = BTreeMap::new(); for (index, (name, proxy)) in core_nodes.into_iter().enumerate() { - let record_id = format!("c:{index}"); + let record_id: String = format!("c:{index}").into(); ids.insert(name.clone(), record_id.clone()); records.insert( record_id.clone(), @@ -328,32 +369,24 @@ fn build_core_records( } fn build_provider_records( - providers: Option, + providers: Option>, records: &mut BTreeMap, ) -> (Vec, ProviderCandidates) { - let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::>()); let mut views = Vec::new(); let mut candidates = BTreeMap::new(); - for (provider_name, provider) in providers { - let ProxyProvider { + for (provider_name, provider) in providers.into_iter().flatten() { + let ProviderSnapshot { vehicle_type, proxies, updated_at, subscription_info, - .. } = provider; - let vehicle_type = match vehicle_type { - VehicleType::HTTP => ProxyProviderVehicleType::Http, - VehicleType::File => ProxyProviderVehicleType::File, - VehicleType::Inline => ProxyProviderVehicleType::Inline, - _ => continue, - }; let provider_index = views.len(); let mut proxy_record_ids = Vec::new(); for (member_index, proxy) in proxies.into_iter().enumerate() { - let record_id = format!("p:{provider_index}:{member_index}"); + let record_id: String = format!("p:{provider_index}:{member_index}").into(); let proxy_name = proxy.name.clone(); let node_name = proxy.name.clone(); candidates @@ -379,12 +412,7 @@ fn build_provider_records( name: provider_name, vehicle_type, updated_at, - subscription_info: subscription_info.map(|subscription_info| ProxySubscriptionInfo { - upload: subscription_info.upload, - download: subscription_info.download, - total: subscription_info.total, - expire: subscription_info.expire, - }), + subscription_info, proxy_record_ids, }); } @@ -392,8 +420,8 @@ fn build_provider_records( (views, candidates) } -fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView { - let Proxy { +fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView { + let ProxySnapshot { all, fixed, hidden, @@ -401,27 +429,15 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro now, test_url, history, - udp, - xudp, - tfo, - mptcp, - smux, + capabilities, proxy_type, .. } = proxy; - // The n-th occurrence of a name in `all` is the n-th scoped candidate. - let mut seen = BTreeMap::)>::new(); + let mut seen = BTreeMap::new(); let members = all .unwrap_or_default() .into_iter() - .map(|member| { - let (occurrence, scoped) = seen - .entry(member.clone()) - .or_insert_with(|| (0, resolver.scoped_candidates(&name, &member))); - let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied(); - *occurrence += 1; - resolver.resolve(member, picked) - }) + .map(|member| resolver.resolve(&name, member, &mut seen)) .collect(); ProxyGroupView { @@ -433,29 +449,19 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro icon, test_url, history, - capabilities: ProxyCapabilities { - udp, - xudp, - tfo, - mptcp, - smux, - }, + capabilities, members, } } -fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView { - let Proxy { +fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView { + let ProxySnapshot { id, hidden, icon, test_url, history, - udp, - xudp, - tfo, - mptcp, - smux, + capabilities, proxy_type, .. } = proxy; @@ -469,19 +475,13 @@ fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSo hidden, icon, test_url, - capabilities: ProxyCapabilities { - udp, - xudp, - tfo, - mptcp, - smux, - }, + capabilities, source, } } fn build_ordered_groups( - mut core_groups: BTreeMap, + mut core_groups: BTreeMap, runtime_group_order: Vec, resolver: &MemberResolver<'_>, ) -> (Vec, ProxyViewOrderSource) { diff --git a/crates/clash-verge-runtime-bundle/Cargo.toml b/crates/clash-verge-runtime-bundle/Cargo.toml new file mode 100644 index 000000000..603bb8de0 --- /dev/null +++ b/crates/clash-verge-runtime-bundle/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "clash-verge-runtime-bundle" +version = "0.1.0" +edition = "2024" + +[dependencies] +thiserror = { workspace = true } +clash-verge-logging = { workspace = true } +hex = "0.4.3" +log = { workspace = true } +serde_yaml_ng = { workspace = true } +sha2 = { workspace = true } +tristr = { workspace = true } +tokio = { workspace = true, features = ["fs"] } + +[lints] +workspace = true diff --git a/crates/clash-verge-runtime-bundle/src/error.rs b/crates/clash-verge-runtime-bundle/src/error.rs new file mode 100644 index 000000000..55c672d1f --- /dev/null +++ b/crates/clash-verge-runtime-bundle/src/error.rs @@ -0,0 +1,43 @@ +use std::path::PathBuf; + +#[derive(Debug, thiserror::Error)] +pub enum RuntimeBundleError { + #[error(transparent)] + Io(#[from] std::io::Error), + #[error("failed to read runtime config {path:?}")] + ReadConfig { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("failed to parse runtime config {path:?}")] + ParseConfig { + path: PathBuf, + #[source] + source: serde_yaml_ng::Error, + }, + #[error("runtime config has no parent directory")] + MissingConfigDirectory, + #[error("runtime provider destination {0:?} is declared for two different sources")] + DifferentSources(String), + #[error("runtime provider destination {0:?} is claimed more than once")] + DuplicateDestination(String), + #[error("local runtime provider is unavailable: {path:?}")] + LocalProviderUnavailable { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("local runtime provider is outside the config root: {0:?}")] + LocalProviderOutsideRoot(PathBuf), + #[error("runtime provider destination traverses outside the runtime")] + DestinationOutsideRuntime, + #[error("runtime provider path has no existing ancestor: {0:?}")] + MissingAncestor(PathBuf), + #[error("runtime provider path is outside the config root: {0:?}")] + ProviderOutsideRoot(PathBuf), + #[error("local runtime provider destination traverses outside the runtime")] + LocalDestinationOutsideRuntime, + #[error("local runtime provider destination is empty")] + EmptyDestination, +} diff --git a/src-tauri/src/core/runtime_bundle.rs b/crates/clash-verge-runtime-bundle/src/lib.rs similarity index 67% rename from src-tauri/src/core/runtime_bundle.rs rename to crates/clash-verge-runtime-bundle/src/lib.rs index e23b44c11..16aee2f8d 100644 --- a/src-tauri/src/core/runtime_bundle.rs +++ b/crates/clash-verge-runtime-bundle/src/lib.rs @@ -1,12 +1,17 @@ -use anyhow::{Context as _, Result, bail}; +mod error; + +pub use error::RuntimeBundleError; + use clash_verge_logging::{Type, logging}; -use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle}; use serde_yaml_ng::{Mapping, Value}; use sha2::{Digest as _, Sha256}; use std::collections::{BTreeMap, HashSet}; use std::path::{Component, Path, PathBuf, Prefix}; +use tristr::TriStr; -pub(crate) const GEO_ASSETS: &[&str] = &[ +const PROVIDER_SECTIONS: [&str; 2] = ["proxy-providers", "rule-providers"]; + +pub const GEO_ASSETS: &[&str] = &[ "Country.mmdb", "ASN.mmdb", "geoip.dat", @@ -17,42 +22,62 @@ pub(crate) const GEO_ASSETS: &[&str] = &[ /// Provider identity used by the runtime config and core API. #[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct RemoteProviderRef { +pub struct RemoteProviderRef { pub section: &'static str, pub name: String, - pub provider: RemoteProvider, + pub destination: TriStr, + pub url: String, } -struct RuntimeParts { - config: Value, - assets: Vec, - remote_providers: Vec, +pub struct RuntimeAsset { + pub source: String, + pub destination: TriStr, } -pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result { +pub struct RuntimeBundlePlan { + pub config: Value, + pub assets: Vec, + pub remote_providers: Vec, +} + +type Result = std::result::Result; + +pub async fn collect_runtime_bundle(config_file: &Path) -> Result { let yaml = tokio::fs::read_to_string(config_file) .await - .with_context(|| format!("failed to read runtime config {config_file:?}"))?; - let config: Value = - serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?; - let config_root = config_file - .parent() - .ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?; - let parts = collect_runtime_parts(config, config_root)?; - Ok(RuntimeBundle { - yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?, - assets: parts.assets, - remote_providers: parts - .remote_providers - .into_iter() - .map(|declared| declared.provider) - .collect(), - core_path: core_path.to_string_lossy().into_owned(), - }) + .map_err(|source| RuntimeBundleError::ReadConfig { + path: config_file.to_owned(), + source, + })?; + let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig { + path: config_file.to_owned(), + source, + })?; + let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?; + collect_runtime_parts(config, config_root) } -pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result> { - Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers) +pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result> { + let config_root = std::fs::canonicalize(config_root)?; + let mut destinations = HashSet::new(); + let mut remote_providers = Vec::new(); + for section in PROVIDER_SECTIONS { + let Some(providers) = config.get(section).and_then(Value::as_mapping) else { + continue; + }; + for (name, provider) in providers { + plan_provider( + section, + name, + provider, + &config_root, + &mut destinations, + None, + &mut remote_providers, + )?; + } + } + Ok(remote_providers) } #[derive(Default)] @@ -61,11 +86,11 @@ struct ProviderPathOwners { local: bool, } -pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> { +pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> { let config_root = std::fs::canonicalize(config_root)?; - let mut paths = BTreeMap::::new(); - let mut reserved: HashSet = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect(); - for section in ["proxy-providers", "rule-providers"] { + let mut paths = BTreeMap::::new(); + let mut reserved: HashSet = GEO_ASSETS.iter().copied().map(TriStr::from).collect(); + for section in PROVIDER_SECTIONS { let Some(providers) = config.get(section).and_then(Value::as_mapping) else { continue; }; @@ -84,6 +109,7 @@ pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: let Ok(destination) = destination else { continue; }; + let destination = TriStr::from(destination.as_str()); reserved.insert(destination.clone()); let owners = paths.entry(destination).or_default(); match (is_remote, provider.get("url").and_then(Value::as_str)) { @@ -117,12 +143,12 @@ pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: Ok(()) } -fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet) -> String { +fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet) -> String { let mut digest = Sha256::new(); digest.update(destination.as_bytes()); digest.update([0]); digest.update(url.as_bytes()); - let digest: String = crate::utils::help::hex_encode(&digest.finalize()); + let digest = hex::encode(digest.finalize()); let path = Path::new(destination); let extension = path .extension() @@ -134,7 +160,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha .with_file_name(format!("cvr-{digest}{suffix}{extension}")) .to_string_lossy() .replace('\\', "/"); - if reserved.insert(candidate.clone()) { + if reserved.insert(TriStr::from(candidate.as_str())) { return candidate; } sequence += 1; @@ -142,40 +168,34 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha } } -fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result { +fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result { let config_root = std::fs::canonicalize(config_root)?; let mut assets = Vec::new(); let mut destinations = HashSet::new(); let mut remote_providers = Vec::new(); - collect_provider_assets( - &mut config, - "proxy-providers", - &config_root, - &mut destinations, - &mut assets, - &mut remote_providers, - )?; - collect_provider_assets( - &mut config, - "rule-providers", - &config_root, - &mut destinations, - &mut assets, - &mut remote_providers, - )?; + for section in PROVIDER_SECTIONS { + collect_provider_assets( + &mut config, + section, + &config_root, + &mut destinations, + &mut assets, + &mut remote_providers, + )?; + } collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets); for filename in GEO_ASSETS { let source = config_root.join(filename); - if source.is_file() && destinations.insert((*filename).to_string()) { + if source.is_file() && destinations.insert(TriStr::from(*filename)) { assets.push(RuntimeAsset { source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(), - destination: (*filename).to_string(), + destination: (*filename).into(), }); } } - Ok(RuntimeParts { + Ok(RuntimeBundlePlan { config, assets, remote_providers, @@ -188,7 +208,7 @@ fn collect_provider_assets( config: &mut Value, section: &'static str, config_root: &Path, - destinations: &mut HashSet, + destinations: &mut HashSet, assets: &mut Vec, remote_providers: &mut Vec, ) -> Result<()> { @@ -201,80 +221,105 @@ fn collect_provider_assets( }; for (name, provider) in providers.iter_mut() { - let Some(provider) = provider.as_mapping_mut() else { - continue; - }; - let Some(raw_path) = provider.get("path").and_then(Value::as_str) else { - continue; - }; - // Match mihomo's `type` classification and leave malformed-but-accepted providers untouched. - let is_remote = provider.get("type").and_then(Value::as_str) == Some("http"); - let url = provider.get("url").and_then(Value::as_str).map(str::to_owned); - let destination = match (is_remote, url) { - (true, Some(url)) => { - let destination = provider_destination(config_root, raw_path)?; - // Reserve remote destinations too; copied and downloaded files must not collide. + if let Some(destination) = plan_provider( + section, + name, + provider, + config_root, + destinations, + Some(assets), + remote_providers, + )? && let Some(provider) = provider.as_mapping_mut() + { + provider.insert(Value::String("path".to_owned()), Value::String(destination)); + } + } + Ok(()) +} + +fn plan_provider( + section: &'static str, + name: &Value, + provider: &Value, + config_root: &Path, + destinations: &mut HashSet, + assets: Option<&mut Vec>, + remote_providers: &mut Vec, +) -> Result> { + let Some(raw_path) = provider + .as_mapping() + .and_then(|provider| provider.get("path")) + .and_then(Value::as_str) + else { + return Ok(None); + }; + // Match mihomo's `type` classification and leave malformed-but-accepted providers untouched. + let is_remote = provider.get("type").and_then(Value::as_str) == Some("http"); + let url = provider.get("url").and_then(Value::as_str); + let destination = match (is_remote, url) { + (true, Some(url)) => { + let destination = provider_destination(config_root, raw_path)?; + // Reserve remote destinations too; copied and downloaded files must not collide. + let reserved = TriStr::from(destination.as_str()); + if destinations.insert(reserved.clone()) { + remote_providers.push(RemoteProviderRef { + section, + name: name.as_str().unwrap_or_default().to_owned(), + destination: reserved, + url: url.to_owned(), + }); + } else { match remote_providers .iter() - .find(|declared| declared.provider.destination == destination) + .find(|declared| declared.destination == destination) { - Some(declared) if declared.provider.url == url => {} - Some(_) => { - bail!("runtime provider destination {destination:?} is declared for two different sources") - } - None => { - if !destinations.insert(destination.clone()) { - bail!("runtime provider destination {destination:?} is claimed more than once"); - } - remote_providers.push(RemoteProviderRef { - section, - name: name.as_str().unwrap_or_default().to_owned(), - provider: RemoteProvider { - destination: destination.clone(), - url, - }, - }); - } + Some(declared) if declared.url == url => {} + Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)), + None => return Err(RuntimeBundleError::DuplicateDestination(destination)), } - destination } - (true, None) => { + destination + } + (true, None) => { + logging!( + warn, + Type::Config, + "remote provider {name:?} declares no url; leaving its path to the core" + ); + return Ok(None); + } + (false, _) => { + let Ok(source) = local_provider_source(config_root, raw_path) else { logging!( warn, Type::Config, - "remote provider {name:?} declares no url; leaving its path to the core" + "local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core" ); - continue; - } - (false, _) => { - let Ok(source) = local_provider_source(config_root, raw_path) else { - logging!( - warn, - Type::Config, - "local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core" - ); - continue; - }; - let destination = destination_below_root(config_root, &source)?; - if destinations.insert(destination.clone()) { + return Ok(None); + }; + let destination = destination_below_root(config_root, &source)?; + let reserved = TriStr::from(destination.as_str()); + if destinations.insert(reserved.clone()) { + if let Some(assets) = assets { assets.push(RuntimeAsset { source: source.to_string_lossy().into_owned(), - destination: destination.clone(), + destination: reserved, }); } - destination + } else if remote_providers.iter().any(|provider| provider.destination == reserved) { + return Err(RuntimeBundleError::DuplicateDestination(destination)); } - }; - provider.insert(Value::String("path".to_owned()), Value::String(destination)); - } - Ok(()) + destination + } + }; + Ok(Some(destination)) } /// Stages file-based ssh keys, which mihomo resolves against the core home directory. fn collect_ssh_private_keys( config: &mut Value, config_root: &Path, - destinations: &mut HashSet, + destinations: &mut HashSet, assets: &mut Vec, ) { let Some(config) = config.as_mapping_mut() else { @@ -325,7 +370,7 @@ fn collect_ssh_private_keys( let destination = allocate_provider_destination("ssh-private-key", &source, destinations); assets.push(RuntimeAsset { source, - destination: destination.clone(), + destination: TriStr::from(destination.as_str()), }); proxy.insert(Value::String("private-key".to_owned()), Value::String(destination)); } @@ -347,10 +392,13 @@ fn local_provider_source(config_root: &Path, raw_path: &str) -> Result config_root.join(path) }; let canonical_source = - std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?; + std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable { + path: source, + source: error, + })?; canonical_source .strip_prefix(config_root) - .map_err(|_| anyhow::anyhow!("local runtime provider is outside the config root: {canonical_source:?}"))?; + .map_err(|_| RuntimeBundleError::LocalProviderOutsideRoot(canonical_source.clone()))?; Ok(canonical_source) } @@ -360,7 +408,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result { .components() .any(|component| matches!(component, Component::ParentDir)) { - bail!("runtime provider destination traverses outside the runtime"); + return Err(RuntimeBundleError::DestinationOutsideRuntime); } if path.is_absolute() { let normalized = canonicalize_with_missing_tail(path)?; @@ -376,11 +424,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result { while !ancestor.exists() { let name = ancestor .file_name() - .ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?; + .ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?; tail.push(name.to_owned()); ancestor = ancestor .parent() - .ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?; + .ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?; } let mut normalized = std::fs::canonicalize(ancestor)?; for component in tail.iter().rev() { @@ -392,31 +440,60 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result { fn destination_below_root(config_root: &Path, path: &Path) -> Result { let relative = path .strip_prefix(config_root) - .map_err(|_| anyhow::anyhow!("runtime provider path is outside the config root: {path:?}"))?; + .map_err(|_| RuntimeBundleError::ProviderOutsideRoot(path.to_owned()))?; normalized_destination(relative) } fn normalized_destination(relative: &Path) -> Result { - let mut destination = PathBuf::new(); + let mut destination = PathBuf::with_capacity(relative.as_os_str().len()); for component in relative.components() { match component { Component::Normal(component) => destination.push(component), Component::CurDir => {} - _ => bail!("local runtime provider destination traverses outside the runtime"), + _ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime), } } if destination.as_os_str().is_empty() { - bail!("local runtime provider destination is empty"); + return Err(RuntimeBundleError::EmptyDestination); + } + let destination = destination + .into_os_string() + .into_string() + .unwrap_or_else(|path| path.to_string_lossy().into_owned()); + if destination.contains('\\') { + Ok(destination.replace('\\', "/")) + } else { + Ok(destination) } - Ok(destination.to_string_lossy().replace('\\', "/")) } #[cfg(test)] mod tests { use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts}; + #[test] + fn local_and_remote_providers_cannot_claim_the_same_file() -> Result<(), Box> { + let root = std::env::temp_dir().join(format!("clash-verge-mixed-providers-{}", std::process::id())); + std::fs::create_dir_all(&root)?; + std::fs::write(root.join("shared.yaml"), "payload: []")?; + let local = "type: file, path: ./shared.yaml"; + let remote = "type: http, url: 'https://example.com/provider', path: shared.yaml"; + for (proxy, rule) in [(local, remote), (remote, local)] { + let config = serde_yaml_ng::from_str(&format!( + "proxy-providers: {{a: {{{proxy}}}}}\nrule-providers: {{b: {{{rule}}}}}" + ))?; + assert!(matches!( + remote_providers_of(&config, &root), + Err(super::RuntimeBundleError::DuplicateDestination(path)) if path == "shared.yaml" + )); + } + std::fs::remove_dir_all(root)?; + Ok(()) + } + #[tokio::test] - async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> { + async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() + -> std::result::Result<(), Box> { let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id())); std::fs::create_dir_all(&root)?; let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str( @@ -433,7 +510,7 @@ mod tests { resolve_provider_path_conflicts(&mut config, &root)?; let config_file = root.join("config.yaml"); std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?; - let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?; + let bundle = collect_runtime_bundle(&config_file).await?; let paths = &config["rule-providers"]; assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]); resolve_provider_path_conflicts(&mut reordered, &root)?; @@ -448,14 +525,14 @@ mod tests { "resolving an already generated config must be idempotent" ); - assert_eq!(serde_yaml_ng::from_str::(&bundle.yaml)?, config); + assert_eq!(bundle.config.as_mapping(), Some(&config)); let readback = remote_providers_of(&config, &root)?; assert_eq!(bundle.remote_providers.len(), 2); for declared in readback { - assert!(bundle.remote_providers.contains(&declared.provider)); + assert!(bundle.remote_providers.contains(&declared)); assert_eq!( config[declared.section][&declared.name]["path"], - declared.provider.destination + declared.destination.as_str() ); assert_eq!( config[declared.section][&declared.name]["url"], @@ -467,7 +544,8 @@ mod tests { } #[test] - fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> { + fn allocated_provider_paths_do_not_claim_another_declared_path() + -> std::result::Result<(), Box> { let root = std::env::temp_dir(); let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str( "proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n", @@ -489,7 +567,8 @@ mod tests { } #[test] - fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> { + fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() + -> std::result::Result<(), Box> { let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str( "rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n", )?; @@ -500,7 +579,8 @@ mod tests { } #[tokio::test] - async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> { + async fn collects_only_local_providers_and_existing_geo_assets() + -> std::result::Result<(), Box> { let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id())); std::fs::create_dir_all(root.join("providers"))?; std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?; @@ -516,12 +596,10 @@ mod tests { absolute_remote.display() ), )?; - let core = root.join("mihomo"); - std::fs::write(&core, b"core")?; - let bundle = collect_runtime_bundle(&config, &core).await?; + let bundle = collect_runtime_bundle(&config).await?; - let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?; + let bundled_config = &bundle.config; assert_eq!( bundled_config["proxy-providers"]["local"]["path"].as_str(), Some("providers/local.yaml") @@ -530,7 +608,7 @@ mod tests { bundled_config["proxy-providers"]["remote"]["path"].as_str(), Some("providers/remote.yaml") ); - assert!(!bundle.yaml.contains(&root.to_string_lossy().into_owned())); + assert!(!serde_yaml_ng::to_string(bundled_config)?.contains(root.to_string_lossy().as_ref())); assert!( bundle .assets @@ -560,7 +638,8 @@ mod tests { } #[tokio::test] - async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> { + async fn two_names_for_one_remote_file_are_folded_rather_than_refused() + -> std::result::Result<(), Box> { // Identical repeats are one service-side file and are safe to fold. let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); @@ -570,10 +649,8 @@ mod tests { &config, "rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n", )?; - let core = root.join("mihomo"); - std::fs::write(&core, b"core")?; - let bundle = collect_runtime_bundle(&config, &core).await?; + let bundle = collect_runtime_bundle(&config).await?; assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice"); assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml"); @@ -582,7 +659,7 @@ mod tests { } #[tokio::test] - async fn two_sources_for_one_remote_file_are_refused() -> anyhow::Result<()> { + async fn two_sources_for_one_remote_file_are_refused() -> std::result::Result<(), Box> { let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); std::fs::create_dir_all(&root)?; @@ -591,11 +668,9 @@ mod tests { &config, "rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n", )?; - let core = root.join("mihomo"); - std::fs::write(&core, b"core")?; - let Err(error) = collect_runtime_bundle(&config, &core).await else { - anyhow::bail!("two sources cannot own one file"); + let Err(error) = collect_runtime_bundle(&config).await else { + return Err("two sources cannot own one file".into()); }; assert!(error.to_string().contains("two different sources"), "{error}"); @@ -604,7 +679,8 @@ mod tests { } #[tokio::test] - async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> { + async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() + -> std::result::Result<(), Box> { // Odd providers accepted by mihomo must not block the rest of the bundle. let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); @@ -614,10 +690,8 @@ mod tests { &config, "rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n", )?; - let core = root.join("mihomo"); - std::fs::write(&core, b"core")?; - let bundle = collect_runtime_bundle(&config, &core).await?; + let bundle = collect_runtime_bundle(&config).await?; assert_eq!( bundle.remote_providers.len(), @@ -625,9 +699,8 @@ mod tests { "only the provider that could be classified is declared" ); assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml"); - let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?; assert_eq!( - reserialized["rule-providers"]["nourl"]["path"].as_str(), + bundle.config["rule-providers"]["nourl"]["path"].as_str(), Some("./rules/nourl.yaml"), "an unclassifiable provider keeps the path the core was given" ); @@ -636,13 +709,13 @@ mod tests { } #[tokio::test] - async fn rejects_provider_paths_outside_the_config_root() -> anyhow::Result<()> { + async fn rejects_provider_paths_outside_the_config_root() -> std::result::Result<(), Box> { let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id())); std::fs::create_dir_all(&root)?; let config = root.join("config.yaml"); let outside = root .parent() - .ok_or_else(|| anyhow::anyhow!("test root has no parent"))? + .ok_or("test root has no parent")? .join(format!("outside-{}.yaml", std::process::id())); std::fs::write( &config, @@ -651,11 +724,9 @@ mod tests { outside.display() ), )?; - let core = root.join("mihomo"); - std::fs::write(&core, b"core")?; - let Err(error) = collect_runtime_bundle(&config, &core).await else { - anyhow::bail!("outside provider path must be rejected"); + let Err(error) = collect_runtime_bundle(&config).await else { + return Err("outside provider path must be rejected".into()); }; assert!(error.to_string().contains("outside the config root")); diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index da77a5232..cec480c10 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -37,6 +37,10 @@ clash-verge-logging = { workspace = true } clash-verge-i18n = { workspace = true } clash-verge-limiter = { workspace = true } clash-verge-subscription = { workspace = true } +clash-verge-runtime-bundle = { workspace = true } +clash-verge-config-render = { workspace = true } +clash-verge-profile-script = { workspace = true } +clash-verge-proxy-view = { workspace = true } clash-verge-profile = { workspace = true } clash-verge-backup-archive = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true } @@ -64,7 +68,6 @@ dirs = "7.0.0" dunce = "1.0.5" nanoid = "0.5" chrono = { workspace = true } -boa_engine = "0.22.0" http-body-util = "0.1.5" percent-encoding = "2.3.2" reqwest = { workspace = true } @@ -83,7 +86,7 @@ flate2 = "1.1.11" reqwest_dav = "0.4.0" aes-gcm = { version = "0.11.1" } base64 = "0.23.1" -sha2 = "0.11.2" +sha2 = { workspace = true } getrandom = "0.4.3" futures = { workspace = true } gethostname = "1.1.0" @@ -94,9 +97,7 @@ tracing = { workspace = true } tauri-plugin-devtools = { version = "2.2.3", optional = true } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" } async-trait = "0.1.92" -clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [ - "client", -] } +clash_verge_service_ipc = { workspace = true, features = ["client"] } arc-swap = "1.9.5" tokio-rustls = "0.26.6" rustls = { version = "0.23.47", features = ["ring"] } @@ -104,7 +105,7 @@ webpki-roots = "1.0.12" dark-light = "3.0.0" bytes = "1.12.2" tokio-util = { version = "0.7.20", features = ["time"] } -specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] } +specta = { workspace = true, features = ["derive", "function", "serde_json"] } tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] } specta-typescript = "=0.0.13" diff --git a/src-tauri/src/cmd/clash.rs b/src-tauri/src/cmd/clash.rs index 0a9720719..87559217f 100644 --- a/src-tauri/src/cmd/clash.rs +++ b/src-tauri/src/cmd/clash.rs @@ -1,10 +1,10 @@ use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error}; use crate::core::notify::NoticeStatus; use crate::feat; -use crate::utils::{dirs, yaml_emitter}; +use crate::utils::dirs; use crate::{ cmd::StringifyErr as _, - config::{ClashInfo, Config, profiles::save_committed_profiles}, + config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles}, constants, core::{ CoreManager, handle, @@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult { let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG); - let yaml_str = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?; + let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?; fs::write(&dns_path, yaml_str).await.stringify_err()?; logging!(info, Type::Config, "DNS config saved to {dns_path:?}"); diff --git a/src-tauri/src/cmd/proxy.rs b/src-tauri/src/cmd/proxy.rs index 7beef7af6..284739665 100644 --- a/src-tauri/src/cmd/proxy.rs +++ b/src-tauri/src/cmd/proxy.rs @@ -1,14 +1,6 @@ use super::CmdResult; -use crate::{ - cmd::StringifyErr as _, - config::Config, - core::{ - handle::Handle, - proxy_view::{GroupScope, ProxyViewBuilder, ProxyViewInput, ProxyViewV1}, - }, -}; -use serde_yaml_ng::Mapping; -use std::collections::{BTreeMap, HashSet}; +use crate::{cmd::StringifyErr as _, config::Config, core::handle::Handle}; +use clash_verge_proxy_view::ProxyViewV1; /// Merges one selection pair into fresh backend state to avoid stale-list overwrites. #[tauri::command] @@ -27,90 +19,16 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo .stringify_err() } -fn runtime_group_order(config: Option<&Mapping>) -> Vec { - let mut seen = HashSet::new(); - - config - .and_then(|config| config.get("proxy-groups")) - .and_then(|groups| groups.as_sequence()) - .into_iter() - .flatten() - .filter_map(|group| group.get("name")) - .filter_map(|name| name.as_str()) - .filter(|name| !name.is_empty() && *name != "GLOBAL") - .filter(|name| seen.insert(*name)) - .map(str::to_owned) - .collect() -} - -/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted. -fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap { - let Some(config) = config else { - return BTreeMap::new(); - }; - let mut all_providers = config - .get("proxy-providers") - .and_then(|providers| providers.as_mapping()) - .into_iter() - .flat_map(|providers| providers.keys()) - .filter_map(|name| name.as_str()) - .map(str::to_owned) - .collect::>(); - all_providers.sort(); - let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true); - - config - .get("proxy-groups") - .and_then(|groups| groups.as_sequence()) - .into_iter() - .flatten() - .filter_map(|group| group.as_mapping()) - .filter_map(|group| { - let name = group.get("name")?.as_str()?.to_owned(); - let providers = if flag(group, "include-all") || flag(group, "include-all-providers") { - all_providers.clone() - } else { - group - .get("use") - .and_then(|providers| providers.as_sequence()) - .into_iter() - .flatten() - .filter_map(|provider| provider.as_str()) - .map(str::to_owned) - .collect() - }; - let exclude_types = group - .get("exclude-type") - .and_then(|types| types.as_str()) - .filter(|types| !types.is_empty()) - .map_or_default(|types| types.split('|').map(str::to_owned).collect()); - Some(( - name, - GroupScope { - providers, - exclude_types, - }, - )) - }) - .collect() -} - #[tauri::command] #[specta::specta] pub async fn get_proxy_view() -> CmdResult { - let runtime = Config::runtime().await; - let latest_runtime = runtime.latest_arc(); - let runtime_group_order = runtime_group_order(latest_runtime.config.as_ref()); - let group_scopes = runtime_group_scopes(latest_runtime.config.as_ref()); - + let runtime = Config::runtime().await.latest_arc(); let mihomo = Handle::mihomo(); - let (proxies, providers) = tokio::join!(mihomo.get_proxies(), mihomo.get_proxy_providers(),); - let proxies = proxies.stringify_err()?; - - Ok(ProxyViewBuilder::build(ProxyViewInput { - runtime_group_order, - group_scopes, - proxies, - providers: providers.ok(), - })) + crate::feat::proxy_view::load_proxy_view( + runtime.config.as_ref(), + mihomo.get_proxies(), + mihomo.get_proxy_providers(), + ) + .await + .stringify_err() } diff --git a/src-tauri/src/cmd/runtime.rs b/src-tauri/src/cmd/runtime.rs index fa2972b4a..cb4f27524 100644 --- a/src-tauri/src/cmd/runtime.rs +++ b/src-tauri/src/cmd/runtime.rs @@ -1,5 +1,9 @@ use super::CmdResult; -use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter}; +use crate::{ + cmd::StringifyErr as _, + config::{Config, mihomo_yaml}, + core::CoreManager, +}; use anyhow::{Context as _, anyhow}; use std::collections::HashMap; use tristr::alias::String; @@ -24,7 +28,7 @@ pub async fn get_runtime_yaml() -> CmdResult { let config = runtime.config.as_ref(); config .ok_or_else(|| anyhow!("failed to parse config to yaml file")) - .and_then(|config| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml")) + .and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml")) .stringify_err() } @@ -87,7 +91,7 @@ pub async fn get_runtime_proxy_chain_config( config.insert("proxies".into(), proxies_chain); - yaml_emitter::to_mihomo_config_string(&config) + mihomo_yaml::serialize_for_export(&config) .context("YAML generation failed") .stringify_err() } else { diff --git a/src-tauri/src/config/clash.rs b/src-tauri/src/config/clash.rs index 8c8de6798..7bcecd125 100644 --- a/src-tauri/src/config/clash.rs +++ b/src-tauri/src/config/clash.rs @@ -1,3 +1,4 @@ +use super::mihomo_yaml; use crate::constants::{network, tun as tun_const}; use crate::utils::dirs::{path_to_str, sidecar_ipc_path}; use crate::utils::{dirs, help}; @@ -150,7 +151,9 @@ impl IClashTemp { } pub async fn save_config(&self) -> Result<()> { - help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await + let path = dirs::clash_path()?; + let yaml = mihomo_yaml::serialize(&self.0)?; + help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await } pub fn get_mixed_port(&self) -> u16 { diff --git a/src-tauri/src/config/config.rs b/src-tauri/src/config/config.rs index 240d66636..10b6b4cb2 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -1,4 +1,4 @@ -use super::{IClashTemp, IProfiles, IVerge, MixedPort}; +use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml}; use crate::core::notify::NoticeStatus; use crate::{ config::{ @@ -11,7 +11,6 @@ use crate::{ CoreManager, handle::{self, Handle}, listener::MIXED_PORT_KEY, - runtime_bundle::resolve_provider_path_conflicts, tray, validate::CoreConfigValidator, }, @@ -23,6 +22,7 @@ use anyhow::{Result, anyhow}; use backon::{ExponentialBuilder, Retryable as _}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging, logging_error}; +use clash_verge_runtime_bundle::resolve_provider_path_conflicts; use serde_yaml_ng::{Mapping, Value}; use std::{collections::HashSet, path::PathBuf}; use tokio::sync::{Mutex, MutexGuard, OnceCell}; @@ -230,7 +230,7 @@ impl Config { { return Ok(std::sync::Arc::clone(cached)); } - let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?); + let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?); *RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str))); Ok(yaml_str) }) @@ -250,7 +250,7 @@ impl Config { } pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> { - let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).await?; + let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(profiles).await?; resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?; sanitize_tunnels_proxy(&mut config); diff --git a/src-tauri/src/utils/yaml_emitter.rs b/src-tauri/src/config/mihomo_yaml.rs similarity index 59% rename from src-tauri/src/utils/yaml_emitter.rs rename to src-tauri/src/config/mihomo_yaml.rs index 9cf287dc1..18689c6d2 100644 --- a/src-tauri/src/utils/yaml_emitter.rs +++ b/src-tauri/src/config/mihomo_yaml.rs @@ -1,9 +1,10 @@ use serde::Serialize; use serde_yaml_ng::Result; -pub fn to_mihomo_config_string(data: &T) -> Result { - let yaml = serde_yaml_ng::to_string(data)?; - Ok(quote_fake_ip_filter_wildcards(&yaml)) +pub(crate) use serde_yaml_ng::to_string as serialize; + +pub(crate) fn serialize_for_export(data: &T) -> Result { + Ok(quote_fake_ip_filter_wildcards(&serialize(data)?)) } fn quote_fake_ip_filter_wildcards(yaml: &str) -> String { @@ -12,7 +13,7 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String { let mut fake_ip_filter_indent = 0; for line in yaml.lines() { - let indent = leading_spaces(line); + let indent = line.len() - line.trim_start_matches(' ').len(); let trimmed = &line[indent..]; if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") { @@ -22,54 +23,47 @@ fn quote_fake_ip_filter_wildcards(yaml: &str) -> String { if !in_fake_ip_filter && trimmed == "fake-ip-filter:" { in_fake_ip_filter = true; fake_ip_filter_indent = indent; + } + + if in_fake_ip_filter + && indent >= fake_ip_filter_indent + && let Some(item) = trimmed.strip_prefix("- ") + && needs_quotes(item) + { + result.push_str(&line[..indent + 2]); + push_quoted(&mut result, item); + } else { result.push_str(line); - result.push('\n'); - continue; } - - if in_fake_ip_filter && indent >= fake_ip_filter_indent && trimmed.starts_with("- ") { - result.push_str(&line[..indent]); - result.push_str("- "); - result.push_str("e_wildcard_item(&trimmed[2..])); - result.push('\n'); - continue; - } - - result.push_str(line); result.push('\n'); } result } -fn leading_spaces(line: &str) -> usize { - line.len() - line.trim_start_matches(' ').len() +fn needs_quotes(item: &str) -> bool { + !item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.'])) } -fn quote_wildcard_item(item: &str) -> String { - if !item.starts_with('\"') && !item.starts_with('\'') && contains_wildcard(item) { - quote_string(item) - } else { - item.to_string() +fn push_quoted(output: &mut String, item: &str) { + output.push('\''); + for (index, part) in item.split('\'').enumerate() { + if index != 0 { + output.push_str("''"); + } + output.push_str(part); } -} - -fn quote_string(s: &str) -> String { - "\'".to_string() + s.replace('\'', "''").as_str() + "\'" -} - -fn contains_wildcard(value: &str) -> bool { - value.contains('*') || value.starts_with('+') || value.starts_with('.') + output.push('\''); } #[cfg(test)] #[allow(clippy::expect_used)] mod tests { - use super::to_mihomo_config_string; + use super::serialize_for_export; fn roundtrip(input: &str) { let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse"); - let output = to_mihomo_config_string(&value).expect("yaml should serialize"); + let output = serialize_for_export(&value).expect("yaml should serialize"); let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse"); assert_eq!(reparsed, value); @@ -90,7 +84,7 @@ dns: roundtrip(input); let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse"); - let output = to_mihomo_config_string(&value).expect("yaml should serialize"); + let output = serialize_for_export(&value).expect("yaml should serialize"); assert!(output.contains("- '*.lan'")); assert!(output.contains("- '+.market.xiaomi.com'")); diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index 21335bad7..350b1f17d 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -3,6 +3,7 @@ mod clash; mod config; pub(crate) mod dns; mod encrypt; +pub(crate) mod mihomo_yaml; mod mixed_port; mod port; mod prfitem; diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs index 0fbcb9811..a1b8ecf6d 100644 --- a/src-tauri/src/config/runtime.rs +++ b/src-tauri/src/config/runtime.rs @@ -2,10 +2,6 @@ use serde_yaml_ng::{Mapping, Value}; use std::collections::{HashMap, HashSet}; use tristr::alias::String; -use crate::enhance::field::use_keys; - -const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"]; - #[derive(Default, Clone)] pub struct IRuntime { pub config: Option, @@ -17,39 +13,6 @@ pub struct IRuntime { } impl IRuntime { - #[inline] - pub fn patch_config(&mut self, patch: &Mapping) { - let config = if let Some(config) = self.config.as_mut() { - config - } else { - return; - }; - - for key in PATCH_CONFIG_INNER.iter() { - if let Some(value) = patch.get(key) { - config.insert((*key).into(), value.clone()); - } - } - - let Some(patch_tun) = patch.get("tun") else { - return; - }; - - let tun_key = Value::from("tun"); - if !matches!(config.get(&tun_key), Some(Value::Mapping(_))) { - config.insert(tun_key.clone(), Value::Mapping(Mapping::new())); - } - - if let (Some(patch_tun_mapping), Some(Value::Mapping(tun))) = (patch_tun.as_mapping(), config.get_mut(&tun_key)) - { - for key in use_keys(patch_tun_mapping) { - if let Some(value) = patch_tun_mapping.get(key.as_str()) { - tun.insert(Value::from(key.as_str()), value.clone()); - } - } - } - } - /// Rebuilds `dialer-proxy` links from an ordered proxy chain, or removes them for `None`. #[inline] pub fn update_proxy_chain_config(&mut self, proxy_chain_config: Option) { diff --git a/src-tauri/src/constants.rs b/src-tauri/src/constants.rs index b03c13e19..34b28f2f7 100644 --- a/src-tauri/src/constants.rs +++ b/src-tauri/src/constants.rs @@ -64,22 +64,5 @@ pub mod files { pub mod tun { pub const DEFAULT_STACK: &str = "mips"; - pub const DEFAULT_MTU: u16 = 1500; - pub const DNS_HIJACK: &[&str] = &["any:53"]; - - /// Saved dialog fields; `enable` belongs to the verge switch. - pub const GUI_KEYS: &[&str] = &[ - "stack", - "device", - "auto-route", - "route-exclude-address", - #[cfg(target_os = "linux")] - "auto-redirect", - "auto-detect-interface", - "dns-hijack", - "dns-mode", - "strict-route", - "mtu", - ]; } diff --git a/src-tauri/src/core/manager/config.rs b/src-tauri/src/core/manager/config.rs index 7dd783758..a4f991331 100644 --- a/src-tauri/src/core/manager/config.rs +++ b/src-tauri/src/core/manager/config.rs @@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use crate::core::notify::NoticeStatus; use crate::core::service::StageRequest; use crate::{ - config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime}, + config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime}, constants::timing, core::{ handle, @@ -170,7 +170,8 @@ impl CoreManager { } }); - help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?; + let yaml = mihomo_yaml::serialize(clash_config)?; + help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?; handle::Handle::notice(status, message); Ok(()) } diff --git a/src-tauri/src/core/manager/state.rs b/src-tauri/src/core/manager/state.rs index 538212ca5..ca9e6e6f1 100644 --- a/src-tauri/src/core/manager/state.rs +++ b/src-tauri/src/core/manager/state.rs @@ -35,6 +35,7 @@ pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error { #[cfg(target_os = "windows")] fn sidecar_config_without_tun(yaml: &str) -> Result { + use crate::config::mihomo_yaml; use serde_yaml_ng::{Mapping, Value}; let mut config: Mapping = serde_yaml_ng::from_str(yaml)?; @@ -47,7 +48,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result { tun.as_mapping_mut() .context("invalid Sidecar TUN configuration")? .insert(Value::from("enable"), Value::Bool(false)); - Ok(serde_yaml_ng::to_string(&config)?) + Ok(mihomo_yaml::serialize(&config)?) } const SIDECAR_READINESS_ATTEMPTS: usize = 30; diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rs index bad0022a7..5d45c7f31 100644 --- a/src-tauri/src/core/mod.rs +++ b/src-tauri/src/core/mod.rs @@ -11,9 +11,7 @@ pub mod network_watch; pub mod notify; pub(crate) mod owner_identity; pub mod proxy_control; -pub mod proxy_view; pub mod runstate; -pub(crate) mod runtime_bundle; pub mod service; pub mod sysopt; pub mod timer; diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index b405e635d..445ddc71e 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -1,7 +1,7 @@ use crate::core::notify::NoticeStatus; use crate::utils::dirs; use crate::{ - config::{Config, runtime::IRuntime}, + config::{Config, mihomo_yaml, runtime::IRuntime}, constants, core::{ CoreManager, @@ -13,7 +13,6 @@ use crate::{ CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE, ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth, }, - runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of}, tray::Tray, }, process::AsyncHandler, @@ -21,10 +20,11 @@ use crate::{ use anyhow::{Context as _, Result, anyhow, bail}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging}; +use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of}; use clash_verge_service_ipc::{ MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome, - RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot, - StageRuntimeOutcome, StartClashRequest, WriterConfig, + RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, + ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig, }; use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask}; use clash_verge_task::watch_task; @@ -611,7 +611,27 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result Result { let loaded_before = provider_load_times().await; let mut fetched = Vec::new(); for declared in applied_remote_providers(&runtime, &app_dir)? { - let (temp, file) = match create_sync_temp(&app_dir.join(&declared.provider.destination)).await { + let (temp, file) = match create_sync_temp(&app_dir.join(declared.destination.as_str())).await { Ok(created) => created, Err(error) => { logging!(warn, Type::Service, "{error:#}"); @@ -956,7 +976,7 @@ async fn sync_runtime_providers_by_service() -> Result { continue; } }; - match fetch_runtime_file(&credentials, &session, &declared.provider.destination, file).await { + match fetch_runtime_file(&credentials, &session, &declared.destination, file).await { Ok(Fetch::Complete { len, mtime_ns }) => fetched.push(FetchedCache { declared, temp, @@ -977,7 +997,7 @@ async fn sync_runtime_providers_by_service() -> Result { warn, Type::Service, "failed to read provider cache {} into {}: {error:#}", - declared.provider.destination, + declared.destination, temp.display() ); outcome.pending += 1; @@ -1088,7 +1108,7 @@ async fn sync_runtime_geo( fn applied_remote_providers(runtime: &Draft, app_dir: &Path) -> Result> { let applied = runtime.data_arc(); match applied.config.as_ref() { - Some(config) => remote_providers_of(config, app_dir), + Some(config) => remote_providers_of(config, app_dir).map_err(Into::into), None => Ok(Vec::new()), } } @@ -1117,7 +1137,7 @@ async fn publish_fetched( }; let mut synced = 0; for cache in fetched { - let target = app_dir.join(&cache.declared.provider.destination); + let target = app_dir.join(cache.declared.destination.as_str()); if !declared.contains(&cache.declared) || same_contents(&cache.temp, &target).await { remove_temp(&cache.temp).await; continue; @@ -1194,7 +1214,7 @@ async fn recheck_identity( cache: &FetchedCache, ) -> Result { let request = RuntimeFileRequest { - destination: cache.declared.provider.destination.to_owned(), + destination: cache.declared.destination.as_str().to_owned(), offset: cache.len, }; Ok(match read_chunk(credentials, session, &request).await? { diff --git a/src-tauri/src/core/validate.rs b/src-tauri/src/core/validate.rs index 7d708ff42..42cb68a7c 100644 --- a/src-tauri/src/core/validate.rs +++ b/src-tauri/src/core/validate.rs @@ -17,6 +17,7 @@ use crate::core::handle; use crate::singleton; use crate::utils::{dirs, help}; use clash_verge_logging::{Type, logging}; +use clash_verge_profile_script::MainDeclaration; const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); @@ -33,7 +34,7 @@ async fn validation_fingerprint(yaml: &str) -> u64 { .into_iter(); // The test run reads geo databases from the app dir; a geo update must revalidate. let geo = dirs::app_home_dir().into_iter().flat_map(|dir| { - super::runtime_bundle::GEO_ASSETS + clash_verge_runtime_bundle::GEO_ASSETS .iter() .map(move |asset| dir.join(asset)) }); @@ -257,22 +258,8 @@ impl CoreConfigValidator { }; logging!(debug, Type::Validate, "验证脚本文件: {}", path); - let has_main = - content.contains("function main") || content.contains("const main") || content.contains("let main"); - - // Boa parsing is pure CPU; keep it off the async worker, with a timeout. - let syntax = crate::process::AsyncHandler::spawn_blocking(move || { - use boa_engine::{Context, Source}; - - let mut context = Context::default(); - let _ = context.eval(Source::from_bytes( - "var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});", - )); - context - .eval(Source::from_bytes(&content)) - .map(|_| ()) - .map_err(|err| err.to_string()) - }); + let syntax = + crate::process::AsyncHandler::spawn_blocking(move || clash_verge_profile_script::validate(&content)); let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await { Ok(Ok(evaluated)) => evaluated, Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")), @@ -280,10 +267,10 @@ impl CoreConfigValidator { }; match result { - Ok(()) => { + Ok(main) => { logging!(debug, Type::Validate, "脚本语法验证通过: {}", path); - if !has_main { + if main == MainDeclaration::Missing { let error_msg = "Script must contain a main function"; logging!(warn, Type::Validate, "脚本缺少main函数: {}", path); return Ok(ValidationOutcome::invalid_from_message(error_msg)); diff --git a/src-tauri/src/enhance/chain.rs b/src-tauri/src/enhance/chain.rs index d4f3781b4..fe663a629 100644 --- a/src-tauri/src/enhance/chain.rs +++ b/src-tauri/src/enhance/chain.rs @@ -1,31 +1,14 @@ -use super::SeqMap; use crate::{ config::PrfItem, utils::{dirs, help}, }; +use clash_verge_config_render::{ChainItem, ChainType, SeqMap}; use parking_lot::Mutex; -use serde_yaml_ng::Mapping; use std::collections::HashMap; use std::path::PathBuf; use std::sync::{Arc, LazyLock}; use std::time::SystemTime; use tokio::fs; -use tristr::alias::String; - -#[derive(Debug)] -pub struct ChainItem { - pub uid: String, - pub data: ChainType, -} - -#[derive(Debug)] -pub enum ChainType { - Merge(Mapping), - Script(String), - Rules(SeqMap), - Proxies(SeqMap), - Groups(SeqMap), -} struct CachedChain { mtime: SystemTime, @@ -35,56 +18,45 @@ struct CachedChain { static CHAIN_CACHE: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); -// Helper trait to allow async conversion -pub trait AsyncChainItemFrom { - async fn from_async(item: &PrfItem) -> Option>; -} +pub(super) async fn load_chain_item(item: &PrfItem) -> Option> { + let itype = item.itype.as_ref()?.as_str(); + let file = item.file.as_ref()?; + let path = dirs::app_profiles_dir().ok()?.join(file.as_str()); -impl AsyncChainItemFrom for Option> { - async fn from_async(item: &PrfItem) -> Self { - let itype = item.itype.as_ref()?.as_str(); - let file = item.file.clone()?; - let uid = item.uid.clone().unwrap_or_else(|| "".into()); - let path = dirs::app_profiles_dir().ok()?.join(file.as_str()); - - let meta = fs::metadata(&path).await.ok()?; - let (mtime, len) = (meta.modified().ok()?, meta.len()); - if let Some(cached) = CHAIN_CACHE.lock().get(&path) - && cached.mtime == mtime - && cached.len == len - { - return Some(Arc::clone(&cached.item)); - } - - let loaded = Arc::new(match itype { - "script" => Some(ChainItem { - uid, - data: ChainType::Script(fs::read_to_string(&path).await.ok()?.as_str().into()), - }), - "merge" => Some(ChainItem { - uid, - data: ChainType::Merge(help::read_mapping(&path).await.ok()?), - }), - "rules" | "proxies" | "groups" => { - let seq_map = help::read_yaml::(&path).await.ok()?; - let data = match itype { - "rules" => ChainType::Rules(seq_map), - "proxies" => ChainType::Proxies(seq_map), - _ => ChainType::Groups(seq_map), - }; - Some(ChainItem { uid, data }) - } - _ => None, - }?); - - CHAIN_CACHE.lock().insert( - path, - CachedChain { - mtime, - len, - item: Arc::clone(&loaded), - }, - ); - Some(loaded) + let meta = fs::metadata(&path).await.ok()?; + let (mtime, len) = (meta.modified().ok()?, meta.len()); + if let Some(cached) = CHAIN_CACHE.lock().get(&path) + && cached.mtime == mtime + && cached.len == len + { + return Some(Arc::clone(&cached.item)); } + + let data = match itype { + "script" => ChainType::Script(fs::read_to_string(&path).await.ok()?.into()), + "merge" => ChainType::Merge(help::read_mapping(&path).await.ok()?), + "rules" | "proxies" | "groups" => { + let seq_map = help::read_yaml::(&path).await.ok()?; + match itype { + "rules" => ChainType::Rules(seq_map), + "proxies" => ChainType::Proxies(seq_map), + _ => ChainType::Groups(seq_map), + } + } + _ => return None, + }; + let loaded = Arc::new(ChainItem { + uid: item.uid.clone().unwrap_or_default(), + data, + }); + + CHAIN_CACHE.lock().insert( + path, + CachedChain { + mtime, + len, + item: Arc::clone(&loaded), + }, + ); + Some(loaded) } diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index 766775ded..45fd0abb9 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -1,21 +1,9 @@ -use crate::core::notify::NoticeStatus; mod chain; -pub mod field; -mod merge; -mod script; -pub mod seq; -mod tun; -use self::{ - chain::{AsyncChainItemFrom as _, ChainItem, ChainType}, - field::{use_keys, use_lowercase, use_sort}, - merge::use_merge, - script::use_script, - seq::{SeqMap, use_seq}, - tun::use_tun, -}; +use self::chain::load_chain_item; use crate::config::dns::{DnsOverrideState, dns_override_source}; use crate::core::handle::Handle; +use crate::core::notify::NoticeStatus; use crate::utils::dirs; use crate::{ config::{Config, IProfiles, IVerge, PrfItem, profiles::current_mapping}, @@ -23,79 +11,54 @@ use crate::{ utils::tmpl, }; use anyhow::{Context as _, Result}; -use clash_verge_logging::{Type, logging}; +use clash_verge_config_render::{ + ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, render, +}; use parking_lot::Mutex; -use serde_yaml_ng::{Mapping, Value}; +use serde_yaml_ng::Mapping; use std::collections::{HashMap, HashSet}; -use std::hash::{Hash as _, Hasher as _}; use std::sync::Arc; use tokio::fs; use tristr::alias::String; -type ResultLog = Vec<(String, String)>; -#[derive(Debug)] struct ConfigValues { - clash_config: Mapping, - enable_tun: bool, - enable_builtin: bool, - socks_enabled: bool, - http_enabled: bool, + render: RenderSettings, enable_dns_settings: bool, dns_override_confirmation: Option, - enable_external_controller: bool, - #[cfg(not(target_os = "windows"))] - redir_enabled: bool, - #[cfg(target_os = "linux")] - tproxy_enabled: bool, } -#[derive(Debug)] -struct ProfileItems { - config: Mapping, - merge_item: Arc, - script_item: Arc, - rules_item: Arc, - proxies_item: Arc, - groups_item: Arc, - global_merge: Arc, - global_script: Arc, - profile_name: String, -} - -impl Default for ProfileItems { - fn default() -> Self { - Self { - config: Default::default(), - profile_name: Default::default(), - merge_item: Arc::new(ChainItem { - uid: "".into(), - data: ChainType::Merge(Mapping::new()), - }), - script_item: Arc::new(ChainItem { - uid: "".into(), - data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), - }), - rules_item: Arc::new(ChainItem { - uid: "".into(), - data: ChainType::Rules(SeqMap::default()), - }), - proxies_item: Arc::new(ChainItem { - uid: "".into(), - data: ChainType::Proxies(SeqMap::default()), - }), - groups_item: Arc::new(ChainItem { - uid: "".into(), - data: ChainType::Groups(SeqMap::default()), - }), - global_merge: Arc::new(ChainItem { - uid: "Merge".into(), - data: ChainType::Merge(Mapping::new()), - }), - global_script: Arc::new(ChainItem { - uid: "Script".into(), - data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), - }), - } +fn default_profile() -> RenderProfile { + RenderProfile { + config: Default::default(), + profile_name: Default::default(), + merge_item: Arc::new(ChainItem { + uid: "".into(), + data: ChainType::Merge(Mapping::new()), + }), + script_item: Arc::new(ChainItem { + uid: "".into(), + data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), + }), + rules_item: Arc::new(ChainItem { + uid: "".into(), + data: ChainType::Rules(SeqMap::default()), + }), + proxies_item: Arc::new(ChainItem { + uid: "".into(), + data: ChainType::Proxies(SeqMap::default()), + }), + groups_item: Arc::new(ChainItem { + uid: "".into(), + data: ChainType::Groups(SeqMap::default()), + }), + global_merge: Arc::new(ChainItem { + uid: "Merge".into(), + data: ChainType::Merge(Mapping::new()), + }), + global_script: Arc::new(ChainItem { + uid: "Script".into(), + data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), + }), } } @@ -104,9 +67,7 @@ async fn chain_item_or_default( default_item: impl FnOnce() -> Arc, ) -> Arc { if let Some(item) = item { - >>::from_async(item) - .await - .unwrap_or_else(default_item) + load_chain_item(item).await.unwrap_or_else(default_item) } else { default_item() } @@ -152,26 +113,28 @@ async fn get_config_values(profile_uid: &str) -> ConfigValues { drop(verge); ConfigValues { - clash_config, - enable_tun, - enable_builtin, - socks_enabled, - http_enabled, + render: RenderSettings { + clash_config, + enable_tun, + enable_builtin, + socks_enabled, + http_enabled, + enable_external_controller, + #[cfg(not(target_os = "windows"))] + redir_enabled, + #[cfg(target_os = "linux")] + tproxy_enabled, + }, enable_dns_settings, dns_override_confirmation, - enable_external_controller, - #[cfg(not(target_os = "windows"))] - redir_enabled, - #[cfg(target_os = "linux")] - tproxy_enabled, } } #[allow(clippy::cognitive_complexity)] -async fn collect_profile_items(profiles: &IProfiles) -> Result { +async fn collect_profile_items(profiles: &IProfiles) -> Result { let current_profile_uid = match profiles.current.clone() { Some(uid) => uid, - None => return Ok(ProfileItems::default()), + None => return Ok(default_profile()), }; let current = current_mapping(profiles) @@ -202,7 +165,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result { let name = current_item.name.clone().unwrap_or_default(); - let ProfileItems { + let RenderProfile { merge_item: default_merge, script_item: default_script, rules_item: default_rules, @@ -211,7 +174,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result { global_merge: default_global_merge, global_script: default_global_script, .. - } = ProfileItems::default(); + } = default_profile(); let (merge_item, script_item, rules_item, proxies_item, groups_item, global_merge, global_script) = tokio::join!( chain_item_or_default(profiles.get_item(&merge_uid).ok(), || default_merge,), @@ -223,7 +186,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result { chain_item_or_default(profiles.get_item("Script").ok(), || default_global_script,), ); - Ok(ProfileItems { + Ok(RenderProfile { config: current, merge_item, script_item, @@ -236,209 +199,6 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result { }) } -async fn process_override_items( - mut config: Mapping, - mut exists_keys: Vec, - mut result_map: HashMap, - merge_item: Arc, - script_item: Arc, - profile_name: &str, - authoritative: &AuthoritativeFields, -) -> (Mapping, Vec, HashMap) { - if let ChainType::Merge(merge) = &merge_item.data { - exists_keys.extend(use_keys(merge)); - let before = authoritative.current(&config); - config = use_merge(merge.clone(), config); - let notes: ResultLog = authoritative - .overridden(&before, &authoritative.current(&config)) - .into_iter() - .map(discarded_note) - .collect(); - if !notes.is_empty() { - result_map.entry(merge_item.uid.clone()).or_default().extend(notes); - } - } - - if let ChainType::Script(script) = &script_item.data { - let before = authoritative.current(&config); - let (res_config, changed_keys, mut logs) = use_script(script.clone(), config, profile_name.into()).await; - exists_keys.extend(changed_keys); - config = res_config; - logs.extend( - authoritative - .overridden(&before, &authoritative.current(&config)) - .into_iter() - .map(discarded_note), - ); - result_map.insert(script_item.uid.clone(), logs); - } - - (config, exists_keys, result_map) -} - -fn process_seq_items( - mut config: Mapping, - rules_item: Arc, - proxies_item: Arc, - groups_item: Arc, -) -> Mapping { - if let ChainType::Rules(rules) = &rules_item.data { - config = use_seq(rules.clone(), config, "rules"); - } - - if let ChainType::Proxies(proxies) = &proxies_item.data { - config = use_seq(proxies.clone(), config, "proxies"); - } - - if let ChainType::Groups(groups) = &groups_item.data { - config = use_seq(groups.clone(), config, "proxy-groups"); - } - - config -} - -/// App-owned control-plane keys; DNS settings are captured separately. -const CONTROL_PLANE_KEYS: &[&str] = &[ - "external-controller", - #[cfg(unix)] - "external-controller-unix", - #[cfg(windows)] - "external-controller-pipe", - "external-controller-cors", - "secret", - "mixed-port", - "socks-port", - "port", - #[cfg(not(target_os = "windows"))] - "redir-port", - #[cfg(target_os = "linux")] - "tproxy-port", - "mode", - "allow-lan", - "log-level", - "ipv6", - "unified-delay", -]; - -/// App-owned fields: captured after the app derives them, enforced after every override. -struct AuthoritativeFields { - control_plane: Mapping, - tun: Mapping, - dns: Mapping, - hosts: Option, - fingerprints: FieldFingerprints, -} - -#[derive(Default)] -struct FieldFingerprints { - control_plane: Vec>, - tun: Vec>, - dns: Vec>, - hosts: Option, -} - -fn fingerprint(value: Option<&Value>) -> Option { - let value = value?; - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - value.hash(&mut hasher); - Some(hasher.finish()) -} - -impl AuthoritativeFields { - fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self { - let control_plane = snapshot_control_plane(config); - let tun = snapshot_tun(config, gui_tun_keys); - let dns = take_mapping(&mut dns_settings, "dns"); - let hosts = dns_settings.remove("hosts"); - let fingerprints = FieldFingerprints { - control_plane: CONTROL_PLANE_KEYS - .iter() - .map(|&key| fingerprint(control_plane.get(Value::from(key)))) - .collect(), - tun: tun.iter().map(|(_, value)| fingerprint(Some(value))).collect(), - dns: dns.iter().map(|(_, value)| fingerprint(Some(value))).collect(), - hosts: fingerprint(hosts.as_ref()), - }; - Self { - control_plane, - tun, - dns, - hosts, - fingerprints, - } - } - - fn enforce(self, config: Mapping) -> Mapping { - let config = enforce_control_plane(config, self.control_plane); - let mut config = enforce_tun(config, self.tun); - if !self.dns.is_empty() { - let mut dns = take_mapping(&mut config, "dns"); - dns.extend(self.dns); - config.insert("dns".into(), dns.into()); - } - if let Some(hosts) = self.hosts { - config.insert("hosts".into(), hosts); - } - config - } - - /// What `config` holds now, for diffing one override. - fn current(&self, config: &Mapping) -> FieldFingerprints { - let tun = config.get("tun").and_then(Value::as_mapping); - let dns = config.get("dns").and_then(Value::as_mapping); - FieldFingerprints { - control_plane: CONTROL_PLANE_KEYS - .iter() - .map(|&key| fingerprint(config.get(key))) - .collect(), - tun: self - .tun - .keys() - .map(|key| fingerprint(tun.and_then(|map| map.get(key)))) - .collect(), - dns: self - .dns - .keys() - .map(|key| fingerprint(dns.and_then(|map| map.get(key)))) - .collect(), - hosts: self.hosts.as_ref().and_then(|_| fingerprint(config.get("hosts"))), - } - } - - /// Owned keys an override moved off the app value; `enforce` discards those writes. - fn overridden(&self, before: &FieldFingerprints, after: &FieldFingerprints) -> Vec { - let mut keys = Vec::new(); - for (index, &key) in CONTROL_PLANE_KEYS.iter().enumerate() { - if before.control_plane[index] != after.control_plane[index] - && after.control_plane[index] != self.fingerprints.control_plane[index] - { - keys.push(key.into()); - } - } - for (index, key) in self.tun.keys().enumerate() { - if before.tun[index] != after.tun[index] && after.tun[index] != self.fingerprints.tun[index] { - keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into()); - } - } - for (index, key) in self.dns.keys().enumerate() { - if before.dns[index] != after.dns[index] && after.dns[index] != self.fingerprints.dns[index] { - keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into()); - } - } - if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.fingerprints.hosts { - keys.push("hosts".into()); - } - keys - } -} - -fn discarded_note(key: String) -> (String, String) { - ( - "warn".into(), - format!("`{key}` is managed by Settings; the value written here was discarded").into(), - ) -} - struct DiscardedKeysNotice { pending: Option, last: Vec, @@ -471,1429 +231,46 @@ fn notify_discarded_keys(keys: Vec) { } } -/// 手动 merge/script 前保存 app 最终控制面值,只记录当前存在的键。 -fn snapshot_control_plane(config: &Mapping) -> Mapping { - let mut snapshot = Mapping::new(); - for &key in CONTROL_PLANE_KEYS { - let key = Value::from(key); - if let Some(value) = config.get(&key) { - snapshot.insert(key, value.clone()); - } - } - snapshot -} - -/// 手动覆盖后恢复控制面快照;快照缺失的控制面键从最终配置删除。 -fn enforce_control_plane(mut config: Mapping, snapshot: Mapping) -> Mapping { - for &key in CONTROL_PLANE_KEYS { - let key = Value::from(key); - if !snapshot.contains_key(&key) { - config.remove(&key); - } - } - config.extend(snapshot); - config -} - -/// Only saved GUI fields and the verge switch override profile settings. -fn gui_tun_keys(clash_config: &Mapping) -> Vec { - let mut keys = vec![Value::from("enable")]; - if let Some(Value::Mapping(tun)) = clash_config.get("tun") { - keys.extend( - constants::tun::GUI_KEYS - .iter() - .filter(|key| tun.get(**key).is_some_and(|value| !value.is_null())) - .map(|key| Value::from(*key)), - ); - } - keys -} - -fn snapshot_tun(config: &Mapping, gui_tun_keys: &[Value]) -> Mapping { - let mut snapshot = Mapping::new(); - if let Some(Value::Mapping(tun)) = config.get("tun") { - for key in gui_tun_keys { - if let Some(value) = tun.get(key) { - snapshot.insert(key.clone(), value.clone()); - } - } - } - snapshot -} - -fn enforce_tun(mut config: Mapping, snapshot: Mapping) -> Mapping { - if snapshot.is_empty() { - return config; - } - let mut tun = take_mapping(&mut config, "tun"); - tun.extend(snapshot); - config.insert(Value::from("tun"), Value::Mapping(tun)); - config -} - -fn is_loopback_bind_address(addr: &str) -> bool { - let addr = addr.trim(); - let addr = addr.strip_circumfix('[', ']').unwrap_or(addr); - - addr.eq_ignore_ascii_case("localhost") - || addr.parse::().is_ok_and(|addr| addr.is_loopback()) - || is_ipv4_shorthand_loopback(addr) -} - -fn is_ipv4_shorthand_loopback(addr: &str) -> bool { - let parts = addr.split('.').map(str::parse::).collect::, _>>(); - - let Ok(parts) = parts else { - return false; - }; - - match parts.as_slice() { - [first, rest] => *first == 127 && *rest <= 0x00ff_ffff, - [first, second, rest] => *first == 127 && *second <= 0xff && *rest <= 0xffff, - [first, second, third, fourth] => *first == 127 && *second <= 0xff && *third <= 0xff && *fourth <= 0xff, - _ => false, - } -} - -fn ensure_lan_bind_address(mut config: Mapping) -> Mapping { - let allow_lan = config.get("allow-lan").and_then(Value::as_bool).unwrap_or(false); - - if allow_lan - && config - .get("bind-address") - .and_then(Value::as_str) - .is_some_and(is_loopback_bind_address) - { - config.insert(Value::from("bind-address"), Value::from("*")); +async fn read_dns_settings(enabled: bool) -> Option { + if !enabled { + return None; } - config -} - -fn ensure_tun_default_mtu(mut config: Mapping) -> Mapping { - if let Some(Value::Mapping(tun)) = config.get_mut("tun") - && matches!(tun.get("mtu"), None | Some(Value::Null)) - { - tun.insert(Value::from("mtu"), Value::from(constants::tun::DEFAULT_MTU)); + let dns_path = dirs::app_home_dir().ok()?.join(constants::files::DNS_CONFIG); + if !dns_path.exists() { + return None; } - - config -} - -/// Merges the app's clash config over the profile; switches are parameters to keep it pure. -fn merge_default_config( - mut config: Mapping, - clash_config: Mapping, - socks_enabled: bool, - http_enabled: bool, - enable_external_controller: bool, - #[cfg(not(target_os = "windows"))] redir_enabled: bool, - #[cfg(target_os = "linux")] tproxy_enabled: bool, -) -> Mapping { - for (key, value) in clash_config.into_iter() { - if key.as_str() == Some("tun") { - if let Value::Mapping(patch_tun) = value { - let mut tun = take_mapping(&mut config, "tun"); - for (key, value) in patch_tun { - if !value.is_null() { - tun.insert(key, value); - } - } - config.insert(Value::from("tun"), Value::Mapping(tun)); - } - } else { - if key.as_str() == Some("socks-port") && !socks_enabled { - config.remove("socks-port"); - continue; - } - if key.as_str() == Some("port") && !http_enabled { - config.remove("port"); - continue; - } - #[cfg(target_os = "windows")] - { - if key.as_str() == Some("redir-port") { - continue; - } - } - #[cfg(not(target_os = "windows"))] - { - if key.as_str() == Some("redir-port") && !redir_enabled { - config.remove("redir-port"); - continue; - } - } - #[cfg(target_os = "linux")] - { - if key.as_str() == Some("tproxy-port") && !tproxy_enabled { - config.remove("tproxy-port"); - continue; - } - } - #[cfg(not(target_os = "linux"))] - { - if key.as_str() == Some("tproxy-port") { - config.remove("tproxy-port"); - continue; - } - } - if key.as_str() == Some("external-controller") { - if enable_external_controller { - config.insert(key, value); - } else { - config.insert(key, "".into()); - } - } else { - config.insert(key, value); - } - } - } - - config -} - -fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping { - if enable_builtin { - // The JS path saw a lowercased view; lowercase once, only when the builtin runs. - config = use_lowercase(config); - logging!(debug, Type::Core, "run builtin script verge_hy_alpn"); - config = builtin_hy_alpn(config); - } - - config -} - -fn builtin_hy_alpn(mut config: Mapping) -> Mapping { - if let Some(Value::Sequence(proxies)) = config.get_mut("proxies") { - for proxy in proxies.iter_mut() { - let Some(proxy) = proxy.as_mapping_mut() else { continue }; - let is_hysteria = proxy.get("type").and_then(Value::as_str) == Some("hysteria"); - if is_hysteria - && let Some(alpn) = proxy.get_mut("alpn") - && let Value::String(text) = alpn - { - let text = std::mem::take(text); - *alpn = Value::Sequence(vec![Value::String(text)]); - } - } - } - - config -} - -fn cleanup_proxy_groups(mut config: Mapping) -> Mapping { - // built-in proxies docs: https://wiki.metacubex.one/config/proxies/built-in - const BUILTIN_POLICIES: &[&str] = &["DIRECT", "REJECT", "REJECT-DROP", "PASS", "PASS-RULE"]; - - let proxy_names = config - .get("proxies") - .and_then(|v| v.as_sequence()) - .map_or_default(|seq| { - seq.iter() - .filter_map(|item| match item { - Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(Into::into), - Value::String(name) => Some(name.as_str().into()), - _ => None, - }) - .collect::>() - }); - - let group_names = config - .get("proxy-groups") - .and_then(|v| v.as_sequence()) - .map_or_default(|seq| { - seq.iter() - .filter_map(|item| { - item.as_mapping() - .and_then(|map| map.get("name")) - .and_then(Value::as_str) - .map(std::convert::Into::into) - }) - .collect::>() - }); - - let provider_names = config - .get("proxy-providers") - .and_then(Value::as_mapping) - .map_or_default(|map| { - map.keys() - .filter_map(Value::as_str) - .map(std::convert::Into::into) - .collect::>() - }); - - let mut allowed_names = proxy_names; - allowed_names.extend(group_names); - allowed_names.extend(provider_names.iter().cloned()); - allowed_names.extend(BUILTIN_POLICIES.iter().map(|p| (*p).into())); - - if let Some(Value::Sequence(groups)) = config.get_mut("proxy-groups") { - for group in groups { - if let Some(group_map) = group.as_mapping_mut() { - let mut has_valid_provider = false; - - if let Some(Value::Sequence(uses)) = group_map.get_mut("use") { - uses.retain(|provider| match provider { - Value::String(name) => { - let exists = provider_names.contains(name.as_str()); - has_valid_provider = has_valid_provider || exists; - exists - } - _ => false, - }); - } - - if let Some(Value::Sequence(proxies)) = group_map.get_mut("proxies") { - proxies.retain(|proxy| match proxy { - Value::String(name) => allowed_names.contains(name.as_str()) || has_valid_provider, - _ => true, - }); - } - } - } - } - - config -} - -/// fake-ip + IPv6 缺少 `fake-ip-range6` 时补默认值,否则 AAAA 无法解析(#7373)。 -fn ensure_fake_ip_range6(dns: &mut Mapping) { - use serde_yaml_ng::Value; - - let ipv6_enabled = dns.get("ipv6").and_then(|v| v.as_bool()).unwrap_or(false); - let is_fake_ip = dns - .get("enhanced-mode") - .and_then(|v| v.as_str()) - .is_none_or(|m| m == "fake-ip"); - - // Hand-edited YAML may leave the key present but empty. - let range6_missing = dns - .get("fake-ip-range6") - .and_then(|v| v.as_str()) - .is_none_or(|s| s.trim().is_empty()); - - if ipv6_enabled && is_fake_ip && range6_missing { - dns.insert(Value::from("fake-ip-range6"), Value::from("2001:2::0/64")); - } -} - -/// On, non-blank text, or non-empty list/map; anything else keeps the profile's value. -fn is_set(value: &Value) -> bool { - match value { - Value::Null => false, - Value::Bool(on) => *on, - Value::String(text) => !text.trim().is_empty(), - Value::Sequence(items) => !items.is_empty(), - Value::Mapping(map) => !map.is_empty(), - Value::Number(_) | Value::Tagged(_) => true, - } -} - -fn take_mapping(config: &mut Mapping, key: &str) -> Mapping { - config - .get_mut(key) - .and_then(Value::as_mapping_mut) - .map_or_default(std::mem::take) -} - -fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, Mapping) { - let mut applied = Mapping::new(); - if let Some(Value::Mapping(hosts)) = dns_config.remove("hosts") - && !hosts.is_empty() - { - applied.insert("hosts".into(), hosts.clone().into()); - config.insert("hosts".into(), hosts.into()); - logging!(debug, Type::Core, "apply hosts configuration"); - } - - // Legacy layout: no `dns` root. - let dns_override = match dns_config.remove("dns") { - Some(Value::Mapping(dns)) => Some(dns), - Some(_) => None, - None => Some(dns_config), - }; - if let Some(mut dns_override) = dns_override { - dns_override.retain(|_, value| is_set(value)); - if !dns_override.is_empty() { - applied.insert("dns".into(), dns_override.clone().into()); - } - let mut dns = take_mapping(&mut config, "dns"); - dns.extend(dns_override); - ensure_fake_ip_range6(&mut dns); - config.insert("dns".into(), dns.into()); - logging!(debug, Type::Core, "apply dns_config.yaml"); - } - (config, applied) -} - -/// Returns the merged config and the non-empty fields owned by the DNS page. -async fn apply_dns_settings(config: Mapping, enable_dns_settings: bool) -> (Mapping, Mapping) { - if enable_dns_settings && let Ok(app_dir) = dirs::app_home_dir() { - let dns_path = app_dir.join(constants::files::DNS_CONFIG); - - if dns_path.exists() - && let Ok(dns_yaml) = fs::read_to_string(&dns_path).await - && let Ok(dns_config) = serde_yaml_ng::from_str::(&dns_yaml) - { - return merge_dns_config(config, dns_config); - } - } - - (config, Mapping::new()) + let yaml = fs::read_to_string(&dns_path).await.ok()?; + serde_yaml_ng::from_str(&yaml).ok() } /// Returns the enhanced profile, its original keys, script logs, and DNS override decision. -pub async fn enhance( +pub async fn render_runtime_config( profiles: &IProfiles, ) -> Result<(Mapping, HashSet, HashMap, DnsOverrideState)> { let profile_uid = profiles.current.as_deref().unwrap_or_default(); - let cfg_vals = get_config_values(profile_uid).await; - let ConfigValues { - clash_config, - enable_tun, - enable_builtin, - socks_enabled, - http_enabled, - enable_dns_settings, - dns_override_confirmation, - enable_external_controller, - #[cfg(not(target_os = "windows"))] - redir_enabled, - #[cfg(target_os = "linux")] - tproxy_enabled, - } = cfg_vals; - + let settings = get_config_values(profile_uid).await; let profile = collect_profile_items(profiles).await?; let dns_override = DnsOverrideState::new( profile_uid, dns_override_source(profile_uid, &profile.config)?, - enable_dns_settings, - dns_override_confirmation, + settings.enable_dns_settings, + settings.dns_override_confirmation, ); - let enable_dns_settings = dns_override.enabled; - let config = profile.config; - let merge_item = profile.merge_item; - let script_item = profile.script_item; - let rules_item = profile.rules_item; - let proxies_item = profile.proxies_item; - let groups_item = profile.groups_item; - let global_merge = profile.global_merge; - let global_script = profile.global_script; - let profile_name = profile.profile_name; - - let result_map = HashMap::new(); - - let config = process_seq_items(config, rules_item, proxies_item, groups_item); - let exists_keys = use_keys(&config).collect::>(); - let gui_tun_keys = gui_tun_keys(&clash_config); - - let config = merge_default_config( - config, - clash_config, - socks_enabled, - http_enabled, - enable_external_controller, - #[cfg(not(target_os = "windows"))] - redir_enabled, - #[cfg(target_os = "linux")] - tproxy_enabled, - ); - - let config = apply_builtin_scripts(config, enable_builtin); - let config = use_tun(config, enable_tun); - let (config, dns_settings) = apply_dns_settings(config, enable_dns_settings).await; - - let authoritative = AuthoritativeFields::capture(&config, &gui_tun_keys, dns_settings); - - let (config, exists_keys, result_map) = process_override_items( + let dns_config = read_dns_settings(dns_override.enabled).await; + let RenderedConfig { config, exists_keys, - result_map, - global_merge, - global_script, - profile_name.as_str(), - &authoritative, + logs, + discarded_keys, + } = render( + profile, + settings.render, + dns_config, + clash_verge_profile_script::execute, ) .await; + notify_discarded_keys(discarded_keys); - let (config, exists_keys, result_map) = process_override_items( - config, - exists_keys, - result_map, - merge_item, - script_item, - profile_name.as_str(), - &authoritative, - ) - .await; - - notify_discarded_keys(authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config))); - let config = authoritative.enforce(config); - let config = ensure_tun_default_mtu(config); - let config = ensure_lan_bind_address(config); - - let config = cleanup_proxy_groups(config); - let config = use_sort(config); - - let mut exists_keys_set = HashSet::new(); - exists_keys_set.extend(exists_keys); - - Ok((config, exists_keys_set, result_map, dns_override)) -} - -#[cfg(test)] -#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] -mod fake_ip_tests { - use super::{Mapping, Value, ensure_fake_ip_range6}; - - fn dns(pairs: &[(&str, Value)]) -> Mapping { - let mut map = Mapping::new(); - for (key, value) in pairs { - map.insert(Value::from(*key), value.clone()); - } - map - } - - const RANGE6: &str = "2001:2::0/64"; - - #[test] - fn an_ipv6_fake_ip_setup_missing_its_range_gets_one() { - let mut config = dns(&[("ipv6", Value::from(true)), ("enhanced-mode", Value::from("fake-ip"))]); - - ensure_fake_ip_range6(&mut config); - - assert_eq!(config.get(Value::from("fake-ip-range6")), Some(&Value::from(RANGE6))); - } - - #[test] - fn fake_ip_is_the_assumed_mode_when_unstated() { - let mut config = dns(&[("ipv6", Value::from(true))]); - - ensure_fake_ip_range6(&mut config); - - assert_eq!(config.get(Value::from("fake-ip-range6")), Some(&Value::from(RANGE6))); - } - - #[test] - fn a_hand_edited_empty_range_counts_as_missing() { - // Hand-edited YAML may leave the key present but empty. - for blank in ["", " "] { - let mut config = dns(&[ - ("ipv6", Value::from(true)), - ("enhanced-mode", Value::from("fake-ip")), - ("fake-ip-range6", Value::from(blank)), - ]); - - ensure_fake_ip_range6(&mut config); - - assert_eq!( - config.get(Value::from("fake-ip-range6")), - Some(&Value::from(RANGE6)), - "blank range {blank:?} should be filled in" - ); - } - } - - #[test] - fn an_existing_range_is_never_overwritten() { - let mut config = dns(&[ - ("ipv6", Value::from(true)), - ("enhanced-mode", Value::from("fake-ip")), - ("fake-ip-range6", Value::from("fc00::1/64")), - ]); - - ensure_fake_ip_range6(&mut config); - - assert_eq!( - config.get(Value::from("fake-ip-range6")), - Some(&Value::from("fc00::1/64")) - ); - } - - #[test] - fn nothing_is_added_without_ipv6_or_outside_fake_ip() { - let mut without_ipv6 = dns(&[("enhanced-mode", Value::from("fake-ip"))]); - ensure_fake_ip_range6(&mut without_ipv6); - assert!(!without_ipv6.contains_key(Value::from("fake-ip-range6"))); - - let mut redir_host = dns(&[ - ("ipv6", Value::from(true)), - ("enhanced-mode", Value::from("redir-host")), - ]); - ensure_fake_ip_range6(&mut redir_host); - assert!(!redir_host.contains_key(Value::from("fake-ip-range6"))); - } -} - -#[cfg(test)] -#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] -mod use_tun_tests { - use super::{Mapping, Value, use_tun}; - - fn mapping(pairs: &[(&str, Value)]) -> Mapping { - let mut map = Mapping::new(); - for (key, value) in pairs { - map.insert(Value::from(*key), value.clone()); - } - map - } - - fn tun_of(config: &Mapping) -> &Mapping { - config - .get(Value::from("tun")) - .and_then(Value::as_mapping) - .expect("tun should be a mapping") - } - - fn dns_of(config: &Mapping) -> Option<&Mapping> { - config.get(Value::from("dns")).and_then(Value::as_mapping) - } - - #[tokio::test] - async fn the_switch_is_written_either_way() { - assert_eq!( - tun_of(&use_tun(Mapping::new(), true)).get(Value::from("enable")), - Some(&Value::from(true)) - ); - assert_eq!( - tun_of(&use_tun(Mapping::new(), false)).get(Value::from("enable")), - Some(&Value::from(false)) - ); - } - - #[tokio::test] - async fn existing_tun_keys_survive_being_switched_on() { - let config = mapping(&[("tun", Value::Mapping(mapping(&[("stack", Value::from("gvisor"))])))]); - - let result = use_tun(config, true); - - assert_eq!(tun_of(&result).get(Value::from("stack")), Some(&Value::from("gvisor"))); - } - - #[tokio::test] - async fn enabling_tun_sets_up_fake_ip_dns() { - let result = use_tun(Mapping::new(), true); - - let dns = dns_of(&result).expect("enabling tun should write dns settings"); - assert_eq!(dns.get(Value::from("enable")), Some(&Value::from(true))); - assert_eq!(dns.get(Value::from("enhanced-mode")), Some(&Value::from("fake-ip"))); - assert_eq!( - dns.get(Value::from("fake-ip-range")), - Some(&Value::from("198.18.0.1/16")) - ); - } - - #[tokio::test] - async fn a_deliberate_redir_host_setup_is_left_alone() { - // Only fake-ip DNS is ours to configure; someone who chose redir-host meant it. - let config = mapping(&[( - "dns", - Value::Mapping(mapping(&[("enhanced-mode", Value::from("redir-host"))])), - )]); - - let result = use_tun(config, true); - - let dns = dns_of(&result).expect("dns should still be present"); - assert_eq!(dns.get(Value::from("enhanced-mode")), Some(&Value::from("redir-host"))); - assert!(!dns.contains_key(Value::from("fake-ip-range"))); - } - - #[tokio::test] - async fn the_ipv6_fake_ip_range_follows_the_top_level_switch() { - let with_ipv6 = use_tun(mapping(&[("ipv6", Value::from(true))]), true); - let dns = dns_of(&with_ipv6).expect("dns should be written"); - assert_eq!(dns.get(Value::from("ipv6")), Some(&Value::from(true))); - assert_eq!( - dns.get(Value::from("fake-ip-range6")), - Some(&Value::from("2001:2::0/64")) - ); - - let without_ipv6 = use_tun(Mapping::new(), true); - let dns = dns_of(&without_ipv6).expect("dns should be written"); - assert!(!dns.contains_key(Value::from("fake-ip-range6"))); - } - - #[tokio::test] - async fn switching_tun_off_leaves_dns_untouched() { - // TUN off must not rewrite the DNS the profile chose. - let config = mapping(&[("dns", Value::Mapping(mapping(&[("enable", Value::from(false))])))]); - - let result = use_tun(config, false); - - let dns = dns_of(&result).expect("dns should be untouched"); - assert_eq!(dns.get(Value::from("enable")), Some(&Value::from(false))); - } -} - -#[cfg(test)] -#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] -mod use_sort_tests { - use super::{Mapping, Value, use_sort}; - - #[test] - fn every_key_survives_sorting() { - let mut config = Mapping::new(); - for key in ["rules", "mode", "proxies", "not-a-known-field", "log-level"] { - config.insert(Value::from(key), Value::from(key)); - } - let expected = config.len(); - - let sorted = use_sort(config); - - assert_eq!(sorted.len(), expected, "sorting must not drop or invent keys"); - for key in ["rules", "mode", "proxies", "not-a-known-field", "log-level"] { - assert_eq!(sorted.get(Value::from(key)), Some(&Value::from(key))); - } - } - - #[test] - fn the_bulky_list_fields_are_written_last() { - // Bulky list fields go last so the top of the file stays readable. - let mut config = Mapping::new(); - config.insert(Value::from("rules"), Value::from("rules")); - config.insert(Value::from("mode"), Value::from("rule")); - - let sorted = use_sort(config); - let order: Vec<_> = sorted.keys().filter_map(Value::as_str).collect(); - - let mode = order.iter().position(|key| *key == "mode"); - let rules = order.iter().position(|key| *key == "rules"); - assert!(mode < rules, "expected mode before rules, got {order:?}"); - } - - #[test] - fn sorting_is_stable_when_applied_twice() { - let mut config = Mapping::new(); - for key in ["proxies", "mode", "unknown-key", "rules"] { - config.insert(Value::from(key), Value::from(1)); - } - - let once = use_sort(config); - let twice = use_sort(once.clone()); - - assert_eq!(once.keys().collect::>(), twice.keys().collect::>()); - } -} - -#[cfg(test)] -#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] -mod merge_default_config_tests { - use super::{Mapping, Value, merge_default_config}; - - fn mapping(pairs: &[(&str, Value)]) -> Mapping { - let mut map = Mapping::new(); - for (key, value) in pairs { - map.insert(Value::from(*key), value.clone()); - } - map - } - - /// Call with every listener enabled, so a test only says what it is turning off. - fn merge(config: Mapping, clash_config: Mapping, external_controller: bool) -> Mapping { - merge_default_config( - config, - clash_config, - true, - true, - external_controller, - #[cfg(not(target_os = "windows"))] - true, - #[cfg(target_os = "linux")] - true, - ) - } - - fn merge_without_optional_listeners(config: Mapping, clash_config: Mapping) -> Mapping { - merge_default_config( - config, - clash_config, - false, - false, - true, - #[cfg(not(target_os = "windows"))] - false, - #[cfg(target_os = "linux")] - false, - ) - } - - #[test] - fn the_merge_config_overwrites_the_profile() { - let config = mapping(&[("mode", Value::from("rule"))]); - let clash_config = mapping(&[("mode", Value::from("global"))]); - - let merged = merge(config, clash_config, true); - - assert_eq!(merged.get(Value::from("mode")), Some(&Value::from("global"))); - } - - #[test] - fn keys_the_merge_config_says_nothing_about_survive() { - let config = mapping(&[("profile-only", Value::from(1))]); - - let merged = merge(config, Mapping::new(), true); - - assert_eq!(merged.get(Value::from("profile-only")), Some(&Value::from(1))); - } - - #[test] - fn a_disabled_listener_is_removed_rather_than_merged() { - // Removed, not skipped: the profile's own value must not reopen a disabled listener. - let config = mapping(&[("socks-port", Value::from(7891)), ("port", Value::from(7890))]); - let clash_config = mapping(&[("socks-port", Value::from(1080)), ("port", Value::from(8080))]); - - let merged = merge_without_optional_listeners(config, clash_config); - - assert!(!merged.contains_key(Value::from("socks-port"))); - assert!(!merged.contains_key(Value::from("port"))); - } - - #[test] - fn an_enabled_listener_takes_the_merge_config_value() { - let config = mapping(&[("socks-port", Value::from(7891))]); - let clash_config = mapping(&[("socks-port", Value::from(1080))]); - - let merged = merge(config, clash_config, true); - - assert_eq!(merged.get(Value::from("socks-port")), Some(&Value::from(1080))); - } - - #[test] - fn a_disabled_external_controller_is_blanked_rather_than_dropped() { - // Blanked, not removed: an absent key makes mihomo listen on its default. - let clash_config = mapping(&[("external-controller", Value::from("127.0.0.1:9090"))]); - - let merged = merge(Mapping::new(), clash_config, false); - - assert_eq!( - merged.get(Value::from("external-controller")), - Some(&Value::from("")), - "the key must remain, holding an empty value" - ); - } - - #[test] - fn an_enabled_external_controller_keeps_its_address() { - let clash_config = mapping(&[("external-controller", Value::from("127.0.0.1:9090"))]); - - let merged = merge(Mapping::new(), clash_config, true); - - assert_eq!( - merged.get(Value::from("external-controller")), - Some(&Value::from("127.0.0.1:9090")) - ); - } - - #[test] - fn tun_settings_are_merged_key_by_key_rather_than_replaced() { - // The profile's other tun keys have to survive a merge config that sets only one. - let config = mapping(&[( - "tun", - Value::Mapping(mapping(&[ - ("device", Value::from("utun9")), - ("stack", Value::from("system")), - ])), - )]); - let clash_config = mapping(&[("tun", Value::Mapping(mapping(&[("stack", Value::from("gvisor"))])))]); - - let merged = merge(config, clash_config, true); - - let tun = merged - .get(Value::from("tun")) - .and_then(Value::as_mapping) - .expect("tun should still be a mapping"); - assert_eq!(tun.get(Value::from("device")), Some(&Value::from("utun9"))); - assert_eq!(tun.get(Value::from("stack")), Some(&Value::from("gvisor"))); - } -} - -#[cfg(test)] -#[allow(clippy::expect_used, clippy::panic, reason = "tests assert by panicking")] -mod authoritative_field_tests { - use super::{AuthoritativeFields, Mapping, Value}; - - fn config_with(pairs: &[(&str, Value)]) -> Mapping { - let mut config = Mapping::new(); - for (key, value) in pairs { - config.insert(Value::from(*key), value.clone()); - } - config - } - - fn dns_with_ipv6(enabled: bool) -> Value { - let mut dns = Mapping::new(); - dns.insert(Value::from("ipv6"), Value::from(enabled)); - dns.insert(Value::from("enable"), Value::from(true)); - Value::Mapping(dns) - } - - #[test] - fn an_override_cannot_change_a_field_the_app_owns() { - let derived = config_with(&[("mode", Value::from("rule")), ("secret", Value::from("ours"))]); - let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new()); - - let overridden = config_with(&[("mode", Value::from("global")), ("secret", Value::from("theirs"))]); - let result = authoritative.enforce(overridden); - - assert_eq!(result.get(Value::from("mode")), Some(&Value::from("rule"))); - assert_eq!(result.get(Value::from("secret")), Some(&Value::from("ours"))); - } - - #[test] - fn an_override_cannot_introduce_a_field_the_app_left_out() { - // The app decided not to expose the external controller; a profile must not re-add it. - let derived = Mapping::new(); - let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new()); - - let overridden = config_with(&[("external-controller", Value::from("0.0.0.0:9090"))]); - let result = authoritative.enforce(overridden); - - assert!(!result.contains_key(Value::from("external-controller"))); - } - - #[test] - fn fields_the_app_does_not_own_survive_an_override() { - let derived = config_with(&[("mode", Value::from("rule"))]); - let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new()); - - let overridden = config_with(&[("mode", Value::from("global")), ("profile-key", Value::from(1))]); - let result = authoritative.enforce(overridden); - - assert_eq!(result.get(Value::from("profile-key")), Some(&Value::from(1))); - } - - #[test] - fn dns_ipv6_is_only_reclaimed_when_the_dns_page_owns_it() { - let derived = config_with(&[("dns", dns_with_ipv6(true))]); - - let owned = AuthoritativeFields::capture(&derived, &[], derived.clone()); - let restored = owned.enforce(config_with(&[("dns", dns_with_ipv6(false))])); - assert_eq!( - restored.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")), - Some(&Value::from(true)), - "with the DNS page on, the app's value wins" - ); - - let unowned = AuthoritativeFields::capture(&derived, &[], Mapping::new()); - let left_alone = unowned.enforce(config_with(&[("dns", dns_with_ipv6(false))])); - assert_eq!( - left_alone.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")), - Some(&Value::from(false)), - "with the DNS page off, an override may set it" - ); - } - - #[test] - fn restoring_dns_settings_reinstates_a_removed_dns_block() { - let derived = config_with(&[("dns", dns_with_ipv6(true))]); - let authoritative = AuthoritativeFields::capture(&derived, &[], derived.clone()); - - let result = authoritative.enforce(Mapping::new()); - - assert_eq!(result["dns"], derived["dns"]); - } -} - -#[allow(clippy::expect_used)] -#[cfg(test)] -mod tests { - use super::{ - AuthoritativeFields, ChainItem, ChainType, Mapping, cleanup_proxy_groups, ensure_lan_bind_address, - process_override_items, use_keys, - }; - use std::collections::HashMap; - use std::sync::Arc; - - fn mapping(yaml: &str) -> serde_yaml_ng::Mapping { - serde_yaml_ng::from_str(yaml).expect("test config should be valid") - } - - #[tokio::test] - async fn dns_settings_override_only_filled_fields_after_merge_and_script() { - let profile = mapping( - "dns: {nameserver: [9.9.9.9], nameserver-policy: {profile.example: 9.9.9.9}}\n\ - hosts: {profile.example: 192.0.2.1}", - ); - let settings = mapping( - "dns: {ipv6: true, nameserver: [8.8.8.8], nameserver-policy: {settings.example: 8.8.8.8},\n\ - proxy-server-nameserver: [], fallback: null, listen: ' '}\n\ - hosts: {settings.example: 192.0.2.2}", - ); - let merge = mapping( - "dns: {ipv6: false, nameserver-policy: {merge.example: 1.1.1.1}}\n\ - hosts: {merge.example: 192.0.2.3}", - ); - let script = r#"function main(config) { - config.dns = { - ipv6: false, - nameserver: ["4.4.4.4"], - "nameserver-policy": {"script.example": "4.4.4.4"}, - "proxy-server-nameserver": ["4.4.4.4"], - fallback: ["4.4.4.4"], - listen: "127.0.0.1:1053" - }; - config.hosts = {"script.example": "192.0.2.4"}; - return config; - }"#; - - for enabled in [false, true] { - let (config, dns_settings) = if enabled { - super::merge_dns_config(profile.clone(), settings.clone()) - } else { - (profile.clone(), Mapping::new()) - }; - let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); - let merge_item = |uid: &str| { - Arc::new(ChainItem { - uid: uid.into(), - data: ChainType::Merge(merge.clone()), - }) - }; - let profile_name = "test-profile"; - let (config, keys, logs) = process_override_items( - config, - vec![], - HashMap::new(), - merge_item("global-merge"), - Arc::new(ChainItem { - uid: "global-script".into(), - data: ChainType::Script(script.into()), - }), - profile_name, - &authoritative, - ) - .await; - let (config, _, logs) = process_override_items( - config, - keys, - logs, - merge_item("profile-merge"), - Arc::new(ChainItem { - uid: "profile-script".into(), - data: ChainType::Script(script.into()), - }), - profile_name, - &authoritative, - ) - .await; - let manual = config.clone(); - let result = authoritative.enforce(config); - - let source = if enabled { &settings } else { &manual }; - assert_eq!(result["dns"]["nameserver-policy"], source["dns"]["nameserver-policy"]); - assert_eq!(result["hosts"], source["hosts"]); - assert_eq!(result["dns"]["nameserver"], source["dns"]["nameserver"]); - assert_eq!(result["dns"]["ipv6"], serde_yaml_ng::Value::from(enabled)); - for key in ["proxy-server-nameserver", "fallback", "listen"] { - assert_eq!(result["dns"][key], manual["dns"][key]); - } - if enabled { - for uid in ["global-merge", "global-script", "profile-merge", "profile-script"] { - assert!( - logs[uid] - .iter() - .any(|(_, message)| message.contains("dns.nameserver-policy")) - ); - } - } - } - } - - #[tokio::test] - async fn manual_overrides_follow_expected_priority() { - let mut config = mapping( - r"{global-merge-wins: other, global-script-wins: other, profile-merge-wins: other, - profile-script-wins: other, nested: {winner: other}, dns: {enable: true}, tun: {enable: true}}", - ); - let exists_keys = use_keys(&config).collect(); - config.insert("application-only".into(), true.into()); - - let global_merge = Arc::new(ChainItem { - uid: "Merge".into(), - data: ChainType::Merge(mapping( - r"{global-merge-wins: global-merge, global-script-wins: global-merge, - profile-merge-wins: global-merge, profile-script-wins: global-merge, - nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}", - )), - }); - let global_script = Arc::new(ChainItem { - uid: "Script".into(), - data: ChainType::Script( - r#"function main(config) { - config["global-script-wins"] = "global-script"; - config["profile-merge-wins"] = "global-script"; - config["profile-script-wins"] = "global-script"; - config.nested.winner = "global-script"; - return config; - }"# - .into(), - ), - }); - let profile_merge = Arc::new(ChainItem { - uid: "profile-merge".into(), - data: ChainType::Merge(mapping( - r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge, - nested: {winner: profile-merge}}", - )), - }); - let profile_script = Arc::new(ChainItem { - uid: "profile-script".into(), - data: ChainType::Script( - r#"function main(config) { - config["profile-script-wins"] = "profile-script"; - config.nested.winner = "profile-script"; - return config; - }"# - .into(), - ), - }); - - let profile_name = "test-profile"; - let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new()); - let (config, exists_keys, result_map) = process_override_items( - config, - exists_keys, - HashMap::new(), - global_merge, - global_script, - profile_name, - &authoritative, - ) - .await; - let (config, exists_keys, _) = process_override_items( - config, - exists_keys, - result_map, - profile_merge, - profile_script, - profile_name, - &authoritative, - ) - .await; - - let string_value = |key| config.get(key).and_then(serde_yaml_ng::Value::as_str); - assert_eq!(string_value("global-merge-wins"), Some("global-merge")); - assert_eq!(string_value("global-script-wins"), Some("global-script")); - assert_eq!(string_value("profile-merge-wins"), Some("profile-merge")); - assert_eq!(string_value("profile-script-wins"), Some("profile-script")); - assert_eq!( - config - .get("nested") - .and_then(|value| value.get("winner")) - .and_then(serde_yaml_ng::Value::as_str), - Some("profile-script") - ); - assert!(!exists_keys.contains(&"application-only".into())); - } - - #[test] - fn control_plane_survives_manual_overrides() { - let app_config = mapping( - r#"{external-controller: "", - external-controller-cors: {allow-origins: ["app-only"]}, - mixed-port: 7890, socks-port: 7891, secret: "app-secret", mode: rule, allow-lan: false, - log-level: info, ipv6: false, unified-delay: true, - dns: {proxy-server-nameserver: ["1.1.1.1"]}}"#, - ); - let snapshot = super::snapshot_control_plane(&app_config); - - let hijacked = mapping( - r#"{external-controller: "0.0.0.0:9090", - external-controller-cors: {allow-origins: ["*"]}, - mixed-port: 1080, socks-port: 1080, secret: "hijacked", mode: global, allow-lan: true, - log-level: debug, ipv6: true, unified-delay: false, - dns: {proxy-server-nameserver: ["8.8.8.8"]}}"#, - ); - - let result = super::enforce_control_plane(hijacked, snapshot); - - let as_str = |key| result.get(key).and_then(serde_yaml_ng::Value::as_str); - assert_eq!(as_str("external-controller"), Some("")); - assert_eq!( - result.get("mixed-port").and_then(serde_yaml_ng::Value::as_u64), - Some(7890) - ); - assert_eq!( - result.get("socks-port").and_then(serde_yaml_ng::Value::as_u64), - Some(7891) - ); - assert_eq!( - result - .get("external-controller-cors") - .and_then(|value| value.get("allow-origins")) - .and_then(serde_yaml_ng::Value::as_sequence) - .and_then(|seq| seq.first()) - .and_then(serde_yaml_ng::Value::as_str), - Some("app-only") - ); - assert_eq!(as_str("secret"), Some("app-secret")); - assert_eq!(as_str("mode"), Some("rule")); - assert_eq!( - result.get("allow-lan").and_then(serde_yaml_ng::Value::as_bool), - Some(false) - ); - assert_eq!(as_str("log-level"), Some("info")); - assert_eq!(result.get("ipv6").and_then(serde_yaml_ng::Value::as_bool), Some(false)); - assert_eq!( - result.get("unified-delay").and_then(serde_yaml_ng::Value::as_bool), - Some(true) - ); - - // DNS 数据面不属于顶层控制面。 - assert_eq!( - result - .get("dns") - .and_then(|value| value.get("proxy-server-nameserver")) - .and_then(serde_yaml_ng::Value::as_sequence) - .and_then(|seq| seq.first()) - .and_then(serde_yaml_ng::Value::as_str), - Some("8.8.8.8") - ); - } - - #[test] - fn lan_bind_address_loopback_is_widened() { - for bind_address in [ - "localhost", - "127.0.0.1", - "127.0.0.2", - "127.1", - "::1", - "[::1]", - "0:0:0:0:0:0:0:1", - ] { - let result = ensure_lan_bind_address(mapping(&format!( - r#"{{allow-lan: true, bind-address: "{bind_address}"}}"# - ))); - - assert_eq!( - result.get("bind-address").and_then(serde_yaml_ng::Value::as_str), - Some("*"), - "bind-address {bind_address} should be widened" - ); - } - } - - #[test] - fn lan_bind_address_preserves_custom_or_disabled() { - let custom = ensure_lan_bind_address(mapping(r#"{allow-lan: true, bind-address: "192.168.1.2"}"#)); - assert_eq!( - custom.get("bind-address").and_then(serde_yaml_ng::Value::as_str), - Some("192.168.1.2") - ); - - let disabled = ensure_lan_bind_address(mapping(r#"{allow-lan: false, bind-address: "127.0.0.1"}"#)); - assert_eq!( - disabled.get("bind-address").and_then(serde_yaml_ng::Value::as_str), - Some("127.0.0.1") - ); - } - - #[test] - fn control_plane_removes_reenabled_disabled_port() { - let app_config = mapping(r"{mixed-port: 7890, mode: rule}"); - let snapshot = super::snapshot_control_plane(&app_config); - - let hijacked = mapping(r"{mixed-port: 7890, mode: rule, socks-port: 1080}"); - let result = super::enforce_control_plane(hijacked, snapshot); - - assert!(!result.contains_key("socks-port")); - assert_eq!( - result.get("mixed-port").and_then(serde_yaml_ng::Value::as_u64), - Some(7890) - ); - } - - #[test] - fn empty_dns_settings_leave_inherited_fields_overridable() { - let app_config = mapping(r#"{dns: {ipv6: false, proxy-server-nameserver: ["1.1.1.1"]}}"#); - let (config, dns_settings) = - super::merge_dns_config(app_config, mapping("dns: {ipv6: false, proxy-server-nameserver: []}")); - let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); - - let hijacked = mapping(r#"{dns: {ipv6: true, proxy-server-nameserver: ["8.8.8.8"]}}"#); - let result = authoritative.enforce(hijacked); - - assert_eq!( - result - .get("dns") - .and_then(|value| value.get("ipv6")) - .and_then(serde_yaml_ng::Value::as_bool), - Some(true) - ); - assert_eq!( - result - .get("dns") - .and_then(|value| value.get("proxy-server-nameserver")) - .and_then(serde_yaml_ng::Value::as_sequence) - .and_then(|seq| seq.first()) - .and_then(serde_yaml_ng::Value::as_str), - Some("8.8.8.8") - ); - } - - #[test] - fn snapshot_control_plane_skips_absent_keys() { - let app_config = mapping(r"{mode: rule, mixed-port: 7890}"); - let snapshot = super::snapshot_control_plane(&app_config); - assert!(snapshot.contains_key("mode")); - assert!(snapshot.contains_key("mixed-port")); - assert!(!snapshot.contains_key("secret")); - assert!(!snapshot.contains_key("allow-lan")); - } - - #[test] - fn remove_missing_proxies_from_groups() { - let config_str = r#" -proxies: - - name: "alive-node" - type: ss -proxy-groups: - - name: "manual" - type: select - proxies: - - "alive-node" - - "missing-node" - - "DIRECT" - - name: "nested" - type: select - proxies: - - "manual" - - "ghost" -"#; - - let mut config: serde_yaml_ng::Mapping = - serde_yaml_ng::from_str(config_str).expect("Failed to parse test yaml"); - config = cleanup_proxy_groups(config); - - let groups = config - .get("proxy-groups") - .and_then(|v| v.as_sequence()) - .cloned() - .expect("proxy-groups should be a sequence"); - - let manual_group = groups - .iter() - .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("manual")) - .and_then(|group| group.as_mapping()) - .expect("manual group should exist"); - - let manual_proxies = manual_group - .get("proxies") - .and_then(|v| v.as_sequence()) - .expect("manual proxies should be a sequence"); - - assert_eq!(manual_proxies.len(), 2); - assert!(manual_proxies.iter().any(|p| p.as_str() == Some("alive-node"))); - assert!(manual_proxies.iter().any(|p| p.as_str() == Some("DIRECT"))); - - let nested_group = groups - .iter() - .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("nested")) - .and_then(|group| group.as_mapping()) - .expect("nested group should exist"); - - let nested_proxies = nested_group - .get("proxies") - .and_then(|v| v.as_sequence()) - .expect("nested proxies should be a sequence"); - - assert_eq!(nested_proxies.len(), 1); - assert_eq!(nested_proxies[0].as_str(), Some("manual")); - } - - #[test] - fn keep_provider_backed_groups_intact() { - let config_str = r#" -proxy-providers: - providerA: - type: http - url: https://example.com - path: ./providerA.yaml -proxies: [] -proxy-groups: - - name: "manual" - type: select - use: - - "providerA" - - "ghostProvider" - proxies: - - "dynamic-node" - - "DIRECT" -"#; - - let mut config: serde_yaml_ng::Mapping = - serde_yaml_ng::from_str(config_str).expect("Failed to parse test yaml"); - config = cleanup_proxy_groups(config); - - let groups = config - .get("proxy-groups") - .and_then(|v| v.as_sequence()) - .cloned() - .expect("proxy-groups should be a sequence"); - - let manual_group = groups - .iter() - .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("manual")) - .and_then(|group| group.as_mapping()) - .expect("manual group should exist"); - - let uses = manual_group - .get("use") - .and_then(|v| v.as_sequence()) - .expect("use should be a sequence"); - assert_eq!(uses.len(), 1); - assert_eq!(uses[0].as_str(), Some("providerA")); - - let proxies = manual_group - .get("proxies") - .and_then(|v| v.as_sequence()) - .expect("proxies should be a sequence"); - assert_eq!(proxies.len(), 2); - assert!(proxies.iter().any(|p| p.as_str() == Some("dynamic-node"))); - assert!(proxies.iter().any(|p| p.as_str() == Some("DIRECT"))); - } - - #[test] - fn prune_invalid_provider_and_proxies_without_provider() { - let config_str = r#" -proxy-groups: - - name: "manual" - type: select - use: - - "ghost-provider" - proxies: - - "ghost-node" - - "DIRECT" -"#; - - let mut config: serde_yaml_ng::Mapping = - serde_yaml_ng::from_str(config_str).expect("Failed to parse test yaml"); - config = cleanup_proxy_groups(config); - - let groups = config - .get("proxy-groups") - .and_then(|v| v.as_sequence()) - .cloned() - .expect("proxy-groups should be a sequence"); - - let manual_group = groups - .iter() - .find(|group| group.get("name").and_then(serde_yaml_ng::Value::as_str) == Some("manual")) - .and_then(|group| group.as_mapping()) - .expect("manual group should exist"); - - let uses = manual_group - .get("use") - .and_then(|v| v.as_sequence()) - .expect("use should be a sequence"); - assert_eq!(uses.len(), 0); - - let proxies = manual_group - .get("proxies") - .and_then(|v| v.as_sequence()) - .expect("proxies should be a sequence"); - assert_eq!(proxies.len(), 1); - assert_eq!(proxies[0].as_str(), Some("DIRECT")); - } + Ok((config, exists_keys, logs, dns_override)) } diff --git a/src-tauri/src/feat/mod.rs b/src-tauri/src/feat/mod.rs index f9ce00d87..915c09fa9 100644 --- a/src-tauri/src/feat/mod.rs +++ b/src-tauri/src/feat/mod.rs @@ -9,6 +9,7 @@ mod icon; mod listener; mod profile; mod proxy; +pub(crate) mod proxy_view; mod subscription; mod tun; mod window; diff --git a/src-tauri/src/feat/proxy_view.rs b/src-tauri/src/feat/proxy_view.rs new file mode 100644 index 000000000..b42283842 --- /dev/null +++ b/src-tauri/src/feat/proxy_view.rs @@ -0,0 +1,170 @@ +mod groups; + +use clash_verge_proxy_view::{ + DelayHistory, ProviderSnapshot, ProxyCapabilities, ProxyProviderVehicleType, ProxySnapshot, ProxySubscriptionInfo, + ProxyViewInput, ProxyViewV1, +}; +use serde_yaml_ng::Mapping; +use std::future::Future; +use tauri_plugin_mihomo::{ + Result, + models::{Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType}, +}; + +pub(crate) async fn load_proxy_view( + config: Option<&Mapping>, + proxies: impl Future>, + providers: impl Future>, +) -> Result { + let (runtime_group_order, group_scopes) = groups::runtime_groups(config); + let (proxies, providers) = tokio::join!(proxies, providers); + let proxies = proxies?; + + Ok(ProxyViewInput { + runtime_group_order, + group_scopes, + proxies: proxies + .proxies + .into_iter() + .map(|(name, proxy)| (name.into(), proxy_snapshot(proxy))) + .collect(), + providers: providers.ok().map(|providers| { + providers + .providers + .into_iter() + .filter_map(|(name, provider)| provider_snapshot(provider).map(|snapshot| (name.into(), snapshot))) + .collect() + }), + } + .into_view()) +} + +fn proxy_snapshot(proxy: Proxy) -> ProxySnapshot { + ProxySnapshot { + name: proxy.name.into(), + proxy_type: match proxy.proxy_type { + ProxyType::Unknown(value) => value.into(), + proxy_type => proxy_type.as_str().into(), + }, + all: proxy.all.map(|all| all.into_iter().map(Into::into).collect()), + fixed: proxy.fixed.map(Into::into), + hidden: proxy.hidden, + icon: proxy.icon.map(Into::into), + now: proxy.now.map(Into::into), + test_url: proxy.test_url.map(Into::into), + id: proxy.id.map(Into::into), + history: proxy + .history + .into_iter() + .map(|entry| DelayHistory { + time: entry.time.into(), + delay: entry.delay, + }) + .collect(), + capabilities: ProxyCapabilities { + udp: proxy.udp, + xudp: proxy.xudp, + tfo: proxy.tfo, + mptcp: proxy.mptcp, + smux: proxy.smux, + }, + } +} + +fn provider_snapshot(provider: ProxyProvider) -> Option { + let vehicle_type = match provider.vehicle_type { + VehicleType::HTTP => ProxyProviderVehicleType::Http, + VehicleType::File => ProxyProviderVehicleType::File, + VehicleType::Inline => ProxyProviderVehicleType::Inline, + _ => return None, + }; + + Some(ProviderSnapshot { + vehicle_type, + proxies: provider.proxies.into_iter().map(proxy_snapshot).collect(), + updated_at: provider.updated_at.map(Into::into), + subscription_info: provider.subscription_info.map(|info| ProxySubscriptionInfo { + upload: info.upload, + download: info.download, + total: info.total, + expire: info.expire, + }), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use clash_verge_proxy_view::{ + ProxyMemberRef, ProxyMemberUnresolvedReason, ProxyNodeSource, ProxyViewProviderState, + }; + use std::future::ready; + use tauri_plugin_mihomo::Error; + + #[tokio::test] + async fn preserves_scoped_members_and_global_when_providers_are_unavailable() -> anyhow::Result<()> { + let config = serde_yaml_ng::from_str( + "proxy-providers: {z: {}, a: {}}\n\ + proxy-groups:\n\ + - {name: GLOBAL}\n\ + - {name: Select, use: [a]}\n\ + - {name: Another}\n\ + - {name: Select, use: [a], include-all-providers: true, exclude-type: Direct}", + )?; + let proxies = r#"{"proxies":{ + "GLOBAL":{"type":"Selector","all":["Select"]}, + "Select":{"type":"Selector","all":["shared"]}, + "Another":{"type":"Selector","all":[]} + }}"#; + let providers = serde_json::from_str( + r#"{"providers":{ + "a":{"vehicleType":"HTTP","proxies":[{"name":"shared","type":"Direct"}]}, + "z":{"vehicleType":"File","proxies":[{"name":"shared","type":"Shadowsocks"}]} + }}"#, + )?; + + let available = load_proxy_view( + Some(&config), + ready(Ok(serde_json::from_str(proxies)?)), + ready(Ok(providers)), + ) + .await?; + let unavailable = load_proxy_view( + Some(&config), + ready(Ok(serde_json::from_str(proxies)?)), + ready(Err(Error::FailedResponse("providers unavailable".into()))), + ) + .await?; + + for view in [&available, &unavailable] { + assert_eq!( + view.global.as_ref().map(|global| global.members.as_slice()), + Some([ProxyMemberRef::Group { name: "Select".into() }].as_slice()) + ); + assert_eq!(view.groups.len(), 2); + assert_eq!(view.groups[1].name.as_str(), "Another"); + assert_eq!(view.groups[0].name.as_str(), "Select"); + } + + assert_eq!(available.provider_state, ProxyViewProviderState::Ready); + let [ProxyMemberRef::Node { record_id, .. }] = available.groups[0].members.as_slice() else { + anyhow::bail!("expected the scoped provider member"); + }; + assert_eq!( + available.records.get(record_id).map(|record| &record.source), + Some(&ProxyNodeSource::Provider { + provider_name: "z".into(), + proxy_name: "shared".into(), + }) + ); + assert_eq!(unavailable.provider_state, ProxyViewProviderState::Unavailable); + assert_eq!( + unavailable.groups[0].members, + [ProxyMemberRef::Unresolved { + name: "shared".into(), + reason: ProxyMemberUnresolvedReason::ProviderUnavailable, + }] + ); + Ok(()) + } +} diff --git a/src-tauri/src/feat/proxy_view/groups.rs b/src-tauri/src/feat/proxy_view/groups.rs new file mode 100644 index 000000000..f35203775 --- /dev/null +++ b/src-tauri/src/feat/proxy_view/groups.rs @@ -0,0 +1,61 @@ +use clash_verge_proxy_view::GroupScope; +use serde_yaml_ng::Mapping; +use std::collections::BTreeMap; +use tristr::alias::String as ViewString; + +pub(super) fn runtime_groups(config: Option<&Mapping>) -> (Vec, BTreeMap) { + let mut order = Vec::new(); + let mut scopes = BTreeMap::new(); + let Some(config) = config else { return (order, scopes) }; + let Some(groups) = config.get("proxy-groups").and_then(|groups| groups.as_sequence()) else { + return (order, scopes); + }; + let mut all_providers = None; + let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true); + + for group in groups.iter().filter_map(|group| group.as_mapping()) { + let Some(name) = group.get("name").and_then(|name| name.as_str()) else { + continue; + }; + let name = ViewString::from(name); + // Mihomo sorts all providers when either flag replaces the explicit use list. + let providers = if flag(group, "include-all") || flag(group, "include-all-providers") { + all_providers + .get_or_insert_with(|| { + let mut names = config + .get("proxy-providers") + .and_then(|providers| providers.as_mapping()) + .into_iter() + .flat_map(|providers| providers.keys()) + .filter_map(|name| name.as_str()) + .map(ViewString::from) + .collect::>(); + names.sort(); + names + }) + .clone() + } else { + group + .get("use") + .and_then(|providers| providers.as_sequence()) + .into_iter() + .flatten() + .filter_map(|provider| provider.as_str()) + .map(ViewString::from) + .collect() + }; + let exclude_types = group + .get("exclude-type") + .and_then(|types| types.as_str()) + .filter(|types| !types.is_empty()) + .map_or_default(|types| types.split('|').map(ViewString::from).collect()); + let scope = GroupScope { + providers, + exclude_types, + }; + if scopes.insert(name.clone(), scope).is_none() && !name.is_empty() && name != "GLOBAL" { + order.push(name); + } + } + (order, scopes) +} diff --git a/src-tauri/src/ipc.rs b/src-tauri/src/ipc.rs index 102cf4b55..17c03a735 100644 --- a/src-tauri/src/ipc.rs +++ b/src-tauri/src/ipc.rs @@ -165,12 +165,6 @@ impl From for NetworkInterfaceView { } } -#[derive(serde::Serialize, serde::Deserialize, specta::Type)] -pub struct DelayHistory { - pub time: String, - pub delay: u16, -} - fn platform_types() -> specta::Types { use specta::datatype::{DataType, Fields}; let mut types = specta::Types::default().register::(); diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs index 106ec4669..b27afa301 100644 --- a/src-tauri/src/utils/mod.rs +++ b/src-tauri/src/utils/mod.rs @@ -21,4 +21,3 @@ pub mod tmpl; #[cfg(target_os = "macos")] pub mod tray_speed; pub mod window_manager; -pub mod yaml_emitter; diff --git a/src-tauri/src/utils/tmpl.rs b/src-tauri/src/utils/tmpl.rs index ddc4d5a42..3df027084 100644 --- a/src-tauri/src/utils/tmpl.rs +++ b/src-tauri/src/utils/tmpl.rs @@ -17,12 +17,7 @@ pub const ITEM_MERGE_EMPTY: &str = "# Profile Enhancement Merge Template for Cla "; -pub const ITEM_SCRIPT: &str = "// Define main function (script entry) - -function main(config, profileName) { - return config; -} -"; +pub use clash_verge_config_render::ITEM_SCRIPT; pub const ITEM_RULES: &str = "# Profile Enhancement Rules Template for Clash Verge