> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Plugin System with Code Execution

> Build a WordPress/Shopify-style plugin marketplace with untrusted code execution, permission systems, API access control, and sandbox isolation

Build a production-ready plugin system that safely executes untrusted code from third-party developers. This cookbook demonstrates how to create a plugin marketplace with security isolation using HopX.

## Overview

Plugin systems allow third-party developers to extend platform functionality. The system must execute untrusted code safely, enforce permissions, control API access, and maintain complete isolation between plugins.

## Prerequisites

* HopX API key ([Get one here](https://console.hopx.dev/api-keys))
* Python 3.8+ or Node.js 16+
* Understanding of security isolation
* Basic knowledge of permission systems

## Architecture

```
┌──────────────┐
│   Plugin     │ Untrusted code
└──────┬───────┘
       │
       ▼
┌─────────────────┐
│  Plugin         │ Validate, isolate
│   Manager       │
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  Isolated        │ One per plugin
│  Sandbox         │
└─────────────────┘
```

## Implementation

### Step 1: Plugin Execution with Isolation

Execute plugins in isolated sandboxes:

<CodeGroup>
  ```python Python theme={null}
  from hopx_ai import Sandbox
  import os
  from typing import Dict, Any, List

  class Plugin:
      def __init__(self, plugin_id: str, code: str, permissions: List[str]):
          self.plugin_id = plugin_id
          self.code = code
          self.permissions = permissions

  class PluginSystem:
      def __init__(self, api_key: str):
          self.api_key = api_key
          self.plugins = {}
          self.plugin_sandboxes = {}
      
      def register_plugin(self, plugin: Plugin):
          """Register a plugin"""
          self.plugins[plugin.plugin_id] = plugin
      
      def execute_plugin(self, plugin_id: str, context: Dict[str, Any] = None) -> Dict[str, Any]:
          """Execute plugin in isolated sandbox"""
          if plugin_id not in self.plugins:
              return {
                  "success": False,
                  "error": f"Plugin {plugin_id} not found"
              }
          
          plugin = self.plugins[plugin_id]
          sandbox = None
          
          try:
              # Create fresh sandbox for each execution
              sandbox = Sandbox.create(
                  template="code-interpreter",
                  api_key=self.api_key,
                  timeout_seconds=60
              )
              
              # Set up plugin environment with limited permissions
              env_vars = {
                  "PLUGIN_ID": plugin_id,
                  "PERMISSIONS": ",".join(plugin.permissions)
              }
              sandbox.env.set_all(env_vars)
              
              # Add context if provided
              if context:
                  for key, value in context.items():
                      sandbox.env.set(f"CONTEXT_{key}", str(value))
              
              # Execute plugin code
              result = sandbox.run_code(plugin.code, timeout=30)
              
              return {
                  "success": result.success,
                  "stdout": result.stdout,
                  "stderr": result.stderr,
                  "plugin_id": plugin_id
              }
          except Exception as e:
              return {
                  "success": False,
                  "error": str(e),
                  "plugin_id": plugin_id
              }
          finally:
              if sandbox:
                  sandbox.kill()  # Always cleanup
      
      def cleanup_all(self):
          """Clean up all plugin resources"""
          for sandbox in self.plugin_sandboxes.values():
              sandbox.kill()
          self.plugin_sandboxes.clear()

  # Usage
  system = PluginSystem(api_key=os.getenv("HOPX_API_KEY"))

  # Register plugin
  system.register_plugin(Plugin(
      plugin_id="calculator",
      code="result = 2 + 2\nprint(f'Result: {result}')",
      permissions=["compute"]
  ))

  # Execute
  result = system.execute_plugin("calculator")
  print(result)

  system.cleanup_all()
  ```

  ```javascript JavaScript theme={null}
  import { Sandbox } from '@hopx-ai/sdk';

  class Plugin {
      constructor(pluginId, code, permissions) {
          this.pluginId = pluginId;
          this.code = code;
          this.permissions = permissions;
      }
  }

  class PluginSystem {
      constructor(apiKey) {
          this.apiKey = apiKey;
          this.plugins = {};
          this.pluginSandboxes = {};
      }
      
      registerPlugin(plugin) {
          this.plugins[plugin.pluginId] = plugin;
      }
      
      async executePlugin(pluginId, context = null) {
          if (!this.plugins[pluginId]) {
              return {
                  success: false,
                  error: `Plugin ${pluginId} not found`
              };
          }
          
          const plugin = this.plugins[pluginId];
          let sandbox = null;
          
          try {
              // Create fresh sandbox for each execution
              sandbox = await Sandbox.create({
                  template: 'code-interpreter',
                  apiKey: this.apiKey,
                  timeoutSeconds: 60
              });
              
              // Set up plugin environment with limited permissions
              const envVars = {
                  PLUGIN_ID: pluginId,
                  PERMISSIONS: plugin.permissions.join(',')
              };
              await sandbox.env.setAll(envVars);
              
              // Add context if provided
              if (context) {
                  for (const [key, value] of Object.entries(context)) {
                      await sandbox.env.set(`CONTEXT_${key}`, String(value));
                  }
              }
              
              // Execute plugin code
              const result = await sandbox.runCode(plugin.code, { timeout: 30 });
              
              return {
                  success: result.success,
                  stdout: result.stdout,
                  stderr: result.stderr,
                  pluginId
              };
          } catch (error) {
              return {
                  success: false,
                  error: error.message,
                  pluginId
              };
          } finally {
              if (sandbox) {
                  await sandbox.kill();  // Always cleanup
              }
          }
      }
      
      async cleanupAll() {
          await Promise.all(
              Object.values(this.pluginSandboxes).map(sandbox => sandbox.kill())
          );
          this.pluginSandboxes = {};
      }
  }

  // Usage
  const system = new PluginSystem(process.env.HOPX_API_KEY);

  // Register plugin
  system.registerPlugin(new Plugin(
      'calculator',
      "result = 2 + 2\nprint(f'Result: {result}')",
      ['compute']
  ));

  // Execute
  const result = await system.executePlugin('calculator');
  console.log(result);

  await system.cleanupAll();
  ```
</CodeGroup>

## Best Practices

<Warning>
  Always execute plugins in fresh, isolated sandboxes. Never trust plugin code or allow plugins to access system resources.
</Warning>

1. **Complete Isolation**: One sandbox per plugin execution
2. **Permission System**: Enforce permissions strictly
3. **Code Validation**: Validate plugin code before execution
4. **Resource Limits**: Set strict resource limits

## Related Cookbooks

* [Multi-Tenant Execution](/cookbooks/enterprise/multi-tenant-execution) - Multi-tenant patterns
* [User-Defined Functions](/cookbooks/marketplace/user-functions) - Custom functions

## Next Steps

1. Implement permission system
2. Add plugin marketplace features
3. Create plugin validation
4. Implement plugin versioning
5. Add plugin monitoring
