can you make a indicator that inside cache folder are empty or not, don't touch anything ok.
Assistant
To create an indicator that checks whether the cache folder is empty or not without modifying your existing code structure, you can add a simple function that runs before the server starts. This function will check the contents of the cache directory and log the result.
Here's how you can do it:
Create a function that checks if the cache folder is empty.
Call this function in the run method before starting the server.
Below is the modified part of your code where the new function is added:
A new function called checkCacheFolderEmpty is added. This function uses fs.readdir to read the contents of the cache directory.
Depending on the length of the files array returned, it logs whether the folder is empty or shows how many files are present.
This function is called from within the existing run method before the server starts (startServer()).
Make sure you have a directory named cache in the same location as your script to test the functionality.
User
code
Assistant
The error you're encountering is due to the import syntax being used in a Node.js script that is not set up to handle ECMAScript modules (ESM). Node.js treats files as CommonJS modules by default, which means that you need to use require() instead of import, unless you are using the ESM syntax correctly.
To fix this error, you have two options:
Option 1: Use CommonJS require()
Change the import statement to use require() like this:
javascript
const gradient = require('gradient-string');
This will keep your file as a CommonJS module and avoid any syntax errors.
Option 2: Use an ESM-compatible environment
If you want to use the import syntax, you need to enable ESM support. Here are the steps you can take:
Change the file extension from .js to .mjs. This tells Node.js that you want it to treat this file as an ESM module.
Add "type": "module" to your package.json file, which makes all .js files in that package treated as ESM modules by default.
After doing that, your original import statement should work:
If you're looking for a quick fix without changing your project structure, I recommend using Option 1, which allows you to keep your current setup intact. Here's how you could modify the part of your code:
javascript
const gradient = require('gradient-string');
Resulting Code Snippet
Here’s the specific part of your modified code:
javascript
// Change this line:
const gradient = (await import('gradient-string')).default;
// To this line:
const gradient = require('gradient-string');
Choose the option that best fits your needs and project requirements, and the error should be resolved!
User
undefined
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Administrator\Downloads\AVIATUM LE NORA\node_modules\gradient-string\dist\index.js from C:\Users\Administrator\Downloads\AVIATUM LE NORA\ee.js not supported.
Instead change the require of index.js in C:\Users\Administrator\Downloads\AVIATUM LE NORA\ee.js to a dynamic import() which is available in all CommonJS modules.
at TracingChannel.traceSync (node:diagnostics_channel:315:14)
at Object. (C:\Users\Administrator\Downloads\AVIATUM LE NORA\ee.js:8:18) {
code: 'ERR_REQUIRE_ESM'
}
Assistant
The new error you're encountering indicates that the gradient-string package is now an ES Module (ESM), which means you cannot use require() to import it in CommonJS files. You need to use import syntax instead.
Here are two ways to resolve this issue:
Option 1: Convert Your File to ESM
Rename your file from .js to .mjs. This tells Node.js to treat it as an ESM module by default.
Update your package.json: Optionally, you can add "type": "module" to your package.json file to treat all .js files as ESM automatically.
Use the import Statement: Replace require() with import.
For example, your code would look like this:
javascript
import { execSync } from 'child_process';
import { machineIdSync } from 'node-machine-id';
import https from 'https';
import express from 'express';
import bodyParser from 'body-parser';
import fs from 'fs';
import path from 'path';
import gradient from 'gradient-string';
const SERVER_PORT = 443;
// the rest of your code remains unchanged...
Option 2: Dynamic Import in CommonJS
If you want to keep your file as a CommonJS module (.js), you can perform a dynamic import as suggested in the error message:
To block specific hostnames or IP addresses from accessing your server, you can implement middleware in your Express application that checks the incoming request's origin or hostname against a list of blocked hosts. If a match is found, you can respond with an appropriate status code (e.g., 403 Forbidden).
Here's how you can implement this functionality:
Step 1: Define Blocked Hosts
You can create an array to store the URLs or IP addresses of the hosts you want to block.
Step 2: Create Middleware for Checking Access
You will then create a middleware function that checks if the request's origin matches any of the blocked hosts.
Step 3: Apply the Middleware
Finally, you will apply this middleware in your Express application before defining any routes.
Here’s how to add this functionality to your existing code:
javascript
(async () => {
// Your existing imports and configuration
const blockedHosts = [
'check-host.net',
'check-host.cc',
'badhost.com', // add other hosts as needed
// You can also add IP addresses as strings (e.g., '192.168.1.1')
];
const checkBlockedHosts = (req, res, next) => {
const host = req.headers['host'] || '';
// Check if the host matches any of the blocked hosts
if (blockedHosts.some(blocked => host.includes(blocked))) {
return res.status(403).send('Access Forbidden'); // Respond with 403 Forbidden
}
next(); // Continue to the next middleware if not blocked
};
const startServer = () => {
const app = express();
app.use(checkBlockedHosts); // Add the blocked hosts check middleware
app.use(bodyParser.urlencoded({ extended: true }));
// Rest of your existing startServer code...
app.post('/growtopia/server_data.php', (req, res) => {
// Your existing route handling...
});
app.get('/cache', (req, res) => {
// Your existing cache handling...
});
// Other middlewares and TLS setup...
https.createServer(tlsOptions, app).listen(SERVER_PORT, () => {
console.log(``);
console.log(gradient.summer(`HTTP STATUS : ONLINE`));
console.log(``);
});
};
const run = async () => {
checkCacheFolderEmpty();
startServer();
};
run();
})();
User
They still can scan my opened port status
Assistant
To prevent unwanted port scanning and probing on your server, a simple middleware in Express is not sufficient, as it only filters HTTP requests to your application. If someone is scanning your server's open ports, that happens at a lower network level, which cannot be controlled by application-layer logic. Here are a few strategies you can implement to mitigate port scanning and restrict access:
1. Use a Firewall
Using a firewall (like iptables, ufw for Linux, or Windows Firewall) is the most effective way to block access to specific ports or hosts.
On Linux with iptables:
You can block specific IP addresses that you suspect are scanning your server. For example:
bash
# Block a specific IP address
sudo iptables -A INPUT -s <BLOCKED_IP_ADDRESS> -j DROP
# Block all packets from the specified domain (requires DNS lookup)
# This requires installation of the iptables-persistent package to handle this effectively
On Linux with ufw:
You can allow only specific IP addresses to access your HTTP and HTTPS ports.
bash
# Allow access from a specific IP
sudo ufw allow from <ALLOWED_IP> to any port 443
# Deny access to everyone else (optional)
sudo ufw deny 443
On Windows:
You can configure Windows Firewall to block specific IP addresses under inbound rules.
2. Implement Rate Limiting
To reduce the possibility of scanning attacks, you can implement rate limiting with libraries like express-rate-limit:
bash
npm install express-rate-limit
Example Code:
Here is how to apply a rate limit middleware in your Express application:
javascript
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.'
});
// Apply to all requests
app.use(limiter);
User
No, i dont like using external. can you do that in my script? (im using windows)
Assistant
If you want to integrate IP blocking directly within your Node.js application without using external tools, you can implement a simple solution to check incoming requests against a predefined blocklist of IP addresses right in your Express application.
Here's how to do it:
Maintain an IP blocklist in your JavaScript code.
Implement middleware that checks the incoming requests' IP addresses against this blocklist.
Respond with a 403 Forbidden status if a match is found.
Step-by-Step Implementation
Below are the modifications to your existing code that implement IP blocking directly within the server script:
javascript
User
not ip, i dont want check-host.net,check-host.cc can check, thats it.
Assistant
If you want to prevent specific domains or hostnames (like check-host.net and check-host.cc) from accessing your Node.js server by blocking their HTTP requests regardless of their IP, you can implement a middleware that checks the User-Agent or Referer header of incoming requests against a predefined list of blocked domains.
Steps
Maintain a list of domains you want to block.
Implement middleware to check incoming requests against this list.
Respond with a 403 Forbidden status if a match is found.
Below is how you can modify your existing code to block access based on these domains.
Example Code Implementation
Here’s how to implement this functionality in your existing Node.js server script:
javascript
User
they can still check
Assistant
If you want to prevent specific domains (like check-host.net and check-host.cc) from probing or scanning your server status, keep in mind that such external services often work at a lower level than your application code. These services can attempt to connect directly to your server's IP and port (without sending specific HTTP request headers) to check if the ports are open, which your application won't be able to reject.
However, there are several strategies you can use within your Node.js server code, but keep in mind that these measures mainly help with HTTP-level requests and won't directly stop network-level scans. Here are some strategies you can implement within your application and consider, along with added security.
1. Limit Response to Specific User Agents
While this won’t stop a service based on IP from probing, you can limit access to your service by allowing only known user agents (though this can be easily bypassed). You can adjust the middleware to respond only to requests that have specific user agents you expect.
2. Use a Basic Challenge-Response Verification
You can also implement a basic challenge-response system where clients need to provide a token or key. This won't necessarily stop probes, but it will stop unwanted access.
3. Implement IP Whitelisting
While less flexible, you could allow connections from known IPs only if possible. This could reduce the possibility of unwanted accesses.
4. Using a Firewall or Routing Level Filtering
The most effective solution to stop unauthorized scanners or services is not application-side filtering but blocking via a firewall. Since you prefer not to use external tools, the Windows Firewall is a built-in feature that can be used to only allow incoming traffic from specific IP addresses or ranges.
Windows Firewall Configuration
Since you're using Windows, you can set up inbound rules to block known scanning services.
Open Windows Firewall:
Go to Control Panel > System and Security > Windows Defender Firewall.
Create a New Inbound Rule:
Click on "Advanced settings" on the left side.
In the Windows Firewall with Advanced Security, select "Inbound Rules" and then "New Rule" on the right side.
Select Rule Type:
Choose "Custom" for a custom rule that can be specified by port and IP.
Program:
Choose "All programs" or specify your Node.js server executable.
Dynamic imports need to be used within an async function or at the top-level code of a module. If you put it at the top level, you should use an IIFE (Immediately Invoked Function Expression):
javascript
(async () => {
const gradient = (await import('gradient-string')).default;
// Start your application logic here
run();
})();
Using ESM in an existing project: If you have many dependencies using CommonJS, converting entirely to ESM can introduce complications unless you're ready to refactor your codebase.
Recommendation
If gradient-string is the only package causing issues, using dynamic import in a CommonJS module might be a bit complicated for simple projects. Alternatively, if you aim to use ESM for more compatibility with modern libraries, consider converting your project to ESM by renaming files to .mjs and updating your imports accordingly.
Choose the approach that makes more sense for your project's context!
can you add block website from getting access to our server, like check-host.net, check-host.cc and other port/host checker cuz i dont want someone scan my server.
Explanation:
Blocked Hosts: An array blockedHosts is created to store hostnames that you want to block. You can add any host you want to restrict access to.
Middleware Function: The checkBlockedHosts function checks the Host header of incoming requests. If the host matches any entry in blockedHosts, a 403 Forbidden response is sent, denying access to the request.
Applying Middleware: The middleware is applied to the Express app using app.use(checkBlockedHosts), ensuring it runs before any route handlers.
Notes:
This implementation checks the Host header, which is typically used in HTTP requests. However, be aware that headers can be forged in some cases. While this approach can help mitigate unwanted access, it's not a foolproof method against all forms of probing or attacks.
Consider monitoring your server access logs for suspicious activity and implementing more stringent security measures as needed.
3. Use an Intrusion Detection System (IDS)
Consider setting up an IDS (like Fail2Ban) that will monitor your server logs and automatically block IP addresses that show malicious signs, such as multiple failed access attempts.
4. Make Service on Non-Standard Ports
You can change the port your server is running on from the standard ports (like 80 for HTTP and 443 for HTTPS) to a non-standard port. This will reduce some automated scanning since many tools default to these standard ports.
5. Configure Network Security Groups (if on the cloud)
If you are hosting your application in the cloud (e.g., AWS, Azure, GCP), make sure to configure your Network Security Groups (or equivalent) to allow traffic only from trusted IP addresses.
6. Consider DDoS Protection Services
For more robust applications, consider using DDoS protection services such as Cloudflare or AWS Shield that can provide additional layers of security against scanning and DDoS threats.
Summary
While no solution is foolproof, combining these techniques will help you close potential vulnerabilities and secure your server against port scanning and other unauthorized access attempts. Always ensure you monitor your logging and alerts to catch potential intrusions early.
(async () => {
const gradient = (await import('gradient-string')).default;
const { execSync } = require('child_process');
const { machineIdSync } = require('node-machine-id');
const https = require('https');
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const SERVER_PORT = 443;
const configPath = path.resolve(__dirname, './config/main.json');
const checkAndInstall = (pkgList) => {
pkgList.forEach(pkg => {
try {
require.resolve(pkg);
} catch (error) {
execSync(`npm install ${pkg}`, { stdio: 'ignore' });
}
});
};
checkAndInstall(['https', 'express', 'node-machine-id']);
const readConfig = () => {
try {
const data = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(data);
if (!config.allowedCountries) {
config.allowedCountries = [];
}
return config;
} catch (err) {
return { allowedCountries: [] };
}
};
let config = readConfig();
const blockedIPs = [
'192.168.1.1', // Replace with actual IPs you want to block
'10.0.0.1',
// Add more IP addresses as needed
];
const checkBlockedIPs = (req, res, next) => {
// Get IP address of the requester
const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
// Check if the IP is in the blocklist
if (blockedIPs.includes(clientIp)) {
return res.status(403).send('Access Forbidden'); // Respond with 403 Forbidden
}
next(); // Continue to the next middleware if not blocked
};
const cacheFolderPath = path.join(__dirname, 'cache');
const checkCacheFolderEmpty = () => {
fs.readdir(cacheFolderPath, (err, files) => {
if (err) {
console.error('Error reading cache folder:', err);
return;
}
if (files.length === 0) {
console.log(gradient.cristal('Status cache : Tidak ada / Kosong'));
} else {
console.log(gradient.cristal(`Status cache : Tersedia / Online`));
}
});
};
const startServer = () => {
const app = express();
// Use the IP blocking middleware before other middlewares
app.use(checkBlockedIPs);
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/growtopia/server_data.php', (req, res) => {
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`;
res.setHeader('Content-Type', 'text/plain');
res.send(packet);
});
app.get('/cache', (req, res) => {
const filePath = path.join(__dirname, req.url);
fs.stat(filePath, (err, stats) => {
if (err || !stats.isFile()) {
res.end();
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'
};
res.setHeader('Content-Type', map[ext] || 'application/octet-stream');
fs.createReadStream(filePath).pipe(res);
});
});
app.use((req, res) => {
req.socket.end();
});
const tlsOptions = {
key: fs.readFileSync(path.join(__dirname, 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'server.crt')),
minVersion: 'TLSv1.3',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256'
].join(':')
};
https.createServer(tlsOptions, app).listen(SERVER_PORT, () => {
console.log(``);
console.log(gradient.summer(`HTTP STATUS : ONLINE`));
console.log(``);
});
};
const run = async () => {
checkCacheFolderEmpty();
startServer();
};
run();
})();
Explanation
Blocked IPs Array: The blockedIPs array contains the list of IP addresses you want to block. Replace the sample IPs (192.168.1.1, 10.0.0.1) with actual IPs you want to restrict access to.
Middleware Function: The checkBlockedIPs function checks the incoming request's IP address against the blocked IPs. The IP is retrieved from the x-forwarded-for header or directly from the socket address.
Middleware Usage: The blocking middleware is applied to the Express app with app.use(checkBlockedIPs); before defining any routes. This ensures that any blocked requests are rejected before reaching your application logic.
Response Handling: If a blocked IP tries to access your server, a 403 Forbidden response is sent back.
Important Notes
The method of blocking IP addresses is effective for simple cases, but sophisticated attackers can use various methods to bypass IP blocking (like proxy servers).
Always keep your blocklist updated and monitor access logs to catch suspicious behaviors.
This approach won't stop port scanning directly since it only affects HTTP traffic. You'd still need firewall settings to manage TCP/IP connections themselves.
Blocked Domains: An array, blockedDomains, is created to hold the domains you want to block from accessing your server.
Middleware Function:
The checkBlockedDomains function examines the Referer and User-Agent headers of incoming requests.
If either header contains any of the blocked domains, it sends a 403 Forbidden response.
Middleware Usage:
The middleware is applied to the Express app using app.use(checkBlockedDomains);, ensuring it runs before any request handlers. This will block any requests from unwanted domains.
Response Handling:
If a blocked domain attempts to access your server, they will receive a 403 Forbidden response.
Note
This solution operates at the HTTP request level (application layer). However, if the host resolves (for example, through a browser) and attempts to connect using another means (like direct TCP/IP), it will not be blocked. This method is effective primarily for web requests.
Ensure that you validate if the blocked hosts generate requests that include specific headers; if they do not send the Referer header, this method will not work for them.
Protocol and Ports:
Specify the protocol (TCP) and the local port (your server is likely using 443).
Scope:
On the Scope page, you can specify IP addresses to block. You could add the IP addresses or ranges associated with services you want to block.
Action:
Select "Block the connection."
Profile:
Choose the profile where this rule applies (Domain, Private, Public).
Name Your Rule:
Give your rule a name for easy reference.
Simple Server Code Example
Here’s a combined example of both the middleware for checking incoming requests and basic blocking by user agent (if applicable):
To effectively prevent domain name probes, implement a combination of application-level security (like validation against expected user agents) and network-level security (using firewalls to block unwanted external services). The combination of both strategies will help strengthen your server's defenses against unwanted access.
It's also recommended to regularly monitor your server access logs for any suspicious activity and adjust your configurations accordingly.