UNPKG

@ufdevsllc/auth-me

Version:

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

680 lines (571 loc) 16.4 kB
# SecureGuard Integration Guide ## Overview SecureGuard is an enterprise-grade license validation and security package that provides comprehensive protection for your applications. This guide shows you how to integrate SecureGuard into your project with offline support, usage tracking, and security features. ## Table of Contents - [Installation](#installation) - [Quick Start](#quick-start) - [Configuration](#configuration) - [Core Features](#core-features) - [Advanced Usage](#advanced-usage) - [Offline Mode](#offline-mode) - [Security Features](#security-features) - [API Reference](#api-reference) - [Examples](#examples) - [Troubleshooting](#troubleshooting) ## Installation ### npm Installation ```bash npm install @ufdevsllc/auth-me ``` ### yarn Installation ```bash yarn add @ufdevsllc/auth-me ``` ### Requirements - Node.js 14+ - MongoDB (for secure database features) - Valid license key from vendor ## Quick Start ### Basic Setup ```javascript const { SecureGuard } = require('@ufdevsllc/auth-me'); // Initialize SecureGuard const secureGuard = new SecureGuard({ licenseKey: 'your-license-key-here', secureDatabase: { connectionString: 'mongodb://localhost:27017/secure-db', options: { useNewUrlParser: true, useUnifiedTopology: true } }, enableOfflineMode: true }); // Initialize the system async function initialize() { try { await secureGuard.initialize(); console.log('SecureGuard initialized successfully'); } catch (error) { console.error('Failed to initialize SecureGuard:', error.message); } } initialize(); ``` ### Express.js Integration ```javascript const express = require('express'); const { SecureGuard } = require('@ufdevsllc/auth-me'); const app = express(); const secureGuard = new SecureGuard({ licenseKey: process.env.SECURE_GUARD_LICENSE, secureDatabase: { connectionString: process.env.MONGODB_URI } }); // Middleware for license validation app.use(async (req, res, next) => { try { const isValid = await secureGuard.validateRequest(req); if (!isValid) { return res.status(403).json({ error: 'License validation failed' }); } next(); } catch (error) { console.error('License validation error:', error); res.status(500).json({ error: 'Internal server error' }); } }); app.listen(3000, () => { console.log('Server running with SecureGuard protection'); }); ``` ## Configuration ### Basic Configuration ```javascript const config = { // Required: Your license key licenseKey: 'your-license-key', // Secure database configuration secureDatabase: { connectionString: 'mongodb://localhost:27017/secure-db', options: { useNewUrlParser: true, useUnifiedTopology: true, serverSelectionTimeoutMS: 5000 } }, // Offline mode settings offlineMode: { enabled: true, cacheExpirationHours: 24, gracePeriodHours: 72, cacheDirectory: '.secure-guard-cache' }, // Usage tracking usageTracking: { enabled: true, persistInterval: 60000, // 1 minute limits: { maxWrites: 10000, maxUsers: 100, maxDeployments: 5 } }, // Security features security: { enableTamperDetection: true, enableObfuscation: true, enableSecurityHardening: true, strictMode: false }, // Logging logging: { level: 'info', // debug, info, warn, error, critical enableSecurityLogging: true, logToFile: true, logDirectory: './logs' } }; const secureGuard = new SecureGuard(config); ``` ### Environment Variables ```bash # .env file SECURE_GUARD_LICENSE=your-license-key-here MONGODB_URI=mongodb://localhost:27017/secure-db SECURE_GUARD_LOG_LEVEL=info SECURE_GUARD_OFFLINE_MODE=true SECURE_GUARD_CACHE_EXPIRATION=24 ``` ```javascript // Using environment variables const secureGuard = new SecureGuard({ licenseKey: process.env.SECURE_GUARD_LICENSE, secureDatabase: { connectionString: process.env.MONGODB_URI }, offlineMode: { enabled: process.env.SECURE_GUARD_OFFLINE_MODE === 'true', cacheExpirationHours: parseInt(process.env.SECURE_GUARD_CACHE_EXPIRATION) || 24 } }); ``` ## Core Features ### 1. License Validation ```javascript // Validate license const validation = await secureGuard.validateLicense(); console.log('License valid:', validation.isValid); console.log('License info:', validation.license); // Validate with environment binding const fingerprint = secureGuard.generateEnvironmentFingerprint(); const boundValidation = await secureGuard.validateLicense(fingerprint); // Check validation result if (boundValidation.isValid) { console.log('License valid for this environment'); } else { console.error('License validation failed:', boundValidation.reason); } ``` ### 2. Usage Tracking ```javascript // Track usage await secureGuard.trackUsage('user_action', { userId: 'user123', action: 'data_write', metadata: { recordCount: 100 } }); // Get usage statistics const stats = secureGuard.getUsageStats(); console.log('Total writes:', stats.totalWrites); console.log('Remaining writes:', stats.writesRemaining); // Check if within limits if (!secureGuard.isWithinLimits()) { console.warn('Usage limits exceeded'); } ``` ### 3. Data Mirroring ```javascript // Register schema for mirroring const userSchema = new mongoose.Schema({ name: String, email: String, createdAt: { type: Date, default: Date.now } }); await secureGuard.registerSchema({ schema: userSchema, modelName: 'User', mirrorWrites: true }); // Data will be automatically mirrored to secure database const User = mongoose.model('User', userSchema); const user = new User({ name: 'John', email: 'john@example.com' }); await user.save(); // Automatically mirrored ``` ## Advanced Usage ### Custom Validation Logic ```javascript // Add custom validation rules secureGuard.addValidationRule('custom-check', async (context) => { // Your custom validation logic const isValid = await yourCustomValidation(context); return { isValid, reason: isValid ? 'Custom validation passed' : 'Custom validation failed' }; }); // Use custom validation const result = await secureGuard.validateWithRules(['custom-check']); ``` ### Event Handling ```javascript // Listen for security events secureGuard.on('license-validation-failed', (event) => { console.error('License validation failed:', event); // Handle failed validation }); secureGuard.on('usage-limit-exceeded', (event) => { console.warn('Usage limit exceeded:', event); // Handle limit exceeded }); secureGuard.on('tamper-detected', (event) => { console.error('Tamper detected:', event); // Handle security violation }); secureGuard.on('offline-mode-entered', (event) => { console.info('Entered offline mode:', event.reason); }); ``` ### Middleware Integration ```javascript // Express middleware const secureGuardMiddleware = (options = {}) => { return async (req, res, next) => { try { // Validate license const validation = await secureGuard.validateLicense(); if (!validation.isValid) { return res.status(403).json({ error: 'License validation failed', reason: validation.reason }); } // Track usage await secureGuard.trackUsage('api_request', { endpoint: req.path, method: req.method, ip: req.ip }); // Check limits if (!secureGuard.isWithinLimits()) { return res.status(429).json({ error: 'Usage limits exceeded' }); } req.secureGuard = secureGuard; next(); } catch (error) { console.error('SecureGuard middleware error:', error); if (options.failOpen) { next(); } else { res.status(500).json({ error: 'Security validation failed' }); } } }; }; // Use middleware app.use(secureGuardMiddleware({ failOpen: false })); ``` ## Offline Mode ### Configuration ```javascript const secureGuard = new SecureGuard({ licenseKey: 'your-license-key', offlineMode: { enabled: true, cacheExpirationHours: 24, // Cache valid for 24 hours gracePeriodHours: 72, // Grace period for stale cache cacheDirectory: '.cache', // Cache storage directory strictMode: false // Allow degraded operation } }); ``` ### Offline Operations ```javascript // Check offline status const offlineStatus = secureGuard.getOfflineStatus(); console.log('Is offline:', offlineStatus.isOfflineMode); console.log('Cache entries:', offlineStatus.cachedLicenses); // Force offline mode (for testing) secureGuard.enterOfflineMode('Testing offline functionality'); // Validate license offline const offlineValidation = await secureGuard.validateLicense(); if (offlineValidation.isOfflineValidation) { console.log('Using cached license validation'); } // Clean expired cache const removedCount = await secureGuard.cleanExpiredCache(); console.log('Removed expired entries:', removedCount); ``` ### Graceful Degradation ```javascript // Check degraded mode status const degradedStatus = secureGuard.getDegradedModeStatus(); if (degradedStatus.isDegradedMode) { console.log('Operating in degraded mode'); console.log('Reduced limits applied'); } // Handle degraded operations if (secureGuard.isInDegradedMode()) { // Implement fallback behavior console.log('Using reduced functionality due to network issues'); } ``` ## Security Features ### Tamper Detection ```javascript // Enable tamper detection const secureGuard = new SecureGuard({ licenseKey: 'your-license-key', security: { enableTamperDetection: true, tamperDetectionLevel: 'strict' // 'basic', 'standard', 'strict' } }); // Handle tamper detection events secureGuard.on('tamper-detected', (event) => { console.error('Tamper detected:', event); // Implement security response process.exit(1); // Or other security measures }); ``` ### Code Obfuscation ```javascript // Enable code obfuscation const secureGuard = new SecureGuard({ licenseKey: 'your-license-key', security: { enableObfuscation: true, obfuscationLevel: 'high' // 'low', 'medium', 'high' } }); ``` ### Security Hardening ```javascript // Enable security hardening const secureGuard = new SecureGuard({ licenseKey: 'your-license-key', security: { enableSecurityHardening: true, preventDebugging: true, preventReverseEngineering: true, enableIntegrityChecks: true } }); ``` ## API Reference ### SecureGuard Class #### Constructor ```javascript new SecureGuard(config) ``` #### Methods ##### `initialize()` Initializes the SecureGuard system. ```javascript await secureGuard.initialize(); ``` ##### `validateLicense(fingerprint?)` Validates the license key. ```javascript const result = await secureGuard.validateLicense(); // Returns: { isValid: boolean, license: object, reason: string, code: string } ``` ##### `trackUsage(operation, metadata?)` Tracks usage for the specified operation. ```javascript await secureGuard.trackUsage('api_call', { endpoint: '/users' }); ``` ##### `getUsageStats()` Returns current usage statistics. ```javascript const stats = secureGuard.getUsageStats(); // Returns: { totalWrites: number, writesRemaining: number, ... } ``` ##### `isWithinLimits()` Checks if usage is within license limits. ```javascript const withinLimits = secureGuard.isWithinLimits(); // Returns: boolean ``` ##### `getOfflineStatus()` Returns offline mode status. ```javascript const status = secureGuard.getOfflineStatus(); // Returns: { isOfflineMode: boolean, cachedLicenses: number, ... } ``` ## Examples ### Basic Web Application ```javascript const express = require('express'); const { SecureGuard } = require('@ufdevsllc/auth-me'); const app = express(); const secureGuard = new SecureGuard({ licenseKey: process.env.LICENSE_KEY, secureDatabase: { connectionString: process.env.MONGODB_URI } }); // Initialize SecureGuard secureGuard.initialize().then(() => { console.log('SecureGuard ready'); }).catch(console.error); // Protected route app.get('/api/data', async (req, res) => { try { // Validate license const validation = await secureGuard.validateLicense(); if (!validation.isValid) { return res.status(403).json({ error: 'Invalid license' }); } // Track usage await secureGuard.trackUsage('data_access'); // Your business logic here res.json({ data: 'Protected data' }); } catch (error) { res.status(500).json({ error: 'Server error' }); } }); app.listen(3000); ``` ### Database Integration ```javascript const mongoose = require('mongoose'); const { SecureGuard } = require('@ufdevsllc/auth-me'); const secureGuard = new SecureGuard({ licenseKey: process.env.LICENSE_KEY, secureDatabase: { connectionString: process.env.SECURE_MONGODB_URI } }); // Define schema const userSchema = new mongoose.Schema({ name: String, email: String }); // Register for mirroring await secureGuard.registerSchema({ schema: userSchema, modelName: 'User', mirrorWrites: true }); const User = mongoose.model('User', userSchema); // Create user (automatically mirrored) const user = new User({ name: 'John', email: 'john@example.com' }); await user.save(); ``` ### Microservice Integration ```javascript const { SecureGuard } = require('@ufdevsllc/auth-me'); class UserService { constructor() { this.secureGuard = new SecureGuard({ licenseKey: process.env.LICENSE_KEY, serviceName: 'user-service' }); } async initialize() { await this.secureGuard.initialize(); } async createUser(userData) { // Validate license const validation = await this.secureGuard.validateLicense(); if (!validation.isValid) { throw new Error('License validation failed'); } // Track usage await this.secureGuard.trackUsage('user_creation'); // Business logic const user = await this.saveUser(userData); return user; } } ``` ## Troubleshooting ### Common Issues #### 1. License Validation Fails ```javascript // Check license status const validation = await secureGuard.validateLicense(); console.log('Validation result:', validation); // Common causes: // - Invalid license key // - License expired // - Environment mismatch // - Network connectivity issues ``` #### 2. Database Connection Issues ```javascript // Check connection status const status = secureGuard.getConnectionStatus(); console.log('Database connected:', status.isConnected); // Enable verbose logging const secureGuard = new SecureGuard({ licenseKey: 'your-key', logging: { level: 'debug' } }); ``` #### 3. Offline Mode Issues ```javascript // Check offline status const offlineStatus = secureGuard.getOfflineStatus(); console.log('Offline status:', offlineStatus); // Clear cache if corrupted await secureGuard.clearCache(); ``` #### 4. Usage Limit Exceeded ```javascript // Check current usage const stats = secureGuard.getUsageStats(); console.log('Usage stats:', stats); // Reset usage period (if allowed) await secureGuard.resetUsagePeriod(); ``` ### Debug Mode ```javascript // Enable debug logging const secureGuard = new SecureGuard({ licenseKey: 'your-key', logging: { level: 'debug', enableSecurityLogging: true } }); // Check internal state console.log('SecureGuard state:', secureGuard.getDebugInfo()); ``` ### Error Codes - `INVALID_FORMAT`: License key format is invalid - `NOT_FOUND`: License key not found in database - `EXPIRED`: License has expired - `BLACKLISTED`: License key is blacklisted - `ENVIRONMENT_MISMATCH`: License not authorized for this environment - `USAGE_EXCEEDED`: Usage limits exceeded - `NETWORK_ERROR`: Network connectivity issues - `CACHE_CORRUPTED`: Offline cache is corrupted ## Support ### Getting Help - GitHub Issues: [Repository Issues](https://github.com/your-org/secure-guard/issues) - Documentation: [Full Documentation](https://your-org.github.io/secure-guard) - Email Support: support@your-org.com ### Contributing - Fork the repository - Create a feature branch - Submit a pull request - Follow the contribution guidelines ### License This package is licensed under the MIT License. See LICENSE file for details. --- For more detailed information, please refer to the [API Documentation](API_DOCUMENTATION.md) and [Examples Repository](https://github.com/your-org/secure-guard-examples).