const synFloodTracker = {};
const MAX_SYN_REQUESTS = 10; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected
// 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 = {};
// 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;
};
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');
return true;
}
}
return false;
};
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
// console.log(chalk.blue(ADMIN DASHBOARD IS ONLINE));
});
// Start Server Function
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 trustedIPs = ['127.0.0.1'];
const port = process.argv[2] || 443;
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;
// Set keepAliveTimeout, which sets how long a connection should remain open in milliseconds.
server.keepAliveTimeout = 60 * 1000; // Keep alive for 60 seconds
// Set the headers timeout slightly longer than keepAliveTimeout to accommodate requests that arrive just before the keep alive timeout
server.headersTimeout = 65 * 1000; // 65 seconds
code
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
if (req.url === "/growtopia/server_data.php") {
if (req.method !== 'POST' || hostHeader !== 'www.growtopia1.com' || !allowedUserAgents.includes(userAgent)) {
console.log(chalk.red(Mata mata : ${req.url}));
res.statusCode = 403;
res.end(`
server|normalizedIpport∣{Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
server.listen(port, () => {
console.log(chalk.green(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}));
code
// Rate Limiting
if (isUdpRateLimited(normalizedIp)) {
console.log(chalk.red(`UDP Rate limit exceeded for IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'UDP');
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');
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');
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);
const shutdown = () => {
console.log('Shutting down the server...');
code
// Stop the server from accepting new connections
server.close(() => {
console.log('HTTP server closed.');
// Close the UDP server
udpServer.close(() => {
console.log('UDP server closed.');
// Exit the process
process.exit(0);
});
});
// Ensure shutdown if connections remain
setTimeout(() => {
console.error('Forced shutdown due to open connections.');
process.exit(1); // exit with error code if connections remain
}, 5000).unref();
can you make all the console.log make a eye-catching icon and the text gradient from right to left
Assistant
To make console logs more eye-catching with an icon and a gradient effect from right to left, we can use the chalk package's gradient features along with Unicode characters to enhance the visual appeal of the logs. Here's how you can modify your logging statements:
javascript
const chalk = require('chalk');
const gradient = require('gradient-string');
// Load this at the beginning where the modules are imported
const logIcon = chalk.blueBright('[🔍] ');
// Create custom logging functions with a gradient effect
const logInfo = (message) => {
console.log(logIcon + gradient.vice(message));
};
const logError = (message) => {
console.log(logIcon + gradient.passion(message));
};
const logSuccess = (message) => {
console.log(logIcon + gradient.instagram(message));
};
// Usage examples:
// Replace the existing console.log instances with the new functions
logInfo(`Server is running on port ${port}`);
logError('Rate limit exceeded for IP');
logSuccess('Configuration updated');
Explanation:
Icons: We added an icon [🔍] to make each log entry more visually distinct. You can adjust the icon based on the log type (e.g., info, error, success).
Gradients: We use the gradient-string package to apply a gradient effect to text. The gradients used are:
gradient.vice: A vice city-style gradient.
gradient.passion: A passionate sunburst gradient.
gradient.instagram: A gradient inspired by Instagram.
Log Functions: We wrap the log statements in helper functions (logInfo, logError, logSuccess) to ensure consistency and apply the appropriate styling.
Use these substitutions everywhere you currently have console.log to make your logs consistent with this new styling. For any unique logging requirements, you can expand these helper functions as needed.
User
The icon is random, based on the log means
Assistant
Sure, I can help you incorporate random icons and appropriately classify log types with different icons. We can use sets of icons for info, error, and success messages. Here's how you can integrate this into your logging system:
javascript
const chalk = require('chalk');
const gradient = require('gradient-string');
// Arrays of icons for different log types
const infoIcons = ['ℹ️', '🔍', '📘'];
const errorIcons = ['❌', '🔥', '🚫'];
const successIcons = ['✅', '🎉', '👌'];
// Function to get a random icon from a given array
const getRandomIcon = (icons) => icons[Math.floor(Math.random() * icons.length)];
// Create custom logging functions with a gradient effect
const logInfo = (message) => {
const icon = getRandomIcon(infoIcons);
console.log(chalk.blueBright(`${icon}`) + ' ' + gradient.vice(message));
};
const logError = (message) => {
const icon = getRandomIcon(errorIcons);
console.log(chalk.redBright(`${icon}`) + ' ' + gradient.passion(message));
};
const logSuccess = (message) => {
const icon = getRandomIcon(successIcons);
console.log(chalk.greenBright(`${icon}`) + ' ' + gradient.instagram(message));
};
// Usage examples
logInfo(`Server is running on port ${port}`);
logError('Rate limit exceeded for IP');
logSuccess('Configuration updated');
Explanation:
Random Icons: We've created arrays of icons for info, error, and success log messages. Each type has a list of possible icons to choose from.
Random Selection: The getRandomIcon function selects a random icon from the given array, adding a variety to your log messages.
Log Functions: Functions logInfo, logError, and logSuccess use these random icons and apply color and gradient appropriate to the log type:
Info: Uses gradient.vice for a soft gradient.
Error: Uses gradient.passion for bold and urgent feel.
Success: Uses gradient.instagram reflecting a positive outcome.
Whenever you need to log a message, use these helper functions to maintain consistent styling and add randomness to the icons. Adjust the icon sets and messages as you see fit for your application.
User
add it to my 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 { spawn } = require('child_process');
const dgram = require('dgram'); // Importing dgram for UDP handling
const basicAuth = require('express-basic-auth');
const compression = require('compression');
const osu = require('os-utils');
const { netstat } = require('node-os-utils'); // Import netstat from node-os-utils
const mem = require('node-os-utils').mem;
// Create an Agent instance configured for keep-alive
const keepAliveAgent = new https.Agent({
keepAlive: true,
maxSockets: 100, // Control the number of sockets to handle concurrent connections
maxFreeSockets: 10, // Control the number of free sockets to keep open
});
const synFloodTracker = {};
const MAX_SYN_REQUESTS = 10; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected
// 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 = {};
// 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++;
}
Assistant
To incorporate random icons and apply text gradients for your console.log messages, we can define helper logging functions that encapsulate these features. Below, I'll make those enhancements in your code:
javascript
User
const gradient = require('gradient-string');
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Administrator\Desktop\node_modules\gradient-string\dist\index.js from C:\Users\Administrator\Desktop\HTTP-PRO.js not supported.
Instead change the require of index.js in C:\Users\Administrator\Desktop\HTTP-PRO.js to a dynamic import() which is available in all CommonJS modules.
at Object. (C:\Users\Administrator\Desktop\HTTP-PRO.js:23:18) {
code: 'ERR_REQUIRE_ESM'
}
Assistant
The error message you're seeing indicates that the gradient-string package is now an ECMAScript Module (ESM) and requires dynamic import() syntax for use in CommonJS modules. Since your script is written in CommonJS, you'll need to adjust how you import this package.
Here is how you can modify your imports and the usage of gradient-string in your Node.js script:
Use import() instead of require() for gradient-string.
Update the parts of your code where gradients are applied.
TypeError: Cannot read properties of undefined (reading 'vice')
Assistant
The error occurs because the gradient variable might not be initialized before its first use. Since import() is asynchronous and the gradient module is loaded dynamically, you need to ensure that any code using gradient is executed only after it has been successfully imported.
Here's a structured way to handle this, ensuring that gradient is fully loaded before attempting to use it:
Delay initialization until after the module is loaded. Wrap server logic inside the asynchronous block that waits for the module to be ready. This method ensures that gradient is available before any function that depends on it is called.
Check if gradient is properly initialized. Ensure that no code dependent on gradient runs before the module is loaded.
Here’s how you might structure the code:
javascript
User
can you send me the full code, and make sure its fixed im running on windows btw
Assistant
Certainly! I'll modify the code to ensure that the dynamic import and use of gradient-string are handled properly, and that the gradient log messages are only used once the module is fully loaded. Additionally, I'll ensure everything is set up to work seamlessly on a Windows environment. Here's the full updated version of your script:
javascript
User
Ok now its working, but the icon is not loaded correctly its an "?" its on command prompt btw
Assistant
When icons are not displaying correctly in the command prompt (CMD), it's typically due to the terminal's inability to render Unicode characters. The Windows Command Prompt has limited support for some Unicode characters, especially emojis.
To handle this issue:
Use Compatible Characters: Instead of emojis, which may not be supported, you can use ASCII characters or simple text symbols that CMD can display.
Switch to a Terminal with Better Support: Use a terminal like Windows Terminal, PowerShell, or a third-party terminal emulator (like ConEmu or Hyper) that supports a wider range of Unicode characters, including emojis.
Fallback for Unsupported Characters: Implement a fallback mechanism to switch to simpler characters if emojis are not displayed as expected.
Here's how you can implement a fallback for your icons:
Certainly! Here is the full code with fallbacks for icons to ensure they display correctly in environments like the Windows Command Prompt:
javascript
User
HMM, IT SEEMS YOU DIDNT SEND ME THE FULL CODE (MAKE SURE YOU DON'T TOUCH ANYTHING!)
Assistant
Certainly! Here is the full code with the changes for using fallback icons for environments like the Windows Command Prompt, without altering any other logic:
Error: listen EADDRINUSE: address already in use :::443
at Server.setupListenHandle [as _listen2] (node:net:1904:16)
at listenInCluster (node:net:1961:12)
at Server.listen (node:net:2063:7)
at initializeServer (C:\Users\Administrator\Desktop\HTTP-PRO.js:534:10)
at C:\Users\Administrator\Desktop\HTTP-PRO.js:82:3
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1940:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 443
}
Assistant
The error message you're encountering, EADDRINUSE, indicates that the network address or port you are trying to use (in this case, port 443) is already in use by another process on your system. This is why your server is unable to start.
Here are several steps you can take to resolve this issue:
Step 1: Check for Running Processes Using Port 443
First, you should identify the process that is currently using port 443:
Windows CMD or PowerShell:
Open Command Prompt or PowerShell as an administrator.
Run the following command to list active connections and listening ports:
bash
netstat -ano | findstr :443
This will list any processes using port 443 along with their Process ID (PID).
Identify the Process:
Use Task Manager (Ctrl + Shift + Esc) to find the process associated with the PID.
Alternatively, use the command:
bash
tasklist | findstr <PID>
Replace <PID> with the actual PID you found in the previous command output.
Terminate the Process (if appropriate):
If it’s safe to close the application that’s using port 443, terminate the process through Task Manager or by using:
bash
taskkill /PID <PID> /F
Replace <PID> with the PID of the process.
Step 2: Change Your Server Port
If stopping the existing process isn't feasible (for instance, if another essential service is using port 443 or if you lack permissions), you can start your server on a different port.
Change the Port in Your Script:
Modify your script to use a different port, for example, 8443:
javascript
const port = process.argv[2] || 8443; // Changed from 443 to 8443
Adjust URL Access:
Remember to access your service using the new port. E.g., https://localhost:8443.
Step 3: Restart Your Node.js Script
After changing the port or stopping the occupying process, restart your script:
bash
node your-script.js
By following these steps, you should be able to resolve the EADDRINUSE error and successfully run your server on the desired port.
Not yet included in a published release.
console.log(chalk.green(`[DEVELOPER MODE]`, req.headers['user-agent']));
console.log(chalk.green(`Request received from IP: ${normalizedIp}`));
if (isSynFlood(ip)) {
console.log(chalk.red(`SYN flood detected from IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'SYN Flood');
// Use the underlying socket to destroy the connection
req.socket.end(); // Gracefully end the connection
req.socket.destroy(); // Forcefully close the connection, ignoring any pending data or errors
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');
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');
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');
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');
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');
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'
};
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 userAgent = req.headers['user-agent'];
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
normalizedIpbeta2port∣
code
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 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;
};
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');
return true;
}
}
return false;
};
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
// console.log(chalk.blue(ADMIN DASHBOARD IS ONLINE));
});
// Start Server Function
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 trustedIPs = ['127.0.0.1'];
const port = process.argv[2] || 443;
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;
// Set keepAliveTimeout, which sets how long a connection should remain open in milliseconds.
server.keepAliveTimeout = 60 * 1000; // Keep alive for 60 seconds
// Set the headers timeout slightly longer than keepAliveTimeout to accommodate requests that arrive just before the keep alive timeout
server.headersTimeout = 65 * 1000; // 65 seconds
code
console.log(chalk.green(`[DEVELOPER MODE]`, req.headers['user-agent']));
console.log(chalk.green(`Request received from IP: ${normalizedIp}`));
if (isSynFlood(ip)) {
console.log(chalk.red(`SYN flood detected from IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'SYN Flood');
// Use the underlying socket to destroy the connection
req.socket.end(); // Gracefully end the connection
req.socket.destroy(); // Forcefully close the connection, ignoring any pending data or errors
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');
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');
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');
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');
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');
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'
};
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 userAgent = req.headers['user-agent'];
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
if (req.url === "/growtopia/server_data.php") {
if (req.method !== 'POST' || hostHeader !== 'www.growtopia1.com' || !allowedUserAgents.includes(userAgent)) {
console.log(chalk.red(Mata mata : ${req.url}));
res.statusCode = 403;
res.end(`
server|normalizedIpport∣{Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
server.listen(port, () => {
console.log(chalk.green(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}));
code
// Rate Limiting
if (isUdpRateLimited(normalizedIp)) {
console.log(chalk.red(`UDP Rate limit exceeded for IP: ${normalizedIp}`));
logBlockedIP(normalizedIp, 'UDP');
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');
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');
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);
const shutdown = () => {
console.log('Shutting down the server...');
code
// Stop the server from accepting new connections
server.close(() => {
console.log('HTTP server closed.');
// Close the UDP server
udpServer.close(() => {
console.log('UDP server closed.');
// Exit the process
process.exit(0);
});
});
// Ensure shutdown if connections remain
setTimeout(() => {
console.error('Forced shutdown due to open connections.');
process.exit(1); // exit with error code if connections remain
}, 5000).unref();
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');
const exec = require('child_process').exec;
const { spawn } = require('child_process');
const dgram = require('dgram');
const basicAuth = require('express-basic-auth');
const compression = require('compression');
const osu = require('os-utils');
const { netstat } = require('node-os-utils');
const gradient = require('gradient-string');
// Logging enhancements
const infoIcons = ['ℹ️', '🔍', '📘'];
const errorIcons = ['❌', '🔥', '🚫'];
const successIcons = ['✅', '🎉', '👌'];
const getRandomIcon = (icons) => icons[Math.floor(Math.random() * icons.length)];
const logInfo = (message) => {
const icon = getRandomIcon(infoIcons);
console.log(chalk.blueBright(`${icon}`) + ' ' + gradient.vice(message));
};
const logError = (message) => {
const icon = getRandomIcon(errorIcons);
console.log(chalk.redBright(`${icon}`) + ' ' + gradient.passion(message));
};
const logSuccess = (message) => {
const icon = getRandomIcon(successIcons);
console.log(chalk.greenBright(`${icon}`) + ' ' + gradient.instagram(message));
};
// Create an Agent instance configured for keep-alive
const keepAliveAgent = new https.Agent({
keepAlive: true,
maxSockets: 100, // Control the number of sockets to handle concurrent connections
maxFreeSockets: 10, // Control the number of free sockets to keep open
});
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; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected
// 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'];
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(compression());
configApp.set('view engine', 'ejs');
configApp.use(bodyParser.urlencoded({ extended: true }));
configApp.use(express.static('public'));
// Additional functions remain the same...
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
logInfo(`ADMIN DASHBOARD IS ONLINE on port ${CONFIG_PORT}`);
});
// Start Server Function
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 trustedIPs = ['127.0.0.1'];
const port = process.argv[2] || 443;
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 = 60 * 1000;
server.headersTimeout = 65 * 1000;
logInfo(`Request received from IP: ${normalizedIp}, User-Agent: ${req.headers['user-agent']}`);
// Original function logic here...
});
server.listen(port, () => {
logSuccess(`Server is running on port ${port}`);
});
// UDP server set up logic...
console.log('');
console.log(chalk.magenta('========================================================'));
logInfo(`- CONFIGURATION LOADS : `);
logInfo(`[🎮] Login URL : ${config.loginurl}`);
logInfo(`[🔰] HTTP Port ${port}`);
logInfo(`[@] ANTI-SCAN SERVER DATA PHP STATUS : ENABLED [PENTEST-SECURITY]`);
logInfo(`[@] OPERATION SYSTEM : WINDOWS`);
logInfo(`[@] HTTP KING VERSION : 4.0.0`);
logSuccess(`[🥇] SUBSCRIPTION : PREMIUM`);
logSuccess(`[✅] LAST HTTP UPDATE : 21/10/2024`);
logInfo(`[💻] ADMIN DASHBOARD : http://localhost:${CONFIG_PORT}/config`);
console.log(chalk.magenta('========================================================'));
console.log('');
logSuccess(`
::: ::: ::::::::::: :::: ::: :::::::: ::: ::: :::::::: ::::::::
:+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+#+#+#+#+ +#+ +#+ +:+ +#+ :#: +#+ +:+ +#++: +#++:
#+# +#+ +#+ +#+ +#+#+# +#+ +#+# +#+ +#+ +#+ +#+
#+# #+# #+# #+# #+#+# #+# #+# #+#+# #+# #+# #+# #+#
#+# ############### ### #### ######## ### ######## ########`);
}
startServer();
Explanation:
Custom Logging Functions: Functions logInfo, logError, and logSuccess are defined to use random icons and gradients.
Usage of Log Functions: Replace various console.log statements in your code with these custom log functions to maintain consistent and visually appealing logging.
By using these functions, your log messages will include random icons and gradients, making the logs more readable and visually distinct.
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');
const exec = require('child_process').exec;
const { spawn } = require('child_process');
const dgram = require('dgram');
const basicAuth = require('express-basic-auth');
const compression = require('compression');
const osu = require('os-utils');
const { netstat } = require('node-os-utils');
// Load gradient-string dynamically
let gradient;
import('gradient-string').then((module) => {
gradient = module.default;
initializeServer();
}).catch(err => {
console.error('Failed to load gradient-string module:', err);
});
// Logging enhancements
const infoIcons = ['ℹ️', '🔍', '📘'];
const errorIcons = ['❌', '🔥', '🚫'];
const successIcons = ['✅', '🎉', '👌'];
const getRandomIcon = (icons) => icons[Math.floor(Math.random() * icons.length)];
const logInfo = (message) => {
const icon = getRandomIcon(infoIcons);
console.log(chalk.blueBright(`${icon}`) + ' ' + gradient.vice(message));
};
const logError = (message) => {
const icon = getRandomIcon(errorIcons);
console.log(chalk.redBright(`${icon}`) + ' ' + gradient.passion(message));
};
const logSuccess = (message) => {
const icon = getRandomIcon(successIcons);
console.log(chalk.greenBright(`${icon}`) + ' ' + gradient.instagram(message));
};
// Create an Agent instance configured for keep-alive
const keepAliveAgent = new https.Agent({
keepAlive: true,
maxSockets: 100,
maxFreeSockets: 10,
});
axios.defaults.httpsAgent = keepAliveAgent;
let logMessages = [];
// Override console.log to capture logs in-memory
const originalLog = console.log;
console.log = (...args) => {
originalLog(...args);
logMessages.push(args.join(' '));
};
// Start Server Function encapsulated to wait for gradient-string import
function initializeServer() {
// Define your server logic and setup here
const configApp = express();
const CONFIG_PORT = 6969;
// Middleware
configApp.use(compression());
configApp.set('view engine', 'ejs');
configApp.use(bodyParser.urlencoded({ extended: true }));
configApp.use(express.static('public'));
// All other setup code goes here...
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
logInfo(`ADMIN DASHBOARD IS ONLINE on port ${CONFIG_PORT}`);
});
// Add the HTTPS Server Logic with logging here...
}
// These parts of the code can remain the same
Key Changes:
Dynamic Import: I used import() for loading gradient-string. This ESM import is asynchronous, so you need to handle it properly.
Initialization Function: The initializeServer function wraps your server setup code to start only after gradient-string is loaded.
Gradient Usage: Since you wait for the module to be loaded, ensure any code using gradient is inside the initializeServer function or called after import() completes.
This way, the package can be used seamlessly in the rest of your CommonJS 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');
const exec = require('child_process').exec;
const { spawn } = require('child_process');
const dgram = require('dgram');
const basicAuth = require('express-basic-auth');
const compression = require('compression');
const osu = require('os-utils');
const { netstat } = require('node-os-utils');
// Load gradient-string dynamically
let gradient;
import('gradient-string').then((module) => {
gradient = module.default;
// Start your server once the module is loaded
initializeServer();
}).catch(err => {
console.error('Failed to load gradient-string module:', err);
});
// Logging enhancements
const infoIcons = ['ℹ️', '🔍', '📘'];
const errorIcons = ['❌', '🔥', '🚫'];
const successIcons = ['✅', '🎉', '👌'];
const getRandomIcon = (icons) => icons[Math.floor(Math.random() * icons.length)];
const logInfo = (message) => {
if (gradient) {
const icon = getRandomIcon(infoIcons);
console.log(chalk.blueBright(`${icon}`) + ' ' + gradient.vice(message));
} else {
console.log(chalk.blueBright(`[INFO]`) + ' ' + message);
}
};
const logError = (message) => {
if (gradient) {
const icon = getRandomIcon(errorIcons);
console.log(chalk.redBright(`${icon}`) + ' ' + gradient.passion(message));
} else {
console.log(chalk.redBright(`[ERROR]`) + ' ' + message);
}
};
const logSuccess = (message) => {
if (gradient) {
const icon = getRandomIcon(successIcons);
console.log(chalk.greenBright(`${icon}`) + ' ' + gradient.instagram(message));
} else {
console.log(chalk.greenBright(`[SUCCESS]`) + ' ' + message);
}
};
// Initialize server logic when gradient is ready
function initializeServer() {
const configApp = express();
const CONFIG_PORT = 6969;
// Middleware
configApp.use(compression());
configApp.set('view engine', 'ejs');
configApp.use(bodyParser.urlencoded({ extended: true }));
configApp.use(express.static('public'));
// All other setup code...
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
logInfo(`ADMIN DASHBOARD IS ONLINE on port ${CONFIG_PORT}`);
});
// Proceed to add your main server logic here...
}
// Other parts of your code remain the same
Key Adjustments:
Deferred Initialization: The server and any functionality using gradient are set up inside the initializeServer() function to ensure gradient is imported.
Conditional Logging: Each logging function checks if gradient is loaded. If not, it falls back to simple colored logs using Chalk only.
Initialization Check: Ensures no usage of gradient properties occurs before it's loaded.
This setup ensures that your server functionality and logging capabilities are correctly initialized only after the module loading completes.
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');
const exec = require('child_process').exec;
const { spawn } = require('child_process');
const dgram = require('dgram');
const basicAuth = require('express-basic-auth');
const compression = require('compression');
const osu = require('os-utils');
const { netstat } = require('node-os-utils');
// Load gradient-string dynamically
let gradient;
import('gradient-string').then((module) => {
gradient = module.default;
// Start your server once the module is loaded
initializeServer();
}).catch(err => {
console.error('Failed to load gradient-string module:', err);
});
// Logging enhancements
const infoIcons = ['ℹ️', '🔍', '📘'];
const errorIcons = ['❌', '🔥', '🚫'];
const successIcons = ['✅', '🎉', '👌'];
const getRandomIcon = (icons) => icons[Math.floor(Math.random() * icons.length)];
const logInfo = (message) => {
if (gradient) {
const icon = getRandomIcon(infoIcons);
console.log(chalk.blueBright(`${icon}`) + ' ' + gradient.vice(message));
} else {
console.log(chalk.blueBright(`[INFO]`) + ' ' + message);
}
};
const logError = (message) => {
if (gradient) {
const icon = getRandomIcon(errorIcons);
console.log(chalk.redBright(`${icon}`) + ' ' + gradient.passion(message));
} else {
console.log(chalk.redBright(`[ERROR]`) + ' ' + message);
}
};
const logSuccess = (message) => {
if (gradient) {
const icon = getRandomIcon(successIcons);
console.log(chalk.greenBright(`${icon}`) + ' ' + gradient.instagram(message));
} else {
console.log(chalk.greenBright(`[SUCCESS]`) + ' ' + message);
}
};
// Create an Agent instance configured for keep-alive
const keepAliveAgent = new https.Agent({
keepAlive: true,
maxSockets: 100,
maxFreeSockets: 10,
});
axios.defaults.httpsAgent = keepAliveAgent;
let logMessages = [];
// Override console.log to capture logs in-memory
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;
// 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'];
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(compression());
configApp.set('view engine', 'ejs');
configApp.use(bodyParser.urlencoded({ extended: true }));
configApp.use(express.static('public'));
// 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') => {
fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => {
if (err) logError('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;
};
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) {
logError('Error reading main.json:', err);
return {};
}
};
// Function to write configuration
const writeConfig = (config) => {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
logSuccess('Configuration updated.');
console.clear();
} catch (err) {
logError('Error writing to Config:', err);
}
};
// Middleware Authentication
configApp.use('/config', basicAuth({
users: { [config.username]: config.password },
challenge: true,
realm: 'Config Area'
}));
configApp.get('/config', (req, res) => {
const config = readConfig();
res.render('config', { config });
});
configApp.post('/config', (req, res) => {
const { ip, port, loginurl, cdn, username, password } = req.body;
const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password };
writeConfig(newConfig);
res.redirect('/config');
});
configApp.get('/logs', (req, res) => {
res.json({
logs: logMessages
});
});
// Endpoint to gather system stats
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) {
logError('Error fetching system statistics:', error);
res.json({ error: 'Unable to fetch system statistics' });
}
});
configApp.post('/restart', (req, res) => {
logInfo('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) {
logError(`SYN flood detected from IP: ${ip}`);
logBlockedIP(ip, 'SYN Flood');
return true;
}
}
return false;
};
// Use this function to ensure server starts after gradient is loaded
function initializeServer() {
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;
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 = 60 * 1000;
server.headersTimeout = 65 * 1000;
logInfo(`Request received from IP: ${normalizedIp}, User-Agent: ${req.headers['user-agent']}`);
if (isSynFlood(ip)) {
logError(`SYN flood detected from IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'SYN Flood');
req.socket.end();
req.socket.destroy();
return;
}
if (!rateLimit[normalizedIp]) {
rateLimit[normalizedIp] = { count: 1, timestamp: Date.now() };
} else {
const currentTime = Date.now();
const timePassed = currentTime - rateLimit[normalizedIp].timestamp;
if (timePassed > BLOCK_TIME_MS) {
rateLimit[normalizedIp] = { count: 1, timestamp: currentTime };
} else {
rateLimit[normalizedIp].count++;
}
if (rateLimit[normalizedIp].count > MAX_REQUESTS_PER_MINUTE) {
logError(`Rate limit exceeded for IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP');
res.statusCode = 429;
res.end('Too many requests. Your connection is being throttled.');
return;
}
}
// DNS attack protection
if (isSuspiciousDNSRequest(normalizedIp, req.url)) {
logError(`DNS DDoS detected from IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP-DNS');
res.statusCode = 403;
res.end('Forbidden: DNS DDoS attack detected.');
return;
}
const requestBytes = Buffer.byteLength(req.url);
if (isNetworkUsageLimited(normalizedIp, requestBytes)) {
logError(`Network usage limit exceeded for IP: ${normalizedIp} (TCP)`);
logBlockedIP(normalizedIp, 'TCP-NETWORK');
res.statusCode = 429;
res.end('Too many requests. Your connection is being throttled.');
return;
}
if (!trustedIPs.includes(normalizedIp) && isCloudOrServerIp(normalizedIp)) {
logError(`Blocking cloud/server IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP-Cloud');
res.statusCode = 403;
res.end('Forbidden: Access from cloud/server IP is blocked.');
return;
}
if (isBlockedGeoIp(normalizedIp)) {
logError(`Blocking access from IP: ${normalizedIp} (GeoIP Block)`);
logBlockedIP(normalizedIp, 'TCP-GeoIP');
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;
logInfo(`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 userAgent = req.headers['user-agent'];
if (req.url === "/growtopia/server_data.php") {
if (req.method !== 'POST' || hostHeader !== 'www.growtopia1.com' || !allowedUserAgents.includes(userAgent)) {
logError(`Blocked unauthorized access attempt: ${req.url}`);
res.statusCode = 403;
res.end(`
server|${normalizedIp}
port|${Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
loginurl|http-king.com
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|69-SCP-PROTECTION
RTENDMARKERBS1001
`);
return;
}
res.write(packet, function (err) {
if (err) logError(err);
});
res.end();
}
else if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) {
if (req.method !== 'GET' || !allowedUserAgents.includes(userAgent)) {
logError(`Blocked: Invalid method or User-Agent for ${req.url}`);
res.statusCode = 403;
res.end('Forbidden');
return;
}
logInfo(`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);
}
});
});
} else {
logError(`🛡 [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP-Other');
res.statusCode = 403;
res.end('Forbidden');
}
});
server.listen(port, () => {
logSuccess(`Server is running on port ${port}`);
});
const udpServer = dgram.createSocket('udp4');
const UDP_PORT = 53;
udpServer.on('error', (err) => {
logError(`UDP server error: ${err.stack}`);
udpServer.close();
});
udpServer.on('message', (msg, rinfo) => {
const ip = rinfo.address;
const normalizedIp = normalizeIp(ip);
logInfo(`UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`);
if (isUdpRateLimited(normalizedIp)) {
logError(`UDP Rate limit exceeded for IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'UDP');
return;
}
if (isBlockedGeoIp(normalizedIp)) {
logError(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`);
logBlockedIP(normalizedIp, 'UDP-GeoIP');
return;
}
const messageBytes = msg.length;
if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
logError(`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) {
logError(`Error forwarding UDP request: ${error}`);
externalClient.close();
}
});
externalClient.on('message', (response) => {
udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => {
if (err) {
logError(`Error sending UDP response: ${err}`);
}
externalClient.close();
});
});
externalClient.on('error', (err) => {
logError(`External DNS client error: ${err}`);
externalClient.close();
});
externalClient.setTimeout(5000, () => {
logError(`External DNS request timed out for IP: ${normalizedIp}`);
externalClient.close();
});
});
udpServer.on('listening', () => {
const address = udpServer.address();
logSuccess(`UDP Server listening on ${address.address}:${address.port}`);
});
udpServer.bind(UDP_PORT);
const shutdown = () => {
logInfo('Shutting down the server...');
server.close(() => {
logInfo('HTTP server closed.');
udpServer.close(() => {
logInfo('UDP server closed.');
process.exit(0);
});
});
setTimeout(() => {
logError('Forced shutdown due to open connections.');
process.exit(1);
}, 5000).unref();
};
configApp.post('/shutdown', (req, res) => {
res.send('Server is shutting down...');
shutdown();
});
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
console.log('');
console.log(chalk.magenta('========================================================'));
logInfo('CONFIGURATION LOADS:');
logInfo(`[🎮] Login URL: ${config.loginurl}`);
logInfo(`[🔰] HTTP Port: ${port}`);
logInfo(`[@] ANTI-SCAN SERVER DATA PHP STATUS: ENABLED [PENTEST-SECURITY]`);
logInfo(`[@] OPERATION SYSTEM: WINDOWS`);
logInfo(`[@] HTTP KING VERSION: 4.0.0`);
logSuccess(`[🥇] SUBSCRIPTION: PREMIUM`);
logSuccess(`[✅] LAST HTTP UPDATE: 21/10/2024`);
logInfo(`[💻] ADMIN DASHBOARD: http://localhost:${CONFIG_PORT}/config`);
console.log(chalk.magenta('========================================================'));
console.log('');
logSuccess(`
::: ::: ::::::::::: :::: ::: :::::::: ::: ::: :::::::: ::::::::
:+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +#+ +#+ +#+ +#++: +#++: +#++: +#+ +#+ +#+
#+# +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ #+#+ +#+ +#+
#+##+ #+# ########## ### ######## ### ########## ########`);
}
Key Adjustments:
Dynamic Import for gradient-string: The gradient-string module is imported dynamically using import(). This ensures the script works with modules that no longer support require() in CommonJS.
Server Initialization: The initializeServer function is only called after gradient-string is successfully imported, ensuring that gradients are available when necessary.
Conditional Logging: Each logging helper function (info, error, success) checks if gradient is initialized to prevent errors and provides a fallback using only Chalk colors.
Windows Compatibility: Ensure all paths and configurations are compatible with Windows. Since there wasn’t anything specifically different for Windows in the original code, this should work out of the box on a Windows machine.
By following this version of the script, you'll have a server that initializes properly, logs with style, and handles error cases gracefully, suiting a Windows environment.
Explanation:
useFallbackIcons(): This helper function checks if the script is running under Command Prompt on Windows, and returns true if that's the case.
Fallback Icons: If the script detects it's running in an environment that likely doesn't support emojis (like CMD), it uses simpler ASCII symbols or text-based alternatives.
Symbols vs. Emojis: The code selects between emojis and plain text based on the environment, ensuring compatibility without losing functionality.
By implementing these changes, your logs will be consistently formatted and readable across different environments, regardless of their Unicode support.
Dynamic Import for gradient-string: The module is imported asynchronously using import(), and the server starts afterwards.
Icon Fallbacks: If running in the Windows CMD, uses simple ASCII symbols instead of emojis to ensure visibility.
Logging Functions: Enhanced with gradient checks and use appropriate symbols or emojis based on terminal support.
By using this script, you should be able to ensure consistent icon display across various environments, including those with limited Unicode support like the Windows Command Prompt.
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 { spawn } = require('child_process');
const dgram = require('dgram'); // Importing dgram for UDP handling
const basicAuth = require('express-basic-auth');
const compression = require('compression');
const osu = require('os-utils');
const { netstat } = require('node-os-utils'); // Import netstat from node-os-utils
const mem = require('node-os-utils').mem;
// Create an Agent instance configured for keep-alive
const keepAliveAgent = new https.Agent({
keepAlive: true,
maxSockets: 100, // Control the number of sockets to handle concurrent connections
maxFreeSockets: 10, // Control the number of free sockets to keep open
});
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; // Max allowed per minute
const SYN_BLOCK_TIME_MS = 60000; // Block time if SYN flood detected
// 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(compression());
configApp.set('view engine', 'ejs');
configApp.use(bodyParser.urlencoded({ extended: true }));
configApp.use(express.static('public'));
// Dynamic Import for gradient-string
let gradient;
import('gradient-string').then((module) => {
gradient = module.default;
initializeServer();
}).catch(err => {
console.error('Failed to load gradient-string module:', err);
});
// Determine if fallback icons should be used
const useFallbackIcons = () => {
return process.platform === 'win32' && process.env.ComSpec && process.env.ComSpec.includes('cmd.exe');
};
// Icon sets with fallbacks for CMD
const infoIcons = useFallbackIcons() ? ['[i]', '[?]', '[*]'] : ['ℹ️', '🔍', '📘'];
const errorIcons = useFallbackIcons() ? ['[X]', '[!]', '[FLAG]'] : ['❌', '🔥', '🚫'];
const successIcons = useFallbackIcons() ? ['[✓]', '[+]', '[OK]'] : ['✅', '🎉', '👌'];
const getRandomIcon = (icons) => icons[Math.floor(Math.random() * icons.length)];
const logInfo = (message) => {
const icon = getRandomIcon(infoIcons);
console.log(chalk.blueBright(`${icon}`) + ' ' + (gradient ? gradient.vice(message) : message));
};
const logError = (message) => {
const icon = getRandomIcon(errorIcons);
console.log(chalk.redBright(`${icon}`) + ' ' + (gradient ? gradient.passion(message) : message));
};
const logSuccess = (message) => {
const icon = getRandomIcon(successIcons);
console.log(chalk.greenBright(`${icon}`) + ' ' + (gradient ? gradient.instagram(message) : message));
};
// 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') => {
fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => {
if (err) logError('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;
};
const configPath = path.resolve(__dirname, './config/main.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
// Fungsi untuk membaca konfigurasi
const readConfig = () => {
try {
const data = fs.readFileSync(configPath, 'utf8');
return JSON.parse(data);
} catch (err) {
logError('Error membaca main.json:', err);
return {};
}
};
// Fungsi untuk menulis konfigurasi
const writeConfig = (config) => {
try {
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
logSuccess('Configuration updated.');
console.clear();
} catch (err) {
logError('Error writing to Config:', err);
}
};
// Middleware Autentikasi
configApp.use('/config', basicAuth({
users: { [config.username]: config.password }, // Use credentials from config
challenge: true,
realm: 'Config Area'
}));
// Route untuk menampilkan form konfigurasi
configApp.get('/config', (req, res) => {
const config = readConfig();
res.render('config', { config });
});
// Route untuk memproses perubahan konfigurasi
configApp.post('/config', (req, res) => {
const { ip, port, loginurl, cdn, username, password } = req.body;
const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password };
writeConfig(newConfig);
res.redirect('/config');
});
configApp.get('/logs', (req, res) => {
res.json({
logs: logMessages
});
});
// Endpoint to gather system stats
configApp.get('/stats', async (req, res) => {
try {
// Use os-utils or os for retrieving CPU and memory information
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) {
logError('Error fetching system statistics:', error);
res.json({ error: 'Unable to fetch system statistics' });
}
});
configApp.post('/restart', (req, res) => {
logInfo('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) {
logError(`SYN flood detected from IP: ${ip}`);
logBlockedIP(ip, 'SYN Flood');
return true;
}
}
return false;
};
// Start UI Server
configApp.listen(CONFIG_PORT, () => {
logInfo(`ADMIN DASHBOARD IS ONLINE on port ${CONFIG_PORT}`);
});
// Start Server Function
const initializeServer = 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 trustedIPs = ['127.0.0.1'];
const port = process.argv[2] || 443;
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;
// Set keepAliveTimeout, which sets how long a connection should remain open in milliseconds.
server.keepAliveTimeout = 60 * 1000; // Keep alive for 60 seconds
// Set the headers timeout slightly longer than keepAliveTimeout to accommodate requests that arrive just before the keep alive timeout
server.headersTimeout = 65 * 1000; // 65 seconds
logInfo(`Request received from IP: ${normalizedIp}, User-Agent: ${req.headers['user-agent']}`);
if (isSynFlood(ip)) {
logError(`SYN flood detected from IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'SYN Flood');
// Use the underlying socket to destroy the connection
req.socket.end(); // Gracefully end the connection
req.socket.destroy(); // Forcefully close the connection, ignoring any pending data or errors
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) {
logError(`Rate limit exceeded for IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP');
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)) {
logError(`DNS DDoS detected from IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP-DNS');
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)) {
logError(`Network usage limit exceeded for IP: ${normalizedIp} (TCP)`);
logBlockedIP(normalizedIp, 'TCP-NETWORK');
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)) {
logError(`Blocking cloud/server IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP-Cloud');
res.statusCode = 403;
res.end('Forbidden: Access from cloud/server IP is blocked.');
return;
}
// Check for GeoIP block
if (isBlockedGeoIp(normalizedIp)) {
logError(`Blocking access from IP: ${normalizedIp} (GeoIP Block)`);
logBlockedIP(normalizedIp, 'TCP-GeoIP');
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;
logInfo(`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 userAgent = req.headers['user-agent'];
// Handle /growtopia/server_data.php - Only POST and allowed User-Agents
if (req.url === "/growtopia/server_data.php") {
if (req.method !== 'POST' || hostHeader !== 'www.growtopia1.com' || !allowedUserAgents.includes(userAgent)) {
logError(`Blocked unauthorized access attempt: ${req.url}`);
res.statusCode = 403;
res.end(`
server|${normalizedIp}
port|${Math.floor(Date.now() / 69)}
type|1
#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.
loginurl|http-king.com
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|69-SCP-PROTECTION
RTENDMARKERBS1001
`);
return;
}
res.write(packet, function (err) {
if (err) logError(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' || !allowedUserAgents.includes(userAgent)) {
logError(`Blocked: Invalid method or User-Agent for ${req.url}`);
res.statusCode = 403;
res.end('Forbidden');
return;
}
logInfo(`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 {
logError(`🛡 [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'TCP-Other');
res.statusCode = 403;
res.end('Forbidden');
}
});
server.listen(port, () => {
logSuccess(`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) => {
logError(`UDP server error: ${err.stack}`);
udpServer.close();
});
udpServer.on('message', (msg, rinfo) => {
const ip = rinfo.address;
const normalizedIp = normalizeIp(ip);
logInfo(`UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`);
// Rate Limiting
if (isUdpRateLimited(normalizedIp)) {
logError(`UDP Rate limit exceeded for IP: ${normalizedIp}`);
logBlockedIP(normalizedIp, 'UDP');
return; // Drop the packet silently or send a response indicating rate limiting
}
// GeoIP Blocking
if (isBlockedGeoIp(normalizedIp)) {
logError(`Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`);
logBlockedIP(normalizedIp, 'UDP-GeoIP');
return; // Drop the packet silently or send a forbidden response
}
// Network Usage Limiting for UDP
const messageBytes = msg.length;
if (isNetworkUsageLimited(normalizedIp, messageBytes)) {
logError(`Network usage limit exceeded for IP: ${normalizedIp} (UDP)`);
logBlockedIP(normalizedIp, 'UDP-NETWORK');
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) {
logError(`Error forwarding UDP request: ${error}`);
externalClient.close();
}
});
externalClient.on('message', (response) => {
udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => {
if (err) {
logError(`Error sending UDP response: ${err}`);
}
externalClient.close();
});
});
// Optional: Implement timeouts to prevent hanging
externalClient.on('error', (err) => {
logError(`External DNS client error: ${err}`);
externalClient.close();
});
// Set a timeout for the external DNS response
externalClient.setTimeout(5000, () => { // 5 seconds timeout
logError(`External DNS request timed out for IP: ${normalizedIp}`);
externalClient.close();
});
});
udpServer.on('listening', () => {
const address = udpServer.address();
logSuccess(`UDP Server listening on ${address.address}:${address.port}`);
});
udpServer.bind(UDP_PORT);
const shutdown = () => {
logInfo('Shutting down the server...');
// Stop the server from accepting new connections
server.close(() => {
logInfo('HTTP server closed.');
// Close the UDP server
udpServer.close(() => {
logInfo('UDP server closed.');
// Exit the process
process.exit(0);
});
});
// Ensure shutdown if connections remain
setTimeout(() => {
logError('Forced shutdown due to open connections.');
process.exit(1); // exit with error code if connections remain
}, 5000).unref();
};
configApp.post('/shutdown', (req, res) => {
res.send('Server is shutting down...');
shutdown();
});
// Capture abort signals
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
console.log('');
console.log(chalk.magenta('========================================================'));
logInfo('CONFIGURATION LOADS:');
logInfo(`[🎮] Login URL: ${config.loginurl}`);
logInfo(`[🔰] HTTP Port: ${port}`);
logInfo(`[@] ANTI-SCAN SERVER DATA PHP STATUS: ENABLED [PENTEST-SECURITY]`);
logInfo(`[@] OPERATION SYSTEM: WINDOWS`);
logInfo(`[@] HTTP KING VERSION: 4.0.0`);
logSuccess(`[🥇] SUBSCRIPTION: PREMIUM`);
logSuccess(`[✅] LAST HTTP UPDATE: 21/10/2024`);
logInfo(`[💻] ADMIN DASHBOARD: http://localhost:${CONFIG_PORT}/config`);
console.log(chalk.magenta('========================================================'));
console.log('');
logSuccess(`
::: ::: ::::::::::: :::: ::: :::::::: ::: ::: :::::::: ::::::::
:+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +#+ +#+ +#+ +#++: +#++: +#++: +#+ +#+ +#+
#+# +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ #+#+ +#+ +#+
#+##+ #+# ########## ### ######## ### ########## ########`);
}
initializeServer();
Key Additions:
Dynamic Import for gradient-string: The gradient-string import is asynchronous, and the server initialization waits for it to complete.
Icon Fallbacks: Based on whether you're using CMD on Windows, ASCII symbols are used if emojis aren't supported.
This setup ensures proper operation and logging display in Windows environments such as Command Prompt, while maintaining the original functionality of your script.