@cloudflare/sandbox 0.0.0-7bccc85 → 0.0.0-7edbfa9

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