@cloudflare/sandbox 0.0.0-1dfb064 → 0.0.0-2011e85

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