@cloudflare/sandbox 0.0.0-871f813 → 0.0.0-87a8d20

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