Cloudflare is a widely used content delivery network (CDN) and security service that allows you to protect your website from various threats, including malicious bots. One way to block bots is by creating firewall rules that match specific user agents, hostnames, and IP addresses. This Node.js script automates the generation of such rules and has been tested on Node.js version 16.
Before we dive into the script, make sure you have the following prerequisites:
- Node.js installed on your system.
- NPM (Node Package Manager) installed.
The following Node.js script generates Cloudflare firewall blocking rules to block bots based on user agents, hostnames, and IP addresses:
import { promises as fs } from "fs";
(async () => {
try {
const UserAgents = ["bingbot", "BLEXBot"];
const HostNames = ["search.msn.com"];
const Addresses = ["100.26.127.17"];
// Create unique rules for user agents, hostnames, and addresses
const UserAgentsRules = Array.from(new Set(UserAgents)).map((a) => `(http.user_agent contains "${a}")`);
const HostNamesRules = Array.from(new Set(HostNames)).map((a) => `(http.host contains "${a}")`);
const AddressesRules = Array.from(new Set(Addresses)).map((a) => `(ip.src eq ${a})`);
// Combine all the rules into one array
const BlockRules = [...UserAgentsRules, ...HostNamesRules, ...AddressesRules];
// Write the rules to a text file
await fs.writeFile("./block-rules.txt", BlockRules.join(" or "));
} catch (err) {
console.log("Runtime Exception: " + err);
process.exit(1);
}
})();Follow these steps to use the script:
-
Copy the script code provided above and paste it into a text editor.
-
Save the script with a
.mjsextension, for example,generate-firewall-rules.mjs. -
Open a terminal and navigate to the directory where you saved the script.
-
Run the script using Node.js:
node generate-firewall-rules.mjs
-
The script will generate Cloudflare firewall blocking rules based on the specified user agents, hostnames, and IP addresses and save them to a text file named
block-rules.txt. -
You can then apply these rules in your Cloudflare firewall configuration to block the specified bots.
This Node.js script simplifies the process of generating Cloudflare firewall blocking rules to block bots based on user agents, hostnames, and IP addresses. By automating this process, you can enhance the security of your website and protect it from potentially harmful bot traffic. Please ensure you have Node.js version 16 or higher installed to use this script effectively.