diff --git a/npmextra.json b/npmextra.json index f17a201..0a5441f 100644 --- a/npmextra.json +++ b/npmextra.json @@ -4,9 +4,9 @@ "module": { "githost": "gitlab.com", "gitscope": "serve.zone", - "gitrepo": "platformservice", - "description": "A multifaceted platform service handling mail, SMS, letter delivery, and AI services.", - "npmPackagename": "@serve.zone/platformservice", + "gitrepo": "dcrouter", + "description": "A traffic router intended to be gating your datacenter.", + "npmPackagename": "@serve.zone/dcrouter", "license": "MIT", "projectDomain": "serve.zone", "keywords": [ @@ -17,7 +17,7 @@ "SMTP server", "mail parsing", "DKIM", - "platform service", + "traffic router", "letterXpress", "OpenAI", "Anthropic AI", @@ -35,7 +35,7 @@ "npmci": { "npmGlobalTools": [], "dockerRegistryRepoMap": { - "registry.gitlab.com": "code.foss.global/serve.zone/platformservice" + "registry.gitlab.com": "code.foss.global/serve.zone/dcrouter" }, "dockerBuildargEnvMap": { "NPMCI_TOKEN_NPM2": "NPMCI_TOKEN_NPM2" diff --git a/readme.md b/readme.md index 7879dab..aa98fe8 100644 --- a/readme.md +++ b/readme.md @@ -1,328 +1,824 @@ # dcrouter -dcrouter: a traffic router intended to be gating your datacenter. +**dcrouter: a traffic router intended to be gating your datacenter.** -## Install +A comprehensive traffic routing solution that provides unified gateway capabilities for HTTP/HTTPS, TCP/SNI, email (SMTP), and DNS protocols. Designed for enterprises requiring robust traffic management, automatic certificate provisioning, and enterprise-grade email infrastructure. -To install `@serve.zone/platformservice`, run the following command: +## Table of Contents -```sh -npm install @serve.zone/platformservice --save +- [Features](#features) +- [Installation](#installation) +- [Quick Start](#quick-start) +- [Architecture](#architecture) +- [Configuration](#configuration) +- [Email System](#email-system) +- [SmartProxy Routing](#smartproxy-routing) +- [Security Features](#security-features) +- [API Reference](#api-reference) +- [Examples](#examples) +- [Troubleshooting](#troubleshooting) + +## Features + +### 🌐 **Universal Traffic Router** +- **HTTP/HTTPS routing** with pattern matching and virtual hosts +- **TCP/SNI proxy** for any protocol with TLS termination/passthrough +- **DNS server** with authoritative and dynamic record management +- **Multi-protocol support** on the same infrastructure + +### 🔒 **Enterprise Security** +- **Automatic TLS certificates** via ACME with DNS-01 challenges +- **IP reputation checking** and real-time threat detection +- **Content scanning** for spam, viruses, and malicious content +- **Comprehensive security logging** with correlation tracking + +### 📧 **Complete Email Infrastructure** +- **Multi-domain SMTP server** on standard ports (25, 587, 465) +- **Pattern-based email routing** with three processing modes +- **DKIM, SPF, DMARC** authentication and verification +- **Enterprise deliverability** with IP warmup and reputation management + +### ⚡ **High Performance** +- **Connection pooling** and efficient resource management +- **Load balancing** with automatic failover +- **Rate limiting** at multiple levels +- **Real-time metrics** and monitoring + +## Installation + +```bash +npm install @serve.zone/dcrouter --save ``` -Make sure you have Node.js and npm installed on your system to use this package. - -## Usage - -This document provides extensive usage scenarios for the `@serve.zone/platformservice`, a comprehensive ESM module written in TypeScript offering a wide range of services such as mail, SMS, letter, and artificial intelligence (AI) functionalities. This service is an exemplar of a modular design, allowing users to leverage various communication methods and AI services efficiently. Key features provided by this platform include sending and receiving emails, managing SMS services, letter dispatching, and utilizing AI for diverse purposes. - ### Prerequisites -Before diving into the examples, ensure you have the platform service installed and configured correctly. The package leverages environment variables for configuration, so you must set up the necessary variables, including service endpoints, authentication tokens, and database connections. +- Node.js 18+ with ES modules support +- Valid domain with DNS control (for ACME certificates) +- Cloudflare API token (for DNS challenges) -### Initialization +## Quick Start -First, initialize the platform service, ensuring all dependencies are correctly loaded and configured: +### Basic HTTP/HTTPS Router -```ts -import { SzPlatformService } from '@serve.zone/platformservice'; +```typescript +import { DcRouter } from '@serve.zone/dcrouter'; -async function initService() { - const platformService = new SzPlatformService(); - await platformService.start(); - console.log('Platform service initialized successfully.'); -} +const router = new DcRouter({ + smartProxyConfig: { + routes: [ + { + name: 'web-service', + match: { domains: ['example.com'], ports: [443] }, + action: { + type: 'forward', + target: { host: '192.168.1.10', port: 8080 }, + tls: { mode: 'terminate', certificate: 'auto' } + } + } + ], + acme: { + email: 'admin@example.com', + enabled: true, + useProduction: true + } + } +}); -initService(); +await router.start(); +console.log('DcRouter started successfully'); ``` -### Sending Emails +### Basic Email Router -One of the primary services offered is email management. Here's how to send an email using the platform service: +```typescript +import { DcRouter } from '@serve.zone/dcrouter'; -```ts -import { EmailService, IEmailOptions } from '@serve.zone/platformservice'; +const router = new DcRouter({ + emailConfig: { + ports: [25, 587, 465], + hostname: 'mail.example.com', + domainRules: [ + { + pattern: '*@example.com', + mode: 'mta', + mtaOptions: { + domain: 'example.com', + dkimSign: true + } + } + ], + tls: { + keyPath: './certs/key.pem', + certPath: './certs/cert.pem' + } + } +}); -async function sendEmail() { - const emailOptions: IEmailOptions = { - from: 'no-reply@example.com', - to: 'recipient@example.com', - subject: 'Test Email', - body: '
This is a test email
', - attachments: [] // Optional attachments - }); - - const emailId = await mtaService.send(email); - console.log(`Email queued with ID: ${emailId}`); - - // Check email status - const status = mtaService.getEmailStatus(emailId); - console.log(`Email status: ${status.status}`); - - // Set up API for external access - const apiManager = new ApiManager(platformService.emailService); - await apiManager.start(3000); - console.log('MTA API running on port 3000'); -} - -useMtaService(); + // SNI-based routing for TLS services + { + name: 'secure-service', + match: { + domains: ['secure.example.com'], + ports: [8443] + }, + action: { + type: 'forward', + target: { + host: '192.168.1.40', + port: 8443 + }, + tls: { + mode: 'passthrough' + } + } + } +]; ``` -The consolidated email system provides key advantages for applications requiring: -- Domain-specific email handling -- Flexible email routing -- High-volume email sending -- Compliance with email authentication standards -- Detailed delivery tracking -- Custom email handling logic -- Multi-domain email management -- Complete control over email infrastructure +## Security Features -### Leveraging AI Services +### IP Reputation Checking -The platform also integrates AI functionalities, allowing for innovative use cases like generating content, analyzing text, or automating responses: +```typescript +import { IpReputationChecker } from '@serve.zone/dcrouter'; -```ts -import { AiService } from '@serve.zone/platformservice'; +const ipChecker = new IpReputationChecker({ + providers: ['spamhaus', 'barracuda', 'surbl'], + cacheTimeout: 3600000, // 1 hour + threshold: 0.7 +}); -async function useAiService() { - const aiService = new AiService('OPENAI_API_KEY'); // Replace with your real API key - const response = await aiService.generateText('Prompt for the AI service.'); - - console.log(`AI response: ${response}`); +// Check IP reputation +const result = await ipChecker.checkIp('192.0.2.1'); +if (result.isBlocked) { + console.log(`IP blocked: ${result.reason}`); } - -useAiService(); ``` + +### Content Security Scanner + +```typescript +import { ContentScanner } from '@serve.zone/dcrouter'; + +const scanner = new ContentScanner({ + spamThreshold: 5.0, + virusScanning: true, + attachmentFiltering: { + maxSize: 25 * 1024 * 1024, + blockedTypes: ['.exe', '.bat', '.scr'] + } +}); + +const scanResult = await scanner.scanEmail(email); +``` + +## API Reference + +### DcRouter Class + +#### Constructor +```typescript +constructor(options: IDcRouterOptions) +``` + +#### Methods + +##### `start(): PromiseHello World
', + attachments: [] +}); +``` + +#### `getEmailStatus(emailId: string): IEmailStatus` +```typescript +const status = router.emailService.getEmailStatus(emailId); +console.log(status.status); // 'pending', 'sent', 'delivered', 'bounced' +``` + +#### `getDeliveryReport(emailId: string): IDeliveryReport` +Detailed delivery information including bounce reasons and tracking data. + +## Examples + +### Complete Enterprise Setup + +```typescript +import { DcRouter } from '@serve.zone/dcrouter'; + +const router = new DcRouter({ + // HTTP/HTTPS routing + smartProxyConfig: { + routes: [ + // Main website + { + name: 'website', + priority: 100, + match: { domains: ['example.com', 'www.example.com'], ports: [443] }, + action: { + type: 'forward', + target: { host: '192.168.1.10', port: 80 }, + tls: { mode: 'terminate', certificate: 'auto' } + } + }, + + // API services + { + name: 'api', + priority: 110, + match: { domains: ['api.example.com'], ports: [443] }, + action: { + type: 'forward', + target: { host: '192.168.1.20', port: 8080 }, + tls: { mode: 'terminate', certificate: 'auto' } + } + }, + + // Internal services + { + name: 'internal', + match: { ports: [{ from: 8000, to: 8999 }] }, + action: { + type: 'forward', + target: { host: '192.168.1.30', port: 'preserve' }, + security: { ipAllowList: ['192.168.0.0/16'] } + } + } + ], + + // ACME certificate automation + acme: { + email: 'ssl@example.com', + enabled: true, + useProduction: true, + autoRenew: true + } + }, + + // Enterprise email system + emailConfig: { + ports: [25, 587, 465], + hostname: 'mail.example.com', + + // Authentication configuration + auth: { + required: true, + methods: ['PLAIN', 'LOGIN'] + }, + + // TLS configuration + tls: { + keyPath: './certs/mail-key.pem', + certPath: './certs/mail-cert.pem' + }, + + // Domain routing rules + domainRules: [ + // Transactional emails via MTA + { + pattern: '*@notifications.example.com', + mode: 'mta', + mtaOptions: { + domain: 'notifications.example.com', + dkimSign: true, + dkimOptions: { + domainName: 'notifications.example.com', + keySelector: 'mail', + privateKey: dkimKey + } + } + }, + + // Internal emails forwarded to Exchange + { + pattern: '*@example.com', + mode: 'forward', + target: { + server: 'exchange.internal.example.com', + port: 25, + useTls: true + } + }, + + // Marketing emails with content scanning + { + pattern: '*@marketing.example.com', + mode: 'process', + contentScanning: true, + scanners: [ + { type: 'spam', threshold: 5.0, action: 'tag' }, + { type: 'virus', action: 'reject' } + ] + } + ], + + // Default fallback + defaultMode: 'forward', + defaultServer: 'backup-mail.example.com', + defaultPort: 25 + }, + + // DNS server for ACME challenges + dnsServerConfig: { + port: 53, + authoritative: true + }, + + // Cloudflare DNS challenges + dnsChallenge: { + cloudflareApiKey: process.env.CLOUDFLARE_API_KEY + } +}); + +// Start the router +await router.start(); +console.log('Enterprise DcRouter started'); + +// Monitor statistics +setInterval(() => { + const stats = router.getStats(); + console.log('Active connections:', stats.activeConnections); + console.log('Emails processed:', stats.emailsProcessed); +}, 60000); +``` + +### Email Template System + +```typescript +import { EmailService, TemplateManager } from '@serve.zone/dcrouter'; + +// Setup email templates +const templateManager = new TemplateManager(); +templateManager.addTemplate('welcome', { + subject: 'Welcome to {{company}}!', + html: ` +Thank you for joining {{company}}.
+Your account: {{email}}
+ `, + text: 'Welcome {{name}}! Thank you for joining {{company}}.' +}); + +// Send templated email +const emailService = new EmailService(router); +await emailService.sendTemplatedEmail('welcome', { + to: 'user@example.com', + templateData: { + name: 'John Doe', + company: 'Example Corp', + email: 'user@example.com' + } +}); +``` + +## Troubleshooting + +### Common Issues + +#### Certificate Issues +```bash +# Check certificate status +curl -I https://your-domain.com + +# Verify ACME challenge accessibility +curl http://your-domain.com/.well-known/acme-challenge/test +``` + +#### Email Delivery Issues +```bash +# Test SMTP connectivity +telnet your-server.com 25 + +# Check DKIM record +dig TXT mail._domainkey.your-domain.com + +# Verify SPF record +dig TXT your-domain.com +``` + +#### DNS Issues +```bash +# Test DNS server +dig @your-server.com your-domain.com + +# Check DNS propagation +dig your-domain.com @8.8.8.8 +``` + +### Logging and Monitoring + +```typescript +import { SmartLog } from '@push.rocks/smartlog'; + +// Configure logging +const logger = new SmartLog({ + level: 'info', + transport: 'console' +}); + +// Monitor email events +router.emailServer.on('emailReceived', (email) => { + logger.log('info', `Email received: ${email.from} -> ${email.to}`); +}); + +router.emailServer.on('emailSent', (result) => { + logger.log('info', `Email sent: ${result.messageId} (${result.status})`); +}); + +// Monitor proxy events +router.smartProxy.on('connectionEstablished', (connection) => { + logger.log('info', `Connection: ${connection.clientIp} -> ${connection.target}`); +}); +``` + +### Performance Tuning + +```typescript +const performanceConfig = { + // Connection limits + maxConnections: 1000, + connectionTimeout: 30000, + + // Email queue settings + emailQueue: { + concurrency: 10, + maxRetries: 3, + retryDelay: 300000 + }, + + // Cache settings + cache: { + ipReputation: { ttl: 3600000 }, // 1 hour + dns: { ttl: 300000 }, // 5 minutes + certificates: { ttl: 86400000 } // 24 hours + } +}; +``` + +## License + +MIT License - see LICENSE file for details. + +## Support + +- Documentation: [https://docs.serve.zone/dcrouter](https://docs.serve.zone/dcrouter) +- Issues: [https://github.com/serve-zone/dcrouter/issues](https://github.com/serve-zone/dcrouter/issues) +- Community: [https://community.serve.zone](https://community.serve.zone) \ No newline at end of file