@cloudflare/sandbox 0.0.0-0ac3cfa → 0.0.0-0b4cc05

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