@cloudflare/sandbox 0.0.0-0608f1e → 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 (81) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/Dockerfile +120 -27
  3. package/README.md +164 -0
  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 -4
  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 +85 -12
  53. package/src/interpreter.ts +159 -0
  54. package/src/request-handler.ts +69 -43
  55. package/src/sandbox.ts +539 -287
  56. package/src/security.ts +14 -23
  57. package/src/sse-parser.ts +4 -8
  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/handler/exec.ts +0 -337
  73. package/container_src/handler/file.ts +0 -844
  74. package/container_src/handler/git.ts +0 -182
  75. package/container_src/handler/ports.ts +0 -314
  76. package/container_src/handler/process.ts +0 -640
  77. package/container_src/index.ts +0 -361
  78. package/container_src/package.json +0 -9
  79. package/container_src/types.ts +0 -103
  80. package/src/client.ts +0 -1038
  81. package/src/types.ts +0 -386
package/src/sandbox.ts CHANGED
@@ -1,25 +1,33 @@
1
+ import type { DurableObject } from 'cloudflare:workers';
1
2
  import { Container, getContainer } from "@cloudflare/containers";
2
- import { HttpClient } from "./client";
3
- import { isLocalhostPattern } from "./request-handler";
4
- import {
5
- logSecurityEvent,
6
- SecurityError,
7
- sanitizeSandboxId,
8
- validatePort
9
- } from "./security";
10
3
  import type {
4
+ CodeContext,
5
+ CreateContextOptions,
6
+ ExecEvent,
11
7
  ExecOptions,
12
8
  ExecResult,
9
+ ExecutionResult,
10
+ ExecutionSession,
13
11
  ISandbox,
14
12
  Process,
15
13
  ProcessOptions,
16
14
  ProcessStatus,
15
+ RunCodeOptions,
16
+ SessionOptions,
17
17
  StreamOptions
18
- } from "./types";
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";
19
25
  import {
20
- ProcessNotFoundError,
21
- SandboxError
22
- } from "./types";
26
+ SecurityError,
27
+ sanitizeSandboxId,
28
+ validatePort
29
+ } from "./security";
30
+ import { parseSSEStream } from "./sse-parser";
23
31
 
24
32
  export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
25
33
  const stub = getContainer(ns, id);
@@ -31,36 +39,54 @@ export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
31
39
  }
32
40
 
33
41
  export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
42
+ defaultPort = 3000; // Default port for the container's Bun server
34
43
  sleepAfter = "3m"; // Sleep the sandbox if no requests are made in this timeframe
35
- client: HttpClient;
44
+
45
+ client: SandboxClient;
46
+ private codeInterpreter: CodeInterpreter;
36
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>;
37
52
 
38
- constructor(ctx: DurableObjectState, env: Env) {
53
+ constructor(ctx: DurableObject['ctx'], env: Env) {
39
54
  super(ctx, env);
40
- this.client = new HttpClient({
41
- onCommandComplete: (success, exitCode, _stdout, _stderr, command) => {
42
- console.log(
43
- `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
44
- );
45
- },
46
- onCommandStart: (command) => {
47
- console.log(
48
- `[Container] Command started: ${command}`
49
- );
50
- },
51
- onError: (error, _command) => {
52
- console.error(`[Container] Command error: ${error}`);
53
- },
54
- onOutput: (stream, data, _command) => {
55
- console.log(`[Container] [${stream}] ${data}`);
56
- },
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,
57
72
  port: 3000, // Control plane port
58
73
  stub: this,
59
74
  });
60
75
 
61
- // Load the sandbox name from storage on initialization
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
62
81
  this.ctx.blockConcurrencyWhile(async () => {
63
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
+ }
64
90
  });
65
91
  }
66
92
 
@@ -69,55 +95,81 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
69
95
  if (!this.sandboxName) {
70
96
  this.sandboxName = name;
71
97
  await this.ctx.storage.put('sandboxName', name);
72
- console.log(`[Sandbox] Stored sandbox name via RPC: ${name}`);
73
98
  }
74
99
  }
75
100
 
76
101
  // RPC method to set environment variables
77
102
  async setEnvVars(envVars: Record<string, string>): Promise<void> {
103
+ // Update local state for new sessions
78
104
  this.envVars = { ...this.envVars, ...envVars };
79
- console.log(`[Sandbox] Updated environment variables`);
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();
80
128
  }
81
129
 
82
130
  override onStart() {
83
- console.log("Sandbox successfully started");
131
+ this.logger.debug('Sandbox started');
84
132
  }
85
133
 
86
134
  override onStop() {
87
- console.log("Sandbox successfully shut down");
88
- if (this.client) {
89
- this.client.clearSession();
90
- }
135
+ this.logger.debug('Sandbox stopped');
91
136
  }
92
137
 
93
138
  override onError(error: unknown) {
94
- console.log("Sandbox error:", error);
139
+ this.logger.error('Sandbox error', error instanceof Error ? error : new Error(String(error)));
95
140
  }
96
141
 
97
142
  // Override fetch to route internal container requests to appropriate ports
98
143
  override async fetch(request: Request): Promise<Response> {
99
- const url = new URL(request.url);
144
+ // Extract or generate trace ID from request
145
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
100
146
 
101
- // Capture and store the sandbox name from the header if present
102
- if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
103
- const name = request.headers.get('X-Sandbox-Name')!;
104
- this.sandboxName = name;
105
- await this.ctx.storage.put('sandboxName', name);
106
- console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
107
- }
147
+ // Create request-specific logger with trace ID
148
+ const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
108
149
 
109
- // Determine which port to route to
110
- const port = this.determinePort(url);
150
+ return await runWithLogger(requestLogger, async () => {
151
+ const url = new URL(request.url);
111
152
 
112
- // Route to the appropriate port
113
- return await this.containerFetch(request, port);
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
+ });
114
166
  }
115
167
 
116
168
  private determinePort(url: URL): number {
117
169
  // Extract port from proxy requests (e.g., /proxy/8080/*)
118
170
  const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
119
171
  if (proxyMatch) {
120
- return parseInt(proxyMatch[1]);
172
+ return parseInt(proxyMatch[1], 10);
121
173
  }
122
174
 
123
175
  // All other requests go to control plane on port 3000
@@ -125,9 +177,43 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
125
177
  return 3000;
126
178
  }
127
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
+
128
201
  // Enhanced exec method - always returns ExecResult with optional streaming
129
202
  // This replaces the old exec method to match ISandbox interface
130
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> {
131
217
  const startTime = Date.now();
132
218
  const timestamp = new Date().toISOString();
133
219
 
@@ -144,16 +230,13 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
144
230
 
145
231
  if (options?.stream && options?.onOutput) {
146
232
  // Streaming with callbacks - we need to collect the final result
147
- result = await this.executeWithStreaming(command, options, startTime, timestamp);
233
+ result = await this.executeWithStreaming(command, sessionId, options, startTime, timestamp);
148
234
  } else {
149
- // Regular execution
150
- const response = await this.client.execute(
151
- command,
152
- options?.sessionId
153
- );
235
+ // Regular execution with session
236
+ const response = await this.client.commands.execute(command, sessionId);
154
237
 
155
238
  const duration = Date.now() - startTime;
156
- result = this.mapExecuteResponseToExecResult(response, duration, options?.sessionId);
239
+ result = this.mapExecuteResponseToExecResult(response, duration, sessionId);
157
240
  }
158
241
 
159
242
  // Call completion callback if provided
@@ -176,6 +259,7 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
176
259
 
177
260
  private async executeWithStreaming(
178
261
  command: string,
262
+ sessionId: string,
179
263
  options: ExecOptions,
180
264
  startTime: number,
181
265
  timestamp: string
@@ -184,10 +268,9 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
184
268
  let stderr = '';
185
269
 
186
270
  try {
187
- const stream = await this.client.executeCommandStream(command, options.sessionId);
188
- const { parseSSEStream } = await import('./sse-parser');
271
+ const stream = await this.client.commands.executeStream(command, sessionId);
189
272
 
190
- for await (const event of parseSSEStream<import('./types').ExecEvent>(stream)) {
273
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
191
274
  // Check for cancellation
192
275
  if (options.signal?.aborted) {
193
276
  throw new Error('Operation was aborted');
@@ -211,20 +294,20 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
211
294
  case 'complete': {
212
295
  // Use result from complete event if available
213
296
  const duration = Date.now() - startTime;
214
- return event.result || {
215
- success: event.exitCode === 0,
216
- exitCode: event.exitCode || 0,
297
+ return {
298
+ success: (event.exitCode ?? 0) === 0,
299
+ exitCode: event.exitCode ?? 0,
217
300
  stdout,
218
301
  stderr,
219
302
  command,
220
303
  duration,
221
304
  timestamp,
222
- sessionId: options.sessionId
305
+ sessionId
223
306
  };
224
307
  }
225
308
 
226
309
  case 'error':
227
- throw new Error(event.error || 'Command execution failed');
310
+ throw new Error(event.data || 'Command execution failed');
228
311
  }
229
312
  }
230
313
 
@@ -240,7 +323,7 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
240
323
  }
241
324
 
242
325
  private mapExecuteResponseToExecResult(
243
- response: import('./client').ExecuteResponse,
326
+ response: ExecuteResponse,
244
327
  duration: number,
245
328
  sessionId?: string
246
329
  ): ExecResult {
@@ -256,57 +339,68 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
256
339
  };
257
340
  }
258
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
+
259
385
 
260
386
  // Background process management
261
- async startProcess(command: string, options?: ProcessOptions): Promise<Process> {
387
+ async startProcess(command: string, options?: ProcessOptions, sessionId?: string): Promise<Process> {
262
388
  // Use the new HttpClient method to start the process
263
389
  try {
264
- const response = await this.client.startProcess(command, {
265
- processId: options?.processId,
266
- sessionId: options?.sessionId,
267
- timeout: options?.timeout,
268
- env: options?.env,
269
- cwd: options?.cwd,
270
- encoding: options?.encoding,
271
- autoCleanup: options?.autoCleanup
390
+ const session = sessionId ?? await this.ensureDefaultSession();
391
+ const response = await this.client.processes.startProcess(command, session, {
392
+ processId: options?.processId
272
393
  });
273
394
 
274
- const process = response.process;
275
- const processObj: Process = {
276
- id: process.id,
277
- pid: process.pid,
278
- command: process.command,
279
- status: process.status as ProcessStatus,
280
- startTime: new Date(process.startTime),
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(),
281
401
  endTime: undefined,
282
- exitCode: undefined,
283
- sessionId: process.sessionId,
284
-
285
- async kill(): Promise<void> {
286
- throw new Error('Method will be replaced');
287
- },
288
- async getStatus(): Promise<ProcessStatus> {
289
- throw new Error('Method will be replaced');
290
- },
291
- async getLogs(): Promise<{ stdout: string; stderr: string }> {
292
- throw new Error('Method will be replaced');
293
- }
294
- };
295
-
296
- // Bind context properly
297
- processObj.kill = async (signal?: string) => {
298
- await this.killProcess(process.id, signal);
299
- };
300
-
301
- processObj.getStatus = async () => {
302
- const current = await this.getProcess(process.id);
303
- return current?.status || 'error';
304
- };
305
-
306
- processObj.getLogs = async () => {
307
- const logs = await this.getProcessLogs(process.id);
308
- return { stdout: logs.stdout, stderr: logs.stderr };
309
- };
402
+ exitCode: undefined
403
+ }, session);
310
404
 
311
405
  // Call onStart callback if provided
312
406
  if (options?.onStart) {
@@ -324,108 +418,68 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
324
418
  }
325
419
  }
326
420
 
327
- async listProcesses(): Promise<Process[]> {
328
- const response = await this.client.listProcesses();
329
-
330
- return response.processes.map(processData => ({
331
- id: processData.id,
332
- pid: processData.pid,
333
- command: processData.command,
334
- status: processData.status,
335
- startTime: new Date(processData.startTime),
336
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
337
- exitCode: processData.exitCode,
338
- sessionId: processData.sessionId,
339
-
340
- kill: async (signal?: string) => {
341
- await this.killProcess(processData.id, signal);
342
- },
343
-
344
- getStatus: async () => {
345
- const current = await this.getProcess(processData.id);
346
- return current?.status || 'error';
347
- },
348
-
349
- getLogs: async () => {
350
- const logs = await this.getProcessLogs(processData.id);
351
- return { stdout: logs.stdout, stderr: logs.stderr };
352
- }
353
- }));
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
+ );
354
436
  }
355
437
 
356
- async getProcess(id: string): Promise<Process | null> {
357
- const response = await this.client.getProcess(id);
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);
358
441
  if (!response.process) {
359
442
  return null;
360
443
  }
361
444
 
362
445
  const processData = response.process;
363
- return {
446
+ return this.createProcessFromDTO({
364
447
  id: processData.id,
365
448
  pid: processData.pid,
366
449
  command: processData.command,
367
450
  status: processData.status,
368
- startTime: new Date(processData.startTime),
369
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
370
- exitCode: processData.exitCode,
371
- sessionId: processData.sessionId,
372
-
373
- kill: async (signal?: string) => {
374
- await this.killProcess(processData.id, signal);
375
- },
376
-
377
- getStatus: async () => {
378
- const current = await this.getProcess(processData.id);
379
- return current?.status || 'error';
380
- },
381
-
382
- getLogs: async () => {
383
- const logs = await this.getProcessLogs(processData.id);
384
- return { stdout: logs.stdout, stderr: logs.stderr };
385
- }
386
- };
451
+ startTime: processData.startTime,
452
+ endTime: processData.endTime,
453
+ exitCode: processData.exitCode
454
+ }, session);
387
455
  }
388
456
 
389
- async killProcess(id: string, _signal?: string): Promise<void> {
390
- try {
391
- // Note: signal parameter is not currently supported by the HttpClient implementation
392
- await this.client.killProcess(id);
393
- } catch (error) {
394
- if (error instanceof Error && error.message.includes('Process not found')) {
395
- throw new ProcessNotFoundError(id);
396
- }
397
- throw new SandboxError(
398
- `Failed to kill process ${id}: ${error instanceof Error ? error.message : 'Unknown error'}`,
399
- 'KILL_PROCESS_FAILED'
400
- );
401
- }
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);
402
461
  }
403
462
 
404
- async killAllProcesses(): Promise<number> {
405
- const response = await this.client.killAllProcesses();
406
- return response.killedCount;
463
+ async killAllProcesses(sessionId?: string): Promise<number> {
464
+ const response = await this.client.processes.killAllProcesses();
465
+ return response.cleanedCount;
407
466
  }
408
467
 
409
- async cleanupCompletedProcesses(): Promise<number> {
468
+ async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
410
469
  // For now, this would need to be implemented as a container endpoint
411
470
  // as we no longer maintain local process storage
412
471
  // We'll return 0 as a placeholder until the container endpoint is added
413
472
  return 0;
414
473
  }
415
474
 
416
- async getProcessLogs(id: string): Promise<{ stdout: string; stderr: string }> {
417
- try {
418
- const response = await this.client.getProcessLogs(id);
419
- return {
420
- stdout: response.stdout,
421
- stderr: response.stderr
422
- };
423
- } catch (error) {
424
- if (error instanceof Error && error.message.includes('Process not found')) {
425
- throw new ProcessNotFoundError(id);
426
- }
427
- throw error;
428
- }
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
+ };
429
483
  }
430
484
 
431
485
 
@@ -436,11 +490,21 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
436
490
  throw new Error('Operation was aborted');
437
491
  }
438
492
 
439
- // Get the stream from HttpClient (need to add this method)
440
- const stream = await this.client.executeCommandStream(command, options?.sessionId);
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
+ }
441
506
 
442
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
443
- return stream;
507
+ return this.client.commands.executeStream(command, sessionId);
444
508
  }
445
509
 
446
510
  async streamProcessLogs(processId: string, options?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>> {
@@ -449,69 +513,117 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
449
513
  throw new Error('Operation was aborted');
450
514
  }
451
515
 
452
- // Get the stream from HttpClient
453
- const stream = await this.client.streamProcessLogs(processId);
454
-
455
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
456
- return stream;
516
+ return this.client.processes.streamProcessLogs(processId);
457
517
  }
458
518
 
459
519
  async gitCheckout(
460
520
  repoUrl: string,
461
- options: { branch?: string; targetDir?: string }
521
+ options: { branch?: string; targetDir?: string; sessionId?: string }
462
522
  ) {
463
- return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
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
+ });
464
528
  }
465
529
 
466
530
  async mkdir(
467
531
  path: string,
468
- options: { recursive?: boolean } = {}
532
+ options: { recursive?: boolean; sessionId?: string } = {}
469
533
  ) {
470
- return this.client.mkdir(path, options.recursive);
534
+ const session = options.sessionId ?? await this.ensureDefaultSession();
535
+ return this.client.files.mkdir(path, session, { recursive: options.recursive });
471
536
  }
472
537
 
473
538
  async writeFile(
474
539
  path: string,
475
540
  content: string,
476
- options: { encoding?: string } = {}
541
+ options: { encoding?: string; sessionId?: string } = {}
477
542
  ) {
478
- return this.client.writeFile(path, content, options.encoding);
543
+ const session = options.sessionId ?? await this.ensureDefaultSession();
544
+ return this.client.files.writeFile(path, content, session, { encoding: options.encoding });
479
545
  }
480
546
 
481
- async deleteFile(path: string) {
482
- return this.client.deleteFile(path);
547
+ async deleteFile(path: string, sessionId?: string) {
548
+ const session = sessionId ?? await this.ensureDefaultSession();
549
+ return this.client.files.deleteFile(path, session);
483
550
  }
484
551
 
485
552
  async renameFile(
486
553
  oldPath: string,
487
- newPath: string
554
+ newPath: string,
555
+ sessionId?: string
488
556
  ) {
489
- return this.client.renameFile(oldPath, newPath);
557
+ const session = sessionId ?? await this.ensureDefaultSession();
558
+ return this.client.files.renameFile(oldPath, newPath, session);
490
559
  }
491
560
 
492
561
  async moveFile(
493
562
  sourcePath: string,
494
- destinationPath: string
563
+ destinationPath: string,
564
+ sessionId?: string
495
565
  ) {
496
- return this.client.moveFile(sourcePath, destinationPath);
566
+ const session = sessionId ?? await this.ensureDefaultSession();
567
+ return this.client.files.moveFile(sourcePath, destinationPath, session);
497
568
  }
498
569
 
499
570
  async readFile(
500
571
  path: string,
501
- options: { encoding?: string } = {}
572
+ options: { encoding?: string; sessionId?: string } = {}
502
573
  ) {
503
- return this.client.readFile(path, options.encoding);
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);
504
598
  }
505
599
 
506
600
  async exposePort(port: number, options: { name?: string; hostname: string }) {
507
- await this.client.exposePort(port, options?.name);
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);
508
615
 
509
616
  // We need the sandbox name to construct preview URLs
510
617
  if (!this.sandboxName) {
511
618
  throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
512
619
  }
513
620
 
514
- const url = this.constructPreviewUrl(port, this.sandboxName, options.hostname);
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);
515
627
 
516
628
  return {
517
629
  url,
@@ -522,58 +634,101 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
522
634
 
523
635
  async unexposePort(port: number) {
524
636
  if (!validatePort(port)) {
525
- logSecurityEvent('INVALID_PORT_UNEXPOSE', {
526
- port
527
- }, 'high');
528
637
  throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
529
638
  }
530
639
 
531
- await this.client.unexposePort(port);
640
+ const sessionId = await this.ensureDefaultSession();
641
+ await this.client.ports.unexposePort(port, sessionId);
532
642
 
533
- logSecurityEvent('PORT_UNEXPOSED', {
534
- port
535
- }, 'low');
643
+ // Clean up token for this port
644
+ if (this.portTokens.has(port)) {
645
+ this.portTokens.delete(port);
646
+ await this.persistPortTokens();
647
+ }
536
648
  }
537
649
 
538
650
  async getExposedPorts(hostname: string) {
539
- const response = await this.client.getExposedPorts();
651
+ const sessionId = await this.ensureDefaultSession();
652
+ const response = await this.client.ports.getExposedPorts(sessionId);
540
653
 
541
654
  // We need the sandbox name to construct preview URLs
542
655
  if (!this.sandboxName) {
543
656
  throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
544
657
  }
545
658
 
546
- return response.ports.map(port => ({
547
- url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
548
- port: port.port,
549
- name: port.name,
550
- exposedAt: port.exposedAt,
551
- }));
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
+ });
552
672
  }
553
673
 
554
674
 
555
- private constructPreviewUrl(port: number, sandboxId: string, hostname: string): string {
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 {
556
726
  if (!validatePort(port)) {
557
- logSecurityEvent('INVALID_PORT_REJECTED', {
558
- port,
559
- sandboxId,
560
- hostname
561
- }, 'high');
562
727
  throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
563
728
  }
564
729
 
565
- let sanitizedSandboxId: string;
566
- try {
567
- sanitizedSandboxId = sanitizeSandboxId(sandboxId);
568
- } catch (error) {
569
- logSecurityEvent('INVALID_SANDBOX_ID_REJECTED', {
570
- sandboxId,
571
- port,
572
- hostname,
573
- error: error instanceof Error ? error.message : 'Unknown error'
574
- }, 'high');
575
- throw error;
576
- }
730
+ // Validate sandbox ID (will throw SecurityError if invalid)
731
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
577
732
 
578
733
  const isLocalhost = isLocalhostPattern(hostname);
579
734
 
@@ -585,28 +740,12 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
585
740
  // Use URL constructor for safe URL building
586
741
  try {
587
742
  const baseUrl = new URL(`http://${host}:${mainPort}`);
588
- // Construct subdomain safely
589
- const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
743
+ // Construct subdomain safely with mandatory token
744
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
590
745
  baseUrl.hostname = subdomainHost;
591
746
 
592
- const finalUrl = baseUrl.toString();
593
-
594
- logSecurityEvent('PREVIEW_URL_CONSTRUCTED', {
595
- port,
596
- sandboxId: sanitizedSandboxId,
597
- hostname,
598
- resultUrl: finalUrl,
599
- environment: 'localhost'
600
- }, 'low');
601
-
602
- return finalUrl;
747
+ return baseUrl.toString();
603
748
  } catch (error) {
604
- logSecurityEvent('URL_CONSTRUCTION_FAILED', {
605
- port,
606
- sandboxId: sanitizedSandboxId,
607
- hostname,
608
- error: error instanceof Error ? error.message : 'Unknown error'
609
- }, 'high');
610
749
  throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
611
750
  }
612
751
  }
@@ -617,29 +756,142 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
617
756
  const protocol = "https";
618
757
  const baseUrl = new URL(`${protocol}://${hostname}`);
619
758
 
620
- // Construct subdomain safely
621
- const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
759
+ // Construct subdomain safely with mandatory token
760
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
622
761
  baseUrl.hostname = subdomainHost;
623
762
 
624
- const finalUrl = baseUrl.toString();
625
-
626
- logSecurityEvent('PREVIEW_URL_CONSTRUCTED', {
627
- port,
628
- sandboxId: sanitizedSandboxId,
629
- hostname,
630
- resultUrl: finalUrl,
631
- environment: 'production'
632
- }, 'low');
633
-
634
- return finalUrl;
763
+ return baseUrl.toString();
635
764
  } catch (error) {
636
- logSecurityEvent('URL_CONSTRUCTION_FAILED', {
637
- port,
638
- sandboxId: sanitizedSandboxId,
639
- hostname,
640
- error: error instanceof Error ? error.message : 'Unknown error'
641
- }, 'high');
642
765
  throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
643
766
  }
644
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
+ }
645
897
  }