use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute}; use clash_verge_logging::{Type, logging}; use serde_yaml_ng::Mapping; use std::cell::{Cell, RefCell}; use std::rc::Rc; use tristr::alias::String; const MAX_OUTPUTS: usize = 1000; const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB const MAX_PROFILE_NAME_BYTES: usize = 1024; const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB const MAX_LOOP_ITERATIONS: u64 = 10_000_000; const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); /// 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, } /// Evaluates the source and checks that the entry point is callable. pub fn validate(source: &str) -> Result { let mut context = Context::default(); let _ = context.eval(Source::from_bytes( "var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){},warn(...data){},table(...data){}});", )); context .eval(Source::from_bytes(source)) .map_err(|err| err.to_string())?; let has_main = context .eval(Source::from_bytes("typeof main === 'function'")) .map_err(|err| err.to_string())? .to_boolean(); Ok(if has_main { MainDeclaration::Present } else { MainDeclaration::Missing }) } /// Runs one script on the blocking pool. The timeout bounds waiting for its result. pub async fn execute(script: String, config: serde_json::Value, name: String) -> EvalOutcome { if json_approx_size(&config) > MAX_JSON_SIZE { return ( Err("Configuration size exceeds maximum allowed size".to_owned()), vec![], ); } let 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 logs = Rc::new(RefCell::new(Vec::new())); let console_logs = Rc::clone(&logs); let logged_bytes = Cell::new(0); let take_logs = || logs.take(); let bail = |reason: std::string::String| (Err(reason), take_logs()); let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe { NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| { 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()) })?; let mut entries = console_logs.borrow_mut(); if entries.len() >= MAX_OUTPUTS { return Err(boa_engine::JsError::from_opaque( JsString::from("Maximum number of log outputs exceeded").into(), )); } let new_size = logged_bytes.get() + level.len() + data.len(); if new_size > MAX_OUTPUT_SIZE { return Err(boa_engine::JsError::from_opaque( JsString::from("Maximum output size exceeded").into(), )); } logged_bytes.set(new_size); entries.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 Some(escaped_profile_name) = escape_profile_name(name) else { return bail("Name parameter too long".to_owned()); }; let code = format!( r"try{{ {script}; main(globalThis.__verge_config__,'{escaped_profile_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) => { 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_profile_name(name: &str) -> Option { if name.len() > MAX_PROFILE_NAME_BYTES { return None; } let escaped = name .replace('\\', "\\\\") .replace('\'', "\\'") .replace('\n', "\\n") .replace('\r', "\\r"); (escaped.len() <= MAX_PROFILE_NAME_BYTES).then(|| escaped.into()) } #[cfg(test)] mod tests { use super::{MainDeclaration, eval_script, validate}; #[test] fn profile_name_limit_counts_escaped_bytes() { assert!(super::escape_profile_name(&"订阅".repeat(171)).is_none()); assert!(super::escape_profile_name(&"'".repeat(512)).is_some()); assert!(super::escape_profile_name(&"'".repeat(513)).is_none()); } #[test] fn numeric_size_matches_the_rendered_number() { for number in [ 0.into(), 10.into(), (-10).into(), i64::MIN.into(), u64::MAX.into(), serde_json::json!(1.25), ] { assert_eq!(super::json_approx_size(&number), number.to_string().len()); } } #[test] fn console_entries_survive_a_script_error() { let (result, logs) = eval_script( "function main() { console.log(1); console.warn(2); throw Error(); }", &serde_json::json!({}), &"profile".into(), ); assert!(result.is_err()); assert_eq!(logs, [("log".into(), "1".into()), ("warn".into(), "2".into())]); } #[test] fn validation_checks_the_evaluated_main_binding() { assert_eq!( validate("const main = config => config;"), Ok(MainDeclaration::Present) ); assert_eq!(validate("// function main goes here"), Ok(MainDeclaration::Missing)); assert_eq!(validate("const main = 42;"), Ok(MainDeclaration::Missing)); } #[test] fn validation_supports_console_methods_at_top_level() { assert_eq!( validate("console.warn('setup'); console.table([1]); function main(config) { return config; }"), Ok(MainDeclaration::Present) ); } #[test] fn validation_distinguishes_missing_main_from_evaluation_failure() { assert_eq!( validate("console.log('setup'); const main = config => config;"), Ok(MainDeclaration::Present) ); assert_eq!(validate("console.log('setup');"), Ok(MainDeclaration::Missing)); assert!(validate("throw new Error('setup failed'); function main(config) { return config; }").is_err()); } }