@cloudflare/sandbox 0.0.0-2f85e95 → 0.0.0-30e5c25

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/src/sandbox.ts ADDED
@@ -0,0 +1,646 @@
1
+ import { Container, getContainer } from "@cloudflare/containers";
2
+ import { HttpClient } from "./client";
3
+ import { isLocalhostPattern } from "./request-handler";
4
+ import {
5
+ logSecurityEvent,
6
+ SecurityError,
7
+ sanitizeSandboxId,
8
+ validatePort
9
+ } from "./security";
10
+ import type {
11
+ ExecOptions,
12
+ ExecResult,
13
+ ISandbox,
14
+ Process,
15
+ ProcessOptions,
16
+ ProcessStatus,
17
+ StreamOptions
18
+ } from "./types";
19
+ import {
20
+ ProcessNotFoundError,
21
+ SandboxError
22
+ } from "./types";
23
+
24
+ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
25
+ const stub = getContainer(ns, id);
26
+
27
+ // Store the name on first access
28
+ stub.setSandboxName?.(id);
29
+
30
+ return stub;
31
+ }
32
+
33
+ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
34
+ defaultPort = 3000; // Default port for the container's Bun server
35
+ sleepAfter = "3m"; // Sleep the sandbox if no requests are made in this timeframe
36
+ client: HttpClient;
37
+ private sandboxName: string | null = null;
38
+
39
+ constructor(ctx: DurableObjectState, env: Env) {
40
+ super(ctx, env);
41
+ this.client = new HttpClient({
42
+ onCommandComplete: (success, exitCode, _stdout, _stderr, command) => {
43
+ console.log(
44
+ `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
45
+ );
46
+ },
47
+ onCommandStart: (command) => {
48
+ console.log(
49
+ `[Container] Command started: ${command}`
50
+ );
51
+ },
52
+ onError: (error, _command) => {
53
+ console.error(`[Container] Command error: ${error}`);
54
+ },
55
+ onOutput: (stream, data, _command) => {
56
+ console.log(`[Container] [${stream}] ${data}`);
57
+ },
58
+ port: 3000, // Control plane port
59
+ stub: this,
60
+ });
61
+
62
+ // Load the sandbox name from storage on initialization
63
+ this.ctx.blockConcurrencyWhile(async () => {
64
+ this.sandboxName = await this.ctx.storage.get<string>('sandboxName') || null;
65
+ });
66
+ }
67
+
68
+ // RPC method to set the sandbox name
69
+ async setSandboxName(name: string): Promise<void> {
70
+ if (!this.sandboxName) {
71
+ this.sandboxName = name;
72
+ await this.ctx.storage.put('sandboxName', name);
73
+ console.log(`[Sandbox] Stored sandbox name via RPC: ${name}`);
74
+ }
75
+ }
76
+
77
+ // RPC method to set environment variables
78
+ async setEnvVars(envVars: Record<string, string>): Promise<void> {
79
+ this.envVars = { ...this.envVars, ...envVars };
80
+ console.log(`[Sandbox] Updated environment variables`);
81
+ }
82
+
83
+ override onStart() {
84
+ console.log("Sandbox successfully started");
85
+ }
86
+
87
+ override onStop() {
88
+ console.log("Sandbox successfully shut down");
89
+ if (this.client) {
90
+ this.client.clearSession();
91
+ }
92
+ }
93
+
94
+ override onError(error: unknown) {
95
+ console.log("Sandbox error:", error);
96
+ }
97
+
98
+ // Override fetch to route internal container requests to appropriate ports
99
+ override async fetch(request: Request): Promise<Response> {
100
+ const url = new URL(request.url);
101
+
102
+ // Capture and store the sandbox name from the header if present
103
+ if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
104
+ const name = request.headers.get('X-Sandbox-Name')!;
105
+ this.sandboxName = name;
106
+ await this.ctx.storage.put('sandboxName', name);
107
+ console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
108
+ }
109
+
110
+ // Determine which port to route to
111
+ const port = this.determinePort(url);
112
+
113
+ // Route to the appropriate port
114
+ return await this.containerFetch(request, port);
115
+ }
116
+
117
+ private determinePort(url: URL): number {
118
+ // Extract port from proxy requests (e.g., /proxy/8080/*)
119
+ const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
120
+ if (proxyMatch) {
121
+ return parseInt(proxyMatch[1]);
122
+ }
123
+
124
+ // All other requests go to control plane on port 3000
125
+ // This includes /api/* endpoints and any other control requests
126
+ return 3000;
127
+ }
128
+
129
+ // Enhanced exec method - always returns ExecResult with optional streaming
130
+ // This replaces the old exec method to match ISandbox interface
131
+ async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
132
+ const startTime = Date.now();
133
+ const timestamp = new Date().toISOString();
134
+
135
+ // Handle timeout
136
+ let timeoutId: NodeJS.Timeout | undefined;
137
+
138
+ try {
139
+ // Handle cancellation
140
+ if (options?.signal?.aborted) {
141
+ throw new Error('Operation was aborted');
142
+ }
143
+
144
+ let result: ExecResult;
145
+
146
+ if (options?.stream && options?.onOutput) {
147
+ // Streaming with callbacks - we need to collect the final result
148
+ result = await this.executeWithStreaming(command, options, startTime, timestamp);
149
+ } else {
150
+ // Regular execution
151
+ const response = await this.client.execute(
152
+ command,
153
+ options?.sessionId
154
+ );
155
+
156
+ const duration = Date.now() - startTime;
157
+ result = this.mapExecuteResponseToExecResult(response, duration, options?.sessionId);
158
+ }
159
+
160
+ // Call completion callback if provided
161
+ if (options?.onComplete) {
162
+ options.onComplete(result);
163
+ }
164
+
165
+ return result;
166
+ } catch (error) {
167
+ if (options?.onError && error instanceof Error) {
168
+ options.onError(error);
169
+ }
170
+ throw error;
171
+ } finally {
172
+ if (timeoutId) {
173
+ clearTimeout(timeoutId);
174
+ }
175
+ }
176
+ }
177
+
178
+ private async executeWithStreaming(
179
+ command: string,
180
+ options: ExecOptions,
181
+ startTime: number,
182
+ timestamp: string
183
+ ): Promise<ExecResult> {
184
+ let stdout = '';
185
+ let stderr = '';
186
+
187
+ try {
188
+ const stream = await this.client.executeCommandStream(command, options.sessionId);
189
+ const { parseSSEStream } = await import('./sse-parser');
190
+
191
+ for await (const event of parseSSEStream<import('./types').ExecEvent>(stream)) {
192
+ // Check for cancellation
193
+ if (options.signal?.aborted) {
194
+ throw new Error('Operation was aborted');
195
+ }
196
+
197
+ switch (event.type) {
198
+ case 'stdout':
199
+ case 'stderr':
200
+ if (event.data) {
201
+ // Update accumulated output
202
+ if (event.type === 'stdout') stdout += event.data;
203
+ if (event.type === 'stderr') stderr += event.data;
204
+
205
+ // Call user's callback
206
+ if (options.onOutput) {
207
+ options.onOutput(event.type, event.data);
208
+ }
209
+ }
210
+ break;
211
+
212
+ case 'complete': {
213
+ // Use result from complete event if available
214
+ const duration = Date.now() - startTime;
215
+ return event.result || {
216
+ success: event.exitCode === 0,
217
+ exitCode: event.exitCode || 0,
218
+ stdout,
219
+ stderr,
220
+ command,
221
+ duration,
222
+ timestamp,
223
+ sessionId: options.sessionId
224
+ };
225
+ }
226
+
227
+ case 'error':
228
+ throw new Error(event.error || 'Command execution failed');
229
+ }
230
+ }
231
+
232
+ // If we get here without a complete event, something went wrong
233
+ throw new Error('Stream ended without completion event');
234
+
235
+ } catch (error) {
236
+ if (options.signal?.aborted) {
237
+ throw new Error('Operation was aborted');
238
+ }
239
+ throw error;
240
+ }
241
+ }
242
+
243
+ private mapExecuteResponseToExecResult(
244
+ response: import('./client').ExecuteResponse,
245
+ duration: number,
246
+ sessionId?: string
247
+ ): ExecResult {
248
+ return {
249
+ success: response.success,
250
+ exitCode: response.exitCode,
251
+ stdout: response.stdout,
252
+ stderr: response.stderr,
253
+ command: response.command,
254
+ duration,
255
+ timestamp: response.timestamp,
256
+ sessionId
257
+ };
258
+ }
259
+
260
+
261
+ // Background process management
262
+ async startProcess(command: string, options?: ProcessOptions): Promise<Process> {
263
+ // Use the new HttpClient method to start the process
264
+ try {
265
+ const response = await this.client.startProcess(command, {
266
+ processId: options?.processId,
267
+ sessionId: options?.sessionId,
268
+ timeout: options?.timeout,
269
+ env: options?.env,
270
+ cwd: options?.cwd,
271
+ encoding: options?.encoding,
272
+ autoCleanup: options?.autoCleanup
273
+ });
274
+
275
+ const process = response.process;
276
+ const processObj: Process = {
277
+ id: process.id,
278
+ pid: process.pid,
279
+ command: process.command,
280
+ status: process.status as ProcessStatus,
281
+ startTime: new Date(process.startTime),
282
+ endTime: undefined,
283
+ exitCode: undefined,
284
+ sessionId: process.sessionId,
285
+
286
+ async kill(): Promise<void> {
287
+ throw new Error('Method will be replaced');
288
+ },
289
+ async getStatus(): Promise<ProcessStatus> {
290
+ throw new Error('Method will be replaced');
291
+ },
292
+ async getLogs(): Promise<{ stdout: string; stderr: string }> {
293
+ throw new Error('Method will be replaced');
294
+ }
295
+ };
296
+
297
+ // Bind context properly
298
+ processObj.kill = async (signal?: string) => {
299
+ await this.killProcess(process.id, signal);
300
+ };
301
+
302
+ processObj.getStatus = async () => {
303
+ const current = await this.getProcess(process.id);
304
+ return current?.status || 'error';
305
+ };
306
+
307
+ processObj.getLogs = async () => {
308
+ const logs = await this.getProcessLogs(process.id);
309
+ return { stdout: logs.stdout, stderr: logs.stderr };
310
+ };
311
+
312
+ // Call onStart callback if provided
313
+ if (options?.onStart) {
314
+ options.onStart(processObj);
315
+ }
316
+
317
+ return processObj;
318
+
319
+ } catch (error) {
320
+ if (options?.onError && error instanceof Error) {
321
+ options.onError(error);
322
+ }
323
+
324
+ throw error;
325
+ }
326
+ }
327
+
328
+ async listProcesses(): Promise<Process[]> {
329
+ const response = await this.client.listProcesses();
330
+
331
+ return response.processes.map(processData => ({
332
+ id: processData.id,
333
+ pid: processData.pid,
334
+ command: processData.command,
335
+ status: processData.status,
336
+ startTime: new Date(processData.startTime),
337
+ endTime: processData.endTime ? new Date(processData.endTime) : undefined,
338
+ exitCode: processData.exitCode,
339
+ sessionId: processData.sessionId,
340
+
341
+ kill: async (signal?: string) => {
342
+ await this.killProcess(processData.id, signal);
343
+ },
344
+
345
+ getStatus: async () => {
346
+ const current = await this.getProcess(processData.id);
347
+ return current?.status || 'error';
348
+ },
349
+
350
+ getLogs: async () => {
351
+ const logs = await this.getProcessLogs(processData.id);
352
+ return { stdout: logs.stdout, stderr: logs.stderr };
353
+ }
354
+ }));
355
+ }
356
+
357
+ async getProcess(id: string): Promise<Process | null> {
358
+ const response = await this.client.getProcess(id);
359
+ if (!response.process) {
360
+ return null;
361
+ }
362
+
363
+ const processData = response.process;
364
+ return {
365
+ id: processData.id,
366
+ pid: processData.pid,
367
+ command: processData.command,
368
+ status: processData.status,
369
+ startTime: new Date(processData.startTime),
370
+ endTime: processData.endTime ? new Date(processData.endTime) : undefined,
371
+ exitCode: processData.exitCode,
372
+ sessionId: processData.sessionId,
373
+
374
+ kill: async (signal?: string) => {
375
+ await this.killProcess(processData.id, signal);
376
+ },
377
+
378
+ getStatus: async () => {
379
+ const current = await this.getProcess(processData.id);
380
+ return current?.status || 'error';
381
+ },
382
+
383
+ getLogs: async () => {
384
+ const logs = await this.getProcessLogs(processData.id);
385
+ return { stdout: logs.stdout, stderr: logs.stderr };
386
+ }
387
+ };
388
+ }
389
+
390
+ async killProcess(id: string, _signal?: string): Promise<void> {
391
+ try {
392
+ // Note: signal parameter is not currently supported by the HttpClient implementation
393
+ await this.client.killProcess(id);
394
+ } catch (error) {
395
+ if (error instanceof Error && error.message.includes('Process not found')) {
396
+ throw new ProcessNotFoundError(id);
397
+ }
398
+ throw new SandboxError(
399
+ `Failed to kill process ${id}: ${error instanceof Error ? error.message : 'Unknown error'}`,
400
+ 'KILL_PROCESS_FAILED'
401
+ );
402
+ }
403
+ }
404
+
405
+ async killAllProcesses(): Promise<number> {
406
+ const response = await this.client.killAllProcesses();
407
+ return response.killedCount;
408
+ }
409
+
410
+ async cleanupCompletedProcesses(): Promise<number> {
411
+ // For now, this would need to be implemented as a container endpoint
412
+ // as we no longer maintain local process storage
413
+ // We'll return 0 as a placeholder until the container endpoint is added
414
+ return 0;
415
+ }
416
+
417
+ async getProcessLogs(id: string): Promise<{ stdout: string; stderr: string }> {
418
+ try {
419
+ const response = await this.client.getProcessLogs(id);
420
+ return {
421
+ stdout: response.stdout,
422
+ stderr: response.stderr
423
+ };
424
+ } catch (error) {
425
+ if (error instanceof Error && error.message.includes('Process not found')) {
426
+ throw new ProcessNotFoundError(id);
427
+ }
428
+ throw error;
429
+ }
430
+ }
431
+
432
+
433
+ // Streaming methods - return ReadableStream for RPC compatibility
434
+ async execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>> {
435
+ // Check for cancellation
436
+ if (options?.signal?.aborted) {
437
+ throw new Error('Operation was aborted');
438
+ }
439
+
440
+ // Get the stream from HttpClient (need to add this method)
441
+ const stream = await this.client.executeCommandStream(command, options?.sessionId);
442
+
443
+ // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
444
+ return stream;
445
+ }
446
+
447
+ async streamProcessLogs(processId: string, options?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>> {
448
+ // Check for cancellation
449
+ if (options?.signal?.aborted) {
450
+ throw new Error('Operation was aborted');
451
+ }
452
+
453
+ // Get the stream from HttpClient
454
+ const stream = await this.client.streamProcessLogs(processId);
455
+
456
+ // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
457
+ return stream;
458
+ }
459
+
460
+ async gitCheckout(
461
+ repoUrl: string,
462
+ options: { branch?: string; targetDir?: string }
463
+ ) {
464
+ return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
465
+ }
466
+
467
+ async mkdir(
468
+ path: string,
469
+ options: { recursive?: boolean } = {}
470
+ ) {
471
+ return this.client.mkdir(path, options.recursive);
472
+ }
473
+
474
+ async writeFile(
475
+ path: string,
476
+ content: string,
477
+ options: { encoding?: string } = {}
478
+ ) {
479
+ return this.client.writeFile(path, content, options.encoding);
480
+ }
481
+
482
+ async deleteFile(path: string) {
483
+ return this.client.deleteFile(path);
484
+ }
485
+
486
+ async renameFile(
487
+ oldPath: string,
488
+ newPath: string
489
+ ) {
490
+ return this.client.renameFile(oldPath, newPath);
491
+ }
492
+
493
+ async moveFile(
494
+ sourcePath: string,
495
+ destinationPath: string
496
+ ) {
497
+ return this.client.moveFile(sourcePath, destinationPath);
498
+ }
499
+
500
+ async readFile(
501
+ path: string,
502
+ options: { encoding?: string } = {}
503
+ ) {
504
+ return this.client.readFile(path, options.encoding);
505
+ }
506
+
507
+ async exposePort(port: number, options: { name?: string; hostname: string }) {
508
+ await this.client.exposePort(port, options?.name);
509
+
510
+ // We need the sandbox name to construct preview URLs
511
+ if (!this.sandboxName) {
512
+ throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
513
+ }
514
+
515
+ const url = this.constructPreviewUrl(port, this.sandboxName, options.hostname);
516
+
517
+ return {
518
+ url,
519
+ port,
520
+ name: options?.name,
521
+ };
522
+ }
523
+
524
+ async unexposePort(port: number) {
525
+ if (!validatePort(port)) {
526
+ logSecurityEvent('INVALID_PORT_UNEXPOSE', {
527
+ port
528
+ }, 'high');
529
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
530
+ }
531
+
532
+ await this.client.unexposePort(port);
533
+
534
+ logSecurityEvent('PORT_UNEXPOSED', {
535
+ port
536
+ }, 'low');
537
+ }
538
+
539
+ async getExposedPorts(hostname: string) {
540
+ const response = await this.client.getExposedPorts();
541
+
542
+ // We need the sandbox name to construct preview URLs
543
+ if (!this.sandboxName) {
544
+ throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
545
+ }
546
+
547
+ return response.ports.map(port => ({
548
+ url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
549
+ port: port.port,
550
+ name: port.name,
551
+ exposedAt: port.exposedAt,
552
+ }));
553
+ }
554
+
555
+
556
+ private constructPreviewUrl(port: number, sandboxId: string, hostname: string): string {
557
+ if (!validatePort(port)) {
558
+ logSecurityEvent('INVALID_PORT_REJECTED', {
559
+ port,
560
+ sandboxId,
561
+ hostname
562
+ }, 'high');
563
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
564
+ }
565
+
566
+ let sanitizedSandboxId: string;
567
+ try {
568
+ sanitizedSandboxId = sanitizeSandboxId(sandboxId);
569
+ } catch (error) {
570
+ logSecurityEvent('INVALID_SANDBOX_ID_REJECTED', {
571
+ sandboxId,
572
+ port,
573
+ hostname,
574
+ error: error instanceof Error ? error.message : 'Unknown error'
575
+ }, 'high');
576
+ throw error;
577
+ }
578
+
579
+ const isLocalhost = isLocalhostPattern(hostname);
580
+
581
+ if (isLocalhost) {
582
+ // Unified subdomain approach for localhost (RFC 6761)
583
+ const [host, portStr] = hostname.split(':');
584
+ const mainPort = portStr || '80';
585
+
586
+ // Use URL constructor for safe URL building
587
+ try {
588
+ const baseUrl = new URL(`http://${host}:${mainPort}`);
589
+ // Construct subdomain safely
590
+ const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
591
+ baseUrl.hostname = subdomainHost;
592
+
593
+ const finalUrl = baseUrl.toString();
594
+
595
+ logSecurityEvent('PREVIEW_URL_CONSTRUCTED', {
596
+ port,
597
+ sandboxId: sanitizedSandboxId,
598
+ hostname,
599
+ resultUrl: finalUrl,
600
+ environment: 'localhost'
601
+ }, 'low');
602
+
603
+ return finalUrl;
604
+ } catch (error) {
605
+ logSecurityEvent('URL_CONSTRUCTION_FAILED', {
606
+ port,
607
+ sandboxId: sanitizedSandboxId,
608
+ hostname,
609
+ error: error instanceof Error ? error.message : 'Unknown error'
610
+ }, 'high');
611
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
612
+ }
613
+ }
614
+
615
+ // Production subdomain logic - enforce HTTPS
616
+ try {
617
+ // Always use HTTPS for production (non-localhost)
618
+ const protocol = "https";
619
+ const baseUrl = new URL(`${protocol}://${hostname}`);
620
+
621
+ // Construct subdomain safely
622
+ const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
623
+ baseUrl.hostname = subdomainHost;
624
+
625
+ const finalUrl = baseUrl.toString();
626
+
627
+ logSecurityEvent('PREVIEW_URL_CONSTRUCTED', {
628
+ port,
629
+ sandboxId: sanitizedSandboxId,
630
+ hostname,
631
+ resultUrl: finalUrl,
632
+ environment: 'production'
633
+ }, 'low');
634
+
635
+ return finalUrl;
636
+ } catch (error) {
637
+ logSecurityEvent('URL_CONSTRUCTION_FAILED', {
638
+ port,
639
+ sandboxId: sanitizedSandboxId,
640
+ hostname,
641
+ error: error instanceof Error ? error.message : 'Unknown error'
642
+ }, 'high');
643
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
644
+ }
645
+ }
646
+ }