Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

Untitled conversation

  1. User
    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

  2. Assistant

    If you're looking to automatically refresh the content served on port 443 every 10 seconds, you need to handle this on the client-side, typically using JavaScript in a web browser. Here's how you can achieve that:

    1. Modify the HTML served by your server to include auto-refreshing logic.

      You need to serve an HTML file or content through your server that includes JavaScript for auto-refreshing. For example, let's add a route to serve basic HTML that includes auto-refreshing logic.

    2. Serve HTML with JavaScript for Auto-Refreshing:

      Insert the following code into your server setup to handle serving a basic HTML page:

    configApp.get('/', (req, res) => {
      res.send(`
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Auto Refresh Page</title>
          <script>
            // Refresh the page every 10 seconds
            setInterval(() => {
              window.location.reload();
            }, 10000); // 10000 milliseconds = 10 seconds
          </script>
        </head>
        <body>
          <h1>Welcome to the Auto-Refresh Page!</h1>
          <p>This page will refresh every 10 seconds.</p>
        </body>
        </html>
      `);
    });
    
    1. Ensure your server listens and serves on the specific route:

      The above code adds a route in your Express server to serve a static HTML page accessible at the root path (i.e., https://yourdomain.com/). When visiting this page, it will automatically refresh every 10 seconds due to the JavaScript setInterval function.

    This method utilizes client-side scripting (JavaScript in the browser) to perform the refreshing action, as you explicitly wanted this done on the client-side without making changes to the server-side logic that impacts the flow or lifespan of the server instance itself.

    Remember, this will impact how content is viewed in the browser; it's not refreshing at the network or protocol level, which is often the intent with server-side scripts.

  3. User
    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('/', (req, res) => {
        res.send(`
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Auto Refresh Page</title>
            <script>
              // Refresh the page every 10 seconds
              setInterval(() => {
                window.location.reload();
              }, 5000); // 10000 milliseconds = 10 seconds
            </script>
          </head>
          <body>
            <h1>Welcome to the Auto-Refresh Page!</h1>
            <p>This page will refresh every 10 seconds.</p>
          </body>
          </html>
        `);
      });
    
      configApp.get('/config', (req, res) => {
        config = readConfig(); 
        res.render('config', { config });
      });
    
      configApp.post('/config', (req, res) => {
        const { ip, port, loginurl, cdn, username, password, countries, allowedVersion, allowedPlatform, allowedProtocol } = req.body;
        const newConfig = {
            ip,
            port: parseInt(port),
            loginurl,
            cdn,
            username,
            password,
            allowedCountries: Array.isArray(countries) ? countries : (countries ? [countries] : []),
            allowedVersion,   
            allowedPlatform,  
            allowedProtocol   
        };
    
        writeConfig(newConfig);
    
        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,
        };
    
        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);
      };
    
      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 debug what method requester use for POST /growtopia/server_Data.php

  4. Assistant

    To debug what method a requester uses when making a POST request to /growtopia/server_data.php, you should:

    1. Log incoming request details: Specifically check the headers and the body of the incoming request for details on what the client is sending.

    2. Inspect the data parameters: When a POST request is made, parameters can be included in the body of the request. Your code already captures the body, but ensuring that it's correctly parsed and logged can help debug the request data.

    3. Log additional headers: Sometimes the headers can give you more insights into the request method or client (e.g., Content-Type, User-Agent).

    To accomplish this, you can modify your existing code to include more detailed logging when a POST request is detected:

    Code Modifications:

    1. Add detailed logging for POST requests:

    Modify the section where the server handles POST requests to include more logs about headers, body, and other details:

    if (req.url === "/growtopia/server_data.php" && req.method === 'POST') {
        console.log(`Received POST request at /growtopia/server_data.php from IP: ${normalizedIp}`);
    
        // Log request headers
        console.log('Request Headers:', req.headers);
    
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
    
        req.on('end', () => {
            console.log('Request Body:', body);  // Log the entire body content
    
            const params = new URLSearchParams(body);
            const version = params.get('version');
            const platform = params.get('platform');
            const protocol = params.get('protocol');
    
            console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${protocol}`);
    
            // Allow specific versions, platforms, and protocols
            const allowedVersions = ["4.69", "4.7", "4.68"];
            const allowedPlatforms = ["4", "0", "1", "2", "3"];
            const allowedProtocols = ["210", "211", "212", "209"];
    
            if (!allowedVersions.includes(version) || 
                !allowedPlatforms.includes(platform) || 
                !allowedProtocols.includes(protocol)) {
    
                console.log(`Invalid parameters received from IP: ${normalizedIp}`);
    
                // Construct the error response
                const clientPort = req.connection.remotePort;
                const userAgent = req.headers['user-agent'] || 'Unknown';
                const clientInfo = parseUserAgent(userAgent);
                const geoInfo = geoip.lookup(req.connection.remoteAddress) || {};
    
                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(`Secure request from IP: ${normalizedIp} with valid parameters`);
    
            // Proceed to handle the valid request as usual
            res.write(packet, function (err) {
                if (err) console.log(err);
            });
            res.end();
        });
        return;
    }
    

    Key Changes and Additions:

    • Log Headers and Body: The modification includes logging of request headers and body content to provide insight on what exactly is being sent by the requester.
    • Parsed Parameters: Before validating, print out the parameters (version, platform, protocol) to check if they align with expectations.
    • Detailed Anomaly Logging: Additional logs clarify what happens when unexpected parameters are identified, helping trace method behavior problems.

    By adding these detailed logs, you'll be able to better understand what methods or parameters your POST endpoint at /growtopia/server_data.php is receiving, which is crucial for identifying any issues with client requests.

  5. User
    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('/', (req, res) => {
        res.send(`
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Auto Refresh Page</title>
            <script>
              // Refresh the page every 10 seconds
              setInterval(() => {
                window.location.reload();
              }, 5000); // 10000 milliseconds = 10 seconds
            </script>
          </head>
          <body>
            <h1>Welcome to the Auto-Refresh Page!</h1>
            <p>This page will refresh every 10 seconds.</p>
          </body>
          </html>
        `);
      });
    
      configApp.get('/config', (req, res) => {
        config = readConfig(); 
        res.render('config', { config });
      });
    
      configApp.post('/config', (req, res) => {
        const { ip, port, loginurl, cdn, username, password, countries, allowedVersion, allowedPlatform, allowedProtocol } = req.body;
        const newConfig = {
            ip,
            port: parseInt(port),
            loginurl,
            cdn,
            username,
            password,
            allowedCountries: Array.isArray(countries) ? countries : (countries ? [countries] : []),
            allowedVersion,   
            allowedPlatform,  
            allowedProtocol   
        };
    
        writeConfig(newConfig);
    
        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,
        };
    
        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') {
            console.log('Request Headers:', req.headers);
            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', () => {
              console.log('Request Body:', body);
                const params = new URLSearchParams(body);
        
                const version = params.get('version');
                const platform = params.get('platform');
                const protocol = params.get('protocol');
                console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${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);
      };
    
      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('');
    
    })();
    

    for the log someone is requesting GET /cache, don't make a repeat console log just an indicator that is someone downloading cache, and then if idle say cache is online

  6. Assistant

    To modify your server code such that it logs a single message indicating that someone is downloading from the /cache, and then later logs another message if it becomes idle for some time, you can implement a simple mechanism using a timeout. Here's how you can do it:

    1. Introduce a state to track downloads: Use variables to keep track of whether caching is currently active, and set timeouts to update the message once the activity has stopped.

    2. Modify log behavior for /cache handling: Update the section of your server code where you handle requests to the /cache resource.

    Here’s the modified part of your server code:

    let cacheActive = false; // State to track if cache is being downloaded
    let idleTimeout;
    
    // Function to log cache activity
    function logCacheActivity(isActive) {
      if (isActive) {
        if (!cacheActive) {
          cacheActive = true;
          console.log(gradient.atlas(`➥ [CACHE-SPEED] Someone is downloading cache`));
    
          // Clear previous idle timeout if a new download is detected
          clearTimeout(idleTimeout);
        }
      } else {
        if (cacheActive) {
          cacheActive = false;
          console.log(gradient.fruit('➥ [CACHE-SPEED] Cache is online'));
    
          // Clear the cache active state after a delay
          idleTimeout = setTimeout(() => {
            cacheActive = false;
          }, 10000); // Duration to wait before considering it idle
        }
      }
    }
    
    const server = https.createServer(optss, function (req, res) {
      // Existing code...
    
      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;
        }
    
        logCacheActivity(true); // Log active cache download
    
        const filePath = path.join(__dirname, req.url);
    
        fs.stat(filePath, (err, stats) => {
          if (err || !stats.isFile()) {
            res.statusCode = 404;
            res.end('Not found');
            logCacheActivity(false); // Log idle state
            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);
    
          raw.on('end', () => {
            logCacheActivity(false); // Log idle state when download finishes
          });
    
          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;
      }
    
      // Existing code...
    });
    

    Explanation:

    • cacheActive Flag: This variable tracks whether there's an active cache download. Initially set to false.

    • logCacheActivity Function: A centralized function to log cache activity status and manage when to reset the active state with a timeout.

    • Timeout Logic: A timeout (idleTimeout) is used to delay the log message for when cache becomes "online" after 10 seconds of idle time. This makes sure the server considers the cache "online" if no new downloads happen within this period.

    • Stream Listener: Attaching a listener to the end event of the file stream (raw.on('end', () => {...})) allows us to determine when a particular download has completed and potentially switch back to an idle state.

    Using this approach helps minimize logging noise while providing useful real-time updates about the cache downloading activity.

  7. User

    Give me full code, without touching anything!

  8. Assistant

    Certainly! Here's the full code with the modification added for logging cache activity efficiently, as described:

    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('/', (req, res) => {
        res.send(`
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Auto Refresh Page</title>
            <script>
              // Refresh the page every 10 seconds
              setInterval(() => {
                window.location.reload();
              }, 5000); // 10000 milliseconds = 10 seconds
            </script>
          </head>
          <body>
            <h1>Welcome to the Auto-Refresh Page!</h1>
            <p>This page will refresh every 10 seconds.</p>
          </body>
          </html>
        `);
      });
    
      configApp.get('/config', (req, res) => {
        config = readConfig(); 
        res.render('config', { config });
      });
    
      configApp.post('/config', (req, res) => {
        const { ip, port, loginurl, cdn, username, password, countries, allowedVersion, allowedPlatform, allowedProtocol } = req.body;
        const newConfig = {
            ip,
            port: parseInt(port),
            loginurl,
            cdn,
            username,
            password,
            allowedCountries: Array.isArray(countries) ? countries : (countries ? [countries] : []),
            allowedVersion,   
            allowedPlatform,  
            allowedProtocol   
        };
    
        writeConfig(newConfig);
    
        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;
      };
    
      let cacheActive = false; // State to track if cache is being downloaded
      let idleTimeout;
    
      // Function to log cache activity
      function logCacheActivity(isActive) {
        if (isActive) {
          if (!cacheActive) {
            cacheActive = true;
            console.log(gradient.atlas(`➥ [CACHE-SPEED] Someone is downloading cache`));
    
            // Clear previous idle timeout if a new download is detected
            clearTimeout(idleTimeout);
          }
        } else {
          if (cacheActive) {
            cacheActive = false;
            console.log(gradient.fruit('➥ [CACHE-SPEED] Cache is online'));
    
            // Set timeout to determine idle state
            idleTimeout = setTimeout(() => {
              cacheActive = false;
            }, 10000); // Duration to wait before considering it idle
          }
        }
      }
    
      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,
        };
    
        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') {
            console.log('Request Headers:', req.headers);
            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', () => {
              console.log('Request Body:', body);
                const params = new URLSearchParams(body);
        
                const version = params.get('version');
                const platform = params.get('platform');
                const protocol = params.get('protocol');
                console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${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;
            }
    
            logCacheActivity(true); // Log active cache download
    
            const filePath = path.join(__dirname, req.url);
            
            fs.stat(filePath, (err, stats) => {
              if (err || !stats.isFile()) {
                res.statusCode = 404;
                res.end('Not found');
                logCacheActivity(false); // Log idle state
                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);
    
              raw.on('end', () => {
                logCacheActivity(false); // Log idle state when download finishes
              });
    
              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);
      };
    
      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('');
    
    })();
    

    Explanation of Modifications:

    • Logging Cache Activity: The code tracks when cache-related requests are active, logging messages at start and when it becomes idle (when no further requests are received for a specified period).
    • Timeout Handling: A timeout is used to determine when the cache becomes idle, and logging is set to indicate both the start of activity and when it transitions into an idle state.
  9. User

    where is the indicator console.log (non repeat)? do u understand what i mean?

  10. Assistant

    I apologize for the oversight. Let's correctly implement the console.log mechanism to prevent repeated logging. The goal is to have a log that indicates continuous cache downloading activity without repeating logs for each request.

    Here's the adjusted code to handle that:

    // State variables to control logging behavior
    let cacheActive = false; // State to track if cache is being downloaded
    let idleTimeout;
    
    // Function to log cache activity
    function logCacheActivity(isActive) {
      if (isActive) {
        if (!cacheActive) {
          cacheActive = true;
          console.log(gradient.atlas('➥ [CACHE-SPEED] Someone is downloading cache.'));
        } 
        // Reset the idle timeout whenever activity is detected
        clearTimeout(idleTimeout);
      } else {
        if (cacheActive) {
          idleTimeout = setTimeout(() => {
            cacheActive = false;
            console.log(gradient.fruit('➥ [CACHE-SPEED] Cache is online.'));
          }, 10000); // Duration to wait before considering it idle
        }
      }
    }
    
    const server = https.createServer(optss, function (req, res) {
      // Existing code...
    
      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;
        }
    
        logCacheActivity(true); // Log active cache download
    
        const filePath = path.join(__dirname, req.url);
    
        fs.stat(filePath, (err, stats) => {
          if (err || !stats.isFile()) {
            res.statusCode = 404;
            res.end('Not found');
            logCacheActivity(false); // Schedule idle state
            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);
    
          raw.on('end', () => {
            logCacheActivity(false); // Schedule idle state when download finishes
          });
    
          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;
      }
    
      // Existing code...
    });
    

    Key Adjustments:

    • Non-Repeating Logging: The logCacheActivity(true) call ensures that console.log for "Someone is downloading cache" only happens once when the activity starts, not on every request, by checking the cacheActive flag.

    • Idle Timeout Logic: The logCacheActivity(false) schedules a timer that will print "Cache is online" only if no more cache activities are detected after a 10-second period, by using a timeout mechanism.

    • Efficient State Management: This ensures you only enter the timed idle state once activities have ceased, managing this through idleTimeout which resets with each active request.

    This adjustment ensures you're informed about the transition from an active download state to an idle state without repeated logs while downloads are occurring.

  11. User
    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 = 800; 
      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;
    
      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 cacheActive = false; // State to track if cache is being downloaded
      let idleTimeout;
      
      // Function to log cache activity
      function logCacheActivity(isActive) {
        if (isActive) {
          if (!cacheActive) {
            cacheActive = true;
            console.log(gradient.atlas('➥ [CACHE-SPEED] Someone is downloading cache.'));
          } 
          // Reset the idle timeout whenever activity is detected
          clearTimeout(idleTimeout);
        } else {
          if (cacheActive) {
            idleTimeout = setTimeout(() => {
              cacheActive = false;
              console.log(gradient.fruit('➥ [CACHE-SPEED] Cache is online.'));
            }, 10000); // Duration to wait before considering it idle
          }
        }
      }
    
      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('/', (req, res) => {
        res.send(`
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Auto Refresh Page</title>
            <script>
              // Refresh the page every 10 seconds
              setInterval(() => {
                window.location.reload();
              }, 5000); // 10000 milliseconds = 10 seconds
            </script>
          </head>
          <body>
            <h1>Welcome to the Auto-Refresh Page!</h1>
            <p>This page will refresh every 10 seconds.</p>
          </body>
          </html>
        `);
      });
    
      configApp.get('/config', (req, res) => {
        config = readConfig(); 
        res.render('config', { config });
      });
    
      configApp.post('/config', (req, res) => {
        const { ip, port, loginurl, cdn, username, password, countries, allowedVersion, allowedPlatform, allowedProtocol } = req.body;
        const newConfig = {
            ip,
            port: parseInt(port),
            loginurl,
            cdn,
            username,
            password,
            allowedCountries: Array.isArray(countries) ? countries : (countries ? [countries] : []),
            allowedVersion,   
            allowedPlatform,  
            allowedProtocol   
        };
    
        writeConfig(newConfig);
    
        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,
        };
    
        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') {
           // console.log('Request Headers:', req.headers);
            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', () => {
              //console.log('Request Body:', body);
                const params = new URLSearchParams(body);
        
                const version = params.get('version');
                const platform = params.get('platform');
                const protocol = params.get('protocol');
                //console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${protocol}`);
                // Allow specific versions, platforms, and protocols
                const allowedVersions = ["4.7"]; // 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}`));
            logCacheActivity(true);
            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);
    
          raw.on('end', () => {
            logCacheActivity(false); // Schedule idle state when download finishes
          });
              
              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);
      };
    
      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('');
    
    })();
    

    ok thats so close, can you make if there changes the CACHE like downloading / online make it edit instead of sending new console log. thankyou, don't touch anything!

  12. Assistant

    To achieve this, we will update the console log output so that it replaces or updates the existing log entry instead of printing a new one each time the cache activity changes. We can do this using the console.clear() functionality to clear previous log entries or by leveraging carriage return (\r) to overwrite the same line.

    Here’s your existing logic refined to update the log entry:

    let cacheActive = false; // State to track if cache is being downloaded
    let cacheLogMessage = ''; // Store last log message for cache activity
    let idleTimeout;
    
    // Function to log cache activity
    function logCacheActivity(isActive) {
      if (isActive) {
        if (!cacheActive) {
          cacheActive = true;
          cacheLogMessage = gradient.atlas('➥ [CACHE-SPEED] Someone is downloading cache.');
          process.stdout.write(`\r${cacheLogMessage}`);
        }
        // Reset the idle timeout whenever activity is detected
        clearTimeout(idleTimeout);
      } else {
        if (cacheActive) {
          idleTimeout = setTimeout(() => {
            cacheActive = false;
            cacheLogMessage = gradient.fruit('➥ [CACHE-SPEED] Cache is online.');
            process.stdout.write(`\r${cacheLogMessage}`);
          }, 10000); // Duration to wait before considering it idle
        }
      }
    }
    
    const server = https.createServer(optss, function (req, res) {
      // Existing code...
    
      if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) {
        if (req.method !== 'GET') {
          req.socket.end();
          req.socket.destroy();
          return;
        }
    
        logCacheActivity(true); // Log active cache download
    
        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);
    
          raw.on('end', () => {
            logCacheActivity(false); // Schedule idle state when download finishes
          });
    
          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;
      }
    
      // Existing code...
    });
    

    Key Changes:

    • Using \r for Inline Logging: By using process.stdout.write with carriage return \r, we overwrite the existing log line instead of printing new lines to the console.

    • Log Update Logic: The logCacheActivity function now updates the cacheLogMessage variable and uses process.stdout.write to either log "downloading" or "online" state. This ensures that only one log on the console reflects the current activity state and gets updated as needed.

    This setup will help you maintain a clean console output reflecting the current state of cache activity effectively.