mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-04 21:30:06 +08:00
chore: merge runtime base into storage branch
This commit is contained in:
@@ -41,7 +41,7 @@ pub fn use_sort(mut config: Mapping) -> Mapping {
|
||||
let mut sorted = Mapping::new();
|
||||
HANDLE_FIELDS.into_iter().for_each(|key| {
|
||||
let key = Value::from(key);
|
||||
if let Some(value) = config.remove(&key) {
|
||||
if let Some(value) = config.shift_remove(&key) {
|
||||
sorted.insert(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -882,6 +882,15 @@ mod use_tun_tests {
|
||||
Some(&Value::from("2001:2::0/64"))
|
||||
);
|
||||
|
||||
let blank_range = mapping(&[
|
||||
("ipv6", Value::from(true)),
|
||||
("dns", Value::Mapping(mapping(&[("fake-ip-range6", Value::from(" "))]))),
|
||||
]);
|
||||
assert_eq!(
|
||||
use_tun(blank_range, true)["dns"]["fake-ip-range6"],
|
||||
Value::from("2001:2::0/64")
|
||||
);
|
||||
|
||||
let without_ipv6 = use_tun(Mapping::new(), true);
|
||||
let dns = dns_of(&without_ipv6).expect("dns should be written");
|
||||
assert!(!dns.contains_key(Value::from("fake-ip-range6")));
|
||||
@@ -938,7 +947,7 @@ mod use_sort_tests {
|
||||
#[test]
|
||||
fn sorting_is_stable_when_applied_twice() {
|
||||
let mut config = Mapping::new();
|
||||
for key in ["proxies", "mode", "unknown-key", "rules"] {
|
||||
for key in ["mode", "dns", "tun", "hosts"] {
|
||||
config.insert(Value::from(key), Value::from(1));
|
||||
}
|
||||
|
||||
|
||||
@@ -43,9 +43,12 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let mut updated_items = prepend;
|
||||
if let Some(Value::Sequence(existing_items)) = config.remove(field) {
|
||||
updated_items.extend(existing_items.into_iter().filter(|item| {
|
||||
let mut updated_items = match config.remove(field) {
|
||||
Some(Value::Sequence(items)) => items,
|
||||
_ => Sequence::new(),
|
||||
};
|
||||
if !delete.is_empty() {
|
||||
updated_items.retain(|item| {
|
||||
let name = match item {
|
||||
Value::String(name) => Some(name),
|
||||
Value::Mapping(mapping) => match mapping.get("name") {
|
||||
@@ -55,8 +58,9 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
_ => None,
|
||||
};
|
||||
name.is_none_or(|name| !delete.contains(name))
|
||||
}));
|
||||
});
|
||||
}
|
||||
updated_items.splice(..0, prepend);
|
||||
updated_items.extend(append);
|
||||
config.insert(Value::String(field.into()), Value::Sequence(updated_items));
|
||||
|
||||
@@ -68,31 +72,23 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
return config;
|
||||
};
|
||||
|
||||
let Value::Sequence(proxy_groups) = proxy_groups_value else {
|
||||
let Value::Sequence(mut proxy_groups) = proxy_groups_value else {
|
||||
config.insert(Value::String("proxy-groups".into()), proxy_groups_value);
|
||||
return config;
|
||||
};
|
||||
|
||||
let mut updated_groups = Sequence::new();
|
||||
let mut appended_to_selector = false;
|
||||
for group in proxy_groups {
|
||||
let Value::Mapping(mut group_map) = group else {
|
||||
updated_groups.push(group);
|
||||
for group in &mut proxy_groups {
|
||||
let Value::Mapping(group_map) = group else {
|
||||
continue;
|
||||
};
|
||||
let mut group_proxies = match group_map.remove("proxies") {
|
||||
Some(Value::Sequence(proxies)) => Some(
|
||||
proxies
|
||||
.into_iter()
|
||||
.filter(|p| {
|
||||
if let Value::String(name) = p {
|
||||
!delete.contains(name)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect::<Sequence>(),
|
||||
),
|
||||
Some(Value::Sequence(mut proxies)) => {
|
||||
if !delete.is_empty() {
|
||||
proxies.retain(|member| !matches!(member, Value::String(name) if delete.contains(name)));
|
||||
}
|
||||
Some(proxies)
|
||||
}
|
||||
Some(value) => {
|
||||
group_map.insert(Value::String("proxies".into()), value);
|
||||
None
|
||||
@@ -100,7 +96,7 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
None => None,
|
||||
};
|
||||
|
||||
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(&group_map) {
|
||||
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();
|
||||
@@ -125,9 +121,8 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
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));
|
||||
config.insert(Value::String("proxy-groups".into()), Value::Sequence(proxy_groups));
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
@@ -32,9 +32,7 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||
revise!(dns_val, "fake-ip-range", "198.18.0.1/16");
|
||||
}
|
||||
|
||||
if ipv6_val && !dns_val.contains_key(Value::from("fake-ip-range6")) {
|
||||
revise!(dns_val, "fake-ip-range6", "2001:2::0/64");
|
||||
}
|
||||
super::ensure_fake_ip_range6(&mut dns_val);
|
||||
}
|
||||
|
||||
revise!(config, "dns", dns_val);
|
||||
|
||||
@@ -7,6 +7,7 @@ use tristr::alias::String;
|
||||
|
||||
const MAX_OUTPUTS: usize = 1000;
|
||||
const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB
|
||||
const MAX_PROFILE_NAME_BYTES: usize = 1024;
|
||||
const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB
|
||||
const MAX_LOOP_ITERATIONS: u64 = 10_000_000;
|
||||
const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
@@ -22,16 +23,19 @@ pub enum MainDeclaration {
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// Preserves the editor's evaluation and main-declaration check.
|
||||
/// Evaluates the source and checks that the entry point is callable.
|
||||
pub fn validate(source: &str) -> Result<MainDeclaration, std::string::String> {
|
||||
let mut context = Context::default();
|
||||
let _ = context.eval(Source::from_bytes(
|
||||
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});",
|
||||
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){},warn(...data){},table(...data){}});",
|
||||
));
|
||||
context
|
||||
.eval(Source::from_bytes(source))
|
||||
.map_err(|err| err.to_string())?;
|
||||
let has_main = source.contains("function main") || source.contains("const main") || source.contains("let main");
|
||||
let has_main = context
|
||||
.eval(Source::from_bytes("typeof main === 'function'"))
|
||||
.map_err(|err| err.to_string())?
|
||||
.to_boolean();
|
||||
Ok(if has_main {
|
||||
MainDeclaration::Present
|
||||
} else {
|
||||
@@ -128,10 +132,9 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
||||
return bail(format!("failed to bind config for script: {err}"));
|
||||
}
|
||||
|
||||
let escaped_profile_name = escape_js_string_for_single_quote(name);
|
||||
if escaped_profile_name.len() > 1024 {
|
||||
let Some(escaped_profile_name) = escape_profile_name(name) else {
|
||||
return bail("Name parameter too long".to_owned());
|
||||
}
|
||||
};
|
||||
|
||||
let code = format!(
|
||||
r"try{{
|
||||
@@ -211,27 +214,56 @@ fn json_approx_size(value: &serde_json::Value) -> usize {
|
||||
.map(|(key, value)| key.len() + 4 + json_approx_size(value))
|
||||
.sum(),
|
||||
serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(),
|
||||
serde_json::Value::Number(n) => n.to_string().len(),
|
||||
serde_json::Value::Number(n) => {
|
||||
if let Some(n) = n.as_u64() {
|
||||
n.checked_ilog10().unwrap_or(0) as usize + 1
|
||||
} else if let Some(n) = n.as_i64() {
|
||||
n.unsigned_abs().checked_ilog10().unwrap_or(0) as usize + 2
|
||||
} else {
|
||||
n.to_string().len()
|
||||
}
|
||||
}
|
||||
serde_json::Value::Bool(_) | serde_json::Value::Null => 4,
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_js_string_for_single_quote(s: &str) -> String {
|
||||
if s.len() > 10240 {
|
||||
return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into();
|
||||
fn escape_profile_name(name: &str) -> Option<String> {
|
||||
if name.len() > MAX_PROFILE_NAME_BYTES {
|
||||
return None;
|
||||
}
|
||||
|
||||
s.replace('\\', "\\\\")
|
||||
let escaped = name
|
||||
.replace('\\', "\\\\")
|
||||
.replace('\'', "\\'")
|
||||
.replace('\n', "\\n")
|
||||
.replace('\r', "\\r")
|
||||
.into()
|
||||
.replace('\r', "\\r");
|
||||
(escaped.len() <= MAX_PROFILE_NAME_BYTES).then(|| escaped.into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MainDeclaration, eval_script, validate};
|
||||
|
||||
#[test]
|
||||
fn profile_name_limit_counts_escaped_bytes() {
|
||||
assert!(super::escape_profile_name(&"订阅".repeat(171)).is_none());
|
||||
assert!(super::escape_profile_name(&"'".repeat(512)).is_some());
|
||||
assert!(super::escape_profile_name(&"'".repeat(513)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_size_matches_the_rendered_number() {
|
||||
for number in [
|
||||
0.into(),
|
||||
10.into(),
|
||||
(-10).into(),
|
||||
i64::MIN.into(),
|
||||
u64::MAX.into(),
|
||||
serde_json::json!(1.25),
|
||||
] {
|
||||
assert_eq!(super::json_approx_size(&number), number.to_string().len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn console_entries_survive_a_script_error() {
|
||||
let (result, logs) = eval_script(
|
||||
@@ -243,6 +275,24 @@ mod tests {
|
||||
assert_eq!(logs, [("log".into(), "1".into()), ("warn".into(), "2".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_checks_the_evaluated_main_binding() {
|
||||
assert_eq!(
|
||||
validate("const main = config => config;"),
|
||||
Ok(MainDeclaration::Present)
|
||||
);
|
||||
assert_eq!(validate("// function main goes here"), Ok(MainDeclaration::Missing));
|
||||
assert_eq!(validate("const main = 42;"), Ok(MainDeclaration::Missing));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_supports_console_methods_at_top_level() {
|
||||
assert_eq!(
|
||||
validate("console.warn('setup'); console.table([1]); function main(config) { return config; }"),
|
||||
Ok(MainDeclaration::Present)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_distinguishes_missing_main_from_evaluation_failure() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -209,8 +209,8 @@ struct MemberResolver<'a> {
|
||||
|
||||
impl<'a> MemberResolver<'a> {
|
||||
/// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`.
|
||||
fn scoped_candidates(&self, group: &str, name: &str) -> Vec<&'a String> {
|
||||
let (Some(scope), Some(candidates)) = (self.group_scopes.get(group), self.provider_candidates.get(name)) else {
|
||||
fn scoped_candidates(&self, group: &str, candidates: &'a [(String, String)]) -> Vec<&'a String> {
|
||||
let Some(scope) = self.group_scopes.get(group) else {
|
||||
return Vec::new();
|
||||
};
|
||||
scope
|
||||
@@ -230,7 +230,12 @@ impl<'a> MemberResolver<'a> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolve(&self, name: String, scoped: Option<&String>) -> ProxyMemberRef {
|
||||
fn resolve(
|
||||
&self,
|
||||
group: &str,
|
||||
name: String,
|
||||
seen: &mut BTreeMap<String, (usize, Vec<&'a String>)>,
|
||||
) -> ProxyMemberRef {
|
||||
if self.group_names.contains(&name) {
|
||||
ProxyMemberRef::Group { name }
|
||||
} else if let Some(record_id) = self.core_node_ids.get(&name) {
|
||||
@@ -245,16 +250,30 @@ impl<'a> MemberResolver<'a> {
|
||||
}
|
||||
} else {
|
||||
let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice);
|
||||
match (scoped, candidates) {
|
||||
(Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node {
|
||||
let record_id = match candidates {
|
||||
[(_, record_id)] => Some(record_id),
|
||||
[] => {
|
||||
return ProxyMemberRef::Unresolved {
|
||||
name,
|
||||
reason: ProxyMemberUnresolvedReason::Missing,
|
||||
};
|
||||
}
|
||||
_ => {
|
||||
// The n-th occurrence in Mihomo's member list selects the n-th scoped candidate.
|
||||
let (occurrence, scoped) = seen
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| (0, self.scoped_candidates(group, candidates)));
|
||||
let record_id = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
|
||||
*occurrence += 1;
|
||||
record_id
|
||||
}
|
||||
};
|
||||
match record_id {
|
||||
Some(record_id) => ProxyMemberRef::Node {
|
||||
name,
|
||||
record_id: record_id.clone(),
|
||||
},
|
||||
(None, []) => ProxyMemberRef::Unresolved {
|
||||
name,
|
||||
reason: ProxyMemberUnresolvedReason::Missing,
|
||||
},
|
||||
(None, _) => ProxyMemberRef::Unresolved {
|
||||
None => ProxyMemberRef::Unresolved {
|
||||
name,
|
||||
reason: ProxyMemberUnresolvedReason::Ambiguous,
|
||||
},
|
||||
@@ -414,19 +433,11 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
|
||||
proxy_type,
|
||||
..
|
||||
} = proxy;
|
||||
// The n-th occurrence of a name in `all` is the n-th scoped candidate.
|
||||
let mut seen = BTreeMap::<String, (usize, Vec<&String>)>::new();
|
||||
let mut seen = BTreeMap::new();
|
||||
let members = all
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|member| {
|
||||
let (occurrence, scoped) = seen
|
||||
.entry(member.clone())
|
||||
.or_insert_with(|| (0, resolver.scoped_candidates(&name, &member)));
|
||||
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
|
||||
*occurrence += 1;
|
||||
resolver.resolve(member, picked)
|
||||
})
|
||||
.map(|member| resolver.resolve(&name, member, &mut seen))
|
||||
.collect();
|
||||
|
||||
ProxyGroupView {
|
||||
|
||||
@@ -299,13 +299,15 @@ fn plan_provider(
|
||||
};
|
||||
let destination = destination_below_root(config_root, &source)?;
|
||||
let reserved = TriStr::from(destination.as_str());
|
||||
if destinations.insert(reserved.clone())
|
||||
&& let Some(assets) = assets
|
||||
{
|
||||
assets.push(RuntimeAsset {
|
||||
source: source.to_string_lossy().into_owned(),
|
||||
destination: reserved,
|
||||
});
|
||||
if destinations.insert(reserved.clone()) {
|
||||
if let Some(assets) = assets {
|
||||
assets.push(RuntimeAsset {
|
||||
source: source.to_string_lossy().into_owned(),
|
||||
destination: reserved,
|
||||
});
|
||||
}
|
||||
} else if remote_providers.iter().any(|provider| provider.destination == reserved) {
|
||||
return Err(RuntimeBundleError::DuplicateDestination(destination));
|
||||
}
|
||||
destination
|
||||
}
|
||||
@@ -443,7 +445,7 @@ fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
|
||||
}
|
||||
|
||||
fn normalized_destination(relative: &Path) -> Result<String> {
|
||||
let mut destination = PathBuf::new();
|
||||
let mut destination = PathBuf::with_capacity(relative.as_os_str().len());
|
||||
for component in relative.components() {
|
||||
match component {
|
||||
Component::Normal(component) => destination.push(component),
|
||||
@@ -454,13 +456,41 @@ fn normalized_destination(relative: &Path) -> Result<String> {
|
||||
if destination.as_os_str().is_empty() {
|
||||
return Err(RuntimeBundleError::EmptyDestination);
|
||||
}
|
||||
Ok(destination.to_string_lossy().replace('\\', "/"))
|
||||
let destination = destination
|
||||
.into_os_string()
|
||||
.into_string()
|
||||
.unwrap_or_else(|path| path.to_string_lossy().into_owned());
|
||||
if destination.contains('\\') {
|
||||
Ok(destination.replace('\\', "/"))
|
||||
} else {
|
||||
Ok(destination)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
|
||||
|
||||
#[test]
|
||||
fn local_and_remote_providers_cannot_claim_the_same_file() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-mixed-providers-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root)?;
|
||||
std::fs::write(root.join("shared.yaml"), "payload: []")?;
|
||||
let local = "type: file, path: ./shared.yaml";
|
||||
let remote = "type: http, url: 'https://example.com/provider', path: shared.yaml";
|
||||
for (proxy, rule) in [(local, remote), (remote, local)] {
|
||||
let config = serde_yaml_ng::from_str(&format!(
|
||||
"proxy-providers: {{a: {{{proxy}}}}}\nrule-providers: {{b: {{{rule}}}}}"
|
||||
))?;
|
||||
assert!(matches!(
|
||||
remote_providers_of(&config, &root),
|
||||
Err(super::RuntimeBundleError::DuplicateDestination(path)) if path == "shared.yaml"
|
||||
));
|
||||
}
|
||||
std::fs::remove_dir_all(root)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
Reference in New Issue
Block a user