用途
Cloudflare Sandboxes SDK 用于在边缘的 Linux 容器中安全执行代码,适用于运行不受信任的代码、Python/Node.js 脚本、AI 代码解释器、Git 操作等场景。
主要能力
SDK 提供命令执行、文件操作、Git 操作、代码解释(类 Jupyter)、后台进程和清理等方法,具体包括 sandbox.exec()、writeFile()、readFile()、readdir()、gitCheckout()、createCodeContext()、runCode()、spawn()、isProcessRunning()、killProcess()、destroy() 等。
架构采用三层模型:
- 第一层 Worker:处理 HTTP 请求,调用 getSandbox(),使用 exec()、writeFile() 等。
- 第二层 Durable Object:按沙箱 ID 路由请求,维护持久身份,具备地理粘性。
- 第三层 Ubuntu 容器:完整 Linux 环境(Python 3.11、Node 20、Git 等),文件系统包含 /workspace、/tmp、/home,基于 VM 实现进程隔离。
使用方式
安装 SDK:
bun add @cloudflare/sandbox@latest # preferred
# or: bun add @cloudflare/sandbox@latest
在 wrangler.jsonc 中配置(关键项包括 nodejs_compat、containers、durable_objects、migrations):
{
"name": "my-sandbox-worker",
"main": "src/index.ts",
"compatibility_flags": ["nodejs_compat"],
"containers": [{
"class_name": "Sandbox",
"image": "cloudflare/sandbox:0.6.3-python",
"instance_type": "lite"
}],
"durable_objects": {
"bindings": [{
"class_name": "Sandbox",
"name": "Sandbox"
}]
},
"migrations": [{
"tag": "v1",
"new_sqlite_classes": ["Sandbox"]
}]
}
创建 Worker:
import { getSandbox, type Sandbox } from '@cloudflare/sandbox';
export { Sandbox } from '@cloudflare/sandbox';
type Env = {
Sandbox: DurableObjectNamespace<Sandbox>;
};
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Get sandbox instance (creates if doesn't exist)
const sandbox = getSandbox(env.Sandbox, 'my-first-sandbox');
// Execute Python code
const result = await sandbox.exec('python3 -c "print(2 + 2)"');
return Response.json({
output: result.stdout,
success: result.success,
exitCode: result.exitCode
});
}
};
部署测试:
npm run deploy
curl https://your-worker.workers.dev
预期输出:
{
"output": "4\n",
"success": true,
"exitCode": 0
}
会话(Sessions)机制:会话是单个沙箱内的 bash shell 上下文,类似终端标签页,各自有独立工作目录并共享同一文件系统,工作目录在同一会话内的命令之间保持,适合多步工作流和聊天式编码代理。示例:
await sandbox.exec('cd /workspace/project', { session: sessionId });
await sandbox.exec('ls -la', { session: sessionId });
await sandbox.exec('git status', { session: sessionId });
并行执行示例:
const session1 = await sandbox.createSession();
const session2 = await sandbox.createSession();
await Promise.all([
sandbox.exec('python train_model.py', { session: session1 }),
sandbox.exec('node generate_reports.js', { session: session2 })
]);
沙箱命名策略包括每用户沙箱(持久工作区)、每会话沙箱(每次全新)、每任务沙箱(幂等可追踪)。
持久化处理:
await sandbox.writeFile('/workspace/data.txt', content);
const fileData = await sandbox.readFile('/workspace/data.txt');
await env.R2.put('backup/data.txt', fileData);
const restored = await env.R2.get('backup/data.txt');
if (restored) {
await sandbox.writeFile('/workspace/data.txt', await restored.text());
}
适用场景
涵盖一次性代码执行、持久用户工作区、CI/CD 构建流水线和 AI 智能体集成。具体可用于交互式笔记本、IDE、代码游乐场、学习平台、构建系统、测试流水线、部署自动化、自动化重构与代码生成等。
限制
- 沙箱默认是临时的:容器在约 10 分钟无请求后进入闲置状态,整个文件系统被重置、所有进程被终止、所有状态丢失,下一次请求会从零创建新容器。重要数据需使用 R2/KV/D1 等外部存储持久化。
- 首次请求创建容器有约 2-3 分钟冷启动,后续请求较快(<1s)。
- 必须导出 Sandbox 类、配置 nodejs_compat 标志、注册 migrations,否则会报错。
- 需避免将未经清理的用户输入直接传入 exec(),以防命令注入,建议使用代码解释器 API 或充分验证。
- 一次性/会话沙箱需调用 destroy() 清理,避免资源耗尽和额外成本。
- 本地开发需要 Docker 守护进程运行。
- 需保持 npm 包版本与 Docker 镜像版本一致。
状态:Production Ready(Open Beta)。最新版本:@cloudflare/sandbox@0.6.3,Docker 镜像 cloudflare/sandbox:0.6.3-python。
v0.6.0 起有破坏性变更:默认镜像不再包含 Python,需使用 cloudflare/sandbox:<version>-python 获得 Python 支持(含数据科学包约 1.3GB);精简版(约 600-800MB)不含 Python。
安全安装:SDK 包会授予容器访问权限,安装前应验证。建议阻止安装后脚本(npm config set ignore-scripts true,Bun 默认禁用)、等待 7 天冷却期供社区审查、安装前运行 socket package score npm <pkg> 或 socket npm install <pkg> 审计。
官方资源:Package @cloudflare/sandbox@0.6.3;Docker cloudflare/sandbox:0.6.3-python。