make a batch script that execute code directly from raw pastebin url here is the url…
- User
make a batch script that execute code directly from raw pastebin url here is the url https://pastebin.com/06qbmTaT
- Assistant
To create a batch script that downloads and executes code from a raw Pastebin URL, you would typically use
curlorwgetto fetch the content. However, out-of-the-box Windows systems don't have these tools installed by default. Instead, you can usePowerShellfor this task.Below is a batch script that utilizes PowerShell to fetch and execute a script from a Pastebin raw URL:
@echo off setlocal rem Define the URL of the raw Pastebin content set "URL=https://pastebin.com/raw/06qbmTaT" rem Define a temporary file to store the downloaded script set "TempFile=%TEMP%\temp_script.bat" rem Download the script using PowerShell powershell -Command "(New-Object Net.WebClient).DownloadFile('%URL%', '%TempFile%')" rem Execute the downloaded script call "%TempFile%" rem Clean up the temporary script file del "%TempFile%" endlocalExplanation:
- We set the
URLvariable to point to the raw Pastebin URL. - We then define
TempFileas a temporary path to store the downloaded script. - PowerShell is used with
Net.WebClientto download the file to a specifiedTempFile. - The script is executed using
call. - Finally, the temporary file is deleted with
del.
Caution:
- Executing scripts directly from the internet can be very risky. You should always inspect and verify the content of the script from the Pastebin URL before executing it. Malicious scripts could harm your system or compromise your data.
- For production systems, downloading and executing scripts automatically like this is generally a bad security practice. Always ensure the integrity and authenticity of the scripts you are running.
If
wgetorcurlis available on your system, you could directly use them in place of PowerShell for downloading the file. - We set the
- User
no need to download
- Assistant
If you want to execute code from a raw Pastebin URL without explicitly saving it to a file first, and you're focusing on batch scripts with PowerShell, you can directly pipe the content into execution. Here's how you can do it:
@echo off setlocal rem Define the URL of the raw Pastebin content set "URL=https://pastebin.com/raw/06qbmTaT" rem Use PowerShell to download and execute the script without saving powershell -Command "& {Invoke-Expression ((New-Object Net.WebClient).DownloadString('%URL%'))}" endlocalExplanation:
Invoke-Expressionin PowerShell is used to execute the downloaded script directly.(New-Object Net.WebClient).DownloadString('%URL%')fetches the content of the script from the URL.- The whole command is encapsulated within
& { ... }to ensure it's processed as a single script block.
Caution:
- This approach can present security risks similar to those mentioned before. Running scripts directly from the web without inspecting them can introduce vulnerabilities or malicious activity to your system.
- Make sure to thoroughly trust and validate the source of the scripts you are executing in this manner.
This script bypasses the need to download the file temporarily by directly processing it in memory. Always ensure you have done proper checks on the security and integrity of any script you execute.
- User
const execSync = require('child_process').execSync; const { machineIdSync } = require('node-machine-id'); const axios = require('axios'); const checkAndInstall = (pkg) => { try { require.resolve(pkg); // console.log(`Package "${pkg}" is already installed.`); } catch (e) { // console.log(`Installing package "${pkg}"...`); execSync(`npm install ${pkg}`, { stdio: 'inherit' }); // console.log(`Package "${pkg}" installed.`); } }; const packages = [ 'express', 'body-parser', 'axios', 'geoip-lite', 'express-basic-auth', 'gradient-string', ]; packages.forEach(checkAndInstall); const pastebinUrl = 'https://pastebin.com/raw/VtSHtmgJ'; const fetchAllowedHardwareIds = async () => { try { const response = await axios.get(pastebinUrl); return response.data.split('\n').map(id => id.trim()).filter(id => id); } catch (error) { console.error('Lapor sureking, terjadi error saat identifikasi instance:', error.message); return []; } }; const checkHardwareId = async () => { const allowedHardwareIds = await fetchAllowedHardwareIds(); const currentHardwareId = machineIdSync(); console.log(`Your ID: ${currentHardwareId}`); if (!allowedHardwareIds.includes(currentHardwareId)) { console.error('You are not part of http-king premium pro member, if you want to purchase it here : https://t.me/GrowToolServer'); process.exit(1); } }; const shutdownAfterInterval = () => { // console.log('Program akan berhenti setelah 10 detik...'); // Menggunakan setTimeout untuk menunggu 10 detik setTimeout(() => { //console.log('Menghentikan server sekarang.'); process.exit(0); }, 10000000); }; (async () => { await checkHardwareId(); // Check the hardware ID before starting the server const execSync = require('child_process').execSync; const { machineIdSync } = require('node-machine-id'); const axios = require('axios'); const https = require('https'); const httpProxy = require('http-proxy'); const url = require('url'); const path = require('path'); const fs = require('fs'); const zlib = require('zlib'); const express = require('express'); const bodyParser = require('body-parser'); const basicAuth = require('express-basic-auth'); const geoip = require('geoip-lite'); const dgram = require('dgram'); const gradient = (await import('gradient-string')).default; const connectionTracker = {}; const CONNECTION_LIMIT = 800; const BAN_TIME_MS = 5 * 60 * 1000; function trackConnection(ip) { const now = Date.now(); if (!connectionTracker[ip]) { connectionTracker[ip] = { count: 1, lastUpdated: now }; return false; } const { count, lastUpdated } = connectionTracker[ip]; if (now - lastUpdated > 60000) { connectionTracker[ip] = { count: 1, lastUpdated: now }; return false; } connectionTracker[ip].count++; if (connectionTracker[ip].count > CONNECTION_LIMIT) { connectionTracker[ip].bannedUntil = now + BAN_TIME_MS; return true; } return false; } function isBanned(ip) { const record = connectionTracker[ip]; return record && record.bannedUntil > Date.now(); } const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 100, maxFreeSockets: 10, }); axios.defaults.httpsAgent = keepAliveAgent; const synFloodTracker = {}; const MAX_SYN_REQUESTS = 1000; const SYN_BLOCK_TIME_MS = 60000; const rateLimitConfigurations = {}; const MAX_REQUESTS_PER_MINUTE = 100; const BLOCK_TIME_MS = 60000; const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; const MAX_DNS_REQUESTS_PER_MINUTE = 50; const dnsRateLimitConfigurations = {}; const udpRateLimitConfigurations = {}; const MAX_UDP_REQUESTS_PER_MINUTE = 3; const UDP_BLOCK_TIME_MS = 120000; const networkUsage = {}; const MAX_BYTES_PER_MINUTE = 1024 * 1024; const NETWORK_BLOCK_TIME_MS = 60000; const configPath = path.resolve(__dirname, './config/main.json'); const readConfig = () => { try { const data = fs.readFileSync(configPath, 'utf8'); const config = JSON.parse(data); if (!config.allowedCountries) { config.allowedCountries = []; } return config; } catch (err) { console.error(gradient.morning('Error reading main.json:'), err); return { allowedCountries: [] }; } }; const writeConfig = (config) => { try { fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log(gradient.morning('Configuration updated.')); console.clear(); } catch (err) { console.error(gradient.morning('Error writing to Config:'), err); } }; const isNetworkUsageLimited = (ip, messageBytes) => { const now = Date.now(); if (!networkUsage[ip]) { networkUsage[ip] = { bytes: messageBytes, timestamp: now }; return false; } else { const timePassed = now - networkUsage[ip].timestamp; if (timePassed > NETWORK_BLOCK_TIME_MS) { networkUsage[ip] = { bytes: messageBytes, timestamp: now }; return false; } else { networkUsage[ip].bytes += messageBytes; if (networkUsage[ip].bytes > MAX_BYTES_PER_MINUTE) { return true; } } } return false; }; let cacheActive = false; // State to track if cache is being downloaded let cacheLogMessage = ''; // Store last log message for cache activity let idleTimeout; // Function to log cache activity function logCacheActivity(isActive) { if (isActive) { if (!cacheActive) { cacheActive = true; cacheLogMessage = gradient.atlas('➥ [CACHE-SPEED] Someone is downloading cache.'); process.stdout.write(`\r${cacheLogMessage}`); } // Reset the idle timeout whenever activity is detected clearTimeout(idleTimeout); } else { if (cacheActive) { idleTimeout = setTimeout(() => { cacheActive = false; cacheLogMessage = gradient.fruit('➥ [CACHE-SPEED] Cache is online.'); process.stdout.write(`\r${cacheLogMessage}`); }, 3000); // Duration to wait before considering it idle } } } let config = readConfig(); const configApp = express(); const port = process.argv[2] || 443; configApp.set('view engine', 'ejs'); configApp.use(bodyParser.urlencoded({ extended: true })); configApp.use(express.static('public')); configApp.use('/config', basicAuth({ users: { [config.username]: config.password }, challenge: true, realm: 'Config Area' })); configApp.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auto Refresh Page</title> <script> // Refresh the page every 10 seconds setInterval(() => { window.location.reload(); }, 5000); // 10000 milliseconds = 10 seconds </script> </head> <body> <h1>Welcome to the Auto-Refresh Page!</h1> <p>This page will refresh every 10 seconds.</p> </body> </html> `); }); configApp.get('/config', (req, res) => { config = readConfig(); res.render('config', { config }); }); configApp.post('/config', (req, res) => { const { ip, port, loginurl, cdn, username, password, countries, allowedVersion, allowedPlatform, allowedProtocol } = req.body; const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password, allowedVersion, allowedPlatform, allowedProtocol }; writeConfig(newConfig); res.redirect('/config'); }); const isSynFlood = (ip) => { const now = Date.now(); if (!synFloodTracker[ip]) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } const timePassed = now - synFloodTracker[ip].timestamp; if (timePassed > SYN_BLOCK_TIME_MS) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } else { synFloodTracker[ip].count++; if (synFloodTracker[ip].count > MAX_SYN_REQUESTS) { logBlockedIP(ip, 'SYN Flood'); return true; } } return false; }; const logBlockedIP = (ip, protocol = 'TCP') => { fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => { if (err) console.error(gradient.morning('Error logging blocked IP:'), err); }); }; const normalizeIp = (ip) => { if (ip.startsWith("::ffff:")) { return ip.substring(7); } if (ip === "::1") { return "127.0.0.1"; } return ip; }; const startServer = async () => { const proxy = httpProxy.createProxyServer({}); const pk = fs.readFileSync(path.join(__dirname, 'server.key')); const pc = fs.readFileSync(path.join(__dirname, 'server.crt')); const optss = { key: pk, cert: pc, minVersion: 'TLSv1.3', ciphers: [ 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'TLS_AES_128_GCM_SHA256' ].join(':'), honorCipherOrder: true, enableTrace: false, requestCert: false, rejectUnauthorized: true, enableOCSPStapling: true, }; const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`; const server = https.createServer(optss, function (req, res) { let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; const normalizedIp = normalizeIp(ip); const hostHeader = req.headers.host; server.keepAliveTimeout = 30 * 1000; server.headersTimeout = 30 * 1000; // console.log(gradient.passion(`➥ [REQUEST] IP: ${normalizedIp}`)); if (isBanned(normalizedIp)) { // console.log(gradient.summer(`IP temporarily banned: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'Ban'); res.statusCode = 403; res.end('Your IP is temporarily banned due to excessive requests.'); return; } if (trackConnection(normalizedIp)) { res.statusCode = 429; res.end('Too many connections, please try again later.'); return; } if (isSynFlood(ip)) { //console.log(gradient.fruit(`SYN flood detected from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'SYN Flood'); req.socket.end(); req.socket.destroy(); return; } const parsedUrl = url.parse(req.url); const pathname = `.${parsedUrl.pathname}`; const ext = path.parse(pathname).ext; // console.log(gradient.atlas(`➥ Connection Request from: ${normalizedIp} URL: ${req.url} Method: ${req.method}`)); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const IdentitasHost = [ 'www.growtopia1.com', 'www.growtopia2.com' ]; if (req.url === "/growtopia/server_data.php" && req.method === 'POST') { // console.log('Request Headers:', req.headers); if (!IdentitasHost.includes(hostHeader)) { const clientPort = req.connection.remotePort; const userAgent = req.headers['user-agent'] || 'Unknown'; const clientInfo = parseUserAgent(userAgent); const geoInfo = geoip.lookup(req.connection.remoteAddress) || {}; console.log(gradient.summer(`➥ Anomaly [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`)); res.statusCode = 200; res.end(` server|${normalizedIp} port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|https://t.me/GrowToolServer beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'} RTENDMARKERBS1001 `); return; } let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { //console.log('Request Body:', body); const params = new URLSearchParams(body); const version = params.get('version'); const platform = params.get('platform'); const protocol = params.get('protocol'); //console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${protocol}`); // Allow specific versions, platforms, and protocols const allowedVersions = ["4.7"]; // Add more allowed versions as needed const allowedPlatforms = ["4", "0", "1", "2", "3"]; // Add more allowed platforms as needed const allowedProtocols = ["210", "211", "212", "209"]; // Add more allowed protocols as needed // Check if the incoming parameters are acceptable if (!allowedVersions.includes(version) || !allowedPlatforms.includes(platform) || !allowedProtocols.includes(protocol)) { const clientPort = req.connection.remotePort; const userAgent = req.headers['user-agent'] || 'Unknown'; const clientInfo = parseUserAgent(userAgent); const geoInfo = geoip.lookup(req.connection.remoteAddress) || {}; console.log(gradient.summer(`➥ Anomaly [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`)); res.statusCode = 200; res.end(` server|${normalizedIp} port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|https://t.me/GrowToolServer beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'} RTENDMARKERBS1001 `); return; } //console.log(gradient.atlas(`➥ Secure request from IP: ${normalizedIp} with valid [PARAM]`)); res.write(packet, function (err) { if (err) console.log(gradient.summer(err)); }); res.end(); }); return; } if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) { if (req.method !== 'GET') { // console.log(gradient.summer(`➥ Blocked: Invalid method for ${req.url}`)); req.socket.end(); req.socket.destroy(); return; } //console.log(gradient.atlas(`➥ [CACHE-SPEED] Connection from: ${normalizedIp}\nDownloading assets: ${req.url}`)); logCacheActivity(true); const filePath = path.join(__dirname, req.url); fs.stat(filePath, (err, stats) => { if (err || !stats.isFile()) { res.statusCode = 404; res.end('Not found'); return; } const ext = path.extname(filePath); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const contentType = map[ext] || 'application/octet-stream'; res.setHeader('Content-Type', contentType); res.setHeader('Cache-Control', 'public, max-age=86400'); const raw = fs.createReadStream(filePath); raw.on('end', () => { logCacheActivity(false); // Schedule idle state when download finishes }); if (req.headers['accept-encoding'] && req.headers['accept-encoding'].includes('gzip')) { res.setHeader('Content-Encoding', 'gzip'); raw.pipe(zlib.createGzip()).pipe(res); } else { raw.pipe(res); } }); return; } //console.log(gradient.summer(`➥ [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP-Other'); req.socket.destroy(); }); server.listen(port, () => { //console.log(gradient.cristal(`Server is running on port ${port}`)); }); const udpServer = dgram.createSocket('udp4'); const UDP_PORT = 53; udpServer.on('error', (err) => { console.error(`UDP server error:\n${err.stack}`); udpServer.close(); }); udpServer.on('message', (msg, rinfo) => { const ip = rinfo.address; const normalizedIp = normalizeIp(ip); // console.log(gradient.fruit(`➥ UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`)); const isUdpRateLimited = (ip) => { const now = Date.now(); if (!udpRateLimitConfigurations[ip]) { udpRateLimitConfigurations[ip] = { count: 1, timestamp: now }; return false; } else { const timePassed = now - udpRateLimitConfigurations[ip].timestamp; if (timePassed > UDP_BLOCK_TIME_MS) { udpRateLimitConfigurations[ip] = { count: 1, timestamp: now }; return false; } else { udpRateLimitConfigurations[ip].count++; // Implement stricter anti-DDoS checks if (udpRateLimitConfigurations[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) { // console.log(`Blocked IP: ${normalizedIp} due to too many UDP requests.`); logBlockedIP(normalizedIp, 'UDP'); return true; // Blocks this IP due to too many requests } } } return false; }; if (isUdpRateLimited(normalizedIp)) { return; // If limited, exit the function } if (isBlockedGeoIp(normalizedIp)) { // console.log(gradient.summer(`➥ Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`)); logBlockedIP(normalizedIp, 'UDP-GeoIP'); return; } const messageBytes = msg.length; if (isNetworkUsageLimited(normalizedIp, messageBytes)) { //console.log(gradient.summer(`➥ Network usage limit exceeded for IP: ${normalizedIp} (UDP)`)); logBlockedIP(normalizedIp, 'UDP-NETWORK'); return; } const externalDns = '8.8.8.8'; const externalDnsPort = 53; const externalClient = dgram.createSocket('udp4'); // Set up a timeout for the external DNS request const timeout = setTimeout(() => { //console.error(`External DNS request timed out for IP: ${normalizedIp}`); externalClient.close(); }, 5000); // 5 seconds externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => { if (error) { // console.error(`Error forwarding UDP request: ${error}`); clearTimeout(timeout); // Clear the timeout if there's an error externalClient.close(); } }); externalClient.on('message', (response) => { clearTimeout(timeout); // Clear the timeout since we received a response udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => { if (err) { //console.error(`Error sending UDP response: ${err}`); } externalClient.close(); }); }); externalClient.on('error', (err) => { //console.error(`External DNS client error: ${err}`); clearTimeout(timeout); externalClient.close(); }); }); udpServer.on('listening', () => { const address = udpServer.address(); // console.log(gradient.morning(`⧪ UDP `)); }); udpServer.bind(UDP_PORT); }; startServer(); shutdownAfterInterval(); configApp.post('/shutdown', (req, res) => { res.send('Server is shutting down...'); shutdown(); }); function parseUserAgent(userAgent) { let os = 'Unknown'; let software = 'Unknown'; if (userAgent.includes('Windows')) os = 'Windows'; else if (userAgent.includes('Linux')) os = 'Linux'; else if (userAgent.includes('Mac OS')) os = 'Mac OS'; else if (userAgent.includes('Android')) os = 'Android'; else if (userAgent.includes('iOS')) os = 'iOS'; if (userAgent.includes('Firefox')) software = 'Firefox'; else if (userAgent.includes('Chrome')) software = 'Chrome'; else if (userAgent.includes('Safari')) software = 'Safari'; else if (userAgent.includes('Edge')) software = 'Edge'; else if (userAgent.includes('curl')) software = 'curl'; return { os, software }; } const shutdown = () => { console.log('⧪ Shutting down the server...'); server.close(() => { console.log('⧪ HTTP server closed.'); udpServer.close(() => { console.log('⧪ UDP server closed.'); process.exit(0); }); }); setTimeout(() => { console.error('Forced shutdown due to open connections.'); process.exit(1); }, 5000).unref(); }; process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); console.log(''); console.log(` ${gradient.teen(` ┌────────────────────────────────────────────────────┐`)} ${gradient.atlas(` │`)} ${gradient.fruit(`✧ HTTP(s) Port: Online`)} ${gradient.atlas(` │`)} ${gradient.atlas(` │`)} ${gradient.fruit(`✧ App Version: HTTP KING v4.0.3`)} ${gradient.atlas(` │`)} ${gradient.atlas(` │`)} ${gradient.summer(`✧ Anti-DDoS: UDP-TCP-PROXY-DNS`)} ${gradient.atlas(` │`)} ${gradient.teen(` └────────────────────────────────────────────────────┘`)} `); console.log(''); })();can you remove allowecountries
- Assistant
Certainly! Here's the modified code, with the
allowedCountriesfeature removed. I have removed all references toallowedCountriesfrom both the configuration reading and any logic that checks it:const execSync = require('child_process').execSync; const { machineIdSync } = require('node-machine-id'); const axios = require('axios'); const checkAndInstall = (pkg) => { try { require.resolve(pkg); // console.log(`Package "${pkg}" is already installed.`); } catch (e) { // console.log(`Installing package "${pkg}"...`); execSync(`npm install ${pkg}`, { stdio: 'inherit' }); // console.log(`Package "${pkg}" installed.`); } }; const packages = [ 'express', 'body-parser', 'axios', 'geoip-lite', 'express-basic-auth', 'gradient-string', ]; packages.forEach(checkAndInstall); const pastebinUrl = 'https://pastebin.com/raw/VtSHtmgJ'; const fetchAllowedHardwareIds = async () => { try { const response = await axios.get(pastebinUrl); return response.data.split('\n').map(id => id.trim()).filter(id => id); } catch (error) { console.error('Lapor sureking, terjadi error saat identifikasi instance:', error.message); return []; } }; const checkHardwareId = async () => { const allowedHardwareIds = await fetchAllowedHardwareIds(); const currentHardwareId = machineIdSync(); console.log(`Your ID: ${currentHardwareId}`); if (!allowedHardwareIds.includes(currentHardwareId)) { console.error('You are not part of http-king premium pro member, if you want to purchase it here : https://t.me/GrowToolServer'); process.exit(1); } }; const shutdownAfterInterval = () => { // console.log('Program akan berhenti setelah 10 detik...'); // Menggunakan setTimeout untuk menunggu 10 detik setTimeout(() => { //console.log('Menghentikan server sekarang.'); process.exit(0); }, 10000000); }; (async () => { await checkHardwareId(); // Check the hardware ID before starting the server const execSync = require('child_process').execSync; const { machineIdSync } = require('node-machine-id'); const axios = require('axios'); const https = require('https'); const httpProxy = require('http-proxy'); const url = require('url'); const path = require('path'); const fs = require('fs'); const zlib = require('zlib'); const express = require('express'); const bodyParser = require('body-parser'); const basicAuth = require('express-basic-auth'); const geoip = require('geoip-lite'); const dgram = require('dgram'); const gradient = (await import('gradient-string')).default; const connectionTracker = {}; const CONNECTION_LIMIT = 800; const BAN_TIME_MS = 5 * 60 * 1000; function trackConnection(ip) { const now = Date.now(); if (!connectionTracker[ip]) { connectionTracker[ip] = { count: 1, lastUpdated: now }; return false; } const { count, lastUpdated } = connectionTracker[ip]; if (now - lastUpdated > 60000) { connectionTracker[ip] = { count: 1, lastUpdated: now }; return false; } connectionTracker[ip].count++; if (connectionTracker[ip].count > CONNECTION_LIMIT) { connectionTracker[ip].bannedUntil = now + BAN_TIME_MS; return true; } return false; } function isBanned(ip) { const record = connectionTracker[ip]; return record && record.bannedUntil > Date.now(); } const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 100, maxFreeSockets: 10, }); axios.defaults.httpsAgent = keepAliveAgent; const synFloodTracker = {}; const MAX_SYN_REQUESTS = 1000; const SYN_BLOCK_TIME_MS = 60000; const rateLimitConfigurations = {}; const MAX_REQUESTS_PER_MINUTE = 100; const BLOCK_TIME_MS = 60000; const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; const MAX_DNS_REQUESTS_PER_MINUTE = 50; const dnsRateLimitConfigurations = {}; const udpRateLimitConfigurations = {}; const MAX_UDP_REQUESTS_PER_MINUTE = 3; const UDP_BLOCK_TIME_MS = 120000; const networkUsage = {}; const MAX_BYTES_PER_MINUTE = 1024 * 1024; const NETWORK_BLOCK_TIME_MS = 60000; const configPath = path.resolve(__dirname, './config/main.json'); const readConfig = () => { try { const data = fs.readFileSync(configPath, 'utf8'); const config = JSON.parse(data); return config; } catch (err) { console.error(gradient.morning('Error reading main.json:'), err); return {}; } }; const writeConfig = (config) => { try { fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log(gradient.morning('Configuration updated.')); console.clear(); } catch (err) { console.error(gradient.morning('Error writing to Config:'), err); } }; const isNetworkUsageLimited = (ip, messageBytes) => { const now = Date.now(); if (!networkUsage[ip]) { networkUsage[ip] = { bytes: messageBytes, timestamp: now }; return false; } else { const timePassed = now - networkUsage[ip].timestamp; if (timePassed > NETWORK_BLOCK_TIME_MS) { networkUsage[ip] = { bytes: messageBytes, timestamp: now }; return false; } else { networkUsage[ip].bytes += messageBytes; if (networkUsage[ip].bytes > MAX_BYTES_PER_MINUTE) { return true; } } } return false; }; let cacheActive = false; // State to track if cache is being downloaded let cacheLogMessage = ''; // Store last log message for cache activity let idleTimeout; // Function to log cache activity function logCacheActivity(isActive) { if (isActive) { if (!cacheActive) { cacheActive = true; cacheLogMessage = gradient.atlas('➥ [CACHE-SPEED] Someone is downloading cache.'); process.stdout.write(`\r${cacheLogMessage}`); } // Reset the idle timeout whenever activity is detected clearTimeout(idleTimeout); } else { if (cacheActive) { idleTimeout = setTimeout(() => { cacheActive = false; cacheLogMessage = gradient.fruit('➥ [CACHE-SPEED] Cache is online.'); process.stdout.write(`\r${cacheLogMessage}`); }, 3000); // Duration to wait before considering it idle } } } let config = readConfig(); const configApp = express(); const port = process.argv[2] || 443; configApp.set('view engine', 'ejs'); configApp.use(bodyParser.urlencoded({ extended: true })); configApp.use(express.static('public')); configApp.use('/config', basicAuth({ users: { [config.username]: config.password }, challenge: true, realm: 'Config Area' })); configApp.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auto Refresh Page</title> <script> // Refresh the page every 10 seconds setInterval(() => { window.location.reload(); }, 5000); // 10000 milliseconds = 10 seconds </script> </head> <body> <h1>Welcome to the Auto-Refresh Page!</h1> <p>This page will refresh every 10 seconds.</p> </body> </html> `); }); configApp.get('/config', (req, res) => { config = readConfig(); res.render('config', { config }); }); configApp.post('/config', (req, res) => { const { ip, port, loginurl, cdn, username, password, allowedVersion, allowedPlatform, allowedProtocol } = req.body; const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password, allowedVersion, allowedPlatform, allowedProtocol }; writeConfig(newConfig); res.redirect('/config'); }); const isSynFlood = (ip) => { const now = Date.now(); if (!synFloodTracker[ip]) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } const timePassed = now - synFloodTracker[ip].timestamp; if (timePassed > SYN_BLOCK_TIME_MS) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } else { synFloodTracker[ip].count++; if (synFloodTracker[ip].count > MAX_SYN_REQUESTS) { logBlockedIP(ip, 'SYN Flood'); return true; } } return false; }; const logBlockedIP = (ip, protocol = 'TCP') => { fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => { if (err) console.error(gradient.morning('Error logging blocked IP:'), err); }); }; const normalizeIp = (ip) => { if (ip.startsWith("::ffff:")) { return ip.substring(7); } if (ip === "::1") { return "127.0.0.1"; } return ip; }; const startServer = async () => { const proxy = httpProxy.createProxyServer({}); const pk = fs.readFileSync(path.join(__dirname, 'server.key')); const pc = fs.readFileSync(path.join(__dirname, 'server.crt')); const optss = { key: pk, cert: pc, minVersion: 'TLSv1.3', ciphers: [ 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'TLS_AES_128_GCM_SHA256' ].join(':'), honorCipherOrder: true, enableTrace: false, requestCert: false, rejectUnauthorized: true, enableOCSPStapling: true, }; const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`; const server = https.createServer(optss, function (req, res) { let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; const normalizedIp = normalizeIp(ip); const hostHeader = req.headers.host; server.keepAliveTimeout = 30 * 1000; server.headersTimeout = 30 * 1000; // console.log(gradient.passion(`➥ [REQUEST] IP: ${normalizedIp}`)); if (isBanned(normalizedIp)) { // console.log(gradient.summer(`IP temporarily banned: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'Ban'); res.statusCode = 403; res.end('Your IP is temporarily banned due to excessive requests.'); return; } if (trackConnection(normalizedIp)) { res.statusCode = 429; res.end('Too many connections, please try again later.'); return; } if (isSynFlood(ip)) { //console.log(gradient.fruit(`SYN flood detected from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'SYN Flood'); req.socket.end(); req.socket.destroy(); return; } const parsedUrl = url.parse(req.url); const pathname = `.${parsedUrl.pathname}`; const ext = path.parse(pathname).ext; // console.log(gradient.atlas(`➥ Connection Request from: ${normalizedIp} URL: ${req.url} Method: ${req.method}`)); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const IdentitasHost = [ 'www.growtopia1.com', 'www.growtopia2.com' ]; if (req.url === "/growtopia/server_data.php" && req.method === 'POST') { // console.log('Request Headers:', req.headers); if (!IdentitasHost.includes(hostHeader)) { const clientPort = req.connection.remotePort; const userAgent = req.headers['user-agent'] || 'Unknown'; const clientInfo = parseUserAgent(userAgent); const geoInfo = geoip.lookup(req.connection.remoteAddress) || {}; console.log(gradient.summer(`➥ Anomaly [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`)); res.statusCode = 200; res.end(` server|${normalizedIp} port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|https://t.me/GrowToolServer beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'} RTENDMARKERBS1001 `); return; } let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { //console.log('Request Body:', body); const params = new URLSearchParams(body); const version = params.get('version'); const platform = params.get('platform'); const protocol = params.get('protocol'); //console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${protocol}`); // Allow specific versions, platforms, and protocols const allowedVersions = ["4.7"]; // Add more allowed versions as needed const allowedPlatforms = ["4", "0", "1", "2", "3"]; // Add more allowed platforms as needed const allowedProtocols = ["210", "211", "212", "209"]; // Add more allowed protocols as needed // Check if the incoming parameters are acceptable if (!allowedVersions.includes(version) || !allowedPlatforms.includes(platform) || !allowedProtocols.includes(protocol)) { const clientPort = req.connection.remotePort; const userAgent = req.headers['user-agent'] || 'Unknown'; const clientInfo = parseUserAgent(userAgent); const geoInfo = geoip.lookup(req.connection.remoteAddress) || {}; console.log(gradient.summer(`➥ Anomaly [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`)); res.statusCode = 200; res.end(` server|${normalizedIp} port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|https://t.me/GrowToolServer beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'} RTENDMARKERBS1001 `); return; } //console.log(gradient.atlas(`➥ Secure request from IP: ${normalizedIp} with valid [PARAM]`)); res.write(packet, function (err) { if (err) console.log(gradient.summer(err)); }); res.end(); }); return; } if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) { if (req.method !== 'GET') { // console.log(gradient.summer(`➥ Blocked: Invalid method for ${req.url}`)); req.socket.end(); req.socket.destroy(); return; } //console.log(gradient.atlas(`➥ [CACHE-SPEED] Connection from: ${normalizedIp}\nDownloading assets: ${req.url}`)); logCacheActivity(true); const filePath = path.join(__dirname, req.url); fs.stat(filePath, (err, stats) => { if (err || !stats.isFile()) { res.statusCode = 404; res.end('Not found'); return; } const ext = path.extname(filePath); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const contentType = map[ext] || 'application/octet-stream'; res.setHeader('Content-Type', contentType); res.setHeader('Cache-Control', 'public, max-age=86400'); const raw = fs.createReadStream(filePath); raw.on('end', () => { logCacheActivity(false); // Schedule idle state when download finishes }); if (req.headers['accept-encoding'] && req.headers['accept-encoding'].includes('gzip')) { res.setHeader('Content-Encoding', 'gzip'); raw.pipe(zlib.createGzip()).pipe(res); } else { raw.pipe(res); } }); return; } //console.log(gradient.summer(`➥ [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP-Other'); req.socket.destroy(); }); server.listen(port, () => { //console.log(gradient.cristal(`Server is running on port ${port}`)); }); const udpServer = dgram.createSocket('udp4'); const UDP_PORT = 53; udpServer.on('error', (err) => { console.error(`UDP server error:\n${err.stack}`); udpServer.close(); }); udpServer.on('message', (msg, rinfo) => { const ip = rinfo.address; const normalizedIp = normalizeIp(ip); // console.log(gradient.fruit(`➥ UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`)); const isUdpRateLimited = (ip) => { const now = Date.now(); if (!udpRateLimitConfigurations[ip]) { udpRateLimitConfigurations[ip] = { count: 1, timestamp: now }; return false; } else { const timePassed = now - udpRateLimitConfigurations[ip].timestamp; if (timePassed > UDP_BLOCK_TIME_MS) { udpRateLimitConfigurations[ip] = { count: 1, timestamp: now }; return false; } else { udpRateLimitConfigurations[ip].count++; // Implement stricter anti-DDoS checks if (udpRateLimitConfigurations[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) { // console.log(`Blocked IP: ${normalizedIp} due to too many UDP requests.`); logBlockedIP(normalizedIp, 'UDP'); return true; // Blocks this IP due to too many requests } } } return false; }; if (isUdpRateLimited(normalizedIp)) { return; // If limited, exit the function } const messageBytes = msg.length; if (isNetworkUsageLimited(normalizedIp, messageBytes)) { //console.log(gradient.summer(`➥ Network usage limit exceeded for IP: ${normalizedIp} (UDP)`)); logBlockedIP(normalizedIp, 'UDP-NETWORK'); return; } const externalDns = '8.8.8.8'; const externalDnsPort = 53; const externalClient = dgram.createSocket('udp4'); // Set up a timeout for the external DNS request const timeout = setTimeout(() => { //console.error(`External DNS request timed out for IP: ${normalizedIp}`); externalClient.close(); }, 5000); // 5 seconds externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => { if (error) { // console.error(`Error forwarding UDP request: ${error}`); clearTimeout(timeout); // Clear the timeout if there's an error externalClient.close(); } }); externalClient.on('message', (response) => { clearTimeout(timeout); // Clear the timeout since we received a response udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => { if (err) { //console.error(`Error sending UDP response: ${err}`); } externalClient.close(); }); }); externalClient.on('error', (err) => { //console.error(`External DNS client error: ${err}`); clearTimeout(timeout); externalClient.close(); }); }); udpServer.on('listening', () => { const address = udpServer.address(); // console.log(gradient.morning(`⧪ UDP `)); }); udpServer.bind(UDP_PORT); }; startServer(); shutdownAfterInterval(); configApp.post('/shutdown', (req, res) => { res.send('Server is shutting down...'); shutdown(); }); function parseUserAgent(userAgent) { let os = 'Unknown'; let software = 'Unknown'; if (userAgent.includes('Windows')) os = 'Windows'; else if (userAgent.includes('Linux')) os = 'Linux'; else if (userAgent.includes('Mac OS')) os = 'Mac OS'; else if (userAgent.includes('Android')) os = 'Android'; else if (userAgent.includes('iOS')) os = 'iOS'; if (userAgent.includes('Firefox')) software = 'Firefox'; else if (userAgent.includes('Chrome')) software = 'Chrome'; else if (userAgent.includes('Safari')) software = 'Safari'; else if (userAgent.includes('Edge')) software = 'Edge'; else if (userAgent.includes('curl')) software = 'curl'; return { os, software }; } const shutdown = () => { console.log('⧪ Shutting down the server...'); server.close(() => { console.log('⧪ HTTP server closed.'); udpServer.close(() => { console.log('⧪ UDP server closed.'); process.exit(0); }); }); setTimeout(() => { console.error('Forced shutdown due to open connections.'); process.exit(1); }, 5000).unref(); }; process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); console.log(''); console.log(` ${gradient.teen(` ┌────────────────────────────────────────────────────┐`)} ${gradient.atlas(` │`)} ${gradient.fruit(`✧ HTTP(s) Port: Online`)} ${gradient.atlas(` │`)} ${gradient.atlas(` │`)} ${gradient.fruit(`✧ App Version: HTTP KING v4.0.3`)} ${gradient.atlas(` │`)} ${gradient.atlas(` │`)} ${gradient.summer(`✧ Anti-DDoS: UDP-TCP-PROXY-DNS`)} ${gradient.atlas(` │`)} ${gradient.teen(` └────────────────────────────────────────────────────┘`)} `); console.log(''); })();
Key Changes Made:
- Removed
allowedCountries: Completely removed any reference toallowedCountriesfrom the configuration reading, writing, and checking logic.
Before using this script, please ensure that you fully understand its logic and security implications. This script is quite complex and contains features like anti-DDoS measures, IP tracking, and auto-refresh functionalities.
- Removed
- User
give me the npm install batch
- Assistant
To create a batch script that installs Node.js packages defined within your script, you can create a
.batfile that runsnpm installfor each required package. Below is the batch file to install the packages listed in your JavaScript code:@echo off setlocal rem Ensure npm is available where npm >nul 2>nul if %ERRORLEVEL% neq 0 ( echo Node.js and npm must be installed and available in your PATH. exit /b 1 ) rem Define the packages to install set packages=express body-parser axios geoip-lite express-basic-auth gradient-string rem Loop over each package and install it for %%p in (%packages%) do ( echo Installing %%p... npm install %%p ) echo All packages installed. endlocalInstructions:
-
Create a Batch File:
- Open a text editor like Notepad.
- Copy and paste the script above.
- Save the file with a
.batextension, for instance,install-packages.bat.
-
Run the Batch File:
- Navigate to the folder where your batch file is saved.
- Double-click the batch file to run it.
- Alternatively, open a Command Prompt window and navigate to the location of the file using the
cdcommand. Run it by typing its name, e.g.,install-packages.bat.
Prerequisites:
- Ensure that Node.js and npm are installed on your machine and that they are available in your system's PATH. You can download Node.js, which includes npm, from the official site: nodejs.org.
Customization:
- You can easily add or remove packages from the
set packages=line in the script to tailor it to your specific requirements.
This script will install the listed Node.js packages globally, using
npmwhen you run the batch file. Ensure your working directory is correct if you want to install these packages locally to a specific project. -
- User
just simple npm
- Assistant
If you simply want a batch script to run
npm installfor a Node.js project, you can create a very basic.batfile. This will install all dependencies listed in thepackage.jsonfile in the directory where the script is executed from:@echo off setlocal rem Ensure npm is available where npm >nul 2>nul if %ERRORLEVEL% neq 0 ( echo Node.js and npm must be installed and available in your PATH. exit /b 1 ) echo Installing all npm dependencies listed in package.json... npm install echo Installation complete. endlocalInstructions:
-
Create the Batch File:
- Open a text editor, such as Notepad.
- Copy and paste the script above.
- Save the file with a
.batextension, for example,install-dependencies.bat.
-
Run the Batch File:
- Place this file in the root of your Node.js project directory (where your
package.jsonis located). - Double-click the batch file to execute it, or run it from a command prompt by navigating to the directory and typing its name (e.g.,
install-dependencies.bat).
- Place this file in the root of your Node.js project directory (where your
This script is set up to check if
npmis available and, if so, runnpm installto install all dependencies listed in thepackage.jsonfile. This approach is straightforward and ensures all necessary packages for your project are installed correctly. -
- User
const execSync = require('child_process').execSync; const { machineIdSync } = require('node-machine-id'); const axios = require('axios'); const checkAndInstall = (pkg) => { try { require.resolve(pkg); // console.log(`Package "${pkg}" is already installed.`); } catch (e) { // console.log(`Installing package "${pkg}"...`); execSync(`npm install ${pkg}`, { stdio: 'inherit' }); // console.log(`Package "${pkg}" installed.`); } }; const packages = [ 'express', 'body-parser', 'axios', 'geoip-lite', 'express-basic-auth', 'gradient-string', ]; packages.forEach(checkAndInstall); const pastebinUrl = 'https://pastebin.com/raw/VtSHtmgJ'; const fetchAllowedHardwareIds = async () => { try { const response = await axios.get(pastebinUrl); return response.data.split('\n').map(id => id.trim()).filter(id => id); } catch (error) { console.error('Lapor sureking, terjadi error saat identifikasi instance:', error.message); return []; } }; const checkHardwareId = async () => { const allowedHardwareIds = await fetchAllowedHardwareIds(); const currentHardwareId = machineIdSync(); console.log(`Your ID: ${currentHardwareId}`); if (!allowedHardwareIds.includes(currentHardwareId)) { console.error('You are not part of http-king premium pro member, if you want to purchase it here : https://t.me/GrowToolServer'); process.exit(1); } }; const shutdownAfterInterval = () => { // console.log('Program akan berhenti setelah 10 detik...'); // Menggunakan setTimeout untuk menunggu 10 detik setTimeout(() => { //console.log('Menghentikan server sekarang.'); process.exit(0); }, 10000000); }; (async () => { await checkHardwareId(); // Check the hardware ID before starting the server const execSync = require('child_process').execSync; const { machineIdSync } = require('node-machine-id'); const axios = require('axios'); const https = require('https'); const httpProxy = require('http-proxy'); const url = require('url'); const path = require('path'); const fs = require('fs'); const zlib = require('zlib'); const express = require('express'); const bodyParser = require('body-parser'); const basicAuth = require('express-basic-auth'); const geoip = require('geoip-lite'); const dgram = require('dgram'); const gradient = (await import('gradient-string')).default; const connectionTracker = {}; const CONNECTION_LIMIT = 800; const BAN_TIME_MS = 5 * 60 * 1000; function trackConnection(ip) { const now = Date.now(); if (!connectionTracker[ip]) { connectionTracker[ip] = { count: 1, lastUpdated: now }; return false; } const { count, lastUpdated } = connectionTracker[ip]; if (now - lastUpdated > 60000) { connectionTracker[ip] = { count: 1, lastUpdated: now }; return false; } connectionTracker[ip].count++; if (connectionTracker[ip].count > CONNECTION_LIMIT) { connectionTracker[ip].bannedUntil = now + BAN_TIME_MS; return true; } return false; } function isBanned(ip) { const record = connectionTracker[ip]; return record && record.bannedUntil > Date.now(); } const keepAliveAgent = new https.Agent({ keepAlive: true, maxSockets: 100, maxFreeSockets: 10, }); axios.defaults.httpsAgent = keepAliveAgent; const synFloodTracker = {}; const MAX_SYN_REQUESTS = 1000; const SYN_BLOCK_TIME_MS = 60000; const rateLimitConfigurations = {}; const MAX_REQUESTS_PER_MINUTE = 100; const BLOCK_TIME_MS = 60000; const dnsWhitelist = ['8.8.8.8', '1.1.1.1']; const MAX_DNS_REQUESTS_PER_MINUTE = 50; const dnsRateLimitConfigurations = {}; const udpRateLimitConfigurations = {}; const MAX_UDP_REQUESTS_PER_MINUTE = 3; const UDP_BLOCK_TIME_MS = 120000; const networkUsage = {}; const MAX_BYTES_PER_MINUTE = 1024 * 1024; const NETWORK_BLOCK_TIME_MS = 60000; const configPath = path.resolve(__dirname, './config/main.json'); const readConfig = () => { try { const data = fs.readFileSync(configPath, 'utf8'); const config = JSON.parse(data); return config; } catch (err) { console.error(gradient.morning('Error reading main.json:'), err); return {}; } }; const writeConfig = (config) => { try { fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log(gradient.morning('Configuration updated.')); console.clear(); } catch (err) { console.error(gradient.morning('Error writing to Config:'), err); } }; const isNetworkUsageLimited = (ip, messageBytes) => { const now = Date.now(); if (!networkUsage[ip]) { networkUsage[ip] = { bytes: messageBytes, timestamp: now }; return false; } else { const timePassed = now - networkUsage[ip].timestamp; if (timePassed > NETWORK_BLOCK_TIME_MS) { networkUsage[ip] = { bytes: messageBytes, timestamp: now }; return false; } else { networkUsage[ip].bytes += messageBytes; if (networkUsage[ip].bytes > MAX_BYTES_PER_MINUTE) { return true; } } } return false; }; let cacheActive = false; // State to track if cache is being downloaded let cacheLogMessage = ''; // Store last log message for cache activity let idleTimeout; // Function to log cache activity function logCacheActivity(isActive) { if (isActive) { if (!cacheActive) { cacheActive = true; cacheLogMessage = gradient.atlas('➥ [CACHE-SPEED] Someone is downloading cache.'); process.stdout.write(`\r${cacheLogMessage}`); } // Reset the idle timeout whenever activity is detected clearTimeout(idleTimeout); } else { if (cacheActive) { idleTimeout = setTimeout(() => { cacheActive = false; cacheLogMessage = gradient.fruit('➥ [CACHE-SPEED] Cache is online.'); process.stdout.write(`\r${cacheLogMessage}`); }, 3000); // Duration to wait before considering it idle } } } let config = readConfig(); const configApp = express(); const port = process.argv[2] || 443; configApp.set('view engine', 'ejs'); configApp.use(bodyParser.urlencoded({ extended: true })); configApp.use(express.static('public')); configApp.use('/config', basicAuth({ users: { [config.username]: config.password }, challenge: true, realm: 'Config Area' })); configApp.get('/', (req, res) => { res.send(` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auto Refresh Page</title> <script> // Refresh the page every 10 seconds setInterval(() => { window.location.reload(); }, 5000); // 10000 milliseconds = 10 seconds </script> </head> <body> <h1>Welcome to the Auto-Refresh Page!</h1> <p>This page will refresh every 10 seconds.</p> </body> </html> `); }); configApp.get('/config', (req, res) => { config = readConfig(); res.render('config', { config }); }); configApp.post('/config', (req, res) => { const { ip, port, loginurl, cdn, username, password, countries, allowedVersion, allowedPlatform, allowedProtocol } = req.body; const newConfig = { ip, port: parseInt(port), loginurl, cdn, username, password, allowedVersion, allowedPlatform, allowedProtocol }; writeConfig(newConfig); res.redirect('/config'); }); const isSynFlood = (ip) => { const now = Date.now(); if (!synFloodTracker[ip]) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } const timePassed = now - synFloodTracker[ip].timestamp; if (timePassed > SYN_BLOCK_TIME_MS) { synFloodTracker[ip] = { count: 1, timestamp: now }; return false; } else { synFloodTracker[ip].count++; if (synFloodTracker[ip].count > MAX_SYN_REQUESTS) { logBlockedIP(ip, 'SYN Flood'); return true; } } return false; }; const logBlockedIP = (ip, protocol = 'TCP') => { fs.appendFile('blocked_ips.log', `${new Date().toISOString()} - Blocked IP: ${ip} [${protocol}]\n`, (err) => { if (err) console.error(gradient.morning('Error logging blocked IP:'), err); }); }; const normalizeIp = (ip) => { if (ip.startsWith("::ffff:")) { return ip.substring(7); } if (ip === "::1") { return "127.0.0.1"; } return ip; }; const startServer = async () => { const proxy = httpProxy.createProxyServer({}); const pk = fs.readFileSync(path.join(__dirname, 'server.key')); const pc = fs.readFileSync(path.join(__dirname, 'server.crt')); const optss = { key: pk, cert: pc, minVersion: 'TLSv1.3', ciphers: [ 'TLS_AES_256_GCM_SHA384', 'TLS_CHACHA20_POLY1305_SHA256', 'TLS_AES_128_GCM_SHA256' ].join(':'), honorCipherOrder: true, enableTrace: false, requestCert: false, rejectUnauthorized: true, enableOCSPStapling: true, }; const packet = `server|${config.ip}\nport|${config.port}\ntype|1\n#maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute.\n\n\nloginurl|${config.loginurl}\nbeta_server|127.0.0.1\nbeta_port|17091\nbeta_type|1\nbeta2_server|127.0.0.1\nbeta2_port|17099\nbeta2_type|1\nmeta|${Math.floor(Date.now() / 1000)}\nRTENDMARKERBS1001`; const server = https.createServer(optss, function (req, res) { let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; const normalizedIp = normalizeIp(ip); const hostHeader = req.headers.host; server.keepAliveTimeout = 30 * 1000; server.headersTimeout = 30 * 1000; // console.log(gradient.passion(`➥ [REQUEST] IP: ${normalizedIp}`)); if (isBanned(normalizedIp)) { // console.log(gradient.summer(`IP temporarily banned: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'Ban'); res.statusCode = 403; res.end('Your IP is temporarily banned due to excessive requests.'); return; } if (trackConnection(normalizedIp)) { res.statusCode = 429; res.end('Too many connections, please try again later.'); return; } if (isSynFlood(ip)) { //console.log(gradient.fruit(`SYN flood detected from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'SYN Flood'); req.socket.end(); req.socket.destroy(); return; } const parsedUrl = url.parse(req.url); const pathname = `.${parsedUrl.pathname}`; const ext = path.parse(pathname).ext; // console.log(gradient.atlas(`➥ Connection Request from: ${normalizedIp} URL: ${req.url} Method: ${req.method}`)); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const IdentitasHost = [ 'www.growtopia1.com', 'www.growtopia2.com' ]; if (req.url === "/growtopia/server_data.php" && req.method === 'POST') { // console.log('Request Headers:', req.headers); if (!IdentitasHost.includes(hostHeader)) { const clientPort = req.connection.remotePort; const userAgent = req.headers['user-agent'] || 'Unknown'; const clientInfo = parseUserAgent(userAgent); const geoInfo = geoip.lookup(req.connection.remoteAddress) || {}; console.log(gradient.summer(`➥ Anomaly [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`)); res.statusCode = 200; res.end(` server|${normalizedIp} port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|https://t.me/GrowToolServer beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'} RTENDMARKERBS1001 `); return; } let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { //console.log('Request Body:', body); const params = new URLSearchParams(body); const version = params.get('version'); const platform = params.get('platform'); const protocol = params.get('protocol'); //console.log(`Parsed Parameters: Version - ${version}, Platform - ${platform}, Protocol - ${protocol}`); // Allow specific versions, platforms, and protocols const allowedVersions = ["4.7"]; // Add more allowed versions as needed const allowedPlatforms = ["4", "0", "1", "2", "3"]; // Add more allowed platforms as needed const allowedProtocols = ["210", "211", "212", "209"]; // Add more allowed protocols as needed // Check if the incoming parameters are acceptable if (!allowedVersions.includes(version) || !allowedPlatforms.includes(platform) || !allowedProtocols.includes(protocol)) { const clientPort = req.connection.remotePort; const userAgent = req.headers['user-agent'] || 'Unknown'; const clientInfo = parseUserAgent(userAgent); const geoInfo = geoip.lookup(req.connection.remoteAddress) || {}; console.log(gradient.summer(`➥ Anomaly [⨻] - Received parameters: version=${version}, platform=${platform}, protocol=${protocol}`)); res.statusCode = 200; res.end(` server|${normalizedIp} port|${clientPort}, ${clientInfo.os}, ${clientInfo.software}, ${userAgent} type|1 #maint|Server is currently initializing or re-syncing with sub servers. Please try again in a minute. loginurl|https://t.me/GrowToolServer beta_server|${normalizedIp} beta_port|${Math.floor(Date.now() / 69)} beta_type|1 beta2_server|${normalizedIp} beta2_port|${Math.floor(Date.now() / 69)} beta2_type|1 meta|${geoInfo.city || 'Unknown'}, ${geoInfo.country || 'Unknown'} RTENDMARKERBS1001 `); return; } //console.log(gradient.atlas(`➥ Secure request from IP: ${normalizedIp} with valid [PARAM]`)); res.write(packet, function (err) { if (err) console.log(gradient.summer(err)); }); res.end(); }); return; } if (req.url.indexOf("/cache") !== -1 || req.url.indexOf("/0098") !== -1) { if (req.method !== 'GET') { // console.log(gradient.summer(`➥ Blocked: Invalid method for ${req.url}`)); req.socket.end(); req.socket.destroy(); return; } //console.log(gradient.atlas(`➥ [CACHE-SPEED] Connection from: ${normalizedIp}\nDownloading assets: ${req.url}`)); logCacheActivity(true); const filePath = path.join(__dirname, req.url); fs.stat(filePath, (err, stats) => { if (err || !stats.isFile()) { res.statusCode = 404; res.end('Not found'); return; } const ext = path.extname(filePath); const map = { '.ico': 'image/x-icon', '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.doc': 'application/msword' }; const contentType = map[ext] || 'application/octet-stream'; res.setHeader('Content-Type', contentType); res.setHeader('Cache-Control', 'public, max-age=86400'); const raw = fs.createReadStream(filePath); raw.on('end', () => { logCacheActivity(false); // Schedule idle state when download finishes }); if (req.headers['accept-encoding'] && req.headers['accept-encoding'].includes('gzip')) { res.setHeader('Content-Encoding', 'gzip'); raw.pipe(zlib.createGzip()).pipe(res); } else { raw.pipe(res); } }); return; } //console.log(gradient.summer(`➥ [PROTECTION] Blocked request: ${req.method} ${req.url} from IP: ${normalizedIp}`)); logBlockedIP(normalizedIp, 'TCP-Other'); req.socket.destroy(); }); server.listen(port, () => { //console.log(gradient.cristal(`Server is running on port ${port}`)); }); const udpServer = dgram.createSocket('udp4'); const UDP_PORT = 53; udpServer.on('error', (err) => { console.error(`UDP server error:\n${err.stack}`); udpServer.close(); }); udpServer.on('message', (msg, rinfo) => { const ip = rinfo.address; const normalizedIp = normalizeIp(ip); // console.log(gradient.fruit(`➥ UDP request from IP: ${normalizedIp}, Port: ${rinfo.port}`)); const isUdpRateLimited = (ip) => { const now = Date.now(); if (!udpRateLimitConfigurations[ip]) { udpRateLimitConfigurations[ip] = { count: 1, timestamp: now }; return false; } else { const timePassed = now - udpRateLimitConfigurations[ip].timestamp; if (timePassed > UDP_BLOCK_TIME_MS) { udpRateLimitConfigurations[ip] = { count: 1, timestamp: now }; return false; } else { udpRateLimitConfigurations[ip].count++; // Implement stricter anti-DDoS checks if (udpRateLimitConfigurations[ip].count > MAX_UDP_REQUESTS_PER_MINUTE) { // console.log(`Blocked IP: ${normalizedIp} due to too many UDP requests.`); logBlockedIP(normalizedIp, 'UDP'); return true; // Blocks this IP due to too many requests } } } return false; }; if (isUdpRateLimited(normalizedIp)) { return; // If limited, exit the function } if (isBlockedGeoIp(normalizedIp)) { // console.log(gradient.summer(`➥ Blocking UDP access from IP: ${normalizedIp} (GeoIP Block)`)); logBlockedIP(normalizedIp, 'UDP-GeoIP'); return; } const messageBytes = msg.length; if (isNetworkUsageLimited(normalizedIp, messageBytes)) { //console.log(gradient.summer(`➥ Network usage limit exceeded for IP: ${normalizedIp} (UDP)`)); logBlockedIP(normalizedIp, 'UDP-NETWORK'); return; } const externalDns = '8.8.8.8'; const externalDnsPort = 53; const externalClient = dgram.createSocket('udp4'); // Set up a timeout for the external DNS request const timeout = setTimeout(() => { //console.error(`External DNS request timed out for IP: ${normalizedIp}`); externalClient.close(); }, 5000); // 5 seconds externalClient.send(msg, 0, msg.length, externalDnsPort, externalDns, (error) => { if (error) { // console.error(`Error forwarding UDP request: ${error}`); clearTimeout(timeout); // Clear the timeout if there's an error externalClient.close(); } }); externalClient.on('message', (response) => { clearTimeout(timeout); // Clear the timeout since we received a response udpServer.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => { if (err) { //console.error(`Error sending UDP response: ${err}`); } externalClient.close(); }); }); externalClient.on('error', (err) => { //console.error(`External DNS client error: ${err}`); clearTimeout(timeout); externalClient.close(); }); }); udpServer.on('listening', () => { const address = udpServer.address(); // console.log(gradient.morning(`⧪ UDP `)); }); udpServer.bind(UDP_PORT); }; startServer(); shutdownAfterInterval(); configApp.post('/shutdown', (req, res) => { res.send('Server is shutting down...'); shutdown(); }); function parseUserAgent(userAgent) { let os = 'Unknown'; let software = 'Unknown'; if (userAgent.includes('Windows')) os = 'Windows'; else if (userAgent.includes('Linux')) os = 'Linux'; else if (userAgent.includes('Mac OS')) os = 'Mac OS'; else if (userAgent.includes('Android')) os = 'Android'; else if (userAgent.includes('iOS')) os = 'iOS'; if (userAgent.includes('Firefox')) software = 'Firefox'; else if (userAgent.includes('Chrome')) software = 'Chrome'; else if (userAgent.includes('Safari')) software = 'Safari'; else if (userAgent.includes('Edge')) software = 'Edge'; else if (userAgent.includes('curl')) software = 'curl'; return { os, software }; } const shutdown = () => { console.log('⧪ Shutting down the server...'); server.close(() => { console.log('⧪ HTTP server closed.'); udpServer.close(() => { console.log('⧪ UDP server closed.'); process.exit(0); }); }); setTimeout(() => { console.error('Forced shutdown due to open connections.'); process.exit(1); }, 5000).unref(); }; process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); console.log(''); console.log(` ${gradient.teen(` ┌────────────────────────────────────────────────────┐`)} ${gradient.atlas(` │`)} ${gradient.fruit(`✧ HTTP(s) Port: Online`)} ${gradient.atlas(` │`)} ${gradient.atlas(` │`)} ${gradient.fruit(`✧ App Version: HTTP KING v4.0.3`)} ${gradient.atlas(` │`)} ${gradient.atlas(` │`)} ${gradient.summer(`✧ Anti-DDoS: UDP-TCP-PROXY-DNS`)} ${gradient.atlas(` │`)} ${gradient.teen(` └────────────────────────────────────────────────────┘`)} `); console.log(''); })();give me the npm install
- Assistant
If the goal is to execute
npm installusing the packages listed in your JavaScript code, it appears these packages are already being conditionally installed viaexecSync. However, if you prefer to install them all at once using a batch script, you can simplify the process by listing the packages in a batch file that runsnpm install.Here is a basic batch script to install the packages specified in your JavaScript code:
@echo off setlocal rem Ensure npm is available where npm >nul 2>nul if %ERRORLEVEL% neq 0 ( echo Node.js and npm must be installed and available in your PATH. exit /b 1 ) echo Installing npm packages... rem Install all the necessary packages npm install express body-parser axios geoip-lite express-basic-auth gradient-string echo Installation complete. endlocalInstructions:
-
Create the Batch File:
- Open a text editor, like Notepad.
- Copy the script above and paste it into the editor.
- Save the file with a
.batextension, for instance,install-packages.bat.
-
Run the Batch File:
- Ensure that the batch file is in the root directory of your Node.js project (where your
package.jsonis located). This ensures that packages are installed locally to your project. - Double-click the batch file to execute it, or run it from a Command Prompt by navigating to the directory and typing its name (e.g.,
install-packages.bat).
- Ensure that the batch file is in the root directory of your Node.js project (where your
Considerations:
- Node.js and npm: This script will fail if Node.js and npm are not installed or if they are not in the system's PATH environment variable.
- Package.json: Running
npm installin the directory where apackage.jsonfile resides will automatically install the listed dependencies using the versions specified. If you don't modify dependencies regularly, this is typically the most convenient approach.
This batch file installs the listed packages directly in one command, making management simpler and avoiding unnecessary re-checks by leveraging
npm's internal mechanisms. -