UNPKG

ursamu-mud

Version:

Ursamu - Modular MUD Engine with sandboxed scripting and plugin system

571 lines (455 loc) β€’ 14.5 kB
# Ursamu - Modular MUD Engine **Ursamu** is a next-generation Multi-User Dungeon (MUD) engine built with TypeScript, featuring a modular plugin system, sandboxed virtual machine for user scripts, hot-reload capabilities, and multi-protocol support. [![MIT License](https://img.shields.io/badge/License-MIT-28a745)](#license) [![Node.js](https://img.shields.io/badge/Node.js-18+-339933?logo=node.js&logoColor=white)](#requirements) [![TypeScript](https://img.shields.io/badge/TypeScript-5+-3178c6?logo=typescript&logoColor=white)](#requirements) ## Table of Contents - [Features](#features) - [Architecture Overview](#architecture-overview) - [Quick Start](#quick-start) - [Core Systems](#core-systems) - [Multi-Protocol Server](#multi-protocol-server) - [Plugin System](#plugin-system) - [Sandboxed Virtual Machine](#sandboxed-virtual-machine) - [Hot-Reload System](#hot-reload-system) - [Developer CLI](#developer-cli) - [Getting Started](#getting-started) - [Development](#development) - [Configuration](#configuration) - [API Documentation](#api-documentation) - [Contributing](#contributing) - [License](#license) ## Features ### πŸ—οΈ **Modular Architecture** - Plugin-based system with automatic discovery and lifecycle management - Hot-reload capabilities for zero-downtime updates - Sandboxed execution environment for user scripts - Event-driven architecture with comprehensive monitoring ### 🌐 **Multi-Protocol Support** - **Telnet** - Traditional MUD protocol with full ANSI support - **WebSocket** - Modern web-based connectivity with binary message support - **HTTP/REST** - RESTful API for external integrations - **TCP Raw** - Direct socket connections for custom protocols ### πŸ”’ **Security & Isolation** - VM-based script sandboxing with resource limits - Memory and CPU usage monitoring - Security validation preventing dangerous code patterns - Automatic rollback on validation failures ### ⚑ **Performance & Reliability** - Sub-50ms hot-reload target times - Parallel compilation with dependency resolution - State preservation across updates - Comprehensive error handling and recovery ### πŸ› οΈ **Developer Experience** - Powerful CLI tool for development and debugging - Real-time script compilation and validation - Performance profiling and analysis - Project scaffolding and management ## Architecture Overview ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Multi-Protocol β”‚ β”‚ Plugin System β”‚ β”‚ Hot-Reload Core β”‚ β”‚ Server │◄──►│ Discovery │◄──►│ File Watcher β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Connection Pool β”‚ β”‚ Lifecycle Managerβ”‚ β”‚ Compilation β”‚ β”‚ Management β”‚ β”‚ Events & Deps β”‚ β”‚ Queue β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Sandboxed β”‚ β”‚ Game World β”‚ β”‚ Validation β”‚ β”‚ Virtual Machine │◄──►│ State Mgmt │◄──►│ Engine β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` ## Quick Start ### Prerequisites - Node.js 18.0.0 or higher - TypeScript 5.0 or higher - npm or yarn package manager ### Installation ```bash # Clone the repository git clone https://github.com/your-org/ursamu.git cd ursamu # Install dependencies npm install # Build the project npm run build # Start the server npm start # Or use the Ursamu CLI npx ursamu-mud start ``` ### Basic Usage ```typescript import { MUDEngine } from 'ursamu-mud'; const engine = new MUDEngine({ protocols: ['telnet', 'websocket'], hotReload: { enabled: true, watchPaths: ['./scripts', './plugins'] }, vm: { memoryLimit: 64 * 1024 * 1024, // 64MB timeoutMs: 5000 } }); await engine.start(); console.log('Ursamu MUD engine started successfully!'); ``` ## Core Systems ### Multi-Protocol Server The multi-protocol server provides seamless connectivity across different network protocols: ```typescript // Configure multiple protocols const protocolConfig = { telnet: { port: 4000, encoding: 'utf8', ansiSupport: true }, websocket: { port: 8080, path: '/ws', binaryMessages: true }, http: { port: 3000, cors: true, rateLimiting: true } }; ``` **Key Features:** - Protocol-agnostic message handling - Connection pooling and lifecycle management - Built-in rate limiting and security - Real-time connection monitoring ### Plugin System Discover and manage plugins automatically with full lifecycle control: ```typescript // Plugin structure export class ExamplePlugin implements Plugin { name = 'example-plugin'; version = '1.0.0'; dependencies = ['core-engine']; async onLoad(): Promise<void> { console.log('Plugin loaded'); } async onUnload(): Promise<void> { console.log('Plugin unloaded'); } } ``` **Features:** - Automatic plugin discovery - Dependency resolution and management - Hot-loading and unloading - Version compatibility checking ### Sandboxed Virtual Machine Execute user scripts safely in an isolated environment: ```typescript // VM configuration const vmConfig = { memoryLimit: 64 * 1024 * 1024, // 64MB timeoutMs: 5000, allowedModules: ['util', 'crypto'], blockedPatterns: [/eval/, /Function/, /require/] }; // Execute script safely const result = await vm.executeScript(scriptCode, { context: gameContext, timeout: 1000 }); ``` **Security Features:** - Memory usage monitoring - CPU time limits - Module access control - Dangerous pattern detection ### Hot-Reload System Zero-downtime updates with state preservation: ```typescript // Hot-reload configuration const hotReloadConfig = { enabled: true, watchPaths: ['./scripts', './plugins', './modules'], debounceMs: 250, validateBeforeReload: true, allowRollback: true, backupOnReload: true }; ``` **Pipeline Stages:** 1. **File Watching** - Detect changes with debouncing 2. **Compilation** - Process TypeScript, JavaScript, and MUD scripts 3. **Validation** - Security and performance checks 4. **Deployment** - Atomic updates with state preservation 5. **Rollback** - Automatic recovery on failures ### Developer CLI Comprehensive development tools for building and debugging: ```bash # Script management ursamu-mud script create my-script --template typescript ursamu-mud script compile ./scripts/combat.ts ursamu-mud script validate ./scripts/*.js # Development server ursamu-mud dev --hot-reload --debug ursamu-mud debug --inspect-brk # Performance analysis ursamu-mud profile --script ./scripts/ai.js --duration 60s ursamu-mud benchmark --load-test --connections 1000 # Project management ursamu-mud init --template basic-mud ursamu-mud plugin install combat-system ursamu-mud deploy --environment production ``` ## Getting Started ### 1. Create a New Project ```bash # Initialize new Ursamu MUD project ursamu-mud init my-mud-game --template typescript # Navigate to project cd my-mud-game # Install dependencies npm install ``` ### 2. Configure the Engine Edit `config/default.json`: ```json { "server": { "protocols": { "telnet": { "port": 4000, "enabled": true }, "websocket": { "port": 8080, "enabled": true }, "http": { "port": 3000, "enabled": true } } }, "hotReload": { "enabled": true, "watchPaths": ["./scripts", "./plugins"], "debounceMs": 250, "maxReloadTime": 50 }, "vm": { "memoryLimit": 67108864, "timeoutMs": 5000, "enableProfiling": true }, "plugins": { "autoDiscovery": true, "searchPaths": ["./plugins", "./node_modules/@mud/*"] } } ``` ### 3. Create Your First Script ```typescript // scripts/welcome.ts export function onPlayerConnect(player: Player, context: GameContext): void { player.send(`Welcome to ${context.world.name}!`); player.send('Type "help" for available commands.'); } export function helpCommand(player: Player, args: string[]): CommandResult { const commands = [ 'look - Examine your surroundings', 'inventory - Check your items', 'quit - Leave the game' ]; return { success: true, message: 'Available commands:\n' + commands.join('\n') }; } ``` ### 4. Start the Server ```bash # Development mode with hot-reload npm run dev # Production mode npm start # With custom configuration npm start -- --config ./config/production.json ``` ## Development ### Building from Source ```bash # Clone repository git clone https://github.com/your-org/ursamu.git cd ursamu # Install dependencies npm install # Build TypeScript npm run build # Run tests npm test # Development with watch mode npm run dev ``` ### Running Tests ```bash # Run all tests npm test # Run specific test suite npm test -- --testPathPattern="hotreload" # Run with coverage npm run test:coverage # Run integration tests npm run test:integration ``` ### Project Structure ``` ursamu/ β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ core/ # Core engine systems β”‚ β”œβ”€β”€ protocols/ # Multi-protocol server β”‚ β”œβ”€β”€ plugins/ # Plugin discovery & lifecycle β”‚ β”œβ”€β”€ vm/ # Sandboxed virtual machine β”‚ β”œβ”€β”€ scripting/ # Hot-reload system β”‚ β”œβ”€β”€ cli/ # Developer CLI tool (ursamu-cli) β”‚ └── index.ts # Main entry point β”œβ”€β”€ scripts/ # Game scripts β”œβ”€β”€ plugins/ # Available plugins β”œβ”€β”€ config/ # Configuration files β”œβ”€β”€ tests/ # Test suites └── docs/ # Documentation ``` ## Configuration ### Environment Variables ```bash # Server configuration URSAMU_PORT=4000 URSAMU_HOST=0.0.0.0 # Hot-reload settings HOT_RELOAD_ENABLED=true HOT_RELOAD_DEBOUNCE=250 # VM security VM_MEMORY_LIMIT=67108864 VM_TIMEOUT_MS=5000 # Development NODE_ENV=development DEBUG=ursamu:* ``` ### Advanced Configuration ```typescript // Advanced engine configuration const engineConfig: MUDEngineConfig = { protocols: { telnet: { port: 4000, encoding: 'utf8', options: { localEcho: false, lineMode: true } }, websocket: { port: 8080, path: '/ws', options: { compression: true, maxPayload: 1024 * 1024 // 1MB } } }, hotReload: { enabled: true, watchPaths: ['./scripts', './plugins'], ignorePaths: ['node_modules', '.git'], debounceMs: 250, maxReloadTime: 50, validateBeforeReload: true, allowRollback: true, backupOnReload: true }, vm: { memoryLimit: 64 * 1024 * 1024, timeoutMs: 5000, enableProfiling: true, allowedModules: ['util', 'crypto'], securityOptions: { checkDangerous: true, maxComplexity: 50, maxMemoryUsage: 0.8 } }, plugins: { autoDiscovery: true, searchPaths: ['./plugins'], lifecycle: { loadTimeout: 10000, unloadTimeout: 5000 } } }; ``` ## API Documentation ### Core Engine API ```typescript // Engine lifecycle await engine.start(); await engine.stop(); await engine.restart(); // Plugin management await engine.loadPlugin('combat-system'); await engine.unloadPlugin('combat-system'); const plugins = engine.getLoadedPlugins(); // Script execution const result = await engine.executeScript(script, context); // Hot-reload control await engine.hotReload.start(); await engine.hotReload.reload(['script.js']); const status = engine.hotReload.getStatus(); ``` ### Protocol Management ```typescript // Protocol control await engine.protocols.start('telnet'); await engine.protocols.stop('websocket'); // Connection management const connections = engine.protocols.getActiveConnections(); await engine.protocols.broadcast('Hello everyone!'); // Custom protocol handlers engine.protocols.registerHandler('telnet', customTelnetHandler); ``` ### Virtual Machine API ```typescript // Script execution const result = await vm.executeScript(code, { context: gameContext, timeout: 5000, memoryLimit: 1024 * 1024 }); // Resource monitoring const stats = vm.getResourceUsage(); const profile = vm.getPerformanceProfile(); // Security validation const validation = await vm.validateScript(code); ``` ## Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. ### Development Workflow 1. Fork the repository 2. Create a feature branch: `git checkout -b feature/new-feature` 3. Make your changes and add tests 4. Run tests: `npm test` 5. Commit with conventional commits: `git commit -m "feat: add new feature"` 6. Push to your fork: `git push origin feature/new-feature` 7. Create a Pull Request ### Code Standards - TypeScript with strict mode enabled - ESLint configuration provided - 100% test coverage for new features - Comprehensive documentation for APIs ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. --- ## Support - πŸ“– **Documentation**: [Full API docs](docs/) - πŸ› **Bug Reports**: [GitHub Issues](issues/) - πŸ’¬ **Discussions**: [GitHub Discussions](discussions/) - πŸ”§ **Development**: [Contributing Guide](CONTRIBUTING.md) --- **Ursamu - Built with ❀️ for the MUD development community**