mintrt 0.1.1

Security-featured runtime for lua.
use crate::config::{entity_ro, entity_usr};

//     <<*>> Revenge of snowflake.
//     -^v-  SASWE
//     @ This source code is licensed under a dual license model:
//       1. MPL-2.0 for non-commercial use only
//       2. Commercial License for commercial use
//       See LICENSE and LICENSE_COMMERCIAL files for details.
static fuck: &'static str = "压制我的个人意志,用各种方式撕裂我的人格,去你妈的中式父母,中式教育,傻逼自以为是的垃圾们
又要重建自我意识又要反撕裂式的规训又要凭敏感抗刺激依赖和挫败感(利用时间),我还有一个十字架......";

mod promise;
mod config;
//mod cli;
mod runtime;
pub mod security;
pub mod dynload;
pub mod transmit;
pub mod i10n;  // 通义添加:国际化支持模块

fn main() {
    use std::env::args;
    
    let instruction_ro = args().nth(1).expect("参数读取失败");
    let instruction_usr = args().nth(2).expect("参数读取失败");
    
    promise::panic_hook();
    
    // 通义添加:初始化国际化系统
    i10n::init_i18n();
    
    let entity_data_ro = ron::from_str::<entity_ro>(&instruction_ro).unwrap_or_else(|e| {
        eprintln!("[ERROR] RO 参数解析失败:{}", e);
        std::process::exit(1);
    });
    let entity_data_usr = ron::from_str::<entity_usr>(&instruction_usr).unwrap_or_else(|e| {
        eprintln!("[ERROR] USR 参数解析失败:{}", e);
        std::process::exit(1);
    });
    
    // 初始化日志系统:使用 nickname + 时间戳
    let log_target = format!("{}_{}", 
        entity_data_ro.nickname,
        chrono::Local::now().format("%Y%m%d_%H%M%S")
    );
    env_logger::Builder::from_env(
        env_logger::Env::default().default_filter_or("info")
    )
    .format_timestamp_secs()
    .format(move |buf, record| {
        use std::io::Write;
        writeln!(buf, "[{}] [{}] {}", 
            log_target,
            record.level(),
            record.args()
        )
    })
    .init();
    
    log::info!("{}: {}", i10n::t("runtime_init"), entity_data_ro.nickname);
    
    let entity_data = entity_data_ro.merge(&entity_data_usr);
    runtime::init_runtime(&entity_data, entity_data_usr.flags).unwrap_or_else(|e| {
        error_i18n!("lua_error", ":{}", e);
        std::process::exit(1);
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    
    #[test]
    fn test_jumped_deserialize_as_main_mint_run_entirely() {
        // 获取项目根目录的绝对路径
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        let testdir = PathBuf::from(manifest_dir).join("testdir");
        let testdir_str = testdir.display().to_string().replace("\\", "/");
        
        // 构造 entity_data_ro 的 RON 字符串
        let instruction_ro = format!(r#"(
    nickname: "TestApp",
    entire_id: "com.example.test",
    basic_authority: {{
        MathRandom: true,
        MathRandomseed: true,
        Dofile: false,
        Load: false,
        Loadfile: false,
        Require: false,
        OsExecute: false,
        OsExit: false,
        OsGetenv: false,
        OsRemove: false,
        OsRename: false,
        OsSetenv: false,
        IoOpen: false,
        IoRead: false,
        IoWrite: false,
        IoPopen: false,
        DebugGetinfo: false,
        DebugGetlocal: false,
        DebugGetmetatable: false,
        DebugGetregistry: false,
        DebugGetupvalue: false,
        DebugGetuservalue: false,
        DebugSethook: false,
        DebugSetlocal: false,
        DebugSetupvalue: false,
        DebugSetuservalue: false,
        PackageLoadlib: false,
        PackagePath: false,
        PackageLoaded: false,
        PackagePreload: false,
        PackageSearchpath: false,
        StringDump: false,
    }},
    runtime_permission: Default,
    thinker_script: "{}/test.lua",
    executor_script_or_compiled: "{}/executor.wing",
    native_access_no_suffix: [],
    lua_access_no_suffix: [],
    pkg_path: "{}/",
    command_allow: {{}},
    file_access_allow: {{}},
)"#, 
            testdir_str,
            testdir_str,
            testdir_str
        );
        
        // 构造 entity_data_usr 的 RON 字符串
        let instruction_usr = r#"(
    flags: ["--test", "--verbose"],
    customize_authority: {},
    command_allow_extra: {},
    file_access_allow_extra: {},
)"#.to_string();
        
        // 反序列化
        let entity_data_ro = ron::from_str::<entity_ro>(&instruction_ro).expect("RO 参数解析失败");
        let entity_data_usr = ron::from_str::<entity_usr>(&instruction_usr).expect("USR 参数解析失败");
        
        // 合并数据
        let entity_data = entity_data_ro.merge(&entity_data_usr);
        
        // 初始化运行时并执行 Lua 脚本
        println!("\n========== 开始执行 Lua 脚本 ==========\n");
        runtime::init_runtime(&entity_data, entity_data_usr.flags).unwrap();
        println!("\n========== Lua 脚本执行完成 ==========\n");
    }
    
    /// 通义添加:测试 executor 安全检查功能(使用 luac.exe)
    #[test]
    fn test_executor_security_check_with_luac() {
        use std::path::PathBuf;
        
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        
        // 测试 1: 安全的字节码(无 CALL 指令)
        let safe_wing_path = PathBuf::from(manifest_dir).join("test_safe.wing");
        if safe_wing_path.exists() {
            let result = security::check_exec::check_executable_lua_file(&safe_wing_path.to_string_lossy());
            assert!(result, "test_safe.wing 应该通过安全检查(无 CALL 指令)");
            println!("✅ test_safe.wing 通过安全检查");
        } else {
            println!("⚠️  test_safe.wing 不存在,跳过测试");
        }
        
        // 测试 2: 不安全的字节码(包含 CALL 指令)
        let unsafe_wing_path = PathBuf::from(manifest_dir).join("testdir/executor.wing");
        if unsafe_wing_path.exists() {
            let result = security::check_exec::check_executable_lua_file(&unsafe_wing_path.to_string_lossy());
            assert!(!result, "executor.wing 应该未通过安全检查(包含 CALL 指令)");
            println!("✅ executor.wing 被正确拦截(包含 CALL 指令)");
        } else {
            println!("⚠️  executor.wing 不存在,跳过测试");
        }
    }
}