This commit is contained in:
2025-05-20 19:46:59 +00:00
parent f3f06ed06d
commit f37cddf26d
18 changed files with 338 additions and 553 deletions

View File

@ -1,3 +0,0 @@
export class AIBridge {
}

View File

@ -11,7 +11,8 @@ import { UnifiedDeliveryQueue, type IQueueOptions } from './mail/delivery/classe
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';
import { applyCustomEmailStorage } from './mail/delivery/classes.mta.patch.js';
// Import the MTA configuration helpers directly from mail/delivery
import { configureMtaStorage, configureMtaService } from './mail/delivery/index.js';
export interface IDcRouterOptions {
/**
@ -121,7 +122,7 @@ export class DcRouter {
// Apply custom email storage configuration if available
if (this.platformServiceRef && this.options.emailPortConfig?.receivedEmailsPath) {
logger.log('info', 'Applying custom email storage configuration');
applyCustomEmailStorage(this.platformServiceRef, this.options);
configureMtaStorage(this.platformServiceRef, this.options);
}
}
@ -160,7 +161,9 @@ export class DcRouter {
// If email config exists, automatically add email routes
if (this.options.emailConfig) {
const emailRoutes = this.generateEmailRoutes(this.options.emailConfig);
routes = [...routes, ...emailRoutes];
console.log(`Email Routes are:`)
console.log(emailRoutes)
routes = [...routes, /* ...emailRoutes */];
}
// Merge TLS/ACME configuration if provided at root level
@ -662,6 +665,63 @@ export class DcRouter {
return stats;
}
/**
* 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');
if (!this.platformServiceRef) {
throw new Error('Platform service reference is required for MTA configuration');
}
// 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)}`);
}
// Use the dedicated helper to configure the MTA service
// Pass through the port specified by the implementation
configureMtaService(this.platformServiceRef, {
port: config.internalPort, // Use whatever port the implementation specifies
host: config.host,
secure: config.secure,
storagePath: config.storagePath
});
// 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;
}
}
export default DcRouter;

View File

@ -1,27 +0,0 @@
import * as plugins from './plugins.js';
import { SzPlatformService } from './platformservice.js';
export class PlatformServiceDb {
public smartdataDb: plugins.smartdata.SmartdataDb;
public platformserviceRef: SzPlatformService;
constructor(platformserviceRefArg: SzPlatformService) {
this.platformserviceRef = platformserviceRefArg;
}
public async start() {
this.smartdataDb = new plugins.smartdata.SmartdataDb({
mongoDbUser: await this.platformserviceRef.serviceQenv.getEnvVarOnDemand('MONGO_DB_USER'),
mongoDbName: await this.platformserviceRef.serviceQenv.getEnvVarOnDemand('MONGO_DB_NAME'),
mongoDbPass: await this.platformserviceRef.serviceQenv.getEnvVarOnDemand('MONGO_DB_PASS'),
mongoDbUrl: await this.platformserviceRef.serviceQenv.getEnvVarOnDemand('MONGO_DB_URL'),
});
await this.smartdataDb.init();
}
public async stop() {
await this.smartdataDb.close();
}
}

View File

@ -282,14 +282,4 @@ export class SmtpPortConfig {
return routes;
}
/**
* Apply port configurations to SmartProxy settings
* @param smartProxy SmartProxy instance
* @deprecated Use toSmartProxyRoutes() instead to generate routes
*/
public applyToSmartProxy(smartProxy: plugins.smartproxy.SmartProxy): void {
console.warn('SmtpPortConfig.applyToSmartProxy() is deprecated. Use toSmartProxyRoutes() instead.');
// This method is deprecated and no longer functional
}
}

View File

@ -1,5 +1,5 @@
export * from './00_commitinfo_data.js';
import { SzPlatformService } from './platformservice.js';
import { SzPlatformService } from './classes.platformservice.js';
export * from './mail/index.js';
// DcRouter

View File

@ -0,0 +1,71 @@
import * as plugins from '../../plugins.js';
import * as paths from '../../paths.js';
import type { SzPlatformService } from '../../classes.platformservice.js';
/**
* Configures MTA storage settings for the platform service
* @param platformService Reference to the platform service
* @param options Configuration options containing storage paths
*/
export function configureMtaStorage(platformService: SzPlatformService, options: any): void {
// Extract the receivedEmailsPath if available
if (options?.emailPortConfig?.receivedEmailsPath) {
const receivedEmailsPath = options.emailPortConfig.receivedEmailsPath;
// Ensure the directory exists
plugins.smartfile.fs.ensureDirSync(receivedEmailsPath);
// Apply configuration to MTA service if available
if (platformService.mtaService) {
platformService.mtaService.configure({
storagePath: receivedEmailsPath
});
console.log(`Configured MTA to store received emails to: ${receivedEmailsPath}`);
}
}
}
/**
* Configure MTA service with port and storage settings
* @param platformService Reference to the platform service
* @param config Configuration settings for MTA
*/
export function configureMtaService(
platformService: SzPlatformService,
config: {
port?: number;
host?: string;
secure?: boolean;
storagePath?: string;
}
): boolean {
if (!platformService?.mtaService) {
console.error('MTA service not available in platform service');
return false;
}
// Configure MTA with the provided port
const mtaConfig = {
port: config.port, // Use the port provided by the config
host: config.host || 'localhost',
secure: config.secure || false,
storagePath: config.storagePath
};
// Configure the MTA service
platformService.mtaService.configure(mtaConfig);
console.log(`Configured MTA service on port ${mtaConfig.port}`);
// Set up storage path if provided
if (config.storagePath) {
configureMtaStorage(platformService, {
emailPortConfig: {
receivedEmailsPath: config.storagePath
}
});
}
return true;
}

View File

@ -1,72 +0,0 @@
import * as plugins from '../../plugins.js';
import * as paths from '../../paths.js';
import type { SzPlatformService } from '../../platformservice.js';
/**
* Extension to the MTA service to handle custom email storage
*/
export function configureEmailStorage(mtaService: any, options: any = {}) {
const originalSaveToLocalMailbox = mtaService.saveToLocalMailbox;
// Override the saveToLocalMailbox method to use custom path
mtaService.saveToLocalMailbox = async function(email: any): Promise<void> {
try {
// Use the custom received emails path if configured
const customPath = options?.receivedEmailsPath;
if (customPath) {
// Ensure the directory exists
plugins.smartfile.fs.ensureDirSync(customPath);
// Check if this is a bounce notification
const isBounceNotification = this.isBounceNotification(email);
if (isBounceNotification) {
await this.processBounceNotification(email);
return;
}
// Store the email in the custom path
const emailContent = email.toRFC822String();
const filename = `${Date.now()}_${email.to[0].replace(/[^a-zA-Z0-9]/g, '_')}.eml`;
plugins.smartfile.memory.toFsSync(
emailContent,
plugins.path.join(customPath, filename)
);
console.log(`Email saved to custom mailbox location: ${customPath}/${filename}`);
} else {
// Use the original implementation
await originalSaveToLocalMailbox.call(this, email);
}
} catch (error) {
console.error('Error saving email to local mailbox:', error);
throw error;
}
};
return mtaService;
}
/**
* Apply the email storage configuration to the platform service
*/
export function applyCustomEmailStorage(platformService: SzPlatformService, options: any): void {
// Extract the receivedEmailsPath if available
if (options?.emailPortConfig?.receivedEmailsPath) {
const receivedEmailsPath = options.emailPortConfig.receivedEmailsPath;
// Ensure the directory exists
plugins.smartfile.fs.ensureDirSync(receivedEmailsPath);
// Apply configuration to MTA service if available
if (platformService.mtaService) {
configureEmailStorage(platformService.mtaService, {
receivedEmailsPath
});
console.log(`Configured MTA to store received emails to: ${receivedEmailsPath}`);
}
}
}

View File

@ -14,7 +14,7 @@ import { RateLimiter, type IRateLimitConfig } from './classes.ratelimiter.js';
import { ContentScanner } from '../../security/classes.contentscanner.js';
import { IPWarmupManager } from '../../deliverability/classes.ipwarmupmanager.js';
import { SenderReputationMonitor } from '../../deliverability/classes.senderreputationmonitor.js';
import type { SzPlatformService } from '../../platformservice.js';
import type { SzPlatformService } from '../../classes.platformservice.js';
/**
* Configuration options for the MTA service
@ -41,6 +41,8 @@ export interface IMtaConfig {
keyPath?: string;
certPath?: string;
};
/** Custom path to store received emails */
customStoragePath?: string;
/** Outbound email sending configuration */
outbound?: {
/** Maximum concurrent sending jobs */
@ -694,6 +696,8 @@ export class MtaService {
/**
* Save an email to a local mailbox
*
* This implementation supports custom email storage paths via options.receivedEmailsPath
*/
private async saveToLocalMailbox(email: Email): Promise<void> {
// Check if this is a bounce notification
@ -704,19 +708,43 @@ export class MtaService {
return;
}
// Simplified implementation - in a real system, this would store to a user's mailbox
const mailboxPath = plugins.path.join(paths.receivedEmailsDir, 'local');
plugins.smartfile.fs.ensureDirSync(mailboxPath);
const emailContent = email.toRFC822String();
const filename = `${Date.now()}_${email.to[0].replace('@', '_at_')}.eml`;
plugins.smartfile.memory.toFsSync(
emailContent,
plugins.path.join(mailboxPath, filename)
);
console.log(`Email saved to local mailbox: ${filename}`);
try {
// Check if we have a custom storage path configured
const customPath = this.config?.customStoragePath;
if (customPath) {
// Ensure the directory exists
plugins.smartfile.fs.ensureDirSync(customPath);
// Store the email in the custom path
const emailContent = email.toRFC822String();
const filename = `${Date.now()}_${email.to[0].replace(/[^a-zA-Z0-9]/g, '_')}.eml`;
plugins.smartfile.memory.toFsSync(
emailContent,
plugins.path.join(customPath, filename)
);
console.log(`Email saved to custom mailbox location: ${customPath}/${filename}`);
} else {
// Use the default path
const mailboxPath = plugins.path.join(paths.receivedEmailsDir, 'local');
plugins.smartfile.fs.ensureDirSync(mailboxPath);
const emailContent = email.toRFC822String();
const filename = `${Date.now()}_${email.to[0].replace('@', '_at_')}.eml`;
plugins.smartfile.memory.toFsSync(
emailContent,
plugins.path.join(mailboxPath, filename)
);
console.log(`Email saved to local mailbox: ${filename}`);
}
} catch (error) {
console.error('Error saving email to local mailbox:', error);
throw error;
}
}
/**
@ -1322,6 +1350,81 @@ export class MtaService {
return this.reputationMonitor;
}
/**
* Configure MTA with new settings
*/
public configure(config: {
port?: number;
host?: string;
secure?: boolean;
storagePath?: string;
}): void {
console.log('Configuring MTA service with new settings:', config);
// Update SMTP port if provided
if (config.port !== undefined) {
// Store the original port
const originalPort = this.config.smtp.port;
this.config.smtp.port = config.port;
console.log(`Updated MTA port from ${originalPort} to ${config.port}`);
// If the server is already running, we need to restart it
if (this.server && this.running) {
console.log('Restarting SMTP server with new port');
const restartServer = async () => {
try {
// Stop the current server
await this.server.stop();
// Create and start the new server with updated config
const smtpOptions: ISmtpServerOptions = {
port: this.config.smtp.port,
key: this.certificate.privateKey,
cert: this.certificate.publicKey,
hostname: this.config.smtp.hostname
};
this.server = new SMTPServer(this, smtpOptions);
this.server.start();
console.log(`SMTP server restarted on port ${smtpOptions.port}`);
} catch (error) {
console.error('Error restarting SMTP server:', error);
}
};
// Execute the restart
restartServer().catch(error => {
console.error('Failed to restart SMTP server:', error);
});
}
}
// Update hostname if provided
if (config.host) {
this.config.smtp.hostname = config.host;
console.log(`Updated MTA hostname to ${config.host}`);
}
// Update TLS settings if secure flag is provided
if (config.secure !== undefined) {
// This would update TLS settings as appropriate
console.log(`Updated MTA TLS settings (secure: ${config.secure})`);
}
// Update storage path if provided
if (config.storagePath) {
this.config.customStoragePath = config.storagePath;
// Ensure the directory exists
plugins.smartfile.fs.ensureDirSync(config.storagePath);
console.log(`Updated MTA storage path to ${config.storagePath}`);
}
}
/**
* Get MTA service statistics
*/

View File

@ -15,4 +15,7 @@ export { RateLimiter } from './classes.ratelimiter.js';
export type { IRateLimitConfig } from './classes.ratelimiter.js';
// Unified rate limiter
export * from './classes.unified.rate.limiter.js';
export * from './classes.unified.rate.limiter.js';
// MTA configuration helpers
export * from './classes.mta.config.js';

View File

@ -7,7 +7,7 @@ import { TemplateManager } from '../core/classes.templatemanager.js';
import { EmailValidator } from '../core/classes.emailvalidator.js';
import { BounceManager } from '../core/classes.bouncemanager.js';
import { logger } from '../../logger.js';
import type { SzPlatformService } from '../../platformservice.js';
import type { SzPlatformService } from '../../classes.platformservice.js';
// Import MTA service
import { MtaService } from '../delivery/classes.mta.js';

View File

@ -1,188 +0,0 @@
import * as plugins from './plugins.js';
import * as paths from './paths.js';
import { PlatformServiceDb } from './classes.platformservicedb.js'
import { EmailService } from './mail/services/classes.emailservice.js';
import { SmsService } from './sms/classes.smsservice.js';
import { MtaService } from './mail/delivery/classes.mta.js';
import { logger } from './logger.js';
import { type IPlatformConfig } from './config/index.js';
import { ConfigurationError } from './errors/base.errors.js';
export class SzPlatformService {
public projectinfo: plugins.projectinfo.ProjectInfo;
public serviceQenv = new plugins.qenv.Qenv('./', './.nogit');
public platformserviceDb: PlatformServiceDb;
public typedserver: plugins.typedserver.TypedServer;
public typedrouter = new plugins.typedrequest.TypedRouter();
// SubServices
public emailService: EmailService;
public mtaService: MtaService;
public smsService: SmsService;
// Platform configuration
public config: IPlatformConfig;
/**
* Create a new platform service instance
*
* @param config Optional platform configuration
*/
constructor(config: IPlatformConfig) {
// Store configuration
this.config = config;
// Initialize typed router
this.typedrouter = new plugins.typedrequest.TypedRouter();
}
/**
* Initialize the platform service
* Applies configuration provided in constructor
*/
public async initialize(): Promise<void> {
// Simple validation of config - must be provided
if (!this.config) {
throw new ConfigurationError(
'Platform configuration must be provided in constructor',
'PLATFORM_CONFIG_MISSING',
{}
);
}
// Apply configuration to logger
if (this.config.logging) {
logger.setContext({
environment: this.config.environment,
component: 'PlatformService'
});
}
// Create project info
this.projectinfo = new plugins.projectinfo.ProjectInfo(paths.packageDir);
// Initialize database
this.platformserviceDb = new PlatformServiceDb(this);
logger.info('Platform service initialized successfully');
}
/**
* Start the platform service
*/
public async start(): Promise<void> {
// Initialize first if needed
if (!this.config) {
await this.initialize();
}
// Check if service is enabled
if (this.config.enabled === false) {
logger.warn('Platform service is disabled in configuration, not starting services');
return;
}
logger.info('Starting platform service...');
// Initialize sub-services
await this.initializeServices();
// Start the HTTP server
await this.startServer();
logger.info('Platform service started successfully');
}
/**
* Initialize and start sub-services
*/
private async initializeServices(): Promise<void> {
// Initialize email service
if (this.config.email?.enabled !== false) {
this.emailService = new EmailService(this, this.config.email);
await this.emailService.start();
logger.info('Email service started');
// Initialize MTA service if needed
if (this.config.email?.useMta) {
this.mtaService = new MtaService(this, this.config.email.mtaConfig);
logger.info('MTA service initialized');
}
} else {
logger.info('Email service disabled in configuration');
}
// Initialize SMS service
if (this.config.sms?.enabled !== false) {
// Get API token from config or env var
const apiToken = this.config.sms?.apiGatewayApiToken ||
await this.serviceQenv.getEnvVarOnDemand('SMS_API_TOKEN');
if (!apiToken) {
logger.warn('No SMS API token provided, SMS service will not be started');
} else {
this.smsService = new SmsService(this, {
apiGatewayApiToken: apiToken,
...this.config.sms
});
await this.smsService.start();
logger.info('SMS service started');
}
} else {
logger.info('SMS service disabled in configuration');
}
}
/**
* Start the HTTP server
*/
private async startServer(): Promise<void> {
// Check if server is enabled
if (this.config.server?.enabled === false) {
logger.info('HTTP server disabled in configuration');
return;
}
// Create server with configuration
this.typedserver = new plugins.typedserver.TypedServer({
cors: this.config.server?.cors === false ? false : true,
port: this.config.server?.port || 3000,
// hostname is not supported directly, will be set during start
});
// Add the router
// Note: Using any type to bypass TypeScript restriction
(this.typedserver as any).addRouter(this.typedrouter);
// Start server
await this.typedserver.start();
logger.info(`HTTP server started on ${this.config.server?.host || '0.0.0.0'}:${this.config.server?.port || 3000}`);
}
/**
* Stop the platform service
*/
public async stop(): Promise<void> {
logger.info('Stopping platform service...');
// Stop sub-services
if (this.emailService) {
await this.emailService.stop();
logger.info('Email service stopped');
}
if (this.smsService) {
await this.smsService.stop();
logger.info('SMS service stopped');
}
// Stop the server if it's running
if (this.typedserver) {
await this.typedserver.stop();
logger.info('HTTP server stopped');
}
logger.info('Platform service stopped successfully');
}
}

View File

@ -1,7 +1,7 @@
import * as plugins from '../plugins.js';
import * as paths from '../paths.js';
import { logger } from '../logger.js';
import type { SzPlatformService } from '../platformservice.js';
import type { SzPlatformService } from '../classes.platformservice.js';
import type { ISmsConfig } from '../config/sms.config.js';
import { ConfigValidator, smsConfigSchema } from '../config/index.js';