diff --git a/Cargo.lock b/Cargo.lock index ae1504ace..d708f5665 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1097,6 +1097,7 @@ dependencies = [ "clash-verge-limiter", "clash-verge-logging", "clash-verge-media-unlock", + "clash-verge-profile-script", "clash-verge-runtime-bundle", "clash-verge-signal", "clash-verge-subscription", @@ -1216,6 +1217,20 @@ dependencies = [ "tokio", ] +[[package]] +name = "clash-verge-profile-script" +version = "0.1.0" +dependencies = [ + "boa_engine", + "clash-verge-logging", + "log", + "parking_lot 0.13.0", + "serde_json", + "serde_yaml_ng", + "tokio", + "tristr", +] + [[package]] name = "clash-verge-runtime-bundle" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 6aa4d1b51..0fc4fc3bc 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-profile-script", ] resolver = "2" @@ -54,6 +55,7 @@ split-debuginfo = "unpacked" muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" } [workspace.dependencies] +clash-verge-profile-script = { path = "crates/clash-verge-profile-script" } clash-verge-draft = { path = "crates/clash-verge-draft" } clash-verge-task = { path = "crates/clash-verge-task" } clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" } @@ -73,6 +75,7 @@ tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" thiserror = "2.0.20" +boa_engine = "0.22.0" futures = "0.3.34" chrono = "0.4.45" criterion = { version = "0.8.2", features = ["async_tokio"] } diff --git a/crates/clash-verge-profile-script/Cargo.toml b/crates/clash-verge-profile-script/Cargo.toml new file mode 100644 index 000000000..ad02f236a --- /dev/null +++ b/crates/clash-verge-profile-script/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "clash-verge-profile-script" +version = "0.1.0" +edition = "2024" + +[dependencies] +boa_engine = { workspace = true } +clash-verge-logging = { workspace = true } +log = { workspace = true } +parking_lot = { workspace = true } +serde_json = { workspace = true } +serde_yaml_ng = { workspace = true } +tokio = { workspace = true } +tristr = { workspace = true } + +[lints] +workspace = true diff --git a/crates/clash-verge-profile-script/src/lib.rs b/crates/clash-verge-profile-script/src/lib.rs new file mode 100644 index 000000000..8dea232ac --- /dev/null +++ b/crates/clash-verge-profile-script/src/lib.rs @@ -0,0 +1,248 @@ +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); + +/// Script logs are retained when evaluation or result conversion fails. +pub type ScriptLogs = Vec<(String, String)>; + +type EvalOutcome = (Result, ScriptLogs); + +#[derive(Debug, PartialEq, Eq)] +pub enum MainDeclaration { + Present, + Missing, +} + +/// Preserves the editor's evaluation and main-declaration check. +pub fn validate(source: &str) -> Result { + let mut context = Context::default(); + let _ = context.eval(Source::from_bytes( + "var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});", + )); + 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"); + Ok(if has_main { + MainDeclaration::Present + } else { + MainDeclaration::Missing + }) +} + +/// Runs one script on the blocking pool. The timeout bounds waiting for its result. +pub async fn execute(script: String, config: serde_json::Value, name: String) -> EvalOutcome { + if json_approx_size(&config) > MAX_JSON_SIZE { + return ( + Err("Configuration size exceeds maximum allowed size".to_owned()), + vec![], + ); + } + let evaluated = tokio::task::spawn_blocking(move || eval_script(&script, &config, &name)); + match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await { + Ok(Ok(evaluated)) => evaluated, + Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]), + Err(_) => ( + Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")), + vec![], + ), + } +} + +/// 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 take_logs = || std::mem::take(&mut *outputs.lock()); + let bail = |reason: std::string::String| (Err(reason), take_logs()); + + let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe { + NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| { + 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}")); + } + + 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(config), take_logs()), + 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() +} + +#[cfg(test)] +mod tests { + use super::{MainDeclaration, validate}; + + #[test] + fn validation_distinguishes_missing_main_from_evaluation_failure() { + assert_eq!( + validate("console.log('setup'); const main = config => config;"), + Ok(MainDeclaration::Present) + ); + assert_eq!(validate("console.log('setup');"), Ok(MainDeclaration::Missing)); + assert!(validate("throw new Error('setup failed'); function main(config) { return config; }").is_err()); + } +} diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index edf9686e8..7afa9657e 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-profile-script = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true } tauri = { workspace = true, features = [ @@ -64,7 +65,7 @@ dirs = "7.0.0" dunce = "1.0.5" nanoid = "0.5" chrono = { workspace = true } -boa_engine = "0.22.0" +boa_engine = { workspace = true } http-body-util = "0.1.5" percent-encoding = "2.3.2" reqwest = { workspace = true } diff --git a/src-tauri/src/core/validate.rs b/src-tauri/src/core/validate.rs index f58c5cf77..b7c819dfa 100644 --- a/src-tauri/src/core/validate.rs +++ b/src-tauri/src/core/validate.rs @@ -16,6 +16,7 @@ use crate::core::handle; use crate::singleton; use crate::utils::{dirs, help}; use clash_verge_logging::{Type, logging}; +use clash_verge_profile_script::MainDeclaration; const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); @@ -255,22 +256,8 @@ impl CoreConfigValidator { }; logging!(debug, Type::Validate, "验证脚本文件: {}", path); - let has_main = - content.contains("function main") || content.contains("const main") || content.contains("let main"); - - // Boa parsing is pure CPU; keep it off the async worker, with a timeout. - let syntax = crate::process::AsyncHandler::spawn_blocking(move || { - use boa_engine::{Context, Source}; - - let mut context = Context::default(); - let _ = context.eval(Source::from_bytes( - "var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});", - )); - context - .eval(Source::from_bytes(&content)) - .map(|_| ()) - .map_err(|err| err.to_string()) - }); + let syntax = + crate::process::AsyncHandler::spawn_blocking(move || clash_verge_profile_script::validate(&content)); let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await { Ok(Ok(evaluated)) => evaluated, Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")), @@ -278,10 +265,10 @@ impl CoreConfigValidator { }; match result { - Ok(()) => { + Ok(main) => { logging!(debug, Type::Validate, "脚本语法验证通过: {}", path); - if !has_main { + if main == MainDeclaration::Missing { let error_msg = "Script must contain a main function"; logging!(warn, Type::Validate, "脚本缺少main函数: {}", path); return Ok(ValidationOutcome::invalid_from_message(error_msg));