@cloudflare/sandbox 0.0.0-4bedc3a → 0.0.0-50bc24c

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