@cloudflare/sandbox 0.0.0-8af9edd → 0.0.0-8c1f440

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 (79) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/Dockerfile +108 -64
  3. package/README.md +149 -50
  4. package/dist/chunk-BFVUNTP4.js +104 -0
  5. package/dist/chunk-BFVUNTP4.js.map +1 -0
  6. package/dist/chunk-EKSWCBCA.js +86 -0
  7. package/dist/chunk-EKSWCBCA.js.map +1 -0
  8. package/dist/chunk-EXQOIRZI.js +2351 -0
  9. package/dist/chunk-EXQOIRZI.js.map +1 -0
  10. package/dist/chunk-JXZMAU2C.js +559 -0
  11. package/dist/chunk-JXZMAU2C.js.map +1 -0
  12. package/dist/chunk-Z532A7QC.js +78 -0
  13. package/dist/chunk-Z532A7QC.js.map +1 -0
  14. package/dist/file-stream.d.ts +43 -0
  15. package/dist/file-stream.js +9 -0
  16. package/dist/file-stream.js.map +1 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +66 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/interpreter.d.ts +33 -0
  21. package/dist/interpreter.js +8 -0
  22. package/dist/interpreter.js.map +1 -0
  23. package/dist/request-handler.d.ts +18 -0
  24. package/dist/request-handler.js +12 -0
  25. package/dist/request-handler.js.map +1 -0
  26. package/dist/sandbox-D9K2ypln.d.ts +583 -0
  27. package/dist/sandbox.d.ts +4 -0
  28. package/dist/sandbox.js +12 -0
  29. package/dist/sandbox.js.map +1 -0
  30. package/dist/security.d.ts +31 -0
  31. package/dist/security.js +13 -0
  32. package/dist/security.js.map +1 -0
  33. package/dist/sse-parser.d.ts +28 -0
  34. package/dist/sse-parser.js +11 -0
  35. package/dist/sse-parser.js.map +1 -0
  36. package/package.json +13 -9
  37. package/src/clients/base-client.ts +280 -0
  38. package/src/clients/command-client.ts +115 -0
  39. package/src/clients/file-client.ts +269 -0
  40. package/src/clients/git-client.ts +92 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/clients/interpreter-client.ts +329 -0
  43. package/src/clients/port-client.ts +105 -0
  44. package/src/clients/process-client.ts +177 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +84 -0
  47. package/src/clients/utility-client.ts +94 -0
  48. package/src/errors/adapter.ts +180 -0
  49. package/src/errors/classes.ts +469 -0
  50. package/src/errors/index.ts +105 -0
  51. package/src/file-stream.ts +164 -0
  52. package/src/index.ts +87 -8
  53. package/src/interpreter.ts +159 -0
  54. package/src/request-handler.ts +99 -24
  55. package/src/sandbox.ts +785 -121
  56. package/src/security.ts +104 -0
  57. package/src/sse-parser.ts +143 -0
  58. package/startup.sh +3 -0
  59. package/tests/base-client.test.ts +328 -0
  60. package/tests/command-client.test.ts +407 -0
  61. package/tests/file-client.test.ts +643 -0
  62. package/tests/file-stream.test.ts +306 -0
  63. package/tests/git-client.test.ts +328 -0
  64. package/tests/port-client.test.ts +301 -0
  65. package/tests/process-client.test.ts +658 -0
  66. package/tests/sandbox.test.ts +465 -0
  67. package/tests/sse-parser.test.ts +290 -0
  68. package/tests/utility-client.test.ts +266 -0
  69. package/tests/wrangler.jsonc +35 -0
  70. package/tsconfig.json +9 -1
  71. package/vitest.config.ts +31 -0
  72. package/container_src/index.ts +0 -3252
  73. package/container_src/package.json +0 -9
  74. package/src/client.ts +0 -2089
  75. package/tests/client.example.ts +0 -308
  76. package/tests/connection-test.ts +0 -81
  77. package/tests/simple-test.ts +0 -81
  78. package/tests/test1.ts +0 -281
  79. package/tests/test2.ts +0 -929
package/src/sandbox.ts CHANGED
@@ -1,48 +1,99 @@
1
+ import type { DurableObject } from 'cloudflare:workers';
1
2
  import { Container, getContainer } from "@cloudflare/containers";
2
- import { HttpClient } from "./client";
3
+ import type {
4
+ CodeContext,
5
+ CreateContextOptions,
6
+ ExecEvent,
7
+ ExecOptions,
8
+ ExecResult,
9
+ ExecutionResult,
10
+ ExecutionSession,
11
+ ISandbox,
12
+ Process,
13
+ ProcessOptions,
14
+ ProcessStatus,
15
+ RunCodeOptions,
16
+ SessionOptions,
17
+ StreamOptions
18
+ } from "@repo/shared";
19
+ import { createLogger, runWithLogger, TraceContext } from "@repo/shared";
20
+ import { type ExecuteResponse, SandboxClient } from "./clients";
21
+ import type { ErrorResponse } from './errors';
22
+ import { CustomDomainRequiredError, ErrorCode } from './errors';
23
+ import { CodeInterpreter } from "./interpreter";
3
24
  import { isLocalhostPattern } from "./request-handler";
4
-
5
- export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
25
+ import {
26
+ SecurityError,
27
+ sanitizeSandboxId,
28
+ validatePort
29
+ } from "./security";
30
+ import { parseSSEStream } from "./sse-parser";
31
+
32
+ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string, options?: {
33
+ baseUrl: string
34
+ }) {
6
35
  const stub = getContainer(ns, id);
7
36
 
8
37
  // Store the name on first access
9
38
  stub.setSandboxName?.(id);
10
39
 
40
+ if(options?.baseUrl) {
41
+ stub.setBaseUrl(options.baseUrl);
42
+ }
43
+
11
44
  return stub;
12
45
  }
13
46
 
14
- export class Sandbox<Env = unknown> extends Container<Env> {
47
+ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
48
+ defaultPort = 3000; // Default port for the container's Bun server
15
49
  sleepAfter = "3m"; // Sleep the sandbox if no requests are made in this timeframe
16
- client: HttpClient;
17
- private workerHostname: string | null = null;
50
+
51
+ client: SandboxClient;
52
+ private codeInterpreter: CodeInterpreter;
18
53
  private sandboxName: string | null = null;
54
+ private baseUrl: string | null = null;
55
+ private portTokens: Map<number, string> = new Map();
56
+ private defaultSession: string | null = null;
57
+ envVars: Record<string, string> = {};
58
+ private logger: ReturnType<typeof createLogger>;
19
59
 
20
- constructor(ctx: DurableObjectState, env: Env) {
60
+ constructor(ctx: DurableObject['ctx'], env: Env) {
21
61
  super(ctx, env);
22
- this.client = new HttpClient({
23
- onCommandComplete: (success, exitCode, _stdout, _stderr, command, _args) => {
24
- console.log(
25
- `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
26
- );
27
- },
28
- onCommandStart: (command, args) => {
29
- console.log(
30
- `[Container] Command started: ${command} ${args.join(" ")}`
31
- );
32
- },
33
- onError: (error, _command, _args) => {
34
- console.error(`[Container] Command error: ${error}`);
35
- },
36
- onOutput: (stream, data, _command) => {
37
- console.log(`[Container] [${stream}] ${data}`);
38
- },
62
+
63
+ const envObj = env as any;
64
+ // Set sandbox environment variables from env object
65
+ const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;
66
+ sandboxEnvKeys.forEach(key => {
67
+ if (envObj?.[key]) {
68
+ this.envVars[key] = envObj[key];
69
+ }
70
+ });
71
+
72
+ this.logger = createLogger({
73
+ component: 'sandbox-do',
74
+ sandboxId: this.ctx.id.toString()
75
+ });
76
+
77
+ this.client = new SandboxClient({
78
+ logger: this.logger,
39
79
  port: 3000, // Control plane port
40
80
  stub: this,
41
81
  });
42
82
 
43
- // Load the sandbox name from storage on initialization
83
+ // Initialize code interpreter - pass 'this' after client is ready
84
+ // The CodeInterpreter extracts client.interpreter from the sandbox
85
+ this.codeInterpreter = new CodeInterpreter(this);
86
+
87
+ // Load the sandbox name and port tokens from storage on initialization
44
88
  this.ctx.blockConcurrencyWhile(async () => {
45
89
  this.sandboxName = await this.ctx.storage.get<string>('sandboxName') || null;
90
+ const storedTokens = await this.ctx.storage.get<Record<string, string>>('portTokens') || {};
91
+
92
+ // Convert stored tokens back to Map
93
+ this.portTokens = new Map();
94
+ for (const [portStr, token] of Object.entries(storedTokens)) {
95
+ this.portTokens.set(parseInt(portStr, 10), token);
96
+ }
46
97
  });
47
98
  }
48
99
 
@@ -51,55 +102,93 @@ export class Sandbox<Env = unknown> extends Container<Env> {
51
102
  if (!this.sandboxName) {
52
103
  this.sandboxName = name;
53
104
  await this.ctx.storage.put('sandboxName', name);
54
- console.log(`[Sandbox] Stored sandbox name via RPC: ${name}`);
55
105
  }
56
106
  }
57
107
 
108
+ // RPC method to set the base URL
109
+ async setBaseUrl(baseUrl: string): Promise<void> {
110
+ if (!this.baseUrl) {
111
+ this.baseUrl = baseUrl;
112
+ await this.ctx.storage.put('baseUrl', baseUrl);
113
+ } else {
114
+ if(this.baseUrl !== baseUrl) {
115
+ throw new Error('Base URL already set and different from one previously provided');
116
+ }
117
+ }
118
+ }
119
+
120
+ // RPC method to set environment variables
121
+ async setEnvVars(envVars: Record<string, string>): Promise<void> {
122
+ // Update local state for new sessions
123
+ this.envVars = { ...this.envVars, ...envVars };
124
+
125
+ // If default session already exists, update it directly
126
+ if (this.defaultSession) {
127
+ // Set environment variables by executing export commands in the existing session
128
+ for (const [key, value] of Object.entries(envVars)) {
129
+ const escapedValue = value.replace(/'/g, "'\\''");
130
+ const exportCommand = `export ${key}='${escapedValue}'`;
131
+
132
+ const result = await this.client.commands.execute(exportCommand, this.defaultSession);
133
+
134
+ if (result.exitCode !== 0) {
135
+ throw new Error(`Failed to set ${key}: ${result.stderr || 'Unknown error'}`);
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Cleanup and destroy the sandbox container
143
+ */
144
+ override async destroy(): Promise<void> {
145
+ this.logger.info('Destroying sandbox container');
146
+ await super.destroy();
147
+ }
148
+
58
149
  override onStart() {
59
- console.log("Sandbox successfully started");
150
+ this.logger.debug('Sandbox started');
60
151
  }
61
152
 
62
153
  override onStop() {
63
- console.log("Sandbox successfully shut down");
64
- if (this.client) {
65
- this.client.clearSession();
66
- }
154
+ this.logger.debug('Sandbox stopped');
67
155
  }
68
156
 
69
157
  override onError(error: unknown) {
70
- console.log("Sandbox error:", error);
158
+ this.logger.error('Sandbox error', error instanceof Error ? error : new Error(String(error)));
71
159
  }
72
160
 
73
- // Override fetch to capture the hostname and route to appropriate ports
161
+ // Override fetch to route internal container requests to appropriate ports
74
162
  override async fetch(request: Request): Promise<Response> {
75
- const url = new URL(request.url);
163
+ // Extract or generate trace ID from request
164
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
76
165
 
77
- // Capture the hostname from the first request
78
- if (!this.workerHostname) {
79
- this.workerHostname = url.hostname;
80
- console.log(`[Sandbox] Captured hostname: ${this.workerHostname}`);
81
- }
166
+ // Create request-specific logger with trace ID
167
+ const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
82
168
 
83
- // Capture and store the sandbox name from the header if present
84
- if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
85
- const name = request.headers.get('X-Sandbox-Name')!;
86
- this.sandboxName = name;
87
- await this.ctx.storage.put('sandboxName', name);
88
- console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
89
- }
169
+ return await runWithLogger(requestLogger, async () => {
170
+ const url = new URL(request.url);
171
+
172
+ // Capture and store the sandbox name from the header if present
173
+ if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
174
+ const name = request.headers.get('X-Sandbox-Name')!;
175
+ this.sandboxName = name;
176
+ await this.ctx.storage.put('sandboxName', name);
177
+ }
90
178
 
91
- // Determine which port to route to
92
- const port = this.determinePort(url);
179
+ // Determine which port to route to
180
+ const port = this.determinePort(url);
93
181
 
94
- // Route to the appropriate port
95
- return await this.containerFetch(request, port);
182
+ // Route to the appropriate port
183
+ return await this.containerFetch(request, port);
184
+ });
96
185
  }
97
186
 
98
187
  private determinePort(url: URL): number {
99
188
  // Extract port from proxy requests (e.g., /proxy/8080/*)
100
189
  const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
101
190
  if (proxyMatch) {
102
- return parseInt(proxyMatch[1]);
191
+ return parseInt(proxyMatch[1], 10);
103
192
  }
104
193
 
105
194
  // All other requests go to control plane on port 3000
@@ -107,97 +196,453 @@ export class Sandbox<Env = unknown> extends Container<Env> {
107
196
  return 3000;
108
197
  }
109
198
 
110
- async exec(command: string, args: string[], options?: { stream?: boolean; background?: boolean }) {
111
- if (options?.stream) {
112
- return this.client.executeStream(command, args, undefined, options?.background);
199
+ /**
200
+ * Ensure default session exists - lazy initialization
201
+ * This is called automatically by all public methods that need a session
202
+ */
203
+ private async ensureDefaultSession(): Promise<string> {
204
+ if (!this.defaultSession) {
205
+ const sessionId = `sandbox-${this.sandboxName || 'default'}`;
206
+
207
+ // Create session in container
208
+ await this.client.utils.createSession({
209
+ id: sessionId,
210
+ env: this.envVars || {},
211
+ cwd: '/workspace',
212
+ });
213
+
214
+ this.defaultSession = sessionId;
215
+ this.logger.debug('Default session initialized', { sessionId });
216
+ }
217
+ return this.defaultSession;
218
+ }
219
+
220
+ // Enhanced exec method - always returns ExecResult with optional streaming
221
+ // This replaces the old exec method to match ISandbox interface
222
+ async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
223
+ const session = await this.ensureDefaultSession();
224
+ return this.execWithSession(command, session, options);
225
+ }
226
+
227
+ /**
228
+ * Internal session-aware exec implementation
229
+ * Used by both public exec() and session wrappers
230
+ */
231
+ private async execWithSession(
232
+ command: string,
233
+ sessionId: string,
234
+ options?: ExecOptions
235
+ ): Promise<ExecResult> {
236
+ const startTime = Date.now();
237
+ const timestamp = new Date().toISOString();
238
+
239
+ // Handle timeout
240
+ let timeoutId: NodeJS.Timeout | undefined;
241
+
242
+ try {
243
+ // Handle cancellation
244
+ if (options?.signal?.aborted) {
245
+ throw new Error('Operation was aborted');
246
+ }
247
+
248
+ let result: ExecResult;
249
+
250
+ if (options?.stream && options?.onOutput) {
251
+ // Streaming with callbacks - we need to collect the final result
252
+ result = await this.executeWithStreaming(command, sessionId, options, startTime, timestamp);
253
+ } else {
254
+ // Regular execution with session
255
+ const response = await this.client.commands.execute(command, sessionId);
256
+
257
+ const duration = Date.now() - startTime;
258
+ result = this.mapExecuteResponseToExecResult(response, duration, sessionId);
259
+ }
260
+
261
+ // Call completion callback if provided
262
+ if (options?.onComplete) {
263
+ options.onComplete(result);
264
+ }
265
+
266
+ return result;
267
+ } catch (error) {
268
+ if (options?.onError && error instanceof Error) {
269
+ options.onError(error);
270
+ }
271
+ throw error;
272
+ } finally {
273
+ if (timeoutId) {
274
+ clearTimeout(timeoutId);
275
+ }
276
+ }
277
+ }
278
+
279
+ private async executeWithStreaming(
280
+ command: string,
281
+ sessionId: string,
282
+ options: ExecOptions,
283
+ startTime: number,
284
+ timestamp: string
285
+ ): Promise<ExecResult> {
286
+ let stdout = '';
287
+ let stderr = '';
288
+
289
+ try {
290
+ const stream = await this.client.commands.executeStream(command, sessionId);
291
+
292
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
293
+ // Check for cancellation
294
+ if (options.signal?.aborted) {
295
+ throw new Error('Operation was aborted');
296
+ }
297
+
298
+ switch (event.type) {
299
+ case 'stdout':
300
+ case 'stderr':
301
+ if (event.data) {
302
+ // Update accumulated output
303
+ if (event.type === 'stdout') stdout += event.data;
304
+ if (event.type === 'stderr') stderr += event.data;
305
+
306
+ // Call user's callback
307
+ if (options.onOutput) {
308
+ options.onOutput(event.type, event.data);
309
+ }
310
+ }
311
+ break;
312
+
313
+ case 'complete': {
314
+ // Use result from complete event if available
315
+ const duration = Date.now() - startTime;
316
+ return {
317
+ success: (event.exitCode ?? 0) === 0,
318
+ exitCode: event.exitCode ?? 0,
319
+ stdout,
320
+ stderr,
321
+ command,
322
+ duration,
323
+ timestamp,
324
+ sessionId
325
+ };
326
+ }
327
+
328
+ case 'error':
329
+ throw new Error(event.data || 'Command execution failed');
330
+ }
331
+ }
332
+
333
+ // If we get here without a complete event, something went wrong
334
+ throw new Error('Stream ended without completion event');
335
+
336
+ } catch (error) {
337
+ if (options.signal?.aborted) {
338
+ throw new Error('Operation was aborted');
339
+ }
340
+ throw error;
341
+ }
342
+ }
343
+
344
+ private mapExecuteResponseToExecResult(
345
+ response: ExecuteResponse,
346
+ duration: number,
347
+ sessionId?: string
348
+ ): ExecResult {
349
+ return {
350
+ success: response.success,
351
+ exitCode: response.exitCode,
352
+ stdout: response.stdout,
353
+ stderr: response.stderr,
354
+ command: response.command,
355
+ duration,
356
+ timestamp: response.timestamp,
357
+ sessionId
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Create a Process domain object from HTTP client DTO
363
+ * Centralizes process object creation with bound methods
364
+ * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
365
+ */
366
+ private createProcessFromDTO(
367
+ data: {
368
+ id: string;
369
+ pid?: number;
370
+ command: string;
371
+ status: ProcessStatus;
372
+ startTime: string | Date;
373
+ endTime?: string | Date;
374
+ exitCode?: number;
375
+ },
376
+ sessionId: string
377
+ ): Process {
378
+ return {
379
+ id: data.id,
380
+ pid: data.pid,
381
+ command: data.command,
382
+ status: data.status,
383
+ startTime: typeof data.startTime === 'string' ? new Date(data.startTime) : data.startTime,
384
+ endTime: data.endTime ? (typeof data.endTime === 'string' ? new Date(data.endTime) : data.endTime) : undefined,
385
+ exitCode: data.exitCode,
386
+ sessionId,
387
+
388
+ kill: async (signal?: string) => {
389
+ await this.killProcess(data.id, signal);
390
+ },
391
+
392
+ getStatus: async () => {
393
+ const current = await this.getProcess(data.id);
394
+ return current?.status || 'error';
395
+ },
396
+
397
+ getLogs: async () => {
398
+ const logs = await this.getProcessLogs(data.id);
399
+ return { stdout: logs.stdout, stderr: logs.stderr };
400
+ }
401
+ };
402
+ }
403
+
404
+
405
+ // Background process management
406
+ async startProcess(command: string, options?: ProcessOptions, sessionId?: string): Promise<Process> {
407
+ // Use the new HttpClient method to start the process
408
+ try {
409
+ const session = sessionId ?? await this.ensureDefaultSession();
410
+ const response = await this.client.processes.startProcess(command, session, {
411
+ processId: options?.processId
412
+ });
413
+
414
+ const processObj = this.createProcessFromDTO({
415
+ id: response.processId,
416
+ pid: response.pid,
417
+ command: response.command,
418
+ status: 'running' as ProcessStatus,
419
+ startTime: new Date(),
420
+ endTime: undefined,
421
+ exitCode: undefined
422
+ }, session);
423
+
424
+ // Call onStart callback if provided
425
+ if (options?.onStart) {
426
+ options.onStart(processObj);
427
+ }
428
+
429
+ return processObj;
430
+
431
+ } catch (error) {
432
+ if (options?.onError && error instanceof Error) {
433
+ options.onError(error);
434
+ }
435
+
436
+ throw error;
437
+ }
438
+ }
439
+
440
+ async listProcesses(sessionId?: string): Promise<Process[]> {
441
+ const session = sessionId ?? await this.ensureDefaultSession();
442
+ const response = await this.client.processes.listProcesses();
443
+
444
+ return response.processes.map(processData =>
445
+ this.createProcessFromDTO({
446
+ id: processData.id,
447
+ pid: processData.pid,
448
+ command: processData.command,
449
+ status: processData.status,
450
+ startTime: processData.startTime,
451
+ endTime: processData.endTime,
452
+ exitCode: processData.exitCode
453
+ }, session)
454
+ );
455
+ }
456
+
457
+ async getProcess(id: string, sessionId?: string): Promise<Process | null> {
458
+ const session = sessionId ?? await this.ensureDefaultSession();
459
+ const response = await this.client.processes.getProcess(id);
460
+ if (!response.process) {
461
+ return null;
462
+ }
463
+
464
+ const processData = response.process;
465
+ return this.createProcessFromDTO({
466
+ id: processData.id,
467
+ pid: processData.pid,
468
+ command: processData.command,
469
+ status: processData.status,
470
+ startTime: processData.startTime,
471
+ endTime: processData.endTime,
472
+ exitCode: processData.exitCode
473
+ }, session);
474
+ }
475
+
476
+ async killProcess(id: string, signal?: string, sessionId?: string): Promise<void> {
477
+ // Note: signal parameter is not currently supported by the HttpClient implementation
478
+ // The HTTP client already throws properly typed errors, so we just let them propagate
479
+ await this.client.processes.killProcess(id);
480
+ }
481
+
482
+ async killAllProcesses(sessionId?: string): Promise<number> {
483
+ const response = await this.client.processes.killAllProcesses();
484
+ return response.cleanedCount;
485
+ }
486
+
487
+ async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
488
+ // For now, this would need to be implemented as a container endpoint
489
+ // as we no longer maintain local process storage
490
+ // We'll return 0 as a placeholder until the container endpoint is added
491
+ return 0;
492
+ }
493
+
494
+ async getProcessLogs(id: string, sessionId?: string): Promise<{ stdout: string; stderr: string; processId: string }> {
495
+ // The HTTP client already throws properly typed errors, so we just let them propagate
496
+ const response = await this.client.processes.getProcessLogs(id);
497
+ return {
498
+ stdout: response.stdout,
499
+ stderr: response.stderr,
500
+ processId: response.processId
501
+ };
502
+ }
503
+
504
+
505
+ // Streaming methods - return ReadableStream for RPC compatibility
506
+ async execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>> {
507
+ // Check for cancellation
508
+ if (options?.signal?.aborted) {
509
+ throw new Error('Operation was aborted');
510
+ }
511
+
512
+ const session = await this.ensureDefaultSession();
513
+ // Get the stream from CommandClient
514
+ return this.client.commands.executeStream(command, session);
515
+ }
516
+
517
+ /**
518
+ * Internal session-aware execStream implementation
519
+ */
520
+ private async execStreamWithSession(command: string, sessionId: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>> {
521
+ // Check for cancellation
522
+ if (options?.signal?.aborted) {
523
+ throw new Error('Operation was aborted');
113
524
  }
114
- return this.client.execute(command, args, undefined, options?.background);
525
+
526
+ return this.client.commands.executeStream(command, sessionId);
527
+ }
528
+
529
+ async streamProcessLogs(processId: string, options?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>> {
530
+ // Check for cancellation
531
+ if (options?.signal?.aborted) {
532
+ throw new Error('Operation was aborted');
533
+ }
534
+
535
+ return this.client.processes.streamProcessLogs(processId);
115
536
  }
116
537
 
117
538
  async gitCheckout(
118
539
  repoUrl: string,
119
- options: { branch?: string; targetDir?: string; stream?: boolean }
540
+ options: { branch?: string; targetDir?: string; sessionId?: string }
120
541
  ) {
121
- if (options?.stream) {
122
- return this.client.gitCheckoutStream(
123
- repoUrl,
124
- options.branch,
125
- options.targetDir
126
- );
127
- }
128
- return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
542
+ const session = options.sessionId ?? await this.ensureDefaultSession();
543
+ return this.client.git.checkout(repoUrl, session, {
544
+ branch: options.branch,
545
+ targetDir: options.targetDir
546
+ });
129
547
  }
130
548
 
131
549
  async mkdir(
132
550
  path: string,
133
- options: { recursive?: boolean; stream?: boolean } = {}
551
+ options: { recursive?: boolean; sessionId?: string } = {}
134
552
  ) {
135
- if (options?.stream) {
136
- return this.client.mkdirStream(path, options.recursive);
137
- }
138
- return this.client.mkdir(path, options.recursive);
553
+ const session = options.sessionId ?? await this.ensureDefaultSession();
554
+ return this.client.files.mkdir(path, session, { recursive: options.recursive });
139
555
  }
140
556
 
141
557
  async writeFile(
142
558
  path: string,
143
559
  content: string,
144
- options: { encoding?: string; stream?: boolean } = {}
560
+ options: { encoding?: string; sessionId?: string } = {}
145
561
  ) {
146
- if (options?.stream) {
147
- return this.client.writeFileStream(path, content, options.encoding);
148
- }
149
- return this.client.writeFile(path, content, options.encoding);
562
+ const session = options.sessionId ?? await this.ensureDefaultSession();
563
+ return this.client.files.writeFile(path, content, session, { encoding: options.encoding });
150
564
  }
151
565
 
152
- async deleteFile(path: string, options: { stream?: boolean } = {}) {
153
- if (options?.stream) {
154
- return this.client.deleteFileStream(path);
155
- }
156
- return this.client.deleteFile(path);
566
+ async deleteFile(path: string, sessionId?: string) {
567
+ const session = sessionId ?? await this.ensureDefaultSession();
568
+ return this.client.files.deleteFile(path, session);
157
569
  }
158
570
 
159
571
  async renameFile(
160
572
  oldPath: string,
161
573
  newPath: string,
162
- options: { stream?: boolean } = {}
574
+ sessionId?: string
163
575
  ) {
164
- if (options?.stream) {
165
- return this.client.renameFileStream(oldPath, newPath);
166
- }
167
- return this.client.renameFile(oldPath, newPath);
576
+ const session = sessionId ?? await this.ensureDefaultSession();
577
+ return this.client.files.renameFile(oldPath, newPath, session);
168
578
  }
169
579
 
170
580
  async moveFile(
171
581
  sourcePath: string,
172
582
  destinationPath: string,
173
- options: { stream?: boolean } = {}
583
+ sessionId?: string
174
584
  ) {
175
- if (options?.stream) {
176
- return this.client.moveFileStream(sourcePath, destinationPath);
177
- }
178
- return this.client.moveFile(sourcePath, destinationPath);
585
+ const session = sessionId ?? await this.ensureDefaultSession();
586
+ return this.client.files.moveFile(sourcePath, destinationPath, session);
179
587
  }
180
588
 
181
589
  async readFile(
182
590
  path: string,
183
- options: { encoding?: string; stream?: boolean } = {}
591
+ options: { encoding?: string; sessionId?: string } = {}
184
592
  ) {
185
- if (options?.stream) {
186
- return this.client.readFileStream(path, options.encoding);
187
- }
188
- return this.client.readFile(path, options.encoding);
593
+ const session = options.sessionId ?? await this.ensureDefaultSession();
594
+ return this.client.files.readFile(path, session, { encoding: options.encoding });
595
+ }
596
+
597
+ /**
598
+ * Stream a file from the sandbox using Server-Sent Events
599
+ * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
600
+ * @param path - Path to the file to stream
601
+ * @param options - Optional session ID
602
+ */
603
+ async readFileStream(
604
+ path: string,
605
+ options: { sessionId?: string } = {}
606
+ ): Promise<ReadableStream<Uint8Array>> {
607
+ const session = options.sessionId ?? await this.ensureDefaultSession();
608
+ return this.client.files.readFileStream(path, session);
609
+ }
610
+
611
+ async listFiles(
612
+ path: string,
613
+ options?: { recursive?: boolean; includeHidden?: boolean }
614
+ ) {
615
+ const session = await this.ensureDefaultSession();
616
+ return this.client.files.listFiles(path, session, options);
189
617
  }
190
618
 
191
- async exposePort(port: number, options?: { name?: string }) {
192
- await this.client.exposePort(port, options?.name);
619
+ async exposePort(port: number, options: { name?: string; hostname: string }) {
620
+ // Check if hostname is workers.dev domain (doesn't support wildcard subdomains)
621
+ if (options.hostname.endsWith('.workers.dev')) {
622
+ const errorResponse: ErrorResponse = {
623
+ code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,
624
+ message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,
625
+ context: { originalError: options.hostname },
626
+ httpStatus: 400,
627
+ timestamp: new Date().toISOString()
628
+ };
629
+ throw new CustomDomainRequiredError(errorResponse);
630
+ }
631
+
632
+ const sessionId = await this.ensureDefaultSession();
633
+ await this.client.ports.exposePort(port, sessionId, options?.name);
193
634
 
194
635
  // We need the sandbox name to construct preview URLs
195
636
  if (!this.sandboxName) {
196
637
  throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
197
638
  }
198
639
 
199
- const hostname = this.getHostname();
200
- const url = this.constructPreviewUrl(port, this.sandboxName, hostname);
640
+ // Generate and store token for this port
641
+ const token = this.generatePortToken();
642
+ this.portTokens.set(port, token);
643
+ await this.persistPortTokens();
644
+
645
+ const url = this.constructPreviewUrl(port, this.sandboxName, options.hostname, token);
201
646
 
202
647
  return {
203
648
  url,
@@ -207,46 +652,265 @@ export class Sandbox<Env = unknown> extends Container<Env> {
207
652
  }
208
653
 
209
654
  async unexposePort(port: number) {
210
- await this.client.unexposePort(port);
655
+ if (!validatePort(port)) {
656
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
657
+ }
658
+
659
+ const sessionId = await this.ensureDefaultSession();
660
+ await this.client.ports.unexposePort(port, sessionId);
661
+
662
+ // Clean up token for this port
663
+ if (this.portTokens.has(port)) {
664
+ this.portTokens.delete(port);
665
+ await this.persistPortTokens();
666
+ }
211
667
  }
212
668
 
213
- async getExposedPorts() {
214
- const response = await this.client.getExposedPorts();
669
+ async getExposedPorts(hostname: string) {
670
+ const sessionId = await this.ensureDefaultSession();
671
+ const response = await this.client.ports.getExposedPorts(sessionId);
215
672
 
216
673
  // We need the sandbox name to construct preview URLs
217
674
  if (!this.sandboxName) {
218
675
  throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
219
676
  }
220
677
 
221
- const hostname = this.getHostname();
678
+ return response.ports.map(port => {
679
+ // Get token for this port - must exist for all exposed ports
680
+ const token = this.portTokens.get(port.port);
681
+ if (!token) {
682
+ throw new Error(`Port ${port.port} is exposed but has no token. This should not happen.`);
683
+ }
684
+
685
+ return {
686
+ url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname, token),
687
+ port: port.port,
688
+ status: port.status,
689
+ };
690
+ });
691
+ }
692
+
693
+
694
+ async isPortExposed(port: number): Promise<boolean> {
695
+ try {
696
+ const sessionId = await this.ensureDefaultSession();
697
+ const response = await this.client.ports.getExposedPorts(sessionId);
698
+ return response.ports.some(exposedPort => exposedPort.port === port);
699
+ } catch (error) {
700
+ this.logger.error('Error checking if port is exposed', error instanceof Error ? error : new Error(String(error)), { port });
701
+ return false;
702
+ }
703
+ }
704
+
705
+ async validatePortToken(port: number, token: string): Promise<boolean> {
706
+ // First check if port is exposed
707
+ const isExposed = await this.isPortExposed(port);
708
+ if (!isExposed) {
709
+ return false;
710
+ }
711
+
712
+ // Get stored token for this port - must exist for all exposed ports
713
+ const storedToken = this.portTokens.get(port);
714
+ if (!storedToken) {
715
+ // This should not happen - all exposed ports must have tokens
716
+ this.logger.error('Port is exposed but has no token - bug detected', undefined, { port });
717
+ return false;
718
+ }
719
+
720
+ // Constant-time comparison to prevent timing attacks
721
+ return storedToken === token;
722
+ }
723
+
724
+ private generatePortToken(): string {
725
+ // Generate cryptographically secure 16-character token using Web Crypto API
726
+ // Available in Cloudflare Workers runtime
727
+ const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)
728
+ crypto.getRandomValues(array);
222
729
 
223
- return response.ports.map(port => ({
224
- url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
225
- port: port.port,
226
- name: port.name,
227
- exposedAt: port.exposedAt,
228
- }));
730
+ // Convert to base64url format (URL-safe, no padding, lowercase)
731
+ const base64 = btoa(String.fromCharCode(...array));
732
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '').toLowerCase();
229
733
  }
230
734
 
231
- private getHostname(): string {
232
- // Use the captured hostname or fall back to localhost for development
233
- return this.workerHostname || "localhost:8787";
735
+ private async persistPortTokens(): Promise<void> {
736
+ // Convert Map to plain object for storage
737
+ const tokensObj: Record<string, string> = {};
738
+ for (const [port, token] of this.portTokens.entries()) {
739
+ tokensObj[port.toString()] = token;
740
+ }
741
+ await this.ctx.storage.put('portTokens', tokensObj);
234
742
  }
235
743
 
236
- private constructPreviewUrl(port: number, sandboxId: string, hostname: string): string {
237
- // Check if this is a localhost pattern
744
+ private constructPreviewUrl(port: number, sandboxId: string, hostname: string, token: string): string {
745
+ if (!validatePort(port)) {
746
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
747
+ }
748
+
749
+ // Validate sandbox ID (will throw SecurityError if invalid)
750
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
751
+
238
752
  const isLocalhost = isLocalhostPattern(hostname);
239
753
 
240
754
  if (isLocalhost) {
241
- // For local development, we need to use a different approach
242
- // Since subdomains don't work with localhost, we'll use the base URL
243
- // with a note that the user needs to handle routing differently
244
- return `http://${hostname}/preview/${port}/${sandboxId}`;
755
+ // Unified subdomain approach for localhost (RFC 6761)
756
+ const [host, portStr] = hostname.split(':');
757
+ const mainPort = portStr || '80';
758
+
759
+ // Use URL constructor for safe URL building
760
+ try {
761
+ const baseUrl = new URL(`http://${host}:${mainPort}`);
762
+ // Construct subdomain safely with mandatory token
763
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
764
+ baseUrl.hostname = subdomainHost;
765
+
766
+ return baseUrl.toString();
767
+ } catch (error) {
768
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
769
+ }
770
+ }
771
+
772
+ // Production subdomain logic - enforce HTTPS
773
+ try {
774
+ // Always use HTTPS for production (non-localhost)
775
+ const protocol = "https";
776
+ const baseUrl = new URL(`${protocol}://${hostname}`);
777
+
778
+ // Construct subdomain safely with mandatory token
779
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
780
+ baseUrl.hostname = subdomainHost;
781
+
782
+ return baseUrl.toString();
783
+ } catch (error) {
784
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
245
785
  }
786
+ }
787
+
788
+ // ============================================================================
789
+ // Session Management - Advanced Use Cases
790
+ // ============================================================================
791
+
792
+ /**
793
+ * Create isolated execution session for advanced use cases
794
+ * Returns ExecutionSession with full sandbox API bound to specific session
795
+ */
796
+ async createSession(options?: SessionOptions): Promise<ExecutionSession> {
797
+ const sessionId = options?.id || `session-${Date.now()}`;
798
+
799
+ // Create session in container
800
+ await this.client.utils.createSession({
801
+ id: sessionId,
802
+ env: options?.env,
803
+ cwd: options?.cwd,
804
+ });
805
+
806
+ // Return wrapper that binds sessionId to all operations
807
+ return this.getSessionWrapper(sessionId);
808
+ }
809
+
810
+ /**
811
+ * Get an existing session by ID
812
+ * Returns ExecutionSession wrapper bound to the specified session
813
+ *
814
+ * This is useful for retrieving sessions across different requests/contexts
815
+ * without storing the ExecutionSession object (which has RPC lifecycle limitations)
816
+ *
817
+ * @param sessionId - The ID of an existing session
818
+ * @returns ExecutionSession wrapper bound to the session
819
+ */
820
+ async getSession(sessionId: string): Promise<ExecutionSession> {
821
+ // No need to verify session exists in container - operations will fail naturally if it doesn't
822
+ return this.getSessionWrapper(sessionId);
823
+ }
824
+
825
+ /**
826
+ * Internal helper to create ExecutionSession wrapper for a given sessionId
827
+ * Used by both createSession and getSession
828
+ */
829
+ private getSessionWrapper(sessionId: string): ExecutionSession {
830
+ return {
831
+ id: sessionId,
832
+
833
+ // Command execution - delegate to internal session-aware methods
834
+ exec: (command, options) => this.execWithSession(command, sessionId, options),
835
+ execStream: (command, options) => this.execStreamWithSession(command, sessionId, options),
836
+
837
+ // Process management
838
+ startProcess: (command, options) => this.startProcess(command, options, sessionId),
839
+ listProcesses: () => this.listProcesses(sessionId),
840
+ getProcess: (id) => this.getProcess(id, sessionId),
841
+ killProcess: (id, signal) => this.killProcess(id, signal),
842
+ killAllProcesses: () => this.killAllProcesses(),
843
+ cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),
844
+ getProcessLogs: (id) => this.getProcessLogs(id),
845
+ streamProcessLogs: (processId, options) => this.streamProcessLogs(processId, options),
846
+
847
+ // File operations - pass sessionId via options or parameter
848
+ writeFile: (path, content, options) => this.writeFile(path, content, { ...options, sessionId }),
849
+ readFile: (path, options) => this.readFile(path, { ...options, sessionId }),
850
+ readFileStream: (path) => this.readFileStream(path, { sessionId }),
851
+ mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),
852
+ deleteFile: (path) => this.deleteFile(path, sessionId),
853
+ renameFile: (oldPath, newPath) => this.renameFile(oldPath, newPath, sessionId),
854
+ moveFile: (sourcePath, destPath) => this.moveFile(sourcePath, destPath, sessionId),
855
+ listFiles: (path, options) => this.client.files.listFiles(path, sessionId, options),
856
+
857
+ // Git operations
858
+ gitCheckout: (repoUrl, options) => this.gitCheckout(repoUrl, { ...options, sessionId }),
859
+
860
+ // Environment management - needs special handling
861
+ setEnvVars: async (envVars: Record<string, string>) => {
862
+ try {
863
+ // Set environment variables by executing export commands
864
+ for (const [key, value] of Object.entries(envVars)) {
865
+ const escapedValue = value.replace(/'/g, "'\\''");
866
+ const exportCommand = `export ${key}='${escapedValue}'`;
867
+
868
+ const result = await this.client.commands.execute(exportCommand, sessionId);
869
+
870
+ if (result.exitCode !== 0) {
871
+ throw new Error(`Failed to set ${key}: ${result.stderr || 'Unknown error'}`);
872
+ }
873
+ }
874
+ } catch (error) {
875
+ this.logger.error('Failed to set environment variables', error instanceof Error ? error : new Error(String(error)), { sessionId });
876
+ throw error;
877
+ }
878
+ },
879
+
880
+ // Code interpreter methods - delegate to sandbox's code interpreter
881
+ createCodeContext: (options) => this.codeInterpreter.createCodeContext(options),
882
+ runCode: async (code, options) => {
883
+ const execution = await this.codeInterpreter.runCode(code, options);
884
+ return execution.toJSON();
885
+ },
886
+ runCodeStream: (code, options) => this.codeInterpreter.runCodeStream(code, options),
887
+ listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
888
+ deleteCodeContext: (contextId) => this.codeInterpreter.deleteCodeContext(contextId),
889
+ };
890
+ }
891
+
892
+ // ============================================================================
893
+ // Code interpreter methods - delegate to CodeInterpreter wrapper
894
+ // ============================================================================
895
+
896
+ async createCodeContext(options?: CreateContextOptions): Promise<CodeContext> {
897
+ return this.codeInterpreter.createCodeContext(options);
898
+ }
899
+
900
+ async runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult> {
901
+ const execution = await this.codeInterpreter.runCode(code, options);
902
+ return execution.toJSON();
903
+ }
904
+
905
+ async runCodeStream(code: string, options?: RunCodeOptions): Promise<ReadableStream> {
906
+ return this.codeInterpreter.runCodeStream(code, options);
907
+ }
908
+
909
+ async listCodeContexts(): Promise<CodeContext[]> {
910
+ return this.codeInterpreter.listCodeContexts();
911
+ }
246
912
 
247
- // For all other domains (workers.dev, custom domains, etc.)
248
- // Use subdomain-based routing pattern
249
- const protocol = hostname.includes(":") ? "http" : "https";
250
- return `${protocol}://${port}-${sandboxId}.${hostname}`;
913
+ async deleteCodeContext(contextId: string): Promise<void> {
914
+ return this.codeInterpreter.deleteCodeContext(contextId);
251
915
  }
252
916
  }