@cloudflare/sandbox 0.0.0-02ee8fe

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