diff --git a/Cargo.lock b/Cargo.lock index d708f5665..958ff7a96 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1089,9 +1089,9 @@ dependencies = [ "async-trait", "backon", "base64 0.23.1", - "boa_engine", "bytes", "chrono", + "clash-verge-config-render", "clash-verge-draft", "clash-verge-i18n", "clash-verge-limiter", @@ -1169,6 +1169,20 @@ dependencies = [ "zip", ] +[[package]] +name = "clash-verge-config-render" +version = "0.1.0" +dependencies = [ + "clash-verge-logging", + "clash-verge-profile-script", + "log", + "serde", + "serde_json", + "serde_yaml_ng", + "tokio", + "tristr", +] + [[package]] name = "clash-verge-draft" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0fc4fc3bc..ab25e4af0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "crates/clash-verge-limiter", "crates/clash-verge-subscription", "crates/clash-verge-runtime-bundle", + "crates/clash-verge-config-render", "crates/clash-verge-profile-script", ] resolver = "2" @@ -55,6 +56,7 @@ split-debuginfo = "unpacked" muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" } [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" } diff --git a/crates/clash-verge-config-render/Cargo.toml b/crates/clash-verge-config-render/Cargo.toml new file mode 100644 index 000000000..66d2120cc --- /dev/null +++ b/crates/clash-verge-config-render/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "clash-verge-config-render" +version = "0.1.0" +edition = "2024" + +[dependencies] +clash-verge-profile-script = { workspace = true } +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 83% rename from src-tauri/src/enhance/field.rs rename to crates/clash-verge-config-render/src/field.rs index e37c49700..1424d2d73 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 } 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..5234c18cc --- /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 field::use_keys; +pub use seq::SeqMap; + +use self::{ + field::{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 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 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(), + ) +} + +/// 手动 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(profile: RenderProfile, settings: RenderSettings, dns_config: Option) -> 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 = 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) = 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); + + let (config, exists_keys, result_map) = process_override_items( + config, + exists_keys, + result_map, + global_merge, + global_script, + profile_name.as_str(), + &authoritative, + ) + .await; + + let (config, exists_keys, result_map) = process_override_items( + config, + exists_keys, + result_map, + merge_item, + script_item, + profile_name.as_str(), + &authoritative, + ) + .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: exists_keys.into_iter().collect(), + logs: result_map, + 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 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 { + 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 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")); + } +} 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..ffabad583 --- /dev/null +++ b/crates/clash-verge-config-render/src/script.rs @@ -0,0 +1,52 @@ +use super::field::use_lowercase; +use clash_verge_profile_script::{ScriptLogs, execute}; +use serde_yaml_ng::Mapping; +use tristr::alias::String; + +type ScriptResult = (Mapping, Vec, ScriptLogs); + +/// 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 == 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) + } + } +} diff --git a/src-tauri/src/enhance/seq.rs b/crates/clash-verge-config-render/src/seq.rs similarity index 79% rename from src-tauri/src/enhance/seq.rs rename to crates/clash-verge-config-render/src/seq.rs index 11e083151..4cecb9924 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,11 +10,11 @@ pub struct SeqMap { pub delete: Vec, } -fn collect_proxy_names(seq: &Sequence) -> 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()), + Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(TriStr::from), + Value::String(name) => Some(TriStr::from(name.as_str())), _ => None, }) .collect() @@ -40,7 +41,7 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping { names .into_iter() .filter(|name| seen.insert(name.clone())) - .collect::>() + .collect::>() } else { Vec::new() }; @@ -88,56 +89,56 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping { 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 - } - 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; - } - - if let Some(group_proxies) = group_proxies { - group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies)); - } - updated_groups.push(Value::Mapping(group_map)); - } else { + let Value::Mapping(mut group_map) = group else { updated_groups.push(group); + continue; + }; + 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 + } + 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)); + } + updated_groups.push(Value::Mapping(group_map)); } config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups)); diff --git a/src-tauri/src/enhance/tun.rs b/crates/clash-verge-config-render/src/tun.rs similarity index 79% rename from src-tauri/src/enhance/tun.rs rename to crates/clash-verge-config-render/src/tun.rs index 61362c9b5..0773079d6 100644 --- a/src-tauri/src/enhance/tun.rs +++ b/crates/clash-verge-config-render/src/tun.rs @@ -45,3 +45,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/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7afa9657e..23e78dd7f 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -38,6 +38,7 @@ 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 } tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true } @@ -65,7 +66,6 @@ dirs = "7.0.0" dunce = "1.0.5" nanoid = "0.5" chrono = { workspace = true } -boa_engine = { workspace = true } http-body-util = "0.1.5" percent-encoding = "2.3.2" reqwest = { workspace = true } diff --git a/src-tauri/src/config/runtime.rs b/src-tauri/src/config/runtime.rs index 0fbcb9811..6ac4aefbf 100644 --- a/src-tauri/src/config/runtime.rs +++ b/src-tauri/src/config/runtime.rs @@ -2,7 +2,7 @@ use serde_yaml_ng::{Mapping, Value}; use std::collections::{HashMap, HashSet}; use tristr::alias::String; -use crate::enhance::field::use_keys; +use clash_verge_config_render::use_keys; const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"]; 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/enhance/chain.rs b/src-tauri/src/enhance/chain.rs index d4f3781b4..5bc3c61df 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, diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index ed541cf4f..1c6a39ecc 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::AsyncChainItemFrom as _; 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}, @@ -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()), + }), } } @@ -152,26 +115,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 = profiles @@ -203,7 +168,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, @@ -212,7 +177,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,), @@ -224,7 +189,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, @@ -237,209 +202,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, @@ -472,375 +234,17 @@ 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. @@ -848,1053 +252,22 @@ pub async fn enhance( 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, - ) - .await; + logs, + discarded_keys, + } = render(profile, settings.render, dns_config).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/enhance/script.rs b/src-tauri/src/enhance/script.rs deleted file mode 100644 index 4cc366491..000000000 --- a/src-tauri/src/enhance/script.rs +++ /dev/null @@ -1,255 +0,0 @@ -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 tristr::alias::String; - -const MAX_OUTPUTS: usize = 1000; -const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB -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)>); - -/// 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![]); - } - - 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 { - Ok(Ok(evaluated)) => evaluated, - Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]), - Err(_elapsed) => ( - 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) - } - } -} - -/// Console logs survive every failure path. -fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) -> EvalOutcome { - let mut context = Context::default(); - - context - .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 _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe { - NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| { - let level = args - .first() - .ok_or_else(|| boa_engine::JsError::from_opaque(JsString::from("Missing level argument").into()))?; - let level = level.to_string(context)?; - let level = level.to_std_string().map_err(|_| { - boa_engine::JsError::from_opaque(JsString::from("Failed to convert level to string").into()) - })?; - - let data = args - .get(1) - .ok_or_else(|| boa_engine::JsError::from_opaque(JsString::from("Missing data argument").into()))?; - let data = data.to_string(context)?; - let data = data.to_std_string().map_err(|_| { - boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into()) - })?; - - // 检查输出限制 - if outputs_clone.lock().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(); - 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())); - Ok(JsValue::undefined()) - }) - }); - - let _ = context.eval(Source::from_bytes( - r#"var console = Object.freeze({ - log(data){__verge_log__("log",JSON.stringify(data, null, 2))}, - info(data){__verge_log__("info",JSON.stringify(data, null, 2))}, - error(data){__verge_log__("error",JSON.stringify(data, null, 2))}, - debug(data){__verge_log__("debug",JSON.stringify(data, null, 2))}, - warn(data){__verge_log__("warn",JSON.stringify(data, null, 2))}, - table(data){__verge_log__("table",JSON.stringify(data, null, 2))}, - });"#, - )); - - let config_value = match JsValue::from_json(config_json, &mut context) { - Ok(value) => value, - Err(err) => return bail(format!("failed to bind config for script: {err}")), - }; - if let Err(err) = context.register_global_property(js_string!("__verge_config__"), config_value, Attribute::all()) { - 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 { - return bail("Name parameter too long".to_owned()); - } - - let code = format!( - r"try{{ - {script}; - main(globalThis.__verge_config__,'{safe_name}') - }} catch(err) {{ - `__error_flag__ ${{err.toString()}}` - }}" - ); - - let result = match context.eval(Source::from_bytes(code.as_str())) { - Ok(result) => result, - Err(err) => { - logging!( - error, - Type::Config, - "Script execution error: {err}. Script name: {name}" - ); - return bail("Script execution failed".to_owned()); - } - }; - // The JS wrapper funnels exceptions into a marker string; surface its text. - if result.is_string() { - let text = result - .to_string(&mut context) - .ok() - .and_then(|text| text.to_std_string().ok()) - .unwrap_or_default(); - if text.trim_start().starts_with("__error_flag__") { - logging!( - error, - Type::Config, - "Script execution error: {}. Script name: {name}", - text.trim_start()["__error_flag__".len()..].trim() - ); - return bail("Script execution failed".to_owned()); - } - } - if !result.is_object() { - return bail("main function should return object".to_owned()); - } - let result = match result.to_json(&mut context) { - Ok(Some(result)) => result, - Ok(None) => return bail("main function should return object".to_owned()), - Err(err) => { - logging!( - error, - Type::Config, - "Script execution error: {err}. Script name: {name}" - ); - return bail("Script execution failed".to_owned()); - } - }; - if json_approx_size(&result) > MAX_JSON_SIZE { - return bail("Script result exceeds maximum allowed size".to_owned()); - } - - match serde_json::from_value::(result) { - Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()), - Err(err) => { - logging!( - error, - Type::Config, - "Script execution error: {err:#}. Script name: {name}" - ); - bail("Script execution failed".to_owned()) - } - } -} - -/// Serialized-size estimate without building the serialized string; a DoS guard, not an exact byte count. -fn json_approx_size(value: &serde_json::Value) -> usize { - match value { - serde_json::Value::String(s) => s.len() + 2, - serde_json::Value::Object(map) => map - .iter() - .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::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(); - } - - s.replace('\\', "\\\\") - .replace('\'', "\\'") - .replace('\n', "\\n") // 添加换行符转义 - .replace('\r', "\\r") // 添加回车转义 - .into() -} 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