Respan Dataset Explorer

Select one behavior. Every returned turn has one binary label: Present or Absent. Source: final dense boolean release.

5,167,182physical rows
86shards
0.00%qualified row coverage
0.00%qualified cell coverage
Random row JSON API

turns-00033.parquet:24679

c3cdffa63e8f9b16068ee447
turn 3/20gpt-4o-2024-08-06EnglishIndonesia181 words
degenerate_repetitionAbsentFinal dense release
USER
yang lebih update
ASSISTANT
Berikut adalah beberapa lagu Indonesia yang lebih baru dan mungkin populer di kalangan pasangan pada tahun 2024:

1. **"Halu" - Feby Putri**
   - Lagu dengan lirik yang lembut dan melankolis, menggambarkan perasaan rindu dan cinta yang dalam.

2. **"Sampai Jumpa Kamu" - Mahalini**
   - Mengisahkan tentang janji untuk selalu bersama dan tidak sabar untuk bertemu lagi, sangat cocok untuk pasangan.

3. **"Bertaut" - Nadin Amizah**
   - Meskipun bukan secara eksklusif tentang hubungan romantis, lagu ini memaparkan keintiman dan hubungan yang dalam, cocok untuk pasangan yang menghargai kedekatan emosional.

4. **"Kusut" - Hindia**
   - Menggambarkan tentang hubungan yang kompleks namun indah, sesuai untuk pasangan yang melalui pasang surut bersama.

5. **"Serenata Jiwa Lara" - Diskoria, Dian Sastrowardoyo, dan Laleilmanino**
   - Sebuah lagu dengan sentuhan retro tetapi dengan lirik yang relevan bagi pasangan modern.

6. **"Memilih Dia" - BCL**
   - Liriknya menceritakan pilihan cinta yang penuh keyakinan, cocok untuk merayakan keputusan bersama dalam hubungan.

Lagu-lagu ini memiliki tema dan lirik yang relevan dengan dinamika hubungan pasangan saat ini, serta dapat dinikmati oleh banyak orang karena pesan dan melodi yang menyentuh.

turns-00033.parquet:24680

213b1ddec76ca2b87052a0f9
turn 4/20gpt-4o-2024-08-06EnglishIndonesia316 words
degenerate_repetitionAbsentFinal dense release
USER
I found a https://210.247.249.150 i can visit but when i check port 443 its closed how?!
ASSISTANT
Accessing a website typically involves connecting to a server using a specific protocol and port number. The URL you provided seems to be formatted as an IP address, suggesting a direct connection to a server rather than a domain name. Here’s a brief explanation of what might be happening regarding port 443:

1. **Port 443**: This is the standard port used for HTTPS, which is the secure version of HTTP. When this port is closed, it indicates that the server is not configured to accept secure HTTPS connections, or that the service handling HTTPS is not running.

2. **Possible Reasons for Closed Port 443**:
   - **Server Configuration**: The server might not be configured to use HTTPS, or it might be exclusively using another port for secure connections.
   - **Firewall Settings**: A firewall might be blocking access to port 443, preventing secure connections from being established.
   - **Service Not Running**: The service that handles HTTPS on the server, such as a web server software or a load balancer, might not be active or properly configured.

3. **Troubleshooting Steps**:
   - **Contact Support**: If you have administrative access or contact with the server owner, inquire whether HTTPS is supported and correctly configured.
   - **Check Other Ports**: Determine if there are alternative ports that might be used for secure connections by examining the server configuration or using network scanning tools responsibly.
   - **Use HTTP**: If secure access is not critical and the server allows it, try accessing the site via HTTP on port 80.

If you are attempting to test ports or access a system that you do not own or administrate, it's crucial to ensure that you have permission to avoid ethical or legal issues. If you own the server, consider reaching out to your hosting provider for further assistance in configuring HTTPS.

turns-00033.parquet:24681

847af620f9567de62122067f
turn 5/20gpt-4o-2024-08-06EnglishIndonesia262 words
degenerate_repetitionAbsentFinal dense release
USER
No i mean i've found a website with https but the 443 port status is closed when i check it how is that possible?
ASSISTANT
If you've been able to access a website over HTTPS, yet a port scan indicates that port 443 is closed, it may seem contradictory. Here are several potential explanations for this situation:

1. **Intermittent Access**: The server could be intermittently switching between open and closed status for port 443 due to service issues or maintenance.

2. **Firewall or Security Settings**: Some servers are configured to respond selectively to certain IP ranges or to specific types of network traffic. For instance:
   - A firewall or security appliance might block typical port scans but allow actual web traffic from clients like web browsers.
   - There might be rate limiting implemented, where scans that look like automated requests are blocked after a certain threshold.

3. **Proxy or Load Balancer**: The server might be behind a proxy or load balancer that responds to HTTPS requests but blocks other unsolicited requests, such as port scans.

4. **Scan Limitations or Errors**: The tool or method used to scan the port might themselves have limitations or errors. It could be misinterpreted results, especially if the scan was done quickly or under specific network conditions.

5. **Temporary Network Issues**: Network congestion or temporary routing issues could lead to inconsistent information about port availability.

Given these potential explanations, consider verifying your findings with different tools or from different network environments. Additionally, if you own or manage this server, reviewing server and firewall configurations could provide more insights.

turns-00033.parquet:24682

5d412f798d2250200e468e62
turn 6/20gpt-4o-2024-08-06EnglishIndonesia307 words
degenerate_repetitionAbsentFinal dense release
USER
but when i visit https://210.247.249.150 its up
ASSISTANT
If you can successfully access a website using HTTPS at `https://210.247.249.150`, but a port scan of port 443 indicates it is closed, there are several potential explanations:

1. **Selective Filtering:** The server or a network device (such as a firewall or intrusion prevention system) may be configured to allow access to port 443 only for specific types of requests, such as those originating from web browsers. It might block or ignore other types of traffic, such as that from port scans.

2. **Proxy or Load Balancer:** The server might be behind a proxy or load balancer which handles HTTPS traffic while controlling or blocking other traffic on port 443 from being directly scanned or detected. This setup can front various services and handle incoming connections appropriately.

3. **Security Tools:** Many modern security tools are capable of detecting port scans and responding by blocking attempts to scan the port, while still allowing legitimate traffic.

4. **False Negative with Scanning Tools:** Port scanning tools sometimes report false negatives due to transient network issues, misconfigurations, or specific behavior settings detecting automated scanning activities and shutting down responses temporarily.

5. **Rate Limiting or Permissible Connections:** Some servers will implement rate limiting or restrict responses after a certain number of requests, identifying scans and blocking them while keeping the website accessible to users.

6. **Incorrect Scan Source or Permissions:** If the scan originates from a different network location with different permissions or restrictions (e.g., behind a corporate firewall or VPN), it may be subject to different rules than regular traffic.

In any scenario where an anomaly like this arises, ensuring consistency with different tools or environments is beneficial to draw a more accurate assessment. If you are investigating a system you manage, checking firewall settings, load balancer configurations, and security policies will provide further insights.

turns-00033.parquet:24683

c55b376b8ffa1d066ca5d6f9
turn 7/20gpt-4o-2024-08-06EnglishIndonesia463 words
degenerate_repetitionAbsentFinal dense release
USER
Can you make when the user requesting on POST /growtopia/server_data.php and GET /cache then open and allow port 443 but for other just completely close them.
ASSISTANT
To achieve a setup where port 443 is only open for specific requests (such as POST requests to `/growtopia/server_data.php` and GET requests to `/cache`), you'll need to configure your server and possibly firewall or proxy to handle traffic in this selective manner. Here's a high-level overview of how you can approach this:

### Using a Web Server (e.g., Nginx or Apache)

1. **Nginx Configuration**:
   - Nginx can be configured to handle different locations with specific rules. You can set up location blocks that specify how requests to certain paths are handled.

   ```nginx
   server {
       listen 443 ssl;
       server_name your_server_ip_or_domain;

       ssl_certificate     /path/to/ssl_certificate.crt;
       ssl_certificate_key /path/to/private.key;

       # Default: Return 403 Forbidden for requests not matching below
       location / {
           return 403;
       }

       # Allow POST requests to /growtopia/server_data.php
       location = /growtopia/server_data.php {
           limit_except POST {
               deny all;
           }
           # Handle the request, e.g., via a proxy_pass or local script execution
       }

       # Allow GET requests to /cache
       location /cache {
           limit_except GET {
               deny all;
           }
           # Handle the request as needed
       }
   }
   ```

2. **Apache Configuration**:
   - Similar rules can be applied using the `Directory` and `Location` directives in your `httpd.conf` or a `.htaccess` file.

   ```apache
   <VirtualHost *:443>
       DocumentRoot "/var/www/html"
       ServerName your_server_ip_or_domain

       SSLEngine on
       SSLCertificateFile /path/to/ssl_certificate.crt
       SSLCertificateKeyFile /path/to/private.key

       # Default: Deny access
       <Location />
           Order deny,allow
           Deny from all
       </Location>

       # Allow POST requests to /growtopia/server_data.php
       <Location "/growtopia/server_data.php">
           <LimitExcept POST>
               Order deny,allow
               Deny from all
           </LimitExcept>
       </Location>

       # Allow GET requests to /cache
       <Location "/cache">
           <LimitExcept GET>
               Order deny,allow
               Deny from all
           </LimitExcept>
       </Location>

   </VirtualHost>
   ```

### Security Implementation

- **Firewall Rules**: Consider using firewall rules (e.g., iptables, firewalld) only to allow traffic originating from legitimate sources or known good IP ranges, while dropping unsolicited traffic.
  
- **Intrusion Detection Systems (IDS)/Intrusion Prevention Systems (IPS)**: If feasible, you can implement these to detect and block illegitimate attempts at port scanning or other malicious activity in real time.

### Proxy Server Configuration (if applicable)

- Implement rules on your reverse proxy (e.g., HAProxy) to switch backends or drop requests based on conditions such as HTTP method or URL path.

### General Recommendations

- **Testing**: Always test your configuration in a staging environment before deploying it to production to avoid unexpected downtime or access issues.
  
- **Monitoring & Logging**: Ensure that you have proper logging of both allowed and denied requests for accountability, audits, and real-time monitoring.

- **Security Hardening**: Regularly update your server software to patch any vulnerabilities and adhere to best security practices.

By selectively allowing traffic based on request type and URL path, you can achieve fine-grained control over your server's access policy while maintaining essential service availability.

turns-00033.parquet:24684

ca0ca34b68c2b8524d30be4e
turn 8/20gpt-4o-2024-08-06EnglishIndonesia2810 words
degenerate_repetitionAbsentFinal dense release
USER
Oh i forgot, anyway implement it on my nodejs code : 
```
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 chalk = require('chalk');
const { EventEmitter } = require('events');
const axios = require('axios');
const geoip = require('geoip-lite');  // Importing geoip-lite for GeoIP blocking
const exec = require('child_process').exec; // For executing shell commands
const dgram = require('dgram'); // Importing dgram for UDP handling
const basicAuth = require('express-basic-auth');
const helmet = require('helmet'); // For setting various HTTP headers for security

// Rate Limiting Configurations
const rateLimit = {};
const MAX_REQUESTS_PER_MINUTE = 100; // Set your limit here (100)
const BLOCK_TIME_MS = 60000; // Time to block the IP (1 minute) (60000)

// DNS attack prevention configurations
const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; // Trusted DNS resolvers (Google DNS and Cloudflare DNS)
const MAX_DNS_REQUESTS_PER_MINUTE = 50; // Limit DNS-related requests
const dnsRateLimit = {};

// UDP Rate Limiting Configurations
const udpRateLimit = {};
const MAX_UDP_REQUESTS_PER_MINUTE = 100; // Adjust as needed
const UDP_BLOCK_TIME_MS = 60000; // 1 minute

// Network Usage Limiting Configurations
const networkUsage = {};
const MAX_BYTES_PER_MINUTE = 1024 * 1024; // 1 MB per minute per IP (adjust as needed)
const NETWORK_BLOCK_TIME_MS = 60000; // 1 minute

// Cloud Server IP Ranges
const cloudServerIpRanges = ['35.', '52.', '169.', '198.', '199.', '200.', '216.', '47.'];

// Allowed Countries for GeoIP
const allowedCountries = ['ID', 'SG', 'PH']; // Add allowed countries by their ISO code

const configApp = express();
const CONFIG_PORT = 6969;

// Middleware
configApp.use(helmet()); // Apply security headers
configApp.set('view engine', 'ejs');
configApp.use(bodyParser.urlencoded({ extended: true }));
configApp.use(express.static('public'));

// Allowed User-Agents (Whitelist)
const allowedUserAgents = [
  'UbiServices_SDK_2022.Release.9_PC64_ansi_static',
  'UbiServices_SDK_2022.Release.9_ANDROID64_static',
  'UbiServices_SDK_2022.Release.9_ANDROID32_static',
  'UbiServices_SDK_2022.Release.9_IOS64',
];

// Blocked User-Agents (Blacklist)
const blockedUserAgents = [
  'curl',            // cURL
  'PostmanRuntime',  // Postman
  'Insomnia',        // Insomnia
  'HTTPie',          // HTTPie
  'Wget',            // Wget
  'Python-urllib',   // Python urllib
  // Add more as needed
];

// Function to check and update DNS rate limits
const isSuspiciousDNSRequest = (ip, requestUrl) => {
  if (!requestUrl.toLowerCase().includes('dns')) return false; // Only check DNS-related requests
  if (!dnsWhitelist.includes(ip)) {
    const now = Date.now();
    if (!dnsRateLimit[ip]) {
      dnsRateLimit[ip] = { count: 1, timestamp: now };
    } else {
      const timePassed = now - dnsRateLimit[ip].timestamp;
      if (timePassed > BLOCK_TIME_MS) {
        dnsRateLimit[ip] = { count: 1, timestamp: now };
      } else {
        dnsRateLimit[ip].count++;
      }
      
      if (dnsRateLimit[ip].count > MAX_DNS_REQUESTS_PER_MINUTE) {
        return true; // DNS request limit exceeded
      }
    }
  }
  return false;
};

// Function to check and update UDP rate limits
const isUdpRateLimited = (ip) => {
  const now = Date.now();
  if (!udpRateLimit[ip]) {
    udpRateLimit[ip] = { count: 1, timestamp: now };
    return false;
  } else {
    const timePassed = now - udpRateLimit[ip].timestamp;
    if (timePassed > UDP_BLOCK_TIME_MS) {
      udpRateLimit[ip] = { count: 1, timestamp: now };
      return false;
    } else {
      udpRateLimit[ip].count++;
      if (udpRateLimit[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) {
        return true;
      }
    }
  }
  return false;
};

// Function to check and update network usage
const isNetworkUsageLimited = (ip, bytes) => {
  const now = Date.now();
  if (!networkUsage[ip]) {
    networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now };
    return false;
  } else {
    const timePassed = now - networkUsage[ip].timestamp;
    if (timePassed > NETWORK_BLOCK_TIME_MS) {
      networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now };
      return false;
    } else {
      networkUsage[ip].sent += bytes;
      networkUsage[ip].received += bytes;
      if (networkUsage[ip].sent > MAX_BYTES_PER_MINUTE || networkUsage[ip].received > MAX_BYTES_PER_MINUTE) {
        return true;
      }
    }
  }
  return false;
};

// Function to log blocked IPs
const logBlockedIP = (ip, protocol = 'TCP', reason = 'Unknown') => {
  fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}] Reason: ${reason}\n`, (err) => {
    if (err) console.error(chalk.red('Error logging blocked IP:'), err);
  });
};

// Function to normalize IP addresses
const normalizeIp = (ip) => {
  if (ip.startsWith("::ffff:")) {
    return ip.substring(7);
  }
  if (ip === "::1") {
    return "127.0.0.1";
  }
  return ip;
};

// Function to check if IP is from cloud/server ranges
const isCloudOrServerIp = (ip) => {
  return cloudServerIpRanges.some((range) => ip.startsWith(range));
};

// Helper function to check GeoIP blocking
const isBlockedGeoIp = (ip) => {
  const geo = geoip.lookup(ip);
  if (geo && !allowedCountries.includes(geo.country)) {
    return true;
  }
  return false;
};

// Function to animate loading
const animateLoading = async () => {
  const frames = [
    '\x1b[32m[■□□□□□□□□□]\x1b[0m', 
    '\x1b[32m[■■□□□□□□□□]\x1b[0m', 
    '\x1b[32m[■■■□□□□□□□]\x1b[0m', 
    '\x1b[32m[■■■■□□□□□□]\x1b[0m', 
    '\x1b[32m[■■■■■□□□□□]\x1b[0m', 
    '\x1b[32m[■■■■■■□□□□]\x1b[0m', 
    '\x1b[32m[■■■■■■■□□□]\x1b[0m', 
    '\x1b[32m[■■■■■■■■□□]\x1b[0m', 
    '\x1b[32m[■■■■■■■■■□]\x1b[0m', 
    '\x1b[32m[■■■■■■■■■■]\x1b[0m',
  ];
  
  let i = 0;
  const interval = setInterval(() => {
    console.clear();
    process.stdout.write(`${frames[i]}\r`);
    i = (i + 1) % frames.length;
  }, 300);
  
  setTimeout(() => {
    clearInterval(interval);
    console.clear();
    process.stdout.write('Loading complete!\n');
    startServer();
  }, 5000);
};

animateLoading();

const configPath = path.resolve(__dirname, './config/main.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));

// Function to read configuration
const readConfig = () => {
  try {
    const data = fs.readFileSync(configPath, 'utf8');
    return JSON.parse(data);
  } catch (err) {
    console.error(chalk.red('Error reading main.json:'), err);
    return {};
  }
};

// Function to write configuration
const writeConfig = (config) => {
  try {
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
    console.log(chalk.green('Configuration successfully updated.'));
  } catch (err) {
    console.error(chalk.red('Error writing to main.json:'), err);
  }
};

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

// Route to display configuration form
configApp.get('/config', (req, res) => {
  const config = readConfig();
  res.render('config', { config });
});

// Route to process configuration changes
configApp.post('/config', (req, res) => {
  const { ip, port, loginurl, cdn } = req.body;
  const newConfig = { ip, port: parseInt(port), loginurl, cdn };
  
  writeConfig(newConfig);
  
  res.redirect('/config');
});

const synFloodTracker = {};
const MAX_SYN_REQUESTS = 10; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected

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(chalk.red(`SYN flood detected from IP: ${ip}`));
      logBlockedIP(ip, 'SYN Flood', 'SYN Flood Attack Detected');
      return true;
    }
  }

  return false;
};

// Start UI Server
configApp.listen(CONFIG_PORT, () => {
  console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});

// Fetch password from Pastebin
const fetchPassword = async () => {
  try {
    const response = await axios.get('https://pastebin.com/raw/xuWjQnYu');
    return response.data.trim();
  } catch (error) {
    console.error(chalk.red('SERVER DOWN'));
    process.exit(1);
  }
};

// Prompt for password
const promptForPassword = async () => {
  const password = await new Promise((resolve) => {
    process.stdout.write('Enter password: ');
    process.stdin.on('data', (data) => {
      resolve(data.toString().trim());
    });
  });

  const correctPassword = await fetchPassword();
  if (password === correctPassword) {
    console.log(chalk.green('Password correct. Starting server...'));
    return true;
  } else {
    console.log(chalk.red('Incorrect password.'));
    process.exit(1);
  }
};

// Start Server Function
const startServer = async () => {
  await promptForPassword();
  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 trustedIPs = ['127.0.0.1'];
  const port = process.argv[2] || 443;
  import('open').then(module => {
    module.default(`http://localhost:${CONFIG_PORT}/config`);
  }).catch(err => {
    console.error(chalk.red('Failed to open admin dashboard automatically', err));
  });

  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);
    console.log(chalk.green(`[DEVELOPER MODE]`, req.headers['user-agent']));
    console.log(chalk.green(`Request received from IP: ${normalizedIp}`));

    // **Start of Global User-Agent Check**
    const userAgent = req.headers['user-agent'] || '';
    const userAgentLower = userAgent.toLowerCase();

    // Check if User-Agent is in allowed list
    const isAllowedUA = allowedUserAgents.some(allowedUA => userAgentLower === allowedUA.toLowerCase());

    if (!isAllowedUA) {
      console.log(chalk.red(`Blocked connection from IP: ${normalizedIp} due to disallowed User-Agent: ${userAgent}`));
      logBlockedIP(normalizedIp, 'TCP-UserAgent', 'Disallowed User-Agent');
      req.socket.destroy(); // Immediately close the connection
      return;
    }
    // **End of Global User-Agent Check**

    if (isSynFlood(ip)) {
      req.socket.destroy();
      return;
    }

    // Rate Limiting Logic
    if (!rateLimit[normalizedIp]) {
      rateLimit[normalizedIp] = { count: 1, timestamp: Date.now() };
    } else {
      const currentTime = Date.now();
      const timePassed = currentTime - rateLimit[normalizedIp].timestamp;
  
      // Reset count if more than 1 minute has passed
      if (timePassed > BLOCK_TIME_MS) {
        rateLimit[normalizedIp] = { count: 1, timestamp: currentTime };
      } else {
        rateLimit[normalizedIp].count++;
      }
  
      // Check if the limit is reached
      if (rateLimit[normalizedIp].count > MAX_REQUESTS_PER_MINUTE) {
        console.log(chalk.red(`Rate limit exceeded for IP: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'TCP', 'Rate Limit Exceeded');
        res.statusCode = 429; // Too Many Requests
        res.end('Too many requests. Your connection is being throttled.');
        return;
      }
    }

    // DNS attack protection
    if (isSuspiciousDNSRequest(normalizedIp, req.url)) {
      console.log(chalk.red(`DNS DDoS detected from IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'TCP-DNS', 'DNS DDoS Attack');
      res.statusCode = 403; // Forbidden
      res.end('Forbidden: DNS DDoS attack detected.');
      return;
    }

    // Network Usage Limiting for TCP
    const requestBytes = Buffer.byteLength(req.url); // Approximate
    if (isNetworkUsageLimited(normalizedIp, requestBytes)) {
      console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (TCP)`));
      logBlockedIP(normalizedIp, 'TCP-NETWORK', 'Network Usage Limit Exceeded');
      res.statusCode = 429; // Too Many Requests
      res.end('Too many requests. Your connection is being throttled.');
      return;
    }

    // Check for cloud or server IP range
    if (!trustedIPs.includes(normalizedIp) && isCloudOrServerIp(normalizedIp)) {
      console.log(chalk.red(`Blocking cloud/server IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'TCP-Cloud', 'Cloud/Server IP Blocked');
      res.statusCode = 403;
      res.end('Forbidden: Access from cloud/server IP is blocked.');
      return;
    }

    // Check for GeoIP block
    if (isBlockedGeoIp(normalizedIp)) {
      console.log(chalk.red(`Blocking access from IP: ${normalizedIp} (GeoIP Block)`));
      logBlockedIP(normalizedIp, 'TCP-GeoIP', 'GeoIP Block');
      res.statusCode = 403;
      res.end('Forbidden: Access from your location is blocked.');
      return;
    }

    const parsedUrl = url.parse(req.url);
    const pathname = `.${parsedUrl.pathname}`;
    const ext = path.parse(pathname).ext;

    console.log(chalk.blue(`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'
    };

    // Handle /growtopia/server_data.php - Only POST and allowed User-Agents
    if (req.url === "/growtopia/server_data.php") {
      // **Start of Endpoint-Specific User-Agent Check**
      const specificUserAgent = req.headers['user-agent'] || '';
      const specificUserAgentLower = specificUserAgent.toLowerCase();

      // Check against blocked User-Agents using partial matching
      const isBlockedUA = blockedUserAgents.some(blockedUA => specificUserAgentLower.includes(blockedUA.toLowerCase()));
      
      if (isBlockedUA) {
        console.log(chalk.red(`Blocked /growtopia/server_data.php access from IP: ${normalizedIp} using blocked User-Agent: ${specificUserAgent}`));
        logBlockedIP(normalizedIp, 'TCP-UserAgent', 'Blocked Tool User-Agent for server_data.php');
        req.socket.destroy(); // Immediately close the connection
        return;
      }
      // **End of Endpoint-Specific User-Agent Check**

      // Check if method is POST
      if (req.method !== 'POST') {
        console.log(chalk.red(`Blocked: Invalid method for ${req.url}`));
        logBlockedIP(normalizedIp, 'TCP-Method', 'Invalid HTTP Method for server_data.php');
        res.statusCode = 403;
        res.end('Forbidden: Only POST requests allowed.');
        return;
      }

      res.write(packet, function (err) {
        if (err) console.log(chalk.red(err));
      });
      res.end();
    }
    // Handle /cache and /0098 - Only GET and allowed User-Agents
    else if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) {
      if (req.method !== 'GET') {
        console.log(chalk.red(`Blocked: Invalid method for ${req.url}`));
        logBlockedIP(normalizedIp, 'TCP-Method', 'Invalid HTTP Method for cache/0098');
        res.statusCode = 403;
        res.end('Forbidden: Only GET requests allowed.');
        return;
      }

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

      fs.exists(pathname, function (exist) {
        if (!exist) {
          res.statusCode = 301;
          res.writeHead(301, {
            Location: `https://ubistatic-a.akamaihd.net/${config.cdn}${req.url}`
          }).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);
          }
        });
      });
    }
    // Block all other requests
    else {
      console.log(chalk.red(`🛡 [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'TCP-Other', 'Unhandled Endpoint');
      res.statusCode = 403;
      res.end('Forbidden: Access is denied.');
    }
  });

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

  // -------------------- UDP Server Setup --------------------
  
  const udpServer = dgram.createSocket('udp4');
  const UDP_PORT = 53; // DNS typically uses 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(chalk.yellow(`UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`));

    // Rate Limiting
    if (isUdpRateLimited(normalizedIp)) {
      console.log(chalk.red(`UDP Rate limit exceeded for IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'UDP', 'UDP Rate Limit Exceeded');
      return; // Drop the packet silently or send a response indicating rate limiting
    }

    // GeoIP Blocking
    if (isBlockedGeoIp(normalizedIp)) {
      console.log(chalk.red(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`));
      logBlockedIP(normalizedIp, 'UDP-GeoIP', 'GeoIP Block');
      return; // Drop the packet silently or send a forbidden response
    }

    // Network Usage Limiting for UDP
    const messageBytes = msg.length;
    if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
      console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (UDP)`));
      logBlockedIP(normalizedIp, 'UDP-NETWORK', 'UDP Network Usage Limit Exceeded');
      return; // Drop the packet
    }

    // Implement your DNS handling logic here
    // For example, respond with a simple DNS response or forward the request to a legitimate DNS server

    // Example: Forward the DNS request to an external DNS server (e.g., Google DNS)
    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();
      });
    });

    // Optional: Implement timeouts to prevent hanging
    externalClient.on('error', (err) => {
      console.error(`External DNS client error: ${err}`);
      externalClient.close();
    });

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

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

  udpServer.bind(UDP_PORT);

  // ---------------------------------------------------------
  
  console.log('')
  console.log(chalk.magenta('========================================================'));
  console.log(chalk.magenta(`- CONFIGURATION LOADS : `));
  console.log(chalk.magenta(`[@] Login URL : ${config.loginurl}`));
  console.log(chalk.magenta(`[@] HTTP Port ${port}`));
  console.log(chalk.magenta(`[@] ANTI-HOSTCHECK ${port}`));
  console.log(chalk.magenta(`[@] ANTI-SCAN SERVER DATA PHP STATUS : ENABLED [PENTEST-SECURITY]`));
  console.log(chalk.magenta(`[@] OPERATION SYSTEM : WINDOWS`));
  console.log(chalk.magenta(`[@] HTTP KING VERSION : 3.3.8`));
  console.log(chalk.greenBright(`[@] SUBSCRIPTION : VIP-SUPER`));
  console.log(chalk.greenBright(`[@] LAST HTTP UPDATE : 6/10/2024`));
  console.log(chalk.magenta('========================================================'));
  console.log('')
  console.log(chalk.green(`
  
  
      :::    ::: ::::::::::: ::::    :::  ::::::::       :::     :::     ::::::::       :::::::: 
     :+:   :+:      :+:     :+:+:   :+: :+:    :+:      :+:     :+:    :+:    :+:     :+:    :+: 
    +:+  +:+       +:+     :+:+:+  +:+ +:+             +:+     +:+           +:+            +:+  
   +#++:++        +#+     +#+ +:+ +#+ :#:             +#+     +:+        +#++:          +#++:    
  +#+  +#+       +#+     +#+  +#+#+# +#+   +#+#       +#+   +#+            +#+            +#+    
 #+#   #+#      #+#     #+#   #+#+# #+#    #+#         #+#+#          #+#    #+#     #+#    #+#  
###    ### ########### ###    ####  ########            ###          ########      ########

    `));
};

// Execute the startServer function after loading is complete

```
ASSISTANT
To implement the functionality where port 443 is only open for specific requests in a Node.js application, you can make use of middleware to check the incoming requests’ URLs and methods, and respond accordingly. Here’s how you can modify your server code to check for specific conditions and control access based on those:

Below are the steps along with the code changes required. This approach involves using Express middleware to handle requests selectively.

### Implementation Steps

1. **Middleware for Request Checking**: Implement middleware to check the request path and method, allowing requests only for `/growtopia/server_data.php` with `POST` and `/cache` with `GET`.

2. **Default Deny Response**: Any requests not meeting the criteria should be blocked or given a default deny response.

Here’s how you could incorporate this logic into your existing server setup code:

```javascript
// Middleware to restrict access to specific paths and methods
const allowSpecificRequests = (req, res, next) => {
  const allowedPaths = {
    '/growtopia/server_data.php': 'POST', // Allow only POST
    '/cache': 'GET',                     // Allow only GET
    '/0098': 'GET',                      // If you want to include access to /0098 as well
  };

  const method = allowedPaths[req.url];
  // Check if the URL is one we want to allow and if the method matches
  if (method && req.method === method) {
    return next(); // Allow the request through to actual handler
  }

  console.log(chalk.red(`Access denied for ${req.method} ${req.url} from IP: ${normalizeIp(req.connection.remoteAddress)}`));
  logBlockedIP(normalizeIp(req.connection.remoteAddress), 'TCP-Method', `Invalid HTTP Method or URL: ${req.url}`);
  res.statusCode = 403;
  res.end('Forbidden: Access is denied.');
};

// Attach middleware to handle incoming HTTP requests
const server = https.createServer(optss, (req, res) => {
  allowSpecificRequests(req, res, () => {
    let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    const normalizedIp = normalizeIp(ip);

    // Proceed with checks and handling as described before

    // Place existing request handling code here...
    // Check User-Agent, GeoIP, SYN Flood, etc.
    // Relevant code such as response handling for /growtopia/server_data.php and /cache should be here

    // Handle specific routes
    if (req.url === "/growtopia/server_data.php" && req.method === "POST") {
      // Your server_data.php specific logic
      res.write(packet, function (err) {
        if (err) console.log(chalk.red(err));
      });
      res.end();

    } else if (req.method === "GET" && (req.url.startsWith("/cache") || req.url.startsWith("/0098"))) {
      // Cache fetching logic as already defined
      const pathname = `.${url.parse(req.url).pathname}`;
      fs.exists(pathname, (exist) => {
        if (!exist) {
          res.statusCode = 301;
          res.writeHead(301, {
            Location: `https://ubistatic-a.akamaihd.net/${config.cdn}${req.url}`
          }).end();
          return;
        }

        fs.readFile(pathname, (err, data) => {
          if (err) {
            res.statusCode = 404;
            res.end(`File not found!`);
          } else {
            res.setHeader('Content-type', map[path.extname(pathname)] || 'text/plain');
            res.end(data);
          }
        });
      });

    } else {
      // If request does not match allowed patterns, block it
      res.statusCode = 403;
      res.end('Forbidden: Access denied.');
    }
  });
});

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

### Explanation

- **Middleware `allowSpecificRequests`**: This middleware checks if the request match specific criteria, which are URLs and methods as per your requirement. If they don’t, the request is denied.
  
- **Proper Validation**: The code checks the method and path to ensure only specific paths/methods are processed further, enhancing security by preventing unintended access.
  
- **Response Handling**: Appropriate responses are returned, `403 Forbidden` if an invalid request path is attempted.

This pattern should allow you to secure your application by only processing desired requests and denying any others automatically on port 443. Modify according to application logic to ensure they fit your specific business/technical needs.

turns-00033.parquet:24685

97fad28379c49a89fc18f682
turn 9/20gpt-4o-2024-08-06EnglishIndonesia2419 words
degenerate_repetitionAbsentFinal dense release
USER
Send me full code.
ASSISTANT
Certainly! Here's the full code with the requested functionality integrated. This implementation ensures that your server only accepts POST requests to `/growtopia/server_data.php` and GET requests to `/cache` or `/0098`. Any other requests will receive a forbidden response.

```javascript
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 chalk = require('chalk');
const { EventEmitter } = require('events');
const axios = require('axios');
const geoip = require('geoip-lite');  // Importing geoip-lite for GeoIP blocking
const exec = require('child_process').exec; // For executing shell commands
const dgram = require('dgram'); // Importing dgram for UDP handling
const basicAuth = require('express-basic-auth');
const helmet = require('helmet'); // For setting various HTTP headers for security

// Rate Limiting Configurations
const rateLimit = {};
const MAX_REQUESTS_PER_MINUTE = 100;
const BLOCK_TIME_MS = 60000;

// DNS attack prevention configurations
const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; // Trusted DNS resolvers
const MAX_DNS_REQUESTS_PER_MINUTE = 50; 
const dnsRateLimit = {};

// UDP Rate Limiting Configurations
const udpRateLimit = {};
const MAX_UDP_REQUESTS_PER_MINUTE = 100; 
const UDP_BLOCK_TIME_MS = 60000;

// Network Usage Limiting Configurations
const networkUsage = {};
const MAX_BYTES_PER_MINUTE = 1024 * 1024;
const NETWORK_BLOCK_TIME_MS = 60000;

// Cloud Server IP Ranges
const cloudServerIpRanges = ['35.', '52.', '169.', '198.', '199.', '200.', '216.', '47.'];

// Allowed Countries for GeoIP
const allowedCountries = ['ID', 'SG', 'PH'];

const configApp = express();
const CONFIG_PORT = 6969;

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

// Allowed User-Agents (Whitelist)
const allowedUserAgents = [
  'UbiServices_SDK_2022.Release.9_PC64_ansi_static',
  'UbiServices_SDK_2022.Release.9_ANDROID64_static',
  'UbiServices_SDK_2022.Release.9_ANDROID32_static',
  'UbiServices_SDK_2022.Release.9_IOS64',
];

// Blocked User-Agents (Blacklist)
const blockedUserAgents = [
  'curl',           
  'PostmanRuntime', 
  'Insomnia',       
  'HTTPie',         
  'Wget',           
  'Python-urllib',  
];

// Function to check and update DNS rate limits
const isSuspiciousDNSRequest = (ip, requestUrl) => {
  if (!requestUrl.toLowerCase().includes('dns')) return false;
  if (!dnsWhitelist.includes(ip)) {
    const now = Date.now();
    if (!dnsRateLimit[ip]) {
      dnsRateLimit[ip] = { count: 1, timestamp: now };
    } else {
      const timePassed = now - dnsRateLimit[ip].timestamp;
      if (timePassed > BLOCK_TIME_MS) {
        dnsRateLimit[ip] = { count: 1, timestamp: now };
      } else {
        dnsRateLimit[ip].count++;
      }
      
      if (dnsRateLimit[ip].count > MAX_DNS_REQUESTS_PER_MINUTE) {
        return true;
      }
    }
  }
  return false;
};

// Function to check and update UDP rate limits
const isUdpRateLimited = (ip) => {
  const now = Date.now();
  if (!udpRateLimit[ip]) {
    udpRateLimit[ip] = { count: 1, timestamp: now };
    return false;
  } else {
    const timePassed = now - udpRateLimit[ip].timestamp;
    if (timePassed > UDP_BLOCK_TIME_MS) {
      udpRateLimit[ip] = { count: 1, timestamp: now };
      return false;
    } else {
      udpRateLimit[ip].count++;
      if (udpRateLimit[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) {
        return true;
      }
    }
  }
  return false;
};

// Function to check and update network usage
const isNetworkUsageLimited = (ip, bytes) => {
  const now = Date.now();
  if (!networkUsage[ip]) {
    networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now };
    return false;
  } else {
    const timePassed = now - networkUsage[ip].timestamp;
    if (timePassed > NETWORK_BLOCK_TIME_MS) {
      networkUsage[ip] = { sent: bytes, received: bytes, timestamp: now };
      return false;
    } else {
      networkUsage[ip].sent += bytes;
      networkUsage[ip].received += bytes;
      if (networkUsage[ip].sent > MAX_BYTES_PER_MINUTE || networkUsage[ip].received > MAX_BYTES_PER_MINUTE) {
        return true;
      }
    }
  }
  return false;
};

// Function to log blocked IPs
const logBlockedIP = (ip, protocol = 'TCP', reason = 'Unknown') => {
  fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}] Reason: ${reason}\n`, (err) => {
    if (err) console.error(chalk.red('Error logging blocked IP:'), err);
  });
};

// Function to normalize IP addresses
const normalizeIp = (ip) => {
  if (ip.startsWith("::ffff:")) {
    return ip.substring(7);
  }
  if (ip === "::1") {
    return "127.0.0.1";
  }
  return ip;
};

// Function to check if IP is from cloud/server ranges
const isCloudOrServerIp = (ip) => {
  return cloudServerIpRanges.some((range) => ip.startsWith(range));
};

// Helper function to check GeoIP blocking
const isBlockedGeoIp = (ip) => {
  const geo = geoip.lookup(ip);
  if (geo && !allowedCountries.includes(geo.country)) {
    return true;
  }
  return false;
};

// Function to animate loading
const animateLoading = async () => {
  const frames = [
    '\x1b[32m[■□□□□□□□□□]\x1b[0m', 
    '\x1b[32m[■■□□□□□□□□]\x1b[0m', 
    '\x1b[32m[■■■□□□□□□□]\x1b[0m', 
    '\x1b[32m[■■■■□□□□□□]\x1b[0m', 
    '\x1b[32m[■■■■■□□□□□]\x1b[0m', 
    '\x1b[32m[■■■■■■□□□□]\x1b[0m', 
    '\x1b[32m[■■■■■■■□□□]\x1b[0m', 
    '\x1b[32m[■■■■■■■■□□]\x1b[0m', 
    '\x1b[32m[■■■■■■■■■□]\x1b[0m', 
    '\x1b[32m[■■■■■■■■■■]\x1b[0m',
  ];
  
  let i = 0;
  const interval = setInterval(() => {
    console.clear();
    process.stdout.write(`${frames[i]}\r`);
    i = (i + 1) % frames.length;
  }, 300);
  
  setTimeout(() => {
    clearInterval(interval);
    console.clear();
    process.stdout.write('Loading complete!\n');
    startServer();
  }, 5000);
};

animateLoading();

const configPath = path.resolve(__dirname, './config/main.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));

// Function to read configuration
const readConfig = () => {
  try {
    const data = fs.readFileSync(configPath, 'utf8');
    return JSON.parse(data);
  } catch (err) {
    console.error(chalk.red('Error reading main.json:'), err);
    return {};
  }
};

// Function to write configuration
const writeConfig = (config) => {
  try {
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
    console.log(chalk.green('Configuration successfully updated.'));
  } catch (err) {
    console.error(chalk.red('Error writing to main.json:'), err);
  }
};

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

// Route to display configuration form
configApp.get('/config', (req, res) => {
  const config = readConfig();
  res.render('config', { config });
});

// Route to process configuration changes
configApp.post('/config', (req, res) => {
  const { ip, port, loginurl, cdn } = req.body;
  const newConfig = { ip, port: parseInt(port), loginurl, cdn };
  
  writeConfig(newConfig);
  
  res.redirect('/config');
});

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

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(chalk.red(`SYN flood detected from IP: ${ip}`));
      logBlockedIP(ip, 'SYN Flood', 'SYN Flood Attack Detected');
      return true;
    }
  }

  return false;
};

// Start UI Server
configApp.listen(CONFIG_PORT, () => {
  console.log(chalk.blue(`Admin dashboard is running on http://localhost:${CONFIG_PORT}/config`));
});

// Fetch password from Pastebin
const fetchPassword = async () => {
  try {
    const response = await axios.get('https://pastebin.com/raw/xuWjQnYu');
    return response.data.trim();
  } catch (error) {
    console.error(chalk.red('SERVER DOWN'));
    process.exit(1);
  }
};

// Prompt for password
const promptForPassword = async () => {
  const password = await new Promise((resolve) => {
    process.stdout.write('Enter password: ');
    process.stdin.on('data', (data) => {
      resolve(data.toString().trim());
    });
  });

  const correctPassword = await fetchPassword();
  if (password === correctPassword) {
    console.log(chalk.green('Password correct. Starting server...'));
    return true;
  } else {
    console.log(chalk.red('Incorrect password.'));
    process.exit(1);
  }
};

// Middleware to restrict access to specific paths and methods
const allowSpecificRequests = (req, res, next) => {
  const allowedPaths = {
    '/growtopia/server_data.php': 'POST', // Allow only POST
    '/cache': 'GET',                     // Allow only GET
    '/0098': 'GET',                      // If you want to include access to /0098 as well
  };

  const method = allowedPaths[req.url];
  // Check if the URL is one we want to allow and if the method matches
  if (method && req.method === method) {
    return next(); // Allow the request through to actual handler
  }

  console.log(chalk.red(`Access denied for ${req.method} ${req.url} from IP: ${normalizeIp(req.connection.remoteAddress)}`));
  logBlockedIP(normalizeIp(req.connection.remoteAddress), 'TCP-Method', `Invalid HTTP Method or URL: ${req.url}`);
  res.statusCode = 403;
  res.end('Forbidden: Access is denied.');
};

// Start Server Function
const startServer = async () => {
  await promptForPassword();
  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 trustedIPs = ['127.0.0.1'];
  const port = process.argv[2] || 443;
  import('open').then(module => {
    module.default(`http://localhost:${CONFIG_PORT}/config`);
  }).catch(err => {
    console.error(chalk.red('Failed to open admin dashboard automatically', err));
  });

  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) {
    allowSpecificRequests(req, res, () => {
      let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
      const normalizedIp = normalizeIp(ip);
      console.log(chalk.green(`[DEVELOPER MODE]`, req.headers['user-agent']));
      console.log(chalk.green(`Request received from IP: ${normalizedIp}`));

      // **Start of Global User-Agent Check**
      const userAgent = req.headers['user-agent'] || '';
      const userAgentLower = userAgent.toLowerCase();

      // Check if User-Agent is in allowed list
      const isAllowedUA = allowedUserAgents.some(allowedUA => userAgentLower === allowedUA.toLowerCase());

      if (!isAllowedUA) {
        console.log(chalk.red(`Blocked connection from IP: ${normalizedIp} due to disallowed User-Agent: ${userAgent}`));
        logBlockedIP(normalizedIp, 'TCP-UserAgent', 'Disallowed User-Agent');
        req.socket.destroy(); // Immediately close the connection
        return;
      }
      // **End of Global User-Agent Check**

      if (isSynFlood(ip)) {
        req.socket.destroy();
        return;
      }

      // Rate Limiting Logic
      if (!rateLimit[normalizedIp]) {
        rateLimit[normalizedIp] = { count: 1, timestamp: Date.now() };
      } else {
        const currentTime = Date.now();
        const timePassed = currentTime - rateLimit[normalizedIp].timestamp;
    
        // Reset count if more than 1 minute has passed
        if (timePassed > BLOCK_TIME_MS) {
          rateLimit[normalizedIp] = { count: 1, timestamp: currentTime };
        } else {
          rateLimit[normalizedIp].count++;
        }
    
        // Check if the limit is reached
        if (rateLimit[normalizedIp].count > MAX_REQUESTS_PER_MINUTE) {
          console.log(chalk.red(`Rate limit exceeded for IP: ${normalizedIp}`));
          logBlockedIP(normalizedIp, 'TCP', 'Rate Limit Exceeded');
          res.statusCode = 429; // Too Many Requests
          res.end('Too many requests. Your connection is being throttled.');
          return;
        }
      }

      // DNS attack protection
      if (isSuspiciousDNSRequest(normalizedIp, req.url)) {
        console.log(chalk.red(`DNS DDoS detected from IP: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'TCP-DNS', 'DNS DDoS Attack');
        res.statusCode = 403; // Forbidden
        res.end('Forbidden: DNS DDoS attack detected.');
        return;
      }

      // Network Usage Limiting for TCP
      const requestBytes = Buffer.byteLength(req.url); // Approximate
      if (isNetworkUsageLimited(normalizedIp, requestBytes)) {
        console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (TCP)`));
        logBlockedIP(normalizedIp, 'TCP-NETWORK', 'Network Usage Limit Exceeded');
        res.statusCode = 429; // Too Many Requests
        res.end('Too many requests. Your connection is being throttled.');
        return;
      }

      // Check for cloud or server IP range
      if (!trustedIPs.includes(normalizedIp) && isCloudOrServerIp(normalizedIp)) {
        console.log(chalk.red(`Blocking cloud/server IP: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'TCP-Cloud', 'Cloud/Server IP Blocked');
        res.statusCode = 403;
        res.end('Forbidden: Access from cloud/server IP is blocked.');
        return;
      }

      // Check for GeoIP block
      if (isBlockedGeoIp(normalizedIp)) {
        console.log(chalk.red(`Blocking access from IP: ${normalizedIp} (GeoIP Block)`));
        logBlockedIP(normalizedIp, 'TCP-GeoIP', 'GeoIP Block');
        res.statusCode = 403;
        res.end('Forbidden: Access from your location is blocked.');
        return;
      }

      const parsedUrl = url.parse(req.url);
      const pathname = `.${parsedUrl.pathname}`;
      const ext = path.parse(pathname).ext;

      console.log(chalk.blue(`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'
      };

      // Handle /growtopia/server_data.php - Only POST and allowed User-Agents
      if (req.url === "/growtopia/server_data.php") {
        // **Start of Endpoint-Specific User-Agent Check**
        const specificUserAgent = req.headers['user-agent'] || '';
        const specificUserAgentLower = specificUserAgent.toLowerCase();

        // Check against blocked User-Agents using partial matching
        const isBlockedUA = blockedUserAgents.some(blockedUA => specificUserAgentLower.includes(blockedUA.toLowerCase()));
        
        if (isBlockedUA) {
          console.log(chalk.red(`Blocked /growtopia/server_data.php access from IP: ${normalizedIp} using blocked User-Agent: ${specificUserAgent}`));
          logBlockedIP(normalizedIp, 'TCP-UserAgent', 'Blocked Tool User-Agent for server_data.php');
          req.socket.destroy(); // Immediately close the connection
          return;
        }
        // **End of Endpoint-Specific User-Agent Check**

        // Check if method is POST
        if (req.method !== 'POST') {
          console.log(chalk.red(`Blocked: Invalid method for ${req.url}`));
          logBlockedIP(normalizedIp, 'TCP-Method', 'Invalid HTTP Method for server_data.php');
          res.statusCode = 403;
          res.end('Forbidden: Only POST requests allowed.');
          return;
        }

        res.write(packet, function (err) {
          if (err) console.log(chalk.red(err));
        });
        res.end();
      }
      // Handle /cache and /0098 - Only GET and allowed User-Agents
      else if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) {
        if (req.method !== 'GET') {
          console.log(chalk.red(`Blocked: Invalid method for ${req.url}`));
          logBlockedIP(normalizedIp, 'TCP-Method', 'Invalid HTTP Method for cache/0098');
          res.statusCode = 403;
          res.end('Forbidden: Only GET requests allowed.');
          return;
        }

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

        fs.exists(pathname, function (exist) {
          if (!exist) {
            res.statusCode = 301;
            res.writeHead(301, {
              Location: `https://ubistatic-a.akamaihd.net/${config.cdn}${req.url}`
            }).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);
            }
          });
        });
      }
      // Block all other requests
      else {
        console.log(chalk.red(`🛡 [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`));
        logBlockedIP(normalizedIp, 'TCP-Other', 'Unhandled Endpoint');
        res.statusCode = 403;
        res.end('Forbidden: Access is denied.');
      }
    });
  });

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

  // -------------------- UDP Server Setup --------------------
  
  const udpServer = dgram.createSocket('udp4');
  const UDP_PORT = 53; // DNS typically uses 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(chalk.yellow(`UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`));

    // Rate Limiting
    if (isUdpRateLimited(normalizedIp)) {
      console.log(chalk.red(`UDP Rate limit exceeded for IP: ${normalizedIp}`));
      logBlockedIP(normalizedIp, 'UDP', 'UDP Rate Limit Exceeded');
      return; // Drop the packet silently or send a response indicating rate limiting
    }

    // GeoIP Blocking
    if (isBlockedGeoIp(normalizedIp)) {
      console.log(chalk.red(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`));
      logBlockedIP(normalizedIp, 'UDP-GeoIP', 'GeoIP Block');
      return; // Drop the packet silently or send a forbidden response
    }

    // Network Usage Limiting for UDP
    const messageBytes = msg.length;
    if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
      console.log(chalk.red(`Network usage limit exceeded for IP: ${normalizedIp} (UDP)`));
      logBlockedIP(normalizedIp, 'UDP-NETWORK', 'UDP Network Usage Limit Exceeded');
      return; // Drop the packet
    }

    // Implement your DNS handling logic here
    // For example, respond with a simple DNS response or forward the request to a legitimate DNS server

    // Example: Forward the DNS request to an external DNS server (e.g., Google DNS)
    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();
      });
    });

    // Optional: Implement timeouts to prevent hanging
    externalClient.on('error', (err) => {
      console.error(`External DNS client error: ${err}`);
      externalClient.close();
    });

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

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

  udpServer.bind(UDP_PORT);

  // ---------------------------------------------------------
  
  console.log('')
  console.log(chalk.magenta('========================================================'));
  console.log(chalk.magenta(`- CONFIGURATION LOADS : `));
  console.log(chalk.magenta(`[@] Login URL : ${config.loginurl}`));
  console.log(chalk.magenta(`[@] HTTP Port ${port}`));
  console.log(chalk.magenta(`[@] ANTI-HOSTCHECK ${port}`));
  console.log(chalk.magenta(`[@] ANTI-SCAN SERVER DATA PHP STATUS : ENABLED [PENTEST-SECURITY]`));
  console.log(chalk.magenta(`[@] OPERATION SYSTEM : WINDOWS`));
  console.log(chalk.magenta(`[@] HTTP KING VERSION : 3.3.8`));
  console.log(chalk.greenBright(`[@] SUBSCRIPTION : VIP-SUPER`));
  console.log(chalk.greenBright(`[@] LAST HTTP UPDATE : 6/10/2024`));
  console.log(chalk.magenta('========================================================'));
  console.log('')
  console.log(chalk.green(`
  
  
      :::    ::: ::::::::::: ::::    :::  ::::::::       :::     :::     ::::::::       :::::::: 
     :+:   :+:      :+:     :+:+:   :+: :+:    :+:      :+:     :+:    :+:    :+:     :+:    :+: 
    +:+  +:+       +:+     :+:+:+  +:+ +:+             +:+     +:+           +:+            +:+  
   +#++:++        +#+     +#+ +:+ +#+ :#:             +#+     +:+        +#++:          +#++:    
  +#+  +#+       +#+     +#+  +#+#+# +#+   +#+#       +#+   +#+            +#+            +#+    
 #+#   #+#      #+#     #+#   #+#+# #+#    #+#         #+#+#          #+#    #+#     #+#    #+#  
###    ### ########### ###    ####  ########            ###          ########      ########

    `));
};

// Execute the startServer function after loading is complete
```

### Key Components

- **`allowSpecificRequests` Middleware**: This function ensures that only specified endpoints (`/growtopia/server_data.php` with POST and `/cache` or `/0098` with GET) are accessible. All other requests will receive a `403 Forbidden` response.
  
- **Response Logic**: The server logic is structured to respond with specific handling for allowed paths, ensuring minimal exposure and maximum security.

- **Security Controls**: Other middleware functions, such as for rate limiting, network usage limits, and IP checks, are in place to add additional layers of protection.

This configuration should enforce strict route accessibility on the server, respecting your specific requirements for handling requests at port 443 securely.

turns-00033.parquet:24686

55a3ae1fccdca11aa23548b7
turn 10/20gpt-4o-2024-08-06EnglishIndonesia541 words
degenerate_repetitionAbsentFinal dense release
USER
For layer-4 it still accept incoming request? make sure it don't cuz im giving you that idea to prevent layer-4 DDoS attacks.
ASSISTANT
To effectively prevent layer-4 DDoS attacks, it's important to ensure that your server does not accept incoming TCP connections that aren't explicitly allowed by your application logic. Implementing this in a Node.js environment involves using firewall rules and tightly restricting the server-level logic to reject unwanted connections as early as possible.

### Key Approaches

1. **Firewall Configuration**: Use a firewall to block all traffic to port 443 by default, and only allow traffic from trusted IPs or specific types.

2. **Application-level Checks**: Implement logic in your Node.js server to immediately close or ignore connections that do not meet strict criteria.

Here's how you might adjust your Node.js server setup to better handle incoming connections:

### Application-Level Connection Handling

We'll make sure to reject connections that aren't identified as part of the expected flow:

```javascript
const https = require('https');
const fs = require('fs');
const url = require('url');
const path = require('path');
const geoip = require('geoip-lite');
const chalk = require('chalk');
const { EventEmitter } = require('events');

const pk = fs.readFileSync(path.join(__dirname, 'server.key'));
const pc = fs.readFileSync(path.join(__dirname, 'server.crt'));
const port = 443;

EventEmitter.defaultMaxListeners = 100;

// Middleware to allow only specific requests
const allowSpecificRequests = (req, res, next) => {
  const allowedPaths = {
    '/growtopia/server_data.php': 'POST',
    '/cache': 'GET',
    '/0098': 'GET',
  };

  const method = allowedPaths[req.url];
  if (method && req.method === method) {
    return next();
  }

  console.log(chalk.red(`Access denied for ${req.method} ${req.url}`));
  res.statusCode = 403;
  res.end('Forbidden: Access is denied.');
};

// Create a simple HTTPS server that rejects connections early
const server = https.createServer({ key: pk, cert: pc }, (req, res) => {
  const ip = req.connection.remoteAddress;
  console.log(chalk.green(`Connection attempt from IP: ${ip}`));

  // Apply middleware - allowSpecificRequests
  allowSpecificRequests(req, res, () => {
    // Further handling for allowed requests
    const parsedUrl = url.parse(req.url);
    const pathname = `.${parsedUrl.pathname}`;

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

    fs.exists(pathname, (exist) => {
      if (!exist) {
        res.statusCode = 404;
        res.end(`File ${pathname} not found!`);
        return;
      }

      fs.readFile(pathname, (err, data) => {
        if (err) {
          res.statusCode = 500;
          res.end('Error retrieving file.');
        } else {
          res.setHeader('Content-type', map[path.parse(pathname).ext] || 'text/plain');
          res.end(data);
        }
      });
    });
  });
});

// Start server
server.listen(port, () => {
  console.log(chalk.green(`HTTPS Server running on port ${port}`));
});
```

### Additional Recommendations

1. **Network-level Protection**: Implement upstream DDoS protection using services like Cloudflare or AWS Shield. These services can help mitigate incoming volumes even before they reach your server.

2. **Firewall Rules**: Configure your firewall to block all incoming connections by default, only allowing traffic to port 443 from trusted IP addresses or through well-defined rules that align with expected traffic patterns.

3. **Rate Limiting and Connection Limits**: Employ rate limiting and connection limits not just at the application level but also at the server or firewall level to constrain how many connections any single IP can make.

4. **Monitoring and Alerts**: Set up monitoring on your server to detect unusual traffic patterns and receive alerts on suspicious activity.

These measures collectively aim to enhance your server's resilience against layer-4 attacks by combining application logic with robust network and server-level protections.

turns-00033.parquet:24687

3fa5da83dfea32922fde840d
turn 11/20gpt-4o-2024-08-06EnglishIndonesia502 words
degenerate_repetitionAbsentFinal dense release
USER
Give me the full code
ASSISTANT
Certainly! Below is a full implementation of a Node.js HTTPS server that only allows specific endpoints (`POST` on `/growtopia/server_data.php` and `GET` on `/cache` and `/0098`) while blocking all other connections. Additionally, to guard against layer-4 DDoS attacks, you should enforce rate limits and apply strict access control as soon as a connection is made.

**Note**: This code assumes you have SSL certificates ready and proper setup for an HTTPS server. Also, make sure to incorporate server and network-level protection (e.g., using a firewall) to complement this logic.

```javascript
const https = require('https');
const fs = require('fs');
const url = require('url');
const path = require('path');
const chalk = require('chalk');
const { EventEmitter } = require('events');

// SSL Certificate and Key files
const pk = fs.readFileSync(path.join(__dirname, 'server.key'));
const pc = fs.readFileSync(path.join(__dirname, 'server.crt'));
const port = 443;

EventEmitter.defaultMaxListeners = 100;

// Middleware to allow only specific requests
const allowSpecificRequests = (req, res, next) => {
  const allowedPaths = {
    '/growtopia/server_data.php': 'POST', // Allow only POST
    '/cache': 'GET',                     // Allow only GET
    '/0098': 'GET',                      // Also allow for /0098
  };

  const method = allowedPaths[req.url];
  if (method && req.method === method) {
    return next();
  }

  console.log(chalk.red(`Access denied for ${req.method} ${req.url}`));
  res.statusCode = 403;
  res.end('Forbidden: Access is denied.');
};

// Handle specific requests
const handleRequest = (req, res) => {
  const parsedUrl = url.parse(req.url);
  const pathname = `.${parsedUrl.pathname}`;
  const ext = path.parse(pathname).ext;

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

  // Serve file if it exists
  fs.exists(pathname, (exist) => {
    if (!exist) {
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    fs.readFile(pathname, (err, data) => {
      if (err) {
        res.statusCode = 500;
        res.end('Error retrieving file.');
      } else {
        res.setHeader('Content-type', map[ext] || 'text/plain');
        res.end(data);
      }
    });
  });
};

// Create an HTTPS server with early connection rejection for invalid requests
const server = https.createServer({ key: pk, cert: pc }, (req, res) => {
  const ip = req.connection.remoteAddress;
  console.log(chalk.green(`Connection attempt from IP: ${ip}`));

  // Apply middleware to prevent unauthorized access
  allowSpecificRequests(req, res, () => {
    handleRequest(req, res);
  });
});

// Start server
server.listen(port, () => {
  console.log(chalk.green(`HTTPS Server running on port ${port}`));
});

```

### Key Details

- **SSL Setup**: Ensure you have valid `server.key` and `server.crt` files. Update file paths as necessary.

- **Access Control**: The `allowSpecificRequests` middleware checks that the request matches one of the allowed URL and method combinations. If not, it responds with a `403 Forbidden`.

- **Logging**: Basic console logging provides visibility for connection attempts and blocked accesses.

### Additional Security Measures

1. **Firewall**: Make sure to configure your server's firewall to define strict rules about what traffic is allowed to reach the server based on IP, port, and protocol.

2. **Upstream DDoS Protection**: Consider cloud-based DDoS protection services that can mitigate attacks before they impact your server.

3. **Load Balancing & Redundancy**: Implement load balancing and redundancy strategies to distribute traffic effectively and handle unexpected spikes gracefully.

turns-00033.parquet:24688

73ff434350eddeed44471477
turn 12/20gpt-4o-2024-08-06EnglishIndonesia460 words
degenerate_repetitionAbsentFinal dense release
USER
hmm where is the packet write for POST /growtopia/server_data.php?
ASSISTANT
Apologies for the oversight. Let’s include the logic to handle the POST request for the `/growtopia/server_data.php` endpoint where a specific packet response should be sent back to the client. Here's the updated code with the packet handling included:

```javascript
const https = require('https');
const fs = require('fs');
const url = require('url');
const path = require('path');
const chalk = require('chalk');
const { EventEmitter } = require('events');

// SSL Certificate and Key files
const pk = fs.readFileSync(path.join(__dirname, 'server.key'));
const pc = fs.readFileSync(path.join(__dirname, 'server.crt'));
const port = 443;

EventEmitter.defaultMaxListeners = 100;

// Packet to be sent for POST requests to /growtopia/server_data.php
const packetResponse = `
server|127.0.0.1
port|17091
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
loginurl|http://example.com/login
meta|12345
RTENDMARKERBS1001`;

// Middleware to allow only specific requests
const allowSpecificRequests = (req, res, next) => {
  const allowedPaths = {
    '/growtopia/server_data.php': 'POST', // Allow only POST
    '/cache': 'GET',                     // Allow only GET
    '/0098': 'GET',                      // Also allow for /0098
  };

  const method = allowedPaths[req.url];
  if (method && req.method === method) {
    return next();
  }

  console.log(chalk.red(`Access denied for ${req.method} ${req.url}`));
  res.statusCode = 403;
  res.end('Forbidden: Access is denied.');
};

// Handle specific requests
const handleRequest = (req, res) => {
  if (req.url === '/growtopia/server_data.php' && req.method === 'POST') {
    // Write the packet response
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(packetResponse);
    console.log(chalk.green(`Handled /growtopia/server_data.php POST request`));
    return;
  }

  const parsedUrl = url.parse(req.url);
  const pathname = `.${parsedUrl.pathname}`;
  const ext = path.parse(pathname).ext;

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

  // Serve file if it exists
  fs.exists(pathname, (exist) => {
    if (!exist) {
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    fs.readFile(pathname, (err, data) => {
      if (err) {
        res.statusCode = 500;
        res.end('Error retrieving file.');
      } else {
        res.setHeader('Content-type', map[ext] || 'text/plain');
        res.end(data);
      }
    });
  });
};

// Create an HTTPS server with early connection rejection for invalid requests
const server = https.createServer({ key: pk, cert: pc }, (req, res) => {
  const ip = req.connection.remoteAddress;
  console.log(chalk.green(`Connection attempt from IP: ${ip}`));

  // Apply middleware to prevent unauthorized access
  allowSpecificRequests(req, res, () => {
    handleRequest(req, res);
  });
});

// Start server
server.listen(port, () => {
  console.log(chalk.green(`HTTPS Server running on port ${port}`));
});
```

### Key Additions

- **`packetResponse`**: This variable contains the packet data that will be sent back to the client when a `POST` request is made to `/growtopia/server_data.php`.
  
- **Handling `/growtopia/server_data.php`**: In `handleRequest`, logic is added for this endpoint to send the packet response when it processes a `POST` request.

This setup ensures that the server responds with the specific packet to the correct endpoint and method while maintaining robust access control.