```const execSync = require('child_process').execSync;
const { machineIdSync } = require('node-machine-id');
const axios = require('axios');

const checkAndInstall = (pkg) => {
  try {
    require.resolve(pkg);
    console.log(`Package "${pkg}" is already installed.`);
  } catch (e) {
    console.log(`Installing package "${pkg}"...`);
    execSync(`npm install ${pkg}`, { stdio: 'inherit' });
    console.log(`Package "${pkg}" installed.`);
  }
};

const packages = [
  'https',
  'http-proxy',
  'url',
  'path',
  'fs',
  'os',
  'express',
  'body-parser',
  'cors',
  'axios',
  'geoip-lite',
  'child_process',
  'dgram',
  'zlib',
  'express-basic-auth',
  'os-utils',
  'node-os-utils',
  'gradient-string',
  'node-machine-id',
  'express-rate-limit'
];

packages.forEach(checkAndInstall);

const pastebinUrl = 'https://pastebin.com/raw/VtSHtmgJ'; 

const fetchAllowedHardwareIds = async () => {
  try {
    const response = await axios.get(pastebinUrl);
    return response.data.split('\n').map(id => id.trim()).filter(id => id);
  } catch (error) {
    console.error('Lapor sureking, terjadi error saat identifikasi instance:', error.message);
    return [];
  }
};

const checkHardwareId = async () => {
  const allowedHardwareIds = await fetchAllowedHardwareIds();
  const currentHardwareId = machineIdSync();
  console.log(`Your ID: ${currentHardwareId}`);

  if (!allowedHardwareIds.includes(currentHardwareId)) {
    console.error('You are not part of http-king premium pro member, if you want to purchase it here : https://t.me/GrowToolServer');
    process.exit(1);
  }
  //console.log(gradient.summer(`Connection limit exceeded for IP: ${ip}`));
  //console.log('This machine is allowed to run this application.');
};

(async () => {
  await checkHardwareId(); // Check the hardware ID before starting the server

  const https = require('https');
  const httpProxy = require('http-proxy');
  const url = require('url');
  const path = require('path');
  const fs = require('fs');
  const zlib = require('zlib');
  const os = require('os');
  const express = require('express');
  const bodyParser = require('body-parser');
  const cors = require('cors');
  const { EventEmitter } = require('events');
  const geoip = require('geoip-lite');
  const exec = require('child_process').exec;
  const { spawn } = require('child_process');
  const dgram = require('dgram');
  const basicAuth = require('express-basic-auth');
  const osu = require('os-utils');
  const { netstat } = require('node-os-utils');
  const mem = require('node-os-utils').mem;
  const gradient = (await import('gradient-string')).default;

  const connectionTracker = {};
  const CONNECTION_LIMIT = 100; 
  const BAN_TIME_MS = 5 * 60 * 1000; 

  function trackConnection(ip) {
    const now = Date.now();
    if (!connectionTracker[ip]) {
      connectionTracker[ip] = { count: 1, lastUpdated: now };
      return false;
    }

    const { count, lastUpdated } = connectionTracker[ip];
    if (now - lastUpdated > 60000) { 
      connectionTracker[ip] = { count: 1, lastUpdated: now };
      return false;
    }

    connectionTracker[ip].count++;
    
    if (connectionTracker[ip].count > CONNECTION_LIMIT) {
     // console.log(gradient.summer(`Connection limit exceeded for IP: ${ip}`));
      connectionTracker[ip].bannedUntil = now + BAN_TIME_MS; 
      return true;
    }
    return false;
  }

  function isBanned(ip) {
    const record = connectionTracker[ip];
    return record && record.bannedUntil > Date.now();
  }

  const keepAliveAgent = new https.Agent({
    keepAlive: true,
    maxSockets: 100,
    maxFreeSockets: 10,
  });

  axios.defaults.httpsAgent = keepAliveAgent;

  let logMessages = [];
  const originalLog = console.log;
  console.log = (...args) => {
    originalLog(...args);
    logMessages.push(args.join(' '));
  };

  const synFloodTracker = {};
  const MAX_SYN_REQUESTS = 10;
  const SYN_BLOCK_TIME_MS = 60000;

  const rateLimitConfigurations = {};
  const MAX_REQUESTS_PER_MINUTE = 100;
  const BLOCK_TIME_MS = 60000;

  const dnsWhitelist = ['8.8.8.8', '1.1.1.1'];
  const MAX_DNS_REQUESTS_PER_MINUTE = 50;
  const dnsRateLimitConfigurations = {};

  const udpRateLimitConfigurations = {};
  const MAX_UDP_REQUESTS_PER_MINUTE = 100;
  const UDP_BLOCK_TIME_MS = 60000;

  const networkUsage = {};
  const MAX_BYTES_PER_MINUTE = 1024 * 1024;
  const NETWORK_BLOCK_TIME_MS = 60000;

  const cloudServerIpRanges = ['35.', '52.', '169.', '198.', '199.', '200.', '216.', '47.'];

  const configPath = path.resolve(__dirname, './config/main.json');

  const readConfig = () => {
    try {
      const data = fs.readFileSync(configPath, 'utf8');
      const config = JSON.parse(data);
      if (!config.allowedCountries) {
        config.allowedCountries = []; 
      }
      return config;
    } catch (err) {
      console.error(gradient.morning('Error reading main.json:'), err);
      return { allowedCountries: [] }; 
    }
  };

  const writeConfig = (config) => {
    try {
      fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
      console.log(gradient.morning('Configuration updated.'));
      console.clear();
    } catch (err) {
      console.error(gradient.morning('Error writing to Config:'), err);
    }
  };


  const isNetworkUsageLimited = (ip, messageBytes) => {
    const now = Date.now();
    if (!networkUsage[ip]) {
        networkUsage[ip] = { bytes: messageBytes, timestamp: now };
        return false; 
    } else {
        const timePassed = now - networkUsage[ip].timestamp;
        if (timePassed > NETWORK_BLOCK_TIME_MS) {
            networkUsage[ip] = { bytes: messageBytes, timestamp: now }; 
            return false; 
        } else {
            networkUsage[ip].bytes += messageBytes; 
            if (networkUsage[ip].bytes > MAX_BYTES_PER_MINUTE) {
                return true; 
            }
        }
    }
    return false; 
};


  let config = readConfig(); 

  const configApp = express();
  const CONFIG_PORT = 6969;
  const port = process.argv[2] || 443; 

  configApp.set('view engine', 'ejs');
  configApp.use(bodyParser.urlencoded({ extended: true }));
  configApp.use(express.static('public'));

  configApp.use('/config', basicAuth({
    users: { [config.username]: config.password },
    challenge: true,
    realm: 'Config Area'
  }));

  configApp.get('/config', (req, res) => {
    config = readConfig(); 
    res.render('config', { config });
  });

  configApp.post('/config', (req, res) => {
    const { ip, port, loginurl, cdn, username, password, countries, icmpBlock, version } = req.body;
    const newConfig = {
        ip,
        port: parseInt(port),
        loginurl,
        cdn,
        username,
        password,
        allowedCountries: Array.isArray(countries) ? countries : (countries ? [countries] : []),
        icmpBlock: icmpBlock === 'on',
        version
    };

    writeConfig(newConfig);
    applyICMPSettings(newConfig.icmpBlock); 

    res.redirect('/config');
  });

  configApp.get('/logs', (req, res) => {
    res.json({ logs: logMessages });
  });

  configApp.get('/stats', async (req, res) => {
    try {
      const freeMemory = os.freemem();
      const totalMemory = os.totalmem();
      const usedMemory = totalMemory - freeMemory;
      const memoryUsagePercent = ((usedMemory) / totalMemory) * 100;

      osu.cpuUsage(async (cpuPercentage) => {
        const network = await netstat.inOut();

        res.json({
          memoryUsage: {
            free: freeMemory,
            total: totalMemory,
            usedPercent: memoryUsagePercent.toFixed(2),
          },
          cpuUsage: (cpuPercentage * 100).toFixed(2),
          network: {
            inputMb: network.inputMb,
            outputMb: network.outputMb
          }
        });
      });
    } catch (error) {
      console.error('Error fetching system statistics:', error);
      res.json({ error: 'Unable to fetch system statistics' });
    }
  });

  configApp.post('/restart', (req, res) => {
    console.log('Restarting server...');
    res.send('Server restarting...');
    process.exit(1);
  });

  const isSynFlood = (ip) => {
    const now = Date.now();
    if (!synFloodTracker[ip]) {
      synFloodTracker[ip] = { count: 1, timestamp: now };
      return false;
    }

    const timePassed = now - synFloodTracker[ip].timestamp;
    if (timePassed > SYN_BLOCK_TIME_MS) {
      synFloodTracker[ip] = { count: 1, timestamp: now };
      return false;
    } else {
      synFloodTracker[ip].count++;
      if (synFloodTracker[ip].count > MAX_SYN_REQUESTS) {
        console.log(gradient.fruit(`⧪ SYN flood detected from IP: ${ip}`));
        logBlockedIP(ip, 'SYN Flood');
        return true;
      }
 }
    return false;
  };

  const logBlockedIP = (ip, protocol = 'TCP') => {
    fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => {
      if (err) console.error(gradient.morning('Error logging blocked IP:'), err);
    });
  };

  const normalizeIp = (ip) => {
    if (ip.startsWith("::ffff:")) {
      return ip.substring(7);
    }
    if (ip === "::1") {
      return "127.0.0.1";
    }
    return ip ;
 };

  const isCloudOrServerIp = (ip) => {
    return cloudServerIpRanges.some((range) => ip.startsWith(range));
  };

  const isBlockedGeoIp = (ip) => {
    const geo = geoip.lookup(ip);
    if (geo && !config.allowedCountries.includes(geo.country)) {
      return true;
    }
    return false;
  };

  configApp.listen(CONFIG_PORT, () => {
    // console.log(gradient.cristal('ADMIN DASHBOARD IS ONLINE'));
  });

  function applyICMPSettings(isBlockEnabled) {
    try {
        if (isBlockEnabled) {
            blockICMP();
        } else {
            unblockICMP();
        }
    } catch (error) {
        console.error('Error applying ICMP settings:', error.message);
    }
  }

  function blockICMP() {
    console.log('⧪ Enabling ICMP blocking.');
    execSync('netsh advfirewall firewall add rule name="Block ICMP" protocol=icmpv4:8,any dir=in action=block', { shell: true });
  }

  function unblockICMP() {
    console.log('⧪ Disabling ICMP blocking.');
    execSync('netsh advfirewall firewall delete rule name="Block ICMP"', { shell: true });
  }

  const startServer = async () => {
    const proxy = httpProxy.createProxyServer({});
    const pk = fs.readFileSync(path.join(__dirname, 'server.key'));
    const pc = fs.readFileSync(path.join(__dirname, 'server.crt'));
    const optss = {
        key: pk,
        cert: pc,
        minVersion: 'TLSv1.3', 
        ciphers: [
            'TLS_AES_256_GCM_SHA384', 
            'TLS_CHACHA20_POLY1305_SHA256', 
            'TLS_AES_128_GCM_SHA256' 
        ].join(':'), 
        honorCipherOrder: true,
        enableTrace: false, 
        requestCert: false, 
        rejectUnauthorized: true, 
        enableOCSPStapling: true,
        //sessionTimeout: 300, 
    
        };
    const trustedIPs = ['127.0.0.1'];

    EventEmitter.defaultMaxListeners = 100;

    const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`;

    const server = https.createServer(optss, function (req, res) {
      let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
      const normalizedIp = normalizeIp(ip);
      const hostHeader = req.headers.host;

      server.keepAliveTimeout = 30 * 1000;
      server.headersTimeout = 30 * 1000;

      console.log(gradient.passion(`➥ [REQUEST] IP: ${normalizedIp}`));
      
      if (isBanned(normalizedIp)) {
        console.log(gradient.summer(`IP temporarily banned: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'Ban');
        res.statusCode = 403;
        res.end('Your IP is temporarily banned due to excessive requests.');
        return;
      }

      if (trackConnection(normalizedIp)) {
        res.statusCode = 429;
        res.end('Too many connections, please try again later.');
        return;
      }

      if (isSynFlood(ip)) {
        console.log(gradient.fruit(`SYN flood detected from IP: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'SYN Flood');
        req.socket.end();
        req.socket.destroy();
        return;
      }
      
      const parsedUrl = url.parse(req.url);
      const pathname = `.${parsedUrl.pathname}`;
      const ext = path.parse(pathname).ext;

      console.log(gradient.atlas(`➥ Connection Request from: ${normalizedIp} URL: ${req.url} Method: ${req.method}`));

      const map = {
        '.ico': 'image/x-icon',
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.json': 'application/json',
        '.css': 'text/css',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.wav': 'audio/wav',
        '.mp3': 'audio/mpeg',
        '.svg': 'image/svg+xml',
        '.pdf': 'application/pdf',
        '.doc': 'application/msword'
      };

      const IdentitasHost = [
        'www.growtopia1.com',
        'www.growtopia2.com'
      ];

      if (req.url === "/growtopia/server_data.php" && req.method === 'POST') {
        if (!IdentitasHost.includes(hostHeader)) {
            const clientPort = req.connection.remotePort;
            const userAgent = req.headers['user-agent'] || 'Unknown';
            const clientInfo = parseUserAgent(userAgent);
            const geoInfo = geoip.lookup(req.connection.remoteAddress) || {};
            console.log(gradient.summer(`Anomaly :  ${req.url}`));
          res.statusCode = 200;
          res.end(`
server|${normalizedIp}
port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
 
loginurl|https://t.me/GrowToolServer
beta_server|${normalizedIp}
beta_port|${Math.floor(Date.now() / 69)}
beta_type|1
beta2_server|${normalizedIp}
beta2_port|${Math.floor(Date.now() / 69)}
beta2_type|1
meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'}
RTENDMARKERBS1001
          `);
          return;
        }

    let body = '';
    req.on('data', chunk => {
      body += chunk.toString(); 
    });

    req.on('end', () => {
      const params = new URLSearchParams(body);

      const version = params.get('version');
      const platform = params.get('platform');
      const protocol = params.get('protocol');

      if (version !== `${config.version}` || platform !== '0' || protocol !== '210') {
        const clientPort = req.connection.remotePort;
        const userAgent = req.headers['user-agent'] || 'Unknown';
        const clientInfo = parseUserAgent(userAgent);
        const geoInfo = geoip.lookup(req.connection.remoteAddress) || {};
        console.log(gradient.summer('➥ Anomaly [⨻]'));
        res.statusCode = 200;
        res.end(`
server|${normalizedIp}
port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
 
loginurl|https://t.me/GrowToolServer
beta_server|${normalizedIp}
beta_port|${Math.floor(Date.now() / 69)}
beta_type|1
beta2_server|${normalizedIp}
beta2_port|${Math.floor(Date.now() / 69)}
beta2_type|1
meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'}
RTENDMARKERBS1001
          `);
        return;
      }

      console.log(gradient.atlas(`➥ Secure request from IP: ${normalizedIp} with valid [PARAM]`));

      res.write(packet, function (err) {
        if (err) console.log(gradient.summer(err));
      });
      res.end();
    });
    return; 
  }

      if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) {
        if (req.method !== 'GET') {
          console.log(gradient.summer(`➥ Blocked: Invalid method for ${req.url}`));
          req.socket.end();
          req.socket.destroy();
          return;
        }

        console.log(gradient.atlas(`➥ [CACHE-SPEED] Connection from: ${normalizedIp}\nDownloading assets: ${req.url}`));

        
        const filePath = path.join(__dirname, req.url);
        
        fs.stat(filePath, (err, stats) => {
          if (err || !stats.isFile()) {
            res.statusCode = 404;
            res.end('Not found');
            return;
          }

          const ext = path.extname(filePath);
          const map = {
            '.ico': 'image/x-icon',
            '.html': 'text/html',
            '.js': 'text/javascript',
            '.json': 'application/json',
            '.css': 'text/css',
            '.png': 'image/png',
            '.jpg': 'image/jpeg',
            '.wav': 'audio/wav',
            '.mp3': 'audio/mpeg',
            '.svg': 'image/svg+xml',
            '.pdf': 'application/pdf',
            '.doc': 'application/msword'
          };
          
          const contentType = map[ext] || 'application/octet-stream';
          res.setHeader('Content-Type', contentType);
          res.setHeader('Cache-Control', 'public, max-age=86400');

          const raw = fs.createReadStream(filePath);
          
          if (req.headers['accept-encoding'] && req.headers['accept-encoding'].includes('gzip')) {
            res.setHeader('Content-Encoding', 'gzip');
            raw.pipe(zlib.createGzip()).pipe(res);
          } else {
            raw.pipe(res);
          }
        });
        return;
      }

      console.log(gradient.summer(`➥ [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'TCP-Other');
      req.socket.destroy();
    });

    server.listen(port, () => {
      //console.log(gradient.cristal(`Server is running on port ${port}`));
    });

    const udpServer = dgram.createSocket('udp4');
    const UDP_PORT = 53;

    udpServer.on('error', (err) => {
      console.error(`UDP server error:\n${err.stack}`);
      udpServer.close();
    });

    udpServer.on('message', (msg, rinfo) => {
      const ip = rinfo.address;
      const normalizedIp = normalizeIp(ip);
      console.log(gradient.fruit(`➥ UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`));

      const isUdpRateLimited = (ip) => {
        const now = Date.now();
        if (!udpRateLimitConfigurations[ip]) {
          udpRateLimitConfigurations[ip] = { count: 1, timestamp: now };
          return false;
        } else {
          const timePassed = now - udpRateLimitConfigurations[ip].timestamp;
          if (timePassed > UDP_BLOCK_TIME_MS) {
            udpRateLimitConfigurations[ip] = { count: 1, timestamp: now };
            return false;
          } else {
            udpRateLimitConfigurations[ip].count++;
            if (udpRateLimitConfigurations[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) {
              return true;
            }
          }
        }
        return false;
      };

      if (isUdpRateLimited(normalizedIp)) {
        console.log(gradient.summer(`➥ UDP Rate limit exceeded for IP: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'UDP');
        return;
      }

      if (isBlockedGeoIp(normalizedIp)) {
        console.log(gradient.summer(`➥ Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`));
        logBlockedIP(normalizedIp, 'UDP-GeoIP');
        return;
      }

      const messageBytes = msg.length;
      if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
        console.log(gradient.summer(`➥ Network usage limit exceeded for IP: ${normalizedIp} (UDP)`));
        logBlockedIP(normalizedIp, 'UDP-NETWORK');
        return;
      }

      const externalDns = '8.8.8.8';
      const externalDnsPort = 53;
      const externalClient = dgram.createSocket('udp4');

      externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => {
        if (error) {
          console.error(`Error forwarding UDP request: ${error}`);
          externalClient.close();
        }
      });

      externalClient.on('message', (response) => {
        udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => {
          if (err) {
            console.error(`Error sending UDP response: ${err}`);
          }
          externalClient.close();
        });
      });

      externalClient.on('error', (err) => {
        console.error(`External DNS client error: ${err}`);
        externalClient.close();
      });

      externalClient.setTimeout(5000, () => {
        console.error(`External DNS request timed out for IP: ${normalizedIp}`);
        externalClient.close();
      });
    });

    udpServer.on('listening', () => {
      const address = udpServer.address();
      console.log(gradient.morning(`⧪ UDP Server listening on ${address.address}:${address.port}`));
    });

    udpServer.bind(UDP_PORT);
  };

  applyICMPSettings(config.icmpBlock);
  startServer();

  configApp.post('/shutdown', (req, res) => {
    res.send('Server is shutting down...');
    shutdown();
  });

  function parseUserAgent(userAgent) {
    let os = 'Unknown';
    let software = 'Unknown';
  
    if (userAgent.includes('Windows')) os = 'Windows';
    else if (userAgent.includes('Linux')) os = 'Linux';
    else if (userAgent.includes('Mac OS')) os = 'Mac OS';
    else if (userAgent.includes('Android')) os = 'Android';
    else if (userAgent.includes('iOS')) os = 'iOS';
  
    if (userAgent.includes('Firefox')) software = 'Firefox';
    else if (userAgent.includes('Chrome')) software = 'Chrome';
    else if (userAgent.includes('Safari')) software = 'Safari';
    else if (userAgent.includes('Edge')) software = 'Edge';
    else if (userAgent.includes('curl')) software = 'curl'; 
    return { os, software };
  }

  const shutdown = () => {
    console.log('⧪ Shutting down the server...');

    server.close(() => {
      console.log('⧪ HTTP server closed.');

      udpServer.close(() => {
        console.log('⧪ UDP server closed.');

        process.exit(0);
      });
    });

    setTimeout(() => {
      console.error('Forced shutdown due to open connections.');
      process.exit(1);
    }, 5000).unref();
  };

  process.on('SIGINT', shutdown);
  process.on('SIGTERM', shutdown);

 console.log('');
 console.log(`
${gradient.teen(`  ┌────────────────────────────────────────────────────┐`)}
${gradient.atlas(`  │`)} ${gradient.fruit(`✧ HTTP(s) Port    : ${port}`)}                          ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.fruit(`✧ ANTI-SCAN       : 5 Layer Protection`)}           ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.fruit(`✧ App Version     : HTTP KING v4.0.3`)}             ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.summer(`✧ Subscription   : AVIATUM PREMIUM`)}               ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.summer(`✧ Last Update    : 30/10/2024`)}                    ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.instagram(`✧ Admin Panel : http://localhost:${CONFIG_PORT}/config`)}     ${gradient.atlas(`  │`)}
${gradient.teen(`  └────────────────────────────────────────────────────┘`)}
  `);
  
console.log('');

})();
```

Can you check what's missing, make sure there is no absolutely error! do a deep checking and fix it asap!