# @serve.zone/dcrouter ![](https://code.foss.global/serve.zone/docs/raw/branch/main/dcrouter.png) **dcrouter: The all-in-one gateway for your datacenter.** 🚀 A comprehensive traffic routing solution that provides unified gateway capabilities for HTTP/HTTPS, TCP/SNI, email (SMTP), DNS, and RADIUS protocols. Designed for enterprises requiring robust traffic management, automatic TLS certificate provisioning, and enterprise-grade email infrastructure — all from a single process. ## Issue Reporting and Security For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly. ## Table of Contents - [Features](#features) - [Installation](#installation) - [Quick Start](#quick-start) - [Architecture](#architecture) - [Configuration Reference](#configuration-reference) - [HTTP/HTTPS & TCP/SNI Routing](#httphttps--tcpsni-routing) - [Email System](#email-system) - [DNS Server](#dns-server) - [RADIUS Server](#radius-server) - [Storage & Caching](#storage--caching) - [Security Features](#security-features) - [OpsServer Dashboard](#opsserver-dashboard) - [API Reference](#api-reference) - [Sub-Modules](#sub-modules) - [Testing](#testing) - [License and Legal Information](#license-and-legal-information) ## Features ### 🌐 Universal Traffic Router - **HTTP/HTTPS routing** with domain matching, path-based forwarding, and automatic TLS - **TCP/SNI proxy** for any protocol with TLS termination or passthrough - **DNS server** (Rust-powered via [SmartDNS](https://code.foss.global/push.rocks/smartdns)) with authoritative zones, dynamic record management, and DNS-over-HTTPS - **Multi-protocol support** on the same infrastructure via [SmartProxy](https://code.foss.global/push.rocks/smartproxy) ### 📧 Complete Email Infrastructure (powered by [smartmta](https://code.foss.global/push.rocks/smartmta)) - **Multi-domain SMTP server** on standard ports (25, 587, 465) - **Pattern-based email routing** with four action types: forward, process, deliver, reject - **DKIM signing & verification**, SPF, DMARC authentication stack - **Enterprise deliverability** with IP warmup schedules and sender reputation tracking - **Bounce handling** with automatic suppression lists - **Hierarchical rate limiting** — global, per-domain, per-sender ### 🔒 Enterprise Security - **Automatic TLS certificates** via ACME with Cloudflare DNS-01 challenges - **IP reputation checking** with caching and configurable thresholds - **Content scanning** for spam, viruses, and malicious attachments - **Security event logging** with structured audit trails ### 📡 RADIUS Server - **MAC Authentication Bypass (MAB)** for network device authentication - **VLAN assignment** based on exact MAC, OUI prefix, or wildcard patterns - **RADIUS accounting** for session tracking, traffic metering, and billing - **Real-time management** via OpsServer API ### ⚡ High Performance - **Rust-powered proxy engine** via SmartProxy for maximum throughput - **Rust-powered MTA engine** via smartmta (TypeScript + Rust hybrid) for reliable email delivery - **Rust-powered DNS engine** via SmartDNS for high-performance UDP and DNS-over-HTTPS - **Connection pooling** for outbound SMTP and backend services - **Socket-handler mode** — direct socket passing eliminates internal port hops - **Real-time metrics** via SmartMetrics (CPU, memory, connections, throughput) ### 💾 Persistent Storage & Caching - **Multiple storage backends**: filesystem, custom functions, or in-memory - **Embedded cache database** via smartdata + LocalTsmDb (MongoDB-compatible) - **Automatic TTL-based cleanup** for cached emails and IP reputation data ### 🖥️ OpsServer Dashboard - **Web-based management interface** with real-time monitoring - **JWT authentication** with session persistence - **Live views** for connections, email queues, DNS queries, RADIUS sessions, and security events - **Read-only configuration display** — DcRouter is configured through code ## Installation ```bash pnpm add @serve.zone/dcrouter # or npm install @serve.zone/dcrouter ``` ### Prerequisites - **Node.js 20+** with ES module support - Valid domain with DNS control (for ACME certificate automation) - Cloudflare API token (for DNS-01 challenges) — optional ## Quick Start ### Basic HTTP/HTTPS Router ```typescript import { DcRouter } from '@serve.zone/dcrouter'; const router = new DcRouter({ smartProxyConfig: { routes: [ { name: 'web-app', match: { domains: ['example.com', 'www.example.com'], ports: [443] }, action: { type: 'forward', targets: [{ host: '192.168.1.10', port: 8080 }], tls: { mode: 'terminate', certificate: 'auto' } } } ], acme: { email: 'admin@example.com', enabled: true, useProduction: true } } }); await router.start(); ``` ### Basic Email Server ```typescript import { DcRouter } from '@serve.zone/dcrouter'; const router = new DcRouter({ emailConfig: { ports: [25, 587, 465], hostname: 'mail.example.com', domains: [ { domain: 'example.com', dnsMode: 'external-dns' } ], routes: [ { name: 'process-all', match: { recipients: '*@example.com' }, action: { type: 'process', process: { scan: true, dkim: true, queue: 'normal' } } } ] } }); await router.start(); ``` ### Full Stack with Dashboard ```typescript import { DcRouter } from '@serve.zone/dcrouter'; const router = new DcRouter({ // HTTP/HTTPS routing smartProxyConfig: { routes: [ { name: 'website', match: { domains: ['example.com'], ports: [443] }, action: { type: 'forward', targets: [{ host: '192.168.1.10', port: 80 }], tls: { mode: 'terminate', certificate: 'auto' } } } ], acme: { email: 'ssl@example.com', enabled: true, useProduction: true } }, // Email system (powered by smartmta) emailConfig: { ports: [25, 587, 465], hostname: 'mail.example.com', domains: [{ domain: 'example.com', dnsMode: 'external-dns' }], routes: [ { name: 'inbound-mail', match: { recipients: '*@example.com' }, action: { type: 'process', process: { scan: true, dkim: true, queue: 'normal' } } } ] }, // Authoritative DNS dnsNsDomains: ['ns1.example.com', 'ns2.example.com'], dnsScopes: ['example.com'], publicIp: '203.0.113.1', dnsRecords: [ { name: 'example.com', type: 'A', value: '203.0.113.1' }, { name: 'www.example.com', type: 'CNAME', value: 'example.com' } ], // RADIUS authentication radiusConfig: { authPort: 1812, acctPort: 1813, clients: [ { name: 'switch-1', ipRange: '192.168.1.0/24', secret: 'radius-secret', enabled: true } ], vlanAssignment: { defaultVlan: 100, allowUnknownMacs: true, mappings: [ { mac: 'aa:bb:cc:dd:ee:ff', vlan: 10, enabled: true }, { mac: 'aa:bb:cc', vlan: 20, enabled: true } // OUI prefix ] }, accounting: { enabled: true, retentionDays: 30 } }, // Persistent storage storage: { fsPath: '/var/lib/dcrouter/data' }, // Cache database cacheConfig: { enabled: true, storagePath: '/etc/dcrouter/tsmdb' }, // TLS & ACME tls: { contactEmail: 'admin@example.com' }, dnsChallenge: { cloudflareApiKey: process.env.CLOUDFLARE_API_KEY } }); await router.start(); // OpsServer dashboard available at http://localhost:3000 ``` ## Architecture ### System Overview ```mermaid graph TB subgraph "External Traffic" HTTP[HTTP/HTTPS Clients] SMTP[SMTP Clients] TCP[TCP Clients] DNS[DNS Queries] RAD[RADIUS Clients] end subgraph "DcRouter Core" DC[DcRouter Orchestrator] SP[SmartProxy Engine
Rust-powered] ES[smartmta Email Server
TypeScript + Rust] DS[SmartDNS Server
Rust-powered] RS[SmartRadius Server] CM[Certificate Manager] OS[OpsServer Dashboard] MM[Metrics Manager] SM[Storage Manager] CD[Cache Database] end subgraph "Backend Services" WEB[Web Services] MAIL[Mail Servers] DB[Databases] API[Internal APIs] end HTTP --> SP TCP --> SP SMTP --> ES DNS --> DS RAD --> RS DC --> SP DC --> ES DC --> DS DC --> RS DC --> CM DC --> OS DC --> MM DC --> SM DC --> CD SP --> WEB SP --> API ES --> MAIL ES --> DB CM -.-> SP CM -.-> ES ``` ### Core Components | Component | Package | Description | |-----------|---------|-------------| | **DcRouter** | `@serve.zone/dcrouter` | Central orchestrator — starts, stops, and coordinates all services | | **SmartProxy** | `@push.rocks/smartproxy` | High-performance HTTP/HTTPS and TCP/SNI proxy with route-based config (Rust engine) | | **UnifiedEmailServer** | `@push.rocks/smartmta` | Full SMTP server with pattern-based routing, DKIM, queue management (TypeScript + Rust) | | **DNS Server** | `@push.rocks/smartdns` | Authoritative DNS with dynamic records and DKIM TXT auto-generation (Rust engine) | | **RADIUS Server** | `@push.rocks/smartradius` | Network authentication with MAB, VLAN assignment, and accounting | | **OpsServer** | `@api.global/typedserver` | Web dashboard + TypedRequest API for monitoring and management | | **MetricsManager** | `@push.rocks/smartmetrics` | Real-time metrics collection (CPU, memory, email, DNS, security) | | **StorageManager** | built-in | Pluggable key-value storage (filesystem, custom, or in-memory) | | **CacheDb** | `@push.rocks/smartdata` | Embedded MongoDB-compatible database (LocalTsmDb) for persistent caching | ### How It Works DcRouter acts purely as an **orchestrator** — it doesn't implement protocols itself. Instead, it wires together best-in-class packages for each protocol: 1. **On `start()`**: DcRouter initializes OpsServer (port 3000), then spins up SmartProxy, smartmta, SmartDNS, and SmartRadius based on which configs are provided. 2. **During operation**: Each service handles its own protocol independently. SmartProxy uses a Rust-powered engine for maximum throughput. smartmta uses a hybrid TypeScript + Rust architecture for reliable email delivery. 3. **On `stop()`**: All services are gracefully shut down in reverse order. ### Rust-Powered Architecture DcRouter itself is a pure TypeScript orchestrator, but three of its core sub-components ship with **compiled Rust binaries** for performance-critical paths. At runtime each package detects the platform, unpacks the correct binary, and communicates with TypeScript over IPC/FFI — so you get the ergonomics of TypeScript with the throughput of native code. | Component | Rust Binary | What It Handles | |-----------|-------------|-----------------| | **SmartProxy** | `smartproxy-bin` | All TCP/TLS/HTTP proxy networking, NFTables integration, connection metrics | | **smartmta** | `mailer-bin` | SMTP server + client, DKIM/SPF/DMARC, content scanning, IP reputation | | **SmartDNS** | `smartdns-bin` | DNS server (UDP + DNS-over-HTTPS), DNSSEC, DNS client resolution | | **SmartRadius** | — | Pure TypeScript (no Rust component) | ## Configuration Reference ### `IDcRouterOptions` ```typescript interface IDcRouterOptions { // ── Traffic Routing ──────────────────────────────────────────── /** SmartProxy config for HTTP/HTTPS and TCP/SNI routing */ smartProxyConfig?: ISmartProxyOptions; // ── Email ────────────────────────────────────────────────────── /** Unified email server configuration (smartmta) */ emailConfig?: IUnifiedEmailServerOptions; /** Custom email port mapping overrides */ emailPortConfig?: { portMapping?: Record; portSettings?: Record; receivedEmailsPath?: string; }; // ── DNS ──────────────────────────────────────────────────────── /** Nameserver domains — get A records automatically */ dnsNsDomains?: string[]; /** Domains this server is authoritative for */ dnsScopes?: string[]; /** Public IP for NS A records */ publicIp?: string; /** Ingress proxy IPs (hides real server IP) */ proxyIps?: string[]; /** Custom DNS records */ dnsRecords?: Array<{ name: string; type: 'A' | 'AAAA' | 'CNAME' | 'MX' | 'TXT' | 'NS' | 'SOA'; value: string; ttl?: number; useIngressProxy?: boolean; }>; // ── RADIUS ───────────────────────────────────────────────────── /** RADIUS server for network authentication */ radiusConfig?: { authPort?: number; // default: 1812 acctPort?: number; // default: 1813 clients: IRadiusClient[]; vlanAssignment?: IVlanManagerConfig; accounting?: { enabled: boolean; retentionDays?: number }; }; // ── TLS & Certificates ──────────────────────────────────────── tls?: { contactEmail: string; domain?: string; certPath?: string; keyPath?: string; }; dnsChallenge?: { cloudflareApiKey?: string }; // ── Storage & Caching ───────────────────────────────────────── storage?: { fsPath?: string; readFunction?: (key: string) => Promise; writeFunction?: (key: string, value: string) => Promise; }; cacheConfig?: { enabled?: boolean; // default: true storagePath?: string; // default: '/etc/dcrouter/tsmdb' dbName?: string; // default: 'dcrouter' cleanupIntervalHours?: number; // default: 1 ttlConfig?: { emails?: number; // default: 30 days ipReputation?: number; // default: 1 day bounces?: number; // default: 30 days dkimKeys?: number; // default: 90 days suppression?: number; // default: 30 days }; }; } ``` ## HTTP/HTTPS & TCP/SNI Routing DcRouter uses [SmartProxy](https://code.foss.global/push.rocks/smartproxy) for all HTTP/HTTPS and TCP/SNI routing. Routes are pattern-matched by domain, port, or both. ### HTTPS with Auto-TLS ```typescript { name: 'api-gateway', match: { domains: ['api.example.com'], ports: [443] }, action: { type: 'forward', targets: [{ host: '192.168.1.20', port: 8080 }], tls: { mode: 'terminate', certificate: 'auto' } } } ``` ### TLS Passthrough (SNI Routing) ```typescript { name: 'secure-backend', match: { domains: ['secure.example.com'], ports: [8443] }, action: { type: 'forward', targets: [{ host: '192.168.1.40', port: 8443 }], tls: { mode: 'passthrough' } } } ``` ### TCP Port Range Forwarding ```typescript { name: 'database-cluster', match: { ports: [{ from: 5432, to: 5439 }] }, action: { type: 'forward', targets: [{ host: '192.168.1.30', port: 'preserve' }], security: { ipAllowList: ['192.168.1.0/24'] } } } ``` ### HTTP Redirect ```typescript { name: 'http-to-https', match: { ports: [80] }, action: { type: 'redirect', redirect: { to: 'https://{domain}{path}' } } } ``` ## Email System The email system is powered by [`@push.rocks/smartmta`](https://code.foss.global/push.rocks/smartmta), a TypeScript + Rust hybrid MTA. DcRouter configures and orchestrates smartmta's **UnifiedEmailServer**, which handles SMTP sessions, route matching, delivery queuing, DKIM signing, and all email processing. ### Email Domain Configuration Domains define _infrastructure_ — how DNS and DKIM are handled for each domain: #### Forward Mode Simple forwarding without local DNS management: ```typescript { domain: 'forwarded.com', dnsMode: 'forward', dns: { forward: { skipDnsValidation: true, targetDomain: 'mail.target.com' } } } ``` #### Internal DNS Mode Uses DcRouter's built-in DNS server (requires `dnsNsDomains` + `dnsScopes`): ```typescript { domain: 'mail.example.com', dnsMode: 'internal-dns', dns: { internal: { mxPriority: 10, ttl: 3600 } }, dkim: { selector: 'mail2024', keySize: 2048, rotateKeys: true, rotationInterval: 90 } } ``` #### External DNS Mode Uses existing DNS infrastructure with validation: ```typescript { domain: 'mail.external.com', dnsMode: 'external-dns', dns: { external: { requiredRecords: ['MX', 'SPF', 'DKIM', 'DMARC'] } }, rateLimits: { inbound: { messagesPerMinute: 100, connectionsPerIp: 10 }, outbound: { messagesPerMinute: 200 } } } ``` ### Email Route Actions Routes define _behavior_ — what happens when an email matches: #### Forward 📤 Routes emails to an external SMTP server: ```typescript { name: 'forward-to-internal', match: { recipients: '*@company.com' }, action: { type: 'forward', forward: { host: 'internal-mail.company.com', port: 25, auth: { user: 'relay-user', pass: 'relay-pass' }, addHeaders: { 'X-Forwarded-By': 'dcrouter' } } } } ``` #### Process ⚙️ Full MTA processing with content scanning and delivery queues: ```typescript { name: 'process-notifications', match: { recipients: '*@notifications.company.com' }, action: { type: 'process', process: { scan: true, dkim: true, queue: 'priority' } } } ``` #### Deliver 📥 Local mailbox delivery: ```typescript { name: 'deliver-local', match: { recipients: '*@local.company.com' }, action: { type: 'deliver' } } ``` #### Reject 🚫 Reject with custom SMTP response code: ```typescript { name: 'reject-spam-domain', match: { senders: '*@spam-domain.com', sizeRange: { min: 1000000 } }, action: { type: 'reject', reject: { code: 550, message: 'Message rejected due to policy' } } } ``` ### Route Matching Routes support powerful matching criteria: ```typescript // Recipient patterns match: { recipients: '*@example.com' } // All addresses at domain match: { recipients: 'admin@*' } // "admin" at any domain match: { senders: ['*@trusted.com', '*@vip.com'] } // Multiple sender patterns // IP-based matching (CIDR) match: { clientIp: '192.168.0.0/16' } match: { clientIp: ['10.0.0.0/8', '172.16.0.0/12'] } // Authentication state match: { authenticated: true } // Header matching match: { headers: { 'X-Priority': 'high', 'Subject': /urgent|emergency/i } } // Size and content match: { sizeRange: { min: 1000, max: 5000000 }, hasAttachments: true } match: { subject: /invoice|receipt/i } ``` ### Socket-Handler Mode 🔌 When `useSocketHandler: true` is set, SmartProxy passes sockets directly to the email server — no internal port binding, lower latency, and fewer open ports: ``` Traditional: External Port → SmartProxy → Internal Port → Email Server Socket Mode: External Port → SmartProxy → (direct socket) → Email Server ``` ### Email Security Stack - **DKIM** — Automatic key generation, signing, and rotation for all domains - **SPF** — Sender Policy Framework verification on inbound mail - **DMARC** — Domain-based Message Authentication verification - **IP Reputation** — Real-time IP reputation checking with caching - **Content Scanning** — Spam, virus, and attachment scanning - **Rate Limiting** — Hierarchical limits (global → domain → sender) - **Bounce Management** — Automatic bounce detection and suppression lists ### Email Deliverability - **IP Warmup Manager** — Multi-stage warmup schedules for new IPs - **Sender Reputation Monitor** — Per-domain reputation tracking and scoring - **Connection Pooling** — Pooled outbound SMTP connections per destination ## DNS Server DcRouter includes an authoritative DNS server built on [smartdns](https://code.foss.global/push.rocks/smartdns). It handles standard UDP DNS on port 53 and DNS-over-HTTPS via SmartProxy socket handler. ### Enabling DNS DNS is activated when both `dnsNsDomains` and `dnsScopes` are configured: ```typescript const router = new DcRouter({ dnsNsDomains: ['ns1.example.com', 'ns2.example.com'], dnsScopes: ['example.com'], publicIp: '203.0.113.1', dnsRecords: [ { name: 'example.com', type: 'A', value: '203.0.113.1' }, { name: 'www.example.com', type: 'CNAME', value: 'example.com' }, { name: 'example.com', type: 'MX', value: '10:mail.example.com' }, { name: 'example.com', type: 'TXT', value: 'v=spf1 a mx ~all' } ] }); ``` ### Automatic DNS Records DcRouter auto-generates: - **NS records** for all domains in `dnsScopes` - **SOA records** for authoritative zones - **A records** for nameserver domains (`dnsNsDomains`) - **MX, SPF, DKIM, DMARC records** for email domains with `internal-dns` mode - **ACME challenge records** for certificate provisioning ### Ingress Proxy Support When `proxyIps` is configured, A records with `useIngressProxy: true` (default) will use the proxy IP instead of the real server IP — hiding your origin: ```typescript { proxyIps: ['198.51.100.1', '198.51.100.2'], dnsRecords: [ { name: 'example.com', type: 'A', value: '203.0.113.1' }, // Will resolve to 198.51.100.1 { name: 'ns1.example.com', type: 'A', value: '203.0.113.1', useIngressProxy: false } // Stays real IP ] } ``` ## RADIUS Server DcRouter includes a RADIUS server for network access control, built on [smartradius](https://code.foss.global/push.rocks/smartradius). ### Configuration ```typescript const router = new DcRouter({ radiusConfig: { authPort: 1812, acctPort: 1813, clients: [ { name: 'core-switch', ipRange: '192.168.1.0/24', secret: 'shared-secret', enabled: true } ], vlanAssignment: { defaultVlan: 100, allowUnknownMacs: true, mappings: [ { mac: 'aa:bb:cc:dd:ee:ff', vlan: 10, enabled: true }, // Exact MAC { mac: 'aa:bb:cc', vlan: 20, enabled: true }, // OUI prefix ] }, accounting: { enabled: true, retentionDays: 30 } } }); ``` ### Components | Component | Purpose | |-----------|---------| | **RadiusServer** | Main RADIUS server handling auth + accounting requests | | **VlanManager** | MAC-to-VLAN mapping with exact, OUI, and wildcard patterns | | **AccountingManager** | Session tracking, traffic metering, start/stop/interim updates | ### OpsServer API RADIUS is fully manageable at runtime via the OpsServer API: - Client management (add/remove/list NAS devices) - VLAN mapping CRUD operations - Session monitoring and forced disconnects - Accounting summaries and statistics ## Storage & Caching ### StorageManager Provides a unified key-value interface with three backends: ```typescript // Filesystem backend storage: { fsPath: '/var/lib/dcrouter/data' } // Custom backend (Redis, S3, etc.) storage: { readFunction: async (key) => await redis.get(key), writeFunction: async (key, value) => await redis.set(key, value) } // In-memory (development only — data lost on restart) // Simply omit the storage config ``` Used for: DKIM keys, email routes, bounce/suppression lists, IP reputation data, domain configs. ### Cache Database An embedded MongoDB-compatible database (via smartdata + LocalTsmDb) for persistent caching with automatic TTL cleanup: ```typescript cacheConfig: { enabled: true, storagePath: '/etc/dcrouter/tsmdb', dbName: 'dcrouter', cleanupIntervalHours: 1, ttlConfig: { emails: 30, // days ipReputation: 1, // days bounces: 30, // days dkimKeys: 90, // days suppression: 30 // days } } ``` Cached document types: `CachedEmail`, `CachedIPReputation`. ## Security Features ### IP Reputation Checking Automatic IP reputation checks on inbound connections with configurable caching: ```typescript // IP reputation is checked automatically for inbound SMTP connections. // Results are cached according to cacheConfig.ttlConfig.ipReputation. ``` ### Rate Limiting Hierarchical rate limits with three levels of specificity: ```typescript // Global defaults (via emailConfig.defaults.rateLimits) defaults: { rateLimits: { inbound: { messagesPerMinute: 50, connectionsPerIp: 5, recipientsPerMessage: 50 }, outbound: { messagesPerMinute: 100 } } } // Per-domain overrides (in domain config) { domain: 'high-volume.com', rateLimits: { outbound: { messagesPerMinute: 500 } // Override for this domain } } ``` **Precedence**: Domain-specific > Pattern-specific > Global ### Content Scanning ```typescript action: { type: 'process', options: { contentScanning: true, scanners: [ { type: 'spam', threshold: 5.0, action: 'tag' }, { type: 'virus', action: 'reject' }, { type: 'attachment', blockedExtensions: ['.exe', '.bat', '.scr'], action: 'reject' } ] } } ``` ## OpsServer Dashboard The OpsServer provides a web-based management interface served on port 3000. It's built with modern web components using [@design.estate/dees-catalog](https://code.foss.global/design.estate/dees-catalog). ### Dashboard Views | View | Description | |------|-------------| | 📊 **Overview** | Real-time server stats, CPU/memory, connection counts, email throughput | | 🌐 **Network** | Active connections, top IPs, throughput rates, SmartProxy metrics | | 📧 **Email** | Queue monitoring (queued/sent/failed), bounce records, security incidents | | 📜 **Logs** | Real-time log viewer with level filtering and search | | ⚙️ **Configuration** | Read-only view of current system configuration | | 🛡️ **Security** | IP reputation, rate limit status, blocked connections | ### API Endpoints All management is done via TypedRequest over HTTP POST to `/typedrequest`: ```typescript // Authentication 'adminLoginWithUsernameAndPassword' // Login with credentials → returns JWT identity 'verifyIdentity' // Verify JWT token validity 'adminLogout' // End admin session // Statistics & Health 'getServerStatistics' // Uptime, CPU, memory, connections 'getHealthStatus' // System health check 'getCombinedMetrics' // All metrics in one call // Email Operations 'getQueuedEmails' // Emails pending delivery 'getSentEmails' // Successfully delivered emails 'getFailedEmails' // Failed emails 'resendEmail' // Re-queue a failed email 'getBounceRecords' // Bounce records 'removeFromSuppressionList' // Unsuppress an address // Configuration (read-only) 'getConfiguration' // Current system config // Logs 'getLogs' // Retrieve system logs // RADIUS 'getRadiusSessions' // Active RADIUS sessions 'getRadiusClients' // List NAS clients 'getRadiusStatistics' // RADIUS stats 'setRadiusClient' // Add/update NAS client 'removeRadiusClient' // Remove NAS client 'getVlanMappings' // List VLAN mappings 'setVlanMapping' // Add/update VLAN mapping 'removeVlanMapping' // Remove VLAN mapping 'testVlanAssignment' // Test what VLAN a MAC gets ``` ## API Reference ### DcRouter Class ```typescript import { DcRouter } from '@serve.zone/dcrouter'; const router = new DcRouter(options: IDcRouterOptions); ``` #### Methods | Method | Description | |--------|-------------| | `start(): Promise` | Start all configured services | | `stop(): Promise` | Gracefully stop all services | | `updateSmartProxyConfig(config): Promise` | Hot-update SmartProxy routes | | `updateEmailConfig(config): Promise` | Hot-update email configuration | | `updateEmailRoutes(routes): Promise` | Update email routing rules at runtime | | `updateRadiusConfig(config): Promise` | Hot-update RADIUS configuration | | `getStats(): any` | Get real-time statistics from all services | #### Properties | Property | Type | Description | |----------|------|-------------| | `options` | `IDcRouterOptions` | Current configuration | | `smartProxy` | `SmartProxy` | SmartProxy instance | | `emailServer` | `UnifiedEmailServer` | Email server instance (from smartmta) | | `dnsServer` | `DnsServer` | DNS server instance | | `radiusServer` | `RadiusServer` | RADIUS server instance | | `storageManager` | `StorageManager` | Storage backend | | `opsServer` | `OpsServer` | OpsServer/dashboard instance | | `metricsManager` | `MetricsManager` | Metrics collector | | `cacheDb` | `CacheDb` | Cache database instance | ### Re-exported Types DcRouter re-exports key types from smartmta for convenience: ```typescript import { DcRouter, IDcRouterOptions, UnifiedEmailServer, type IUnifiedEmailServerOptions, type IEmailRoute, type IEmailDomainConfig, } from '@serve.zone/dcrouter'; ``` ## Sub-Modules DcRouter is published as a monorepo with separately-installable interface and web packages: | Package | Description | Install | |---------|-------------|---------| | [`@serve.zone/dcrouter`](https://www.npmjs.com/package/@serve.zone/dcrouter) | Main package — the full router | `pnpm add @serve.zone/dcrouter` | | [`@serve.zone/dcrouter-interfaces`](https://www.npmjs.com/package/@serve.zone/dcrouter-interfaces) | TypedRequest interfaces for the OpsServer API | `pnpm add @serve.zone/dcrouter-interfaces` | | [`@serve.zone/dcrouter-web`](https://www.npmjs.com/package/@serve.zone/dcrouter-web) | Web dashboard components | `pnpm add @serve.zone/dcrouter-web` | You can also import interfaces directly from the main package: ```typescript import { data, requests } from '@serve.zone/dcrouter/interfaces'; ``` ## Testing DcRouter includes a comprehensive test suite covering all system components: ```bash # Run all tests (10 files, 73 tests) pnpm test # Run a specific test file tstest test/test.jwt-auth.ts --verbose # Run with extended timeout tstest test/test.opsserver-api.ts --verbose --timeout 60 ``` ### Test Coverage | Test File | Area | Tests | |-----------|------|-------| | `test.contentscanner.ts` | Content scanning (spam, phishing, malware, attachments) | 13 | | `test.dcrouter.email.ts` | Email config, domain and route setup | 4 | | `test.dns-server-config.ts` | DNS record parsing, grouping, extraction | 5 | | `test.dns-socket-handler.ts` | DNS socket handler and route generation | 6 | | `test.errors.ts` | Error classes, handler, retry utilities | 5 | | `test.ipreputationchecker.ts` | IP reputation, DNSBL, caching, risk classification | 10 | | `test.jwt-auth.ts` | JWT login, verification, logout, invalid credentials | 8 | | `test.opsserver-api.ts` | Health, statistics, configuration, log APIs | 6 | | `test.protected-endpoint.ts` | Admin auth, identity verification, public endpoints | 8 | | `test.storagemanager.ts` | Memory, filesystem, custom backends, concurrency | 8 | ## License and Legal Information This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. ### Trademarks This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar. ### Company Information Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany For any legal inquiries or further information, please contact us via email at hello@task.vc. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.