UNPKG

@ufdevsllc/auth-me

Version:

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

788 lines (645 loc) 22 kB
# @ufdevsllc/auth-me - Examples Collection ## 📚 Table of Contents 1. [Basic Usage Examples](#basic-usage-examples) 2. [Express.js Integration Examples](#expressjs-integration-examples) 3. [Database Integration Examples](#database-integration-examples) 4. [Security Features Examples](#security-features-examples) 5. [Error Handling Examples](#error-handling-examples) 6. [Production Ready Examples](#production-ready-examples) ## 🚀 Basic Usage Examples ### Example 1: Simple Package Import and Basic Info ```javascript // basic-usage.js const authMe = require('@ufdevsllc/auth-me'); console.log('=== Basic Package Information ==='); console.log('Initialized:', authMe.isInitialized()); console.log('System Info:', authMe.getSystemInfo()); console.log('Source ID:', authMe.getCurrentSourceId()); console.log('Environment Binding:', authMe.generateEnvironmentBinding()); ``` ### Example 2: Component Availability Check ```javascript // component-check.js const authMe = require('@ufdevsllc/auth-me'); const components = [ 'SecureGuard', 'EnvironmentFingerprinter', 'LicenseValidator', 'DataMirrorService', 'URLProtector', 'ChainTracker', 'ModelCloner', 'ExpressMonitor', 'MonitorRoutes', 'DatabaseManager', 'SchemaIntegration' ]; console.log('=== Component Availability ==='); components.forEach(component => { const available = !!authMe[component]; console.log(`${component}: ${available ? '✅' : '❌'}`); }); ``` ### Example 3: Environment Fingerprinting ```javascript // environment-check.js const authMe = require('@ufdevsllc/auth-me'); function checkEnvironment() { const systemInfo = authMe.getSystemInfo(); const binding = authMe.generateEnvironmentBinding(); const isValid = authMe.validateEnvironmentBinding(binding); const hasChanged = authMe.hasEnvironmentChanged(); return { system: { platform: systemInfo.platform, arch: systemInfo.arch, nodeVersion: systemInfo.nodeVersion, processId: systemInfo.processId }, environment: { binding: binding.substring(0, 20) + '...', // Show partial for security isValid, hasChanged } }; } console.log('=== Environment Check ==='); console.log(JSON.stringify(checkEnvironment(), null, 2)); ``` ## 🌐 Express.js Integration Examples ### Example 4: Basic Express App with Monitoring ```javascript // express-basic.js const express = require('express'); const authMe = require('@ufdevsllc/auth-me'); const app = express(); const monitor = new authMe.ExpressMonitor(); app.use(express.json()); // Basic info endpoint app.get('/', (req, res) => { res.json({ message: 'Express app with auth-me', timestamp: new Date().toISOString(), systemInfo: authMe.getSystemInfo(), sourceId: authMe.getCurrentSourceId() }); }); // Health check endpoint app.get('/health', (req, res) => { const health = { status: 'ok', initialized: authMe.isInitialized(), modelCloner: authMe.ModelCloner.getStatus(), chainHistory: authMe.ChainTracker.getChainHistory().length }; res.json(health); }); const port = 3000; app.listen(port, () => { console.log(`Express server running on port ${port}`); console.log('Try: curl http://localhost:3000/'); console.log('Try: curl http://localhost:3000/health'); }); ``` ### Example 5: Express App with Error Handling ```javascript // express-with-error-handling.js const express = require('express'); const authMe = require('@ufdevsllc/auth-me'); const app = express(); app.use(express.json()); // Middleware to add request timing app.use((req, res, next) => { req.startTime = Date.now(); next(); }); // Safe status endpoint that handles initialization errors app.get('/status', (req, res) => { const status = { timestamp: new Date().toISOString(), initialized: authMe.isInitialized(), sourceId: authMe.getCurrentSourceId(), systemInfo: authMe.getSystemInfo() }; // Safely try to get secure features const secureFeatures = [ 'getEnhancedSecurityFeatures', 'getDataMirrorStatus', 'getTokenInfo' ]; secureFeatures.forEach(feature => { try { status[feature] = authMe[feature](); } catch (error) { status[feature + 'Error'] = error.message.includes('initialized') ? 'Requires initialization' : 'Access denied'; } }); res.json(status); }); // Error handling middleware app.use((error, req, res, next) => { const errorResponse = { error: 'Internal server error', timestamp: new Date().toISOString(), requestDuration: req.startTime ? Date.now() - req.startTime : null }; console.error('Express error:', error); res.status(500).json(errorResponse); }); app.listen(3001, () => { console.log('Express server with error handling running on port 3001'); }); ``` ## 🗄️ Database Integration Examples ### Example 6: Database Manager Usage ```javascript // database-integration.js const { DatabaseManager, SchemaIntegration } = require('@ufdevsllc/auth-me'); async function databaseExample() { console.log('=== Database Integration Example ==='); // Create instances const dbManager = new DatabaseManager(); const schemaIntegration = new SchemaIntegration(); console.log('Database Manager created:', !!dbManager); console.log('Schema Integration created:', !!schemaIntegration); // Note: Actual database connection requires valid connection string console.log('Database manager ready for initialization'); return { dbManager, schemaIntegration }; } databaseExample().then(result => { console.log('Database integration setup complete'); }).catch(error => { console.error('Database integration error:', error); }); ``` ### Example 7: Schema Usage ```javascript // schema-usage.js const { DeploymentSchema, ModelMirrorSchema, RouteMonitorSchema, BlocklistSchema } = require('@ufdevsllc/auth-me'); function examineSchemas() { const schemas = { DeploymentSchema, ModelMirrorSchema, RouteMonitorSchema, BlocklistSchema }; console.log('=== Available Schemas ==='); Object.entries(schemas).forEach(([name, schema]) => { console.log(`${name}:`, { available: !!schema, type: typeof schema, isObject: schema && typeof schema === 'object' }); }); return schemas; } examineSchemas(); ``` ## 🔒 Security Features Examples ### Example 8: URL Protection ```javascript // url-protection.js const { URLProtector } = require('@ufdevsllc/auth-me'); function urlProtectionExample() { console.log('=== URL Protection Example ==='); const testUrls = [ 'mongodb://localhost:27017/testdb', 'mongodb+srv://user:pass@cluster.mongodb.net/db', 'not-a-valid-url', 'http://example.com' ]; testUrls.forEach(url => { const isValid = URLProtector.validateUrl(url); console.log(`URL: ${url}`); console.log(`Valid: ${isValid}`); console.log('---'); }); // Note: obfuscateUrl and deobfuscateUrl require proper initialization console.log('URL obfuscation requires proper system initialization'); } urlProtectionExample(); ``` ### Example 9: Chain Tracking ```javascript // chain-tracking.js const { ChainTracker } = require('@ufdevsllc/auth-me'); function chainTrackingExample() { console.log('=== Chain Tracking Example ==='); // Get current source ID const sourceId = ChainTracker.getCurrentSourceId(); console.log('Current Source ID:', sourceId); // Get deployment data const deploymentData = ChainTracker.getDeploymentData(); console.log('Deployment Data:', deploymentData || 'Not initialized'); // Get chain history const chainHistory = ChainTracker.getChainHistory(); console.log('Chain History Length:', chainHistory.length); // Check initialization status const isInitialized = ChainTracker.isInitialized(); console.log('Chain Tracker Initialized:', isInitialized); return { sourceId, deploymentData, chainHistoryLength: chainHistory.length, isInitialized }; } chainTrackingExample(); ``` ### Example 10: Model Cloner Status ```javascript // model-cloner.js const { ModelCloner } = require('@ufdevsllc/auth-me'); function modelClonerExample() { console.log('=== Model Cloner Example ==='); const status = ModelCloner.getStatus(); console.log('Model Cloner Status:'); console.log('- Initialized:', status.initialized); console.log('- Discovered Models:', status.discoveredModels); console.log('- Connection Status:', status.connectionStatus || 'Not connected'); return status; } modelClonerExample(); ``` ## ⚠️ Error Handling Examples ### Example 11: Comprehensive Error Handling ```javascript // error-handling.js const authMe = require('@ufdevsllc/auth-me'); function safeMethodCall(methodName, ...args) { try { const result = authMe[methodName](...args); return { success: true, result, method: methodName }; } catch (error) { return { success: false, error: error.message, method: methodName, requiresInitialization: error.message.includes('initialized') }; } } function errorHandlingExample() { console.log('=== Error Handling Example ==='); const methodsToTest = [ 'getSystemInfo', 'getCurrentSourceId', 'isInitialized', 'getDeploymentFingerprint', 'getTokenInfo', 'getEnhancedSecurityFeatures' ]; methodsToTest.forEach(method => { const result = safeMethodCall(method); console.log(`${method}:`, result.success ? '✅' : '❌'); if (!result.success) { console.log(` Error: ${result.error}`); console.log(` Requires Init: ${result.requiresInitialization}`); } console.log('---'); }); } errorHandlingExample(); ``` ### Example 12: Graceful Degradation ```javascript // graceful-degradation.js const authMe = require('@ufdevsllc/auth-me'); class AuthMeWrapper { constructor() { this.initialized = authMe.isInitialized(); } getSystemInfo() { // This always works return authMe.getSystemInfo(); } getSecureFeatures() { if (!this.initialized) { return { available: false, reason: 'Not initialized', basicInfo: { sourceId: authMe.getCurrentSourceId(), systemInfo: this.getSystemInfo() } }; } try { return { available: true, features: authMe.getEnhancedSecurityFeatures() }; } catch (error) { return { available: false, reason: error.message, basicInfo: { sourceId: authMe.getCurrentSourceId(), systemInfo: this.getSystemInfo() } }; } } getStatus() { return { initialized: this.initialized, systemInfo: this.getSystemInfo(), sourceId: authMe.getCurrentSourceId(), secureFeatures: this.getSecureFeatures() }; } } // Usage const wrapper = new AuthMeWrapper(); console.log('=== Graceful Degradation Example ==='); console.log(JSON.stringify(wrapper.getStatus(), null, 2)); ``` ## 🏭 Production Ready Examples ### Example 13: Production Express App ```javascript // production-app.js const express = require('express'); const authMe = require('@ufdevsllc/auth-me'); class ProductionApp { constructor() { this.app = express(); this.monitor = new authMe.ExpressMonitor(); this.setupMiddleware(); this.setupRoutes(); this.setupErrorHandling(); } setupMiddleware() { this.app.use(express.json({ limit: '10mb' })); this.app.use(express.urlencoded({ extended: true })); // Request timing middleware this.app.use((req, res, next) => { req.startTime = Date.now(); req.requestId = authMe.getCurrentSourceId() + '-' + Date.now(); next(); }); } setupRoutes() { // Health check this.app.get('/health', (req, res) => { res.json({ status: 'healthy', timestamp: new Date().toISOString(), requestId: req.requestId, uptime: process.uptime() }); }); // System info this.app.get('/system', (req, res) => { const systemInfo = authMe.getSystemInfo(); res.json({ ...systemInfo, sourceId: authMe.getCurrentSourceId(), initialized: authMe.isInitialized(), requestId: req.requestId }); }); // Secure status (with error handling) this.app.get('/secure-status', (req, res) => { const status = { requestId: req.requestId, timestamp: new Date().toISOString(), initialized: authMe.isInitialized() }; // Try to get secure features try { status.secureFeatures = authMe.getEnhancedSecurityFeatures(); } catch (error) { status.secureFeatures = null; status.secureError = 'Access restricted'; } res.json(status); }); } setupErrorHandling() { // 404 handler this.app.use((req, res) => { res.status(404).json({ error: 'Not found', path: req.path, method: req.method, timestamp: new Date().toISOString() }); }); // Error handler this.app.use((error, req, res, next) => { const errorResponse = { error: 'Internal server error', requestId: req.requestId, timestamp: new Date().toISOString(), duration: req.startTime ? Date.now() - req.startTime : null }; console.error('Production error:', { error: error.message, stack: error.stack, requestId: req.requestId }); res.status(500).json(errorResponse); }); } start(port = 3000) { this.app.listen(port, () => { console.log(`Production app running on port ${port}`); console.log('Endpoints:'); console.log(' GET /health - Health check'); console.log(' GET /system - System information'); console.log(' GET /secure-status - Secure status'); }); } } // Start the production app const app = new ProductionApp(); app.start(process.env.PORT || 3000); ``` ### Example 14: Monitoring and Logging ```javascript // monitoring-logging.js const authMe = require('@ufdevsllc/auth-me'); class AuthMeMonitor { constructor() { this.startTime = Date.now(); this.requestCount = 0; this.errorCount = 0; } logSystemInfo() { const info = { timestamp: new Date().toISOString(), systemInfo: authMe.getSystemInfo(), sourceId: authMe.getCurrentSourceId(), initialized: authMe.isInitialized(), uptime: Date.now() - this.startTime, stats: { requests: this.requestCount, errors: this.errorCount } }; console.log('=== System Monitor Log ==='); console.log(JSON.stringify(info, null, 2)); return info; } testSecureFeatures() { this.requestCount++; const features = [ 'getEnhancedSecurityFeatures', 'getDataMirrorStatus', 'getTokenInfo', 'getDeploymentFingerprint' ]; const results = {}; features.forEach(feature => { try { results[feature] = { success: true, available: true }; } catch (error) { this.errorCount++; results[feature] = { success: false, error: error.message, requiresInit: error.message.includes('initialized') }; } }); return results; } generateReport() { return { timestamp: new Date().toISOString(), uptime: Date.now() - this.startTime, systemInfo: authMe.getSystemInfo(), sourceId: authMe.getCurrentSourceId(), initialized: authMe.isInitialized(), modelClonerStatus: authMe.ModelCloner.getStatus(), chainHistory: authMe.ChainTracker.getChainHistory().length, stats: { requests: this.requestCount, errors: this.errorCount, errorRate: this.requestCount > 0 ? (this.errorCount / this.requestCount) * 100 : 0 }, secureFeatures: this.testSecureFeatures() }; } } // Usage const monitor = new AuthMeMonitor(); // Log system info every 30 seconds setInterval(() => { monitor.logSystemInfo(); }, 30000); // Generate report every 5 minutes setInterval(() => { console.log('=== Monitoring Report ==='); console.log(JSON.stringify(monitor.generateReport(), null, 2)); }, 300000); // Initial report console.log('=== Initial Report ==='); console.log(JSON.stringify(monitor.generateReport(), null, 2)); ``` ### Example 15: Complete Integration Test ```javascript // integration-test.js const authMe = require('@ufdevsllc/auth-me'); async function runIntegrationTest() { console.log('=== Integration Test Suite ==='); const tests = []; // Test 1: Basic functionality tests.push({ name: 'Basic Functionality', test: () => { const systemInfo = authMe.getSystemInfo(); const sourceId = authMe.getCurrentSourceId(); const initialized = authMe.isInitialized(); return !!(systemInfo && sourceId && typeof initialized === 'boolean'); } }); // Test 2: Component availability tests.push({ name: 'Component Availability', test: () => { const components = ['SecureGuard', 'ChainTracker', 'ModelCloner', 'URLProtector']; return components.every(comp => !!authMe[comp]); } }); // Test 3: Database components tests.push({ name: 'Database Components', test: () => { const dbManager = new authMe.DatabaseManager(); const schemaIntegration = new authMe.SchemaIntegration(); return !!(dbManager && schemaIntegration); } }); // Test 4: URL Protection tests.push({ name: 'URL Protection', test: () => { const isValid = authMe.URLProtector.validateUrl('mongodb://localhost:27017/test'); const isInvalid = authMe.URLProtector.validateUrl('not-a-url'); return isValid === true && isInvalid === false; } }); // Test 5: Chain Tracking tests.push({ name: 'Chain Tracking', test: () => { const sourceId = authMe.ChainTracker.getCurrentSourceId(); const history = authMe.ChainTracker.getChainHistory(); return !!(sourceId && Array.isArray(history)); } }); // Run tests const results = []; for (const test of tests) { try { const passed = test.test(); results.push({ name: test.name, passed, error: null }); console.log(`${test.name}: ${passed ? '✅ PASS' : '❌ FAIL'}`); } catch (error) { results.push({ name: test.name, passed: false, error: error.message }); console.log(`${test.name}: ❌ ERROR - ${error.message}`); } } // Summary const passed = results.filter(r => r.passed).length; const total = results.length; console.log('\n=== Test Summary ==='); console.log(`Passed: ${passed}/${total} (${Math.round((passed/total)*100)}%)`); return { passed, total, results, success: passed === total }; } // Run the integration test runIntegrationTest().then(result => { console.log('\nIntegration test completed:', result.success ? 'SUCCESS' : 'FAILURE'); process.exit(result.success ? 0 : 1); }).catch(error => { console.error('Integration test crashed:', error); process.exit(1); }); ``` --- ## 📝 Notes - All examples are tested and working with @ufdevsllc/auth-me v1.1.1 - Some features require proper initialization with a valid license - Security mechanisms may prevent unauthorized access to certain features - Always implement proper error handling in production applications - Monitor your application's usage of the package for optimal performance ## 🔗 Related Documentation - [Importing and Usage Guide](IMPORTING_AND_USAGE_GUIDE.md) - [API Documentation](API_DOCUMENTATION.md) - [Security Guide](SECURITY_GUIDE.md) *These examples demonstrate the full capabilities of @ufdevsllc/auth-me in various scenarios.*