window-sand-box 0.1.0

Windows 沙盒终端执行工具 — 使用受限令牌、ACL 和私有桌面隔离进程权限,提供安全的命令执行环境
//! # window-sand-box — Windows 沙盒终端执行工具 (库)
//!
//! 为 AI 提供受限制的 Windows 命令执行环境。核心安全机制:
//!
//! | 层级 | 机制 | 说明 |
//! |------|------|------|
//! | 第一层 | **受限令牌** | `CreateRestrictedToken` — 禁用特权、模拟标准用户、限制写入 |
//! | 第二层 | **Capability SID** | 每个工作目录唯一随机 SID,不同会话互不干扰 |
//! | 第三层 | **ACL 权限** | Allow/Deny ACE 精细化控制文件系统访问 |
//! | 可选 | **桌面隔离** | 在私有 Windows 桌面运行,防止 GUI 攻击 |
//!
//! # 快速开始
//!
//! ```rust,no_run
//! use window_sand_box::SandboxRunner;
//! use std::collections::HashMap;
//!
//! // 1. 创建执行器(默认家目录 %USERPROFILE%\.wsbx\)
//! let runner = SandboxRunner::new()?;
//!
//! // 2. 创建会话
//! let cwd = std::env::current_dir()?;
//! let session = runner.create_session(cwd)?;
//!
//! // 3. 设置 ACL(需要管理员权限,仅需一次)
//! if let Err(e) = runner.setup_session_acls(&session) {
//!     eprintln!("ACL 设置失败(忽略则沙盒隔离不完整): {e}");
//! }
//!
//! // 4. 执行命令(&[String] 类型)
//! let cmd: Vec<String> = vec!["cmd".into(), "/c".into(), "echo Hello && dir /b".into()];
//! let result = runner.execute(
//!     &session,
//!     &cmd,
//!     HashMap::new(),
//!     None, // 超时(毫秒)
//! )?;
//!
//! println!("退出码: {}", result.exit_code);
//! print!("{}", result.stdout);
//! # Ok::<_, anyhow::Error>(())
//! ```
//!
//! # 实时流式输出
//!
//! 使用 [`execute_stream`](runner::executor::SandboxRunner::execute_stream) 替代 `execute`,
//! 每收到一个输出块就通过回调实时通知,适合长时间运行的命令:
//!
//! ```rust,no_run
//! use window_sand_box::SandboxRunner;
//! use std::collections::HashMap;
//!
//! let runner = SandboxRunner::new()?;
//! let cwd = std::env::current_dir()?;
//! let session = runner.create_session(cwd)?;
//!
//! let cmd = vec!["cmd".into(), "/c".into(), "for /l %i in (1,1,5) do echo Line %i & ping -n 2 127.0.0.1 >nul".into()];
//! let result = runner.execute_stream(
//!     &session,
//!     &cmd,
//!     HashMap::new(),
//!     None,
//!     |stdout| { print!("{stdout}"); },  // 每收到 stdout 块就打印
//!     |stderr| { eprint!("{stderr}"); }, // 每收到 stderr 块就打印
//! )?;
//! println!("\n退出码: {}", result.exit_code);
//! # Ok::<_, anyhow::Error>(())
//! ```
//!
//! # 指定自定义沙盒家目录
//!
//! 沙盒配置文件(config.json、cap_sid.json)默认存储在 `%USERPROFILE%\.wsbx\`。
//! 可通过以下方式自定义:
//!
//! **方式一:环境变量 `WSBX_HOME`(全局生效)**
//!
//! ```rust,ignore
//! // 设置环境变量后,SandboxRunner::new() 自动读取
//! std::env::set_var("WSBX_HOME", "D:\\my_sandbox");
//! let runner = SandboxRunner::new()?;
//! ```
//!
//! **方式二:`SandboxRunner::with_home()`(编程指定)**
//!
//! ```rust,no_run
//! use window_sand_box::SandboxRunner;
//!
//! let runner = SandboxRunner::with_home("D:\\my_sandbox")?;
//! # Ok::<_, anyhow::Error>(())
//! ```
//!
//! # 只读模式
//!
//! ```rust,no_run
//! use window_sand_box::SandboxRunner;
//! use std::collections::HashMap;
//!
//! let runner = SandboxRunner::new()?;
//! let cwd = std::env::current_dir()?;
//!
//! // 只读执行 — 无需 ACL 设置,无需管理员权限
//! let cmd: Vec<String> = vec!["cmd".into(), "/c".into(), "dir /b".into()];
//! let result = runner.execute_readonly(
//!     &cmd,
//!     &cwd,
//!     HashMap::new(),
//!     None,
//! )?;
//!
//! print!("{}", result.stdout);
//! # Ok::<_, anyhow::Error>(())
//! ```
//!
//! # 模块组织
//!
//! | 模块 | 说明 |
//! |------|------|
//! | [`config`] | 沙盒配置管理(黑白名单、敏感路径) |
//! | [`policy`] | 权限策略与会话管理(Capability SID 存储) |
//! | [`sandbox::token`] | Windows 受限令牌创建 |
//! | [`sandbox::acl`] | ACL 权限管理(Allow/Deny ACE) |
//! | [`sandbox::process`] | 受限进程执行与管道捕获 |
//! | [`sandbox::desktop`] | 私有桌面隔离 |
//! | [`runner`] | 整合层(`SandboxRunner` 执行器) |
//! | [`winutil`] | Windows 工具函数(UTF-16 转换等) |

pub mod config;
pub mod policy;
pub mod runner;
pub mod sandbox;
pub mod winutil;

// ==================== 核心 API(最常用) ====================

/// 沙盒执行器 — 整合受限令牌、ACL、进程执行的核心入口。
///
/// 参见 [`runner::executor::SandboxRunner`]。
pub use runner::executor::SandboxRunner;

/// 命令执行结果。
///
/// 包含退出码、stdout/stderr 字符串(已自动从 GBK 转为 UTF-8)、超时标志。
pub use runner::executor::CommandResult;

/// 沙盒异步任务句柄 — 用于中断正在执行的沙盒命令。
///
/// 通过 [`SandboxRunner::spawn`] 或 [`SandboxRunner::spawn_readonly`] 创建。
/// 提供 `kill()` 方法从外部终止进程,`join()` 方法等待结果。
pub use runner::executor::SandboxTask;

// ==================== 配置 ====================

/// 沙盒全局配置(黑白名单、敏感路径模式)。
pub use config::SandboxConfig;

/// 沙盒家目录路径。
///
/// 默认 `%USERPROFILE%\.wsbx\`,可通过环境变量 `WSBX_HOME` 覆盖。
pub use config::sandbox_home;

/// 默认配置文件路径。
pub use config::default_config_path;

/// 默认 Capability SID 存储路径。
pub use config::default_cap_sid_path;

// ==================== 会话与策略 ====================

/// 会话上下文 — 包含工作目录、Capability SID、黑白名单 SID。
pub use policy::SessionContext;

/// Capability SID 持久化存储 — 管理随机 SID 的生成、缓存、增量同步。
pub use policy::CapSidStore;

/// 路径规范化 key 函数 — 将路径转为全小写反斜杠形式用于 HashMap 索引。
pub use policy::canonical_path_key;

// ==================== 沙盒底层模块 ====================

/// 受限令牌创建模块(`LocalSid`、`create_restricted_token` 等)。
pub use sandbox::token;

/// ACL 操作模块(`add_allow_ace`、`add_deny_write_ace` 等)。
pub use sandbox::acl;

/// 进程执行模块(`ProcessResult`、`execute_with_token` 等)。
pub use sandbox::process;

/// 桌面隔离模块(`PrivateDesktop`)。
pub use sandbox::desktop;

// --- 直接导出常用底层类型 ---

/// 本地 SID 封装(自动释放)。
pub use sandbox::token::LocalSid;

/// 进程执行原始结果(UTF-8 编码前的字节)。
pub use sandbox::process::ProcessResult;

/// 私有桌面封装。
pub use sandbox::desktop::PrivateDesktop;

// ==================== 工具函数 ====================

/// 将 cmd.exe 输出的字节(GBK/系统 OEM 代码页)转为 UTF-8 String。
pub use runner::executor::decode_windows_string;

/// 将字符串转为 UTF-16 宽字符数组(以 null 结尾)。
pub use winutil::to_wide;

// ==================== 安全常量 ====================

/// 受保护的环境变量列表,禁止通过 `extra_env` 覆盖。
pub use runner::executor::PROTECTED_ENV_VARS;