@cloudflare/sandbox 0.0.0-215ab49 → 0.0.0-228ef5b

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