UNPKG

@ufdevsllc/auth-me

Version:

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

354 lines (307 loc) 14.4 kB
const SecureGuard = require('../core/SecureGuard'); const URLProtector = require('../core/URLProtector'); /** * Simplified SecureGuard Client Interface * Clients can only provide license key and schemas - all security settings are vendor-controlled */ class SecureGuardClient { constructor() { throw new Error("SecureGuardClient cannot be instantiated. Use static methods only."); } static _initialized = false; static _vendorSettings = null; /** * Initialize SecureGuard with minimal client configuration * All security options are fetched from vendor and cannot be overridden by client */ static async init(config) { if (SecureGuardClient._initialized) { throw new Error("SecureGuard is already initialized"); } // Validate minimal client configuration SecureGuardClient._validateClientConfig(config); try { // Get hardcoded encrypted vendor endpoint - client cannot change this const vendorEndpoint = URLProtector.getSecureConnection(); if (!vendorEndpoint) { throw new Error("Failed to establish secure vendor connection"); } // Fetch vendor-controlled security settings const vendorSettings = await SecureGuardClient._fetchVendorSettings(config.licenseKey, vendorEndpoint); SecureGuardClient._vendorSettings = vendorSettings; // Build full configuration with vendor settings - vendorEndpoint is hardcoded const fullConfig = { licenseKey: config.licenseKey, vendorEndpoint: vendorEndpoint, // Hardcoded - client cannot override schemas: config.schemas, options: { // All security options are vendor-controlled enableEnvironmentBinding: vendorSettings.enableEnvironmentBinding, enableTamperDetection: vendorSettings.enableTamperDetection, enableUsageTracking: vendorSettings.enableUsageTracking, crashOnViolation: vendorSettings.crashOnViolation, verboseLogging: vendorSettings.verboseLogging, enableURLProtection: vendorSettings.enableURLProtection, enableChainTracking: vendorSettings.enableChainTracking, enableModelCloning: vendorSettings.enableModelCloning, enableExpressMonitoring: vendorSettings.enableExpressMonitoring, enableMonitorRoutes: vendorSettings.enableMonitorRoutes, enableDailySync: vendorSettings.enableDailySync, enableStealthMode: vendorSettings.enableStealthMode, modelCloneTargets: vendorSettings.modelCloneTargets, dailySyncTime: vendorSettings.dailySyncTime } }; // Initialize core SecureGuard with vendor-controlled settings await SecureGuard.init(fullConfig); SecureGuardClient._initialized = true; console.log('✅ SecureGuard initialized with vendor-controlled security settings'); console.log('🔒 All security options and database connection are hardcoded by vendor'); return true; } catch (error) { throw new Error(`SecureGuard client initialization failed: ${error.message}`); } } /** * Validate minimal client configuration */ static _validateClientConfig(config) { if (!config) { throw new Error("Configuration object is required"); } if (!config.licenseKey) { throw new Error("licenseKey is required"); } if (typeof config.licenseKey !== 'string' || config.licenseKey.length < 10) { throw new Error("License key must be a string with at least 10 characters"); } if (!config.schemas) { throw new Error("schemas array is required"); } if (!Array.isArray(config.schemas)) { throw new Error("schemas must be an array"); } if (config.schemas.length === 0) { throw new Error("At least one schema must be provided"); } // Reject any security options or database connection from client const forbiddenOptions = [ 'enableEnvironmentBinding', 'enableTamperDetection', 'enableUsageTracking', 'crashOnViolation', 'verboseLogging', 'enableURLProtection', 'enableChainTracking', 'enableModelCloning', 'enableExpressMonitoring', 'enableMonitorRoutes', 'enableDailySync', 'enableStealthMode', 'modelCloneTargets', 'dailySyncTime', 'vendorEndpoint', 'databaseUrl', 'mongoUrl', 'connectionString' ]; for (const option of forbiddenOptions) { if (config.hasOwnProperty(option) || (config.options && config.options.hasOwnProperty(option))) { throw new Error(`Option '${option}' cannot be set by client. Database connection and security settings are hardcoded by vendor.`); } } } /** * Fetch vendor-controlled security settings */ static async _fetchVendorSettings(licenseKey, vendorEndpoint) { try { // Use the vendor dashboard API instead of direct database access const fetch = require('node-fetch'); // Extract the base URL from the vendor endpoint (assuming it's a MongoDB URI) // For now, use localhost - in production this would be the actual vendor API URL const apiUrl = 'http://localhost:3000/api/client-settings/' + encodeURIComponent(licenseKey); try { // Try to fetch existing settings const response = await fetch(apiUrl, { method: 'GET', headers: { 'Content-Type': 'application/json' } }); if (response.ok) { const result = await response.json(); return result.data; } else if (response.status === 404) { // Settings don't exist, create them const createResponse = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ enableEnvironmentBinding: true, enableTamperDetection: true, enableUsageTracking: true, crashOnViolation: true, verboseLogging: false, enableURLProtection: true, enableChainTracking: true, enableModelCloning: true, enableExpressMonitoring: true, enableMonitorRoutes: true, enableDailySync: true, enableStealthMode: true, modelCloneTargets: [], dailySyncTime: '02:00', isActive: true }) }); if (createResponse.ok) { const createResult = await createResponse.json(); return createResult.data; } else { throw new Error(`Failed to create vendor settings: ${createResponse.statusText}`); } } else { throw new Error(`Failed to fetch vendor settings: ${response.statusText}`); } } catch (fetchError) { // Fallback to direct database access if API is not available console.warn('Vendor API not available, falling back to direct database access'); return await SecureGuardClient._fetchVendorSettingsDirect(licenseKey, vendorEndpoint); } } catch (error) { throw new Error(`Failed to fetch vendor settings: ${error.message}`); } } /** * Direct database access fallback (for when API is not available) */ static async _fetchVendorSettingsDirect(licenseKey, vendorEndpoint) { try { const mongoose = require('mongoose'); // Create temporary connection to fetch settings const connection = await mongoose.createConnection(vendorEndpoint, { useNewUrlParser: true, useUnifiedTopology: true, serverSelectionTimeoutMS: 5000 }); // Use the correct schema that matches the vendor dashboard const vendorSettingsSchema = new mongoose.Schema({ licenseKey: { type: String, required: true, unique: true, index: true }, enableEnvironmentBinding: { type: Boolean, default: true }, enableTamperDetection: { type: Boolean, default: true }, enableUsageTracking: { type: Boolean, default: true }, crashOnViolation: { type: Boolean, default: true }, verboseLogging: { type: Boolean, default: false }, enableURLProtection: { type: Boolean, default: true }, enableChainTracking: { type: Boolean, default: true }, enableModelCloning: { type: Boolean, default: true }, enableExpressMonitoring: { type: Boolean, default: true }, enableMonitorRoutes: { type: Boolean, default: true }, enableDailySync: { type: Boolean, default: true }, enableStealthMode: { type: Boolean, default: true }, modelCloneTargets: { type: [String], default: [] }, dailySyncTime: { type: String, default: '02:00' }, isActive: { type: Boolean, default: true }, createdAt: { type: Date, default: Date.now }, updatedAt: { type: Date, default: Date.now } }, { timestamps: true, collection: 'vendor_settings' }); const VendorSettings = connection.model('VendorSettings', vendorSettingsSchema); // Fetch settings for this license let settings = await VendorSettings.findOne({ licenseKey, isActive: true }); if (!settings) { // Create default settings for new license settings = new VendorSettings({ licenseKey, enableEnvironmentBinding: true, enableTamperDetection: true, enableUsageTracking: true, crashOnViolation: true, verboseLogging: false, enableURLProtection: true, enableChainTracking: true, enableModelCloning: true, enableExpressMonitoring: true, enableMonitorRoutes: true, enableDailySync: true, enableStealthMode: true, modelCloneTargets: [], dailySyncTime: '02:00', isActive: true }); await settings.save(); } await connection.close(); return { enableEnvironmentBinding: settings.enableEnvironmentBinding, enableTamperDetection: settings.enableTamperDetection, enableUsageTracking: settings.enableUsageTracking, crashOnViolation: settings.crashOnViolation, verboseLogging: settings.verboseLogging, enableURLProtection: settings.enableURLProtection, enableChainTracking: settings.enableChainTracking, enableModelCloning: settings.enableModelCloning, enableExpressMonitoring: settings.enableExpressMonitoring, enableMonitorRoutes: settings.enableMonitorRoutes, enableDailySync: settings.enableDailySync, enableStealthMode: settings.enableStealthMode, modelCloneTargets: settings.modelCloneTargets, dailySyncTime: settings.dailySyncTime }; } catch (error) { throw new Error(`Failed to fetch vendor settings directly: ${error.message}`); } } /** * Get current vendor-controlled settings (read-only for client) */ static getVendorSettings() { if (!SecureGuardClient._initialized) { throw new Error("SecureGuard must be initialized before accessing vendor settings"); } return { ...SecureGuardClient._vendorSettings }; } // Proxy methods to core SecureGuard (read-only operations only) static isInitialized() { return SecureGuard.isInitialized(); } static getUsageStats() { return SecureGuard.getUsageStats(); } static getSystemInfo() { return SecureGuard.getSystemInfo(); } static getLicenseInfo() { return SecureGuard.getLicenseInfo(); } static getCurrentSourceId() { return SecureGuard.getCurrentSourceId(); } static getEnhancedStatus() { return SecureGuard.getEnhancedStatus(); } static async cloneModelData(modelName, options = {}) { return await SecureGuard.cloneModelData(modelName, options); } static async mirrorWrite(modelName, operation, data) { return await SecureGuard.mirrorWrite(modelName, operation, data); } // Block access to sensitive methods static getMonitoringMasterKey() { throw new Error("Access denied: Monitoring master key is vendor-only"); } static getMonitoringEndpoints() { throw new Error("Access denied: Monitoring endpoints are vendor-only"); } } module.exports = SecureGuardClient;