secure-web-kit
v1.0.1
Published
Comprehensive security toolkit for web applications - XSS protection, rate limiting, JWT, CSRF, and 60+ security features
Maintainers
Readme
🔐 secure-web-kit
Comprehensive security toolkit for web applications with 64+ security features. Built for Node.js/Express applications.
✨ Features
Core Security
- XSS Protection - Input sanitization, removes script tags, HTML injection, inline JS
- Validation Engine - Email, URL, number, min/max, regex, custom rules
- Rate Limiter - Prevent brute force, spam, bot attacks
- CSRF Protection - Token-based security
- Secure Cookie - httpOnly, secure, sameSite attributes
Advanced Security
- IP Block/Allow - Block or allow specific IPs
- Request Logger - Logs IP, route, response time
- Security Headers - CSP, X-Frame-Options, HSTS
- Env Validator - Validate required environment variables
- URL Safety Checker - Detect suspicious TLDs, short links, HTTP
- File Upload Guard - Size limits, type validation, dangerous extensions
- Password Strength Checker - Score + suggestions
JWT & Authentication
- JWT Guard - Token verification, expiry check, tampering detection
- JWT Sign - Create JWT tokens
- Session Security - Session expiry, IP binding, device binding
- API Key Manager - Key validation, usage tracking
- OTP Security - Create and verify OTPs with expiry
Monitoring & Detection
- Request Analytics - Total requests, blocked attacks, rate limit hits
- Suspicious Behavior Detector - Failed logins, bot patterns
- Pattern Attack Detection - SQL injection, XSS, encoded payloads
- Risk Score Engine - Score 0-100 for requests
- Audit Logs - Track login, failed attempts, blocked IPs
Advanced Features
- Geo-IP Block - Block specific countries
- Webhook Signature Validator - Prevent fake webhooks
- Error Shield - Hide sensitive errors in production
- Honeypot Field - Trap bots
- Data Masking - Mask phone, email, sensitive data
- Fingerprint Generator - Device fingerprinting
- Replay Protection - Block duplicate requests
- Adaptive Rate Limiting - Smart throttling
- Config Profiles - banking, startup, public-api presets
- Ultra Mode - Enable everything with one line
🚀 Quick Start
npm install secure-web-kitBasic Usage
const express = require('express');
const app = express();
const {
sanitizeInput, validate, rateLimit, secureHeaders,
jwtGuard, csrfProtect, secureApp, ultraSecure
} = require('secure-web-kit');
// XSS Protection
const userInput = sanitizeInput("<script>alert('hack')</script>");
// Output: alert('hack')
// Validation
const result = validate(
{ email: "[email protected]", password: "12345678" },
{ email: "required|email", password: "required|min:8" }
);
// Rate Limiting
app.use(rateLimit({ limit: 100, window: "1m" }));
// Security Headers
app.use(secureHeaders());
// JWT Guard
app.use(jwtGuard());
// All-in-One
app.use(ultraSecure());📖 API Reference
Input Sanitization
sanitizeInput(input: string): stringRemoves script tags, HTML tags, inline event handlers, javascript: URIs.
Validation
validate(data: object, rules: object): ValidationResultRules: required, email, url, number, min, max, regex, alpha, alphanumeric
Rate Limiting
rateLimit(options: { limit: number, window: string, message?: string })Window format: 1s, 1m, 1h
JWT
jwtSign(payload: object, expiresIn?: number): string
jwtVerify(token: string): { valid: boolean, payload?: object, error?: string }
jwtGuard(): MiddlewareSecure App (All-in-One)
secureApp(options?: {
rateLimit?: RateLimitOptions,
csrf?: CsrfOptions | boolean,
ipGuard?: IpGuardOptions,
logger?: boolean
})Config Profiles
secureAppWithProfile("banking") // Strict: low rate limit, JWT, geo block
secureAppWithProfile("startup") // Moderate: rate limit, CSRF
secureAppWithProfile("public-api") // Loose: high rate limitOther Functions
| Function | Description |
|----------|-------------|
| csrfProtect() | CSRF token middleware |
| setSecureCookie(options) | Set secure cookie |
| ipGuard(options) | Block/allow IPs |
| requestLogger() | Log requests |
| checkEnv(rules) | Validate env vars |
| isSafeURL(url) | Check URL safety |
| fileGuard(file, options) | Validate file uploads |
| checkPassword(password) | Password strength |
| checkDevMode() | Dev warnings |
| schema(rules) | Schema validation |
| normalizeInput(data) | Trim & normalize |
| preventDuplicate() | Block duplicates |
| apiKeyAuth(options) | API key validation |
| getStats() | Request analytics |
| detectAbuse(req) | Detect abuse |
| scanFile(file) | Scan for malware |
| smartCORS() | Smart CORS |
| honeypot() | Bot trap |
| retryBlock() | Block retry attacks |
| createSession() | Create secure session |
| getFingerprint(req) | Generate fingerprint |
| isDisposableEmail(email) | Check disposable email |
| verifyWebhook(req, secret) | Verify webhook signature |
| safeError() | Error handler |
| geoBlock(countries) | Block countries |
| maskData(data, type) | Mask sensitive data |
| detectPatternAttack(input) | Detect attack patterns |
| replayProtect() | Prevent replay attacks |
| createOTP() / verifyOTP() | OTP generation/verification |
| checkDataLeak(data) | Detect data leaks |
| addAuditLog() / getAuditLogs() | Audit logging |
| createRule() / runRules() | Custom rules |
| adaptiveRateLimit() | Smart rate limiting |
| behaviorGuard() | Behavior-based access |
| signRequest() / verifyRequest() | Request signatures |
| createSecureStorage() | Encrypted storage |
| useFormShield() | Form protection |
| checkRisk(req) | Risk detection |
| rotateToken(token) | Token rotation |
| checkSecretAccess() | Secret access guard |
| getLiveSecurityData() | Live security dashboard |
| onThreat(callback) | Alert system |
| getRequestRisk(req) | Risk score (0-100) |
| usePlugin() | Plugin system |
| createSecurityMiddleware() | Custom middleware |
| initWizard(answers) | Auto setup |
| enableDebug() | Debug mode |
| ultraSecure() | Everything enabled |
🔧 CLI Tools
Security Scan
npx secure-web-kit scanScans project for security issues (hardcoded secrets, XSS, SQL injection, etc.)
📝 TypeScript Support
import {
sanitizeInput, validate, rateLimit, jwtGuard,
secureApp, ValidationResult, RateLimitOptions
} from 'secure-web-kit';
const result: ValidationResult = validate(data, rules);✅ Testing
npm test📦 Bundle Size
Tree-shakable - only imports used functions.
🔒 Security
- No external dependencies (zero-dep)
- TypeScript for type safety
- ESM + CommonJS compatible
📄 License
MIT License - see LICENSE
👤 Author
codeble.dev - [email protected]
