@cloudflare/sandbox 0.0.0-871f813 → 0.0.0-89632aa

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +234 -0
  2. package/Dockerfile +173 -89
  3. package/README.md +92 -707
  4. package/dist/index.d.ts +1953 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +3280 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +16 -8
  9. package/src/clients/base-client.ts +295 -0
  10. package/src/clients/command-client.ts +115 -0
  11. package/src/clients/file-client.ts +300 -0
  12. package/src/clients/git-client.ts +98 -0
  13. package/src/clients/index.ts +64 -0
  14. package/src/clients/interpreter-client.ts +333 -0
  15. package/src/clients/port-client.ts +105 -0
  16. package/src/clients/process-client.ts +180 -0
  17. package/src/clients/sandbox-client.ts +39 -0
  18. package/src/clients/types.ts +88 -0
  19. package/src/clients/utility-client.ts +156 -0
  20. package/src/errors/adapter.ts +238 -0
  21. package/src/errors/classes.ts +594 -0
  22. package/src/errors/index.ts +109 -0
  23. package/src/file-stream.ts +169 -0
  24. package/src/index.ts +94 -44
  25. package/src/interpreter.ts +62 -44
  26. package/src/request-handler.ts +94 -55
  27. package/src/sandbox.ts +887 -397
  28. package/src/security.ts +34 -28
  29. package/src/sse-parser.ts +8 -11
  30. package/src/version.ts +6 -0
  31. package/startup.sh +3 -0
  32. package/tests/base-client.test.ts +364 -0
  33. package/tests/command-client.test.ts +444 -0
  34. package/tests/file-client.test.ts +831 -0
  35. package/tests/file-stream.test.ts +310 -0
  36. package/tests/get-sandbox.test.ts +149 -0
  37. package/tests/git-client.test.ts +487 -0
  38. package/tests/port-client.test.ts +293 -0
  39. package/tests/process-client.test.ts +683 -0
  40. package/tests/request-handler.test.ts +292 -0
  41. package/tests/sandbox.test.ts +739 -0
  42. package/tests/sse-parser.test.ts +291 -0
  43. package/tests/utility-client.test.ts +339 -0
  44. package/tests/version.test.ts +16 -0
  45. package/tests/wrangler.jsonc +35 -0
  46. package/tsconfig.json +9 -1
  47. package/tsdown.config.ts +12 -0
  48. package/vitest.config.ts +31 -0
  49. package/container_src/bun.lock +0 -122
  50. package/container_src/circuit-breaker.ts +0 -121
  51. package/container_src/handler/exec.ts +0 -340
  52. package/container_src/handler/file.ts +0 -844
  53. package/container_src/handler/git.ts +0 -182
  54. package/container_src/handler/ports.ts +0 -314
  55. package/container_src/handler/process.ts +0 -640
  56. package/container_src/index.ts +0 -656
  57. package/container_src/jupyter-server.ts +0 -579
  58. package/container_src/jupyter-service.ts +0 -458
  59. package/container_src/jupyter_config.py +0 -48
  60. package/container_src/mime-processor.ts +0 -255
  61. package/container_src/package.json +0 -18
  62. package/container_src/startup.sh +0 -84
  63. package/container_src/types.ts +0 -108
  64. package/src/client.ts +0 -1021
  65. package/src/errors.ts +0 -218
  66. package/src/interpreter-types.ts +0 -383
  67. package/src/jupyter-client.ts +0 -349
  68. package/src/types.ts +0 -401
@@ -1,656 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import { serve } from "bun";
3
- import {
4
- handleExecuteRequest,
5
- handleStreamingExecuteRequest,
6
- } from "./handler/exec";
7
- import {
8
- handleDeleteFileRequest,
9
- handleMkdirRequest,
10
- handleMoveFileRequest,
11
- handleReadFileRequest,
12
- handleRenameFileRequest,
13
- handleWriteFileRequest,
14
- } from "./handler/file";
15
- import { handleGitCheckoutRequest } from "./handler/git";
16
- import {
17
- handleExposePortRequest,
18
- handleGetExposedPortsRequest,
19
- handleProxyRequest,
20
- handleUnexposePortRequest,
21
- } from "./handler/ports";
22
- import {
23
- handleGetProcessLogsRequest,
24
- handleGetProcessRequest,
25
- handleKillAllProcessesRequest,
26
- handleKillProcessRequest,
27
- handleListProcessesRequest,
28
- handleStartProcessRequest,
29
- handleStreamProcessLogsRequest,
30
- } from "./handler/process";
31
- import type { CreateContextRequest } from "./jupyter-server";
32
- import { JupyterNotReadyError, JupyterService } from "./jupyter-service";
33
- import type { ProcessRecord, SessionData } from "./types";
34
-
35
- // In-memory session storage (in production, you'd want to use a proper database)
36
- const sessions = new Map<string, SessionData>();
37
-
38
- // In-memory storage for exposed ports
39
- const exposedPorts = new Map<number, { name?: string; exposedAt: Date }>();
40
-
41
- // In-memory process storage - cleared on container restart
42
- const processes = new Map<string, ProcessRecord>();
43
-
44
- // Generate a unique session ID using cryptographically secure randomness
45
- function generateSessionId(): string {
46
- return `session_${Date.now()}_${randomBytes(6).toString("hex")}`;
47
- }
48
-
49
- // Clean up old sessions (older than 1 hour)
50
- function cleanupOldSessions() {
51
- const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
52
- for (const [sessionId, session] of sessions.entries()) {
53
- if (session.createdAt < oneHourAgo && !session.activeProcess) {
54
- sessions.delete(sessionId);
55
- console.log(`[Server] Cleaned up old session: ${sessionId}`);
56
- }
57
- }
58
- }
59
-
60
- // Run cleanup every 10 minutes
61
- setInterval(cleanupOldSessions, 10 * 60 * 1000);
62
-
63
- // Initialize Jupyter service with graceful degradation
64
- const jupyterService = new JupyterService();
65
-
66
- // Start Jupyter initialization in background (non-blocking)
67
- console.log("[Container] Starting Jupyter initialization in background...");
68
- console.log(
69
- "[Container] API endpoints are available immediately. Jupyter-dependent features will be available shortly."
70
- );
71
-
72
- jupyterService
73
- .initialize()
74
- .then(() => {
75
- console.log(
76
- "[Container] Jupyter fully initialized - all features available"
77
- );
78
- })
79
- .catch((error) => {
80
- console.error("[Container] Jupyter initialization failed:", error.message);
81
- console.error(
82
- "[Container] The API will continue in degraded mode without code execution capabilities"
83
- );
84
- });
85
-
86
- const server = serve({
87
- async fetch(req: Request) {
88
- const url = new URL(req.url);
89
- const pathname = url.pathname;
90
-
91
- console.log(`[Container] Incoming ${req.method} request to ${pathname}`);
92
-
93
- // Handle CORS
94
- const corsHeaders = {
95
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
96
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
97
- "Access-Control-Allow-Origin": "*",
98
- };
99
-
100
- // Handle preflight requests
101
- if (req.method === "OPTIONS") {
102
- console.log(`[Container] Handling CORS preflight for ${pathname}`);
103
- return new Response(null, { headers: corsHeaders, status: 200 });
104
- }
105
-
106
- try {
107
- // Handle different routes
108
- console.log(`[Container] Processing ${req.method} ${pathname}`);
109
- switch (pathname) {
110
- case "/":
111
- return new Response("Hello from Bun server! 🚀", {
112
- headers: {
113
- "Content-Type": "text/plain; charset=utf-8",
114
- ...corsHeaders,
115
- },
116
- });
117
-
118
- case "/api/session/create":
119
- if (req.method === "POST") {
120
- const sessionId = generateSessionId();
121
- const sessionData: SessionData = {
122
- activeProcess: null,
123
- createdAt: new Date(),
124
- sessionId,
125
- };
126
- sessions.set(sessionId, sessionData);
127
-
128
- console.log(`[Server] Created new session: ${sessionId}`);
129
-
130
- return new Response(
131
- JSON.stringify({
132
- message: "Session created successfully",
133
- sessionId,
134
- timestamp: new Date().toISOString(),
135
- }),
136
- {
137
- headers: {
138
- "Content-Type": "application/json",
139
- ...corsHeaders,
140
- },
141
- }
142
- );
143
- }
144
- break;
145
-
146
- case "/api/session/list":
147
- if (req.method === "GET") {
148
- const sessionList = Array.from(sessions.values()).map(
149
- (session) => ({
150
- createdAt: session.createdAt.toISOString(),
151
- hasActiveProcess: !!session.activeProcess,
152
- sessionId: session.sessionId,
153
- })
154
- );
155
-
156
- return new Response(
157
- JSON.stringify({
158
- count: sessionList.length,
159
- sessions: sessionList,
160
- timestamp: new Date().toISOString(),
161
- }),
162
- {
163
- headers: {
164
- "Content-Type": "application/json",
165
- ...corsHeaders,
166
- },
167
- }
168
- );
169
- }
170
- break;
171
-
172
- case "/api/execute":
173
- if (req.method === "POST") {
174
- return handleExecuteRequest(sessions, req, corsHeaders);
175
- }
176
- break;
177
-
178
- case "/api/execute/stream":
179
- if (req.method === "POST") {
180
- return handleStreamingExecuteRequest(sessions, req, corsHeaders);
181
- }
182
- break;
183
-
184
- case "/api/ping":
185
- if (req.method === "GET") {
186
- const health = await jupyterService.getHealthStatus();
187
- return new Response(
188
- JSON.stringify({
189
- message: "pong",
190
- timestamp: new Date().toISOString(),
191
- jupyter: health.ready
192
- ? "ready"
193
- : health.initializing
194
- ? "initializing"
195
- : "not ready",
196
- jupyterHealth: health,
197
- }),
198
- {
199
- headers: {
200
- "Content-Type": "application/json",
201
- ...corsHeaders,
202
- },
203
- }
204
- );
205
- }
206
- break;
207
-
208
- case "/api/commands":
209
- if (req.method === "GET") {
210
- return new Response(
211
- JSON.stringify({
212
- availableCommands: [
213
- "ls",
214
- "pwd",
215
- "echo",
216
- "cat",
217
- "grep",
218
- "find",
219
- "whoami",
220
- "date",
221
- "uptime",
222
- "ps",
223
- "top",
224
- "df",
225
- "du",
226
- "free",
227
- ],
228
- timestamp: new Date().toISOString(),
229
- }),
230
- {
231
- headers: {
232
- "Content-Type": "application/json",
233
- ...corsHeaders,
234
- },
235
- }
236
- );
237
- }
238
- break;
239
-
240
- case "/api/git/checkout":
241
- if (req.method === "POST") {
242
- return handleGitCheckoutRequest(sessions, req, corsHeaders);
243
- }
244
- break;
245
-
246
- case "/api/mkdir":
247
- if (req.method === "POST") {
248
- return handleMkdirRequest(sessions, req, corsHeaders);
249
- }
250
- break;
251
-
252
- case "/api/write":
253
- if (req.method === "POST") {
254
- return handleWriteFileRequest(req, corsHeaders);
255
- }
256
- break;
257
-
258
- case "/api/read":
259
- if (req.method === "POST") {
260
- return handleReadFileRequest(req, corsHeaders);
261
- }
262
- break;
263
-
264
- case "/api/delete":
265
- if (req.method === "POST") {
266
- return handleDeleteFileRequest(req, corsHeaders);
267
- }
268
- break;
269
-
270
- case "/api/rename":
271
- if (req.method === "POST") {
272
- return handleRenameFileRequest(req, corsHeaders);
273
- }
274
- break;
275
-
276
- case "/api/move":
277
- if (req.method === "POST") {
278
- return handleMoveFileRequest(req, corsHeaders);
279
- }
280
- break;
281
-
282
- case "/api/expose-port":
283
- if (req.method === "POST") {
284
- return handleExposePortRequest(exposedPorts, req, corsHeaders);
285
- }
286
- break;
287
-
288
- case "/api/unexpose-port":
289
- if (req.method === "DELETE") {
290
- return handleUnexposePortRequest(exposedPorts, req, corsHeaders);
291
- }
292
- break;
293
-
294
- case "/api/exposed-ports":
295
- if (req.method === "GET") {
296
- return handleGetExposedPortsRequest(exposedPorts, req, corsHeaders);
297
- }
298
- break;
299
-
300
- case "/api/process/start":
301
- if (req.method === "POST") {
302
- return handleStartProcessRequest(processes, req, corsHeaders);
303
- }
304
- break;
305
-
306
- case "/api/process/list":
307
- if (req.method === "GET") {
308
- return handleListProcessesRequest(processes, req, corsHeaders);
309
- }
310
- break;
311
-
312
- case "/api/process/kill-all":
313
- if (req.method === "DELETE") {
314
- return handleKillAllProcessesRequest(processes, req, corsHeaders);
315
- }
316
- break;
317
-
318
- // Code interpreter endpoints
319
- case "/api/contexts":
320
- if (req.method === "POST") {
321
- try {
322
- const body = (await req.json()) as CreateContextRequest;
323
- const context = await jupyterService.createContext(body);
324
- return new Response(
325
- JSON.stringify({
326
- id: context.id,
327
- language: context.language,
328
- cwd: context.cwd,
329
- createdAt: context.createdAt,
330
- lastUsed: context.lastUsed,
331
- }),
332
- {
333
- headers: {
334
- "Content-Type": "application/json",
335
- ...corsHeaders,
336
- },
337
- }
338
- );
339
- } catch (error) {
340
- if (error instanceof JupyterNotReadyError) {
341
- // This happens when request times out waiting for Jupyter
342
- console.log(
343
- `[Container] Request timed out waiting for Jupyter (${error.progress}% complete)`
344
- );
345
- return new Response(
346
- JSON.stringify({
347
- error: error.message,
348
- status: "initializing",
349
- progress: error.progress,
350
- }),
351
- {
352
- status: 503,
353
- headers: {
354
- "Content-Type": "application/json",
355
- "Retry-After": String(error.retryAfter),
356
- ...corsHeaders,
357
- },
358
- }
359
- );
360
- }
361
-
362
- // Check if it's a circuit breaker error
363
- if (
364
- error instanceof Error &&
365
- error.message.includes("Circuit breaker is open")
366
- ) {
367
- console.log(
368
- "[Container] Circuit breaker is open:",
369
- error.message
370
- );
371
- return new Response(
372
- JSON.stringify({
373
- error:
374
- "Service temporarily unavailable due to high error rate. Please try again later.",
375
- status: "circuit_open",
376
- details: error.message,
377
- }),
378
- {
379
- status: 503,
380
- headers: {
381
- "Content-Type": "application/json",
382
- "Retry-After": "60",
383
- ...corsHeaders,
384
- },
385
- }
386
- );
387
- }
388
-
389
- // Only log actual errors with stack traces
390
- console.error("[Container] Error creating context:", error);
391
- return new Response(
392
- JSON.stringify({
393
- error:
394
- error instanceof Error
395
- ? error.message
396
- : "Failed to create context",
397
- }),
398
- {
399
- status: 500,
400
- headers: {
401
- "Content-Type": "application/json",
402
- ...corsHeaders,
403
- },
404
- }
405
- );
406
- }
407
- } else if (req.method === "GET") {
408
- const contexts = await jupyterService.listContexts();
409
- return new Response(JSON.stringify({ contexts }), {
410
- headers: {
411
- "Content-Type": "application/json",
412
- ...corsHeaders,
413
- },
414
- });
415
- }
416
- break;
417
-
418
- case "/api/execute/code":
419
- if (req.method === "POST") {
420
- try {
421
- const body = (await req.json()) as {
422
- context_id: string;
423
- code: string;
424
- language?: string;
425
- };
426
- return await jupyterService.executeCode(
427
- body.context_id,
428
- body.code,
429
- body.language
430
- );
431
- } catch (error) {
432
- // Check if it's a circuit breaker error
433
- if (
434
- error instanceof Error &&
435
- error.message.includes("Circuit breaker is open")
436
- ) {
437
- console.log(
438
- "[Container] Circuit breaker is open for code execution:",
439
- error.message
440
- );
441
- return new Response(
442
- JSON.stringify({
443
- error:
444
- "Service temporarily unavailable due to high error rate. Please try again later.",
445
- status: "circuit_open",
446
- details: error.message,
447
- }),
448
- {
449
- status: 503,
450
- headers: {
451
- "Content-Type": "application/json",
452
- "Retry-After": "30",
453
- ...corsHeaders,
454
- },
455
- }
456
- );
457
- }
458
-
459
- // Don't log stack traces for expected initialization state
460
- if (
461
- error instanceof Error &&
462
- error.message.includes("initializing")
463
- ) {
464
- console.log(
465
- "[Container] Code execution deferred - Jupyter still initializing"
466
- );
467
- } else {
468
- console.error("[Container] Error executing code:", error);
469
- }
470
- // Error response is already handled by jupyterService.executeCode for not ready state
471
- return new Response(
472
- JSON.stringify({
473
- error:
474
- error instanceof Error
475
- ? error.message
476
- : "Failed to execute code",
477
- }),
478
- {
479
- status: 500,
480
- headers: {
481
- "Content-Type": "application/json",
482
- ...corsHeaders,
483
- },
484
- }
485
- );
486
- }
487
- }
488
- break;
489
-
490
- default:
491
- // Handle dynamic routes for contexts
492
- if (
493
- pathname.startsWith("/api/contexts/") &&
494
- pathname.split("/").length === 4
495
- ) {
496
- const contextId = pathname.split("/")[3];
497
- if (req.method === "DELETE") {
498
- try {
499
- await jupyterService.deleteContext(contextId);
500
- return new Response(JSON.stringify({ success: true }), {
501
- headers: {
502
- "Content-Type": "application/json",
503
- ...corsHeaders,
504
- },
505
- });
506
- } catch (error) {
507
- if (error instanceof JupyterNotReadyError) {
508
- console.log(
509
- `[Container] Request timed out waiting for Jupyter (${error.progress}% complete)`
510
- );
511
- return new Response(
512
- JSON.stringify({
513
- error: error.message,
514
- status: "initializing",
515
- progress: error.progress,
516
- }),
517
- {
518
- status: 503,
519
- headers: {
520
- "Content-Type": "application/json",
521
- "Retry-After": "5",
522
- ...corsHeaders,
523
- },
524
- }
525
- );
526
- }
527
- return new Response(
528
- JSON.stringify({
529
- error:
530
- error instanceof Error
531
- ? error.message
532
- : "Failed to delete context",
533
- }),
534
- {
535
- status:
536
- error instanceof Error &&
537
- error.message.includes("not found")
538
- ? 404
539
- : 500,
540
- headers: {
541
- "Content-Type": "application/json",
542
- ...corsHeaders,
543
- },
544
- }
545
- );
546
- }
547
- }
548
- }
549
-
550
- // Handle dynamic routes for individual processes
551
- if (pathname.startsWith("/api/process/")) {
552
- const segments = pathname.split("/");
553
- if (segments.length >= 4) {
554
- const processId = segments[3];
555
- const action = segments[4]; // Optional: logs, stream, etc.
556
-
557
- if (!action && req.method === "GET") {
558
- return handleGetProcessRequest(
559
- processes,
560
- req,
561
- corsHeaders,
562
- processId
563
- );
564
- } else if (!action && req.method === "DELETE") {
565
- return handleKillProcessRequest(
566
- processes,
567
- req,
568
- corsHeaders,
569
- processId
570
- );
571
- } else if (action === "logs" && req.method === "GET") {
572
- return handleGetProcessLogsRequest(
573
- processes,
574
- req,
575
- corsHeaders,
576
- processId
577
- );
578
- } else if (action === "stream" && req.method === "GET") {
579
- return handleStreamProcessLogsRequest(
580
- processes,
581
- req,
582
- corsHeaders,
583
- processId
584
- );
585
- }
586
- }
587
- }
588
- // Check if this is a proxy request for an exposed port
589
- if (pathname.startsWith("/proxy/")) {
590
- return handleProxyRequest(exposedPorts, req, corsHeaders);
591
- }
592
-
593
- console.log(`[Container] Route not found: ${pathname}`);
594
- return new Response("Not Found", {
595
- headers: corsHeaders,
596
- status: 404,
597
- });
598
- }
599
- } catch (error) {
600
- console.error(
601
- `[Container] Error handling ${req.method} ${pathname}:`,
602
- error
603
- );
604
- return new Response(
605
- JSON.stringify({
606
- error: "Internal server error",
607
- message: error instanceof Error ? error.message : "Unknown error",
608
- }),
609
- {
610
- headers: {
611
- "Content-Type": "application/json",
612
- ...corsHeaders,
613
- },
614
- status: 500,
615
- }
616
- );
617
- }
618
- },
619
- hostname: "0.0.0.0",
620
- port: 3000,
621
- // We don't need this, but typescript complains
622
- websocket: { async message() {} },
623
- });
624
-
625
- console.log(`🚀 Bun server running on http://0.0.0.0:${server.port}`);
626
- console.log(`📡 HTTP API endpoints available:`);
627
- console.log(` POST /api/session/create - Create a new session`);
628
- console.log(` GET /api/session/list - List all sessions`);
629
- console.log(` POST /api/execute - Execute a command (non-streaming)`);
630
- console.log(` POST /api/execute/stream - Execute a command (streaming)`);
631
- console.log(` POST /api/git/checkout - Checkout a git repository`);
632
- console.log(` POST /api/mkdir - Create a directory`);
633
- console.log(` POST /api/write - Write a file`);
634
- console.log(` POST /api/read - Read a file`);
635
- console.log(` POST /api/delete - Delete a file`);
636
- console.log(` POST /api/rename - Rename a file`);
637
- console.log(` POST /api/move - Move a file`);
638
- console.log(` POST /api/expose-port - Expose a port for external access`);
639
- console.log(` DELETE /api/unexpose-port - Unexpose a port`);
640
- console.log(` GET /api/exposed-ports - List exposed ports`);
641
- console.log(` POST /api/process/start - Start a background process`);
642
- console.log(` GET /api/process/list - List all processes`);
643
- console.log(` GET /api/process/{id} - Get process status`);
644
- console.log(` DELETE /api/process/{id} - Kill a process`);
645
- console.log(` GET /api/process/{id}/logs - Get process logs`);
646
- console.log(` GET /api/process/{id}/stream - Stream process logs (SSE)`);
647
- console.log(` DELETE /api/process/kill-all - Kill all processes`);
648
- console.log(` GET /proxy/{port}/* - Proxy requests to exposed ports`);
649
- console.log(` POST /api/contexts - Create a code execution context`);
650
- console.log(` GET /api/contexts - List all contexts`);
651
- console.log(` DELETE /api/contexts/{id} - Delete a context`);
652
- console.log(
653
- ` POST /api/execute/code - Execute code in a context (streaming)`
654
- );
655
- console.log(` GET /api/ping - Health check`);
656
- console.log(` GET /api/commands - List available commands`);