Skip to main content
ClaudeWave
Skill169 repo starsupdated 29d ago

cloudflare-sandbox

Cloudflare Sandboxes SDK for secure code execution in Linux containers at edge. Use for untrusted code, Python/Node.js scripts, AI code interpreters, git operations.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/secondsky/claude-skills /tmp/cloudflare-sandbox && cp -r /tmp/cloudflare-sandbox/plugins/cloudflare-sandbox/skills/cloudflare-sandbox ~/.claude/skills/cloudflare-sandbox
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Cloudflare Sandboxes SDK

**Status**: Production Ready (Open Beta)
**Last Updated**: 2025-12-10
**Dependencies**: `cloudflare-worker-base`, `cloudflare-durable-objects` (recommended for understanding)
**Latest Versions**: `@cloudflare/sandbox@0.6.3`, Docker image: `cloudflare/sandbox:0.6.3-python`

**⚠️ BREAKING CHANGE (v0.6.0):** Python is no longer included in the default image. Use `cloudflare/sandbox:<version>-python` for Python support (~1.3GB with data science packages). The lean variant (~600-800MB) excludes Python.

---

## Quick Start (15 Minutes)

### 1. Install SDK and Setup Wrangler

```bash
bun add @cloudflare/sandbox@latest  # preferred
# or: bun add @cloudflare/sandbox@latest
```

**wrangler.jsonc:**
```jsonc
{
  "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"]
  }]
}
```

**Why this matters:**
- `nodejs_compat` enables Node.js APIs required by SDK
- `containers` defines the Ubuntu container image
- `durable_objects` binding enables persistent routing
- `migrations` registers the Sandbox class

### 2. Create Your First Sandbox Worker

```typescript
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
    });
  }
};
```

**CRITICAL:**
- **MUST export** `{ Sandbox }` from `@cloudflare/sandbox` in your Worker
- Sandbox ID determines routing (same ID = same container)
- First request creates container (~2-3 min cold start)
- Subsequent requests are fast (<1s)

### 3. Deploy and Test

```bash
npm run deploy
curl https://your-worker.workers.dev
```

Expected output:
```json
{
  "output": "4\n",
  "success": true,
  "exitCode": 0
}
```

## Secure Installation

Sandbox SDK packages grant container access — verify before installing to prevent unauthorized code execution. Follow supply chain security best practices:

- **Block post-install scripts** — `npm config set ignore-scripts true` (or Bun: disabled by default)
- **Cooldown period** — Wait 7 days for new package versions to be vetted by the community
- **Audit before installing** — Run `socket package score npm <pkg>` or use `socket npm install <pkg>` to check packages

Load the `dependency-upgrade` skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement.

---

## Architecture (Understanding the 3-Layer Model)

### How Sandboxes Work

```
┌─────────────────────────────────────────┐
│  Your Worker (Layer 1)                  │
│  - Handles HTTP requests                │
│  - Calls getSandbox()                   │
│  - Uses sandbox.exec(), writeFile(), etc│
└──────────────┬──────────────────────────┘
               │ RPC via Durable Object
┌──────────────▼──────────────────────────┐
│  Durable Object (Layer 2)               │
│  - Routes by sandbox ID                 │
│  - Maintains persistent identity        │
│  - Geographic stickiness                │
└──────────────┬──────────────────────────┘
               │ Container API
┌──────────────▼──────────────────────────┐
│  Ubuntu Container (Layer 3)             │
│  - Full Linux environment               │
│  - Python 3.11, Node 20, Git, etc.      │
│  - Filesystem: /workspace, /tmp, /home  │
│  - Process isolation (VM-based)         │
└─────────────────────────────────────────┘
```

**Key Insight**: Workers handle API logic (fast), Durable Objects route requests (persistent identity), Containers execute code (full capabilities).

---

## Critical Container Lifecycle (Most Important Section!)

### Container States

```
┌─────────┐  First request  ┌────────┐  ~10 min idle  ┌──────┐
│ Not     │ ───────────────>│ Active │ ─────────────> │ Idle │
│ Created │                 │        │                │      │
└─────────┘                 └───┬────┘                └──┬───┘
                                │ ^                      │
                                │ │ New request          │
                                │ └──────────────────────┘
                                │                         │
                                ▼                         ▼
                            Files persist          ALL FILES DELETED
                            Processes run          ALL PROCESSES KILLED
                            State maintained       ALL STATE RESET
```

### The #1 Gotcha: Ephemeral by Default

**While Container is Active** (~10 min after last request):
- ✅ Files in `/workspace`, `/tmp`, `/home` persist
- ✅ Background processes keep running
- ✅ Shell environment variables remain
- ✅ Session working directories preserved

**When Container Goes Idle** (after inactivity):
- ❌ **ALL files deleted** (entire filesystem reset)
- ❌ **ALL processes terminated**
- ❌ **ALL shell state lost**
- ⚠️  Next request creates **fresh container from scratch**

**This is NOT like a traditional server**. Sandboxes are ephemeral by design.

### Handling Persistence

**For Important Data**: Use external storage
```typescript
// Save to R2 before container goes idle
await sandbox.writeFile('/workspace/data.txt', content);
const fileData = await sandbox.readFile('/workspace/data.txt');
await env.R2.put('backup/data.txt', fileData);

// R
access-control-rbacSkill

Role-based access control (RBAC) with permissions and policies. Use for admin dashboards, enterprise access, multi-tenant apps, fine-grained authorization, or encountering permission hierarchies, role inheritance, policy conflicts.

aceternity-uiSkill

100+ animated React components (Aceternity UI) for Next.js with Tailwind. Use for hero sections, parallax, 3D effects, or encountering animation, shadcn CLI integration errors.

ai-elements-chatbotSkill

shadcn/ui AI chat components for conversational interfaces. Use for streaming chat, tool/function displays, reasoning visualization, or encountering Next.js App Router setup, Tailwind v4 integration, AI SDK v5 migration errors.

ai-sdk-coreSkill

Vercel AI SDK v5 for backend AI (text generation, structured output, tools, agents). Multi-provider. Use for server-side AI or encountering AI_APICallError, AI_NoObjectGeneratedError, streaming failures.

ai-sdk-uiSkill

Vercel AI SDK v5 React hooks (useChat, useCompletion, useObject) for AI chat interfaces. Use for React/Next.js AI apps or encountering parse stream errors, no response, streaming issues.

api-authenticationSkill

Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.

api-changelog-versioningSkill

Creates comprehensive API changelogs documenting breaking changes, deprecations, and migration strategies for API consumers. Use when managing API versions, communicating breaking changes, or creating upgrade guides.

api-contract-testingSkill

Verifies API contracts between services using consumer-driven contracts, schema validation, and tools like Pact. Use when testing microservices communication, preventing breaking changes, or validating OpenAPI specifications.