UNPKG

cleansend

Version:

A TypeScript implementation of the OpenMsg Protocol - secure, decentralized messaging system with end-to-end encryption for cross-domain communication

170 lines â€ĸ 7.51 kB
"use strict"; /** * CleanSend - OpenMsg Protocol Server * * This is the main server file that sets up an Express.js application implementing * the OpenMsg Protocol for secure, decentralized messaging between users across * different domains. * * Features: * - RESTful API for authentication and messaging * - Cross-domain secure communication * - End-to-end encryption using AES-256-GCM * - Pass code-based handshake protocol * - Sandbox mode for development/testing * * @author Keshara1997 * @version 1.0.0 */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.startServer = startServer; const express_1 = __importDefault(require("express")); const cors_1 = __importDefault(require("cors")); const helmet_1 = __importDefault(require("helmet")); const dotenv_1 = __importDefault(require("dotenv")); const settings_1 = __importDefault(require("./config/settings")); // Import route handlers for different protocol endpoints const auth_1 = __importDefault(require("./setup/auth")); const messages_1 = __importDefault(require("./setup/messages")); const setup_1 = __importDefault(require("./setup/setup")); const database_1 = require("./config/database"); // Load environment variables from .env file dotenv_1.default.config(); const app = (0, express_1.default)(); // Security middleware configuration app.use((0, helmet_1.default)()); // Adds various security headers (XSS protection, etc.) app.use((0, cors_1.default)()); // Enable Cross-Origin Resource Sharing for API access // Body parsing middleware - handles JSON and URL-encoded data // Set size limits to 10MB to accommodate encrypted message packages app.use(express_1.default.json({ limit: '10mb' })); app.use(express_1.default.urlencoded({ extended: true, limit: '10mb' })); // Request logging middleware (development only) // Logs all incoming HTTP requests with timestamp, method, and path if (settings_1.default.nodeEnv === 'development') { app.use((req, _res, next) => { console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`); next(); }); } // Health check endpoint for monitoring and load balancer checks // Returns server status, configuration, and version information app.get('/health', (_req, res) => { res.json({ status: 'ok', timestamp: new Date().toISOString(), domain: settings_1.default.openmsgDomain, sandbox: settings_1.default.sandbox, version: '1.0.0' }); }); // OpenMsg Protocol Routes // Base URL changes based on sandbox mode (production vs development) const baseUrl = settings_1.default.sandbox ? '/openmsg/sandbox' : '/openmsg'; // Authentication routes - handles user authentication and connection establishment // POST /auth - Authenticate with another OpenMsg user // POST /auth/confirm - Confirm authentication request from another domain app.use(`${baseUrl}/auth`, auth_1.default); // Message routes - handles encrypted message sending and receiving // POST /message/receive - Receive encrypted messages from other domains // POST /message/confirm - Confirm message delivery authenticity app.use(`${baseUrl}/message`, messages_1.default); // Setup routes - administrative and testing endpoints // POST /setup/initiate-handshake - Start connection with another user // POST /setup/send-message - Send message to connected user // POST /setup/request-pass-code - Generate authentication pass code app.use(`${baseUrl}/setup`, setup_1.default); // Protocol information endpoint // Returns OpenMsg protocol details and available API endpoints app.get(`${baseUrl}/info`, (_req, res) => { res.json({ protocol: 'OpenMsg', version: '1.0.0', domain: settings_1.default.openmsgDomain, sandbox: settings_1.default.sandbox, endpoints: { auth: `${baseUrl}/auth`, auth_confirm: `${baseUrl}/auth/confirm`, message_receive: `${baseUrl}/message/receive`, message_confirm: `${baseUrl}/message/confirm`, setup: `${baseUrl}/setup` } }); }); // Root endpoint - provides basic server information and navigation app.get('/', (_req, res) => { res.json({ message: 'OpenMsg Protocol Server (TypeScript)', version: '1.0.0', info: `${baseUrl}/info`, health: '/health' }); }); // Global error handling middleware // Catches any unhandled errors and returns a standardized error response app.use((err, _req, res, _next) => { console.error('Error:', err); res.status(500).json({ error: true, error_message: 'Internal server error' }); }); // 404 handler for undefined routes app.use((_req, res) => { res.status(404).json({ error: true, error_message: 'Endpoint not found' }); }); /** * Start the OpenMsg Protocol server * * This function: * 1. Tests database connectivity * 2. Starts the Express server on configured port * 3. Displays startup information and available endpoints * 4. Handles startup errors gracefully */ async function startServer() { try { console.log(`Database configuration:`); // Test database connection before starting server // Exit if database is not accessible const dbConnected = await (0, database_1.testConnection)(); if (!dbConnected) { console.error('Failed to connect to database. Please check your configuration.'); process.exit(1); } // Start HTTP server on configured port app.listen(settings_1.default.port, () => { console.log('🚀 OpenMsg Server Started (TypeScript)'); console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); console.log(`🌐 Server running on port: ${settings_1.default.port}`); console.log(`🏠 Domain: ${settings_1.default.openmsgDomain}`); console.log(`đŸ“Ļ Sandbox mode: ${settings_1.default.sandbox ? 'ON' : 'OFF'}`); console.log(`🔗 Base URL: http://localhost:${settings_1.default.port}${baseUrl}`); console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'); console.log(''); console.log('Available endpoints:'); console.log(` 📊 Health: http://localhost:${settings_1.default.port}/health`); console.log(` â„šī¸ Info: http://localhost:${settings_1.default.port}${baseUrl}/info`); console.log(` 🔐 Auth: http://localhost:${settings_1.default.port}${baseUrl}/auth`); console.log(` 📨 Messages: http://localhost:${settings_1.default.port}${baseUrl}/message`); console.log(` âš™ī¸ Setup: http://localhost:${settings_1.default.port}${baseUrl}/setup`); console.log(''); // Development-specific help messages if (settings_1.default.nodeEnv === 'development') { console.log('💡 Run "npm run setup" to initialize the database'); console.log('🔧 Run "npm run typecheck" to check TypeScript types'); console.log(''); } }); } catch (error) { console.error('Failed to start server:', error); process.exit(1); } } //# sourceMappingURL=server.js.map