bot-guardian-js
Version:
A powerful bot detection and prevention library for Node.js applications
100 lines (99 loc) • 3.76 kB
JavaScript
;
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createApiServer = void 0;
// src/api/server.ts
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const GuardianJS_1 = require("../core/GuardianJS");
const path_1 = __importDefault(require("path"));
function createApiServer() {
const app = (0, express_1.default)();
app.use((0, cors_1.default)());
app.use(express_1.default.json());
const guardian = new GuardianJS_1.GuardianJS({
useBehavior: true,
threshold: 0.5,
customRules: [
{
name: 'Known Bot Detection',
test: (params) => {
const knownBots = [
'googlebot',
'bingbot',
'yandexbot',
'duckduckbot',
'baiduspider',
'facebookexternalhit',
'testbot'
];
const ua = params.userAgent.toLowerCase();
return knownBots.some(bot => ua.includes(bot));
},
score: 1.0
}
]
});
// Bot detection endpoint
app.post('/detect', (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
const { userAgent, ip, path } = req.body;
const result = yield guardian.isBot({
userAgent,
ip,
req: { path }
});
res.json(result);
}
catch (error) {
console.error('Detection error:', error);
res.status(500).json({ error: 'Detection failed' });
}
}));
// Dashboard data endpoint
app.get('/data', (req, res) => {
const data = {
totalRequests: 100,
detectedBots: 25,
recentDetections: [{
isBot: false,
score: 0,
confidence: 0,
userAgent: req.headers['user-agent'],
timestamp: new Date(),
behavior: {
mouseMovements: 0,
keystrokes: 0,
timeOnPage: 0,
scrolling: false
},
reasons: []
}]
};
res.json(data);
});
// Serve dashboard
const dashboardPath = path_1.default.resolve(__dirname, '../../dashboard');
app.use('/dashboard', express_1.default.static(dashboardPath));
return app;
}
exports.createApiServer = createApiServer;
// Start server if run directly
if (require.main === module) {
const PORT = process.env.PORT || 3333;
const app = createApiServer();
app.listen(PORT, () => {
console.log(`GuardianJS API running on port ${PORT}`);
});
}