UNPKG

@ufdevsllc/authme2.0

Version:

SDK for license management and remote monitoring with automatic system tracking, license validation, and remote control capabilities

305 lines (256 loc) 10.7 kB
import { describe, it, expect, beforeEach, afterEach, vi, beforeAll } from 'vitest'; import { SystemTracker } from '../system-tracker.js'; import DatabaseManager from '../database-manager.js'; // Mock the DatabaseManager vi.mock('../database-manager.js'); // Mock os module vi.mock('os'); describe('SystemTracker', () => { let systemTracker; let mockDbManager; let mockDb; let mockCollection; beforeAll(async () => { // Mock os module const os = await import('os'); vi.mocked(os.type).mockReturnValue('Linux'); vi.mocked(os.platform).mockReturnValue('linux'); vi.mocked(os.arch).mockReturnValue('x64'); vi.mocked(os.release).mockReturnValue('5.4.0'); vi.mocked(os.hostname).mockReturnValue('test-host'); vi.mocked(os.totalmem).mockReturnValue(8589934592); // 8GB vi.mocked(os.freemem).mockReturnValue(4294967296); // 4GB vi.mocked(os.uptime).mockReturnValue(3600); // 1 hour vi.mocked(os.loadavg).mockReturnValue([0.5, 0.3, 0.1]); vi.mocked(os.cpus).mockReturnValue([ { model: 'Intel Core i7', speed: 2800 }, { model: 'Intel Core i7', speed: 2800 } ]); vi.mocked(os.networkInterfaces).mockReturnValue({ eth0: [ { address: '192.168.1.100', netmask: '255.255.255.0', family: 'IPv4', mac: '00:11:22:33:44:55', internal: false } ], lo: [ { address: '127.0.0.1', netmask: '255.0.0.0', family: 'IPv4', mac: '00:00:00:00:00:00', internal: true } ] }); }); beforeEach(() => { // Clear all mocks vi.clearAllMocks(); // Clear all timers vi.clearAllTimers(); vi.useFakeTimers(); // Create mock collection mockCollection = { updateOne: vi.fn().mockResolvedValue({ upsertedId: 'test-id', modifiedCount: 1 }) }; // Create mock database mockDb = { collection: vi.fn().mockReturnValue(mockCollection) }; // Create mock database manager mockDbManager = { getMonitoringDB: vi.fn().mockReturnValue(mockDb) }; // Mock the DatabaseManager constructor vi.mocked(DatabaseManager).mockImplementation(() => mockDbManager); // Create system tracker instance systemTracker = new SystemTracker(); // Reset environment variables process.env.NODE_ENV = 'test'; process.env.CORS_ORIGINS = 'http://localhost:3000,https://example.com'; process.env.CORS_METHODS = 'GET,POST,PUT,DELETE'; process.env.SERVER_LOCATION = 'Test Server'; process.env.TEST_VAR = 'test-value'; process.env.SECRET_KEY = 'secret-value'; }); afterEach(() => { systemTracker.stopPeriodicTracking(); vi.useRealTimers(); // Clean up environment variables delete process.env.CORS_ORIGINS; delete process.env.CORS_METHODS; delete process.env.SERVER_LOCATION; delete process.env.TEST_VAR; delete process.env.SECRET_KEY; }); describe('collectSystemInfo', () => { it('should collect comprehensive system information', () => { const systemInfo = systemTracker.collectSystemInfo(); expect(systemInfo).toMatchObject({ os: 'Linux', platform: 'linux', arch: 'x64', release: '5.4.0', hostname: 'test-host', memory: { total: 8589934592, free: 4294967296, used: 4294967296 }, cpu: { model: 'Intel Core i7', cores: 2, speed: 2800 }, uptime: 3600, loadAverage: [0.5, 0.3, 0.1] }); expect(systemInfo.networkInterfaces).toBeDefined(); expect(systemInfo.timestamp).toBeInstanceOf(Date); }); }); describe('collectDeploymentInfo', () => { it('should collect deployment information', () => { const deploymentInfo = systemTracker.collectDeploymentInfo(); expect(deploymentInfo).toMatchObject({ nodeVersion: process.version, environment: 'test', processId: process.pid, workingDirectory: process.cwd(), execPath: process.execPath, serverLocation: 'Test Server', ipAddress: '192.168.1.100' }); expect(deploymentInfo.timestamp).toBeInstanceOf(Date); expect(deploymentInfo.startTime).toBeInstanceOf(Date); expect(Array.isArray(deploymentInfo.argv)).toBe(true); }); }); describe('collectCORSInfo', () => { it('should collect CORS information from environment variables', () => { const corsInfo = systemTracker.collectCORSInfo(); expect(corsInfo).toMatchObject({ allowedOrigins: ['http://localhost:3000', 'https://example.com'], allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'], credentials: false, maxAge: 86400 }); expect(corsInfo.timestamp).toBeInstanceOf(Date); }); }); describe('collectEnvironmentVariables', () => { it('should collect and filter environment variables', () => { const envVars = systemTracker.collectEnvironmentVariables(); expect(envVars.variables.TEST_VAR).toBe('test-value'); expect(envVars.variables.SECRET_KEY).toBe('[FILTERED]'); expect(envVars.variables.NODE_ENV).toBe('test'); expect(envVars.count).toBeGreaterThan(0); expect(envVars.filteredCount).toBeGreaterThan(0); expect(envVars.timestamp).toBeInstanceOf(Date); }); }); describe('collectAllTrackingData', () => { it('should collect all tracking data with license key', async () => { const licenseKey = 'test-license-123'; const trackingData = await systemTracker.collectAllTrackingData(licenseKey); expect(trackingData).toMatchObject({ licenseKey: 'test-license-123', isActive: true }); expect(trackingData.systemInfo).toBeDefined(); expect(trackingData.deploymentInfo).toBeDefined(); expect(trackingData.corsSettings).toBeDefined(); expect(trackingData.environmentVariables).toBeDefined(); expect(trackingData.collectionTimestamp).toBeInstanceOf(Date); }); }); describe('saveToMonitoring', () => { it('should save tracking data to monitoring database', async () => { const trackingData = { licenseKey: 'test-license-123', systemInfo: { os: 'Linux' }, isActive: true }; const result = await systemTracker.saveToMonitoring(trackingData); expect(result).toMatchObject({ success: true, operation: 'inserted', id: 'test-id' }); expect(result.timestamp).toBeInstanceOf(Date); // Verify database interaction expect(mockDb.collection).toHaveBeenCalledWith('systemTracking'); expect(mockCollection.updateOne).toHaveBeenCalledWith( { licenseKey: 'test-license-123' }, { $set: { ...trackingData, lastSeen: expect.any(Date) } }, { upsert: true } ); }); }); describe('trackAndSave', () => { it('should collect and save tracking data', async () => { const licenseKey = 'test-license-123'; const result = await systemTracker.trackAndSave(licenseKey); expect(result).toMatchObject({ success: true, operation: 'inserted', id: 'test-id' }); }); }); describe('startPeriodicTracking', () => { it('should start periodic tracking with default interval', async () => { const licenseKey = 'test-license-123'; // Mock trackAndSave to avoid actual database calls systemTracker.trackAndSave = vi.fn().mockResolvedValue({ success: true }); await systemTracker.startPeriodicTracking(licenseKey); // Verify initial call expect(systemTracker.trackAndSave).toHaveBeenCalledWith(licenseKey); // Advance timer and verify periodic call vi.advanceTimersByTime(5 * 60 * 1000); // 5 minutes expect(systemTracker.trackAndSave).toHaveBeenCalledTimes(2); expect(systemTracker.trackingInterval).toBeDefined(); }); }); describe('stopPeriodicTracking', () => { it('should stop periodic tracking', async () => { const licenseKey = 'test-license-123'; systemTracker.trackAndSave = vi.fn().mockResolvedValue({ success: true }); await systemTracker.startPeriodicTracking(licenseKey); expect(systemTracker.trackingInterval).toBeDefined(); systemTracker.stopPeriodicTracking(); expect(systemTracker.trackingInterval).toBeNull(); }); }); describe('private helper methods', () => { describe('_getLocalIPAddress', () => { it('should return local IP address', () => { const ip = systemTracker._getLocalIPAddress(); expect(ip).toBe('192.168.1.100'); }); }); describe('_parseEnvArray', () => { it('should parse comma-separated values', () => { const result = systemTracker._parseEnvArray('value1,value2,value3'); expect(result).toEqual(['value1', 'value2', 'value3']); }); it('should return null for empty or undefined values', () => { expect(systemTracker._parseEnvArray('')).toBeNull(); expect(systemTracker._parseEnvArray(undefined)).toBeNull(); expect(systemTracker._parseEnvArray(null)).toBeNull(); }); }); }); });