```
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 = [
  'express',
  'body-parser',
  'axios',
  'geoip-lite',
  'express-basic-auth',
  'gradient-string',
];

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);
  }
};


const shutdownAfterInterval = () => {
    console.log('Program akan berhenti setelah 10 detik...');
    
    // Menggunakan setTimeout untuk menunggu 10 detik
    setTimeout(() => {
      console.log('Menghentikan server sekarang.');
      process.exit(0); 
    }, 10000000); 
  };
(async () => {
  await checkHardwareId(); // Check the hardware ID before starting the server

  const execSync = require('child_process').execSync;
  const { machineIdSync } = require('node-machine-id');
  const axios = require('axios');
  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 express = require('express');
  const bodyParser = require('body-parser');
  const basicAuth = require('express-basic-auth');
  const geoip = require('geoip-lite');
  const dgram = require('dgram');
  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) {
      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 = 1000;
  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 = 3;
  const UDP_BLOCK_TIME_MS = 120000;

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

  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 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, allowedVersion, allowedPlatform, allowedProtocol } = req.body;
    const newConfig = {
        ip,
        port: parseInt(port),
        loginurl,
        cdn,
        username,
        password,
        allowedCountries: Array.isArray(countries) ? countries : (countries ? [countries] : []),
        icmpBlock: icmpBlock === 'on',
        allowedVersion,   
        allowedPlatform,  
        allowedProtocol   
    };

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

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

  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) {
       
        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 isBlockedGeoIp = (ip) => {
    const geo = geoip.lookup(ip);
    if (geo && !config.allowedCountries.includes(geo.country)) {
      return true;
    }
    return false;
  };

  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,
    };

    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 [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`));
            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');
    
            // Allow specific versions, platforms, and protocols
            const allowedVersions = ["4.69", "4.7", "4.68"]; // Add more allowed versions as needed
            const allowedPlatforms = ["4", "0", "1", "2", "3"]; // Add more allowed platforms as needed
            const allowedProtocols = ["210", "211", "212", "209"]; // Add more allowed protocols as needed
    
            // Check if the incoming parameters are acceptable
            if (!allowedVersions.includes(version) || 
                !allowedPlatforms.includes(platform) || 
                !allowedProtocols.includes(protocol)) {
                
                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 [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`));
                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++;
            // Implement stricter anti-DDoS checks
            if (udpRateLimitConfigurations[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) {
              console.log(`Blocked IP: ${normalizedIp} due to too many UDP requests.`);
              logBlockedIP(normalizedIp, 'UDP');
              return true; // Blocks this IP due to too many requests
            }
          }
        }
        return false;
      };

      if (isUdpRateLimited(normalizedIp)) {
        return; // If limited, exit the function
      }

      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');

      // Set up a timeout for the external DNS request
      const timeout = setTimeout(() => {
        c//onsole.error(`External DNS request timed out for IP: ${normalizedIp}`);
        externalClient.close();
      }, 5000); // 5 seconds

      externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => {
        if (error) {
        //  console.error(`Error forwarding UDP request: ${error}`);
          clearTimeout(timeout); // Clear the timeout if there's an error
          externalClient.close();
        }
      });

      externalClient.on('message', (response) => {
        clearTimeout(timeout); // Clear the timeout since we received a 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}`);
        clearTimeout(timeout); 
        externalClient.close();
      });
    });

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

    udpServer.bind(UDP_PORT);
  };

  applyICMPSettings(config.icmpBlock);
  startServer();
  shutdownAfterInterval();
  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    : Online`)}                          ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.fruit(`✧ App Version     : HTTP KING v4.0.3`)}             ${gradient.atlas(`  │`)}
${gradient.atlas(`  │`)} ${gradient.summer(`✧ Anti-DDoS   : UDP [ON] - TCP [ON] - DNS [ON] - PROXY [ON]`)}               ${gradient.atlas(`  │`)}
${gradient.teen(`  └────────────────────────────────────────────────────┘`)}
  `);
  
  console.log('');

})();
```

Can you make the 443 auto refresh (not script!) every 10 seconds