@cloudflare/sandbox 0.0.0-1be7d53 → 0.0.0-1bf3576

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 (74) hide show
  1. package/CHANGELOG.md +91 -6
  2. package/Dockerfile +91 -51
  3. package/README.md +87 -825
  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 +123 -116
  24. package/src/index.ts +85 -66
  25. package/src/interpreter.ts +58 -40
  26. package/src/request-handler.ts +94 -55
  27. package/src/sandbox.ts +989 -498
  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/bun.lock +0 -76
  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 -457
  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/interpreter-service.ts +0 -276
  60. package/container_src/isolation.ts +0 -1213
  61. package/container_src/mime-processor.ts +0 -255
  62. package/container_src/package.json +0 -18
  63. package/container_src/runtime/executors/javascript/node_executor.ts +0 -123
  64. package/container_src/runtime/executors/python/ipython_executor.py +0 -338
  65. package/container_src/runtime/executors/typescript/ts_executor.ts +0 -138
  66. package/container_src/runtime/process-pool.ts +0 -464
  67. package/container_src/shell-escape.ts +0 -42
  68. package/container_src/startup.sh +0 -11
  69. package/container_src/types.ts +0 -131
  70. package/src/client.ts +0 -1048
  71. package/src/errors.ts +0 -219
  72. package/src/interpreter-client.ts +0 -352
  73. package/src/interpreter-types.ts +0 -390
  74. package/src/types.ts +0 -571
package/src/sandbox.ts CHANGED
@@ -1,79 +1,147 @@
1
- import { Container, getContainer } from "@cloudflare/containers";
2
- import { CodeInterpreter } from "./interpreter";
3
- import { InterpreterClient } from "./interpreter-client";
1
+ import type { DurableObject } from 'cloudflare:workers';
2
+ import { Container, getContainer, switchPort } from '@cloudflare/containers';
4
3
  import type {
5
4
  CodeContext,
6
5
  CreateContextOptions,
7
- ExecutionResult,
8
- RunCodeOptions,
9
- } from "./interpreter-types";
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";
31
-
32
- export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
33
- const stub = getContainer(ns, id);
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 { 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;
34
36
 
35
37
  // Store the name on first access
36
38
  stub.setSandboxName?.(id);
37
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
+
38
52
  return stub;
39
53
  }
40
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
+
41
89
  export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
42
90
  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: InterpreterClient;
45
- private sandboxName: string | null = null;
46
- private codeInterpreter: CodeInterpreter;
47
- private defaultSession: ExecutionSession | null = null;
91
+ sleepAfter: string | number = '10m'; // Sleep the sandbox if no requests are made in this timeframe
48
92
 
49
- 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) {
50
104
  super(ctx, env);
51
- this.client = new InterpreterClient({
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
- },
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,
66
122
  port: 3000, // Control plane port
67
- stub: this,
123
+ stub: this
68
124
  });
69
125
 
70
- // Initialize code interpreter
126
+ // Initialize code interpreter - pass 'this' after client is ready
127
+ // The CodeInterpreter extracts client.interpreter from the sandbox
71
128
  this.codeInterpreter = new CodeInterpreter(this);
72
129
 
73
- // Load the sandbox name from storage on initialization
130
+ // Load the sandbox name, port tokens, and default session from storage on initialization
74
131
  this.ctx.blockConcurrencyWhile(async () => {
75
132
  this.sandboxName =
76
- (await this.ctx.storage.get<string>("sandboxName")) || null;
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
+ }
77
145
  });
78
146
  }
79
147
 
@@ -81,62 +149,222 @@ 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(
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
+ );
86
186
  }
87
187
  }
88
188
 
89
189
  // RPC method to set environment variables
90
190
  async setEnvVars(envVars: Record<string, string>): Promise<void> {
191
+ // Update local state for new sessions
91
192
  this.envVars = { ...this.envVars, ...envVars };
92
- console.log(`[Sandbox] Updated environment variables`);
93
-
94
- // If we have a default session, update its environment too
193
+
194
+ // If default session already exists, update it directly
95
195
  if (this.defaultSession) {
96
- await this.defaultSession.setEnvVars(envVars);
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
+ }
97
212
  }
98
213
  }
99
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();
221
+ }
222
+
100
223
  override onStart() {
101
- 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
+ });
233
+ }
234
+
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
+ });
279
+ }
102
280
  }
103
281
 
104
282
  override onStop() {
105
- console.log("Sandbox successfully shut down");
283
+ this.logger.debug('Sandbox stopped');
106
284
  }
107
285
 
108
286
  override onError(error: unknown) {
109
- 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
+ }
110
308
  }
111
309
 
112
310
  // Override fetch to route internal container requests to appropriate ports
113
311
  override async fetch(request: Request): Promise<Response> {
114
- const url = new URL(request.url);
312
+ // Extract or generate trace ID from request
313
+ const traceId =
314
+ TraceContext.fromHeaders(request.headers) || TraceContext.generate();
115
315
 
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
- }
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);
123
321
 
124
- // Determine which port to route to
125
- 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
+ }
126
354
 
127
- // Route to the appropriate port
128
- 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
+ });
129
361
  }
130
362
 
131
363
  private determinePort(url: URL): number {
132
364
  // Extract port from proxy requests (e.g., /proxy/8080/*)
133
365
  const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
134
366
  if (proxyMatch) {
135
- return parseInt(proxyMatch[1]);
136
- }
137
-
138
- if (url.port) {
139
- return parseInt(url.port);
367
+ return parseInt(proxyMatch[1], 10);
140
368
  }
141
369
 
142
370
  // All other requests go to control plane on port 3000
@@ -144,288 +372,694 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
144
372
  return 3000;
145
373
  }
146
374
 
147
- // Helper to ensure default session is initialized
148
- private async ensureDefaultSession(): Promise<ExecutionSession> {
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> {
149
384
  if (!this.defaultSession) {
150
385
  const sessionId = `sandbox-${this.sandboxName || 'default'}`;
151
- this.defaultSession = await this.createSession({
152
- id: sessionId,
153
- env: this.envVars || {},
154
- cwd: '/workspace',
155
- isolation: true
156
- });
157
- console.log(`[Sandbox] Default session initialized: ${sessionId}`);
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
+ }
158
413
  }
159
414
  return this.defaultSession;
160
415
  }
161
416
 
162
-
417
+ // Enhanced exec method - always returns ExecResult with optional streaming
418
+ // This replaces the old exec method to match ISandbox interface
163
419
  async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
164
420
  const session = await this.ensureDefaultSession();
165
- return session.exec(command, options);
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> {
433
+ const startTime = Date.now();
434
+ const timestamp = new Date().toISOString();
435
+
436
+ let timeoutId: NodeJS.Timeout | undefined;
437
+
438
+ try {
439
+ // Handle cancellation
440
+ if (options?.signal?.aborted) {
441
+ throw new Error('Operation was aborted');
442
+ }
443
+
444
+ let result: ExecResult;
445
+
446
+ if (options?.stream && options?.onOutput) {
447
+ // Streaming with callbacks - we need to collect the final result
448
+ result = await this.executeWithStreaming(
449
+ command,
450
+ sessionId,
451
+ options,
452
+ startTime,
453
+ timestamp
454
+ );
455
+ } else {
456
+ // Regular execution with session
457
+ const response = await this.client.commands.execute(command, sessionId);
458
+
459
+ const duration = Date.now() - startTime;
460
+ result = this.mapExecuteResponseToExecResult(
461
+ response,
462
+ duration,
463
+ sessionId
464
+ );
465
+ }
466
+
467
+ // Call completion callback if provided
468
+ if (options?.onComplete) {
469
+ options.onComplete(result);
470
+ }
471
+
472
+ return result;
473
+ } catch (error) {
474
+ if (options?.onError && error instanceof Error) {
475
+ options.onError(error);
476
+ }
477
+ throw error;
478
+ } finally {
479
+ if (timeoutId) {
480
+ clearTimeout(timeoutId);
481
+ }
482
+ }
483
+ }
484
+
485
+ private async executeWithStreaming(
486
+ command: string,
487
+ sessionId: string,
488
+ options: ExecOptions,
489
+ startTime: number,
490
+ timestamp: string
491
+ ): Promise<ExecResult> {
492
+ let stdout = '';
493
+ let stderr = '';
494
+
495
+ try {
496
+ const stream = await this.client.commands.executeStream(
497
+ command,
498
+ sessionId
499
+ );
500
+
501
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
502
+ // Check for cancellation
503
+ if (options.signal?.aborted) {
504
+ throw new Error('Operation was aborted');
505
+ }
506
+
507
+ switch (event.type) {
508
+ case 'stdout':
509
+ case 'stderr':
510
+ if (event.data) {
511
+ // Update accumulated output
512
+ if (event.type === 'stdout') stdout += event.data;
513
+ if (event.type === 'stderr') stderr += event.data;
514
+
515
+ // Call user's callback
516
+ if (options.onOutput) {
517
+ options.onOutput(event.type, event.data);
518
+ }
519
+ }
520
+ break;
521
+
522
+ case 'complete': {
523
+ // Use result from complete event if available
524
+ const duration = Date.now() - startTime;
525
+ return {
526
+ success: (event.exitCode ?? 0) === 0,
527
+ exitCode: event.exitCode ?? 0,
528
+ stdout,
529
+ stderr,
530
+ command,
531
+ duration,
532
+ timestamp,
533
+ sessionId
534
+ };
535
+ }
536
+
537
+ case 'error':
538
+ throw new Error(event.data || 'Command execution failed');
539
+ }
540
+ }
541
+
542
+ // If we get here without a complete event, something went wrong
543
+ throw new Error('Stream ended without completion event');
544
+ } catch (error) {
545
+ if (options.signal?.aborted) {
546
+ throw new Error('Operation was aborted');
547
+ }
548
+ throw error;
549
+ }
550
+ }
551
+
552
+ private mapExecuteResponseToExecResult(
553
+ response: ExecuteResponse,
554
+ duration: number,
555
+ sessionId?: string
556
+ ): ExecResult {
557
+ return {
558
+ success: response.success,
559
+ exitCode: response.exitCode,
560
+ stdout: response.stdout,
561
+ stderr: response.stderr,
562
+ command: response.command,
563
+ duration,
564
+ timestamp: response.timestamp,
565
+ sessionId
566
+ };
166
567
  }
167
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
+ }
618
+
619
+ // Background process management
168
620
  async startProcess(
169
621
  command: string,
170
- options?: ProcessOptions
622
+ options?: ProcessOptions,
623
+ sessionId?: string
171
624
  ): Promise<Process> {
172
- const session = await this.ensureDefaultSession();
173
- return session.startProcess(command, options);
625
+ // Use the new HttpClient method to start the process
626
+ try {
627
+ const session = sessionId ?? (await this.ensureDefaultSession());
628
+ const response = await this.client.processes.startProcess(
629
+ command,
630
+ session,
631
+ {
632
+ processId: options?.processId
633
+ }
634
+ );
635
+
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
+ );
648
+
649
+ // Call onStart callback if provided
650
+ if (options?.onStart) {
651
+ options.onStart(processObj);
652
+ }
653
+
654
+ return processObj;
655
+ } catch (error) {
656
+ if (options?.onError && error instanceof Error) {
657
+ options.onError(error);
658
+ }
659
+
660
+ throw error;
661
+ }
174
662
  }
175
663
 
176
- async listProcesses(): Promise<Process[]> {
177
- const session = await this.ensureDefaultSession();
178
- return session.listProcesses();
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
+ );
179
682
  }
180
683
 
181
- async getProcess(id: string): Promise<Process | null> {
182
- const session = await this.ensureDefaultSession();
183
- return session.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);
687
+ if (!response.process) {
688
+ return null;
689
+ }
690
+
691
+ const processData = response.process;
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
701
+ },
702
+ session
703
+ );
184
704
  }
185
705
 
186
- async killProcess(id: string, signal?: string): Promise<void> {
187
- const session = await this.ensureDefaultSession();
188
- return session.killProcess(id, signal);
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);
189
714
  }
190
715
 
191
- async killAllProcesses(): Promise<number> {
192
- const session = await this.ensureDefaultSession();
193
- return session.killAllProcesses();
716
+ async killAllProcesses(sessionId?: string): Promise<number> {
717
+ const response = await this.client.processes.killAllProcesses();
718
+ return response.cleanedCount;
194
719
  }
195
720
 
196
- async cleanupCompletedProcesses(): Promise<number> {
197
- const session = await this.ensureDefaultSession();
198
- return session.cleanupCompletedProcesses();
721
+ async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
722
+ // For now, this would need to be implemented as a container endpoint
723
+ // as we no longer maintain local process storage
724
+ // We'll return 0 as a placeholder until the container endpoint is added
725
+ return 0;
199
726
  }
200
727
 
201
728
  async getProcessLogs(
202
- id: string
203
- ): Promise<{ stdout: string; stderr: string }> {
204
- const session = await this.ensureDefaultSession();
205
- return session.getProcessLogs(id);
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
+ };
206
739
  }
207
740
 
208
- // Streaming methods - delegates to default session
741
+ // Streaming methods - return ReadableStream for RPC compatibility
209
742
  async execStream(
210
743
  command: string,
211
744
  options?: StreamOptions
212
745
  ): Promise<ReadableStream<Uint8Array>> {
746
+ // Check for cancellation
747
+ if (options?.signal?.aborted) {
748
+ throw new Error('Operation was aborted');
749
+ }
750
+
213
751
  const session = await this.ensureDefaultSession();
214
- return session.execStream(command, options);
752
+ // Get the stream from CommandClient
753
+ return this.client.commands.executeStream(command, session);
754
+ }
755
+
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>> {
764
+ // Check for cancellation
765
+ if (options?.signal?.aborted) {
766
+ throw new Error('Operation was aborted');
767
+ }
768
+
769
+ return this.client.commands.executeStream(command, sessionId);
215
770
  }
216
771
 
772
+ /**
773
+ * Stream logs from a background process as a ReadableStream.
774
+ */
217
775
  async streamProcessLogs(
218
776
  processId: string,
219
777
  options?: { signal?: AbortSignal }
220
778
  ): Promise<ReadableStream<Uint8Array>> {
221
- const session = await this.ensureDefaultSession();
222
- return session.streamProcessLogs(processId, options);
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);
223
785
  }
224
786
 
225
787
  async gitCheckout(
226
788
  repoUrl: string,
227
- options: { branch?: string; targetDir?: string }
789
+ options: { branch?: string; targetDir?: string; sessionId?: string }
228
790
  ) {
229
- const session = await this.ensureDefaultSession();
230
- return session.gitCheckout(repoUrl, options);
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
+ });
231
796
  }
232
797
 
233
- async mkdir(path: string, options: { recursive?: boolean } = {}) {
234
- const session = await this.ensureDefaultSession();
235
- return session.mkdir(path, options);
798
+ async mkdir(
799
+ path: string,
800
+ options: { recursive?: boolean; sessionId?: string } = {}
801
+ ) {
802
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
803
+ return this.client.files.mkdir(path, session, {
804
+ recursive: options.recursive
805
+ });
236
806
  }
237
807
 
238
808
  async writeFile(
239
809
  path: string,
240
810
  content: string,
241
- options: { encoding?: string } = {}
811
+ options: { encoding?: string; sessionId?: string } = {}
242
812
  ) {
243
- const session = await this.ensureDefaultSession();
244
- return session.writeFile(path, content, options);
813
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
814
+ return this.client.files.writeFile(path, content, session, {
815
+ encoding: options.encoding
816
+ });
245
817
  }
246
818
 
247
- async deleteFile(path: string) {
248
- const session = await this.ensureDefaultSession();
249
- return session.deleteFile(path);
819
+ async deleteFile(path: string, sessionId?: string) {
820
+ const session = sessionId ?? (await this.ensureDefaultSession());
821
+ return this.client.files.deleteFile(path, session);
250
822
  }
251
823
 
252
- async renameFile(oldPath: string, newPath: string) {
253
- const session = await this.ensureDefaultSession();
254
- return session.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);
255
827
  }
256
828
 
257
- async moveFile(sourcePath: string, destinationPath: string) {
258
- const session = await this.ensureDefaultSession();
259
- return session.moveFile(sourcePath, destinationPath);
829
+ async moveFile(
830
+ sourcePath: string,
831
+ destinationPath: string,
832
+ sessionId?: string
833
+ ) {
834
+ const session = sessionId ?? (await this.ensureDefaultSession());
835
+ return this.client.files.moveFile(sourcePath, destinationPath, session);
260
836
  }
261
837
 
262
- async readFile(path: string, options: { encoding?: string } = {}) {
263
- const session = await this.ensureDefaultSession();
264
- return session.readFile(path, options);
838
+ async readFile(
839
+ path: string,
840
+ options: { encoding?: string; sessionId?: string } = {}
841
+ ) {
842
+ const session = options.sessionId ?? (await this.ensureDefaultSession());
843
+ return this.client.files.readFile(path, session, {
844
+ encoding: options.encoding
845
+ });
265
846
  }
266
847
 
267
- async readFileStream(path: string): Promise<ReadableStream<Uint8Array>> {
268
- const session = await this.ensureDefaultSession();
269
- return session.readFileStream(path);
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);
270
860
  }
271
861
 
272
862
  async listFiles(
273
863
  path: string,
274
- options: {
275
- recursive?: boolean;
276
- includeHidden?: boolean;
277
- } = {}
864
+ options?: { recursive?: boolean; includeHidden?: boolean }
278
865
  ) {
279
866
  const session = await this.ensureDefaultSession();
280
- return session.listFiles(path, options);
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);
281
873
  }
282
874
 
283
875
  async exposePort(port: number, options: { name?: string; hostname: string }) {
284
- 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);
285
890
 
286
891
  // We need the sandbox name to construct preview URLs
287
892
  if (!this.sandboxName) {
288
893
  throw new Error(
289
- "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
894
+ 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
290
895
  );
291
896
  }
292
897
 
898
+ // Generate and store token for this port
899
+ const token = this.generatePortToken();
900
+ this.portTokens.set(port, token);
901
+ await this.persistPortTokens();
902
+
293
903
  const url = this.constructPreviewUrl(
294
904
  port,
295
905
  this.sandboxName,
296
- options.hostname
906
+ options.hostname,
907
+ token
297
908
  );
298
909
 
299
910
  return {
300
911
  url,
301
912
  port,
302
- name: options?.name,
913
+ name: options?.name
303
914
  };
304
915
  }
305
916
 
306
917
  async unexposePort(port: number) {
307
918
  if (!validatePort(port)) {
308
- logSecurityEvent(
309
- "INVALID_PORT_UNEXPOSE",
310
- {
311
- port,
312
- },
313
- "high"
314
- );
315
919
  throw new SecurityError(
316
920
  `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
317
921
  );
318
922
  }
319
923
 
320
- await this.client.unexposePort(port);
924
+ const sessionId = await this.ensureDefaultSession();
925
+ await this.client.ports.unexposePort(port, sessionId);
321
926
 
322
- logSecurityEvent(
323
- "PORT_UNEXPOSED",
324
- {
325
- port,
326
- },
327
- "low"
328
- );
927
+ // Clean up token for this port
928
+ if (this.portTokens.has(port)) {
929
+ this.portTokens.delete(port);
930
+ await this.persistPortTokens();
931
+ }
329
932
  }
330
933
 
331
934
  async getExposedPorts(hostname: string) {
332
- const response = await this.client.getExposedPorts();
935
+ const sessionId = await this.ensureDefaultSession();
936
+ const response = await this.client.ports.getExposedPorts(sessionId);
333
937
 
334
938
  // We need the sandbox name to construct preview URLs
335
939
  if (!this.sandboxName) {
336
940
  throw new Error(
337
- "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
941
+ 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
942
+ );
943
+ }
944
+
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
+ });
965
+ }
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
+ }
981
+
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;
987
+ }
988
+
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 }
338
997
  );
998
+ return false;
339
999
  }
340
1000
 
341
- return response.ports.map((port) => ({
342
- url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
343
- port: port.port,
344
- name: port.name,
345
- exposedAt: port.exposedAt,
346
- }));
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);
347
1027
  }
348
1028
 
349
1029
  private constructPreviewUrl(
350
1030
  port: number,
351
1031
  sandboxId: string,
352
- hostname: string
1032
+ hostname: string,
1033
+ token: string
353
1034
  ): string {
354
1035
  if (!validatePort(port)) {
355
- logSecurityEvent(
356
- "INVALID_PORT_REJECTED",
357
- {
358
- port,
359
- sandboxId,
360
- hostname,
361
- },
362
- "high"
363
- );
364
1036
  throw new SecurityError(
365
1037
  `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
366
1038
  );
367
1039
  }
368
1040
 
369
- let sanitizedSandboxId: string;
370
- try {
371
- sanitizedSandboxId = sanitizeSandboxId(sandboxId);
372
- } catch (error) {
373
- logSecurityEvent(
374
- "INVALID_SANDBOX_ID_REJECTED",
375
- {
376
- sandboxId,
377
- port,
378
- hostname,
379
- error: error instanceof Error ? error.message : "Unknown error",
380
- },
381
- "high"
382
- );
383
- throw error;
384
- }
1041
+ // Validate sandbox ID (will throw SecurityError if invalid)
1042
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
385
1043
 
386
1044
  const isLocalhost = isLocalhostPattern(hostname);
387
1045
 
388
1046
  if (isLocalhost) {
389
1047
  // Unified subdomain approach for localhost (RFC 6761)
390
- const [host, portStr] = hostname.split(":");
391
- const mainPort = portStr || "80";
1048
+ const [host, portStr] = hostname.split(':');
1049
+ const mainPort = portStr || '80';
392
1050
 
393
1051
  // Use URL constructor for safe URL building
394
1052
  try {
395
1053
  const baseUrl = new URL(`http://${host}:${mainPort}`);
396
- // Construct subdomain safely
397
- const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
1054
+ // Construct subdomain safely with mandatory token
1055
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
398
1056
  baseUrl.hostname = subdomainHost;
399
1057
 
400
- const finalUrl = baseUrl.toString();
401
-
402
- logSecurityEvent(
403
- "PREVIEW_URL_CONSTRUCTED",
404
- {
405
- port,
406
- sandboxId: sanitizedSandboxId,
407
- hostname,
408
- resultUrl: finalUrl,
409
- environment: "localhost",
410
- },
411
- "low"
412
- );
413
-
414
- return finalUrl;
1058
+ return baseUrl.toString();
415
1059
  } catch (error) {
416
- logSecurityEvent(
417
- "URL_CONSTRUCTION_FAILED",
418
- {
419
- port,
420
- sandboxId: sanitizedSandboxId,
421
- hostname,
422
- error: error instanceof Error ? error.message : "Unknown error",
423
- },
424
- "high"
425
- );
426
1060
  throw new SecurityError(
427
1061
  `Failed to construct preview URL: ${
428
- error instanceof Error ? error.message : "Unknown error"
1062
+ error instanceof Error ? error.message : 'Unknown error'
429
1063
  }`
430
1064
  );
431
1065
  }
@@ -434,73 +1068,168 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
434
1068
  // Production subdomain logic - enforce HTTPS
435
1069
  try {
436
1070
  // Always use HTTPS for production (non-localhost)
437
- const protocol = "https";
1071
+ const protocol = 'https';
438
1072
  const baseUrl = new URL(`${protocol}://${hostname}`);
439
1073
 
440
- // Construct subdomain safely
441
- const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
1074
+ // Construct subdomain safely with mandatory token
1075
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
442
1076
  baseUrl.hostname = subdomainHost;
443
1077
 
444
- const finalUrl = baseUrl.toString();
445
-
446
- logSecurityEvent(
447
- "PREVIEW_URL_CONSTRUCTED",
448
- {
449
- port,
450
- sandboxId: sanitizedSandboxId,
451
- hostname,
452
- resultUrl: finalUrl,
453
- environment: "production",
454
- },
455
- "low"
456
- );
457
-
458
- return finalUrl;
1078
+ return baseUrl.toString();
459
1079
  } catch (error) {
460
- logSecurityEvent(
461
- "URL_CONSTRUCTION_FAILED",
462
- {
463
- port,
464
- sandboxId: sanitizedSandboxId,
465
- hostname,
466
- error: error instanceof Error ? error.message : "Unknown error",
467
- },
468
- "high"
469
- );
470
1080
  throw new SecurityError(
471
1081
  `Failed to construct preview URL: ${
472
- error instanceof Error ? error.message : "Unknown error"
1082
+ error instanceof Error ? error.message : 'Unknown error'
473
1083
  }`
474
1084
  );
475
1085
  }
476
1086
  }
477
1087
 
478
- // Code Interpreter Methods
1088
+ // ============================================================================
1089
+ // Session Management - Advanced Use Cases
1090
+ // ============================================================================
479
1091
 
480
1092
  /**
481
- * Create a new code execution context
1093
+ * Create isolated execution session for advanced use cases
1094
+ * Returns ExecutionSession with full sandbox API bound to specific session
482
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
+
483
1219
  async createCodeContext(
484
1220
  options?: CreateContextOptions
485
1221
  ): Promise<CodeContext> {
486
1222
  return this.codeInterpreter.createCodeContext(options);
487
1223
  }
488
1224
 
489
- /**
490
- * Run code with streaming callbacks
491
- */
492
1225
  async runCode(
493
1226
  code: string,
494
1227
  options?: RunCodeOptions
495
1228
  ): Promise<ExecutionResult> {
496
1229
  const execution = await this.codeInterpreter.runCode(code, options);
497
- // Convert to plain object for RPC serialization
498
1230
  return execution.toJSON();
499
1231
  }
500
1232
 
501
- /**
502
- * Run code and return a streaming response
503
- */
504
1233
  async runCodeStream(
505
1234
  code: string,
506
1235
  options?: RunCodeOptions
@@ -508,249 +1237,11 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
508
1237
  return this.codeInterpreter.runCodeStream(code, options);
509
1238
  }
510
1239
 
511
- /**
512
- * List all code contexts
513
- */
514
1240
  async listCodeContexts(): Promise<CodeContext[]> {
515
1241
  return this.codeInterpreter.listCodeContexts();
516
1242
  }
517
1243
 
518
- /**
519
- * Delete a code context
520
- */
521
1244
  async deleteCodeContext(contextId: string): Promise<void> {
522
1245
  return this.codeInterpreter.deleteCodeContext(contextId);
523
1246
  }
524
-
525
- // ============================================================================
526
- // Session Management (Simple Isolation)
527
- // ============================================================================
528
-
529
- /**
530
- * Create a new execution session with isolation
531
- * Returns a session object with exec() method
532
- */
533
-
534
- async createSession(options: {
535
- id?: string;
536
- env?: Record<string, string>;
537
- cwd?: string;
538
- isolation?: boolean;
539
- }): Promise<ExecutionSession> {
540
- const sessionId = options.id || `session-${Date.now()}`;
541
-
542
- await this.client.createSession({
543
- id: sessionId,
544
- env: options.env,
545
- cwd: options.cwd,
546
- isolation: options.isolation
547
- });
548
- // Return comprehensive ExecutionSession object that implements all ISandbox methods
549
- return {
550
- id: sessionId,
551
-
552
- // Command execution - clean method names
553
- exec: async (command: string, options?: ExecOptions) => {
554
- const result = await this.client.exec(sessionId, command);
555
- return {
556
- ...result,
557
- command,
558
- duration: 0,
559
- timestamp: new Date().toISOString()
560
- };
561
- },
562
-
563
- execStream: async (command: string, options?: StreamOptions) => {
564
- return await this.client.execStream(sessionId, command);
565
- },
566
-
567
- // Process management - route to session-aware methods
568
- startProcess: async (command: string, options?: ProcessOptions) => {
569
- // Use session-specific process management
570
- const response = await this.client.startProcess(command, sessionId, {
571
- processId: options?.processId,
572
- timeout: options?.timeout,
573
- env: options?.env,
574
- cwd: options?.cwd,
575
- encoding: options?.encoding,
576
- autoCleanup: options?.autoCleanup,
577
- });
578
-
579
- // Convert response to Process object with bound methods
580
- const process = response.process;
581
- return {
582
- id: process.id,
583
- pid: process.pid,
584
- command: process.command,
585
- status: process.status as ProcessStatus,
586
- startTime: new Date(process.startTime),
587
- endTime: process.endTime ? new Date(process.endTime) : undefined,
588
- exitCode: process.exitCode ?? undefined,
589
- kill: async (signal?: string) => {
590
- await this.client.killProcess(process.id);
591
- },
592
- getStatus: async () => {
593
- const resp = await this.client.getProcess(process.id);
594
- return resp.process?.status as ProcessStatus || "error";
595
- },
596
- getLogs: async () => {
597
- return await this.client.getProcessLogs(process.id);
598
- },
599
- };
600
- },
601
-
602
- listProcesses: async () => {
603
- // Get processes for this specific session
604
- const response = await this.client.listProcesses(sessionId);
605
-
606
- // Convert to Process objects with bound methods
607
- return response.processes.map(p => ({
608
- id: p.id,
609
- pid: p.pid,
610
- command: p.command,
611
- status: p.status as ProcessStatus,
612
- startTime: new Date(p.startTime),
613
- endTime: p.endTime ? new Date(p.endTime) : undefined,
614
- exitCode: p.exitCode ?? undefined,
615
- kill: async (signal?: string) => {
616
- await this.client.killProcess(p.id);
617
- },
618
- getStatus: async () => {
619
- const processResp = await this.client.getProcess(p.id);
620
- return processResp.process?.status as ProcessStatus || "error";
621
- },
622
- getLogs: async () => {
623
- return this.client.getProcessLogs(p.id);
624
- },
625
- }));
626
- },
627
-
628
- getProcess: async (id: string) => {
629
- const response = await this.client.getProcess(id);
630
- if (!response.process) return null;
631
-
632
- const p = response.process;
633
- return {
634
- id: p.id,
635
- pid: p.pid,
636
- command: p.command,
637
- status: p.status as ProcessStatus,
638
- startTime: new Date(p.startTime),
639
- endTime: p.endTime ? new Date(p.endTime) : undefined,
640
- exitCode: p.exitCode ?? undefined,
641
- kill: async (signal?: string) => {
642
- await this.client.killProcess(p.id);
643
- },
644
- getStatus: async () => {
645
- const processResp = await this.client.getProcess(p.id);
646
- return processResp.process?.status as ProcessStatus || "error";
647
- },
648
- getLogs: async () => {
649
- return this.client.getProcessLogs(p.id);
650
- },
651
- };
652
- },
653
-
654
- killProcess: async (id: string, signal?: string) => {
655
- await this.client.killProcess(id);
656
- },
657
-
658
- killAllProcesses: async () => {
659
- // Kill all processes for this specific session
660
- const response = await this.client.killAllProcesses(sessionId);
661
- return response.killedCount;
662
- },
663
-
664
- streamProcessLogs: async (processId: string, options?: { signal?: AbortSignal }) => {
665
- return await this.client.streamProcessLogs(processId, options);
666
- },
667
-
668
- getProcessLogs: async (id: string) => {
669
- return await this.client.getProcessLogs(id);
670
- },
671
-
672
- cleanupCompletedProcesses: async () => {
673
- // This would need a new endpoint to cleanup processes for a specific session
674
- // For now, return 0 as no cleanup is performed
675
- return 0;
676
- },
677
-
678
- // File operations - clean method names (no "InSession" suffix)
679
- writeFile: async (path: string, content: string, options?: { encoding?: string }) => {
680
- return await this.client.writeFile(path, content, options?.encoding, sessionId);
681
- },
682
-
683
- readFile: async (path: string, options?: { encoding?: string }) => {
684
- return await this.client.readFile(path, options?.encoding, sessionId);
685
- },
686
-
687
- readFileStream: async (path: string) => {
688
- return await this.client.readFileStream(path, sessionId);
689
- },
690
-
691
- mkdir: async (path: string, options?: { recursive?: boolean }) => {
692
- return await this.client.mkdir(path, options?.recursive, sessionId);
693
- },
694
-
695
- deleteFile: async (path: string) => {
696
- return await this.client.deleteFile(path, sessionId);
697
- },
698
-
699
- renameFile: async (oldPath: string, newPath: string) => {
700
- return await this.client.renameFile(oldPath, newPath, sessionId);
701
- },
702
-
703
- moveFile: async (sourcePath: string, destinationPath: string) => {
704
- return await this.client.moveFile(sourcePath, destinationPath, sessionId);
705
- },
706
-
707
- listFiles: async (path: string, options?: { recursive?: boolean; includeHidden?: boolean }) => {
708
- return await this.client.listFiles(path, sessionId, options);
709
- },
710
-
711
- gitCheckout: async (repoUrl: string, options?: { branch?: string; targetDir?: string }) => {
712
- return await this.client.gitCheckout(repoUrl, sessionId, options?.branch, options?.targetDir);
713
- },
714
-
715
- // Port management
716
- exposePort: async (port: number, options: { name?: string; hostname: string }) => {
717
- return await this.exposePort(port, options);
718
- },
719
-
720
- unexposePort: async (port: number) => {
721
- return await this.unexposePort(port);
722
- },
723
-
724
- getExposedPorts: async (hostname: string) => {
725
- return await this.getExposedPorts(hostname);
726
- },
727
-
728
- // Environment management
729
- setEnvVars: async (envVars: Record<string, string>) => {
730
- // TODO: Implement session-specific environment updates
731
- console.log(`[Session ${sessionId}] Environment variables update not yet implemented`);
732
- },
733
-
734
- // Code Interpreter API
735
- createCodeContext: async (options?: any) => {
736
- return await this.createCodeContext(options);
737
- },
738
-
739
- runCode: async (code: string, options?: any) => {
740
- return await this.runCode(code, options);
741
- },
742
-
743
- runCodeStream: async (code: string, options?: any) => {
744
- return await this.runCodeStream(code, options);
745
- },
746
-
747
- listCodeContexts: async () => {
748
- return await this.listCodeContexts();
749
- },
750
-
751
- deleteCodeContext: async (contextId: string) => {
752
- return await this.deleteCodeContext(contextId);
753
- }
754
- };
755
- }
756
1247
  }