@cloudflare/sandbox 0.0.0-db09b4d → 0.0.0-e1fa354

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 (40) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/Dockerfile +99 -11
  3. package/README.md +806 -22
  4. package/container_src/bun.lock +122 -0
  5. package/container_src/circuit-breaker.ts +121 -0
  6. package/container_src/control-process.ts +784 -0
  7. package/container_src/handler/exec.ts +185 -0
  8. package/container_src/handler/file.ts +406 -0
  9. package/container_src/handler/git.ts +130 -0
  10. package/container_src/handler/ports.ts +314 -0
  11. package/container_src/handler/process.ts +568 -0
  12. package/container_src/handler/session.ts +92 -0
  13. package/container_src/index.ts +448 -2467
  14. package/container_src/isolation.ts +1038 -0
  15. package/container_src/jupyter-server.ts +579 -0
  16. package/container_src/jupyter-service.ts +461 -0
  17. package/container_src/jupyter_config.py +48 -0
  18. package/container_src/mime-processor.ts +255 -0
  19. package/container_src/package.json +9 -0
  20. package/container_src/shell-escape.ts +42 -0
  21. package/container_src/startup.sh +84 -0
  22. package/container_src/types.ts +131 -0
  23. package/package.json +6 -8
  24. package/src/client.ts +477 -1192
  25. package/src/errors.ts +218 -0
  26. package/src/index.ts +63 -78
  27. package/src/interpreter-types.ts +383 -0
  28. package/src/interpreter.ts +150 -0
  29. package/src/jupyter-client.ts +349 -0
  30. package/src/request-handler.ts +144 -0
  31. package/src/sandbox.ts +747 -0
  32. package/src/security.ts +113 -0
  33. package/src/sse-parser.ts +147 -0
  34. package/src/types.ts +502 -0
  35. package/tsconfig.json +1 -1
  36. package/tests/client.example.ts +0 -308
  37. package/tests/connection-test.ts +0 -81
  38. package/tests/simple-test.ts +0 -81
  39. package/tests/test1.ts +0 -281
  40. package/tests/test2.ts +0 -710
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Security utilities for URL construction and input validation
3
+ *
4
+ * This module contains critical security functions to prevent:
5
+ * - URL injection attacks
6
+ * - SSRF (Server-Side Request Forgery) attacks
7
+ * - DNS rebinding attacks
8
+ * - Host header injection
9
+ * - Open redirect vulnerabilities
10
+ */
11
+
12
+ export class SecurityError extends Error {
13
+ constructor(message: string, public readonly code?: string) {
14
+ super(message);
15
+ this.name = 'SecurityError';
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Validates port numbers for sandbox services
21
+ * Only allows non-system ports to prevent conflicts and security issues
22
+ */
23
+ export function validatePort(port: number): boolean {
24
+ // Must be a valid integer
25
+ if (!Number.isInteger(port)) {
26
+ return false;
27
+ }
28
+
29
+ // Only allow non-system ports (1024-65535)
30
+ if (port < 1024 || port > 65535) {
31
+ return false;
32
+ }
33
+
34
+ // Exclude ports reserved by our system
35
+ const reservedPorts = [
36
+ 3000, // Control plane port
37
+ 8787, // Common wrangler dev port
38
+ ];
39
+
40
+ if (reservedPorts.includes(port)) {
41
+ return false;
42
+ }
43
+
44
+ return true;
45
+ }
46
+
47
+ /**
48
+ * Sanitizes and validates sandbox IDs for DNS compliance and security
49
+ * Only enforces critical requirements - allows maximum developer flexibility
50
+ */
51
+ export function sanitizeSandboxId(id: string): string {
52
+ // Basic validation: not empty, reasonable length limit (DNS subdomain limit is 63 chars)
53
+ if (!id || id.length > 63) {
54
+ throw new SecurityError(
55
+ 'Sandbox ID must be 1-63 characters long.',
56
+ 'INVALID_SANDBOX_ID_LENGTH'
57
+ );
58
+ }
59
+
60
+ // DNS compliance: cannot start or end with hyphens (RFC requirement)
61
+ if (id.startsWith('-') || id.endsWith('-')) {
62
+ throw new SecurityError(
63
+ 'Sandbox ID cannot start or end with hyphens (DNS requirement).',
64
+ 'INVALID_SANDBOX_ID_HYPHENS'
65
+ );
66
+ }
67
+
68
+ // Prevent reserved names that cause technical conflicts
69
+ const reservedNames = [
70
+ 'www', 'api', 'admin', 'root', 'system',
71
+ 'cloudflare', 'workers'
72
+ ];
73
+
74
+ const lowerCaseId = id.toLowerCase();
75
+ if (reservedNames.includes(lowerCaseId)) {
76
+ throw new SecurityError(
77
+ `Reserved sandbox ID '${id}' is not allowed.`,
78
+ 'RESERVED_SANDBOX_ID'
79
+ );
80
+ }
81
+
82
+ return id;
83
+ }
84
+
85
+
86
+ /**
87
+ * Logs security events for monitoring
88
+ */
89
+ export function logSecurityEvent(
90
+ event: string,
91
+ details: Record<string, any>,
92
+ severity: 'low' | 'medium' | 'high' | 'critical' = 'medium'
93
+ ): void {
94
+ const logEntry = {
95
+ timestamp: new Date().toISOString(),
96
+ event,
97
+ severity,
98
+ ...details
99
+ };
100
+
101
+ switch (severity) {
102
+ case 'critical':
103
+ case 'high':
104
+ console.error(`[SECURITY:${severity.toUpperCase()}] ${event}:`, JSON.stringify(logEntry));
105
+ break;
106
+ case 'medium':
107
+ console.warn(`[SECURITY:${severity.toUpperCase()}] ${event}:`, JSON.stringify(logEntry));
108
+ break;
109
+ case 'low':
110
+ console.info(`[SECURITY:${severity.toUpperCase()}] ${event}:`, JSON.stringify(logEntry));
111
+ break;
112
+ }
113
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Server-Sent Events (SSE) parser for streaming responses
3
+ * Converts ReadableStream<Uint8Array> to typed AsyncIterable<T>
4
+ */
5
+
6
+ /**
7
+ * Parse a ReadableStream of SSE events into typed AsyncIterable
8
+ * @param stream - The ReadableStream from fetch response
9
+ * @param signal - Optional AbortSignal for cancellation
10
+ */
11
+ export async function* parseSSEStream<T>(
12
+ stream: ReadableStream<Uint8Array>,
13
+ signal?: AbortSignal
14
+ ): AsyncIterable<T> {
15
+ const reader = stream.getReader();
16
+ const decoder = new TextDecoder();
17
+ let buffer = '';
18
+
19
+ try {
20
+ while (true) {
21
+ // Check for cancellation
22
+ if (signal?.aborted) {
23
+ throw new Error('Operation was aborted');
24
+ }
25
+
26
+ const { done, value } = await reader.read();
27
+ if (done) break;
28
+
29
+ // Decode chunk and add to buffer
30
+ buffer += decoder.decode(value, { stream: true });
31
+
32
+ // Process complete SSE events in buffer
33
+ const lines = buffer.split('\n');
34
+
35
+ // Keep the last incomplete line in buffer
36
+ buffer = lines.pop() || '';
37
+
38
+ for (const line of lines) {
39
+ // Skip empty lines
40
+ if (line.trim() === '') continue;
41
+
42
+ // Process SSE data lines
43
+ if (line.startsWith('data: ')) {
44
+ const data = line.substring(6);
45
+
46
+ // Skip [DONE] markers or empty data
47
+ if (data === '[DONE]' || data.trim() === '') continue;
48
+
49
+ try {
50
+ const event = JSON.parse(data) as T;
51
+ yield event;
52
+ } catch (error) {
53
+ // Log parsing errors but continue processing
54
+ console.error('Failed to parse SSE event:', data, error);
55
+ // Optionally yield an error event
56
+ // yield { type: 'error', data: `Parse error: ${error.message}` } as T;
57
+ }
58
+ }
59
+ // Handle other SSE fields if needed (event:, id:, retry:)
60
+ // For now, we only care about data: lines
61
+ }
62
+ }
63
+
64
+ // Process any remaining data in buffer
65
+ if (buffer.trim() && buffer.startsWith('data: ')) {
66
+ const data = buffer.substring(6);
67
+ if (data !== '[DONE]' && data.trim()) {
68
+ try {
69
+ const event = JSON.parse(data) as T;
70
+ yield event;
71
+ } catch (error) {
72
+ console.error('Failed to parse final SSE event:', data, error);
73
+ }
74
+ }
75
+ }
76
+ } finally {
77
+ // Clean up resources
78
+ reader.releaseLock();
79
+ }
80
+ }
81
+
82
+
83
+ /**
84
+ * Helper to convert a Response with SSE stream directly to AsyncIterable
85
+ * @param response - Response object with SSE stream
86
+ * @param signal - Optional AbortSignal for cancellation
87
+ */
88
+ export async function* responseToAsyncIterable<T>(
89
+ response: Response,
90
+ signal?: AbortSignal
91
+ ): AsyncIterable<T> {
92
+ if (!response.ok) {
93
+ throw new Error(`Response not ok: ${response.status} ${response.statusText}`);
94
+ }
95
+
96
+ if (!response.body) {
97
+ throw new Error('No response body');
98
+ }
99
+
100
+ yield* parseSSEStream<T>(response.body, signal);
101
+ }
102
+
103
+ /**
104
+ * Create an SSE-formatted ReadableStream from an AsyncIterable
105
+ * (Useful for Worker endpoints that need to forward AsyncIterable as SSE)
106
+ * @param events - AsyncIterable of events
107
+ * @param options - Stream options
108
+ */
109
+ export function asyncIterableToSSEStream<T>(
110
+ events: AsyncIterable<T>,
111
+ options?: {
112
+ signal?: AbortSignal;
113
+ serialize?: (event: T) => string;
114
+ }
115
+ ): ReadableStream<Uint8Array> {
116
+ const encoder = new TextEncoder();
117
+ const serialize = options?.serialize || JSON.stringify;
118
+
119
+ return new ReadableStream({
120
+ async start(controller) {
121
+ try {
122
+ for await (const event of events) {
123
+ if (options?.signal?.aborted) {
124
+ controller.error(new Error('Operation was aborted'));
125
+ break;
126
+ }
127
+
128
+ const data = serialize(event);
129
+ const sseEvent = `data: ${data}\n\n`;
130
+ controller.enqueue(encoder.encode(sseEvent));
131
+ }
132
+
133
+ // Send completion marker
134
+ controller.enqueue(encoder.encode('data: [DONE]\n\n'));
135
+ } catch (error) {
136
+ controller.error(error);
137
+ } finally {
138
+ controller.close();
139
+ }
140
+ },
141
+
142
+ cancel() {
143
+ // Handle stream cancellation
144
+ console.log('SSE stream cancelled');
145
+ }
146
+ });
147
+ }