botblocker.pro
Version:
BotBlocker.Pro is an essential package for protecting your website from unwanted bots that can harm performance and security. Our powerful real-time web traffic filtering and analytics service helps you track and understand your visitors while effectively
134 lines (133 loc) • 5.67 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BotBlocker = void 0;
const https = __importStar(require("https"));
const net = __importStar(require("net"));
const querystring = __importStar(require("querystring"));
class BotBlocker {
/**
* Constructor for the BotBlocker class that initializes with an API key.
* @param apiKey - The API key necessary to access the remote BotBlocker service.
*/
constructor(apiKey) {
this.apiKey = apiKey;
}
/**
* Extracts the IP address and User-Agent from an HTTP request object.
* @param req - The HTTP request object from which to extract the IP and User-Agent.
* @returns An object containing the IP address and User-Agent string.
*/
extractInfoFromReq(req) {
const ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress || '').replace(/^.*:/, '');
const userAgent = req.headers['user-agent'] || '';
const url = req.url || '';
return { ip, userAgent, url };
}
/**
* Processes an HTTP request object to check if it should be blocked based on IP and User-Agent.
* @param req - The request object to be checked.
* @returns A promise that resolves to the blocking decision.
*/
checkReq(req) {
return __awaiter(this, void 0, void 0, function* () {
const { ip, userAgent, url } = this.extractInfoFromReq(req);
return this.check(ip, userAgent, url);
});
}
/**
* Checks if the IP and User-Agent should be blocked by consulting the BotBlocker API.
* Throws an error if the IP address is invalid.
* @param ip - The IP address to check.
* @param userAgent - The User-Agent string to check.
* @param url - The URL string to check.
* @returns A promise that resolves to the API response.
*/
check(ip, userAgent, url) {
return __awaiter(this, void 0, void 0, function* () {
if (!this.isValidIp(ip))
throw new Error("Invalid IP address provided.");
// Prepare query parameters
const queryParams = querystring.stringify({
apikey: this.apiKey,
ip: ip,
ua: userAgent,
url: url
});
const options = {
hostname: 'botblocker.pro',
path: `/api/v1/blocker?${queryParams}`,
method: 'GET',
headers: {
'User-Agent': 'BotBlocker.Pro NPM'
}
};
return this.httpGet(options);
});
}
/**
* Makes an HTTP GET request and returns the JSON-parsed response.
* @param options - The options for the HTTP request.
* @returns A promise that resolves to the parsed JSON response or rejects with an error.
*/
httpGet(options) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
let responseData = '';
res.on('data', chunk => responseData += chunk);
res.on('end', () => {
try {
resolve(JSON.parse(responseData));
}
catch (err) {
reject(new Error(`BotBlocker error: ${err.message}`));
}
});
});
req.on('error', e => reject(new Error(`BotBlocker error: ${e.message}`)));
req.end();
});
});
}
/**
* Validates if an IP address is valid.
* @param ip - The IP address to validate.
* @returns True if the IP address is valid, false otherwise.
*/
isValidIp(ip) {
return net.isIP(ip) !== 0;
}
}
exports.BotBlocker = BotBlocker;