Node SDK
SDK Overview
Section titled “SDK Overview”The WebDecoy Node SDK provides server-side bot detection and threat intelligence for Node.js applications. It enables deep integration with Express, Next.js, Fastify, and other Node.js frameworks.
Note: The Node SDK is currently in development. This documentation reflects the planned API and features.
SDK Capabilities
Section titled “SDK Capabilities”| Feature | Description |
|---|---|
| Bot Detection | Analyze requests for automation signals |
| Threat Scoring | Calculate unified threat scores |
| IP Intelligence | Access reputation and geolocation data |
| TLS Fingerprinting | JA3/JA4 fingerprint analysis |
| Detection Submission | Send detections to WebDecoy |
| Framework Middleware | Express, Next.js, Fastify integration |
When to Use the SDK
Section titled “When to Use the SDK”| Use Case | SDK Benefit |
|---|---|
| Custom Node.js apps | Full control over detection logic |
| API protection | Server-side request analysis |
| High-traffic sites | Efficient server-side processing |
| Sensitive endpoints | Deep request inspection |
| Custom integrations | Programmatic access to detections |
Installation
Section titled “Installation”Core Package
Section titled “Core Package”npm install webdecoy# oryarn add webdecoyFramework-Specific Packages
Section titled “Framework-Specific Packages”# Expressnpm install @webdecoy/express
# Next.jsnpm install @webdecoy/nextjs
# Fastifynpm install @webdecoy/fastifyRequirements
Section titled “Requirements”- Node.js 16.x or later
- npm 7.x or later
- WebDecoy API key
Basic Usage
Section titled “Basic Usage”Client Initialization
Section titled “Client Initialization”const { WebDecoyClient } = require('webdecoy');
const client = new WebDecoyClient({ apiKey: process.env.WEBDECOY_API_KEY, // Optional settings baseUrl: 'https://api.webdecoy.com', timeout: 10000, retries: 3});Environment Variables
Section titled “Environment Variables”WEBDECOY_API_KEY=sk_live_your_api_key_hereWEBDECOY_ORGANIZATION_ID=org_optional_overrideBasic Detection Analysis
Section titled “Basic Detection Analysis”const { WebDecoyClient, BotDetector } = require('webdecoy');
const client = new WebDecoyClient({ apiKey: process.env.WEBDECOY_API_KEY});
const detector = new BotDetector({ sensitivity: 'medium', allowSearchEngines: true});
// In your request handlerasync function handleRequest(req, res) { // Analyze the request const result = await detector.analyze({ ip: req.ip, userAgent: req.headers['user-agent'], headers: req.headers, url: req.url, method: req.method });
// Check if should block if (result.shouldBlock(75)) { return res.status(403).json({ error: 'Access denied' }); }
// Continue with request // ...}Detection Result Object
Section titled “Detection Result Object”const result = await detector.analyze(request);
// Propertiesresult.score // 0-100 unified threat scoreresult.threatLevel // 'MINIMAL', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'result.botScore // 0-100 bot likelihood scoreresult.flags // Array of detection flagsresult.isBot // Boolean: likely a botresult.isGoodBot // Boolean: known legitimate botresult.botName // Name if identified (e.g., 'Googlebot')result.botCategory // Category (e.g., 'search_engine')result.confidence // 0.0-1.0 confidence level
// Methodsresult.shouldBlock(threshold) // true if score >= thresholdresult.shouldChallenge(threshold)// true if score in challenge rangeresult.shouldLog() // true if score warrants loggingresult.isLegitimate() // true if score < 20Submitting Detections
Section titled “Submitting Detections”// Submit a detection to WebDecoyawait client.submitDetection({ source: 'sdk', ipAddress: req.ip, userAgent: req.headers['user-agent'], url: req.url, method: req.method, threatScore: result.score, flags: result.flags, metadata: { customField: 'value' }});Framework Integration
Section titled “Framework Integration”Express Middleware
Section titled “Express Middleware”const express = require('express');const { webDecoyMiddleware } = require('@webdecoy/express');
const app = express();
// Apply globallyapp.use(webDecoyMiddleware({ apiKey: process.env.WEBDECOY_API_KEY, sensitivity: 'medium', blockThreshold: 75, allowSearchEngines: true, excludePaths: ['/health', '/metrics']}));
// Or apply to specific routesapp.post('/api/login', webDecoyMiddleware({ blockThreshold: 60 }), loginHandler);
app.listen(3000);Express Middleware Options
Section titled “Express Middleware Options”| Option | Default | Description |
|---|---|---|
apiKey | Required | Your WebDecoy API key |
sensitivity | ’medium’ | Detection sensitivity |
blockThreshold | 75 | Score threshold to block |
challengeThreshold | 50 | Score threshold to challenge |
allowSearchEngines | true | Bypass for search bots |
allowSocialBots | true | Bypass for social bots |
excludePaths | [] | Paths to skip |
excludeMethods | [‘OPTIONS’] | HTTP methods to skip |
onDetection | null | Custom detection handler |
onBlock | null | Custom block handler |
Next.js Middleware
Section titled “Next.js Middleware”import { withWebDecoy } from '@webdecoy/nextjs';
export default withWebDecoy({ apiKey: process.env.WEBDECOY_API_KEY, blockThreshold: 75, matcher: ['/api/:path*', '/login']});
export const config = { matcher: ['/api/:path*', '/login']};Next.js API Route Protection
Section titled “Next.js API Route Protection”import { withBotProtection } from '@webdecoy/nextjs';
async function handler(req, res) { res.json({ message: 'Protected content' });}
export default withBotProtection(handler, { blockThreshold: 70});Fastify Plugin
Section titled “Fastify Plugin”const fastify = require('fastify')();const webDecoyPlugin = require('@webdecoy/fastify');
fastify.register(webDecoyPlugin, { apiKey: process.env.WEBDECOY_API_KEY, sensitivity: 'medium', blockThreshold: 75});
fastify.get('/protected', async (request, reply) => { // Detection info available on request const botScore = request.webDecoy.score; return { score: botScore };});
fastify.listen({ port: 3000 });Advanced Features
Section titled “Advanced Features”Custom Signal Collection
Section titled “Custom Signal Collection”const { SignalCollector } = require('webdecoy');
const collector = new SignalCollector();
// Collect signals from requestconst signals = collector.collect({ ip: req.ip, userAgent: req.headers['user-agent'], headers: req.headers, // Optional additional signals tlsFingerprint: req.socket.ja3, cookies: req.cookies, bodySize: req.body ? Buffer.byteLength(JSON.stringify(req.body)) : 0});
// Use with detectorconst result = await detector.analyze(signals);IP Intelligence
Section titled “IP Intelligence”const { IPIntelligence } = require('webdecoy');
const intel = new IPIntelligence(client);
const info = await intel.lookup('192.168.1.100');
// Returns{ ip: '192.168.1.100', country: 'US', city: 'New York', asn: 12345, isp: 'Example ISP', isProxy: false, isVPN: true, isTor: false, isHosting: false, abuseScore: 25, riskLevel: 'low'}TLS Fingerprinting
Section titled “TLS Fingerprinting”const { TLSFingerprinter } = require('webdecoy');
// In your HTTPS serverconst server = https.createServer(options, app);
server.on('secureConnection', (tlsSocket) => { const fingerprint = TLSFingerprinter.fromSocket(tlsSocket); // Store fingerprint for later use tlsSocket.ja3 = fingerprint.ja3; tlsSocket.ja4 = fingerprint.ja4;});Rate Limiting Integration
Section titled “Rate Limiting Integration”const { RateLimiter } = require('webdecoy');
const limiter = new RateLimiter({ windowMs: 60000, // 1 minute maxRequests: 100, keyGenerator: (req) => req.ip, onRateLimit: async (req, key) => { // Submit as detection await client.submitDetection({ source: 'sdk', ipAddress: key, flags: ['rate_limit_exceeded'], threatScore: 60 }); }});
app.use(limiter.middleware());API Reference
Section titled “API Reference”WebDecoyClient
Section titled “WebDecoyClient”const client = new WebDecoyClient(options);
// Methodsclient.testConnection() // Verify API keyclient.submitDetection(detection) // Submit detectionclient.getDetections(filters) // Query detectionsclient.blockIP(ip, hours, reason) // Manual IP blockclient.unblockIP(ip) // Remove IP blockBotDetector
Section titled “BotDetector”const detector = new BotDetector(options);
// Methodsdetector.analyze(request) // Analyze requestdetector.setConfig(options) // Update configurationdetector.getSignalCollector() // Get signal collectorDetection Object
Section titled “Detection Object”const detection = { source: 'sdk', ipAddress: '192.168.1.100', userAgent: 'Mozilla/5.0...', url: '/api/endpoint', method: 'POST', threatScore: 75, botScore: 80, flags: ['headless_browser', 'missing_headers'], mitreTactic: { id: 'TA0043', name: 'Reconnaissance' }, metadata: { // Custom fields }};Error Handling
Section titled “Error Handling”const { WebDecoyError, RateLimitError, AuthError } = require('webdecoy');
try { await client.submitDetection(detection);} catch (error) { if (error instanceof AuthError) { console.error('Invalid API key'); } else if (error instanceof RateLimitError) { console.error('Rate limited, retry after:', error.retryAfter); } else if (error instanceof WebDecoyError) { console.error('API error:', error.message); } else { throw error; }}Best Practices
Section titled “Best Practices”Performance
Section titled “Performance”- Initialize client once, reuse across requests
- Use async/await for non-blocking detection
- Cache IP intelligence lookups
- Use exclude patterns for static assets
Security
Section titled “Security”- Store API key in environment variables
- Validate detection results before blocking
- Log detection decisions for audit
- Set appropriate timeout values
Integration
Section titled “Integration”- Start with logging mode before blocking
- Monitor false positive rates
- Adjust thresholds based on traffic
- Combine with client-side bot scanner
Example: Complete Express App
Section titled “Example: Complete Express App”const express = require('express');const { WebDecoyClient, BotDetector } = require('webdecoy');const { webDecoyMiddleware } = require('@webdecoy/express');
const app = express();
// Initialize clientconst client = new WebDecoyClient({ apiKey: process.env.WEBDECOY_API_KEY});
// Global protection (logging mode)app.use(webDecoyMiddleware({ apiKey: process.env.WEBDECOY_API_KEY, blockThreshold: 90, // Only block very high scores onDetection: (req, result) => { console.log(`Detection: ${req.ip} - Score: ${result.score}`); }}));
// Stricter protection for sensitive endpointsapp.post('/api/login', webDecoyMiddleware({ apiKey: process.env.WEBDECOY_API_KEY, blockThreshold: 60, sensitivity: 'high' }), async (req, res) => { // Login logic });
// Custom detection logicapp.post('/api/checkout', async (req, res) => { const detector = new BotDetector({ sensitivity: 'high' });
const result = await detector.analyze({ ip: req.ip, userAgent: req.headers['user-agent'], headers: req.headers });
if (result.shouldBlock(70)) { await client.submitDetection({ source: 'sdk', ipAddress: req.ip, url: '/api/checkout', threatScore: result.score, flags: result.flags }); return res.status(403).json({ error: 'Request blocked' }); }
// Process checkout});
app.listen(3000);