@cloudflare/sandbox 0.0.0-af03394 → 0.0.0-b0c4c97

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