后端修复: Ollama adapter 移除死代码/修复超时硬编码/iteration硬编码/pullModel无超时/流异常断开补发DONE; SSE解析器支持非字符串arguments; Sandbox fail-closed安全加固; IPC移除未使用变量 新增功能: TaskOrchestrator子任务编排器; DelegateTaskTool委派工具; Agent Loop并行工具执行; 上下文自动压缩; 记忆检索注入System Prompt 前端修复: useAgentStream text_delta thought累积bug; 工具调用状态正确流转; 修复重复stateChange事件; TraceStep.thought正确填充
95 lines
2.6 KiB
TypeScript
95 lines
2.6 KiB
TypeScript
/**
|
|
* Sandbox Manager — 沙箱执行环境
|
|
*
|
|
* 四层纵深防御:进程隔离、路径白名单、网络策略、资源限制。
|
|
*
|
|
* @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第五章
|
|
*/
|
|
|
|
import { resolve, sep } from 'path';
|
|
|
|
export interface SandboxConfig {
|
|
allowedPaths?: string[];
|
|
networkPolicy?: 'allowall' | 'deny-all' | 'allowlist';
|
|
resourceLimits?: Partial<ResourceLimits>;
|
|
}
|
|
|
|
export interface ResourceLimits {
|
|
maxMemoryMB: number;
|
|
maxCpuSeconds: number;
|
|
maxExecutionMs: number;
|
|
maxOutputSizeKB: number;
|
|
}
|
|
|
|
export interface SandboxExecutionResult {
|
|
success: boolean;
|
|
output?: string;
|
|
stderr?: string;
|
|
exitCode?: number;
|
|
error?: string;
|
|
durationMs: number;
|
|
}
|
|
|
|
export class SandboxManager {
|
|
private allowedPaths: Set<string> = new Set();
|
|
private networkPolicy: 'allowall' | 'deny-all' | 'allowlist' = 'deny-all';
|
|
private resourceLimits: ResourceLimits = {
|
|
maxMemoryMB: 512,
|
|
maxCpuSeconds: 30,
|
|
maxExecutionMs: 60_000,
|
|
maxOutputSizeKB: 1024,
|
|
};
|
|
|
|
constructor(private config: SandboxConfig) {
|
|
this.allowedPaths = new Set(config.allowedPaths ?? []);
|
|
this.networkPolicy = config.networkPolicy ?? 'allowlist';
|
|
}
|
|
|
|
/**
|
|
* 校验文件路径是否在白名单内
|
|
*
|
|
* 安全策略:fail-closed — 如果未配置任何白名单路径,拒绝所有访问。
|
|
*/
|
|
validatePath(requestedPath: string): { allowed: boolean; resolvedPath: string; reason?: string } {
|
|
const resolved = resolve(requestedPath);
|
|
|
|
if (this.allowedPaths.size === 0) {
|
|
return { allowed: false, resolvedPath: resolved, reason: 'No allowed paths configured (fail-closed)' };
|
|
}
|
|
|
|
const isAllowed = Array.from(this.allowedPaths).some(
|
|
(allowed) => resolved === allowed || resolved.startsWith(allowed + sep),
|
|
);
|
|
if (!isAllowed) {
|
|
return { allowed: false, resolvedPath: resolved, reason: 'Path not in allowed list' };
|
|
}
|
|
|
|
return { allowed: true, resolvedPath: resolved };
|
|
}
|
|
|
|
/**
|
|
* 静态代码安全扫描
|
|
*/
|
|
scanCode(code: string): { safe: boolean; reason?: string } {
|
|
const dangerousPatterns = [
|
|
/require\s*\(\s*['"]child_process['"]\s*\)/,
|
|
/eval\s*\(/,
|
|
/process\.exit/,
|
|
/import\s+.*from\s+['"]fs['"]/,
|
|
/\.\.\//,
|
|
/rm\s+-rf/,
|
|
/>\s*\/dev\/null/,
|
|
/curl.*\|\s*bash/,
|
|
/wget.*\|\s*sh/,
|
|
];
|
|
|
|
for (const pattern of dangerousPatterns) {
|
|
if (pattern.test(code)) {
|
|
return { safe: false, reason: `Dangerous pattern detected: ${pattern.source}` };
|
|
}
|
|
}
|
|
|
|
return { safe: true };
|
|
}
|
|
}
|