严格限制 Pi 的操作范围,对高危操作进行人工确认的安全扩展。
| 功能 | 描述 |
|---|---|
| 工作目录限制 | 禁止访问允许目录之外的文件 |
| 高危命令确认 | rm -rf, sudo, curl | sh 等需确认 |
| 受保护路径 | .env, .git 等文件特殊保护 |
| 配置系统 | JSON 配置,支持项目级和用户级 |
| 审计日志 | 记录拦截、确认、允许的操作 |
| 非交互模式 | 支持 -p 模式的自动处理策略 |
- 网络管道命令深度检测
- 配置热重载文件监听
- 规则统计报告
- 智能风险等级评估
mkdir -p ~/.pi/agent/extensions
cp sandbox.ts ~/.pi/agent/extensions/Pi 启动时自动加载。
pi -e ./sandbox.ts{
"extensions": [
"/Users/bgs/Documents/YI/sandbox.ts"
]
}- 项目级(优先):
.pi/sandbox-config.json - 用户级:
~/.pi/sandbox-config.json
{
"allowedPaths": ["./"]
}{
"allowedPaths": ["./", "/tmp"],
"protectedPaths": [
".env",
".git/",
"node_modules/",
"*.secret"
],
"dangerousPatterns": [
"\\brm\\s+-rf",
"\\bsudo\\s"
],
"blockedCommands": [
"\\brm\\s+-rf\\s+/\\s*$"
],
"nonInteractiveMode": "block",
"enableAuditLog": true
}
}| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
allowedPaths |
string[] | [cwd] | 允许操作的目录(绝对路径或相对路径) |
protectedPaths |
string[] | 见代码 | 受保护路径,操作需额外确认 |
dangerousPatterns |
string[] | 见代码 | 需要确认的高危命令正则 |
blockedCommands |
string[] | 见代码 | 完全禁止的命令正则 |
nonInteractiveMode |
string | "block" | 非交互模式:block/allow/warn |
enableAuditLog |
boolean | true | 是否启用审计日志 |
扩展加载成功后会显示:
🔒 安全沙盒已启用(默认配置)
或
🔒 安全沙盒已启用 (2 个允许目录)
🚫 安全沙盒:路径 "../../../etc/passwd" 超出允许范围
允许目录: /Users/bgs/Documents/YI
⚠️ 高危操作确认
即将执行可能危险的操作:
rm -rf ./node_modules
是否允许执行?
⚠️ 受保护的路径
即将修改受保护文件: .env
是否继续?
| 命令 | 描述 |
|---|---|
/sandbox-status |
显示当前配置和审计摘要 |
/sandbox-log |
显示最近 20 条审计记录 |
/sandbox-reload |
重新加载配置文件 |
🔒 安全沙盒状态
配置来源: /Users/bgs/Documents/YI/.pi/sandbox-config.json
允许目录:
• /Users/bgs/Documents/YI
• /tmp
受保护路径:
• .env
• .git/
• node_modules/
高危模式数: 15
禁止模式数: 3
非交互模式: block
审计记录: 42 条 | 阻止: 12 | 确认: 8 | 允许: 22
| 等级 | 命令示例 | 处理方式 |
|---|---|---|
| Blocked | rm -rf /, dd if=/dev/zero of=/dev/sda |
自动阻止,不可覆盖 |
| Dangerous | rm -rf ./dir, sudo apt update |
交互确认,非交互按配置处理 |
| Safe | ls, cat, grep |
直接允许 |
rm -rf /或类似根目录删除dd写入磁盘设备- 重定向到
/dev/sd*等磁盘设备
rm -rf*- 递归强制删除sudo*- 特权命令curl | sh/wget | bash- 管道执行远程脚本git push --force- 强制推送git reset --hard- 强制重置chmod 777- 全开权限npm install -g- 全局安装
当使用 -p (print) 模式或没有 UI 时:
| 模式 | 行为 |
|---|---|
block |
高危操作自动阻止(默认) |
allow |
高危操作自动允许(不推荐) |
warn |
允许但输出警告到 stderr |
tool_call事件 - 拦截所有工具调用user_bash事件 - 拦截用户 bash 命令
ConfigManager- 配置加载与合并PathGuard- 路径边界检查CommandRiskAnalyzer- 命令风险分析AuditLogger- 审计日志记录
// 规范化路径并检查是否在允许目录内
const resolvedPath = resolve(cwd, inputPath);
const normalizedPath = normalize(resolvedPath);
const rel = relative(allowedPath, normalizedPath);
// 允许:!rel.startsWith("..") && !isAbsolute(rel)检查文件位置是否正确:
ls ~/.pi/agent/extensions/sandbox.ts检查配置文件语法:
python3 -m json.tool .pi/sandbox-config.json重新加载配置:
/sandbox-reload
确保使用绝对路径或相对于 cwd 的路径:
{
"allowedPaths": ["/home/user/project", "./subdir"]
}MIT