2025-05-08 01:13:54 +00:00
|
|
|
import * as plugins from './plugins.js';
|
|
|
|
import * as paths from './paths.js';
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-07 22:06:55 +00:00
|
|
|
// Certificate types are available via plugins.tsclass
|
2025-05-07 14:33:20 +00:00
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
// Import the consolidated email config
|
2025-05-08 01:13:54 +00:00
|
|
|
import type { IEmailConfig, IDomainRule } from './mail/routing/classes.email.config.js';
|
2025-05-24 01:00:30 +00:00
|
|
|
import type { EmailProcessingMode } from './mail/delivery/interfaces.js';
|
2025-05-08 01:13:54 +00:00
|
|
|
import { DomainRouter } from './mail/routing/classes.domain.router.js';
|
|
|
|
import { UnifiedEmailServer } from './mail/routing/classes.unified.email.server.js';
|
|
|
|
import { UnifiedDeliveryQueue, type IQueueOptions } from './mail/delivery/classes.delivery.queue.js';
|
|
|
|
import { MultiModeDeliverySystem, type IMultiModeDeliveryOptions } from './mail/delivery/classes.delivery.system.js';
|
|
|
|
import { UnifiedRateLimiter, type IHierarchicalRateLimits } from './mail/delivery/classes.unified.rate.limiter.js';
|
|
|
|
import { logger } from './logger.js';
|
2025-05-21 00:12:49 +00:00
|
|
|
// Import the email configuration helpers directly from mail/delivery
|
|
|
|
import { configureEmailStorage, configureEmailServer } from './mail/delivery/index.js';
|
2025-05-07 23:04:54 +00:00
|
|
|
|
|
|
|
export interface IDcRouterOptions {
|
2025-05-07 23:45:19 +00:00
|
|
|
/**
|
|
|
|
* Direct SmartProxy configuration - gives full control over HTTP/HTTPS and TCP/SNI traffic
|
|
|
|
* This is the preferred way to configure HTTP/HTTPS and general TCP/SNI traffic
|
|
|
|
*/
|
|
|
|
smartProxyConfig?: plugins.smartproxy.ISmartProxyOptions;
|
|
|
|
|
|
|
|
/**
|
2025-05-08 00:12:36 +00:00
|
|
|
* Consolidated email configuration
|
|
|
|
* This enables all email handling with pattern-based routing
|
2025-05-07 23:45:19 +00:00
|
|
|
*/
|
2025-05-08 00:12:36 +00:00
|
|
|
emailConfig?: IEmailConfig;
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-20 11:04:09 +00:00
|
|
|
/**
|
|
|
|
* Custom email port configuration
|
|
|
|
* Allows configuring specific ports for email handling
|
|
|
|
* This overrides the default port mapping in the emailConfig
|
|
|
|
*/
|
|
|
|
emailPortConfig?: {
|
|
|
|
/** External to internal port mapping */
|
|
|
|
portMapping?: Record<number, number>;
|
|
|
|
/** Custom port configuration for specific ports */
|
|
|
|
portSettings?: Record<number, any>;
|
|
|
|
/** Path to store received emails */
|
|
|
|
receivedEmailsPath?: string;
|
|
|
|
};
|
|
|
|
|
2025-05-07 23:04:54 +00:00
|
|
|
/** TLS/certificate configuration */
|
|
|
|
tls?: {
|
|
|
|
/** Contact email for ACME certificates */
|
|
|
|
contactEmail: string;
|
|
|
|
/** Domain for main certificate */
|
|
|
|
domain?: string;
|
|
|
|
/** Path to certificate file (if not using auto-provisioning) */
|
|
|
|
certPath?: string;
|
|
|
|
/** Path to key file (if not using auto-provisioning) */
|
|
|
|
keyPath?: string;
|
2025-05-21 00:12:49 +00:00
|
|
|
/** Path to CA certificate file (for custom CAs) */
|
|
|
|
caPath?: string;
|
2025-05-07 23:04:54 +00:00
|
|
|
};
|
|
|
|
|
2025-05-07 14:33:20 +00:00
|
|
|
/** DNS server configuration */
|
2025-05-04 10:10:07 +00:00
|
|
|
dnsServerConfig?: plugins.smartdns.IDnsServerOptions;
|
2025-05-19 17:34:48 +00:00
|
|
|
|
|
|
|
/** DNS challenge configuration for ACME (optional) */
|
|
|
|
dnsChallenge?: {
|
|
|
|
/** Cloudflare API key for DNS challenges */
|
|
|
|
cloudflareApiKey?: string;
|
|
|
|
/** Other DNS providers can be added here */
|
|
|
|
};
|
2025-05-04 10:10:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* DcRouter can be run on ingress and egress to and from a datacenter site.
|
|
|
|
*/
|
2025-05-07 14:33:20 +00:00
|
|
|
/**
|
|
|
|
* Context passed to HTTP routing rules
|
|
|
|
*/
|
|
|
|
/**
|
|
|
|
* Context passed to port proxy (SmartProxy) routing rules
|
|
|
|
*/
|
|
|
|
export interface PortProxyRuleContext {
|
|
|
|
proxy: plugins.smartproxy.SmartProxy;
|
2025-05-16 15:50:46 +00:00
|
|
|
routes: plugins.smartproxy.IRouteConfig[];
|
2025-05-07 14:33:20 +00:00
|
|
|
}
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-04 10:10:07 +00:00
|
|
|
export class DcRouter {
|
2025-05-07 14:33:20 +00:00
|
|
|
public options: IDcRouterOptions;
|
2025-05-07 23:04:54 +00:00
|
|
|
|
|
|
|
// Core services
|
2025-05-07 14:33:20 +00:00
|
|
|
public smartProxy?: plugins.smartproxy.SmartProxy;
|
|
|
|
public dnsServer?: plugins.smartdns.DnsServer;
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
// Unified email components
|
|
|
|
public domainRouter?: DomainRouter;
|
2025-05-08 00:39:43 +00:00
|
|
|
public unifiedEmailServer?: UnifiedEmailServer;
|
|
|
|
public deliveryQueue?: UnifiedDeliveryQueue;
|
|
|
|
public deliverySystem?: MultiModeDeliverySystem;
|
|
|
|
public rateLimiter?: UnifiedRateLimiter;
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-20 11:04:09 +00:00
|
|
|
|
2025-05-07 23:04:54 +00:00
|
|
|
// Environment access
|
|
|
|
private qenv = new plugins.qenv.Qenv('./', '.nogit/');
|
|
|
|
|
2025-05-21 02:17:18 +00:00
|
|
|
constructor(optionsArg: IDcRouterOptions) {
|
2025-05-07 22:06:55 +00:00
|
|
|
// Set defaults in options
|
|
|
|
this.options = {
|
|
|
|
...optionsArg
|
|
|
|
};
|
2025-05-20 11:04:09 +00:00
|
|
|
|
2025-05-07 14:33:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async start() {
|
2025-05-07 23:04:54 +00:00
|
|
|
console.log('Starting DcRouter services...');
|
|
|
|
|
|
|
|
try {
|
2025-05-16 15:50:46 +00:00
|
|
|
// Set up SmartProxy for HTTP/HTTPS and all traffic including email routes
|
|
|
|
await this.setupSmartProxy();
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
// Set up unified email handling if configured
|
|
|
|
if (this.options.emailConfig) {
|
|
|
|
await this.setupUnifiedEmailHandling();
|
2025-05-20 11:04:09 +00:00
|
|
|
|
|
|
|
// Apply custom email storage configuration if available
|
2025-05-21 00:12:49 +00:00
|
|
|
if (this.unifiedEmailServer && this.options.emailPortConfig?.receivedEmailsPath) {
|
2025-05-20 11:04:09 +00:00
|
|
|
logger.log('info', 'Applying custom email storage configuration');
|
2025-05-21 00:12:49 +00:00
|
|
|
configureEmailStorage(this.unifiedEmailServer, this.options);
|
2025-05-20 11:04:09 +00:00
|
|
|
}
|
2025-05-07 23:04:54 +00:00
|
|
|
}
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Set up DNS server if configured
|
2025-05-07 23:04:54 +00:00
|
|
|
if (this.options.dnsServerConfig) {
|
|
|
|
this.dnsServer = new plugins.smartdns.DnsServer(this.options.dnsServerConfig);
|
|
|
|
await this.dnsServer.start();
|
|
|
|
console.log('DNS server started');
|
|
|
|
}
|
|
|
|
|
|
|
|
console.log('DcRouter started successfully');
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error starting DcRouter:', error);
|
|
|
|
// Try to clean up any services that may have started
|
|
|
|
await this.stop();
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2025-05-16 15:50:46 +00:00
|
|
|
* Set up SmartProxy with direct configuration and automatic email routes
|
2025-05-07 23:04:54 +00:00
|
|
|
*/
|
2025-05-07 23:45:19 +00:00
|
|
|
private async setupSmartProxy(): Promise<void> {
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log('[DcRouter] Setting up SmartProxy...');
|
2025-05-16 15:50:46 +00:00
|
|
|
let routes: plugins.smartproxy.IRouteConfig[] = [];
|
|
|
|
let acmeConfig: plugins.smartproxy.IAcmeOptions | undefined;
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// If user provides full SmartProxy config, use it directly
|
|
|
|
if (this.options.smartProxyConfig) {
|
|
|
|
routes = this.options.smartProxyConfig.routes || [];
|
|
|
|
acmeConfig = this.options.smartProxyConfig.acme;
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log(`[DcRouter] Found ${routes.length} routes in config`);
|
|
|
|
console.log(`[DcRouter] ACME config present: ${!!acmeConfig}`);
|
2025-05-16 15:50:46 +00:00
|
|
|
}
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// If email config exists, automatically add email routes
|
|
|
|
if (this.options.emailConfig) {
|
|
|
|
const emailRoutes = this.generateEmailRoutes(this.options.emailConfig);
|
2025-05-20 19:46:59 +00:00
|
|
|
console.log(`Email Routes are:`)
|
|
|
|
console.log(emailRoutes)
|
2025-05-21 00:12:49 +00:00
|
|
|
routes = [...routes, ...emailRoutes]; // Enable email routing through SmartProxy
|
2025-05-16 15:50:46 +00:00
|
|
|
}
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Merge TLS/ACME configuration if provided at root level
|
|
|
|
if (this.options.tls && !acmeConfig) {
|
|
|
|
acmeConfig = {
|
|
|
|
accountEmail: this.options.tls.contactEmail,
|
|
|
|
enabled: true,
|
|
|
|
useProduction: true,
|
|
|
|
autoRenew: true,
|
|
|
|
renewThresholdDays: 30
|
|
|
|
};
|
|
|
|
}
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-19 17:34:48 +00:00
|
|
|
// Configure DNS challenge if available
|
|
|
|
let challengeHandlers: any[] = [];
|
|
|
|
if (this.options.dnsChallenge?.cloudflareApiKey) {
|
|
|
|
console.log('Configuring Cloudflare DNS challenge for ACME');
|
|
|
|
const cloudflareAccount = new plugins.cloudflare.CloudflareAccount(this.options.dnsChallenge.cloudflareApiKey);
|
|
|
|
const dns01Handler = new plugins.smartacme.handlers.Dns01Handler(cloudflareAccount);
|
|
|
|
challengeHandlers.push(dns01Handler);
|
|
|
|
}
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// If we have routes or need a basic SmartProxy instance, create it
|
|
|
|
if (routes.length > 0 || this.options.smartProxyConfig) {
|
|
|
|
console.log('Setting up SmartProxy with combined configuration');
|
|
|
|
|
|
|
|
// Create SmartProxy configuration
|
|
|
|
const smartProxyConfig: plugins.smartproxy.ISmartProxyOptions = {
|
|
|
|
...this.options.smartProxyConfig,
|
|
|
|
routes,
|
|
|
|
acme: acmeConfig
|
|
|
|
};
|
|
|
|
|
2025-05-19 17:34:48 +00:00
|
|
|
// If we have DNS challenge handlers, enhance the config
|
|
|
|
if (challengeHandlers.length > 0) {
|
|
|
|
// We'll need to pass this to SmartProxy somehow
|
|
|
|
// For now, we'll set it as a property
|
|
|
|
(smartProxyConfig as any).acmeChallengeHandlers = challengeHandlers;
|
|
|
|
(smartProxyConfig as any).acmeChallengePriority = ['dns-01', 'http-01'];
|
|
|
|
}
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Create SmartProxy instance
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log('[DcRouter] Creating SmartProxy instance with config:', JSON.stringify({
|
|
|
|
routeCount: smartProxyConfig.routes?.length,
|
|
|
|
acmeEnabled: smartProxyConfig.acme?.enabled,
|
|
|
|
acmeEmail: smartProxyConfig.acme?.email,
|
|
|
|
certProvisionFunction: !!smartProxyConfig.certProvisionFunction
|
|
|
|
}, null, 2));
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
this.smartProxy = new plugins.smartproxy.SmartProxy(smartProxyConfig);
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Set up event listeners
|
|
|
|
this.smartProxy.on('error', (err) => {
|
2025-05-19 17:34:48 +00:00
|
|
|
console.error('[DcRouter] SmartProxy error:', err);
|
|
|
|
console.error('[DcRouter] Error stack:', err.stack);
|
2025-05-07 23:45:19 +00:00
|
|
|
});
|
2025-05-16 15:50:46 +00:00
|
|
|
|
|
|
|
if (acmeConfig) {
|
|
|
|
this.smartProxy.on('certificate-issued', (event) => {
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log(`[DcRouter] Certificate issued for ${event.domain}, expires ${event.expiryDate}`);
|
2025-05-16 15:50:46 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
this.smartProxy.on('certificate-renewed', (event) => {
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log(`[DcRouter] Certificate renewed for ${event.domain}, expires ${event.expiryDate}`);
|
|
|
|
});
|
|
|
|
|
|
|
|
this.smartProxy.on('certificate-failed', (event) => {
|
|
|
|
console.error(`[DcRouter] Certificate failed for ${event.domain}:`, event.error);
|
2025-05-16 15:50:46 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start SmartProxy
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log('[DcRouter] Starting SmartProxy...');
|
2025-05-16 15:50:46 +00:00
|
|
|
await this.smartProxy.start();
|
2025-05-19 17:34:48 +00:00
|
|
|
console.log('[DcRouter] SmartProxy started successfully');
|
2025-05-16 15:50:46 +00:00
|
|
|
|
|
|
|
console.log(`SmartProxy started with ${routes.length} routes`);
|
2025-05-07 23:45:19 +00:00
|
|
|
}
|
2025-05-07 23:04:54 +00:00
|
|
|
}
|
|
|
|
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-04 10:10:07 +00:00
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
/**
|
|
|
|
* Generate SmartProxy routes for email configuration
|
|
|
|
*/
|
|
|
|
private generateEmailRoutes(emailConfig: IEmailConfig): plugins.smartproxy.IRouteConfig[] {
|
|
|
|
const emailRoutes: plugins.smartproxy.IRouteConfig[] = [];
|
|
|
|
|
2025-05-20 11:04:09 +00:00
|
|
|
// Get the custom port mapping if available, otherwise use defaults
|
|
|
|
const defaultPortMapping = {
|
|
|
|
25: 10025, // SMTP
|
|
|
|
587: 10587, // Submission
|
|
|
|
465: 10465 // SMTPS
|
|
|
|
};
|
|
|
|
|
|
|
|
// Use custom port mapping if provided, otherwise fall back to defaults
|
|
|
|
const portMapping = this.options.emailPortConfig?.portMapping || defaultPortMapping;
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Create routes for each email port
|
|
|
|
for (const port of emailConfig.ports) {
|
2025-05-20 11:04:09 +00:00
|
|
|
// Calculate the internal port using the mapping
|
|
|
|
const internalPort = portMapping[port] || port + 10000;
|
|
|
|
|
|
|
|
// Create a descriptive name for the route based on the port
|
|
|
|
let routeName = 'email-route';
|
|
|
|
let tlsMode = 'passthrough';
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Handle different email ports differently
|
|
|
|
switch (port) {
|
|
|
|
case 25: // SMTP
|
2025-05-20 11:04:09 +00:00
|
|
|
routeName = 'smtp-route';
|
|
|
|
tlsMode = 'passthrough'; // STARTTLS handled by email server
|
2025-05-16 15:50:46 +00:00
|
|
|
break;
|
|
|
|
|
|
|
|
case 587: // Submission
|
2025-05-20 11:04:09 +00:00
|
|
|
routeName = 'submission-route';
|
|
|
|
tlsMode = 'passthrough'; // STARTTLS handled by email server
|
2025-05-16 15:50:46 +00:00
|
|
|
break;
|
|
|
|
|
|
|
|
case 465: // SMTPS
|
2025-05-20 11:04:09 +00:00
|
|
|
routeName = 'smtps-route';
|
|
|
|
tlsMode = 'terminate'; // Terminate TLS and re-encrypt to email server
|
|
|
|
break;
|
|
|
|
|
|
|
|
default:
|
|
|
|
routeName = `email-port-${port}-route`;
|
|
|
|
// For unknown ports, assume passthrough by default
|
|
|
|
tlsMode = 'passthrough';
|
|
|
|
|
|
|
|
// Check if we have specific settings for this port
|
|
|
|
if (this.options.emailPortConfig?.portSettings &&
|
|
|
|
this.options.emailPortConfig.portSettings[port]) {
|
|
|
|
const portSettings = this.options.emailPortConfig.portSettings[port];
|
|
|
|
|
|
|
|
// If this port requires TLS termination, set the mode accordingly
|
|
|
|
if (portSettings.terminateTls) {
|
|
|
|
tlsMode = 'terminate';
|
2025-05-16 15:50:46 +00:00
|
|
|
}
|
2025-05-20 11:04:09 +00:00
|
|
|
|
|
|
|
// Override the route name if specified
|
|
|
|
if (portSettings.routeName) {
|
|
|
|
routeName = portSettings.routeName;
|
|
|
|
}
|
|
|
|
}
|
2025-05-16 15:50:46 +00:00
|
|
|
break;
|
|
|
|
}
|
2025-05-20 11:04:09 +00:00
|
|
|
|
|
|
|
// Create the route configuration
|
|
|
|
const routeConfig: plugins.smartproxy.IRouteConfig = {
|
|
|
|
name: routeName,
|
|
|
|
match: {
|
|
|
|
ports: [port]
|
|
|
|
},
|
|
|
|
action: {
|
|
|
|
type: 'forward',
|
|
|
|
target: {
|
|
|
|
host: 'localhost', // Forward to internal email server
|
|
|
|
port: internalPort
|
|
|
|
},
|
|
|
|
tls: {
|
|
|
|
mode: tlsMode as any
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// For TLS terminate mode, add certificate info
|
|
|
|
if (tlsMode === 'terminate') {
|
|
|
|
routeConfig.action.tls.certificate = 'auto';
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add the route to our list
|
|
|
|
emailRoutes.push(routeConfig);
|
2025-05-16 15:50:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add domain-specific email routes if configured
|
|
|
|
if (emailConfig.domainRules) {
|
|
|
|
for (const rule of emailConfig.domainRules) {
|
|
|
|
// Extract domain from pattern (e.g., "*@example.com" -> "example.com")
|
|
|
|
const domain = rule.pattern.split('@')[1];
|
|
|
|
|
|
|
|
if (domain && rule.mode === 'forward' && rule.target) {
|
|
|
|
emailRoutes.push({
|
|
|
|
name: `email-forward-${domain}`,
|
|
|
|
match: {
|
|
|
|
ports: emailConfig.ports,
|
|
|
|
domains: [domain]
|
|
|
|
},
|
|
|
|
action: {
|
|
|
|
type: 'forward',
|
|
|
|
target: {
|
|
|
|
host: rule.target.server,
|
|
|
|
port: rule.target.port || 25
|
|
|
|
},
|
|
|
|
tls: {
|
|
|
|
mode: rule.target.useTls ? 'terminate-and-reencrypt' : 'passthrough'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return emailRoutes;
|
|
|
|
}
|
|
|
|
|
2025-05-07 22:06:55 +00:00
|
|
|
/**
|
2025-05-07 23:04:54 +00:00
|
|
|
* Check if a domain matches a pattern (including wildcard support)
|
|
|
|
* @param domain The domain to check
|
|
|
|
* @param pattern The pattern to match against (e.g., "*.example.com")
|
|
|
|
* @returns Whether the domain matches the pattern
|
2025-05-07 22:06:55 +00:00
|
|
|
*/
|
2025-05-07 23:04:54 +00:00
|
|
|
private isDomainMatch(domain: string, pattern: string): boolean {
|
|
|
|
// Normalize inputs
|
|
|
|
domain = domain.toLowerCase();
|
|
|
|
pattern = pattern.toLowerCase();
|
|
|
|
|
|
|
|
// Check for exact match
|
|
|
|
if (domain === pattern) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for wildcard match (*.example.com)
|
|
|
|
if (pattern.startsWith('*.')) {
|
|
|
|
const patternSuffix = pattern.slice(2); // Remove the "*." prefix
|
|
|
|
|
|
|
|
// Check if domain ends with the pattern suffix and has at least one character before it
|
|
|
|
return domain.endsWith(patternSuffix) && domain.length > patternSuffix.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
// No match
|
|
|
|
return false;
|
|
|
|
}
|
2025-05-07 22:06:55 +00:00
|
|
|
|
2025-05-07 23:04:54 +00:00
|
|
|
public async stop() {
|
|
|
|
console.log('Stopping DcRouter services...');
|
|
|
|
|
2025-05-07 22:06:55 +00:00
|
|
|
try {
|
2025-05-07 23:04:54 +00:00
|
|
|
// Stop all services in parallel for faster shutdown
|
|
|
|
await Promise.all([
|
2025-05-08 00:12:36 +00:00
|
|
|
// Stop unified email components if running
|
|
|
|
this.domainRouter ? this.stopUnifiedEmailComponents().catch(err => console.error('Error stopping unified email components:', err)) : Promise.resolve(),
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-07 23:45:19 +00:00
|
|
|
// Stop HTTP SmartProxy if running
|
|
|
|
this.smartProxy ? this.smartProxy.stop().catch(err => console.error('Error stopping SmartProxy:', err)) : Promise.resolve(),
|
2025-05-07 23:04:54 +00:00
|
|
|
|
|
|
|
// Stop DNS server if running
|
|
|
|
this.dnsServer ?
|
|
|
|
this.dnsServer.stop().catch(err => console.error('Error stopping DNS server:', err)) :
|
|
|
|
Promise.resolve()
|
|
|
|
]);
|
|
|
|
|
|
|
|
console.log('All DcRouter services stopped');
|
2025-05-07 22:06:55 +00:00
|
|
|
} catch (error) {
|
2025-05-07 23:04:54 +00:00
|
|
|
console.error('Error during DcRouter shutdown:', error);
|
|
|
|
throw error;
|
2025-05-07 22:06:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-05-07 23:04:54 +00:00
|
|
|
/**
|
2025-05-07 23:45:19 +00:00
|
|
|
* Update SmartProxy configuration
|
|
|
|
* @param config New SmartProxy configuration
|
2025-05-07 23:04:54 +00:00
|
|
|
*/
|
2025-05-07 23:45:19 +00:00
|
|
|
public async updateSmartProxyConfig(config: plugins.smartproxy.ISmartProxyOptions): Promise<void> {
|
|
|
|
// Stop existing SmartProxy if running
|
2025-05-04 10:10:07 +00:00
|
|
|
if (this.smartProxy) {
|
|
|
|
await this.smartProxy.stop();
|
2025-05-07 23:04:54 +00:00
|
|
|
this.smartProxy = undefined;
|
2025-05-04 10:10:07 +00:00
|
|
|
}
|
2025-05-07 22:06:55 +00:00
|
|
|
|
2025-05-07 23:45:19 +00:00
|
|
|
// Update configuration
|
|
|
|
this.options.smartProxyConfig = config;
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Start new SmartProxy with updated configuration (will include email routes if configured)
|
2025-05-07 23:45:19 +00:00
|
|
|
await this.setupSmartProxy();
|
|
|
|
|
|
|
|
console.log('SmartProxy configuration updated');
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
|
2025-05-07 23:45:19 +00:00
|
|
|
/**
|
2025-05-08 00:12:36 +00:00
|
|
|
* Set up unified email handling with pattern-based routing
|
|
|
|
* This implements the consolidated emailConfig approach
|
2025-05-07 23:45:19 +00:00
|
|
|
*/
|
2025-05-08 00:12:36 +00:00
|
|
|
private async setupUnifiedEmailHandling(): Promise<void> {
|
2025-05-08 00:39:43 +00:00
|
|
|
logger.log('info', 'Setting up unified email handling with pattern-based routing');
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
if (!this.options.emailConfig) {
|
|
|
|
throw new Error('Email configuration is required for unified email handling');
|
|
|
|
}
|
2025-05-16 15:50:46 +00:00
|
|
|
|
|
|
|
const emailConfig = this.options.emailConfig;
|
|
|
|
|
2025-05-20 11:04:09 +00:00
|
|
|
// Map external ports to internal ports with support for custom port mapping
|
|
|
|
const defaultPortMapping = {
|
2025-05-16 15:50:46 +00:00
|
|
|
25: 10025, // SMTP
|
|
|
|
587: 10587, // Submission
|
|
|
|
465: 10465 // SMTPS
|
|
|
|
};
|
|
|
|
|
2025-05-20 11:04:09 +00:00
|
|
|
// Use custom port mapping if provided, otherwise fall back to defaults
|
|
|
|
const portMapping = this.options.emailPortConfig?.portMapping || defaultPortMapping;
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Create internal email server configuration
|
|
|
|
const internalEmailConfig: IEmailConfig = {
|
|
|
|
...emailConfig,
|
|
|
|
ports: emailConfig.ports.map(port => portMapping[port] || port + 10000),
|
|
|
|
hostname: 'localhost' // Listen on localhost for SmartProxy forwarding
|
|
|
|
};
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-20 11:04:09 +00:00
|
|
|
// If custom MTA options are provided, merge them
|
|
|
|
if (this.options.emailPortConfig?.portSettings) {
|
|
|
|
// Will be used in MTA configuration
|
|
|
|
logger.log('info', 'Custom port settings detected for email configuration');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Configure custom email storage path if specified
|
|
|
|
if (this.options.emailPortConfig?.receivedEmailsPath) {
|
|
|
|
logger.log('info', `Custom email storage path configured: ${this.options.emailPortConfig.receivedEmailsPath}`);
|
|
|
|
}
|
|
|
|
|
2025-05-07 23:45:19 +00:00
|
|
|
try {
|
2025-05-08 00:12:36 +00:00
|
|
|
// Create domain router for pattern matching
|
|
|
|
this.domainRouter = new DomainRouter({
|
2025-05-16 15:50:46 +00:00
|
|
|
domainRules: emailConfig.domainRules,
|
|
|
|
defaultMode: emailConfig.defaultMode,
|
|
|
|
defaultServer: emailConfig.defaultServer,
|
|
|
|
defaultPort: emailConfig.defaultPort,
|
|
|
|
defaultTls: emailConfig.defaultTls
|
2025-05-07 23:45:19 +00:00
|
|
|
});
|
|
|
|
|
2025-05-08 00:39:43 +00:00
|
|
|
// Initialize the rate limiter
|
|
|
|
this.rateLimiter = new UnifiedRateLimiter({
|
|
|
|
global: {
|
|
|
|
maxMessagesPerMinute: 100,
|
|
|
|
maxRecipientsPerMessage: 100,
|
|
|
|
maxConnectionsPerIP: 20,
|
|
|
|
maxErrorsPerIP: 10,
|
|
|
|
maxAuthFailuresPerIP: 5
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
// Initialize the unified delivery queue
|
|
|
|
const queueOptions: IQueueOptions = {
|
2025-05-16 15:50:46 +00:00
|
|
|
storageType: emailConfig.queue?.storageType || 'memory',
|
|
|
|
persistentPath: emailConfig.queue?.persistentPath,
|
|
|
|
maxRetries: emailConfig.queue?.maxRetries,
|
|
|
|
baseRetryDelay: emailConfig.queue?.baseRetryDelay,
|
|
|
|
maxRetryDelay: emailConfig.queue?.maxRetryDelay
|
2025-05-08 00:39:43 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
this.deliveryQueue = new UnifiedDeliveryQueue(queueOptions);
|
|
|
|
await this.deliveryQueue.initialize();
|
|
|
|
|
|
|
|
// Initialize the delivery system
|
|
|
|
const deliveryOptions: IMultiModeDeliveryOptions = {
|
|
|
|
globalRateLimit: 100, // Default to 100 emails per minute
|
|
|
|
concurrentDeliveries: 10
|
|
|
|
};
|
|
|
|
|
|
|
|
this.deliverySystem = new MultiModeDeliverySystem(this.deliveryQueue, deliveryOptions);
|
|
|
|
await this.deliverySystem.start();
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
// Initialize the unified email server with internal configuration
|
2025-05-08 00:39:43 +00:00
|
|
|
this.unifiedEmailServer = new UnifiedEmailServer({
|
2025-05-16 15:50:46 +00:00
|
|
|
ports: internalEmailConfig.ports,
|
|
|
|
hostname: internalEmailConfig.hostname,
|
|
|
|
maxMessageSize: emailConfig.maxMessageSize,
|
|
|
|
auth: emailConfig.auth,
|
|
|
|
tls: emailConfig.tls,
|
|
|
|
domainRules: emailConfig.domainRules,
|
|
|
|
defaultMode: emailConfig.defaultMode,
|
|
|
|
defaultServer: emailConfig.defaultServer,
|
|
|
|
defaultPort: emailConfig.defaultPort,
|
|
|
|
defaultTls: emailConfig.defaultTls
|
2025-05-08 00:39:43 +00:00
|
|
|
});
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-08 00:39:43 +00:00
|
|
|
// Set up event listeners
|
|
|
|
this.unifiedEmailServer.on('error', (err) => {
|
|
|
|
logger.log('error', `UnifiedEmailServer error: ${err.message}`);
|
|
|
|
});
|
|
|
|
|
|
|
|
// Connect the unified email server with the delivery queue
|
|
|
|
this.unifiedEmailServer.on('emailProcessed', (email, mode, rule) => {
|
|
|
|
this.deliveryQueue!.enqueue(email, mode, rule).catch(err => {
|
|
|
|
logger.log('error', `Failed to enqueue email: ${err.message}`);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// Start the unified email server
|
|
|
|
await this.unifiedEmailServer.start();
|
|
|
|
|
2025-05-16 15:50:46 +00:00
|
|
|
logger.log('info', `Unified email handling configured with ${emailConfig.domainRules.length} domain rules on internal ports`);
|
|
|
|
logger.log('info', `Email server listening on ports: ${internalEmailConfig.ports.join(', ')}`);
|
2025-05-07 23:45:19 +00:00
|
|
|
} catch (error) {
|
2025-05-08 00:39:43 +00:00
|
|
|
logger.log('error', `Error setting up unified email handling: ${error.message}`);
|
2025-05-07 23:45:19 +00:00
|
|
|
throw error;
|
|
|
|
}
|
2025-05-07 14:33:20 +00:00
|
|
|
}
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-07 14:33:20 +00:00
|
|
|
/**
|
2025-05-08 00:12:36 +00:00
|
|
|
* Update the unified email configuration
|
|
|
|
* @param config New email configuration
|
2025-05-07 14:33:20 +00:00
|
|
|
*/
|
2025-05-08 00:12:36 +00:00
|
|
|
public async updateEmailConfig(config: IEmailConfig): Promise<void> {
|
|
|
|
// Stop existing email components
|
|
|
|
await this.stopUnifiedEmailComponents();
|
2025-05-07 23:04:54 +00:00
|
|
|
|
|
|
|
// Update configuration
|
2025-05-08 00:12:36 +00:00
|
|
|
this.options.emailConfig = config;
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
// Start email handling with new configuration
|
|
|
|
await this.setupUnifiedEmailHandling();
|
2025-05-07 23:04:54 +00:00
|
|
|
|
2025-05-08 00:12:36 +00:00
|
|
|
console.log('Unified email configuration updated');
|
2025-05-04 10:10:07 +00:00
|
|
|
}
|
2025-05-07 23:45:19 +00:00
|
|
|
|
|
|
|
/**
|
2025-05-08 00:12:36 +00:00
|
|
|
* Stop all unified email components
|
2025-05-07 23:45:19 +00:00
|
|
|
*/
|
2025-05-08 00:12:36 +00:00
|
|
|
private async stopUnifiedEmailComponents(): Promise<void> {
|
2025-05-08 00:39:43 +00:00
|
|
|
try {
|
|
|
|
// Stop all components in the correct order
|
|
|
|
|
|
|
|
// 1. Stop the unified email server first
|
|
|
|
if (this.unifiedEmailServer) {
|
|
|
|
await this.unifiedEmailServer.stop();
|
|
|
|
logger.log('info', 'Unified email server stopped');
|
|
|
|
this.unifiedEmailServer = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 2. Stop the delivery system
|
|
|
|
if (this.deliverySystem) {
|
|
|
|
await this.deliverySystem.stop();
|
|
|
|
logger.log('info', 'Delivery system stopped');
|
|
|
|
this.deliverySystem = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 3. Stop the delivery queue
|
|
|
|
if (this.deliveryQueue) {
|
|
|
|
await this.deliveryQueue.shutdown();
|
|
|
|
logger.log('info', 'Delivery queue shut down');
|
|
|
|
this.deliveryQueue = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 4. Stop the rate limiter
|
|
|
|
if (this.rateLimiter) {
|
|
|
|
this.rateLimiter.stop();
|
|
|
|
logger.log('info', 'Rate limiter stopped');
|
|
|
|
this.rateLimiter = undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 5. Clear the domain router
|
|
|
|
this.domainRouter = undefined;
|
|
|
|
|
|
|
|
logger.log('info', 'All unified email components stopped');
|
|
|
|
} catch (error) {
|
|
|
|
logger.log('error', `Error stopping unified email components: ${error.message}`);
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update domain rules for email routing
|
|
|
|
* @param rules New domain rules to apply
|
|
|
|
*/
|
|
|
|
public async updateDomainRules(rules: IDomainRule[]): Promise<void> {
|
|
|
|
// Validate that email config exists
|
|
|
|
if (!this.options.emailConfig) {
|
|
|
|
throw new Error('Email configuration is required before updating domain rules');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the configuration
|
|
|
|
this.options.emailConfig.domainRules = rules;
|
|
|
|
|
|
|
|
// Update the domain router if it exists
|
|
|
|
if (this.domainRouter) {
|
|
|
|
this.domainRouter.updateRules(rules);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update the unified email server if it exists
|
|
|
|
if (this.unifiedEmailServer) {
|
|
|
|
this.unifiedEmailServer.updateDomainRules(rules);
|
|
|
|
}
|
2025-05-07 23:45:19 +00:00
|
|
|
|
2025-05-08 00:39:43 +00:00
|
|
|
console.log(`Domain rules updated with ${rules.length} rules`);
|
2025-05-07 23:45:19 +00:00
|
|
|
}
|
|
|
|
|
2025-05-08 00:39:43 +00:00
|
|
|
/**
|
|
|
|
* Get statistics from all components
|
|
|
|
*/
|
|
|
|
public getStats(): any {
|
|
|
|
const stats: any = {
|
|
|
|
unifiedEmailServer: this.unifiedEmailServer?.getStats(),
|
|
|
|
deliveryQueue: this.deliveryQueue?.getStats(),
|
|
|
|
deliverySystem: this.deliverySystem?.getStats(),
|
|
|
|
rateLimiter: this.rateLimiter?.getStats()
|
|
|
|
};
|
|
|
|
|
|
|
|
return stats;
|
|
|
|
}
|
2025-05-20 19:46:59 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Configure MTA for email handling with custom port and storage settings
|
|
|
|
* @param config Configuration for the MTA service
|
|
|
|
*/
|
|
|
|
public async configureEmailMta(config: {
|
|
|
|
internalPort: number;
|
|
|
|
host?: string;
|
|
|
|
secure?: boolean;
|
|
|
|
storagePath?: string;
|
|
|
|
portMapping?: Record<number, number>;
|
|
|
|
}): Promise<boolean> {
|
|
|
|
logger.log('info', 'Configuring MTA service with custom settings');
|
|
|
|
|
|
|
|
|
|
|
|
// Update email port configuration
|
|
|
|
if (!this.options.emailPortConfig) {
|
|
|
|
this.options.emailPortConfig = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
// Configure storage paths for received emails
|
|
|
|
if (config.storagePath) {
|
|
|
|
// Set the storage path for received emails
|
|
|
|
this.options.emailPortConfig.receivedEmailsPath = config.storagePath;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply port mapping if provided
|
|
|
|
if (config.portMapping) {
|
|
|
|
this.options.emailPortConfig.portMapping = {
|
|
|
|
...this.options.emailPortConfig.portMapping,
|
|
|
|
...config.portMapping
|
|
|
|
};
|
|
|
|
|
|
|
|
logger.log('info', `Updated MTA port mappings: ${JSON.stringify(this.options.emailPortConfig.portMapping)}`);
|
|
|
|
}
|
|
|
|
|
2025-05-21 00:12:49 +00:00
|
|
|
// Use the dedicated helper to configure the email server
|
|
|
|
// Pass through the options specified by the implementation
|
|
|
|
if (this.unifiedEmailServer) {
|
|
|
|
configureEmailServer(this.unifiedEmailServer, {
|
|
|
|
ports: [config.internalPort], // Use whatever port the implementation specifies
|
|
|
|
hostname: config.host,
|
|
|
|
tls: config.secure ? {
|
|
|
|
// Basic TLS settings if secure mode is enabled
|
|
|
|
certPath: this.options.tls?.certPath,
|
|
|
|
keyPath: this.options.tls?.keyPath,
|
|
|
|
caPath: this.options.tls?.caPath
|
|
|
|
} : undefined,
|
|
|
|
storagePath: config.storagePath
|
|
|
|
});
|
|
|
|
}
|
2025-05-20 19:46:59 +00:00
|
|
|
|
|
|
|
// If email handling is already set up, restart it to apply changes
|
|
|
|
if (this.unifiedEmailServer) {
|
|
|
|
logger.log('info', 'Restarting unified email handling to apply MTA configuration changes');
|
|
|
|
await this.stopUnifiedEmailComponents();
|
|
|
|
await this.setupUnifiedEmailHandling();
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2025-05-04 10:10:07 +00:00
|
|
|
}
|
|
|
|
|
2025-05-24 01:00:30 +00:00
|
|
|
// Re-export types for convenience
|
|
|
|
export type { IEmailConfig, IDomainRule, EmailProcessingMode };
|
|
|
|
|
2025-05-04 10:10:07 +00:00
|
|
|
export default DcRouter;
|