@cloudflare/sandbox 0.0.0-16a90ce → 0.0.0-17d2a4d

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 (56) hide show
  1. package/CHANGELOG.md +300 -0
  2. package/Dockerfile +142 -9
  3. package/README.md +154 -50
  4. package/dist/index.d.ts +1889 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +3146 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +16 -12
  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 +91 -0
  13. package/src/clients/index.ts +60 -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 +123 -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 +91 -120
  25. package/src/interpreter.ts +168 -0
  26. package/src/request-handler.ts +183 -0
  27. package/src/sandbox.ts +1235 -0
  28. package/src/security.ts +119 -0
  29. package/src/sse-parser.ts +144 -0
  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 +415 -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 +706 -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/index.ts +0 -2906
  50. package/container_src/package.json +0 -9
  51. package/src/client.ts +0 -1950
  52. package/tests/client.example.ts +0 -308
  53. package/tests/connection-test.ts +0 -81
  54. package/tests/simple-test.ts +0 -81
  55. package/tests/test1.ts +0 -281
  56. package/tests/test2.ts +0 -929
package/src/sandbox.ts ADDED
@@ -0,0 +1,1235 @@
1
+ import type { DurableObject } from 'cloudflare:workers';
2
+ import { Container, getContainer, switchPort } from '@cloudflare/containers';
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
+ SandboxOptions,
17
+ SessionOptions,
18
+ StreamOptions
19
+ } from '@repo/shared';
20
+ import { createLogger, runWithLogger, TraceContext } from '@repo/shared';
21
+ import { type ExecuteResponse, SandboxClient } from './clients';
22
+ import type { ErrorResponse } from './errors';
23
+ import { CustomDomainRequiredError, ErrorCode } from './errors';
24
+ import { CodeInterpreter } from './interpreter';
25
+ import { isLocalhostPattern } from './request-handler';
26
+ import { SecurityError, sanitizeSandboxId, validatePort } from './security';
27
+ import { parseSSEStream } from './sse-parser';
28
+ import { SDK_VERSION } from './version';
29
+
30
+ export function getSandbox(
31
+ ns: DurableObjectNamespace<Sandbox>,
32
+ id: string,
33
+ options?: SandboxOptions
34
+ ): Sandbox {
35
+ const stub = getContainer(ns, id) as unknown as Sandbox;
36
+
37
+ // Store the name on first access
38
+ stub.setSandboxName?.(id);
39
+
40
+ if (options?.baseUrl) {
41
+ stub.setBaseUrl(options.baseUrl);
42
+ }
43
+
44
+ if (options?.sleepAfter !== undefined) {
45
+ stub.setSleepAfter(options.sleepAfter);
46
+ }
47
+
48
+ if (options?.keepAlive !== undefined) {
49
+ stub.setKeepAlive(options.keepAlive);
50
+ }
51
+
52
+ return Object.assign(stub, {
53
+ wsConnect: connect(stub)
54
+ });
55
+ }
56
+
57
+ export function connect(
58
+ stub: { fetch: (request: Request) => Promise<Response> }
59
+ ) {
60
+ return async (request: Request, port: number) => {
61
+ // Validate port before routing
62
+ if (!validatePort(port)) {
63
+ throw new SecurityError(
64
+ `Invalid or restricted port: ${port}. Ports must be in range 1024-65535 and not reserved.`
65
+ );
66
+ }
67
+ const portSwitchedRequest = switchPort(request, port);
68
+ return await stub.fetch(portSwitchedRequest);
69
+ };
70
+ }
71
+
72
+ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
73
+ defaultPort = 3000; // Default port for the container's Bun server
74
+ sleepAfter: string | number = '10m'; // Sleep the sandbox if no requests are made in this timeframe
75
+
76
+ client: SandboxClient;
77
+ private codeInterpreter: CodeInterpreter;
78
+ private sandboxName: string | null = null;
79
+ private baseUrl: string | null = null;
80
+ private portTokens: Map<number, string> = new Map();
81
+ private defaultSession: string | null = null;
82
+ envVars: Record<string, string> = {};
83
+ private logger: ReturnType<typeof createLogger>;
84
+ private keepAliveEnabled: boolean = false;
85
+
86
+ constructor(ctx: DurableObjectState<{}>, env: Env) {
87
+ super(ctx, env);
88
+
89
+ const envObj = env as any;
90
+ // Set sandbox environment variables from env object
91
+ const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;
92
+ sandboxEnvKeys.forEach((key) => {
93
+ if (envObj?.[key]) {
94
+ this.envVars[key] = envObj[key];
95
+ }
96
+ });
97
+
98
+ this.logger = createLogger({
99
+ component: 'sandbox-do',
100
+ sandboxId: this.ctx.id.toString()
101
+ });
102
+
103
+ this.client = new SandboxClient({
104
+ logger: this.logger,
105
+ port: 3000, // Control plane port
106
+ stub: this
107
+ });
108
+
109
+ // Initialize code interpreter - pass 'this' after client is ready
110
+ // The CodeInterpreter extracts client.interpreter from the sandbox
111
+ this.codeInterpreter = new CodeInterpreter(this);
112
+
113
+ // Load the sandbox name, port tokens, and default session from storage on initialization
114
+ this.ctx.blockConcurrencyWhile(async () => {
115
+ this.sandboxName =
116
+ (await this.ctx.storage.get<string>('sandboxName')) || null;
117
+ this.defaultSession =
118
+ (await this.ctx.storage.get<string>('defaultSession')) || null;
119
+ const storedTokens =
120
+ (await this.ctx.storage.get<Record<string, string>>('portTokens')) ||
121
+ {};
122
+
123
+ // Convert stored tokens back to Map
124
+ this.portTokens = new Map();
125
+ for (const [portStr, token] of Object.entries(storedTokens)) {
126
+ this.portTokens.set(parseInt(portStr, 10), token);
127
+ }
128
+ });
129
+ }
130
+
131
+ // RPC method to set the sandbox name
132
+ async setSandboxName(name: string): Promise<void> {
133
+ if (!this.sandboxName) {
134
+ this.sandboxName = name;
135
+ await this.ctx.storage.put('sandboxName', name);
136
+ }
137
+ }
138
+
139
+ // RPC method to set the base URL
140
+ async setBaseUrl(baseUrl: string): Promise<void> {
141
+ if (!this.baseUrl) {
142
+ this.baseUrl = baseUrl;
143
+ await this.ctx.storage.put('baseUrl', baseUrl);
144
+ } else {
145
+ if (this.baseUrl !== baseUrl) {
146
+ throw new Error(
147
+ 'Base URL already set and different from one previously provided'
148
+ );
149
+ }
150
+ }
151
+ }
152
+
153
+ // RPC method to set the sleep timeout
154
+ async setSleepAfter(sleepAfter: string | number): Promise<void> {
155
+ this.sleepAfter = sleepAfter;
156
+ }
157
+
158
+ // RPC method to enable keepAlive mode
159
+ async setKeepAlive(keepAlive: boolean): Promise<void> {
160
+ this.keepAliveEnabled = keepAlive;
161
+ if (keepAlive) {
162
+ this.logger.info(
163
+ 'KeepAlive mode enabled - container will stay alive until explicitly destroyed'
164
+ );
165
+ } else {
166
+ this.logger.info(
167
+ 'KeepAlive mode disabled - container will timeout normally'
168
+ );
169
+ }
170
+ }
171
+
172
+ // RPC method to set environment variables
173
+ async setEnvVars(envVars: Record<string, string>): Promise<void> {
174
+ // Update local state for new sessions
175
+ this.envVars = { ...this.envVars, ...envVars };
176
+
177
+ // If default session already exists, update it directly
178
+ if (this.defaultSession) {
179
+ // Set environment variables by executing export commands in the existing session
180
+ for (const [key, value] of Object.entries(envVars)) {
181
+ const escapedValue = value.replace(/'/g, "'\\''");
182
+ const exportCommand = `export ${key}='${escapedValue}'`;
183
+
184
+ const result = await this.client.commands.execute(
185
+ exportCommand,
186
+ this.defaultSession
187
+ );
188
+
189
+ if (result.exitCode !== 0) {
190
+ throw new Error(
191
+ `Failed to set ${key}: ${result.stderr || 'Unknown error'}`
192
+ );
193
+ }
194
+ }
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Cleanup and destroy the sandbox container
200
+ */
201
+ override async destroy(): Promise<void> {
202
+ this.logger.info('Destroying sandbox container');
203
+ await super.destroy();
204
+ }
205
+
206
+ override onStart() {
207
+ this.logger.debug('Sandbox started');
208
+
209
+ // Check version compatibility asynchronously (don't block startup)
210
+ this.checkVersionCompatibility().catch((error) => {
211
+ this.logger.error(
212
+ 'Version compatibility check failed',
213
+ error instanceof Error ? error : new Error(String(error))
214
+ );
215
+ });
216
+ }
217
+
218
+ /**
219
+ * Check if the container version matches the SDK version
220
+ * Logs a warning if there's a mismatch
221
+ */
222
+ private async checkVersionCompatibility(): Promise<void> {
223
+ try {
224
+ // Get the SDK version (imported from version.ts)
225
+ const sdkVersion = SDK_VERSION;
226
+
227
+ // Get container version
228
+ const containerVersion = await this.client.utils.getVersion();
229
+
230
+ // If container version is unknown, it's likely an old container without the endpoint
231
+ if (containerVersion === 'unknown') {
232
+ this.logger.warn(
233
+ 'Container version check: Container version could not be determined. ' +
234
+ 'This may indicate an outdated container image. ' +
235
+ 'Please update your container to match SDK version ' +
236
+ sdkVersion
237
+ );
238
+ return;
239
+ }
240
+
241
+ // Check if versions match
242
+ if (containerVersion !== sdkVersion) {
243
+ const message =
244
+ `Version mismatch detected! SDK version (${sdkVersion}) does not match ` +
245
+ `container version (${containerVersion}). This may cause compatibility issues. ` +
246
+ `Please update your container image to version ${sdkVersion}`;
247
+
248
+ // Log warning - we can't reliably detect dev vs prod environment in Durable Objects
249
+ // so we always use warning level as requested by the user
250
+ this.logger.warn(message);
251
+ } else {
252
+ this.logger.debug('Version check passed', {
253
+ sdkVersion,
254
+ containerVersion
255
+ });
256
+ }
257
+ } catch (error) {
258
+ // Don't fail the sandbox initialization if version check fails
259
+ this.logger.debug('Version compatibility check encountered an error', {
260
+ error: error instanceof Error ? error.message : String(error)
261
+ });
262
+ }
263
+ }
264
+
265
+ override onStop() {
266
+ this.logger.debug('Sandbox stopped');
267
+ }
268
+
269
+ override onError(error: unknown) {
270
+ this.logger.error(
271
+ 'Sandbox error',
272
+ error instanceof Error ? error : new Error(String(error))
273
+ );
274
+ }
275
+
276
+ /**
277
+ * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled
278
+ * When keepAlive is disabled, calls parent implementation which stops the container
279
+ */
280
+ override async onActivityExpired(): Promise<void> {
281
+ if (this.keepAliveEnabled) {
282
+ this.logger.debug(
283
+ 'Activity expired but keepAlive is enabled - container will stay alive'
284
+ );
285
+ // Do nothing - don't call stop(), container stays alive
286
+ } else {
287
+ // Default behavior: stop the container
288
+ this.logger.debug('Activity expired - stopping container');
289
+ await super.onActivityExpired();
290
+ }
291
+ }
292
+
293
+ // Override fetch to route internal container requests to appropriate ports
294
+ override async fetch(request: Request): Promise<Response> {
295
+ // Extract or generate trace ID from request
296
+ const traceId =
297
+ TraceContext.fromHeaders(request.headers) || TraceContext.generate();
298
+
299
+ // Create request-specific logger with trace ID
300
+ const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
301
+
302
+ return await runWithLogger(requestLogger, async () => {
303
+ const url = new URL(request.url);
304
+
305
+ // Capture and store the sandbox name from the header if present
306
+ if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
307
+ const name = request.headers.get('X-Sandbox-Name')!;
308
+ this.sandboxName = name;
309
+ await this.ctx.storage.put('sandboxName', name);
310
+ }
311
+
312
+ // Detect WebSocket upgrade request (RFC 6455 compliant)
313
+ const upgradeHeader = request.headers.get('Upgrade');
314
+ const connectionHeader = request.headers.get('Connection');
315
+ const isWebSocket =
316
+ upgradeHeader?.toLowerCase() === 'websocket' &&
317
+ connectionHeader?.toLowerCase().includes('upgrade');
318
+
319
+ if (isWebSocket) {
320
+ // WebSocket path: Let parent Container class handle WebSocket proxying
321
+ // This bypasses containerFetch() which uses JSRPC and cannot handle WebSocket upgrades
322
+ try {
323
+ requestLogger.debug('WebSocket upgrade requested', {
324
+ path: url.pathname,
325
+ port: this.determinePort(url)
326
+ });
327
+ return await super.fetch(request);
328
+ } catch (error) {
329
+ requestLogger.error(
330
+ 'WebSocket connection failed',
331
+ error instanceof Error ? error : new Error(String(error)),
332
+ { path: url.pathname }
333
+ );
334
+ throw error;
335
+ }
336
+ }
337
+
338
+ // Non-WebSocket: Use existing port determination and HTTP routing logic
339
+ const port = this.determinePort(url);
340
+
341
+ // Route to the appropriate port
342
+ return await this.containerFetch(request, port);
343
+ });
344
+ }
345
+
346
+ wsConnect(request: Request, port: number): Promise<Response> {
347
+ // Dummy implementation that will be overridden by the stub
348
+ throw new Error('Not implemented here to avoid RPC serialization issues');
349
+ }
350
+
351
+ private determinePort(url: URL): number {
352
+ // Extract port from proxy requests (e.g., /proxy/8080/*)
353
+ const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
354
+ if (proxyMatch) {
355
+ return parseInt(proxyMatch[1], 10);
356
+ }
357
+
358
+ // All other requests go to control plane on port 3000
359
+ // This includes /api/* endpoints and any other control requests
360
+ return 3000;
361
+ }
362
+
363
+ /**
364
+ * Ensure default session exists - lazy initialization
365
+ * This is called automatically by all public methods that need a session
366
+ *
367
+ * The session is persisted to Durable Object storage to survive hot reloads
368
+ * during development. If a session already exists in the container after reload,
369
+ * we reuse it instead of trying to create a new one.
370
+ */
371
+ private async ensureDefaultSession(): Promise<string> {
372
+ if (!this.defaultSession) {
373
+ const sessionId = `sandbox-${this.sandboxName || 'default'}`;
374
+
375
+ try {
376
+ // Try to create session in container
377
+ await this.client.utils.createSession({
378
+ id: sessionId,
379
+ env: this.envVars || {},
380
+ cwd: '/workspace'
381
+ });
382
+
383
+ this.defaultSession = sessionId;
384
+ // Persist to storage so it survives hot reloads
385
+ await this.ctx.storage.put('defaultSession', sessionId);
386
+ this.logger.debug('Default session initialized', { sessionId });
387
+ } catch (error: any) {
388
+ // If session already exists (e.g., after hot reload), reuse it
389
+ if (error?.message?.includes('already exists')) {
390
+ this.logger.debug('Reusing existing session after reload', {
391
+ sessionId
392
+ });
393
+ this.defaultSession = sessionId;
394
+ // Persist to storage in case it wasn't saved before
395
+ await this.ctx.storage.put('defaultSession', sessionId);
396
+ } else {
397
+ // Re-throw other errors
398
+ throw error;
399
+ }
400
+ }
401
+ }
402
+ return this.defaultSession;
403
+ }
404
+
405
+ // Enhanced exec method - always returns ExecResult with optional streaming
406
+ // This replaces the old exec method to match ISandbox interface
407
+ async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
408
+ const session = await this.ensureDefaultSession();
409
+ return this.execWithSession(command, session, options);
410
+ }
411
+
412
+ /**
413
+ * Internal session-aware exec implementation
414
+ * Used by both public exec() and session wrappers
415
+ */
416
+ private async execWithSession(
417
+ command: string,
418
+ sessionId: string,
419
+ options?: ExecOptions
420
+ ): Promise<ExecResult> {
421
+ const startTime = Date.now();
422
+ const timestamp = new Date().toISOString();
423
+
424
+ let timeoutId: NodeJS.Timeout | undefined;
425
+
426
+ try {
427
+ // Handle cancellation
428
+ if (options?.signal?.aborted) {
429
+ throw new Error('Operation was aborted');
430
+ }
431
+
432
+ let result: ExecResult;
433
+
434
+ if (options?.stream && options?.onOutput) {
435
+ // Streaming with callbacks - we need to collect the final result
436
+ result = await this.executeWithStreaming(
437
+ command,
438
+ sessionId,
439
+ options,
440
+ startTime,
441
+ timestamp
442
+ );
443
+ } else {
444
+ // Regular execution with session
445
+ const response = await this.client.commands.execute(command, sessionId);
446
+
447
+ const duration = Date.now() - startTime;
448
+ result = this.mapExecuteResponseToExecResult(
449
+ response,
450
+ duration,
451
+ sessionId
452
+ );
453
+ }
454
+
455
+ // Call completion callback if provided
456
+ if (options?.onComplete) {
457
+ options.onComplete(result);
458
+ }
459
+
460
+ return result;
461
+ } catch (error) {
462
+ if (options?.onError && error instanceof Error) {
463
+ options.onError(error);
464
+ }
465
+ throw error;
466
+ } finally {
467
+ if (timeoutId) {
468
+ clearTimeout(timeoutId);
469
+ }
470
+ }
471
+ }
472
+
473
+ private async executeWithStreaming(
474
+ command: string,
475
+ sessionId: string,
476
+ options: ExecOptions,
477
+ startTime: number,
478
+ timestamp: string
479
+ ): Promise<ExecResult> {
480
+ let stdout = '';
481
+ let stderr = '';
482
+
483
+ try {
484
+ const stream = await this.client.commands.executeStream(
485
+ command,
486
+ sessionId
487
+ );
488
+
489
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
490
+ // Check for cancellation
491
+ if (options.signal?.aborted) {
492
+ throw new Error('Operation was aborted');
493
+ }
494
+
495
+ switch (event.type) {
496
+ case 'stdout':
497
+ case 'stderr':
498
+ if (event.data) {
499
+ // Update accumulated output
500
+ if (event.type === 'stdout') stdout += event.data;
501
+ if (event.type === 'stderr') stderr += event.data;
502
+
503
+ // Call user's callback
504
+ if (options.onOutput) {
505
+ options.onOutput(event.type, event.data);
506
+ }
507
+ }
508
+ break;
509
+
510
+ case 'complete': {
511
+ // Use result from complete event if available
512
+ const duration = Date.now() - startTime;
513
+ return {
514
+ success: (event.exitCode ?? 0) === 0,
515
+ exitCode: event.exitCode ?? 0,
516
+ stdout,
517
+ stderr,
518
+ command,
519
+ duration,
520
+ timestamp,
521
+ sessionId
522
+ };
523
+ }
524
+
525
+ case 'error':
526
+ throw new Error(event.data || 'Command execution failed');
527
+ }
528
+ }
529
+
530
+ // If we get here without a complete event, something went wrong
531
+ throw new Error('Stream ended without completion event');
532
+ } catch (error) {
533
+ if (options.signal?.aborted) {
534
+ throw new Error('Operation was aborted');
535
+ }
536
+ throw error;
537
+ }
538
+ }
539
+
540
+ private mapExecuteResponseToExecResult(
541
+ response: ExecuteResponse,
542
+ duration: number,
543
+ sessionId?: string
544
+ ): ExecResult {
545
+ return {
546
+ success: response.success,
547
+ exitCode: response.exitCode,
548
+ stdout: response.stdout,
549
+ stderr: response.stderr,
550
+ command: response.command,
551
+ duration,
552
+ timestamp: response.timestamp,
553
+ sessionId
554
+ };
555
+ }
556
+
557
+ /**
558
+ * Create a Process domain object from HTTP client DTO
559
+ * Centralizes process object creation with bound methods
560
+ * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
561
+ */
562
+ private createProcessFromDTO(
563
+ data: {
564
+ id: string;
565
+ pid?: number;
566
+ command: string;
567
+ status: ProcessStatus;
568
+ startTime: string | Date;
569
+ endTime?: string | Date;
570
+ exitCode?: number;
571
+ },
572
+ sessionId: string
573
+ ): Process {
574
+ return {
575
+ id: data.id,
576
+ pid: data.pid,
577
+ command: data.command,
578
+ status: data.status,
579
+ startTime:
580
+ typeof data.startTime === 'string'
581
+ ? new Date(data.startTime)
582
+ : data.startTime,
583
+ endTime: data.endTime
584
+ ? typeof data.endTime === 'string'
585
+ ? new Date(data.endTime)
586
+ : data.endTime
587
+ : undefined,
588
+ exitCode: data.exitCode,
589
+ sessionId,
590
+
591
+ kill: async (signal?: string) => {
592
+ await this.killProcess(data.id, signal);
593
+ },
594
+
595
+ getStatus: async () => {
596
+ const current = await this.getProcess(data.id);
597
+ return current?.status || 'error';
598
+ },
599
+
600
+ getLogs: async () => {
601
+ const logs = await this.getProcessLogs(data.id);
602
+ return { stdout: logs.stdout, stderr: logs.stderr };
603
+ }
604
+ };
605
+ }
606
+
607
+ // Background process management
608
+ async startProcess(
609
+ command: string,
610
+ options?: ProcessOptions,
611
+ sessionId?: string
612
+ ): Promise<Process> {
613
+ // Use the new HttpClient method to start the process
614
+ try {
615
+ const session = sessionId ?? (await this.ensureDefaultSession());
616
+ const response = await this.client.processes.startProcess(
617
+ command,
618
+ session,
619
+ {
620
+ processId: options?.processId
621
+ }
622
+ );
623
+
624
+ const processObj = this.createProcessFromDTO(
625
+ {
626
+ id: response.processId,
627
+ pid: response.pid,
628
+ command: response.command,
629
+ status: 'running' as ProcessStatus,
630
+ startTime: new Date(),
631
+ endTime: undefined,
632
+ exitCode: undefined
633
+ },
634
+ session
635
+ );
636
+
637
+ // Call onStart callback if provided
638
+ if (options?.onStart) {
639
+ options.onStart(processObj);
640
+ }
641
+
642
+ return processObj;
643
+ } catch (error) {
644
+ if (options?.onError && error instanceof Error) {
645
+ options.onError(error);
646
+ }
647
+
648
+ throw error;
649
+ }
650
+ }
651
+
652
+ async listProcesses(sessionId?: string): Promise<Process[]> {
653
+ const session = sessionId ?? (await this.ensureDefaultSession());
654
+ const response = await this.client.processes.listProcesses();
655
+
656
+ return response.processes.map((processData) =>
657
+ this.createProcessFromDTO(
658
+ {
659
+ id: processData.id,
660
+ pid: processData.pid,
661
+ command: processData.command,
662
+ status: processData.status,
663
+ startTime: processData.startTime,
664
+ endTime: processData.endTime,
665
+ exitCode: processData.exitCode
666
+ },
667
+ session
668
+ )
669
+ );
670
+ }
671
+
672
+ async getProcess(id: string, sessionId?: string): Promise<Process | null> {
673
+ const session = sessionId ?? (await this.ensureDefaultSession());
674
+ const response = await this.client.processes.getProcess(id);
675
+ if (!response.process) {
676
+ return null;
677
+ }
678
+
679
+ const processData = response.process;
680
+ return this.createProcessFromDTO(
681
+ {
682
+ id: processData.id,
683
+ pid: processData.pid,
684
+ command: processData.command,
685
+ status: processData.status,
686
+ startTime: processData.startTime,
687
+ endTime: processData.endTime,
688
+ exitCode: processData.exitCode
689
+ },
690
+ session
691
+ );
692
+ }
693
+
694
+ async killProcess(
695
+ id: string,
696
+ signal?: string,
697
+ sessionId?: string
698
+ ): Promise<void> {
699
+ // Note: signal parameter is not currently supported by the HttpClient implementation
700
+ // The HTTP client already throws properly typed errors, so we just let them propagate
701
+ await this.client.processes.killProcess(id);
702
+ }
703
+
704
+ async killAllProcesses(sessionId?: string): Promise<number> {
705
+ const response = await this.client.processes.killAllProcesses();
706
+ return response.cleanedCount;
707
+ }
708
+
709
+ async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
710
+ // For now, this would need to be implemented as a container endpoint
711
+ // as we no longer maintain local process storage
712
+ // We'll return 0 as a placeholder until the container endpoint is added
713
+ return 0;
714
+ }
715
+
716
+ async getProcessLogs(
717
+ id: string,
718
+ sessionId?: string
719
+ ): Promise<{ stdout: string; stderr: string; processId: string }> {
720
+ // The HTTP client already throws properly typed errors, so we just let them propagate
721
+ const response = await this.client.processes.getProcessLogs(id);
722
+ return {
723
+ stdout: response.stdout,
724
+ stderr: response.stderr,
725
+ processId: response.processId
726
+ };
727
+ }
728
+
729
+ // Streaming methods - return ReadableStream for RPC compatibility
730
+ async execStream(
731
+ command: string,
732
+ options?: StreamOptions
733
+ ): Promise<ReadableStream<Uint8Array>> {
734
+ // Check for cancellation
735
+ if (options?.signal?.aborted) {
736
+ throw new Error('Operation was aborted');
737
+ }
738
+
739
+ const session = await this.ensureDefaultSession();
740
+ // Get the stream from CommandClient
741
+ return this.client.commands.executeStream(command, session);
742
+ }
743
+
744
+ /**
745
+ * Internal session-aware execStream implementation
746
+ */
747
+ private async execStreamWithSession(
748
+ command: string,
749
+ sessionId: string,
750
+ options?: StreamOptions
751
+ ): Promise<ReadableStream<Uint8Array>> {
752
+ // Check for cancellation
753
+ if (options?.signal?.aborted) {
754
+ throw new Error('Operation was aborted');
755
+ }
756
+
757
+ return this.client.commands.executeStream(command, sessionId);
758
+ }
759
+
760
+ /**
761
+ * Stream logs from a background process as a ReadableStream.
762
+ */
763
+ async streamProcessLogs(
764
+ processId: string,
765
+ options?: { signal?: AbortSignal }
766
+ ): Promise<ReadableStream<Uint8Array>> {
767
+ // Check for cancellation
768
+ if (options?.signal?.aborted) {
769
+ throw new Error('Operation was aborted');
770
+ }
771
+
772
+ return this.client.processes.streamProcessLogs(processId);
773
+ }
774
+
775
+ async gitCheckout(
776
+ repoUrl: string,
777
+ options: { branch?: string; targetDir?: string; sessionId?: string }
778
+ ) {
779
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
780
+ return this.client.git.checkout(repoUrl, session, {
781
+ branch: options.branch,
782
+ targetDir: options.targetDir
783
+ });
784
+ }
785
+
786
+ async mkdir(
787
+ path: string,
788
+ options: { recursive?: boolean; sessionId?: string } = {}
789
+ ) {
790
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
791
+ return this.client.files.mkdir(path, session, {
792
+ recursive: options.recursive
793
+ });
794
+ }
795
+
796
+ async writeFile(
797
+ path: string,
798
+ content: string,
799
+ options: { encoding?: string; sessionId?: string } = {}
800
+ ) {
801
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
802
+ return this.client.files.writeFile(path, content, session, {
803
+ encoding: options.encoding
804
+ });
805
+ }
806
+
807
+ async deleteFile(path: string, sessionId?: string) {
808
+ const session = sessionId ?? (await this.ensureDefaultSession());
809
+ return this.client.files.deleteFile(path, session);
810
+ }
811
+
812
+ async renameFile(oldPath: string, newPath: string, sessionId?: string) {
813
+ const session = sessionId ?? (await this.ensureDefaultSession());
814
+ return this.client.files.renameFile(oldPath, newPath, session);
815
+ }
816
+
817
+ async moveFile(
818
+ sourcePath: string,
819
+ destinationPath: string,
820
+ sessionId?: string
821
+ ) {
822
+ const session = sessionId ?? (await this.ensureDefaultSession());
823
+ return this.client.files.moveFile(sourcePath, destinationPath, session);
824
+ }
825
+
826
+ async readFile(
827
+ path: string,
828
+ options: { encoding?: string; sessionId?: string } = {}
829
+ ) {
830
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
831
+ return this.client.files.readFile(path, session, {
832
+ encoding: options.encoding
833
+ });
834
+ }
835
+
836
+ /**
837
+ * Stream a file from the sandbox using Server-Sent Events
838
+ * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
839
+ * @param path - Path to the file to stream
840
+ * @param options - Optional session ID
841
+ */
842
+ async readFileStream(
843
+ path: string,
844
+ options: { sessionId?: string } = {}
845
+ ): Promise<ReadableStream<Uint8Array>> {
846
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
847
+ return this.client.files.readFileStream(path, session);
848
+ }
849
+
850
+ async listFiles(
851
+ path: string,
852
+ options?: { recursive?: boolean; includeHidden?: boolean }
853
+ ) {
854
+ const session = await this.ensureDefaultSession();
855
+ return this.client.files.listFiles(path, session, options);
856
+ }
857
+
858
+ async exists(path: string, sessionId?: string) {
859
+ const session = sessionId ?? (await this.ensureDefaultSession());
860
+ return this.client.files.exists(path, session);
861
+ }
862
+
863
+ async exposePort(port: number, options: { name?: string; hostname: string }) {
864
+ // Check if hostname is workers.dev domain (doesn't support wildcard subdomains)
865
+ if (options.hostname.endsWith('.workers.dev')) {
866
+ const errorResponse: ErrorResponse = {
867
+ code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,
868
+ message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,
869
+ context: { originalError: options.hostname },
870
+ httpStatus: 400,
871
+ timestamp: new Date().toISOString()
872
+ };
873
+ throw new CustomDomainRequiredError(errorResponse);
874
+ }
875
+
876
+ const sessionId = await this.ensureDefaultSession();
877
+ await this.client.ports.exposePort(port, sessionId, options?.name);
878
+
879
+ // We need the sandbox name to construct preview URLs
880
+ if (!this.sandboxName) {
881
+ throw new Error(
882
+ 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
883
+ );
884
+ }
885
+
886
+ // Generate and store token for this port
887
+ const token = this.generatePortToken();
888
+ this.portTokens.set(port, token);
889
+ await this.persistPortTokens();
890
+
891
+ const url = this.constructPreviewUrl(
892
+ port,
893
+ this.sandboxName,
894
+ options.hostname,
895
+ token
896
+ );
897
+
898
+ return {
899
+ url,
900
+ port,
901
+ name: options?.name
902
+ };
903
+ }
904
+
905
+ async unexposePort(port: number) {
906
+ if (!validatePort(port)) {
907
+ throw new SecurityError(
908
+ `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
909
+ );
910
+ }
911
+
912
+ const sessionId = await this.ensureDefaultSession();
913
+ await this.client.ports.unexposePort(port, sessionId);
914
+
915
+ // Clean up token for this port
916
+ if (this.portTokens.has(port)) {
917
+ this.portTokens.delete(port);
918
+ await this.persistPortTokens();
919
+ }
920
+ }
921
+
922
+ async getExposedPorts(hostname: string) {
923
+ const sessionId = await this.ensureDefaultSession();
924
+ const response = await this.client.ports.getExposedPorts(sessionId);
925
+
926
+ // We need the sandbox name to construct preview URLs
927
+ if (!this.sandboxName) {
928
+ throw new Error(
929
+ 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
930
+ );
931
+ }
932
+
933
+ return response.ports.map((port) => {
934
+ // Get token for this port - must exist for all exposed ports
935
+ const token = this.portTokens.get(port.port);
936
+ if (!token) {
937
+ throw new Error(
938
+ `Port ${port.port} is exposed but has no token. This should not happen.`
939
+ );
940
+ }
941
+
942
+ return {
943
+ url: this.constructPreviewUrl(
944
+ port.port,
945
+ this.sandboxName!,
946
+ hostname,
947
+ token
948
+ ),
949
+ port: port.port,
950
+ status: port.status
951
+ };
952
+ });
953
+ }
954
+
955
+ async isPortExposed(port: number): Promise<boolean> {
956
+ try {
957
+ const sessionId = await this.ensureDefaultSession();
958
+ const response = await this.client.ports.getExposedPorts(sessionId);
959
+ return response.ports.some((exposedPort) => exposedPort.port === port);
960
+ } catch (error) {
961
+ this.logger.error(
962
+ 'Error checking if port is exposed',
963
+ error instanceof Error ? error : new Error(String(error)),
964
+ { port }
965
+ );
966
+ return false;
967
+ }
968
+ }
969
+
970
+ async validatePortToken(port: number, token: string): Promise<boolean> {
971
+ // First check if port is exposed
972
+ const isExposed = await this.isPortExposed(port);
973
+ if (!isExposed) {
974
+ return false;
975
+ }
976
+
977
+ // Get stored token for this port - must exist for all exposed ports
978
+ const storedToken = this.portTokens.get(port);
979
+ if (!storedToken) {
980
+ // This should not happen - all exposed ports must have tokens
981
+ this.logger.error(
982
+ 'Port is exposed but has no token - bug detected',
983
+ undefined,
984
+ { port }
985
+ );
986
+ return false;
987
+ }
988
+
989
+ // Constant-time comparison to prevent timing attacks
990
+ return storedToken === token;
991
+ }
992
+
993
+ private generatePortToken(): string {
994
+ // Generate cryptographically secure 16-character token using Web Crypto API
995
+ // Available in Cloudflare Workers runtime
996
+ const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)
997
+ crypto.getRandomValues(array);
998
+
999
+ // Convert to base64url format (URL-safe, no padding, lowercase)
1000
+ const base64 = btoa(String.fromCharCode(...array));
1001
+ return base64
1002
+ .replace(/\+/g, '-')
1003
+ .replace(/\//g, '_')
1004
+ .replace(/=/g, '')
1005
+ .toLowerCase();
1006
+ }
1007
+
1008
+ private async persistPortTokens(): Promise<void> {
1009
+ // Convert Map to plain object for storage
1010
+ const tokensObj: Record<string, string> = {};
1011
+ for (const [port, token] of this.portTokens.entries()) {
1012
+ tokensObj[port.toString()] = token;
1013
+ }
1014
+ await this.ctx.storage.put('portTokens', tokensObj);
1015
+ }
1016
+
1017
+ private constructPreviewUrl(
1018
+ port: number,
1019
+ sandboxId: string,
1020
+ hostname: string,
1021
+ token: string
1022
+ ): string {
1023
+ if (!validatePort(port)) {
1024
+ throw new SecurityError(
1025
+ `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
1026
+ );
1027
+ }
1028
+
1029
+ // Validate sandbox ID (will throw SecurityError if invalid)
1030
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
1031
+
1032
+ const isLocalhost = isLocalhostPattern(hostname);
1033
+
1034
+ if (isLocalhost) {
1035
+ // Unified subdomain approach for localhost (RFC 6761)
1036
+ const [host, portStr] = hostname.split(':');
1037
+ const mainPort = portStr || '80';
1038
+
1039
+ // Use URL constructor for safe URL building
1040
+ try {
1041
+ const baseUrl = new URL(`http://${host}:${mainPort}`);
1042
+ // Construct subdomain safely with mandatory token
1043
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
1044
+ baseUrl.hostname = subdomainHost;
1045
+
1046
+ return baseUrl.toString();
1047
+ } catch (error) {
1048
+ throw new SecurityError(
1049
+ `Failed to construct preview URL: ${
1050
+ error instanceof Error ? error.message : 'Unknown error'
1051
+ }`
1052
+ );
1053
+ }
1054
+ }
1055
+
1056
+ // Production subdomain logic - enforce HTTPS
1057
+ try {
1058
+ // Always use HTTPS for production (non-localhost)
1059
+ const protocol = 'https';
1060
+ const baseUrl = new URL(`${protocol}://${hostname}`);
1061
+
1062
+ // Construct subdomain safely with mandatory token
1063
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
1064
+ baseUrl.hostname = subdomainHost;
1065
+
1066
+ return baseUrl.toString();
1067
+ } catch (error) {
1068
+ throw new SecurityError(
1069
+ `Failed to construct preview URL: ${
1070
+ error instanceof Error ? error.message : 'Unknown error'
1071
+ }`
1072
+ );
1073
+ }
1074
+ }
1075
+
1076
+ // ============================================================================
1077
+ // Session Management - Advanced Use Cases
1078
+ // ============================================================================
1079
+
1080
+ /**
1081
+ * Create isolated execution session for advanced use cases
1082
+ * Returns ExecutionSession with full sandbox API bound to specific session
1083
+ */
1084
+ async createSession(options?: SessionOptions): Promise<ExecutionSession> {
1085
+ const sessionId = options?.id || `session-${Date.now()}`;
1086
+
1087
+ // Create session in container
1088
+ await this.client.utils.createSession({
1089
+ id: sessionId,
1090
+ env: options?.env,
1091
+ cwd: options?.cwd
1092
+ });
1093
+
1094
+ // Return wrapper that binds sessionId to all operations
1095
+ return this.getSessionWrapper(sessionId);
1096
+ }
1097
+
1098
+ /**
1099
+ * Get an existing session by ID
1100
+ * Returns ExecutionSession wrapper bound to the specified session
1101
+ *
1102
+ * This is useful for retrieving sessions across different requests/contexts
1103
+ * without storing the ExecutionSession object (which has RPC lifecycle limitations)
1104
+ *
1105
+ * @param sessionId - The ID of an existing session
1106
+ * @returns ExecutionSession wrapper bound to the session
1107
+ */
1108
+ async getSession(sessionId: string): Promise<ExecutionSession> {
1109
+ // No need to verify session exists in container - operations will fail naturally if it doesn't
1110
+ return this.getSessionWrapper(sessionId);
1111
+ }
1112
+
1113
+ /**
1114
+ * Internal helper to create ExecutionSession wrapper for a given sessionId
1115
+ * Used by both createSession and getSession
1116
+ */
1117
+ private getSessionWrapper(sessionId: string): ExecutionSession {
1118
+ return {
1119
+ id: sessionId,
1120
+
1121
+ // Command execution - delegate to internal session-aware methods
1122
+ exec: (command, options) =>
1123
+ this.execWithSession(command, sessionId, options),
1124
+ execStream: (command, options) =>
1125
+ this.execStreamWithSession(command, sessionId, options),
1126
+
1127
+ // Process management
1128
+ startProcess: (command, options) =>
1129
+ this.startProcess(command, options, sessionId),
1130
+ listProcesses: () => this.listProcesses(sessionId),
1131
+ getProcess: (id) => this.getProcess(id, sessionId),
1132
+ killProcess: (id, signal) => this.killProcess(id, signal),
1133
+ killAllProcesses: () => this.killAllProcesses(),
1134
+ cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),
1135
+ getProcessLogs: (id) => this.getProcessLogs(id),
1136
+ streamProcessLogs: (processId, options) =>
1137
+ this.streamProcessLogs(processId, options),
1138
+
1139
+ // File operations - pass sessionId via options or parameter
1140
+ writeFile: (path, content, options) =>
1141
+ this.writeFile(path, content, { ...options, sessionId }),
1142
+ readFile: (path, options) =>
1143
+ this.readFile(path, { ...options, sessionId }),
1144
+ readFileStream: (path) => this.readFileStream(path, { sessionId }),
1145
+ mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),
1146
+ deleteFile: (path) => this.deleteFile(path, sessionId),
1147
+ renameFile: (oldPath, newPath) =>
1148
+ this.renameFile(oldPath, newPath, sessionId),
1149
+ moveFile: (sourcePath, destPath) =>
1150
+ this.moveFile(sourcePath, destPath, sessionId),
1151
+ listFiles: (path, options) =>
1152
+ this.client.files.listFiles(path, sessionId, options),
1153
+ exists: (path) => this.exists(path, sessionId),
1154
+
1155
+ // Git operations
1156
+ gitCheckout: (repoUrl, options) =>
1157
+ this.gitCheckout(repoUrl, { ...options, sessionId }),
1158
+
1159
+ // Environment management - needs special handling
1160
+ setEnvVars: async (envVars: Record<string, string>) => {
1161
+ try {
1162
+ // Set environment variables by executing export commands
1163
+ for (const [key, value] of Object.entries(envVars)) {
1164
+ const escapedValue = value.replace(/'/g, "'\\''");
1165
+ const exportCommand = `export ${key}='${escapedValue}'`;
1166
+
1167
+ const result = await this.client.commands.execute(
1168
+ exportCommand,
1169
+ sessionId
1170
+ );
1171
+
1172
+ if (result.exitCode !== 0) {
1173
+ throw new Error(
1174
+ `Failed to set ${key}: ${result.stderr || 'Unknown error'}`
1175
+ );
1176
+ }
1177
+ }
1178
+ } catch (error) {
1179
+ this.logger.error(
1180
+ 'Failed to set environment variables',
1181
+ error instanceof Error ? error : new Error(String(error)),
1182
+ { sessionId }
1183
+ );
1184
+ throw error;
1185
+ }
1186
+ },
1187
+
1188
+ // Code interpreter methods - delegate to sandbox's code interpreter
1189
+ createCodeContext: (options) =>
1190
+ this.codeInterpreter.createCodeContext(options),
1191
+ runCode: async (code, options) => {
1192
+ const execution = await this.codeInterpreter.runCode(code, options);
1193
+ return execution.toJSON();
1194
+ },
1195
+ runCodeStream: (code, options) =>
1196
+ this.codeInterpreter.runCodeStream(code, options),
1197
+ listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
1198
+ deleteCodeContext: (contextId) =>
1199
+ this.codeInterpreter.deleteCodeContext(contextId)
1200
+ };
1201
+ }
1202
+
1203
+ // ============================================================================
1204
+ // Code interpreter methods - delegate to CodeInterpreter wrapper
1205
+ // ============================================================================
1206
+
1207
+ async createCodeContext(
1208
+ options?: CreateContextOptions
1209
+ ): Promise<CodeContext> {
1210
+ return this.codeInterpreter.createCodeContext(options);
1211
+ }
1212
+
1213
+ async runCode(
1214
+ code: string,
1215
+ options?: RunCodeOptions
1216
+ ): Promise<ExecutionResult> {
1217
+ const execution = await this.codeInterpreter.runCode(code, options);
1218
+ return execution.toJSON();
1219
+ }
1220
+
1221
+ async runCodeStream(
1222
+ code: string,
1223
+ options?: RunCodeOptions
1224
+ ): Promise<ReadableStream> {
1225
+ return this.codeInterpreter.runCodeStream(code, options);
1226
+ }
1227
+
1228
+ async listCodeContexts(): Promise<CodeContext[]> {
1229
+ return this.codeInterpreter.listCodeContexts();
1230
+ }
1231
+
1232
+ async deleteCodeContext(contextId: string): Promise<void> {
1233
+ return this.codeInterpreter.deleteCodeContext(contextId);
1234
+ }
1235
+ }