@cloudflare/sandbox 0.0.0-7de28be → 0.0.0-7f4442b

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