@cloudflare/sandbox 0.4.18 → 0.5.2

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 (40) hide show
  1. package/.turbo/turbo-build.log +17 -9
  2. package/CHANGELOG.md +64 -0
  3. package/Dockerfile +5 -1
  4. package/LICENSE +176 -0
  5. package/README.md +1 -1
  6. package/dist/dist-gVyG2H2h.js +612 -0
  7. package/dist/dist-gVyG2H2h.js.map +1 -0
  8. package/dist/index.d.ts +94 -1834
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +489 -678
  11. package/dist/index.js.map +1 -1
  12. package/dist/openai/index.d.ts +67 -0
  13. package/dist/openai/index.d.ts.map +1 -0
  14. package/dist/openai/index.js +362 -0
  15. package/dist/openai/index.js.map +1 -0
  16. package/dist/sandbox-B3vJ541e.d.ts +1729 -0
  17. package/dist/sandbox-B3vJ541e.d.ts.map +1 -0
  18. package/package.json +16 -2
  19. package/src/clients/base-client.ts +107 -46
  20. package/src/index.ts +19 -2
  21. package/src/openai/index.ts +465 -0
  22. package/src/request-handler.ts +2 -1
  23. package/src/sandbox.ts +684 -62
  24. package/src/storage-mount/credential-detection.ts +41 -0
  25. package/src/storage-mount/errors.ts +51 -0
  26. package/src/storage-mount/index.ts +17 -0
  27. package/src/storage-mount/provider-detection.ts +93 -0
  28. package/src/storage-mount/types.ts +17 -0
  29. package/src/version.ts +1 -1
  30. package/tests/base-client.test.ts +218 -0
  31. package/tests/get-sandbox.test.ts +24 -1
  32. package/tests/git-client.test.ts +7 -39
  33. package/tests/openai-shell-editor.test.ts +434 -0
  34. package/tests/port-client.test.ts +25 -35
  35. package/tests/process-client.test.ts +73 -107
  36. package/tests/sandbox.test.ts +128 -1
  37. package/tests/storage-mount/credential-detection.test.ts +119 -0
  38. package/tests/storage-mount/provider-detection.test.ts +77 -0
  39. package/tsconfig.json +2 -2
  40. package/tsdown.config.ts +3 -2
package/src/sandbox.ts CHANGED
@@ -1,6 +1,7 @@
1
- import type { DurableObject } from 'cloudflare:workers';
2
1
  import { Container, getContainer, switchPort } from '@cloudflare/containers';
3
2
  import type {
3
+ BucketCredentials,
4
+ BucketProvider,
4
5
  CodeContext,
5
6
  CreateContextOptions,
6
7
  ExecEvent,
@@ -9,6 +10,7 @@ import type {
9
10
  ExecutionResult,
10
11
  ExecutionSession,
11
12
  ISandbox,
13
+ MountBucketOptions,
12
14
  Process,
13
15
  ProcessOptions,
14
16
  ProcessStatus,
@@ -19,8 +21,9 @@ import type {
19
21
  } from '@repo/shared';
20
22
  import {
21
23
  createLogger,
22
- runWithLogger,
24
+ getEnvString,
23
25
  type SessionDeleteResult,
26
+ shellEscape,
24
27
  TraceContext
25
28
  } from '@repo/shared';
26
29
  import { type ExecuteResponse, SandboxClient } from './clients';
@@ -30,6 +33,16 @@ import { CodeInterpreter } from './interpreter';
30
33
  import { isLocalhostPattern } from './request-handler';
31
34
  import { SecurityError, sanitizeSandboxId, validatePort } from './security';
32
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';
33
46
  import { SDK_VERSION } from './version';
34
47
 
35
48
  export function getSandbox(
@@ -37,10 +50,24 @@ export function getSandbox(
37
50
  id: string,
38
51
  options?: SandboxOptions
39
52
  ): Sandbox {
40
- const stub = getContainer(ns, id) as unknown as 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
+ }
41
67
 
42
- // Store the name on first access
43
- stub.setSandboxName?.(id);
68
+ const stub = getContainer(ns, effectiveId) as unknown as Sandbox;
69
+
70
+ stub.setSandboxName?.(effectiveId, options?.normalizeId);
44
71
 
45
72
  if (options?.baseUrl) {
46
73
  stub.setBaseUrl(options.baseUrl);
@@ -54,6 +81,10 @@ export function getSandbox(
54
81
  stub.setKeepAlive(options.keepAlive);
55
82
  }
56
83
 
84
+ if (options?.containerTimeouts) {
85
+ stub.setContainerTimeouts(options.containerTimeouts);
86
+ }
87
+
57
88
  return Object.assign(stub, {
58
89
  wsConnect: connect(stub)
59
90
  });
@@ -63,7 +94,6 @@ export function connect(stub: {
63
94
  fetch: (request: Request) => Promise<Response>;
64
95
  }) {
65
96
  return async (request: Request, port: number) => {
66
- // Validate port before routing
67
97
  if (!validatePort(port)) {
68
98
  throw new SecurityError(
69
99
  `Invalid or restricted port: ${port}. Ports must be in range 1024-65535 and not reserved.`
@@ -81,25 +111,54 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
81
111
  client: SandboxClient;
82
112
  private codeInterpreter: CodeInterpreter;
83
113
  private sandboxName: string | null = null;
114
+ private normalizeId: boolean = false;
84
115
  private baseUrl: string | null = null;
85
116
  private portTokens: Map<number, string> = new Map();
86
117
  private defaultSession: string | null = null;
87
118
  envVars: Record<string, string> = {};
88
119
  private logger: ReturnType<typeof createLogger>;
89
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 };
90
146
 
91
147
  constructor(ctx: DurableObjectState<{}>, env: Env) {
92
148
  super(ctx, env);
93
149
 
94
- const envObj = env as any;
150
+ const envObj = env as Record<string, unknown>;
95
151
  // Set sandbox environment variables from env object
96
152
  const sandboxEnvKeys = ['SANDBOX_LOG_LEVEL', 'SANDBOX_LOG_FORMAT'] as const;
97
153
  sandboxEnvKeys.forEach((key) => {
98
154
  if (envObj?.[key]) {
99
- this.envVars[key] = envObj[key];
155
+ this.envVars[key] = String(envObj[key]);
100
156
  }
101
157
  });
102
158
 
159
+ // Initialize timeouts with env var fallbacks
160
+ this.containerTimeouts = this.getDefaultTimeouts(envObj);
161
+
103
162
  this.logger = createLogger({
104
163
  component: 'sandbox-do',
105
164
  sandboxId: this.ctx.id.toString()
@@ -115,10 +174,11 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
115
174
  // The CodeInterpreter extracts client.interpreter from the sandbox
116
175
  this.codeInterpreter = new CodeInterpreter(this);
117
176
 
118
- // Load the sandbox name, port tokens, and default session from storage on initialization
119
177
  this.ctx.blockConcurrencyWhile(async () => {
120
178
  this.sandboxName =
121
179
  (await this.ctx.storage.get<string>('sandboxName')) || null;
180
+ this.normalizeId =
181
+ (await this.ctx.storage.get<boolean>('normalizeId')) || false;
122
182
  this.defaultSession =
123
183
  (await this.ctx.storage.get<string>('defaultSession')) || null;
124
184
  const storedTokens =
@@ -130,14 +190,27 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
130
190
  for (const [portStr, token] of Object.entries(storedTokens)) {
131
191
  this.portTokens.set(parseInt(portStr, 10), token);
132
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
+ }
133
205
  });
134
206
  }
135
207
 
136
- // RPC method to set the sandbox name
137
- async setSandboxName(name: string): Promise<void> {
208
+ async setSandboxName(name: string, normalizeId?: boolean): Promise<void> {
138
209
  if (!this.sandboxName) {
139
210
  this.sandboxName = name;
211
+ this.normalizeId = normalizeId || false;
140
212
  await this.ctx.storage.put('sandboxName', name);
213
+ await this.ctx.storage.put('normalizeId', this.normalizeId);
141
214
  }
142
215
  }
143
216
 
@@ -200,11 +273,427 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
200
273
  }
201
274
  }
202
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
+
203
669
  /**
204
670
  * Cleanup and destroy the sandbox container
205
671
  */
206
672
  override async destroy(): Promise<void> {
207
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
+
208
697
  await super.destroy();
209
698
  }
210
699
 
@@ -267,8 +756,20 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
267
756
  }
268
757
  }
269
758
 
270
- override onStop() {
759
+ override async onStop() {
271
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
+ ]);
272
773
  }
273
774
 
274
775
  override onError(error: unknown) {
@@ -278,6 +779,117 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
278
779
  );
279
780
  }
280
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
+
281
893
  /**
282
894
  * Override onActivityExpired to prevent automatic shutdown when keepAlive is enabled
283
895
  * When keepAlive is disabled, calls parent implementation which stops the container
@@ -304,48 +916,46 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
304
916
  // Create request-specific logger with trace ID
305
917
  const requestLogger = this.logger.child({ traceId, operation: 'fetch' });
306
918
 
307
- return await runWithLogger(requestLogger, async () => {
308
- const url = new URL(request.url);
919
+ const url = new URL(request.url);
309
920
 
310
- // Capture and store the sandbox name from the header if present
311
- if (!this.sandboxName && request.headers.has('X-Sandbox-Name')) {
312
- const name = request.headers.get('X-Sandbox-Name')!;
313
- this.sandboxName = name;
314
- await this.ctx.storage.put('sandboxName', name);
315
- }
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
+ }
316
927
 
317
- // Detect WebSocket upgrade request (RFC 6455 compliant)
318
- const upgradeHeader = request.headers.get('Upgrade');
319
- const connectionHeader = request.headers.get('Connection');
320
- const isWebSocket =
321
- upgradeHeader?.toLowerCase() === 'websocket' &&
322
- connectionHeader?.toLowerCase().includes('upgrade');
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');
323
934
 
324
- if (isWebSocket) {
325
- // WebSocket path: Let parent Container class handle WebSocket proxying
326
- // This bypasses containerFetch() which uses JSRPC and cannot handle WebSocket upgrades
327
- try {
328
- requestLogger.debug('WebSocket upgrade requested', {
329
- path: url.pathname,
330
- port: this.determinePort(url)
331
- });
332
- return await super.fetch(request);
333
- } catch (error) {
334
- requestLogger.error(
335
- 'WebSocket connection failed',
336
- error instanceof Error ? error : new Error(String(error)),
337
- { path: url.pathname }
338
- );
339
- throw error;
340
- }
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;
341
951
  }
952
+ }
342
953
 
343
- // Non-WebSocket: Use existing port determination and HTTP routing logic
344
- const port = this.determinePort(url);
954
+ // Non-WebSocket: Use existing port determination and HTTP routing logic
955
+ const port = this.determinePort(url);
345
956
 
346
- // Route to the appropriate port
347
- return await this.containerFetch(request, port);
348
- });
957
+ // Route to the appropriate port
958
+ return await this.containerFetch(request, port);
349
959
  }
350
960
 
351
961
  wsConnect(request: Request, port: number): Promise<Response> {
@@ -389,9 +999,12 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
389
999
  // Persist to storage so it survives hot reloads
390
1000
  await this.ctx.storage.put('defaultSession', sessionId);
391
1001
  this.logger.debug('Default session initialized', { sessionId });
392
- } catch (error: any) {
1002
+ } catch (error: unknown) {
393
1003
  // If session already exists (e.g., after hot reload), reuse it
394
- if (error?.message?.includes('already exists')) {
1004
+ if (
1005
+ error instanceof Error &&
1006
+ error.message.includes('already exists')
1007
+ ) {
395
1008
  this.logger.debug('Reusing existing session after reload', {
396
1009
  sessionId
397
1010
  });
@@ -1031,20 +1644,29 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
1031
1644
  );
1032
1645
  }
1033
1646
 
1034
- // Validate sandbox ID (will throw SecurityError if invalid)
1035
- const sanitizedSandboxId = sanitizeSandboxId(sandboxId);
1647
+ // Hostnames are case-insensitive, routing requests to wrong DO instance when keys contain uppercase letters
1648
+ const effectiveId = this.sandboxName || sandboxId;
1649
+ const hasUppercase = /[A-Z]/.test(effectiveId);
1650
+ if (!this.normalizeId && hasUppercase) {
1651
+ throw new SecurityError(
1652
+ `Preview URLs require lowercase sandbox IDs. Your ID "${effectiveId}" contains uppercase letters.\n\n` +
1653
+ `To fix this:\n` +
1654
+ `1. Create a new sandbox with: getSandbox(ns, "${effectiveId}", { normalizeId: true })\n` +
1655
+ `2. This will create a sandbox with ID: "${effectiveId.toLowerCase()}"\n\n` +
1656
+ `Note: Due to DNS case-insensitivity, IDs with uppercase letters cannot be used with preview URLs.`
1657
+ );
1658
+ }
1659
+
1660
+ const sanitizedSandboxId = sanitizeSandboxId(sandboxId).toLowerCase();
1036
1661
 
1037
1662
  const isLocalhost = isLocalhostPattern(hostname);
1038
1663
 
1039
1664
  if (isLocalhost) {
1040
- // Unified subdomain approach for localhost (RFC 6761)
1041
1665
  const [host, portStr] = hostname.split(':');
1042
1666
  const mainPort = portStr || '80';
1043
1667
 
1044
- // Use URL constructor for safe URL building
1045
1668
  try {
1046
1669
  const baseUrl = new URL(`http://${host}:${mainPort}`);
1047
- // Construct subdomain safely with mandatory token
1048
1670
  const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${host}`;
1049
1671
  baseUrl.hostname = subdomainHost;
1050
1672
 
@@ -1058,13 +1680,8 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
1058
1680
  }
1059
1681
  }
1060
1682
 
1061
- // Production subdomain logic - enforce HTTPS
1062
1683
  try {
1063
- // Always use HTTPS for production (non-localhost)
1064
- const protocol = 'https';
1065
- const baseUrl = new URL(`${protocol}://${hostname}`);
1066
-
1067
- // Construct subdomain safely with mandatory token
1684
+ const baseUrl = new URL(`https://${hostname}`);
1068
1685
  const subdomainHost = `${port}-${sanitizedSandboxId}-${token}.${hostname}`;
1069
1686
  baseUrl.hostname = subdomainHost;
1070
1687
 
@@ -1229,7 +1846,12 @@ export class Sandbox<Env = unknown> extends Container<Env> implements ISandbox {
1229
1846
  this.codeInterpreter.runCodeStream(code, options),
1230
1847
  listCodeContexts: () => this.codeInterpreter.listCodeContexts(),
1231
1848
  deleteCodeContext: (contextId) =>
1232
- this.codeInterpreter.deleteCodeContext(contextId)
1849
+ this.codeInterpreter.deleteCodeContext(contextId),
1850
+
1851
+ // Bucket mounting - sandbox-level operations
1852
+ mountBucket: (bucket, mountPath, options) =>
1853
+ this.mountBucket(bucket, mountPath, options),
1854
+ unmountBucket: (mountPath) => this.unmountBucket(mountPath)
1233
1855
  };
1234
1856
  }
1235
1857