# Remote Source ID Blocking System Guide

## Overview

The Remote Source ID Blocking System allows vendors to remotely disable specific deployments when misuse, unauthorized resale, or license violations are detected. Blocked Source IDs cause immediate application failure, providing complete control over software distribution.

## How Remote Blocking Works

### 1. Automatic Blocklist Checking
- Every application startup checks against a remote blocklist
- Blocklist is stored in the secure MongoDB database
- Checks happen before any application functionality loads

### 2. Immediate Application Crash
- Blocked Source IDs cause immediate application termination
- Generic error messages hide the blocking system
- No recovery possible until Source ID is unblocked

### 3. Remote Control
- Vendors can add/remove blocks without code updates
- Changes propagate to all deployments within 24 hours
- No client-side configuration required

### 4. Offline Caching
- Blocklist is cached locally for offline operation
- Cache updates when network connection is available
- Prevents bypass attempts during network outages

## Blocking a Source ID

### Method 1: Via Hidden Monitoring API

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

async function blockSourceIdViaAPI(clientBaseUrl, sourceId, reason) {
  try {
    const response = await axios.post(
      `${clientBaseUrl}/___sg_internal_monitor___/encrypted-token/block`,
      {
        sourceId: sourceId,
        reason: reason,
        blockedBy: 'vendor-admin'
      },
      {
        headers: {
          'X-SG-Vendor-Auth': 'your-master-vendor-key',
          'Content-Type': 'application/json'
        }
      }
    );

    console.log('✅ Source ID blocked successfully');
    console.log('Response:', response.data);
    return response.data;
  } catch (error) {
    console.error('❌ Failed to block Source ID:', error.message);
    return null;
  }
}

// Usage
await blockSourceIdViaAPI(
  'https://client-app.com',
  'SRC-1704067200000-abc123-env456',
  'Unauthorized resale detected'
);
```

### Method 2: Direct Database Access

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

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

// Define blocklist schema
const BlocklistSchema = new mongoose.Schema({
  sourceId: { type: String, required: true, unique: true },
  blockReason: String,
  blockedBy: String,
  blockTime: Date,
  isActive: { type: Boolean, default: true },
  lastChecked: Date
});

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

async function blockSourceId(sourceId, reason, blockedBy = 'vendor-admin') {
  try {
    const block = await Blocklist.create({
      sourceId,
      blockReason: reason,
      blockedBy,
      blockTime: new Date(),
      isActive: true,
      lastChecked: new Date()
    });

    console.log(`🚫 Blocked Source ID: ${sourceId}`);
    console.log(`   Reason: ${reason}`);
    console.log(`   Blocked by: ${blockedBy}`);
    console.log(`   Block time: ${block.blockTime}`);
    console.log(`   ⏰ Block will propagate within 24 hours`);

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

// Usage examples
await blockSourceId('SRC-1704067200000-suspicious-123', 'Unauthorized resale detected');
await blockSourceId('SRC-1704067200000-violation-456', 'License terms violation');
await blockSourceId('SRC-1704067200000-security-789', 'Security breach detected');
```

## Unblocking a Source ID

### Via Hidden Monitoring API

```javascript
async function unblockSourceIdViaAPI(clientBaseUrl, sourceId) {
  try {
    const response = await axios.delete(
      `${clientBaseUrl}/___sg_internal_monitor___/encrypted-token/block/${sourceId}`,
      {
        headers: {
          'X-SG-Vendor-Auth': 'your-master-vendor-key'
        }
      }
    );

    console.log('✅ Source ID unblocked successfully');
    return response.data;
  } catch (error) {
    console.error('❌ Failed to unblock Source ID:', error.message);
    return null;
  }
}
```

### Direct Database Access

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

// Usage
await unblockSourceId('SRC-1704067200000-suspicious-123');
```

## Checking Block Status

### Check Single Source ID

```javascript
async function checkBlockStatus(sourceId) {
  const block = await Blocklist.findOne({ sourceId, isActive: true });
  
  if (block) {
    console.log(`🚫 ${sourceId} is BLOCKED`);
    console.log(`   Reason: ${block.blockReason}`);
    console.log(`   Blocked by: ${block.blockedBy}`);
    console.log(`   Block time: ${block.blockTime}`);
    console.log(`   Last checked: ${block.lastChecked}`);
  } else {
    console.log(`✅ ${sourceId} is NOT blocked`);
  }

  return {
    isBlocked: !!block,
    blockInfo: block
  };
}

// Usage
const status = await checkBlockStatus('SRC-1704067200000-abc123-env456');
```

### Get All Blocked Source IDs

```javascript
async function getAllBlockedSources() {
  const blocked = await Blocklist.find({ isActive: true }).sort({ blockTime: -1 });
  
  console.log(`📋 Currently Blocked Source IDs (${blocked.length}):`);
  blocked.forEach((block, i) => {
    console.log(`\n   ${i+1}. ${block.sourceId}`);
    console.log(`      Reason: ${block.blockReason}`);
    console.log(`      Blocked by: ${block.blockedBy}`);
    console.log(`      Block time: ${block.blockTime}`);
  });

  return blocked;
}

// Usage
const allBlocked = await getAllBlockedSources();
```

## Client-Side Behavior When Blocked

When a blocked Source ID attempts to initialize, the following happens:

### 1. Startup Check
```javascript
// This happens automatically during SecureGuard.initialize()
const secureGuard = new SecureGuard({ licenseKey: 'key' });

try {
  await secureGuard.initialize(); // Blocklist check happens here
  console.log('Application started successfully');
} catch (error) {
  // If Source ID is blocked, this error occurs:
  console.error('Initialization failed - Unable to establish secure connection');
  process.exit(1); // Application cannot start
}
```

### 2. Generic Error Message
```
Error: Initialization failed - Unable to establish secure connection
    at SecureGuard.initialize (secure-guard/index.js:45:11)
    at Application.start (app.js:12:5)

Process finished with exit code 1
```

### 3. No Recovery
- Application cannot start until Source ID is unblocked
- No indication that blocking system exists
- Appears as a generic connection error
- No bypass mechanism available

## Automated Blocking System

### Risk-Based Blocking

```javascript
class AutomatedBlockingSystem {
  constructor() {
    this.mongoUrl = 'mongodb+srv://incrypto09:VcFzmdvSgSbqHx5m@transcoding.jcngo.mongodb.net/auth-me';
  }

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

  async scanForSuspiciousActivity() {
    console.log('🔍 Scanning for suspicious activity...');
    
    const Deployment = mongoose.model('Deployment');
    const RouteMonitor = mongoose.model('RouteMonitor');
    const Blocklist = mongoose.model('Blocklist');

    const deployments = await Deployment.find({});
    const suspiciousDeployments = [];

    for (const deployment of deployments) {
      const sourceId = deployment.sourceId;
      
      // Skip already blocked deployments
      const isBlocked = await Blocklist.findOne({ sourceId, isActive: true });
      if (isBlocked) continue;

      const riskScore = await this.calculateRiskScore(deployment);
      
      if (riskScore.score >= 80) {
        suspiciousDeployments.push({
          sourceId,
          riskScore: riskScore.score,
          reasons: riskScore.reasons,
          deployment
        });
      }
    }

    console.log(`⚠️  Found ${suspiciousDeployments.length} suspicious deployments`);
    return suspiciousDeployments;
  }

  async calculateRiskScore(deployment) {
    const RouteMonitor = mongoose.model('RouteMonitor');
    const sourceId = deployment.sourceId;
    
    let score = 0;
    const reasons = [];

    // Check resale chain depth
    const resaleDepth = deployment.resaleHistory?.length || 0;
    if (resaleDepth > 2) {
      score += 30;
      reasons.push(`Deep resale chain (${resaleDepth} levels)`);
    }

    // Check number of CORS origins
    const corsCount = deployment.corsOrigins?.length || 0;
    if (corsCount > 5) {
      score += 25;
      reasons.push(`Multiple CORS origins (${corsCount})`);
    }

    // Check API usage in last 24 hours
    const last24h = new Date(Date.now() - 24*60*60*1000);
    const apiRequests = await RouteMonitor.countDocuments({
      sourceId,
      timestamp: { $gte: last24h }
    });

    if (apiRequests > 10000) {
      score += 20;
      reasons.push(`High API usage (${apiRequests} requests/24h)`);
    }

    // Check for admin/debug routes
    const suspiciousRoutes = await RouteMonitor.countDocuments({
      sourceId,
      path: { $regex: /(admin|debug|test|dev|internal)/i },
      timestamp: { $gte: last24h }
    });

    if (suspiciousRoutes > 50) {
      score += 15;
      reasons.push(`Suspicious route access (${suspiciousRoutes} admin/debug calls)`);
    }

    // Check for localhost/development environment
    if (deployment.environment?.hostname?.includes('localhost') || 
        deployment.environment?.hostname?.includes('127.0.0.1')) {
      score += 10;
      reasons.push('Development environment detected');
    }

    return { score, reasons };
  }

  async autoBlockSuspicious() {
    const suspicious = await this.scanForSuspiciousActivity();
    const Blocklist = mongoose.model('Blocklist');

    for (const deployment of suspicious) {
      console.log(`🚨 Auto-blocking high-risk deployment: ${deployment.sourceId}`);
      console.log(`   Risk Score: ${deployment.riskScore}/100`);
      console.log(`   Reasons: ${deployment.reasons.join(', ')}`);

      try {
        await Blocklist.create({
          sourceId: deployment.sourceId,
          blockReason: `Auto-blocked: Risk score ${deployment.riskScore} (${deployment.reasons.join(', ')})`,
          blockedBy: 'auto-system',
          blockTime: new Date(),
          isActive: true
        });

        console.log(`   ✅ Successfully blocked ${deployment.sourceId}`);
      } catch (error) {
        console.log(`   ❌ Failed to block ${deployment.sourceId}: ${error.message}`);
      }
    }

    return suspicious.length;
  }

  async startAutomatedMonitoring(intervalMinutes = 60) {
    console.log(`🤖 Starting automated monitoring (every ${intervalMinutes} minutes)`);
    
    setInterval(async () => {
      try {
        const blockedCount = await this.autoBlockSuspicious();
        if (blockedCount > 0) {
          console.log(`🚫 Auto-blocked ${blockedCount} suspicious deployments`);
        }
      } catch (error) {
        console.error('❌ Automated monitoring error:', error.message);
      }
    }, intervalMinutes * 60 * 1000);
  }
}

// Usage
const autoBlocker = new AutomatedBlockingSystem();
await autoBlocker.connect();

// Run once
const suspicious = await autoBlocker.scanForSuspiciousActivity();
console.log('Suspicious deployments:', suspicious);

// Start automated monitoring
await autoBlocker.startAutomatedMonitoring(30); // Check every 30 minutes
```

## Block Reasons and Categories

### Common Block Reasons

1. **Unauthorized Resale**
   - Code sold without permission
   - Deep resale chains (A→B→C→D)
   - Resale to competitors

2. **License Violation**
   - Usage exceeds license terms
   - Multiple deployments on single license
   - Commercial use on personal license

3. **Security Breach**
   - Compromised deployment detected
   - Suspicious access patterns
   - Tamper detection triggered

4. **Suspicious Activity**
   - Unusual API usage patterns
   - Multiple CORS origins
   - Development environment in production

5. **Non-Payment**
   - License fees not paid
   - Subscription expired
   - Payment disputes

6. **Terms Violation**
   - Breach of usage terms
   - Prohibited use cases
   - Reverse engineering attempts

### Block Reason Examples

```javascript
// Specific block reasons for different scenarios
const blockReasons = {
  unauthorizedResale: 'Unauthorized resale to third party detected',
  deepResale: 'Resale chain exceeds maximum depth (3 levels)',
  licenseViolation: 'Usage exceeds license limits by 300%',
  securityBreach: 'Multiple tamper detection events triggered',
  suspiciousActivity: 'Unusual API patterns detected (10k+ requests/hour)',
  nonPayment: 'License subscription expired - payment overdue',
  termsViolation: 'Prohibited use case detected (cryptocurrency mining)',
  developmentInProduction: 'Development environment detected in production use',
  multipleDeployments: 'Single license used across multiple deployments',
  competitorResale: 'Resale to direct competitor organization'
};

// Usage
await blockSourceId('SRC-123-456-789', blockReasons.unauthorizedResale);
```

## Vendor Management Interface

### Complete Blocking Management System

```javascript
class BlockingManagementInterface {
  constructor() {
    this.mongoUrl = 'mongodb+srv://incrypto09:VcFzmdvSgSbqHx5m@transcoding.jcngo.mongodb.net/auth-me';
  }

  async connect() {
    await mongoose.connect(this.mongoUrl);
    console.log('✅ Connected to blocking management system');
  }

  async blockSourceId(sourceId, reason, blockedBy = 'manual-admin') {
    const Blocklist = mongoose.model('Blocklist');
    
    try {
      const block = await Blocklist.create({
        sourceId,
        blockReason: reason,
        blockedBy,
        blockTime: new Date(),
        isActive: true,
        lastChecked: new Date()
      });

      console.log(`🚫 Successfully blocked: ${sourceId}`);
      console.log(`   Reason: ${reason}`);
      console.log(`   Blocked by: ${blockedBy}`);
      console.log(`   Time: ${block.blockTime}`);

      return { success: true, block };
    } catch (error) {
      if (error.code === 11000) {
        console.log(`⚠️  ${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(`✅ Successfully unblocked: ${sourceId}`);
      return { success: true };
    } else {
      console.log(`⚠️  ${sourceId} was not blocked`);
      return { success: false, reason: 'Not blocked' };
    }
  }

  async listBlockedSources() {
    const Blocklist = mongoose.model('Blocklist');
    const blocked = await Blocklist.find({ isActive: true }).sort({ blockTime: -1 });
    
    console.log(`\n📋 Currently Blocked Source IDs (${blocked.length}):`);
    blocked.forEach((block, i) => {
      console.log(`\n   ${i+1}. ${block.sourceId}`);
      console.log(`      Reason: ${block.blockReason}`);
      console.log(`      Blocked by: ${block.blockedBy}`);
      console.log(`      Time: ${block.blockTime}`);
    });

    return blocked;
  }

  async getBlockingStats() {
    const Blocklist = mongoose.model('Blocklist');
    
    const totalBlocked = await Blocklist.countDocuments({ isActive: true });
    const last24h = new Date(Date.now() - 24*60*60*1000);
    const recentBlocks = await Blocklist.countDocuments({
      isActive: true,
      blockTime: { $gte: last24h }
    });

    const blockReasons = await Blocklist.aggregate([
      { $match: { isActive: true } },
      { $group: { _id: '$blockedBy', count: { $sum: 1 } } },
      { $sort: { count: -1 } }
    ]);

    console.log('\n📊 Blocking Statistics:');
    console.log(`   Total Blocked: ${totalBlocked}`);
    console.log(`   Blocked (24h): ${recentBlocks}`);
    console.log('\n   Blocks by Admin:');
    blockReasons.forEach(reason => {
      console.log(`     ${reason._id}: ${reason.count}`);
    });

    return {
      totalBlocked,
      recentBlocks,
      blockReasons
    };
  }

  async bulkBlock(sourceIds, reason, blockedBy = 'bulk-admin') {
    const Blocklist = mongoose.model('Blocklist');
    const results = [];

    for (const sourceId of sourceIds) {
      try {
        await Blocklist.create({
          sourceId,
          blockReason: reason,
          blockedBy,
          blockTime: new Date(),
          isActive: true
        });
        results.push({ sourceId, success: true });
        console.log(`✅ Blocked: ${sourceId}`);
      } catch (error) {
        results.push({ sourceId, success: false, error: error.message });
        console.log(`❌ Failed to block: ${sourceId} - ${error.message}`);
      }
    }

    const successCount = results.filter(r => r.success).length;
    console.log(`\n📊 Bulk blocking complete: ${successCount}/${sourceIds.length} successful`);

    return results;
  }
}

// Usage examples
const blockingInterface = new BlockingManagementInterface();
await blockingInterface.connect();

// Block specific Source IDs
await blockingInterface.blockSourceId(
  'SRC-1704067200000-resale-123',
  'Unauthorized resale to competitor',
  'security-team'
);

// Bulk block multiple Source IDs
const suspiciousSources = [
  'SRC-1704067200000-suspicious-1',
  'SRC-1704067200000-suspicious-2',
  'SRC-1704067200000-suspicious-3'
];

await blockingInterface.bulkBlock(
  suspiciousSources,
  'Bulk block: Suspicious activity pattern detected',
  'auto-system'
);

// Get blocking statistics
await blockingInterface.getBlockingStats();

// List all blocked sources
await blockingInterface.listBlockedSources();
```

## Best Practices

### 1. Document All Blocks
Always provide clear, specific reasons for blocking:

```javascript
// Good - Specific and actionable
await blockSourceId('SRC-123', 'Unauthorized resale to CompetitorCorp detected on 2024-01-20');

// Bad - Vague and unhelpful
await blockSourceId('SRC-123', 'Violation detected');
```

### 2. Monitor Before Blocking
Analyze deployment patterns before taking action:

```javascript
// Analyze before blocking
const riskScore = await calculateRiskScore(deployment);
if (riskScore.score > 80) {
  console.log(`High risk deployment: ${deployment.sourceId}`);
  console.log(`Reasons: ${riskScore.reasons.join(', ')}`);
  
  // Consider warning first for borderline cases
  if (riskScore.score < 90) {
    await sendWarningToClient(deployment.sourceId);
  } else {
    await blockSourceId(deployment.sourceId, `High risk: ${riskScore.reasons.join(', ')}`);
  }
}
```

### 3. Implement Graduated Response
Use warnings before blocking when appropriate:

```javascript
class GraduatedResponseSystem {
  async handleSuspiciousActivity(sourceId, riskScore, reasons) {
    if (riskScore >= 90) {
      // Immediate block for high risk
      await this.blockSourceId(sourceId, `Critical risk: ${reasons.join(', ')}`);
    } else if (riskScore >= 70) {
      // Warning for medium risk
      await this.sendWarning(sourceId, reasons);
      await this.scheduleReview(sourceId, 7); // Review in 7 days
    } else if (riskScore >= 50) {
      // Monitor for low-medium risk
      await this.flagForMonitoring(sourceId, reasons);
    }
  }
}
```

### 4. Regular Review Process
Periodically review blocked Source IDs:

```javascript
async function reviewBlockedSources() {
  const Blocklist = mongoose.model('Blocklist');
  const oldBlocks = await Blocklist.find({
    isActive: true,
    blockTime: { $lt: new Date(Date.now() - 30*24*60*60*1000) } // 30 days old
  });

  console.log(`📋 Reviewing ${oldBlocks.length} blocks older than 30 days`);
  
  for (const block of oldBlocks) {
    console.log(`\n🔍 Reviewing: ${block.sourceId}`);
    console.log(`   Blocked: ${block.blockTime}`);
    console.log(`   Reason: ${block.blockReason}`);
    
    // Check if issue is resolved
    const currentRisk = await assessCurrentRisk(block.sourceId);
    if (currentRisk.score < 30) {
      console.log(`   ✅ Risk reduced - consider unblocking`);
    } else {
      console.log(`   ⚠️  Still high risk - maintain block`);
    }
  }
}

// Schedule monthly review
setInterval(reviewBlockedSources, 30 * 24 * 60 * 60 * 1000); // Every 30 days
```

**Requirements Addressed:** 8.1 - Complete documentation of remote Source ID blocking system with immediate application crash for blocked sources.