@cloudflare/sandbox 0.0.0-444d2da → 0.0.0-4572082

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