@cloudflare/sandbox 0.0.0-d1c7c99 → 0.0.0-d55b0f4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # @cloudflare/sandbox
2
2
 
3
+ ## 0.1.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#30](https://github.com/cloudflare/sandbox-sdk/pull/30) [`30e5c25`](https://github.com/cloudflare/sandbox-sdk/commit/30e5c25cf7d4b07f9049724206c531e2d5d29d5c) Thanks [@ghostwriternr](https://github.com/ghostwriternr)! - Remove actions timeout
8
+
9
+ - [#29](https://github.com/cloudflare/sandbox-sdk/pull/29) [`d78508f`](https://github.com/cloudflare/sandbox-sdk/commit/d78508f7287a59e0423edd2999c2c83e9e34ccfd) Thanks [@ghostwriternr](https://github.com/ghostwriternr)! - Create multi-platform Docker image and switch to Cloudflare official repo
10
+
11
+ ## 0.1.1
12
+
13
+ ### Patch Changes
14
+
15
+ - [`157dde9`](https://github.com/cloudflare/sandbox-sdk/commit/157dde9b1f23e9bb6f3e9c3f0514b639a8813897) Thanks [@threepointone](https://github.com/threepointone)! - update deps
16
+
17
+ - [`a04f6b6`](https://github.com/cloudflare/sandbox-sdk/commit/a04f6b6c0b2ef9e3ce0851b53769f1c10d8c6de6) Thanks [@threepointone](https://github.com/threepointone)! - trigger a build with updated deps
18
+
19
+ ## 0.1.0
20
+
21
+ ### Minor Changes
22
+
23
+ - [#24](https://github.com/cloudflare/sandbox-sdk/pull/24) [`cecde0a`](https://github.com/cloudflare/sandbox-sdk/commit/cecde0a7530a87deffd8562fb8b01d66ee80ee19) Thanks [@ghostwriternr](https://github.com/ghostwriternr)! - Redesign command execution API
24
+
25
+ ### Patch Changes
26
+
27
+ - [#22](https://github.com/cloudflare/sandbox-sdk/pull/22) [`f5fcd52`](https://github.com/cloudflare/sandbox-sdk/commit/f5fcd52025d1f7958a374e69d75e3fc590275f3f) Thanks [@ghostwriternr](https://github.com/ghostwriternr)! - Allow setting env variables dynamically and remove command restrictions
28
+
29
+ ## 0.0.9
30
+
31
+ ### Patch Changes
32
+
33
+ - [#20](https://github.com/cloudflare/sandbox-sdk/pull/20) [`f106fda`](https://github.com/cloudflare/sandbox-sdk/commit/f106fdac98e7ef35677326290d45cbf3af88982c) Thanks [@ghostwriternr](https://github.com/ghostwriternr)! - add preview URLs and dynamic port forwarding
34
+
35
+ ## 0.0.8
36
+
37
+ ### Patch Changes
38
+
39
+ - [`60af265`](https://github.com/cloudflare/sandbox-sdk/commit/60af265d834e83fd30a921a3e1be232f13fe24da) Thanks [@threepointone](https://github.com/threepointone)! - update dependencies
40
+
41
+ ## 0.0.7
42
+
43
+ ### Patch Changes
44
+
45
+ - [`d1c7c99`](https://github.com/cloudflare/sandbox-sdk/commit/d1c7c99df6555eff71bcd59852e4b8eed2ad8cb6) Thanks [@threepointone](https://github.com/threepointone)! - fix file operations
46
+
3
47
  ## 0.0.6
4
48
 
5
49
  ### Patch Changes
package/Dockerfile CHANGED
@@ -1,16 +1,79 @@
1
- # syntax=docker/dockerfile:1
1
+ # Sandbox base image with development tools, Python, Node.js, and Bun
2
+ FROM oven/bun:latest AS bun-source
3
+ FROM ubuntu:22.04
2
4
 
3
- FROM oven/bun:latest
4
- # Set destination for COPY
5
+ # Prevent interactive prompts during package installation
6
+ ENV DEBIAN_FRONTEND=noninteractive
7
+
8
+ # Install essential system packages and development tools
9
+ RUN apt-get update && apt-get install -y \
10
+ # Basic utilities
11
+ curl \
12
+ wget \
13
+ git \
14
+ unzip \
15
+ zip \
16
+ # Process management
17
+ procps \
18
+ htop \
19
+ # Build tools
20
+ build-essential \
21
+ pkg-config \
22
+ # Network tools
23
+ net-tools \
24
+ iputils-ping \
25
+ dnsutils \
26
+ # Text processing
27
+ jq \
28
+ vim \
29
+ nano \
30
+ # Python dependencies
31
+ python3.11 \
32
+ python3.11-dev \
33
+ python3-pip \
34
+ # Other useful tools
35
+ sudo \
36
+ ca-certificates \
37
+ gnupg \
38
+ lsb-release \
39
+ && rm -rf /var/lib/apt/lists/*
40
+
41
+ # Set Python 3.11 as default python3
42
+ RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1
43
+
44
+ # Install Node.js 22 LTS
45
+ # Using the official NodeSource repository setup script
46
+ RUN apt-get update && apt-get install -y ca-certificates curl gnupg \
47
+ && mkdir -p /etc/apt/keyrings \
48
+ && curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
49
+ && echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list \
50
+ && apt-get update \
51
+ && apt-get install -y nodejs \
52
+ && rm -rf /var/lib/apt/lists/*
53
+
54
+ # Install Bun from official image (avoids architecture compatibility issues)
55
+ COPY --from=bun-source /usr/local/bin/bun /usr/local/bin/bun
56
+ COPY --from=bun-source /usr/local/bin/bunx /usr/local/bin/bunx
57
+
58
+ # Install global npm packages as root
59
+ RUN npm install -g yarn pnpm
60
+
61
+ # Set up working directory
5
62
  WORKDIR /app
6
63
 
7
- # Install git
8
- RUN apt-get update && apt-get install -y git
64
+ # Verify installations
65
+ RUN python3 --version && \
66
+ node --version && \
67
+ npm --version && \
68
+ bun --version && \
69
+ yarn --version && \
70
+ pnpm --version
9
71
 
10
- COPY container_src/* ./
11
- # RUN bun install
72
+ # Copy container source files
73
+ COPY container_src/ ./
12
74
 
75
+ # Expose the application port
13
76
  EXPOSE 3000
14
- # Run
15
- CMD ["bun", "index.ts"]
16
77
 
78
+ # Run the application
79
+ CMD ["bun", "index.ts"]
@@ -0,0 +1,337 @@
1
+ import { type SpawnOptions, spawn } from "node:child_process";
2
+ import type { ExecuteRequest, SessionData } from "../types";
3
+
4
+ function executeCommand(
5
+ sessions: Map<string, SessionData>,
6
+ command: string,
7
+ sessionId?: string,
8
+ background?: boolean
9
+ ): Promise<{
10
+ success: boolean;
11
+ stdout: string;
12
+ stderr: string;
13
+ exitCode: number;
14
+ }> {
15
+ return new Promise((resolve, reject) => {
16
+ const spawnOptions: SpawnOptions = {
17
+ shell: true,
18
+ stdio: ["pipe", "pipe", "pipe"] as const,
19
+ detached: background || false,
20
+ };
21
+
22
+ const child = spawn(command, spawnOptions);
23
+
24
+ // Store the process reference for cleanup if sessionId is provided
25
+ if (sessionId && sessions.has(sessionId)) {
26
+ const session = sessions.get(sessionId)!;
27
+ session.activeProcess = child;
28
+ }
29
+
30
+ let stdout = "";
31
+ let stderr = "";
32
+
33
+ child.stdout?.on("data", (data) => {
34
+ stdout += data.toString();
35
+ });
36
+
37
+ child.stderr?.on("data", (data) => {
38
+ stderr += data.toString();
39
+ });
40
+
41
+ if (background) {
42
+ // For background processes, unref and return quickly
43
+ child.unref();
44
+
45
+ // Collect initial output for 100ms then return
46
+ setTimeout(() => {
47
+ resolve({
48
+ exitCode: 0, // Process is still running
49
+ stderr,
50
+ stdout,
51
+ success: true,
52
+ });
53
+ }, 100);
54
+
55
+ // Still handle errors
56
+ child.on("error", (error) => {
57
+ console.error(`[Server] Background process error: ${command}`, error);
58
+ // Don't reject since we might have already resolved
59
+ });
60
+ } else {
61
+ // Normal synchronous execution
62
+ child.on("close", (code) => {
63
+ // Clear the active process reference
64
+ if (sessionId && sessions.has(sessionId)) {
65
+ const session = sessions.get(sessionId)!;
66
+ session.activeProcess = null;
67
+ }
68
+
69
+ console.log(`[Server] Command completed: ${command}, Exit code: ${code}`);
70
+
71
+ resolve({
72
+ exitCode: code || 0,
73
+ stderr,
74
+ stdout,
75
+ success: code === 0,
76
+ });
77
+ });
78
+
79
+ child.on("error", (error) => {
80
+ // Clear the active process reference
81
+ if (sessionId && sessions.has(sessionId)) {
82
+ const session = sessions.get(sessionId)!;
83
+ session.activeProcess = null;
84
+ }
85
+
86
+ reject(error);
87
+ });
88
+ }
89
+ });
90
+ }
91
+
92
+ export async function handleExecuteRequest(
93
+ sessions: Map<string, SessionData>,
94
+ req: Request,
95
+ corsHeaders: Record<string, string>
96
+ ): Promise<Response> {
97
+ try {
98
+ const body = (await req.json()) as ExecuteRequest;
99
+ const { command, sessionId, background } = body;
100
+
101
+ if (!command || typeof command !== "string") {
102
+ return new Response(
103
+ JSON.stringify({
104
+ error: "Command is required and must be a string",
105
+ }),
106
+ {
107
+ headers: {
108
+ "Content-Type": "application/json",
109
+ ...corsHeaders,
110
+ },
111
+ status: 400,
112
+ }
113
+ );
114
+ }
115
+
116
+ console.log(`[Server] Executing command: ${command}`);
117
+
118
+ const result = await executeCommand(sessions, command, sessionId, background);
119
+
120
+ return new Response(
121
+ JSON.stringify({
122
+ command,
123
+ exitCode: result.exitCode,
124
+ stderr: result.stderr,
125
+ stdout: result.stdout,
126
+ success: result.success,
127
+ timestamp: new Date().toISOString(),
128
+ }),
129
+ {
130
+ headers: {
131
+ "Content-Type": "application/json",
132
+ ...corsHeaders,
133
+ },
134
+ }
135
+ );
136
+ } catch (error) {
137
+ console.error("[Server] Error in handleExecuteRequest:", error);
138
+ return new Response(
139
+ JSON.stringify({
140
+ error: "Failed to execute command",
141
+ message: error instanceof Error ? error.message : "Unknown error",
142
+ }),
143
+ {
144
+ headers: {
145
+ "Content-Type": "application/json",
146
+ ...corsHeaders,
147
+ },
148
+ status: 500,
149
+ }
150
+ );
151
+ }
152
+ }
153
+
154
+ export async function handleStreamingExecuteRequest(
155
+ sessions: Map<string, SessionData>,
156
+ req: Request,
157
+ corsHeaders: Record<string, string>
158
+ ): Promise<Response> {
159
+ try {
160
+ const body = (await req.json()) as ExecuteRequest;
161
+ const { command, sessionId, background } = body;
162
+
163
+ if (!command || typeof command !== "string") {
164
+ return new Response(
165
+ JSON.stringify({
166
+ error: "Command is required and must be a string",
167
+ }),
168
+ {
169
+ headers: {
170
+ "Content-Type": "application/json",
171
+ ...corsHeaders,
172
+ },
173
+ status: 400,
174
+ }
175
+ );
176
+ }
177
+
178
+ console.log(
179
+ `[Server] Executing streaming command: ${command}`
180
+ );
181
+
182
+ const stream = new ReadableStream({
183
+ start(controller) {
184
+ const spawnOptions: SpawnOptions = {
185
+ shell: true,
186
+ stdio: ["pipe", "pipe", "pipe"] as const,
187
+ detached: background || false,
188
+ };
189
+
190
+ const child = spawn(command, spawnOptions);
191
+
192
+ // Store the process reference for cleanup if sessionId is provided
193
+ if (sessionId && sessions.has(sessionId)) {
194
+ const session = sessions.get(sessionId)!;
195
+ session.activeProcess = child;
196
+ }
197
+
198
+ // For background processes, unref to prevent blocking
199
+ if (background) {
200
+ child.unref();
201
+ }
202
+
203
+ let stdout = "";
204
+ let stderr = "";
205
+
206
+ // Send command start event
207
+ controller.enqueue(
208
+ new TextEncoder().encode(
209
+ `data: ${JSON.stringify({
210
+ type: "start",
211
+ timestamp: new Date().toISOString(),
212
+ command,
213
+ background: background || false,
214
+ })}\n\n`
215
+ )
216
+ );
217
+
218
+ child.stdout?.on("data", (data) => {
219
+ const output = data.toString();
220
+ stdout += output;
221
+
222
+ // Send real-time output
223
+ controller.enqueue(
224
+ new TextEncoder().encode(
225
+ `data: ${JSON.stringify({
226
+ type: "stdout",
227
+ timestamp: new Date().toISOString(),
228
+ data: output,
229
+ command,
230
+ })}\n\n`
231
+ )
232
+ );
233
+ });
234
+
235
+ child.stderr?.on("data", (data) => {
236
+ const output = data.toString();
237
+ stderr += output;
238
+
239
+ // Send real-time error output
240
+ controller.enqueue(
241
+ new TextEncoder().encode(
242
+ `data: ${JSON.stringify({
243
+ type: "stderr",
244
+ timestamp: new Date().toISOString(),
245
+ data: output,
246
+ command,
247
+ })}\n\n`
248
+ )
249
+ );
250
+ });
251
+
252
+ child.on("close", (code) => {
253
+ // Clear the active process reference
254
+ if (sessionId && sessions.has(sessionId)) {
255
+ const session = sessions.get(sessionId)!;
256
+ session.activeProcess = null;
257
+ }
258
+
259
+ console.log(
260
+ `[Server] Command completed: ${command}, Exit code: ${code}`
261
+ );
262
+
263
+ // Send command completion event
264
+ controller.enqueue(
265
+ new TextEncoder().encode(
266
+ `data: ${JSON.stringify({
267
+ type: "complete",
268
+ timestamp: new Date().toISOString(),
269
+ command,
270
+ exitCode: code,
271
+ result: {
272
+ success: code === 0,
273
+ exitCode: code,
274
+ stdout,
275
+ stderr,
276
+ command,
277
+ timestamp: new Date().toISOString(),
278
+ },
279
+ })}\n\n`
280
+ )
281
+ );
282
+
283
+ // For non-background processes, close the stream
284
+ // For background processes with streaming, the stream stays open
285
+ if (!background) {
286
+ controller.close();
287
+ }
288
+ });
289
+
290
+ child.on("error", (error) => {
291
+ // Clear the active process reference
292
+ if (sessionId && sessions.has(sessionId)) {
293
+ const session = sessions.get(sessionId)!;
294
+ session.activeProcess = null;
295
+ }
296
+
297
+ controller.enqueue(
298
+ new TextEncoder().encode(
299
+ `data: ${JSON.stringify({
300
+ type: "error",
301
+ timestamp: new Date().toISOString(),
302
+ error: error.message,
303
+ command,
304
+ })}\n\n`
305
+ )
306
+ );
307
+
308
+ controller.close();
309
+ });
310
+ },
311
+ });
312
+
313
+ return new Response(stream, {
314
+ headers: {
315
+ "Cache-Control": "no-cache",
316
+ Connection: "keep-alive",
317
+ "Content-Type": "text/event-stream",
318
+ ...corsHeaders,
319
+ },
320
+ });
321
+ } catch (error) {
322
+ console.error("[Server] Error in handleStreamingExecuteRequest:", error);
323
+ return new Response(
324
+ JSON.stringify({
325
+ error: "Failed to execute streaming command",
326
+ message: error instanceof Error ? error.message : "Unknown error",
327
+ }),
328
+ {
329
+ headers: {
330
+ "Content-Type": "application/json",
331
+ ...corsHeaders,
332
+ },
333
+ status: 500,
334
+ }
335
+ );
336
+ }
337
+ }