@cloudflare/sandbox 0.0.0-7de28be → 0.0.0-7edbfa9

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