BotDetect v2 — Production Bot Detection Library
Client-side bot and automation detection library with weighted scoring, behavioral analysis, browser fingerprinting, and configurable thresholds. Detects headless browsers, Selenium, Puppeteer, Playwright, CDP-based tools, and stealth automation frameworks.
v2.1.0 — anti-detection honeypots, GPU-stable canvas fingerprinting, enhanced behavioral analysis, lazy initialization, server-side tamper detection, request fingerprint binding, and rate limiting.
Table of Contents
Features
- 28 detection modules covering automation frameworks, headless browsers, fingerprinting, behavioral analysis, honeypots, and stack trace traps
- Weighted scoring system — each signal has configurable weight; final score computed server-side
- Three verdict levels:
human, suspicious, bot with corresponding friction actions (monitor, challenge, block)
- Server-side verification — nonce-gated, replay-protected, proof-of-work signed
- Stack trace traps — monkey-patches DOM APIs to capture automation tool call stacks
- Behavioral analysis — mouse curvature, keystroke timing variance, scroll acceleration, touch dynamics
- Anti-detection honeypots — randomized CSS cloaking, decoy fields, realistic field names
- Server-side tamper detection — validates signal integrity, detects gaming attempts
- Request fingerprint binding — PoW tokens bound to HTTP request attributes
- Rate limiting — per-session rate limiting on all verification endpoints
- No-script detection — identifies clients that never send detection payloads
- Known crawler allowlist — 20+ legitimate bots excluded from scoring
Architecture
Browser Your Server
┌──────────────────────────┐ ┌──────────────────────┐
│ Collector (singleton) │ POST │ Express Middleware │
│ ├─ 28 detection modules│ signals │ ├─ NonceManager │
│ ├─ BehaviorTracker │ + nonce │ ├─ RateLimiter │
│ ├─ HoneypotTraps │───────────▶│ ├─ TamperDetector │
│ ├─ Stack trace traps │ │ ├─ computeVerdict() │
│ └─ IframeContext │ │ └─ Proof-of-Work │
│ │ verdict │ │
│ ↓ collect() → │ + proof │ Returns: │
│ DetectionResult[] │◀───────────│ { verdict, score, │
└──────────────────────────┘ │ confidence, proof, │
│ tamperScore } │
└──────────────────────┘
│
▼
Session-gated endpoint
(login, checkout, etc.)
validates proof before
granting access
Key principle: The browser only collects raw DetectionResult[] signals. The server computes the final verdict using a secret weight table. Client-computed verdicts are never trusted.
Quick Start
1. Build
npm install
npm run build
Outputs to dist/:
botdetect.min.js (with polyfills, ~151 KB)
botdetect-clean.min.js (modern browsers only, ~74 KB)
2. Include on your page
<script src="/path/to/botdetect.min.js"></script>
<script>
BotDetect.collector.enableTraps();
BotDetect.collector.enableBehavioralTracking();
BotDetect.collector.enableHoneypots();
</script>
3. Set up server-side verification
cd server
npm install express cors express-session
node example-integration.js
4. Send signals on sensitive action
async function onLogin() {
const { nonce } = await (await fetch('/api/botdetect/nonce')).json();
BotDetect.collector.setNonce(nonce);
const signals = await BotDetect.collector.collect();
const resp = await fetch('/api/botdetect/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ signals, nonce })
});
const { verdict, score, proof, friction } = await resp.json();
document.getElementById('botdetect-proof').value = proof;
document.getElementById('login-form').submit();
}
5. Validate on the server
app.post('/api/login', (req, res) => {
const bd = req.session.botdetect;
if (!bd) return res.status(403).json({ error: 'no_verification' });
if (bd.verdict === 'bot') return res.status(403).json({ error: 'access_denied' });
if (bd.verdict === 'suspicious') return challengeCaptcha(req, res);
res.json({ success: true });
});
Client-Side API
Collector (singleton)
import Collector from './collector/Collector';
// or via global: BotDetect.collector
Detector (debug only)
import Detector from './detector/Detector';
Warning: analyze() runs entirely in the browser. Never use its output for production decisions.
Types
interface DetectionResult {
name: string; // Module name
score: number; // 0.0 – 1.0
weight: number; // 1 – 10 (importance)
detail?: string; // Human-readable description
}
interface DetectionVerdict {
verdict: 'bot' | 'suspicious' | 'human';
score: number; // 0.0 – 1.0
confidence: number; // 0.0 – 1.0
signals: DetectionResult[];
threshold: number;
friction: 'monitor' | 'challenge' | 'block';
}
interface CollectorConfig {
detectionTimeoutMs: number; // per-module timeout (default: 3000)
enableTraps: boolean;
enableBehavioralTracking: boolean;
enableHoneypots: boolean;
thresholds: { strict: number; balanced: number; relaxed: number };
}
Server-Side Integration
Express Middleware
const { createBotDetectEndpoint } = require('./server');
const { router, generateProofOfWork, cleanup } = createBotDetectEndpoint({
secretSalt: process.env.BOTDETECT_SALT,
scoring: {
threshold: 'balanced', // 'strict' | 'balanced' | 'relaxed' | number
minSignals: 2,
signalBoostThreshold: 0.8,
frictionThresholds: { monitor: 0.2, challenge: 0.5, block: 0.8 }
},
nonce: { ttl: 300000 }, // 5-minute nonce expiry
noScript: { timeout: 10000 }, // 10s no-script window
rateLimit: { maxRequests: 10, windowMs: 60000 },
noScriptPaths: ['/api/login', '/api/checkout', '/api/register']
});
app.use('/api', router);
Endpoints
| Endpoint | Method | Purpose |
|---|
/api/botdetect/nonce | GET |
{
"verdict": "human",
"score": 0.125,
"confidence": 0.85,
"tamperScore": 0,
"friction": "monitor",
"threshold": 0.5,
"proof": "a1b2c3d4e5f6..."
}
Server-Side Scoring (Node.js)
const { computeVerdict, RateLimiter, NonceManager } = require('./scoring');
const verdict = computeVerdict(signals, {
threshold: 'balanced',
minSignals: 2,
signalBoostThreshold: 0.8,
frictionThresholds: { monitor: 0.2, challenge: 0.5, block: 0.8 }
});
// verdict.tamperScore > 0 if signal tampering detected
Detection Modules
Automation Frameworks (weights 5–7)
Playwright-Specific (weights 3–4)
| Module | Detects | Weight |
|---|
playwrightWebKit | WebKit automation artifacts | 4 |
playwrightOrientation | Orientation + chrome.runtime inconsistency | 3 |
Behavioral Analysis (weight 7)
| Module | Signals Analyzed | Weight |
|---|
behavioralAnalysis | Mouse curvature + straight-line ratio, keystroke CV + burst patterns + KPM, scroll acceleration + direction changes, touch force variance + radius | 7 |
Browser Fingerprinting (weights 3–4)
Navigator & OS Properties (weight 5)
| Module | Checks | Weight |
|---|
navigatorInconsistencies | 11 checks: languages, plugins, mimeTypes, platform, UA, cookies, DNT, touch, hardwareConcurrency, deviceMemory, connection | 5 |
Active Traps & Honeypots (weights 8–9)
| Module | Detects | Weight |
|---|
honeypotTraps | Randomized hidden fields + decoys + canary endpoint | 9 |
|
Network & Contextual (weights 1–2)
Allowlist (weight 0)
| Module | Detects | Weight |
|---|
verifiedBots | 20+ known crawlers (Googlebot, Bingbot, Yandex, Facebook, Twitter, etc.) — returns -1, excluded from scoring | 0 |
Configuration
Collector
const collector = Collector.getInstance({
detectionTimeoutMs: 1000, // Lower for faster UX
enableTraps: true,
enableBehavioralTracking: true,
enableHoneypots: true,
thresholds: {
strict: 0.3, // Aggressive (login, checkout)
balanced: 0.5, // Default
relaxed: 0.7 // Permissive (content browsing)
}
});
Detector (debug only)
const detector = Detector.getInstance({
threshold: 'balanced', // 'strict' | 'balanced' | 'relaxed' | number
minSignals: 2, // Minimum signals before boost
signalBoostThreshold: 0.8, // Signals above this get extra weight
failPolicy: 'open', // 'open' = human on error, 'closed' = bot on error
frictionThresholds: {
monitor: 0.2,
challenge: 0.5,
block: 0.8
}
});
Server
createBotDetectEndpoint({
secretSalt: process.env.BOTDETECT_SALT, // Keep secret
scoring: { threshold: 'balanced' },
nonce: { ttl: 300000, cleanupInterval: 60000 },
noScript: { timeout: 10000 },
rateLimit: { maxRequests: 10, windowMs: 60000 },
requestFingerprint: true, // Bind PoW to request attributes
noScriptPaths: ['/api/login', '/api/checkout']
});
Production Checklist
Security
Monitoring
Testing
npm test # 74 Jest tests across 6 suites
npm run typecheck # TypeScript strict mode
npm run lint # ESLint
npm run build # Webpack production bundle
License
Apache — Lahmeri Mohamed Amine