@cloudflare/sandbox 0.5.4 → 0.6.0

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 (57) hide show
  1. package/Dockerfile +54 -59
  2. package/README.md +1 -1
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +12 -1
  6. package/dist/index.js.map +1 -1
  7. package/package.json +13 -8
  8. package/.turbo/turbo-build.log +0 -23
  9. package/CHANGELOG.md +0 -441
  10. package/src/clients/base-client.ts +0 -356
  11. package/src/clients/command-client.ts +0 -133
  12. package/src/clients/file-client.ts +0 -300
  13. package/src/clients/git-client.ts +0 -98
  14. package/src/clients/index.ts +0 -64
  15. package/src/clients/interpreter-client.ts +0 -333
  16. package/src/clients/port-client.ts +0 -105
  17. package/src/clients/process-client.ts +0 -198
  18. package/src/clients/sandbox-client.ts +0 -39
  19. package/src/clients/types.ts +0 -88
  20. package/src/clients/utility-client.ts +0 -156
  21. package/src/errors/adapter.ts +0 -238
  22. package/src/errors/classes.ts +0 -594
  23. package/src/errors/index.ts +0 -109
  24. package/src/file-stream.ts +0 -169
  25. package/src/index.ts +0 -121
  26. package/src/interpreter.ts +0 -168
  27. package/src/openai/index.ts +0 -465
  28. package/src/request-handler.ts +0 -184
  29. package/src/sandbox.ts +0 -1937
  30. package/src/security.ts +0 -119
  31. package/src/sse-parser.ts +0 -144
  32. package/src/storage-mount/credential-detection.ts +0 -41
  33. package/src/storage-mount/errors.ts +0 -51
  34. package/src/storage-mount/index.ts +0 -17
  35. package/src/storage-mount/provider-detection.ts +0 -93
  36. package/src/storage-mount/types.ts +0 -17
  37. package/src/version.ts +0 -6
  38. package/tests/base-client.test.ts +0 -582
  39. package/tests/command-client.test.ts +0 -444
  40. package/tests/file-client.test.ts +0 -831
  41. package/tests/file-stream.test.ts +0 -310
  42. package/tests/get-sandbox.test.ts +0 -172
  43. package/tests/git-client.test.ts +0 -455
  44. package/tests/openai-shell-editor.test.ts +0 -434
  45. package/tests/port-client.test.ts +0 -283
  46. package/tests/process-client.test.ts +0 -649
  47. package/tests/request-handler.test.ts +0 -292
  48. package/tests/sandbox.test.ts +0 -890
  49. package/tests/sse-parser.test.ts +0 -291
  50. package/tests/storage-mount/credential-detection.test.ts +0 -119
  51. package/tests/storage-mount/provider-detection.test.ts +0 -77
  52. package/tests/utility-client.test.ts +0 -339
  53. package/tests/version.test.ts +0 -16
  54. package/tests/wrangler.jsonc +0 -35
  55. package/tsconfig.json +0 -11
  56. package/tsdown.config.ts +0 -13
  57. package/vitest.config.ts +0 -31
package/src/sandbox.ts DELETED
@@ -1,1937 +0,0 @@
1
- import { Container, getContainer, switchPort } from '@cloudflare/containers';
2
- import type {
3
- BucketCredentials,
4
- BucketProvider,
5
- CodeContext,
6
- CreateContextOptions,
7
- ExecEvent,
8
- ExecOptions,
9
- ExecResult,
10
- ExecutionResult,
11
- ExecutionSession,
12
- ISandbox,
13
- MountBucketOptions,
14
- Process,
15
- ProcessOptions,
16
- ProcessStatus,
17
- RunCodeOptions,
18
- SandboxOptions,
19
- SessionOptions,
20
- StreamOptions
21
- } from '@repo/shared';
22
- import {
23
- createLogger,
24
- getEnvString,
25
- type SessionDeleteResult,
26
- shellEscape,
27
- TraceContext
28
- } from '@repo/shared';
29
- import { type ExecuteResponse, SandboxClient } from './clients';
30
- import type { ErrorResponse } from './errors';
31
- import { CustomDomainRequiredError, ErrorCode } from './errors';
32
- import { CodeInterpreter } from './interpreter';
33
- import { isLocalhostPattern } from './request-handler';
34
- import { SecurityError, sanitizeSandboxId, validatePort } from './security';
35
- import { parseSSEStream } from './sse-parser';
36
- import {
37
- detectCredentials,
38
- detectProviderFromUrl,
39
- resolveS3fsOptions
40
- } from './storage-mount';
41
- import {
42
- InvalidMountConfigError,
43
- S3FSMountError
44
- } from './storage-mount/errors';
45
- import type { MountInfo } from './storage-mount/types';
46
- import { SDK_VERSION } from './version';
47
-
48
- export function getSandbox(
49
- ns: DurableObjectNamespace<Sandbox>,
50
- id: string,
51
- options?: SandboxOptions
52
- ): Sandbox {
53
- const sanitizedId = sanitizeSandboxId(id);
54
- const effectiveId = options?.normalizeId
55
- ? sanitizedId.toLowerCase()
56
- : sanitizedId;
57
-
58
- const hasUppercase = /[A-Z]/.test(sanitizedId);
59
- if (!options?.normalizeId && hasUppercase) {
60
- const logger = createLogger({ component: 'sandbox-do' });
61
- logger.warn(
62
- `Sandbox ID "${sanitizedId}" contains uppercase letters, which causes issues with preview URLs (hostnames are case-insensitive). ` +
63
- `normalizeId will default to true in a future version to prevent this. ` +
64
- `Use lowercase IDs or pass { normalizeId: true } to prepare.`
65
- );
66
- }
67
-
68
- const stub = getContainer(ns, effectiveId) as unknown as Sandbox;
69
-
70
- stub.setSandboxName?.(effectiveId, options?.normalizeId);
71
-
72
- if (options?.baseUrl) {
73
- stub.setBaseUrl(options.baseUrl);
74
- }
75
-
76
- if (options?.sleepAfter !== undefined) {
77
- stub.setSleepAfter(options.sleepAfter);
78
- }
79
-
80
- if (options?.keepAlive !== undefined) {
81
- stub.setKeepAlive(options.keepAlive);
82
- }
83
-
84
- if (options?.containerTimeouts) {
85
- stub.setContainerTimeouts(options.containerTimeouts);
86
- }
87
-
88
- return Object.assign(stub, {
89
- wsConnect: connect(stub)
90
- });
91
- }
92
-
93
- export function connect(stub: {
94
- fetch: (request: Request) => Promise<Response>;
95
- }) {
96
- return async (request: Request, port: number) => {
97
- if (!validatePort(port)) {
98
- throw new SecurityError(
99
- `Invalid or restricted port: ${port}. Ports must be in range 1024-65535 and not reserved.`
100
- );
101
- }
102
- const portSwitchedRequest = switchPort(request, port);
103
- return await stub.fetch(portSwitchedRequest);
104
- };
105
- }
106
-
107
- export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
108
- defaultPort = 3000; // Default port for the container's Bun server
109
- sleepAfter: string | number = '10m'; // Sleep the sandbox if no requests are made in this timeframe
110
-
111
- client: SandboxClient;
112
- private codeInterpreter: CodeInterpreter;
113
- private sandboxName: string | null = null;
114
- private normalizeId: boolean = false;
115
- private baseUrl: string | null = null;
116
- private portTokens: Map<number, string> = new Map();
117
- private defaultSession: string | null = null;
118
- envVars: Record<string, string> = {};
119
- private logger: ReturnType<typeof createLogger>;
120
- private keepAliveEnabled: boolean = false;
121
- private activeMounts: Map<string, MountInfo> = new Map();
122
-
123
- /**
124
- * Default container startup timeouts (conservative for production)
125
- * Based on Cloudflare docs: "Containers take several minutes to provision"
126
- */
127
- private readonly DEFAULT_CONTAINER_TIMEOUTS = {
128
- // Time to get container instance and launch VM
129
- // @cloudflare/containers default: 8s (too short for cold starts)
130
- instanceGetTimeoutMS: 30_000, // 30 seconds
131
-
132
- // Time for application to start and ports to be ready
133
- // @cloudflare/containers default: 20s
134
- portReadyTimeoutMS: 90_000, // 90 seconds (allows for heavy containers)
135
-
136
- // Polling interval for checking container readiness
137
- // @cloudflare/containers default: 300ms (too aggressive)
138
- waitIntervalMS: 1000 // 1 second (reduces load)
139
- };
140
-
141
- /**
142
- * Active container timeout configuration
143
- * Can be set via options, env vars, or defaults
144
- */
145
- private containerTimeouts = { ...this.DEFAULT_CONTAINER_TIMEOUTS };
146
-
147
- constructor(ctx: DurableObjectState<{}>, env: Env) {
148
- super(ctx, env);
149
-
150
- const envObj = env as Record<string, unknown>;
151
- // Set sandbox environment variables from env object
152
- const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;
153
- sandboxEnvKeys.forEach((key) => {
154
- if (envObj?.[key]) {
155
- this.envVars[key] = String(envObj[key]);
156
- }
157
- });
158
-
159
- // Initialize timeouts with env var fallbacks
160
- this.containerTimeouts = this.getDefaultTimeouts(envObj);
161
-
162
- this.logger = createLogger({
163
- component: 'sandbox-do',
164
- sandboxId: this.ctx.id.toString()
165
- });
166
-
167
- this.client = new SandboxClient({
168
- logger: this.logger,
169
- port: 3000, // Control plane port
170
- stub: this
171
- });
172
-
173
- // Initialize code interpreter - pass 'this' after client is ready
174
- // The CodeInterpreter extracts client.interpreter from the sandbox
175
- this.codeInterpreter = new CodeInterpreter(this);
176
-
177
- this.ctx.blockConcurrencyWhile(async () => {
178
- this.sandboxName =
179
- (await this.ctx.storage.get<string>('sandboxName')) || null;
180
- this.normalizeId =
181
- (await this.ctx.storage.get<boolean>('normalizeId')) || false;
182
- this.defaultSession =
183
- (await this.ctx.storage.get<string>('defaultSession')) || null;
184
- const storedTokens =
185
- (await this.ctx.storage.get<Record<string, string>>('portTokens')) ||
186
- {};
187
-
188
- // Convert stored tokens back to Map
189
- this.portTokens = new Map();
190
- for (const [portStr, token] of Object.entries(storedTokens)) {
191
- this.portTokens.set(parseInt(portStr, 10), token);
192
- }
193
-
194
- // Load saved timeout configuration (highest priority)
195
- const storedTimeouts =
196
- await this.ctx.storage.get<
197
- NonNullable<SandboxOptions['containerTimeouts']>
198
- >('containerTimeouts');
199
- if (storedTimeouts) {
200
- this.containerTimeouts = {
201
- ...this.containerTimeouts,
202
- ...storedTimeouts
203
- };
204
- }
205
- });
206
- }
207
-
208
- async setSandboxName(name: string, normalizeId?: boolean): Promise<void> {
209
- if (!this.sandboxName) {
210
- this.sandboxName = name;
211
- this.normalizeId = normalizeId || false;
212
- await this.ctx.storage.put('sandboxName', name);
213
- await this.ctx.storage.put('normalizeId', this.normalizeId);
214
- }
215
- }
216
-
217
- // RPC method to set the base URL
218
- async setBaseUrl(baseUrl: string): Promise<void> {
219
- if (!this.baseUrl) {
220
- this.baseUrl = baseUrl;
221
- await this.ctx.storage.put('baseUrl', baseUrl);
222
- } else {
223
- if (this.baseUrl !== baseUrl) {
224
- throw new Error(
225
- 'Base URL already set and different from one previously provided'
226
- );
227
- }
228
- }
229
- }
230
-
231
- // RPC method to set the sleep timeout
232
- async setSleepAfter(sleepAfter: string | number): Promise<void> {
233
- this.sleepAfter = sleepAfter;
234
- }
235
-
236
- // RPC method to enable keepAlive mode
237
- async setKeepAlive(keepAlive: boolean): Promise<void> {
238
- this.keepAliveEnabled = keepAlive;
239
- if (keepAlive) {
240
- this.logger.info(
241
- 'KeepAlive mode enabled - container will stay alive until explicitly destroyed'
242
- );
243
- } else {
244
- this.logger.info(
245
- 'KeepAlive mode disabled - container will timeout normally'
246
- );
247
- }
248
- }
249
-
250
- // RPC method to set environment variables
251
- async setEnvVars(envVars: Record<string, string>): Promise<void> {
252
- // Update local state for new sessions
253
- this.envVars = { ...this.envVars, ...envVars };
254
-
255
- // If default session already exists, update it directly
256
- if (this.defaultSession) {
257
- // Set environment variables by executing export commands in the existing session
258
- for (const [key, value] of Object.entries(envVars)) {
259
- const escapedValue = value.replace(/'/g, "'\\''");
260
- const exportCommand = `export ${key}='${escapedValue}'`;
261
-
262
- const result = await this.client.commands.execute(
263
- exportCommand,
264
- this.defaultSession
265
- );
266
-
267
- if (result.exitCode !== 0) {
268
- throw new Error(
269
- `Failed to set ${key}: ${result.stderr || 'Unknown error'}`
270
- );
271
- }
272
- }
273
- }
274
- }
275
-
276
- /**
277
- * RPC method to configure container startup timeouts
278
- */
279
- async setContainerTimeouts(
280
- timeouts: NonNullable<SandboxOptions['containerTimeouts']>
281
- ): Promise<void> {
282
- const validated = { ...this.containerTimeouts };
283
-
284
- // Validate each timeout if provided
285
- if (timeouts.instanceGetTimeoutMS !== undefined) {
286
- validated.instanceGetTimeoutMS = this.validateTimeout(
287
- timeouts.instanceGetTimeoutMS,
288
- 'instanceGetTimeoutMS',
289
- 5_000,
290
- 300_000
291
- );
292
- }
293
-
294
- if (timeouts.portReadyTimeoutMS !== undefined) {
295
- validated.portReadyTimeoutMS = this.validateTimeout(
296
- timeouts.portReadyTimeoutMS,
297
- 'portReadyTimeoutMS',
298
- 10_000,
299
- 600_000
300
- );
301
- }
302
-
303
- if (timeouts.waitIntervalMS !== undefined) {
304
- validated.waitIntervalMS = this.validateTimeout(
305
- timeouts.waitIntervalMS,
306
- 'waitIntervalMS',
307
- 100,
308
- 5_000
309
- );
310
- }
311
-
312
- this.containerTimeouts = validated;
313
-
314
- // Persist to storage
315
- await this.ctx.storage.put('containerTimeouts', this.containerTimeouts);
316
-
317
- this.logger.debug('Container timeouts updated', this.containerTimeouts);
318
- }
319
-
320
- /**
321
- * Validate a timeout value is within acceptable range
322
- * Throws error if invalid - used for user-provided values
323
- */
324
- private validateTimeout(
325
- value: number,
326
- name: string,
327
- min: number,
328
- max: number
329
- ): number {
330
- if (
331
- typeof value !== 'number' ||
332
- Number.isNaN(value) ||
333
- !Number.isFinite(value)
334
- ) {
335
- throw new Error(`${name} must be a valid finite number, got ${value}`);
336
- }
337
-
338
- if (value < min || value > max) {
339
- throw new Error(
340
- `${name} must be between ${min}-${max}ms, got ${value}ms`
341
- );
342
- }
343
-
344
- return value;
345
- }
346
-
347
- /**
348
- * Get default timeouts with env var fallbacks and validation
349
- * Precedence: SDK defaults < Env vars < User config
350
- */
351
- private getDefaultTimeouts(
352
- env: Record<string, unknown>
353
- ): typeof this.DEFAULT_CONTAINER_TIMEOUTS {
354
- const parseAndValidate = (
355
- envVar: string | undefined,
356
- name: keyof typeof this.DEFAULT_CONTAINER_TIMEOUTS,
357
- min: number,
358
- max: number
359
- ): number => {
360
- const defaultValue = this.DEFAULT_CONTAINER_TIMEOUTS[name];
361
-
362
- if (envVar === undefined) {
363
- return defaultValue;
364
- }
365
-
366
- const parsed = parseInt(envVar, 10);
367
-
368
- if (Number.isNaN(parsed)) {
369
- this.logger.warn(
370
- `Invalid ${name}: "${envVar}" is not a number. Using default: ${defaultValue}ms`
371
- );
372
- return defaultValue;
373
- }
374
-
375
- if (parsed < min || parsed > max) {
376
- this.logger.warn(
377
- `Invalid ${name}: ${parsed}ms. Must be ${min}-${max}ms. Using default: ${defaultValue}ms`
378
- );
379
- return defaultValue;
380
- }
381
-
382
- return parsed;
383
- };
384
-
385
- return {
386
- instanceGetTimeoutMS: parseAndValidate(
387
- getEnvString(env, 'SANDBOX_INSTANCE_TIMEOUT_MS'),
388
- 'instanceGetTimeoutMS',
389
- 5_000, // Min 5s
390
- 300_000 // Max 5min
391
- ),
392
- portReadyTimeoutMS: parseAndValidate(
393
- getEnvString(env, 'SANDBOX_PORT_TIMEOUT_MS'),
394
- 'portReadyTimeoutMS',
395
- 10_000, // Min 10s
396
- 600_000 // Max 10min
397
- ),
398
- waitIntervalMS: parseAndValidate(
399
- getEnvString(env, 'SANDBOX_POLL_INTERVAL_MS'),
400
- 'waitIntervalMS',
401
- 100, // Min 100ms
402
- 5_000 // Max 5s
403
- )
404
- };
405
- }
406
-
407
- /*
408
- * Mount an S3-compatible bucket as a local directory using S3FS-FUSE
409
- *
410
- * Requires explicit endpoint URL. Credentials are auto-detected from environment
411
- * variables or can be provided explicitly.
412
- *
413
- * @param bucket - Bucket name
414
- * @param mountPath - Absolute path in container to mount at
415
- * @param options - Configuration options with required endpoint
416
- * @throws MissingCredentialsError if no credentials found in environment
417
- * @throws S3FSMountError if S3FS mount command fails
418
- * @throws InvalidMountConfigError if bucket name, mount path, or endpoint is invalid
419
- */
420
- async mountBucket(
421
- bucket: string,
422
- mountPath: string,
423
- options: MountBucketOptions
424
- ): Promise<void> {
425
- this.logger.info(`Mounting bucket ${bucket} to ${mountPath}`);
426
-
427
- // Validate options
428
- this.validateMountOptions(bucket, mountPath, options);
429
-
430
- // Detect provider from explicit option or URL pattern
431
- const provider: BucketProvider | null =
432
- options.provider || detectProviderFromUrl(options.endpoint);
433
-
434
- this.logger.debug(`Detected provider: ${provider || 'unknown'}`, {
435
- explicitProvider: options.provider
436
- });
437
-
438
- // Detect credentials
439
- const credentials = detectCredentials(options, this.envVars);
440
-
441
- // Generate unique password file path
442
- const passwordFilePath = this.generatePasswordFilePath();
443
-
444
- // Reserve mount path immediately to prevent race conditions
445
- // (two concurrent mount calls would both pass validation otherwise)
446
- this.activeMounts.set(mountPath, {
447
- bucket,
448
- mountPath,
449
- endpoint: options.endpoint,
450
- provider,
451
- passwordFilePath,
452
- mounted: false
453
- });
454
-
455
- try {
456
- // Create password file with credentials
457
- await this.createPasswordFile(passwordFilePath, bucket, credentials);
458
-
459
- // Create mount directory
460
- await this.exec(`mkdir -p ${shellEscape(mountPath)}`);
461
-
462
- // Execute S3FS mount with password file
463
- await this.executeS3FSMount(
464
- bucket,
465
- mountPath,
466
- options,
467
- provider,
468
- passwordFilePath
469
- );
470
-
471
- // Mark as successfully mounted
472
- this.activeMounts.set(mountPath, {
473
- bucket,
474
- mountPath,
475
- endpoint: options.endpoint,
476
- provider,
477
- passwordFilePath,
478
- mounted: true
479
- });
480
-
481
- this.logger.info(`Successfully mounted bucket ${bucket} to ${mountPath}`);
482
- } catch (error) {
483
- // Clean up password file on failure
484
- await this.deletePasswordFile(passwordFilePath);
485
-
486
- // Clean up reservation on failure
487
- this.activeMounts.delete(mountPath);
488
- throw error;
489
- }
490
- }
491
-
492
- /**
493
- * Manually unmount a bucket filesystem
494
- *
495
- * @param mountPath - Absolute path where the bucket is mounted
496
- * @throws InvalidMountConfigError if mount path doesn't exist or isn't mounted
497
- */
498
- async unmountBucket(mountPath: string): Promise<void> {
499
- this.logger.info(`Unmounting bucket from ${mountPath}`);
500
-
501
- // Look up mount by path
502
- const mountInfo = this.activeMounts.get(mountPath);
503
-
504
- // Throw error if mount doesn't exist
505
- if (!mountInfo) {
506
- throw new InvalidMountConfigError(
507
- `No active mount found at path: ${mountPath}`
508
- );
509
- }
510
-
511
- // Unmount the filesystem
512
- try {
513
- await this.exec(`fusermount -u ${shellEscape(mountPath)}`);
514
- mountInfo.mounted = false;
515
-
516
- // Only remove from tracking if unmount succeeded
517
- this.activeMounts.delete(mountPath);
518
- } finally {
519
- // Always cleanup password file, even if unmount fails
520
- await this.deletePasswordFile(mountInfo.passwordFilePath);
521
- }
522
-
523
- this.logger.info(`Successfully unmounted bucket from ${mountPath}`);
524
- }
525
-
526
- /**
527
- * Validate mount options
528
- */
529
- private validateMountOptions(
530
- bucket: string,
531
- mountPath: string,
532
- options: MountBucketOptions
533
- ): void {
534
- // Require endpoint field
535
- if (!options.endpoint) {
536
- throw new InvalidMountConfigError(
537
- 'Endpoint is required. Provide the full S3-compatible endpoint URL.'
538
- );
539
- }
540
-
541
- // Basic URL validation
542
- try {
543
- new URL(options.endpoint);
544
- } catch (error) {
545
- throw new InvalidMountConfigError(
546
- `Invalid endpoint URL: "${options.endpoint}". Must be a valid HTTP(S) URL.`
547
- );
548
- }
549
-
550
- // Validate bucket name (S3-compatible naming rules)
551
- const bucketNameRegex = /^[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?$/;
552
- if (!bucketNameRegex.test(bucket)) {
553
- throw new InvalidMountConfigError(
554
- `Invalid bucket name: "${bucket}". Bucket names must be 3-63 characters, ` +
555
- `lowercase alphanumeric, dots, or hyphens, and cannot start/end with dots or hyphens.`
556
- );
557
- }
558
-
559
- // Validate mount path is absolute
560
- if (!mountPath.startsWith('/')) {
561
- throw new InvalidMountConfigError(
562
- `Mount path must be absolute (start with /): "${mountPath}"`
563
- );
564
- }
565
-
566
- // Check for duplicate mount path
567
- if (this.activeMounts.has(mountPath)) {
568
- const existingMount = this.activeMounts.get(mountPath);
569
- throw new InvalidMountConfigError(
570
- `Mount path "${mountPath}" is already in use by bucket "${existingMount?.bucket}". ` +
571
- `Unmount the existing bucket first or use a different mount path.`
572
- );
573
- }
574
- }
575
-
576
- /**
577
- * Generate unique password file path for s3fs credentials
578
- */
579
- private generatePasswordFilePath(): string {
580
- const uuid = crypto.randomUUID();
581
- return `/tmp/.passwd-s3fs-${uuid}`;
582
- }
583
-
584
- /**
585
- * Create password file with s3fs credentials
586
- * Format: bucket:accessKeyId:secretAccessKey
587
- */
588
- private async createPasswordFile(
589
- passwordFilePath: string,
590
- bucket: string,
591
- credentials: BucketCredentials
592
- ): Promise<void> {
593
- const content = `${bucket}:${credentials.accessKeyId}:${credentials.secretAccessKey}`;
594
-
595
- await this.writeFile(passwordFilePath, content);
596
-
597
- await this.exec(`chmod 0600 ${shellEscape(passwordFilePath)}`);
598
-
599
- this.logger.debug(`Created password file: ${passwordFilePath}`);
600
- }
601
-
602
- /**
603
- * Delete password file
604
- */
605
- private async deletePasswordFile(passwordFilePath: string): Promise<void> {
606
- try {
607
- await this.exec(`rm -f ${shellEscape(passwordFilePath)}`);
608
- this.logger.debug(`Deleted password file: ${passwordFilePath}`);
609
- } catch (error) {
610
- this.logger.warn(`Failed to delete password file ${passwordFilePath}`, {
611
- error: error instanceof Error ? error.message : String(error)
612
- });
613
- }
614
- }
615
-
616
- /**
617
- * Execute S3FS mount command
618
- */
619
- private async executeS3FSMount(
620
- bucket: string,
621
- mountPath: string,
622
- options: MountBucketOptions,
623
- provider: BucketProvider | null,
624
- passwordFilePath: string
625
- ): Promise<void> {
626
- // Resolve s3fs options (provider defaults + user overrides)
627
- const resolvedOptions = resolveS3fsOptions(provider, options.s3fsOptions);
628
-
629
- // Build s3fs mount command
630
- const s3fsArgs: string[] = [];
631
-
632
- // Add password file option FIRST
633
- s3fsArgs.push(`passwd_file=${passwordFilePath}`);
634
-
635
- // Add resolved provider-specific and user options
636
- s3fsArgs.push(...resolvedOptions);
637
-
638
- // Add read-only flag if requested
639
- if (options.readOnly) {
640
- s3fsArgs.push('ro');
641
- }
642
-
643
- // Add endpoint URL
644
- s3fsArgs.push(`url=${options.endpoint}`);
645
-
646
- // Build final command with escaped options
647
- const optionsStr = shellEscape(s3fsArgs.join(','));
648
- const mountCmd = `s3fs ${shellEscape(bucket)} ${shellEscape(mountPath)} -o ${optionsStr}`;
649
-
650
- this.logger.debug('Executing s3fs mount', {
651
- bucket,
652
- mountPath,
653
- provider,
654
- resolvedOptions
655
- });
656
-
657
- // Execute mount command
658
- const result = await this.exec(mountCmd);
659
-
660
- if (result.exitCode !== 0) {
661
- throw new S3FSMountError(
662
- `S3FS mount failed: ${result.stderr || result.stdout || 'Unknown error'}`
663
- );
664
- }
665
-
666
- this.logger.debug('Mount command executed successfully');
667
- }
668
-
669
- /**
670
- * Cleanup and destroy the sandbox container
671
- */
672
- override async destroy(): Promise<void> {
673
- this.logger.info('Destroying sandbox container');
674
-
675
- // Unmount all mounted buckets and cleanup password files
676
- for (const [mountPath, mountInfo] of this.activeMounts.entries()) {
677
- if (mountInfo.mounted) {
678
- try {
679
- this.logger.info(
680
- `Unmounting bucket ${mountInfo.bucket} from ${mountPath}`
681
- );
682
- await this.exec(`fusermount -u ${shellEscape(mountPath)}`);
683
- mountInfo.mounted = false;
684
- } catch (error) {
685
- const errorMsg =
686
- error instanceof Error ? error.message : String(error);
687
- this.logger.warn(
688
- `Failed to unmount bucket ${mountInfo.bucket} from ${mountPath}: ${errorMsg}`
689
- );
690
- }
691
- }
692
-
693
- // Always cleanup password file
694
- await this.deletePasswordFile(mountInfo.passwordFilePath);
695
- }
696
-
697
- await super.destroy();
698
- }
699
-
700
- override onStart() {
701
- this.logger.debug('Sandbox started');
702
-
703
- // Check version compatibility asynchronously (don't block startup)
704
- this.checkVersionCompatibility().catch((error) => {
705
- this.logger.error(
706
- 'Version compatibility check failed',
707
- error instanceof Error ? error : new Error(String(error))
708
- );
709
- });
710
- }
711
-
712
- /**
713
- * Check if the container version matches the SDK version
714
- * Logs a warning if there's a mismatch
715
- */
716
- private async checkVersionCompatibility(): Promise<void> {
717
- try {
718
- // Get the SDK version (imported from version.ts)
719
- const sdkVersion = SDK_VERSION;
720
-
721
- // Get container version
722
- const containerVersion = await this.client.utils.getVersion();
723
-
724
- // If container version is unknown, it's likely an old container without the endpoint
725
- if (containerVersion === 'unknown') {
726
- this.logger.warn(
727
- 'Container version check: Container version could not be determined. ' +
728
- 'This may indicate an outdated container image. ' +
729
- 'Please update your container to match SDK version ' +
730
- sdkVersion
731
- );
732
- return;
733
- }
734
-
735
- // Check if versions match
736
- if (containerVersion !== sdkVersion) {
737
- const message =
738
- `Version mismatch detected! SDK version (${sdkVersion}) does not match ` +
739
- `container version (${containerVersion}). This may cause compatibility issues. ` +
740
- `Please update your container image to version ${sdkVersion}`;
741
-
742
- // Log warning - we can't reliably detect dev vs prod environment in Durable Objects
743
- // so we always use warning level as requested by the user
744
- this.logger.warn(message);
745
- } else {
746
- this.logger.debug('Version check passed', {
747
- sdkVersion,
748
- containerVersion
749
- });
750
- }
751
- } catch (error) {
752
- // Don't fail the sandbox initialization if version check fails
753
- this.logger.debug('Version compatibility check encountered an error', {
754
- error: error instanceof Error ? error.message : String(error)
755
- });
756
- }
757
- }
758
-
759
- override async onStop() {
760
- this.logger.debug('Sandbox stopped');
761
-
762
- // Clear in-memory state that references the old container
763
- // This prevents stale references after container restarts
764
- this.portTokens.clear();
765
- this.defaultSession = null;
766
- this.activeMounts.clear();
767
-
768
- // Persist cleanup to storage so state is clean on next container start
769
- await Promise.all([
770
- this.ctx.storage.delete('portTokens'),
771
- this.ctx.storage.delete('defaultSession')
772
- ]);
773
- }
774
-
775
- override onError(error: unknown) {
776
- this.logger.error(
777
- 'Sandbox error',
778
- error instanceof Error ? error : new Error(String(error))
779
- );
780
- }
781
-
782
- /**
783
- * Override Container.containerFetch to use production-friendly timeouts
784
- * Automatically starts container with longer timeouts if not running
785
- */
786
- override async containerFetch(
787
- requestOrUrl: Request | string | URL,
788
- portOrInit?: number | RequestInit,
789
- portParam?: number
790
- ): Promise<Response> {
791
- // Parse arguments to extract request and port
792
- const { request, port } = this.parseContainerFetchArgs(
793
- requestOrUrl,
794
- portOrInit,
795
- portParam
796
- );
797
-
798
- const state = await this.getState();
799
-
800
- // If container not healthy, start it with production timeouts
801
- if (state.status !== 'healthy') {
802
- try {
803
- this.logger.debug('Starting container with configured timeouts', {
804
- instanceTimeout: this.containerTimeouts.instanceGetTimeoutMS,
805
- portTimeout: this.containerTimeouts.portReadyTimeoutMS
806
- });
807
-
808
- await this.startAndWaitForPorts({
809
- ports: port,
810
- cancellationOptions: {
811
- instanceGetTimeoutMS: this.containerTimeouts.instanceGetTimeoutMS,
812
- portReadyTimeoutMS: this.containerTimeouts.portReadyTimeoutMS,
813
- waitInterval: this.containerTimeouts.waitIntervalMS,
814
- abort: request.signal
815
- }
816
- });
817
- } catch (e) {
818
- // Handle provisioning vs startup errors
819
- if (this.isNoInstanceError(e)) {
820
- return new Response(
821
- 'Container is currently provisioning. This can take several minutes on first deployment. Please retry in a moment.',
822
- {
823
- status: 503,
824
- headers: { 'Retry-After': '10' } // Suggest 10s retry
825
- }
826
- );
827
- }
828
-
829
- // Other startup errors
830
- this.logger.error(
831
- 'Container startup failed',
832
- e instanceof Error ? e : new Error(String(e))
833
- );
834
- return new Response(
835
- `Failed to start container: ${e instanceof Error ? e.message : String(e)}`,
836
- { status: 500 }
837
- );
838
- }
839
- }
840
-
841
- // Delegate to parent for the actual fetch (handles TCP port access internally)
842
- return await super.containerFetch(requestOrUrl, portOrInit, portParam);
843
- }
844
-
845
- /**
846
- * Helper: Check if error is "no container instance available"
847
- */
848
- private isNoInstanceError(error: unknown): boolean {
849
- return (
850
- error instanceof Error &&
851
- error.message.toLowerCase().includes('no container instance')
852
- );
853
- }
854
-
855
- /**
856
- * Helper: Parse containerFetch arguments (supports multiple signatures)
857
- */
858
- private parseContainerFetchArgs(
859
- requestOrUrl: Request | string | URL,
860
- portOrInit?: number | RequestInit,
861
- portParam?: number
862
- ): { request: Request; port: number } {
863
- let request: Request;
864
- let port: number | undefined;
865
-
866
- if (requestOrUrl instanceof Request) {
867
- request = requestOrUrl;
868
- port = typeof portOrInit === 'number' ? portOrInit : undefined;
869
- } else {
870
- const url =
871
- typeof requestOrUrl === 'string'
872
- ? requestOrUrl
873
- : requestOrUrl.toString();
874
- const init = typeof portOrInit === 'number' ? {} : portOrInit || {};
875
- port =
876
- typeof portOrInit === 'number'
877
- ? portOrInit
878
- : typeof portParam === 'number'
879
- ? portParam
880
- : undefined;
881
- request = new Request(url, init);
882
- }
883
-
884
- port ??= this.defaultPort;
885
-
886
- if (port === undefined) {
887
- throw new Error('No port specified for container fetch');
888
- }
889
-
890
- return { request, port };
891
- }
892
-
893
- /**
894
- * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled
895
- * When keepAlive is disabled, calls parent implementation which stops the container
896
- */
897
- override async onActivityExpired(): Promise<void> {
898
- if (this.keepAliveEnabled) {
899
- this.logger.debug(
900
- 'Activity expired but keepAlive is enabled - container will stay alive'
901
- );
902
- // Do nothing - don't call stop(), container stays alive
903
- } else {
904
- // Default behavior: stop the container
905
- this.logger.debug('Activity expired - stopping container');
906
- await super.onActivityExpired();
907
- }
908
- }
909
-
910
- // Override fetch to route internal container requests to appropriate ports
911
- override async fetch(request: Request): Promise<Response> {
912
- // Extract or generate trace ID from request
913
- const traceId =
914
- TraceContext.fromHeaders(request.headers) || TraceContext.generate();
915
-
916
- // Create request-specific logger with trace ID
917
- const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
918
-
919
- const url = new URL(request.url);
920
-
921
- // Capture and store the sandbox name from the header if present
922
- if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
923
- const name = request.headers.get('X-Sandbox-Name')!;
924
- this.sandboxName = name;
925
- await this.ctx.storage.put('sandboxName', name);
926
- }
927
-
928
- // Detect WebSocket upgrade request (RFC 6455 compliant)
929
- const upgradeHeader = request.headers.get('Upgrade');
930
- const connectionHeader = request.headers.get('Connection');
931
- const isWebSocket =
932
- upgradeHeader?.toLowerCase() === 'websocket' &&
933
- connectionHeader?.toLowerCase().includes('upgrade');
934
-
935
- if (isWebSocket) {
936
- // WebSocket path: Let parent Container class handle WebSocket proxying
937
- // This bypasses containerFetch() which uses JSRPC and cannot handle WebSocket upgrades
938
- try {
939
- requestLogger.debug('WebSocket upgrade requested', {
940
- path: url.pathname,
941
- port: this.determinePort(url)
942
- });
943
- return await super.fetch(request);
944
- } catch (error) {
945
- requestLogger.error(
946
- 'WebSocket connection failed',
947
- error instanceof Error ? error : new Error(String(error)),
948
- { path: url.pathname }
949
- );
950
- throw error;
951
- }
952
- }
953
-
954
- // Non-WebSocket: Use existing port determination and HTTP routing logic
955
- const port = this.determinePort(url);
956
-
957
- // Route to the appropriate port
958
- return await this.containerFetch(request, port);
959
- }
960
-
961
- wsConnect(request: Request, port: number): Promise<Response> {
962
- // Dummy implementation that will be overridden by the stub
963
- throw new Error('Not implemented here to avoid RPC serialization issues');
964
- }
965
-
966
- private determinePort(url: URL): number {
967
- // Extract port from proxy requests (e.g., /proxy/8080/*)
968
- const proxyMatch = url.pathname.match(/^\/proxy\/(\d+)/);
969
- if (proxyMatch) {
970
- return parseInt(proxyMatch[1], 10);
971
- }
972
-
973
- // All other requests go to control plane on port 3000
974
- // This includes /api/* endpoints and any other control requests
975
- return 3000;
976
- }
977
-
978
- /**
979
- * Ensure default session exists - lazy initialization
980
- * This is called automatically by all public methods that need a session
981
- *
982
- * The session is persisted to Durable Object storage to survive hot reloads
983
- * during development. If a session already exists in the container after reload,
984
- * we reuse it instead of trying to create a new one.
985
- */
986
- private async ensureDefaultSession(): Promise<string> {
987
- if (!this.defaultSession) {
988
- const sessionId = `sandbox-${this.sandboxName || 'default'}`;
989
-
990
- try {
991
- // Try to create session in container
992
- await this.client.utils.createSession({
993
- id: sessionId,
994
- env: this.envVars || {},
995
- cwd: '/workspace'
996
- });
997
-
998
- this.defaultSession = sessionId;
999
- // Persist to storage so it survives hot reloads
1000
- await this.ctx.storage.put('defaultSession', sessionId);
1001
- this.logger.debug('Default session initialized', { sessionId });
1002
- } catch (error: unknown) {
1003
- // If session already exists (e.g., after hot reload), reuse it
1004
- if (
1005
- error instanceof Error &&
1006
- error.message.includes('already exists')
1007
- ) {
1008
- this.logger.debug('Reusing existing session after reload', {
1009
- sessionId
1010
- });
1011
- this.defaultSession = sessionId;
1012
- // Persist to storage in case it wasn't saved before
1013
- await this.ctx.storage.put('defaultSession', sessionId);
1014
- } else {
1015
- // Re-throw other errors
1016
- throw error;
1017
- }
1018
- }
1019
- }
1020
- return this.defaultSession;
1021
- }
1022
-
1023
- // Enhanced exec method - always returns ExecResult with optional streaming
1024
- // This replaces the old exec method to match ISandbox interface
1025
- async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
1026
- const session = await this.ensureDefaultSession();
1027
- return this.execWithSession(command, session, options);
1028
- }
1029
-
1030
- /**
1031
- * Internal session-aware exec implementation
1032
- * Used by both public exec() and session wrappers
1033
- */
1034
- private async execWithSession(
1035
- command: string,
1036
- sessionId: string,
1037
- options?: ExecOptions
1038
- ): Promise<ExecResult> {
1039
- const startTime = Date.now();
1040
- const timestamp = new Date().toISOString();
1041
-
1042
- let timeoutId: NodeJS.Timeout | undefined;
1043
-
1044
- try {
1045
- // Handle cancellation
1046
- if (options?.signal?.aborted) {
1047
- throw new Error('Operation was aborted');
1048
- }
1049
-
1050
- let result: ExecResult;
1051
-
1052
- if (options?.stream && options?.onOutput) {
1053
- // Streaming with callbacks - we need to collect the final result
1054
- result = await this.executeWithStreaming(
1055
- command,
1056
- sessionId,
1057
- options,
1058
- startTime,
1059
- timestamp
1060
- );
1061
- } else {
1062
- // Regular execution with session
1063
- const commandOptions =
1064
- options &&
1065
- (options.timeout !== undefined ||
1066
- options.env !== undefined ||
1067
- options.cwd !== undefined)
1068
- ? {
1069
- timeoutMs: options.timeout,
1070
- env: options.env,
1071
- cwd: options.cwd
1072
- }
1073
- : undefined;
1074
-
1075
- const response = await this.client.commands.execute(
1076
- command,
1077
- sessionId,
1078
- commandOptions
1079
- );
1080
-
1081
- const duration = Date.now() - startTime;
1082
- result = this.mapExecuteResponseToExecResult(
1083
- response,
1084
- duration,
1085
- sessionId
1086
- );
1087
- }
1088
-
1089
- // Call completion callback if provided
1090
- if (options?.onComplete) {
1091
- options.onComplete(result);
1092
- }
1093
-
1094
- return result;
1095
- } catch (error) {
1096
- if (options?.onError && error instanceof Error) {
1097
- options.onError(error);
1098
- }
1099
- throw error;
1100
- } finally {
1101
- if (timeoutId) {
1102
- clearTimeout(timeoutId);
1103
- }
1104
- }
1105
- }
1106
-
1107
- private async executeWithStreaming(
1108
- command: string,
1109
- sessionId: string,
1110
- options: ExecOptions,
1111
- startTime: number,
1112
- timestamp: string
1113
- ): Promise<ExecResult> {
1114
- let stdout = '';
1115
- let stderr = '';
1116
-
1117
- try {
1118
- const stream = await this.client.commands.executeStream(
1119
- command,
1120
- sessionId,
1121
- {
1122
- timeoutMs: options.timeout,
1123
- env: options.env,
1124
- cwd: options.cwd
1125
- }
1126
- );
1127
-
1128
- for await (const event of parseSSEStream<ExecEvent>(stream)) {
1129
- // Check for cancellation
1130
- if (options.signal?.aborted) {
1131
- throw new Error('Operation was aborted');
1132
- }
1133
-
1134
- switch (event.type) {
1135
- case 'stdout':
1136
- case 'stderr':
1137
- if (event.data) {
1138
- // Update accumulated output
1139
- if (event.type === 'stdout') stdout += event.data;
1140
- if (event.type === 'stderr') stderr += event.data;
1141
-
1142
- // Call user's callback
1143
- if (options.onOutput) {
1144
- options.onOutput(event.type, event.data);
1145
- }
1146
- }
1147
- break;
1148
-
1149
- case 'complete': {
1150
- // Use result from complete event if available
1151
- const duration = Date.now() - startTime;
1152
- return {
1153
- success: (event.exitCode ?? 0) === 0,
1154
- exitCode: event.exitCode ?? 0,
1155
- stdout,
1156
- stderr,
1157
- command,
1158
- duration,
1159
- timestamp,
1160
- sessionId
1161
- };
1162
- }
1163
-
1164
- case 'error':
1165
- throw new Error(event.data || 'Command execution failed');
1166
- }
1167
- }
1168
-
1169
- // If we get here without a complete event, something went wrong
1170
- throw new Error('Stream ended without completion event');
1171
- } catch (error) {
1172
- if (options.signal?.aborted) {
1173
- throw new Error('Operation was aborted');
1174
- }
1175
- throw error;
1176
- }
1177
- }
1178
-
1179
- private mapExecuteResponseToExecResult(
1180
- response: ExecuteResponse,
1181
- duration: number,
1182
- sessionId?: string
1183
- ): ExecResult {
1184
- return {
1185
- success: response.success,
1186
- exitCode: response.exitCode,
1187
- stdout: response.stdout,
1188
- stderr: response.stderr,
1189
- command: response.command,
1190
- duration,
1191
- timestamp: response.timestamp,
1192
- sessionId
1193
- };
1194
- }
1195
-
1196
- /**
1197
- * Create a Process domain object from HTTP client DTO
1198
- * Centralizes process object creation with bound methods
1199
- * This eliminates duplication across startProcess, listProcesses, getProcess, and session wrappers
1200
- */
1201
- private createProcessFromDTO(
1202
- data: {
1203
- id: string;
1204
- pid?: number;
1205
- command: string;
1206
- status: ProcessStatus;
1207
- startTime: string | Date;
1208
- endTime?: string | Date;
1209
- exitCode?: number;
1210
- },
1211
- sessionId: string
1212
- ): Process {
1213
- return {
1214
- id: data.id,
1215
- pid: data.pid,
1216
- command: data.command,
1217
- status: data.status,
1218
- startTime:
1219
- typeof data.startTime === 'string'
1220
- ? new Date(data.startTime)
1221
- : data.startTime,
1222
- endTime: data.endTime
1223
- ? typeof data.endTime === 'string'
1224
- ? new Date(data.endTime)
1225
- : data.endTime
1226
- : undefined,
1227
- exitCode: data.exitCode,
1228
- sessionId,
1229
-
1230
- kill: async (signal?: string) => {
1231
- await this.killProcess(data.id, signal);
1232
- },
1233
-
1234
- getStatus: async () => {
1235
- const current = await this.getProcess(data.id);
1236
- return current?.status || 'error';
1237
- },
1238
-
1239
- getLogs: async () => {
1240
- const logs = await this.getProcessLogs(data.id);
1241
- return { stdout: logs.stdout, stderr: logs.stderr };
1242
- }
1243
- };
1244
- }
1245
-
1246
- // Background process management
1247
- async startProcess(
1248
- command: string,
1249
- options?: ProcessOptions,
1250
- sessionId?: string
1251
- ): Promise<Process> {
1252
- // Use the new HttpClient method to start the process
1253
- try {
1254
- const session = sessionId ?? (await this.ensureDefaultSession());
1255
- const requestOptions = {
1256
- ...(options?.processId !== undefined && {
1257
- processId: options.processId
1258
- }),
1259
- ...(options?.timeout !== undefined && { timeoutMs: options.timeout }),
1260
- ...(options?.env !== undefined && { env: options.env }),
1261
- ...(options?.cwd !== undefined && { cwd: options.cwd }),
1262
- ...(options?.encoding !== undefined && { encoding: options.encoding }),
1263
- ...(options?.autoCleanup !== undefined && {
1264
- autoCleanup: options.autoCleanup
1265
- })
1266
- };
1267
-
1268
- const response = await this.client.processes.startProcess(
1269
- command,
1270
- session,
1271
- requestOptions
1272
- );
1273
-
1274
- const processObj = this.createProcessFromDTO(
1275
- {
1276
- id: response.processId,
1277
- pid: response.pid,
1278
- command: response.command,
1279
- status: 'running' as ProcessStatus,
1280
- startTime: new Date(),
1281
- endTime: undefined,
1282
- exitCode: undefined
1283
- },
1284
- session
1285
- );
1286
-
1287
- // Call onStart callback if provided
1288
- if (options?.onStart) {
1289
- options.onStart(processObj);
1290
- }
1291
-
1292
- return processObj;
1293
- } catch (error) {
1294
- if (options?.onError && error instanceof Error) {
1295
- options.onError(error);
1296
- }
1297
-
1298
- throw error;
1299
- }
1300
- }
1301
-
1302
- async listProcesses(sessionId?: string): Promise<Process[]> {
1303
- const session = sessionId ?? (await this.ensureDefaultSession());
1304
- const response = await this.client.processes.listProcesses();
1305
-
1306
- return response.processes.map((processData) =>
1307
- this.createProcessFromDTO(
1308
- {
1309
- id: processData.id,
1310
- pid: processData.pid,
1311
- command: processData.command,
1312
- status: processData.status,
1313
- startTime: processData.startTime,
1314
- endTime: processData.endTime,
1315
- exitCode: processData.exitCode
1316
- },
1317
- session
1318
- )
1319
- );
1320
- }
1321
-
1322
- async getProcess(id: string, sessionId?: string): Promise<Process | null> {
1323
- const session = sessionId ?? (await this.ensureDefaultSession());
1324
- const response = await this.client.processes.getProcess(id);
1325
- if (!response.process) {
1326
- return null;
1327
- }
1328
-
1329
- const processData = response.process;
1330
- return this.createProcessFromDTO(
1331
- {
1332
- id: processData.id,
1333
- pid: processData.pid,
1334
- command: processData.command,
1335
- status: processData.status,
1336
- startTime: processData.startTime,
1337
- endTime: processData.endTime,
1338
- exitCode: processData.exitCode
1339
- },
1340
- session
1341
- );
1342
- }
1343
-
1344
- async killProcess(
1345
- id: string,
1346
- signal?: string,
1347
- sessionId?: string
1348
- ): Promise<void> {
1349
- // Note: signal parameter is not currently supported by the HttpClient implementation
1350
- // The HTTP client already throws properly typed errors, so we just let them propagate
1351
- await this.client.processes.killProcess(id);
1352
- }
1353
-
1354
- async killAllProcesses(sessionId?: string): Promise<number> {
1355
- const response = await this.client.processes.killAllProcesses();
1356
- return response.cleanedCount;
1357
- }
1358
-
1359
- async cleanupCompletedProcesses(sessionId?: string): Promise<number> {
1360
- // For now, this would need to be implemented as a container endpoint
1361
- // as we no longer maintain local process storage
1362
- // We'll return 0 as a placeholder until the container endpoint is added
1363
- return 0;
1364
- }
1365
-
1366
- async getProcessLogs(
1367
- id: string,
1368
- sessionId?: string
1369
- ): Promise<{ stdout: string; stderr: string; processId: string }> {
1370
- // The HTTP client already throws properly typed errors, so we just let them propagate
1371
- const response = await this.client.processes.getProcessLogs(id);
1372
- return {
1373
- stdout: response.stdout,
1374
- stderr: response.stderr,
1375
- processId: response.processId
1376
- };
1377
- }
1378
-
1379
- // Streaming methods - return ReadableStream for RPC compatibility
1380
- async execStream(
1381
- command: string,
1382
- options?: StreamOptions
1383
- ): Promise<ReadableStream<Uint8Array>> {
1384
- // Check for cancellation
1385
- if (options?.signal?.aborted) {
1386
- throw new Error('Operation was aborted');
1387
- }
1388
-
1389
- const session = await this.ensureDefaultSession();
1390
- // Get the stream from CommandClient
1391
- return this.client.commands.executeStream(command, session, {
1392
- timeoutMs: options?.timeout,
1393
- env: options?.env,
1394
- cwd: options?.cwd
1395
- });
1396
- }
1397
-
1398
- /**
1399
- * Internal session-aware execStream implementation
1400
- */
1401
- private async execStreamWithSession(
1402
- command: string,
1403
- sessionId: string,
1404
- options?: StreamOptions
1405
- ): Promise<ReadableStream<Uint8Array>> {
1406
- // Check for cancellation
1407
- if (options?.signal?.aborted) {
1408
- throw new Error('Operation was aborted');
1409
- }
1410
-
1411
- return this.client.commands.executeStream(command, sessionId, {
1412
- timeoutMs: options?.timeout,
1413
- env: options?.env,
1414
- cwd: options?.cwd
1415
- });
1416
- }
1417
-
1418
- /**
1419
- * Stream logs from a background process as a ReadableStream.
1420
- */
1421
- async streamProcessLogs(
1422
- processId: string,
1423
- options?: { signal?: AbortSignal }
1424
- ): Promise<ReadableStream<Uint8Array>> {
1425
- // Check for cancellation
1426
- if (options?.signal?.aborted) {
1427
- throw new Error('Operation was aborted');
1428
- }
1429
-
1430
- return this.client.processes.streamProcessLogs(processId);
1431
- }
1432
-
1433
- async gitCheckout(
1434
- repoUrl: string,
1435
- options: { branch?: string; targetDir?: string; sessionId?: string }
1436
- ) {
1437
- const session = options.sessionId ?? (await this.ensureDefaultSession());
1438
- return this.client.git.checkout(repoUrl, session, {
1439
- branch: options.branch,
1440
- targetDir: options.targetDir
1441
- });
1442
- }
1443
-
1444
- async mkdir(
1445
- path: string,
1446
- options: { recursive?: boolean; sessionId?: string } = {}
1447
- ) {
1448
- const session = options.sessionId ?? (await this.ensureDefaultSession());
1449
- return this.client.files.mkdir(path, session, {
1450
- recursive: options.recursive
1451
- });
1452
- }
1453
-
1454
- async writeFile(
1455
- path: string,
1456
- content: string,
1457
- options: { encoding?: string; sessionId?: string } = {}
1458
- ) {
1459
- const session = options.sessionId ?? (await this.ensureDefaultSession());
1460
- return this.client.files.writeFile(path, content, session, {
1461
- encoding: options.encoding
1462
- });
1463
- }
1464
-
1465
- async deleteFile(path: string, sessionId?: string) {
1466
- const session = sessionId ?? (await this.ensureDefaultSession());
1467
- return this.client.files.deleteFile(path, session);
1468
- }
1469
-
1470
- async renameFile(oldPath: string, newPath: string, sessionId?: string) {
1471
- const session = sessionId ?? (await this.ensureDefaultSession());
1472
- return this.client.files.renameFile(oldPath, newPath, session);
1473
- }
1474
-
1475
- async moveFile(
1476
- sourcePath: string,
1477
- destinationPath: string,
1478
- sessionId?: string
1479
- ) {
1480
- const session = sessionId ?? (await this.ensureDefaultSession());
1481
- return this.client.files.moveFile(sourcePath, destinationPath, session);
1482
- }
1483
-
1484
- async readFile(
1485
- path: string,
1486
- options: { encoding?: string; sessionId?: string } = {}
1487
- ) {
1488
- const session = options.sessionId ?? (await this.ensureDefaultSession());
1489
- return this.client.files.readFile(path, session, {
1490
- encoding: options.encoding
1491
- });
1492
- }
1493
-
1494
- /**
1495
- * Stream a file from the sandbox using Server-Sent Events
1496
- * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
1497
- * @param path - Path to the file to stream
1498
- * @param options - Optional session ID
1499
- */
1500
- async readFileStream(
1501
- path: string,
1502
- options: { sessionId?: string } = {}
1503
- ): Promise<ReadableStream<Uint8Array>> {
1504
- const session = options.sessionId ?? (await this.ensureDefaultSession());
1505
- return this.client.files.readFileStream(path, session);
1506
- }
1507
-
1508
- async listFiles(
1509
- path: string,
1510
- options?: { recursive?: boolean; includeHidden?: boolean }
1511
- ) {
1512
- const session = await this.ensureDefaultSession();
1513
- return this.client.files.listFiles(path, session, options);
1514
- }
1515
-
1516
- async exists(path: string, sessionId?: string) {
1517
- const session = sessionId ?? (await this.ensureDefaultSession());
1518
- return this.client.files.exists(path, session);
1519
- }
1520
-
1521
- async exposePort(port: number, options: { name?: string; hostname: string }) {
1522
- // Check if hostname is workers.dev domain (doesn't support wildcard subdomains)
1523
- if (options.hostname.endsWith('.workers.dev')) {
1524
- const errorResponse: ErrorResponse = {
1525
- code: ErrorCode.CUSTOM_DOMAIN_REQUIRED,
1526
- message: `Port exposure requires a custom domain. .workers.dev domains do not support wildcard subdomains required for port proxying.`,
1527
- context: { originalError: options.hostname },
1528
- httpStatus: 400,
1529
- timestamp: new Date().toISOString()
1530
- };
1531
- throw new CustomDomainRequiredError(errorResponse);
1532
- }
1533
-
1534
- const sessionId = await this.ensureDefaultSession();
1535
- await this.client.ports.exposePort(port, sessionId, options?.name);
1536
-
1537
- // We need the sandbox name to construct preview URLs
1538
- if (!this.sandboxName) {
1539
- throw new Error(
1540
- 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
1541
- );
1542
- }
1543
-
1544
- // Generate and store token for this port
1545
- const token = this.generatePortToken();
1546
- this.portTokens.set(port, token);
1547
- await this.persistPortTokens();
1548
-
1549
- const url = this.constructPreviewUrl(
1550
- port,
1551
- this.sandboxName,
1552
- options.hostname,
1553
- token
1554
- );
1555
-
1556
- return {
1557
- url,
1558
- port,
1559
- name: options?.name
1560
- };
1561
- }
1562
-
1563
- async unexposePort(port: number) {
1564
- if (!validatePort(port)) {
1565
- throw new SecurityError(
1566
- `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
1567
- );
1568
- }
1569
-
1570
- const sessionId = await this.ensureDefaultSession();
1571
- await this.client.ports.unexposePort(port, sessionId);
1572
-
1573
- // Clean up token for this port
1574
- if (this.portTokens.has(port)) {
1575
- this.portTokens.delete(port);
1576
- await this.persistPortTokens();
1577
- }
1578
- }
1579
-
1580
- async getExposedPorts(hostname: string) {
1581
- const sessionId = await this.ensureDefaultSession();
1582
- const response = await this.client.ports.getExposedPorts(sessionId);
1583
-
1584
- // We need the sandbox name to construct preview URLs
1585
- if (!this.sandboxName) {
1586
- throw new Error(
1587
- 'Sandbox name not available. Ensure sandbox is accessed through getSandbox()'
1588
- );
1589
- }
1590
-
1591
- return response.ports.map((port) => {
1592
- // Get token for this port - must exist for all exposed ports
1593
- const token = this.portTokens.get(port.port);
1594
- if (!token) {
1595
- throw new Error(
1596
- `Port ${port.port} is exposed but has no token. This should not happen.`
1597
- );
1598
- }
1599
-
1600
- return {
1601
- url: this.constructPreviewUrl(
1602
- port.port,
1603
- this.sandboxName!,
1604
- hostname,
1605
- token
1606
- ),
1607
- port: port.port,
1608
- status: port.status
1609
- };
1610
- });
1611
- }
1612
-
1613
- async isPortExposed(port: number): Promise<boolean> {
1614
- try {
1615
- const sessionId = await this.ensureDefaultSession();
1616
- const response = await this.client.ports.getExposedPorts(sessionId);
1617
- return response.ports.some((exposedPort) => exposedPort.port === port);
1618
- } catch (error) {
1619
- this.logger.error(
1620
- 'Error checking if port is exposed',
1621
- error instanceof Error ? error : new Error(String(error)),
1622
- { port }
1623
- );
1624
- return false;
1625
- }
1626
- }
1627
-
1628
- async validatePortToken(port: number, token: string): Promise<boolean> {
1629
- // First check if port is exposed
1630
- const isExposed = await this.isPortExposed(port);
1631
- if (!isExposed) {
1632
- return false;
1633
- }
1634
-
1635
- // Get stored token for this port - must exist for all exposed ports
1636
- const storedToken = this.portTokens.get(port);
1637
- if (!storedToken) {
1638
- // This should not happen - all exposed ports must have tokens
1639
- this.logger.error(
1640
- 'Port is exposed but has no token - bug detected',
1641
- undefined,
1642
- { port }
1643
- );
1644
- return false;
1645
- }
1646
-
1647
- // Constant-time comparison to prevent timing attacks
1648
- return storedToken === token;
1649
- }
1650
-
1651
- private generatePortToken(): string {
1652
- // Generate cryptographically secure 16-character token using Web Crypto API
1653
- // Available in Cloudflare Workers runtime
1654
- const array = new Uint8Array(12); // 12 bytes = 16 base64url chars (after padding removal)
1655
- crypto.getRandomValues(array);
1656
-
1657
- // Convert to base64url format (URL-safe, no padding, lowercase)
1658
- const base64 = btoa(String.fromCharCode(...array));
1659
- return base64
1660
- .replace(/\+/g, '-')
1661
- .replace(/\//g, '_')
1662
- .replace(/=/g, '')
1663
- .toLowerCase();
1664
- }
1665
-
1666
- private async persistPortTokens(): Promise<void> {
1667
- // Convert Map to plain object for storage
1668
- const tokensObj: Record<string, string> = {};
1669
- for (const [port, token] of this.portTokens.entries()) {
1670
- tokensObj[port.toString()] = token;
1671
- }
1672
- await this.ctx.storage.put('portTokens', tokensObj);
1673
- }
1674
-
1675
- private constructPreviewUrl(
1676
- port: number,
1677
- sandboxId: string,
1678
- hostname: string,
1679
- token: string
1680
- ): string {
1681
- if (!validatePort(port)) {
1682
- throw new SecurityError(
1683
- `Invalid port number: ${port}. Must be between 1024-65535 and not reserved.`
1684
- );
1685
- }
1686
-
1687
- // Hostnames are case-insensitive, routing requests to wrong DO instance when keys contain uppercase letters
1688
- const effectiveId = this.sandboxName || sandboxId;
1689
- const hasUppercase = /[A-Z]/.test(effectiveId);
1690
- if (!this.normalizeId && hasUppercase) {
1691
- throw new SecurityError(
1692
- `Preview URLs require lowercase sandbox IDs. Your ID "${effectiveId}" contains uppercase letters.\n\n` +
1693
- `To fix this:\n` +
1694
- `1. Create a new sandbox with: getSandbox(ns, "${effectiveId}", { normalizeId: true })\n` +
1695
- `2. This will create a sandbox with ID: "${effectiveId.toLowerCase()}"\n\n` +
1696
- `Note: Due to DNS case-insensitivity, IDs with uppercase letters cannot be used with preview URLs.`
1697
- );
1698
- }
1699
-
1700
- const sanitizedSandboxId = sanitizeSandboxId(sandboxId).toLowerCase();
1701
-
1702
- const isLocalhost = isLocalhostPattern(hostname);
1703
-
1704
- if (isLocalhost) {
1705
- const [host, portStr] = hostname.split(':');
1706
- const mainPort = portStr || '80';
1707
-
1708
- try {
1709
- const baseUrl = new URL(`http://${host}:${mainPort}`);
1710
- const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
1711
- baseUrl.hostname = subdomainHost;
1712
-
1713
- return baseUrl.toString();
1714
- } catch (error) {
1715
- throw new SecurityError(
1716
- `Failed to construct preview URL: ${
1717
- error instanceof Error ? error.message : 'Unknown error'
1718
- }`
1719
- );
1720
- }
1721
- }
1722
-
1723
- try {
1724
- const baseUrl = new URL(`https://${hostname}`);
1725
- const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
1726
- baseUrl.hostname = subdomainHost;
1727
-
1728
- return baseUrl.toString();
1729
- } catch (error) {
1730
- throw new SecurityError(
1731
- `Failed to construct preview URL: ${
1732
- error instanceof Error ? error.message : 'Unknown error'
1733
- }`
1734
- );
1735
- }
1736
- }
1737
-
1738
- // ============================================================================
1739
- // Session Management - Advanced Use Cases
1740
- // ============================================================================
1741
-
1742
- /**
1743
- * Create isolated execution session for advanced use cases
1744
- * Returns ExecutionSession with full sandbox API bound to specific session
1745
- */
1746
- async createSession(options?: SessionOptions): Promise<ExecutionSession> {
1747
- const sessionId = options?.id || `session-${Date.now()}`;
1748
-
1749
- const mergedEnv = {
1750
- ...this.envVars,
1751
- ...(options?.env ?? {})
1752
- };
1753
- const envPayload =
1754
- Object.keys(mergedEnv).length > 0 ? mergedEnv : undefined;
1755
-
1756
- // Create session in container
1757
- await this.client.utils.createSession({
1758
- id: sessionId,
1759
- ...(envPayload && { env: envPayload }),
1760
- ...(options?.cwd && { cwd: options.cwd })
1761
- });
1762
-
1763
- // Return wrapper that binds sessionId to all operations
1764
- return this.getSessionWrapper(sessionId);
1765
- }
1766
-
1767
- /**
1768
- * Get an existing session by ID
1769
- * Returns ExecutionSession wrapper bound to the specified session
1770
- *
1771
- * This is useful for retrieving sessions across different requests/contexts
1772
- * without storing the ExecutionSession object (which has RPC lifecycle limitations)
1773
- *
1774
- * @param sessionId - The ID of an existing session
1775
- * @returns ExecutionSession wrapper bound to the session
1776
- */
1777
- async getSession(sessionId: string): Promise<ExecutionSession> {
1778
- // No need to verify session exists in container - operations will fail naturally if it doesn't
1779
- return this.getSessionWrapper(sessionId);
1780
- }
1781
-
1782
- /**
1783
- * Delete an execution session
1784
- * Cleans up session resources and removes it from the container
1785
- * Note: Cannot delete the default session. To reset the default session,
1786
- * use sandbox.destroy() to terminate the entire sandbox.
1787
- *
1788
- * @param sessionId - The ID of the session to delete
1789
- * @returns Result with success status, sessionId, and timestamp
1790
- * @throws Error if attempting to delete the default session
1791
- */
1792
- async deleteSession(sessionId: string): Promise<SessionDeleteResult> {
1793
- // Prevent deletion of default session
1794
- if (this.defaultSession && sessionId === this.defaultSession) {
1795
- throw new Error(
1796
- `Cannot delete default session '${sessionId}'. Use sandbox.destroy() to terminate the sandbox.`
1797
- );
1798
- }
1799
-
1800
- const response = await this.client.utils.deleteSession(sessionId);
1801
-
1802
- // Map HTTP response to result type
1803
- return {
1804
- success: response.success,
1805
- sessionId: response.sessionId,
1806
- timestamp: response.timestamp
1807
- };
1808
- }
1809
-
1810
- /**
1811
- * Internal helper to create ExecutionSession wrapper for a given sessionId
1812
- * Used by both createSession and getSession
1813
- */
1814
- private getSessionWrapper(sessionId: string): ExecutionSession {
1815
- return {
1816
- id: sessionId,
1817
-
1818
- // Command execution - delegate to internal session-aware methods
1819
- exec: (command, options) =>
1820
- this.execWithSession(command, sessionId, options),
1821
- execStream: (command, options) =>
1822
- this.execStreamWithSession(command, sessionId, options),
1823
-
1824
- // Process management
1825
- startProcess: (command, options) =>
1826
- this.startProcess(command, options, sessionId),
1827
- listProcesses: () => this.listProcesses(sessionId),
1828
- getProcess: (id) => this.getProcess(id, sessionId),
1829
- killProcess: (id, signal) => this.killProcess(id, signal),
1830
- killAllProcesses: () => this.killAllProcesses(),
1831
- cleanupCompletedProcesses: () => this.cleanupCompletedProcesses(),
1832
- getProcessLogs: (id) => this.getProcessLogs(id),
1833
- streamProcessLogs: (processId, options) =>
1834
- this.streamProcessLogs(processId, options),
1835
-
1836
- // File operations - pass sessionId via options or parameter
1837
- writeFile: (path, content, options) =>
1838
- this.writeFile(path, content, { ...options, sessionId }),
1839
- readFile: (path, options) =>
1840
- this.readFile(path, { ...options, sessionId }),
1841
- readFileStream: (path) => this.readFileStream(path, { sessionId }),
1842
- mkdir: (path, options) => this.mkdir(path, { ...options, sessionId }),
1843
- deleteFile: (path) => this.deleteFile(path, sessionId),
1844
- renameFile: (oldPath, newPath) =>
1845
- this.renameFile(oldPath, newPath, sessionId),
1846
- moveFile: (sourcePath, destPath) =>
1847
- this.moveFile(sourcePath, destPath, sessionId),
1848
- listFiles: (path, options) =>
1849
- this.client.files.listFiles(path, sessionId, options),
1850
- exists: (path) => this.exists(path, sessionId),
1851
-
1852
- // Git operations
1853
- gitCheckout: (repoUrl, options) =>
1854
- this.gitCheckout(repoUrl, { ...options, sessionId }),
1855
-
1856
- // Environment management - needs special handling
1857
- setEnvVars: async (envVars: Record<string, string>) => {
1858
- try {
1859
- // Set environment variables by executing export commands
1860
- for (const [key, value] of Object.entries(envVars)) {
1861
- const escapedValue = value.replace(/'/g, "'\\''");
1862
- const exportCommand = `export ${key}='${escapedValue}'`;
1863
-
1864
- const result = await this.client.commands.execute(
1865
- exportCommand,
1866
- sessionId
1867
- );
1868
-
1869
- if (result.exitCode !== 0) {
1870
- throw new Error(
1871
- `Failed to set ${key}: ${result.stderr || 'Unknown error'}`
1872
- );
1873
- }
1874
- }
1875
- } catch (error) {
1876
- this.logger.error(
1877
- 'Failed to set environment variables',
1878
- error instanceof Error ? error : new Error(String(error)),
1879
- { sessionId }
1880
- );
1881
- throw error;
1882
- }
1883
- },
1884
-
1885
- // Code interpreter methods - delegate to sandbox's code interpreter
1886
- createCodeContext: (options) =>
1887
- this.codeInterpreter.createCodeContext(options),
1888
- runCode: async (code, options) => {
1889
- const execution = await this.codeInterpreter.runCode(code, options);
1890
- return execution.toJSON();
1891
- },
1892
- runCodeStream: (code, options) =>
1893
- this.codeInterpreter.runCodeStream(code, options),
1894
- listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
1895
- deleteCodeContext: (contextId) =>
1896
- this.codeInterpreter.deleteCodeContext(contextId),
1897
-
1898
- // Bucket mounting - sandbox-level operations
1899
- mountBucket: (bucket, mountPath, options) =>
1900
- this.mountBucket(bucket, mountPath, options),
1901
- unmountBucket: (mountPath) => this.unmountBucket(mountPath)
1902
- };
1903
- }
1904
-
1905
- // ============================================================================
1906
- // Code interpreter methods - delegate to CodeInterpreter wrapper
1907
- // ============================================================================
1908
-
1909
- async createCodeContext(
1910
- options?: CreateContextOptions
1911
- ): Promise<CodeContext> {
1912
- return this.codeInterpreter.createCodeContext(options);
1913
- }
1914
-
1915
- async runCode(
1916
- code: string,
1917
- options?: RunCodeOptions
1918
- ): Promise<ExecutionResult> {
1919
- const execution = await this.codeInterpreter.runCode(code, options);
1920
- return execution.toJSON();
1921
- }
1922
-
1923
- async runCodeStream(
1924
- code: string,
1925
- options?: RunCodeOptions
1926
- ): Promise<ReadableStream> {
1927
- return this.codeInterpreter.runCodeStream(code, options);
1928
- }
1929
-
1930
- async listCodeContexts(): Promise<CodeContext[]> {
1931
- return this.codeInterpreter.listCodeContexts();
1932
- }
1933
-
1934
- async deleteCodeContext(contextId: string): Promise<void> {
1935
- return this.codeInterpreter.deleteCodeContext(contextId);
1936
- }
1937
- }