mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 10:40:14 +08:00
refactor(config): extract configuration renderer
Render from inputs supplied by the app, reuse the script crate, and preserve the default template fast path.
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use tristr::alias::String;
|
||||
|
||||
pub const HANDLE_FIELDS: [&str; 12] = [
|
||||
"mode",
|
||||
"redir-port",
|
||||
"tproxy-port",
|
||||
"mixed-port",
|
||||
"socks-port",
|
||||
"port",
|
||||
"allow-lan",
|
||||
"log-level",
|
||||
"ipv6",
|
||||
"external-controller",
|
||||
"secret",
|
||||
"unified-delay",
|
||||
];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
lowercased
|
||||
}
|
||||
|
||||
pub fn use_sort(mut config: Mapping) -> Mapping {
|
||||
let mut sorted = Mapping::new();
|
||||
HANDLE_FIELDS.into_iter().for_each(|key| {
|
||||
let key = Value::from(key);
|
||||
if let Some(value) = config.remove(&key) {
|
||||
sorted.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
let mut default_field_values = Mapping::new();
|
||||
for (key, value) in config {
|
||||
if let Some(key_str) = key.as_str() {
|
||||
if DEFAULT_FIELDS.contains(&key_str) {
|
||||
default_field_values.insert(key, value);
|
||||
} else if !HANDLE_FIELDS.contains(&key_str) {
|
||||
sorted.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DEFAULT_FIELDS.into_iter().for_each(|key| {
|
||||
let key = Value::from(key);
|
||||
if let Some(value) = default_field_values.remove(&key) {
|
||||
sorted.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
sorted
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn use_keys<'a>(config: &'a Mapping) -> impl Iterator<Item = String> + 'a {
|
||||
config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| {
|
||||
let mut s: String = s.into();
|
||||
s.make_ascii_lowercase();
|
||||
s
|
||||
})
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
use super::field::use_lowercase;
|
||||
use serde_yaml_ng::{self, Mapping, Value};
|
||||
|
||||
fn deep_merge(a: &mut Value, b: Value) {
|
||||
match (a, b) {
|
||||
(Value::Mapping(a_map), Value::Mapping(b_map)) => {
|
||||
for (key, value) in b_map {
|
||||
if let Some(existing) = a_map.get_mut(&key) {
|
||||
deep_merge(existing, value);
|
||||
} else {
|
||||
a_map.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
(a, b) => *a = b,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
|
||||
for (key, value) in use_lowercase(merge) {
|
||||
match (config.get_mut(&key), value) {
|
||||
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
|
||||
existing.extend(overlay);
|
||||
}
|
||||
(Some(existing), value) if key.as_str() != Some("hosts") => deep_merge(existing, value),
|
||||
(_, value) => {
|
||||
config.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge() -> anyhow::Result<()> {
|
||||
let merge = r"
|
||||
prepend-rules:
|
||||
- prepend
|
||||
- 1123123
|
||||
append-rules:
|
||||
- append
|
||||
prepend-proxies:
|
||||
- 9999
|
||||
append-proxies:
|
||||
- 1111
|
||||
rules:
|
||||
- replace
|
||||
proxy-groups:
|
||||
- 123781923810
|
||||
tun:
|
||||
enable: true
|
||||
dns:
|
||||
enable: true
|
||||
nameserver-policy:
|
||||
new.example: 1.1.1.1
|
||||
fallback-filter:
|
||||
geoip: false
|
||||
hosts:
|
||||
new.example: 192.0.2.2
|
||||
";
|
||||
|
||||
let config = r"
|
||||
rules:
|
||||
- aaaaa
|
||||
script1: test
|
||||
tun:
|
||||
mtu: 1500
|
||||
dns:
|
||||
nameserver: [9.9.9.9]
|
||||
nameserver-policy:
|
||||
old.example: 8.8.8.8
|
||||
fallback-filter:
|
||||
geoip: true
|
||||
domain: [old.example]
|
||||
hosts:
|
||||
old.example: 192.0.2.1
|
||||
";
|
||||
|
||||
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
||||
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
||||
|
||||
let result = use_merge(merge.clone(), config);
|
||||
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
|
||||
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
|
||||
assert_eq!(result["hosts"], merge["hosts"]);
|
||||
assert_eq!(result["dns"]["nameserver"], serde_yaml_ng::to_value(["9.9.9.9"])?);
|
||||
assert_eq!(result["tun"]["mtu"], Value::from(1500));
|
||||
assert_eq!(result["rules"], merge["rules"]);
|
||||
assert_eq!(result["script1"], Value::from("test"));
|
||||
|
||||
let cleared = serde_yaml_ng::from_str::<Mapping>(
|
||||
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
|
||||
)?;
|
||||
let result = use_merge(cleared.clone(), result);
|
||||
assert_eq!(result["dns"], cleared["dns"]);
|
||||
assert_eq!(result["hosts"], cleared["hosts"]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+74
-1701
File diff suppressed because it is too large
Load Diff
@@ -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<String>, Vec<(String, String)>);
|
||||
type EvalOutcome = (Result<Mapping, std::string::String>, 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::<Mapping>(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()
|
||||
}
|
||||
@@ -1,320 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::{Mapping, Sequence, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct SeqMap {
|
||||
pub prepend: Sequence,
|
||||
pub append: Sequence,
|
||||
pub delete: Vec<String>,
|
||||
}
|
||||
|
||||
fn collect_proxy_names(seq: &Sequence) -> Vec<String> {
|
||||
seq.iter()
|
||||
.filter_map(|item| match item {
|
||||
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(str::to_owned),
|
||||
Value::String(name) => Some(name.to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn is_selector_group(group_map: &Mapping) -> bool {
|
||||
group_map.get("type").and_then(Value::as_str).is_some_and(|value| {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value == "select" || value == "selector"
|
||||
})
|
||||
}
|
||||
|
||||
pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
let SeqMap {
|
||||
prepend,
|
||||
append,
|
||||
delete,
|
||||
} = seq;
|
||||
|
||||
let added_proxy_names = if field == "proxies" {
|
||||
let mut names = collect_proxy_names(&prepend);
|
||||
names.extend(collect_proxy_names(&append));
|
||||
let mut seen = HashSet::new();
|
||||
names
|
||||
.into_iter()
|
||||
.filter(|name| seen.insert(name.clone()))
|
||||
.collect::<Vec<String>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let mut updated_items = Sequence::new();
|
||||
updated_items.extend(prepend);
|
||||
|
||||
if let Some(Value::Sequence(existing_items)) = config.remove(field) {
|
||||
// Filter out deleted items
|
||||
let kept_items: Sequence = existing_items
|
||||
.into_iter()
|
||||
.filter(|item| {
|
||||
if let Value::String(s) = item {
|
||||
!delete.contains(s)
|
||||
} else if let Value::Mapping(m) = item {
|
||||
if let Some(Value::String(name)) = m.get("name") {
|
||||
!delete.contains(name)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
updated_items.extend(kept_items);
|
||||
}
|
||||
|
||||
updated_items.extend(append);
|
||||
config.insert(Value::String(field.into()), Value::Sequence(updated_items));
|
||||
|
||||
if field != "proxies" {
|
||||
return config;
|
||||
}
|
||||
|
||||
let Some(proxy_groups_value) = config.remove("proxy-groups") else {
|
||||
return config;
|
||||
};
|
||||
|
||||
let Value::Sequence(proxy_groups) = proxy_groups_value else {
|
||||
config.insert(Value::String("proxy-groups".into()), proxy_groups_value);
|
||||
return config;
|
||||
};
|
||||
|
||||
let mut updated_groups = Sequence::new();
|
||||
let mut appended_to_selector = false;
|
||||
for group in proxy_groups {
|
||||
if let Value::Mapping(mut group_map) = group {
|
||||
let mut group_proxies = match group_map.remove("proxies") {
|
||||
Some(Value::Sequence(proxies)) => Some(
|
||||
proxies
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
if let Value::String(name) = p {
|
||||
!delete.contains(name)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect::<Sequence>(),
|
||||
),
|
||||
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 {
|
||||
updated_groups.push(group);
|
||||
}
|
||||
}
|
||||
config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups));
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[allow(unused_imports)]
|
||||
use serde_yaml_ng::Value;
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn test_delete_proxy_and_references() {
|
||||
let config_str = r#"
|
||||
proxies:
|
||||
- name: "proxy1"
|
||||
type: "ss"
|
||||
- name: "proxy2"
|
||||
type: "vmess"
|
||||
proxy-groups:
|
||||
- name: "group1"
|
||||
type: "select"
|
||||
proxies:
|
||||
- "proxy1"
|
||||
- "proxy2"
|
||||
- name: "group2"
|
||||
type: "select"
|
||||
proxies:
|
||||
- "proxy1"
|
||||
"#;
|
||||
let mut config: Mapping = serde_yaml_ng::from_str(config_str).expect("Failed to parse test config YAML");
|
||||
|
||||
let seq = SeqMap {
|
||||
prepend: Sequence::new(),
|
||||
append: Sequence::new(),
|
||||
delete: vec!["proxy1".to_string()],
|
||||
};
|
||||
|
||||
config = use_seq(seq, config, "proxies");
|
||||
|
||||
// Check if proxy1 is removed from proxies
|
||||
let proxies = config
|
||||
.get("proxies")
|
||||
.expect("proxies field should exist")
|
||||
.as_sequence()
|
||||
.expect("proxies should be a sequence");
|
||||
assert_eq!(proxies.len(), 1);
|
||||
assert_eq!(
|
||||
proxies[0]
|
||||
.as_mapping()
|
||||
.expect("proxy should be a mapping")
|
||||
.get("name")
|
||||
.expect("proxy should have name")
|
||||
.as_str()
|
||||
.expect("name should be string"),
|
||||
"proxy2"
|
||||
);
|
||||
|
||||
// Check if proxy1 is removed from all groups
|
||||
let groups = config
|
||||
.get("proxy-groups")
|
||||
.expect("proxy-groups field should exist")
|
||||
.as_sequence()
|
||||
.expect("proxy-groups should be a sequence");
|
||||
let group1_proxies = groups[0]
|
||||
.as_mapping()
|
||||
.expect("group should be a mapping")
|
||||
.get("proxies")
|
||||
.expect("group should have proxies")
|
||||
.as_sequence()
|
||||
.expect("group proxies should be a sequence");
|
||||
let group2_proxies = groups[1]
|
||||
.as_mapping()
|
||||
.expect("group should be a mapping")
|
||||
.get("proxies")
|
||||
.expect("group should have proxies")
|
||||
.as_sequence()
|
||||
.expect("group proxies should be a sequence");
|
||||
|
||||
assert_eq!(group1_proxies.len(), 1);
|
||||
assert_eq!(
|
||||
group1_proxies[0].as_str().expect("proxy name should be string"),
|
||||
"proxy2"
|
||||
);
|
||||
assert_eq!(group2_proxies.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn test_add_new_proxies_to_first_selector_group() {
|
||||
let config_str = r#"
|
||||
proxies:
|
||||
- name: "proxy1"
|
||||
type: "ss"
|
||||
proxy-groups:
|
||||
- name: "group1"
|
||||
type: "select"
|
||||
proxies:
|
||||
- "proxy1"
|
||||
- name: "group2"
|
||||
type: "select"
|
||||
proxies:
|
||||
- "proxy1"
|
||||
"#;
|
||||
let mut config: Mapping = serde_yaml_ng::from_str(config_str).expect("Failed to parse test config YAML");
|
||||
|
||||
let prepend: Sequence = serde_yaml_ng::from_str(
|
||||
r#"
|
||||
- name: "proxy3"
|
||||
type: "ss"
|
||||
"#,
|
||||
)
|
||||
.expect("Failed to parse prepend proxies");
|
||||
|
||||
let append: Sequence = serde_yaml_ng::from_str(
|
||||
r#"
|
||||
- name: "proxy4"
|
||||
type: "vmess"
|
||||
"#,
|
||||
)
|
||||
.expect("Failed to parse append proxies");
|
||||
|
||||
let seq = SeqMap {
|
||||
prepend,
|
||||
append,
|
||||
delete: vec![],
|
||||
};
|
||||
|
||||
config = use_seq(seq, config, "proxies");
|
||||
|
||||
let groups = config
|
||||
.get("proxy-groups")
|
||||
.expect("proxy-groups field should exist")
|
||||
.as_sequence()
|
||||
.expect("proxy-groups should be a sequence");
|
||||
let group1_proxies = groups[0]
|
||||
.as_mapping()
|
||||
.expect("group should be a mapping")
|
||||
.get("proxies")
|
||||
.expect("group should have proxies")
|
||||
.as_sequence()
|
||||
.expect("group proxies should be a sequence");
|
||||
let names: Vec<&str> = group1_proxies.iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(names, vec!["proxy3", "proxy4", "proxy1"]);
|
||||
|
||||
let group2_proxies = groups[1]
|
||||
.as_mapping()
|
||||
.expect("group should be a mapping")
|
||||
.get("proxies")
|
||||
.expect("group should have proxies")
|
||||
.as_sequence()
|
||||
.expect("group proxies should be a sequence");
|
||||
let names: Vec<&str> = group2_proxies.iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(names, vec!["proxy1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::expect_used)]
|
||||
fn test_preserve_non_sequence_proxy_groups() {
|
||||
let config_str = r#"
|
||||
proxies:
|
||||
- name: "proxy1"
|
||||
type: "ss"
|
||||
proxy-groups: "invalid"
|
||||
"#;
|
||||
let mut config: Mapping = serde_yaml_ng::from_str(config_str).expect("Failed to parse test config YAML");
|
||||
|
||||
let seq = SeqMap {
|
||||
prepend: Sequence::new(),
|
||||
append: Sequence::new(),
|
||||
delete: vec!["proxy1".to_string()],
|
||||
};
|
||||
|
||||
config = use_seq(seq, config, "proxies");
|
||||
|
||||
assert_eq!(config.get("proxy-groups").and_then(Value::as_str), Some("invalid"));
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
|
||||
macro_rules! revise {
|
||||
($map: expr, $key: expr, $val: expr) => {
|
||||
let ret_key = Value::String($key.into());
|
||||
$map.insert(ret_key, Value::from($val));
|
||||
};
|
||||
}
|
||||
|
||||
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||
let mut tun_val = super::take_mapping(&mut config, "tun");
|
||||
|
||||
if enable {
|
||||
let mut dns_val = super::take_mapping(&mut config, "dns");
|
||||
let ipv6_key = Value::from("ipv6");
|
||||
let ipv6_val = config.get(&ipv6_key).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
|
||||
let current_mode = dns_val
|
||||
.get(Value::from("enhanced-mode"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("fake-ip");
|
||||
|
||||
if current_mode == "fake-ip" {
|
||||
revise!(dns_val, "enable", true);
|
||||
revise!(dns_val, "ipv6", ipv6_val);
|
||||
|
||||
if !dns_val.contains_key(Value::from("enhanced-mode")) {
|
||||
revise!(dns_val, "enhanced-mode", "fake-ip");
|
||||
}
|
||||
|
||||
if !dns_val.contains_key(Value::from("fake-ip-range")) {
|
||||
revise!(dns_val, "fake-ip-range", "198.18.0.1/16");
|
||||
}
|
||||
|
||||
if ipv6_val && !dns_val.contains_key(Value::from("fake-ip-range6")) {
|
||||
revise!(dns_val, "fake-ip-range6", "2001:2::0/64");
|
||||
}
|
||||
}
|
||||
|
||||
revise!(config, "dns", dns_val);
|
||||
}
|
||||
|
||||
revise!(tun_val, "enable", enable);
|
||||
revise!(config, "tun", tun_val);
|
||||
|
||||
config
|
||||
}
|
||||
Reference in New Issue
Block a user