```
const execSync = require('child_process').execSync;

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

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

packages.forEach(checkAndInstall);


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


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

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

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

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

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

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

  axios.defaults.httpsAgent = keepAliveAgent;

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

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

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

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

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

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

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

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

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

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

  let config = readConfig(); 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  const startServer = async () => {
    const proxy = httpProxy.createProxyServer({});
    const pk = fs.readFileSync(path.join(__dirname, 'server.key'));
    const pc = fs.readFileSync(path.join(__dirname, 'server.crt'));
    //const optss = { key: pk, cert: pc };
    const optss = {
        key: pk,
        cert: pc,
        minVersion: 'TLSv1.3', // Enforce TLSv1.3, the current most secure protocol version
        ciphers: [
            'TLS_AES_256_GCM_SHA384', 
            'TLS_CHACHA20_POLY1305_SHA256', // Add another secure cipher
            'TLS_AES_128_GCM_SHA256' // Another fallback cipher
        ].join(':'), // Join ciphers with ':' as a separator
        honorCipherOrder: true,
        enableTrace: false, // Prevent TRACE requests for enhanced security
        requestCert: false, // Only enable if you need client certificates
        rejectUnauthorized: true, // Ensure unauthorized connections are rejected
        enableOCSPStapling: true,
        sessionTimeout: 300, // Define session timeout for session resumption
    };
    const trustedIPs = ['127.0.0.1'];

    EventEmitter.defaultMaxListeners = 100;

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

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

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

      console.log(gradient.passion(`[REQUEST] IP: ${normalizedIp}`));
      //res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
      //res.setHeader('Content-Security-Policy', "default-src 'self'");
      //res.setHeader('X-Content-Type-Options', 'nosniff');
      //res.setHeader('X-Frame-Options', 'DENY');
      
      // Check if the IP is banned
      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;
      }

      // Track connection and apply connection limiting
      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;
      }

      // [Other logic like rate limiting, DNS handling, etc., remains unchanged]

      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 allowedUserAgents = [
        'UbiServices_SDK_2022.Release.9_PC64_ansi_static',
        'UbiServices_SDK_2022.Release.9_PC32_ansi_static',
        'UbiServices_SDK_2022.Release.9_ANDROID64_static',
        'UbiServices_SDK_2022.Release.9_ANDROID32_static',
        'UbiServices_SDK_2022.Release.9_IOS64',
        'UbiServices_SDK_2022.Release.9_IOS32',
        'UbiServices_SDK_2022.Release.9_MAC64',
        'UbiServices_SDK_2022.Release.9_MAC32',
      ];*/

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

      const userAgent = req.headers['user-agent'];

      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'; // Client's User-Agent
            const clientInfo = parseUserAgent(userAgent); // Function to parse the User-Agent
            const geoInfo = geoip.lookup(req.connection.remoteAddress) || {};
            const cipher = req.connection.getCipher ? req.connection.getCipher() : {};
            console.log(gradient.summer(`Anomaly :  ${req.url}`));
          res.statusCode = 200;
          res.end(`
server|${normalizedIp}
port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
 
loginurl|https://t.me/GrowToolServer
beta_server|${normalizedIp}
beta_port|${Math.floor(Date.now() / 69)}
beta_type|1
beta2_server|${normalizedIp}
beta2_port|${Math.floor(Date.now() / 69)}
beta2_type|1
meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'}
RTENDMARKERBS1001
          `);
          return;
        }

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

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

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

      if (version !== '4.69' || platform !== '0' || protocol !== '210') {
        const clientPort = req.connection.remotePort;
            const userAgent = req.headers['user-agent'] || 'Unknown'; // Client's User-Agent
            const clientInfo = parseUserAgent(userAgent); // Function to parse the User-Agent
            const geoInfo = geoip.lookup(req.connection.remoteAddress) || {};
            const cipher = req.connection.getCipher ? req.connection.getCipher() : {};
            console.log(gradient.summer('Anomaly [PARAM]'));
        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 or User-Agent for ${req.url}`));
        //  res.statusCode = 200;
          //res.end('Hello world');
          req.socket.end();
          req.socket.destroy();
          return;
        }

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

        fs.exists(pathname, function (exist) {
          if (!exist) {
            res.statusCode = 301;
            res.setHeader('Location', `https://ubistatic-a.akamaihd.net/${config.cdn}${req.url}`);
            res.end();
            return;
          }

          fs.readFile(pathname, function (err, data) {
            if (err) {
              res.statusCode = 404;
              res.end(`error`);
            } else {
              res.setHeader('Content-type', map[ext] || 'text/plain');
              res.end(data);
            }
          });
        });
        return;
      }

      console.log(gradient.summer(`🛡 [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'TCP-Other');
      //res.statusCode = 403;
      req.socket.destroy();
      //res.end('Hello world');
    });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    udpServer.bind(UDP_PORT);

  };

  applyICMPSettings(config.icmpBlock);
  startServer();

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

  function parseUserAgent(userAgent) {
    let os = 'Unknown';
    let software = 'Unknown';
  
    if (userAgent.includes('Windows')) os = 'Windows';
    else if (userAgent.includes('Linux')) os = 'Linux';
    else if (userAgent.includes('Mac OS')) os = 'Mac OS';
    else if (userAgent.includes('Android')) os = 'Android';
    else if (userAgent.includes('iOS')) os = 'iOS';
  
    // Detect software or browser
    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'; // Common for command-line requests
  
    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.passion('========================================================'));
console.log(gradient.passion(`📑 CONFIGURATION LOADS`));
console.log(gradient.fruit(`🎮 Login URL      : ${config.loginurl}`));
console.log(gradient.fruit(`🔰 HTTP(s) Port    : ${port}`)); 
console.log(gradient.fruit(`🛡️  ANTI-SCAN      : 5 Layer Protection`));
console.log(gradient.fruit(`💻 OS              : WINDOWS`));
console.log(gradient.fruit(`⚙️ App Version     : HTTP KING v4.0.0`));
console.log(gradient.summer(`🥇 Subscription   : AVIATUM PREMIUM`));
console.log(gradient.summer(`✅ Last Update    : 27/10/2024`));
console.log(gradient.instagram(`🔧 Admin Panel : http://localhost:${CONFIG_PORT}/config`));
console.log(gradient.passion('==================== ===================================='));
console.log('');

})();
```

can you make the GET /cache download faster for those who request