HEX
Server: LiteSpeed
System: Linux CentOS-79-64-minimal 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64
User: vishn3436 (5293)
PHP: 8.0.15
Disabled: NONE
Upload Files
File: //data/silvera-firewall-app/test_direct_sync.js
const { Pool } = require('pg');
const fs = require('fs').promises;
const path = require('path');

const pool = new Pool({
  host: 'database',
  port: 5432,
  database: 'silvera_firewall',
  user: 'admin',
  password: 'silvera_firewall_2024',
});

const BRIDGE_DIR = '/app/bitninja_bridge';
const COMMAND_FILE = path.join(BRIDGE_DIR, 'command.txt');
const RESULT_FILE = path.join(BRIDGE_DIR, 'result.txt');

async function executeBitNinjaCommand(action, ip, comment = '') {
  try {
    const command = `${action} ${ip} ${comment}\n`;
    await fs.writeFile(COMMAND_FILE, command);
    
    let attempts = 0;
    while (attempts < 30) {
      try {
        await fs.access(RESULT_FILE);
        const result = await fs.readFile(RESULT_FILE, 'utf8');
        await fs.unlink(RESULT_FILE);
        return { success: true, message: result.trim() };
      } catch {
        await new Promise(resolve => setTimeout(resolve, 100));
        attempts++;
      }
    }
    
    throw new Error('BitNinja command timeout');
  } catch (error) {
    console.error('BitNinja bridge error:', error);
    return { success: false, message: error.message };
  }
}

async function getBitNinjaWhitelist() {
  try {
    const result = await executeBitNinjaCommand('list', '');
    if (!result.success) {
      return [];
    }
    
    const lines = result.message.split('\n').filter(line => line.trim());
    const ips = [];
    
    for (const line of lines) {
      const trimmedLine = line.trim();
      if (/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/.test(trimmedLine)) {
        ips.push(trimmedLine);
      }
    }
    
    return ips;
  } catch (error) {
    console.error('BitNinja list error:', error);
    return [];
  }
}

async function performDirectSync() {
  try {
    console.log('Starting direct sync test...');
    
    // Get BitNinja IPs
    const bitninjaIPs = await getBitNinjaWhitelist();
    console.log(`Found ${bitninjaIPs.length} IPs from BitNinja:`, bitninjaIPs);
    
    let syncedCount = 0;
    let existingCount = 0;
    
    for (const ip of bitninjaIPs) {
      console.log(`Processing IP: ${ip}`);
      
      // Check if IP already exists in database
      const existing = await pool.query(
        "SELECT id FROM ip_whitelist WHERE ip_address = $1",
        [ip]
      );
      
      if (existing.rows.length === 0) {
        // Add IP to database if not exists
        await pool.query(
          "INSERT INTO ip_whitelist (ip_address, description, admin_id, bitninja_status) VALUES ($1, $2, $3, $4)",
          [ip, "Direct sync test", 1, "whitelisted"]
        );
        syncedCount++;
        console.log(`✅ Added new IP: ${ip}`);
      } else {
        // Update status to whitelisted if exists
        await pool.query(
          "UPDATE ip_whitelist SET bitninja_status = 'whitelisted' WHERE ip_address = $1",
          [ip]
        );
        existingCount++;
        console.log(`✅ Updated existing IP: ${ip}`);
      }
    }
    
    console.log(`\n=== SYNC COMPLETE ===`);
    console.log(`Synced: ${syncedCount} new IPs`);
    console.log(`Updated: ${existingCount} existing IPs`);
    console.log(`Total: ${bitninjaIPs.length} IPs from BitNinja`);
    
    // Verify database state
    const dbResult = await pool.query("SELECT ip_address FROM ip_whitelist WHERE bitninja_status = 'whitelisted' ORDER BY ip_address");
    console.log(`\nDatabase now contains ${dbResult.rows.length} whitelisted IPs:`);
    dbResult.rows.forEach(row => console.log(`  - ${row.ip_address}`));
    
    process.exit(0);
  } catch (error) {
    console.error('Direct sync failed:', error);
    process.exit(1);
  }
}

performDirectSync();