# Sandbox Execution Interfaces

This directory defines interfaces for secure code execution environments.

## Files

### `sandbox-wrapper.ts`
Contains the core `ISandboxWrapper` interface and `SandboxContext` class for managing secure code execution.

## Core Components

### ISandboxWrapper Interface
Defines the contract for executing user code in isolated environments.

**Purpose:** Provides a standardized way to execute user code safely with controlled access to system resources.

**Usage:**
```typescript
import { ISandboxWrapper } from '@chargebee/chargebee-apps-shared';

class MyCodeExecutor {
  constructor(private sandbox: ISandboxWrapper) {}
  
  async runUserCode(code: string, eventData: any): Promise<any> {
    const context = this.sandbox.createContext(eventData);
    const result = await this.sandbox.execute(code, context);
    
    if (result.success) {
      return result.result;
    } else {
      throw new Error(result.error);
    }
  }
}
```

### SandboxContext Class
Manages execution context and correlation tracking for sandbox operations.

**Purpose:** Provides correlation IDs and context management for tracking code execution across different parts of the system.

**Usage:**
```typescript
import { SandboxContext } from '@chargebee/chargebee-apps-shared';

class EventProcessor {
  async processEvent(eventData: any): Promise<void> {
    const correlationId = SandboxContext.generateCorrelationId();
    
    SandboxContext.run(correlationId, async () => {
      // All operations within this block share the same correlation ID
      await this.executeHandler(eventData);
      await this.logResults();
    });
  }
}
```

## Security Model

### Controlled Execution
Sandbox implementations provide:
- **Module restrictions** - Only whitelisted modules can be required
- **Global access control** - Limited access to Node.js globals
- **Timeout management** - Code execution has time limits
- **Resource limits** - Memory and CPU usage controls

### Context Isolation
Each execution gets:
- **Fresh context** - No shared state between executions
- **Safe globals** - Controlled versions of console, setTimeout, etc.
- **Payload** - The sandbox exposes a single `payload` object (`{ event, iparams }`). Handlers are invoked as `handler(payload)`; use `payload.event` for the webhook event and `payload.iparams` for installation parameters.
- **Logging interface** - Structured logging through provided logger

## Execution Flow

### Basic Execution Pattern
```typescript
// 1. Create context with event data
const context = sandbox.createContext(eventData);

// 2. Execute user code in isolated environment
const result = await sandbox.execute(handlerCode, context);

// 3. Handle results
if (result.success) {
  console.log('Handler executed successfully:', result.result);
} else {
  console.error('Handler execution failed:', result.error);
}
```

### Context Correlation
```typescript
// 1. Generate correlation ID
const correlationId = SandboxContext.generateCorrelationId();

// 2. Run operations with shared context
SandboxContext.run(correlationId, async () => {
  // All logging and operations share the same correlation ID
  await processEvent();
  await updateDatabase();
  await sendNotification();
});
```

## Error Handling

Sandbox implementations handle various error scenarios:
- **Syntax errors** - Invalid JavaScript code
- **Runtime errors** - Exceptions during execution
- **Timeout errors** - Code execution exceeds time limits
- **Security violations** - Attempts to access restricted resources

## Best Practices

1. **Always use correlation IDs** - Track operations across the system
2. **Implement timeouts** - Prevent infinite loops and hanging code
3. **Validate inputs** - Check code and context before execution
4. **Handle errors gracefully** - Provide meaningful error messages
5. **Log execution details** - Track performance and issues
6. **Isolate contexts** - Don't share state between executions
7. **Control resource access** - Limit what user code can access