@cloudflare/sandbox 0.0.0-4aceb32 → 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 (66) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/Dockerfile +107 -66
  3. package/README.md +87 -710
  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 +87 -48
  25. package/src/interpreter.ts +22 -13
  26. package/src/request-handler.ts +80 -44
  27. package/src/sandbox.ts +767 -449
  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/handler/exec.ts +0 -340
  52. package/container_src/handler/file.ts +0 -844
  53. package/container_src/handler/git.ts +0 -182
  54. package/container_src/handler/ports.ts +0 -314
  55. package/container_src/handler/process.ts +0 -640
  56. package/container_src/index.ts +0 -656
  57. package/container_src/jupyter-server.ts +0 -579
  58. package/container_src/jupyter-service.ts +0 -448
  59. package/container_src/mime-processor.ts +0 -255
  60. package/container_src/package.json +0 -18
  61. package/container_src/startup.sh +0 -83
  62. package/container_src/types.ts +0 -108
  63. package/src/client.ts +0 -1021
  64. package/src/errors.ts +0 -218
  65. package/src/interpreter-types.ts +0 -383
  66. package/src/types.ts +0 -401
package/src/sandbox.ts CHANGED
@@ -1,75 +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
+ ExecEvent,
7
+ ExecOptions,
8
+ ExecResult,
6
9
  ExecutionResult,
10
+ ExecutionSession,
11
+ ISandbox,
12
+ Process,
13
+ ProcessOptions,
14
+ ProcessStatus,
7
15
  RunCodeOptions,
8
- } from "./interpreter-types";
9
- import { JupyterClient } from "./jupyter-client";
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";
10
25
  import { isLocalhostPattern } from "./request-handler";
11
26
  import {
12
- logSecurityEvent,
13
27
  SecurityError,
14
28
  sanitizeSandboxId,
15
- validatePort,
29
+ validatePort
16
30
  } from "./security";
17
31
  import { parseSSEStream } from "./sse-parser";
18
- import type {
19
- ExecOptions,
20
- ExecResult,
21
- ISandbox,
22
- Process,
23
- ProcessOptions,
24
- ProcessStatus,
25
- StreamOptions,
26
- } from "./types";
27
- import { ProcessNotFoundError, SandboxError } from "./types";
32
+ import { SDK_VERSION } from "./version";
28
33
 
29
- export function getSandbox(ns: DurableObjectNamespace<Sandbox>, id: string) {
30
- 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;
31
40
 
32
41
  // Store the name on first access
33
42
  stub.setSandboxName?.(id);
34
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
+
35
56
  return stub;
36
57
  }
37
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
+
38
93
  export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
39
94
  defaultPort = 3000; // Default port for the container's Bun server
40
- sleepAfter = "3m"; // Sleep the sandbox if no requests are made in this timeframe
41
- client: JupyterClient;
42
- private sandboxName: string | null = null;
43
- private codeInterpreter: CodeInterpreter;
95
+ sleepAfter: string | number = "10m"; // Sleep the sandbox if no requests are made in this timeframe
44
96
 
45
- 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) {
46
108
  super(ctx, env);
47
- this.client = new JupyterClient({
48
- onCommandComplete: (success, exitCode, _stdout, _stderr, command) => {
49
- console.log(
50
- `[Container] Command completed: ${command}, Success: ${success}, Exit code: ${exitCode}`
51
- );
52
- },
53
- onCommandStart: (command) => {
54
- console.log(`[Container] Command started: ${command}`);
55
- },
56
- onError: (error, _command) => {
57
- console.error(`[Container] Command error: ${error}`);
58
- },
59
- onOutput: (stream, data, _command) => {
60
- console.log(`[Container] [${stream}] ${data}`);
61
- },
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,
62
126
  port: 3000, // Control plane port
63
127
  stub: this,
64
128
  });
65
129
 
66
- // Initialize code interpreter
130
+ // Initialize code interpreter - pass 'this' after client is ready
131
+ // The CodeInterpreter extracts client.interpreter from the sandbox
67
132
  this.codeInterpreter = new CodeInterpreter(this);
68
133
 
69
- // Load the sandbox name from storage on initialization
134
+ // Load the sandbox name, port tokens, and default session from storage on initialization
70
135
  this.ctx.blockConcurrencyWhile(async () => {
71
- this.sandboxName =
72
- (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
+ }
73
145
  });
74
146
  }
75
147
 
@@ -77,56 +149,199 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
77
149
  async setSandboxName(name: string): Promise<void> {
78
150
  if (!this.sandboxName) {
79
151
  this.sandboxName = name;
80
- await this.ctx.storage.put("sandboxName", name);
81
- 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');
82
180
  }
83
181
  }
84
182
 
85
183
  // RPC method to set environment variables
86
184
  async setEnvVars(envVars: Record<string, string>): Promise<void> {
185
+ // Update local state for new sessions
87
186
  this.envVars = { ...this.envVars, ...envVars };
88
- console.log(`[Sandbox] Updated environment variables`);
187
+
188
+ // If default session already exists, update it directly
189
+ if (this.defaultSession) {
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
+ }
201
+ }
202
+ }
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();
89
210
  }
90
211
 
91
212
  override onStart() {
92
- 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
+ });
93
219
  }
94
220
 
95
- override onStop() {
96
- console.log("Sandbox successfully shut down");
97
- if (this.client) {
98
- this.client.clearSession();
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
+ });
99
261
  }
100
262
  }
101
263
 
264
+ override onStop() {
265
+ this.logger.debug('Sandbox stopped');
266
+ }
267
+
102
268
  override onError(error: unknown) {
103
- 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
+ }
104
285
  }
105
286
 
287
+
106
288
  // Override fetch to route internal container requests to appropriate ports
107
289
  override async fetch(request: Request): Promise<Response> {
108
- const url = new URL(request.url);
290
+ // Extract or generate trace ID from request
291
+ const traceId = TraceContext.fromHeaders(request.headers) || TraceContext.generate();
109
292
 
110
- // Capture and store the sandbox name from the header if present
111
- if (!this.sandboxName && request.headers.has("X-Sandbox-Name")) {
112
- const name = request.headers.get("X-Sandbox-Name")!;
113
- this.sandboxName = name;
114
- await this.ctx.storage.put("sandboxName", name);
115
- console.log(`[Sandbox] Stored sandbox name: ${this.sandboxName}`);
116
- }
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
+ }
117
331
 
118
- // Determine which port to route to
119
- const port = this.determinePort(url);
332
+ // Non-WebSocket: Use existing port determination and HTTP routing logic
333
+ const port = this.determinePort(url);
120
334
 
121
- // Route to the appropriate port
122
- return await this.containerFetch(request, port);
335
+ // Route to the appropriate port
336
+ return await this.containerFetch(request, port);
337
+ });
123
338
  }
124
339
 
125
340
  private determinePort(url: URL): number {
126
341
  // Extract port from proxy requests (e.g., /proxy/8080/*)
127
342
  const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
128
343
  if (proxyMatch) {
129
- return parseInt(proxyMatch[1]);
344
+ return parseInt(proxyMatch[1], 10);
130
345
  }
131
346
 
132
347
  // All other requests go to control plane on port 3000
@@ -134,45 +349,84 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
134
349
  return 3000;
135
350
  }
136
351
 
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> {
361
+ if (!this.defaultSession) {
362
+ const sessionId = `sandbox-${this.sandboxName || 'default'}`;
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
+ }
388
+ }
389
+ return this.defaultSession;
390
+ }
391
+
137
392
  // Enhanced exec method - always returns ExecResult with optional streaming
138
393
  // This replaces the old exec method to match ISandbox interface
139
394
  async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
395
+ const session = await this.ensureDefaultSession();
396
+ return this.execWithSession(command, session, options);
397
+ }
398
+
399
+ /**
400
+ * Internal session-aware exec implementation
401
+ * Used by both public exec() and session wrappers
402
+ */
403
+ private async execWithSession(
404
+ command: string,
405
+ sessionId: string,
406
+ options?: ExecOptions
407
+ ): Promise<ExecResult> {
140
408
  const startTime = Date.now();
141
409
  const timestamp = new Date().toISOString();
142
410
 
143
- // Handle timeout
144
411
  let timeoutId: NodeJS.Timeout | undefined;
145
412
 
146
413
  try {
147
414
  // Handle cancellation
148
415
  if (options?.signal?.aborted) {
149
- throw new Error("Operation was aborted");
416
+ throw new Error('Operation was aborted');
150
417
  }
151
418
 
152
419
  let result: ExecResult;
153
420
 
154
421
  if (options?.stream && options?.onOutput) {
155
422
  // Streaming with callbacks - we need to collect the final result
156
- result = await this.executeWithStreaming(
157
- command,
158
- options,
159
- startTime,
160
- timestamp
161
- );
423
+ result = await this.executeWithStreaming(command, sessionId, options, startTime, timestamp);
162
424
  } else {
163
- // Regular execution
164
- const response = await this.client.execute(command, {
165
- sessionId: options?.sessionId,
166
- cwd: options?.cwd,
167
- env: options?.env,
168
- });
425
+ // Regular execution with session
426
+ const response = await this.client.commands.execute(command, sessionId);
169
427
 
170
428
  const duration = Date.now() - startTime;
171
- result = this.mapExecuteResponseToExecResult(
172
- response,
173
- duration,
174
- options?.sessionId
175
- );
429
+ result = this.mapExecuteResponseToExecResult(response, duration, sessionId);
176
430
  }
177
431
 
178
432
  // Call completion callback if provided
@@ -195,34 +449,30 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
195
449
 
196
450
  private async executeWithStreaming(
197
451
  command: string,
452
+ sessionId: string,
198
453
  options: ExecOptions,
199
454
  startTime: number,
200
455
  timestamp: string
201
456
  ): Promise<ExecResult> {
202
- let stdout = "";
203
- let stderr = "";
457
+ let stdout = '';
458
+ let stderr = '';
204
459
 
205
460
  try {
206
- const stream = await this.client.executeCommandStream(
207
- command,
208
- options.sessionId
209
- );
210
-
211
- for await (const event of parseSSEStream<import("./types").ExecEvent>(
212
- stream
213
- )) {
461
+ const stream = await this.client.commands.executeStream(command, sessionId);
462
+
463
+ for await (const event of parseSSEStream<ExecEvent>(stream)) {
214
464
  // Check for cancellation
215
465
  if (options.signal?.aborted) {
216
- throw new Error("Operation was aborted");
466
+ throw new Error('Operation was aborted');
217
467
  }
218
468
 
219
469
  switch (event.type) {
220
- case "stdout":
221
- case "stderr":
470
+ case 'stdout':
471
+ case 'stderr':
222
472
  if (event.data) {
223
473
  // Update accumulated output
224
- if (event.type === "stdout") stdout += event.data;
225
- if (event.type === "stderr") stderr += event.data;
474
+ if (event.type === 'stdout') stdout += event.data;
475
+ if (event.type === 'stderr') stderr += event.data;
226
476
 
227
477
  // Call user's callback
228
478
  if (options.onOutput) {
@@ -231,40 +481,39 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
231
481
  }
232
482
  break;
233
483
 
234
- case "complete": {
484
+ case 'complete': {
235
485
  // Use result from complete event if available
236
486
  const duration = Date.now() - startTime;
237
- return (
238
- event.result || {
239
- success: event.exitCode === 0,
240
- exitCode: event.exitCode || 0,
241
- stdout,
242
- stderr,
243
- command,
244
- duration,
245
- timestamp,
246
- sessionId: options.sessionId,
247
- }
248
- );
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
+ };
249
497
  }
250
498
 
251
- case "error":
252
- throw new Error(event.error || "Command execution failed");
499
+ case 'error':
500
+ throw new Error(event.data || 'Command execution failed');
253
501
  }
254
502
  }
255
503
 
256
504
  // If we get here without a complete event, something went wrong
257
- throw new Error("Stream ended without completion event");
505
+ throw new Error('Stream ended without completion event');
506
+
258
507
  } catch (error) {
259
508
  if (options.signal?.aborted) {
260
- throw new Error("Operation was aborted");
509
+ throw new Error('Operation was aborted');
261
510
  }
262
511
  throw error;
263
512
  }
264
513
  }
265
514
 
266
515
  private mapExecuteResponseToExecResult(
267
- response: import("./client").ExecuteResponse,
516
+ response: ExecuteResponse,
268
517
  duration: number,
269
518
  sessionId?: string
270
519
  ): ExecResult {
@@ -276,63 +525,72 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
276
525
  command: response.command,
277
526
  duration,
278
527
  timestamp: response.timestamp,
528
+ sessionId
529
+ };
530
+ }
531
+
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,
279
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
+ }
280
572
  };
281
573
  }
282
574
 
575
+
283
576
  // Background process management
284
- async startProcess(
285
- command: string,
286
- options?: ProcessOptions
287
- ): Promise<Process> {
577
+ async startProcess(command: string, options?: ProcessOptions, sessionId?: string): Promise<Process> {
288
578
  // Use the new HttpClient method to start the process
289
579
  try {
290
- const response = await this.client.startProcess(command, {
291
- processId: options?.processId,
292
- sessionId: options?.sessionId,
293
- timeout: options?.timeout,
294
- env: options?.env,
295
- cwd: options?.cwd,
296
- encoding: options?.encoding,
297
- autoCleanup: options?.autoCleanup,
580
+ const session = sessionId ?? await this.ensureDefaultSession();
581
+ const response = await this.client.processes.startProcess(command, session, {
582
+ processId: options?.processId
298
583
  });
299
584
 
300
- const process = response.process;
301
- const processObj: Process = {
302
- id: process.id,
303
- pid: process.pid,
304
- command: process.command,
305
- status: process.status as ProcessStatus,
306
- startTime: new Date(process.startTime),
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(),
307
591
  endTime: undefined,
308
- exitCode: undefined,
309
- sessionId: process.sessionId,
310
-
311
- async kill(): Promise<void> {
312
- throw new Error("Method will be replaced");
313
- },
314
- async getStatus(): Promise<ProcessStatus> {
315
- throw new Error("Method will be replaced");
316
- },
317
- async getLogs(): Promise<{ stdout: string; stderr: string }> {
318
- throw new Error("Method will be replaced");
319
- },
320
- };
321
-
322
- // Bind context properly
323
- processObj.kill = async (signal?: string) => {
324
- await this.killProcess(process.id, signal);
325
- };
326
-
327
- processObj.getStatus = async () => {
328
- const current = await this.getProcess(process.id);
329
- return current?.status || "error";
330
- };
331
-
332
- processObj.getLogs = async () => {
333
- const logs = await this.getProcessLogs(process.id);
334
- return { stdout: logs.stdout, stderr: logs.stderr };
335
- };
592
+ exitCode: undefined
593
+ }, session);
336
594
 
337
595
  // Call onStart callback if provided
338
596
  if (options?.onStart) {
@@ -340,6 +598,7 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
340
598
  }
341
599
 
342
600
  return processObj;
601
+
343
602
  } catch (error) {
344
603
  if (options?.onError && error instanceof Error) {
345
604
  options.onError(error);
@@ -349,206 +608,219 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
349
608
  }
350
609
  }
351
610
 
352
- async listProcesses(): Promise<Process[]> {
353
- const response = await this.client.listProcesses();
354
-
355
- return response.processes.map((processData) => ({
356
- id: processData.id,
357
- pid: processData.pid,
358
- command: processData.command,
359
- status: processData.status,
360
- startTime: new Date(processData.startTime),
361
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
362
- exitCode: processData.exitCode,
363
- sessionId: processData.sessionId,
364
-
365
- kill: async (signal?: string) => {
366
- await this.killProcess(processData.id, signal);
367
- },
368
-
369
- getStatus: async () => {
370
- const current = await this.getProcess(processData.id);
371
- return current?.status || "error";
372
- },
373
-
374
- getLogs: async () => {
375
- const logs = await this.getProcessLogs(processData.id);
376
- return { stdout: logs.stdout, stderr: logs.stderr };
377
- },
378
- }));
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
+ );
379
626
  }
380
627
 
381
- async getProcess(id: string): Promise<Process | null> {
382
- const response = await this.client.getProcess(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);
383
631
  if (!response.process) {
384
632
  return null;
385
633
  }
386
634
 
387
635
  const processData = response.process;
388
- return {
636
+ return this.createProcessFromDTO({
389
637
  id: processData.id,
390
638
  pid: processData.pid,
391
639
  command: processData.command,
392
640
  status: processData.status,
393
- startTime: new Date(processData.startTime),
394
- endTime: processData.endTime ? new Date(processData.endTime) : undefined,
395
- exitCode: processData.exitCode,
396
- sessionId: processData.sessionId,
397
-
398
- kill: async (signal?: string) => {
399
- await this.killProcess(processData.id, signal);
400
- },
401
-
402
- getStatus: async () => {
403
- const current = await this.getProcess(processData.id);
404
- return current?.status || "error";
405
- },
406
-
407
- getLogs: async () => {
408
- const logs = await this.getProcessLogs(processData.id);
409
- return { stdout: logs.stdout, stderr: logs.stderr };
410
- },
411
- };
641
+ startTime: processData.startTime,
642
+ endTime: processData.endTime,
643
+ exitCode: processData.exitCode
644
+ }, session);
412
645
  }
413
646
 
414
- async killProcess(id: string, _signal?: string): Promise<void> {
415
- try {
416
- // Note: signal parameter is not currently supported by the HttpClient implementation
417
- await this.client.killProcess(id);
418
- } catch (error) {
419
- if (
420
- error instanceof Error &&
421
- error.message.includes("Process not found")
422
- ) {
423
- throw new ProcessNotFoundError(id);
424
- }
425
- throw new SandboxError(
426
- `Failed to kill process ${id}: ${
427
- error instanceof Error ? error.message : "Unknown error"
428
- }`,
429
- "KILL_PROCESS_FAILED"
430
- );
431
- }
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);
432
651
  }
433
652
 
434
- async killAllProcesses(): Promise<number> {
435
- const response = await this.client.killAllProcesses();
436
- return response.killedCount;
653
+ async killAllProcesses(sessionId?: string): Promise<number> {
654
+ const response = await this.client.processes.killAllProcesses();
655
+ return response.cleanedCount;
437
656
  }
438
657
 
439
- async cleanupCompletedProcesses(): Promise<number> {
658
+ async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
440
659
  // For now, this would need to be implemented as a container endpoint
441
660
  // as we no longer maintain local process storage
442
661
  // We'll return 0 as a placeholder until the container endpoint is added
443
662
  return 0;
444
663
  }
445
664
 
446
- async getProcessLogs(
447
- id: string
448
- ): Promise<{ stdout: string; stderr: string }> {
449
- try {
450
- const response = await this.client.getProcessLogs(id);
451
- return {
452
- stdout: response.stdout,
453
- stderr: response.stderr,
454
- };
455
- } catch (error) {
456
- if (
457
- error instanceof Error &&
458
- error.message.includes("Process not found")
459
- ) {
460
- throw new ProcessNotFoundError(id);
461
- }
462
- throw error;
463
- }
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
+ };
464
673
  }
465
674
 
466
- // Streaming methods - return ReadableStream for RPC compatibility
467
- async execStream(
468
- command: string,
469
- options?: StreamOptions
470
- ): Promise<ReadableStream<Uint8Array>> {
675
+ // Streaming methods - return ReadableStream for RPC compatibility
676
+ async execStream(command: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>> {
471
677
  // Check for cancellation
472
678
  if (options?.signal?.aborted) {
473
- throw new Error("Operation was aborted");
679
+ throw new Error('Operation was aborted');
474
680
  }
475
681
 
476
- // Get the stream from HttpClient (need to add this method)
477
- const stream = await this.client.executeCommandStream(
478
- command,
479
- options?.sessionId
480
- );
481
-
482
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
483
- return stream;
682
+ const session = await this.ensureDefaultSession();
683
+ // Get the stream from CommandClient
684
+ return this.client.commands.executeStream(command, session);
484
685
  }
485
686
 
486
- async streamProcessLogs(
487
- processId: string,
488
- options?: { signal?: AbortSignal }
489
- ): Promise<ReadableStream<Uint8Array>> {
687
+ /**
688
+ * Internal session-aware execStream implementation
689
+ */
690
+ private async execStreamWithSession(command: string, sessionId: string, options?: StreamOptions): Promise<ReadableStream<Uint8Array>> {
490
691
  // Check for cancellation
491
692
  if (options?.signal?.aborted) {
492
- throw new Error("Operation was aborted");
693
+ throw new Error('Operation was aborted');
493
694
  }
494
695
 
495
- // Get the stream from HttpClient
496
- const stream = await this.client.streamProcessLogs(processId);
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
+ }
497
707
 
498
- // Return the ReadableStream directly - can be converted to AsyncIterable by consumers
499
- return stream;
708
+ return this.client.processes.streamProcessLogs(processId);
500
709
  }
501
710
 
502
711
  async gitCheckout(
503
712
  repoUrl: string,
504
- options: { branch?: string; targetDir?: string }
713
+ options: { branch?: string; targetDir?: string; sessionId?: string }
505
714
  ) {
506
- return this.client.gitCheckout(repoUrl, options.branch, options.targetDir);
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
+ });
507
720
  }
508
721
 
509
- async mkdir(path: string, options: { recursive?: boolean } = {}) {
510
- return this.client.mkdir(path, options.recursive);
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 });
511
728
  }
512
729
 
513
730
  async writeFile(
514
731
  path: string,
515
732
  content: string,
516
- options: { encoding?: string } = {}
733
+ options: { encoding?: string; sessionId?: string } = {}
517
734
  ) {
518
- return this.client.writeFile(path, content, options.encoding);
735
+ const session = options.sessionId ?? await this.ensureDefaultSession();
736
+ return this.client.files.writeFile(path, content, session, { encoding: options.encoding });
519
737
  }
520
738
 
521
- async deleteFile(path: string) {
522
- return this.client.deleteFile(path);
739
+ async deleteFile(path: string, sessionId?: string) {
740
+ const session = sessionId ?? await this.ensureDefaultSession();
741
+ return this.client.files.deleteFile(path, session);
742
+ }
743
+
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);
523
751
  }
524
752
 
525
- async renameFile(oldPath: string, newPath: string) {
526
- return this.client.renameFile(oldPath, newPath);
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);
527
760
  }
528
761
 
529
- async moveFile(sourcePath: string, destinationPath: string) {
530
- return this.client.moveFile(sourcePath, destinationPath);
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 });
531
768
  }
532
769
 
533
- async readFile(path: string, options: { encoding?: string } = {}) {
534
- return this.client.readFile(path, options.encoding);
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);
782
+ }
783
+
784
+ async listFiles(
785
+ path: string,
786
+ options?: { recursive?: boolean; includeHidden?: boolean }
787
+ ) {
788
+ const session = await this.ensureDefaultSession();
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);
535
795
  }
536
796
 
537
797
  async exposePort(port: number, options: { name?: string; hostname: string }) {
538
- 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);
539
812
 
540
813
  // We need the sandbox name to construct preview URLs
541
814
  if (!this.sandboxName) {
542
- throw new Error(
543
- "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
544
- );
815
+ throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
545
816
  }
546
817
 
547
- const url = this.constructPreviewUrl(
548
- port,
549
- this.sandboxName,
550
- options.hostname
551
- );
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);
552
824
 
553
825
  return {
554
826
  url,
@@ -559,129 +831,120 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
559
831
 
560
832
  async unexposePort(port: number) {
561
833
  if (!validatePort(port)) {
562
- logSecurityEvent(
563
- "INVALID_PORT_UNEXPOSE",
564
- {
565
- port,
566
- },
567
- "high"
568
- );
569
- throw new SecurityError(
570
- `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
571
- );
834
+ throw new SecurityError(`Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`);
572
835
  }
573
836
 
574
- await this.client.unexposePort(port);
837
+ const sessionId = await this.ensureDefaultSession();
838
+ await this.client.ports.unexposePort(port, sessionId);
575
839
 
576
- logSecurityEvent(
577
- "PORT_UNEXPOSED",
578
- {
579
- port,
580
- },
581
- "low"
582
- );
840
+ // Clean up token for this port
841
+ if (this.portTokens.has(port)) {
842
+ this.portTokens.delete(port);
843
+ await this.persistPortTokens();
844
+ }
583
845
  }
584
846
 
585
847
  async getExposedPorts(hostname: string) {
586
- const response = await this.client.getExposedPorts();
848
+ const sessionId = await this.ensureDefaultSession();
849
+ const response = await this.client.ports.getExposedPorts(sessionId);
587
850
 
588
851
  // We need the sandbox name to construct preview URLs
589
852
  if (!this.sandboxName) {
590
- throw new Error(
591
- "Sandbox name not available. Ensure sandbox is accessed through getSandbox()"
592
- );
853
+ throw new Error('Sandbox name not available. Ensure sandbox is accessed through getSandbox()');
593
854
  }
594
855
 
595
- return response.ports.map((port) => ({
596
- url: this.constructPreviewUrl(port.port, this.sandboxName!, hostname),
597
- port: port.port,
598
- name: port.name,
599
- exposedAt: port.exposedAt,
600
- }));
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
+ });
601
869
  }
602
870
 
603
- private constructPreviewUrl(
604
- port: number,
605
- sandboxId: string,
606
- hostname: string
607
- ): string {
608
- if (!validatePort(port)) {
609
- logSecurityEvent(
610
- "INVALID_PORT_REJECTED",
611
- {
612
- port,
613
- sandboxId,
614
- hostname,
615
- },
616
- "high"
617
- );
618
- throw new SecurityError(
619
- `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
620
- );
621
- }
622
871
 
623
- let sanitizedSandboxId: string;
872
+ async isPortExposed(port: number): Promise<boolean> {
624
873
  try {
625
- 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);
626
877
  } catch (error) {
627
- logSecurityEvent(
628
- "INVALID_SANDBOX_ID_REJECTED",
629
- {
630
- sandboxId,
631
- port,
632
- hostname,
633
- error: error instanceof Error ? error.message : "Unknown error",
634
- },
635
- "high"
636
- );
637
- 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;
638
896
  }
639
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.`);
926
+ }
927
+
928
+ // Validate sandbox ID (will throw SecurityError if invalid)
929
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
930
+
640
931
  const isLocalhost = isLocalhostPattern(hostname);
641
932
 
642
933
  if (isLocalhost) {
643
934
  // Unified subdomain approach for localhost (RFC 6761)
644
- const [host, portStr] = hostname.split(":");
645
- const mainPort = portStr || "80";
935
+ const [host, portStr] = hostname.split(':');
936
+ const mainPort = portStr || '80';
646
937
 
647
938
  // Use URL constructor for safe URL building
648
939
  try {
649
940
  const baseUrl = new URL(`http://${host}:${mainPort}`);
650
- // Construct subdomain safely
651
- const subdomainHost = `${port}-${sanitizedSandboxId}.${host}`;
941
+ // Construct subdomain safely with mandatory token
942
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
652
943
  baseUrl.hostname = subdomainHost;
653
944
 
654
- const finalUrl = baseUrl.toString();
655
-
656
- logSecurityEvent(
657
- "PREVIEW_URL_CONSTRUCTED",
658
- {
659
- port,
660
- sandboxId: sanitizedSandboxId,
661
- hostname,
662
- resultUrl: finalUrl,
663
- environment: "localhost",
664
- },
665
- "low"
666
- );
667
-
668
- return finalUrl;
945
+ return baseUrl.toString();
669
946
  } catch (error) {
670
- logSecurityEvent(
671
- "URL_CONSTRUCTION_FAILED",
672
- {
673
- port,
674
- sandboxId: sanitizedSandboxId,
675
- hostname,
676
- error: error instanceof Error ? error.message : "Unknown error",
677
- },
678
- "high"
679
- );
680
- throw new SecurityError(
681
- `Failed to construct preview URL: ${
682
- error instanceof Error ? error.message : "Unknown error"
683
- }`
684
- );
947
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
685
948
  }
686
949
  }
687
950
 
@@ -691,87 +954,142 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
691
954
  const protocol = "https";
692
955
  const baseUrl = new URL(`${protocol}://${hostname}`);
693
956
 
694
- // Construct subdomain safely
695
- const subdomainHost = `${port}-${sanitizedSandboxId}.${hostname}`;
957
+ // Construct subdomain safely with mandatory token
958
+ const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
696
959
  baseUrl.hostname = subdomainHost;
697
960
 
698
- const finalUrl = baseUrl.toString();
699
-
700
- logSecurityEvent(
701
- "PREVIEW_URL_CONSTRUCTED",
702
- {
703
- port,
704
- sandboxId: sanitizedSandboxId,
705
- hostname,
706
- resultUrl: finalUrl,
707
- environment: "production",
708
- },
709
- "low"
710
- );
711
-
712
- return finalUrl;
961
+ return baseUrl.toString();
713
962
  } catch (error) {
714
- logSecurityEvent(
715
- "URL_CONSTRUCTION_FAILED",
716
- {
717
- port,
718
- sandboxId: sanitizedSandboxId,
719
- hostname,
720
- error: error instanceof Error ? error.message : "Unknown error",
721
- },
722
- "high"
723
- );
724
- throw new SecurityError(
725
- `Failed to construct preview URL: ${
726
- error instanceof Error ? error.message : "Unknown error"
727
- }`
728
- );
963
+ throw new SecurityError(`Failed to construct preview URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
729
964
  }
730
965
  }
731
966
 
732
- // Code Interpreter Methods
967
+ // ============================================================================
968
+ // Session Management - Advanced Use Cases
969
+ // ============================================================================
733
970
 
734
971
  /**
735
- * 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
736
974
  */
737
- async createCodeContext(
738
- options?: CreateContextOptions
739
- ): Promise<CodeContext> {
740
- 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);
741
987
  }
742
988
 
743
989
  /**
744
- * 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
745
998
  */
746
- async runCode(
747
- code: string,
748
- options?: RunCodeOptions
749
- ): Promise<ExecutionResult> {
750
- const execution = await this.codeInterpreter.runCode(code, options);
751
- // Convert to plain object for RPC serialization
752
- 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);
753
1002
  }
754
1003
 
755
1004
  /**
756
- * 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
757
1007
  */
758
- async runCodeStream(
759
- code: string,
760
- options?: RunCodeOptions
761
- ): 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> {
762
1086
  return this.codeInterpreter.runCodeStream(code, options);
763
1087
  }
764
1088
 
765
- /**
766
- * List all code contexts
767
- */
768
1089
  async listCodeContexts(): Promise<CodeContext[]> {
769
1090
  return this.codeInterpreter.listCodeContexts();
770
1091
  }
771
1092
 
772
- /**
773
- * Delete a code context
774
- */
775
1093
  async deleteCodeContext(contextId: string): Promise<void> {
776
1094
  return this.codeInterpreter.deleteCodeContext(contextId);
777
1095
  }