@munesoft/securex
v1.0.10
Published
The most advanced, self-configuring security middleware for Node.js — smart headers, CSP auto-generation, rate limiting, anomaly detection, and more in one line.
Maintainers
Readme
@munesoft/securex
The most advanced, self-configuring security middleware for Node.js smart HTTP security headers, CSP auto-generation, rate limiting, bot detection, anomaly detection, CSRF protection, and more. One line. Full protection.
import securex from "@munesoft/securex";
app.use(securex());📋 Table of Contents
- What is securex?
- Why Not Existing Tools?
- Features
- Quick Start
- Examples
- Advanced Usage
- Security Concepts
- CLI
- Framework Support
- Comparison
- API Reference
- Plugin System
- FAQ
What is securex?
securex is a next-generation Node.js security middleware that goes far beyond traditional header-setting tools. It is designed for developers who want strong security by default, with zero boilerplate.
Unlike tools that require manual configuration of dozens of options, securex:
- Auto-configures based on your environment (
development,production,testing) - Analyzes your HTML to auto-generate accurate Content-Security-Policy rules
- Detects bots, anomalies, and attack patterns in real-time
- Guides you with actionable, inline dev-mode insights
- Scores your security configuration via CLI
securex is designed to become the default security layer for every new Node.js project.
Why Not Existing Tools?
| Problem | Traditional Tools | securex |
|---|---|---|
| Setup time | Hours of config | One line |
| CSP generation | Manual, error-prone | Auto-detected from HTML |
| Environment awareness | Manual per-env configs | Built-in auto mode |
| Dev feedback | Silent | Inline warnings + suggestions |
| Bot detection | Not included | Built-in |
| Anomaly detection | Not included | Built-in |
| Security scoring | External tools needed | npx securex analyze |
| Rate limiting | Separate package needed | Built-in |
| CSRF protection | Separate package needed | Built-in |
| Plugin system | Limited | Extensible |
Features
🔒 Smart Security Headers
Automatically sets all modern HTTP security headers:
Content-Security-Policy(dynamic or auto-generated)Strict-Transport-Security(production only)X-Frame-OptionsReferrer-PolicyX-Content-Type-OptionsPermissions-PolicyCross-Origin-Opener-PolicyCross-Origin-Resource-PolicyCross-Origin-Embedder-Policy
🧠 AI-Like CSP Generator
The killer feature. Pass csp: "auto" and securex will analyze your outgoing HTML, detect external scripts, stylesheets, and images, and build Content-Security-Policy rules automatically — updating them dynamically as your app evolves.
🌍 Environment-Aware Modes
- Development → relaxed rules + inline developer warnings
- Production → strict enforcement, HSTS enabled
- Testing → silent mode, no output
⚡ Built-in Rate Limiting
IP-based rate limiting with adaptive throttling and burst protection — no extra package needed.
🤖 Bot & Anomaly Detection
Detect and block known security scanners (sqlmap, nikto, nmap, etc.), path traversal attempts, SQL injection probes, and XSS patterns.
🛡️ CSRF Protection
Token-based CSRF protection with automatic cookie generation and header/body validation.
🧹 Input Sanitization
Automatic XSS sanitization of request body and query parameters.
📊 Security Score Engine
Run npx securex analyze to get a visual security score and actionable recommendations for your configuration.
🔌 Plugin System
Extend securex with custom plugins for additional functionality.
Quick Start
Install
npm install @munesoft/securexOne-line setup (Express)
import express from "express";
import securex from "@munesoft/securex";
const app = express();
app.use(securex());That's it. You now have:
- All security headers set
- Environment-aware defaults
- Dev-mode insights in your console
Examples
Basic Usage
import securex from "@munesoft/securex";
// Zero config — auto-detects environment
app.use(securex());CSP Auto Mode
app.use(securex({
csp: "auto",
}));securex intercepts outgoing HTML responses, scans for external scripts, styles, and images, and auto-generates your CSP. In dev mode, it logs:
[securex] ⚠️ External script detected: https://cdn.jsdelivr.net
👉 Add 'https://cdn.jsdelivr.net' to your CSP script-src allowlist
[securex] ⚠️ Inline script detected
👉 Use nonces or hashes in CSP to allow inline scripts safelyRate Limiting
app.use(securex({
rateLimit: {
windowMs: 60_000, // 1 minute
max: 100, // max 100 requests per IP
burst: 20, // allow 20-request burst
},
}));CORS Auto Configuration
// Development: auto-learn and warn about new origins
app.use(securex({ cors: "auto" }));
// Production: explicit allowlist
app.use(securex({
cors: {
origins: ["https://app.example.com", "https://admin.example.com"],
credentials: true,
},
}));Production Setup
app.use(securex({
mode: "production",
strict: true,
headers: true,
csp: {
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "https://cdn.example.com"],
"style-src": ["'self'", "https://fonts.googleapis.com"],
},
},
cors: {
origins: ["https://yourapp.com"],
credentials: true,
},
rateLimit: {
windowMs: 60_000,
max: 200,
},
csrf: true,
sanitize: true,
botDetection: true,
anomalyDetection: true,
logging: {
level: "warn",
format: "json",
onEvent: (event) => myLogger.log(event),
},
}));CSRF Protection
app.use(cookieParser()); // required for CSRF cookie reading
app.use(securex({ csrf: true }));
// In your HTML form:
// <input type="hidden" name="_csrf" value="<%= csrfToken %>">
// Or in your API client:
// headers: { "x-csrf-token": token }Full Feature Example
app.use(securex({
mode: "auto", // auto-detect environment
strict: false,
silent: false,
headers: true,
csp: "auto",
cors: "auto",
rateLimit: true,
csrf: true,
sanitize: true,
botDetection: true,
anomalyDetection: true,
logging: true,
plugins: [
// require("securex-bot-shield"),
],
}));Advanced Usage
Strict Mode
Maximum security enforcement. Enables HSTS with preload, DENY framing, strict CSP defaults, and all detection features.
app.use(securex({ strict: true }));Silent Mode (CI/CD)
app.use(securex({ silent: true }));Custom Security Headers
app.use(securex({
headers: {
"X-Custom-Security": "enabled",
"Server": false, // remove header
},
}));Custom Rate Limit Key
Rate-limit by API key instead of IP:
app.use(securex({
rateLimit: {
max: 1000,
keyGenerator: (req) => req.headers["x-api-key"] ?? req.ip,
},
}));Logging & Monitoring
app.use(securex({
logging: {
level: "warn",
format: "json",
onEvent: (event) => {
// event: { type, timestamp, ip, path, userAgent, detail, severity }
if (event.severity === "critical") {
pagerDuty.trigger(event);
}
datadog.metric("security_event", { type: event.type });
},
},
}));Trust Proxy
app.use(securex({
trustProxy: true, // use X-Forwarded-For for IP detection
rateLimit: true,
}));Security Concepts
Content Security Policy (CSP)
CSP is an HTTP header that tells browsers which sources of scripts, styles, images, and other content are trusted. A well-configured CSP is one of the strongest defenses against XSS attacks.
securex's csp: "auto" mode analyzes your actual HTML responses to build accurate CSP rules, eliminating the guesswork.
HTTP Strict Transport Security (HSTS)
Tells browsers to always use HTTPS for your domain. securex enables this automatically in production with a 1-year max-age. In strict mode, it adds preload for HSTS preload list eligibility.
CSRF Protection
Cross-Site Request Forgery attacks trick authenticated users into submitting malicious requests. securex generates a cryptographically random token per session and validates it on all state-changing requests.
Rate Limiting
Prevents brute force, credential stuffing, scraping, and DoS attacks. securex uses an in-memory sliding window with burst support.
Anomaly Detection
securex monitors request patterns for path traversal, SQL injection probes, XSS attempts, and other common attack signatures, blocking or alerting as appropriate.
CLI
# Analyze your securex config and get a security score
npx securex analyze
# Analyze with a specific config file
npx securex analyze --config ./myconfig.js
# Output as JSON (for CI pipelines)
npx securex analyze --json
# Check HTTP headers of a live URL
npx securex check-headers --url https://yourapp.com
# Generate a starter config file
npx securex initExample output
╔════════════════════════════════════╗
║ @munesoft/securex — Score Report ║
╚════════════════════════════════════╝
Overall Score: 87/100 ██████████████████████████░░░░
✔ Security Headers 20/20
✔ CSP 20/20
✔ CORS 15/15
✔ Rate Limiting 15/15
✖ CSRF Protection 0/10
→ CSRF protection disabled
✔ Input Sanitization 10/10
⚠ Threat Detection 7/10
→ Bot detection not enabled
Recommendations:
💡 Enable CSRF: securex({ csrf: true })
💡 Enable: securex({ botDetection: true, anomalyDetection: true })Framework Support
Express
import express from "express";
import securex from "@munesoft/securex";
const app = express();
app.use(express.json());
app.use(securex());Fastify
import Fastify from "fastify";
import securex from "@munesoft/securex";
const fastify = Fastify();
fastify.addHook("onRequest", (request, reply, done) => {
securex()(request.raw, reply.raw, done);
});Next.js (API Routes)
// middleware.ts
import { NextResponse } from "next/server";
import securex from "@munesoft/securex";
export function middleware(request) {
const response = NextResponse.next();
// Apply headers manually or use the score engine for config guidance
return response;
}Or wrap individual API routes:
// pages/api/[...].ts
import securex from "@munesoft/securex";
import { createServer } from "http";
const security = securex({ silent: true, headers: true, rateLimit: true });
export default function handler(req, res) {
security(req, res, () => {
// your handler logic
});
}Comparison
| Feature | securex | helmet | cors | express-rate-limit | csurf | |---|:---:|:---:|:---:|:---:|:---:| | Security headers | ✅ | ✅ | ❌ | ❌ | ❌ | | Auto CSP generation | ✅ | ❌ | ❌ | ❌ | ❌ | | Environment-aware | ✅ | ❌ | ❌ | ❌ | ❌ | | Dev-mode insights | ✅ | ❌ | ❌ | ❌ | ❌ | | Rate limiting | ✅ | ❌ | ❌ | ✅ | ❌ | | Bot detection | ✅ | ❌ | ❌ | ❌ | ❌ | | Anomaly detection | ✅ | ❌ | ❌ | ❌ | ❌ | | CSRF protection | ✅ | ❌ | ❌ | ❌ | ✅ | | Input sanitization | ✅ | ❌ | ❌ | ❌ | ❌ | | CORS handling | ✅ | ❌ | ✅ | ❌ | ❌ | | Security score CLI | ✅ | ❌ | ❌ | ❌ | ❌ | | Plugin system | ✅ | ❌ | ❌ | ❌ | ❌ | | Zero config | ✅ | ❌ | ❌ | ❌ | ❌ | | Packages needed | 1 | 1+ | +1 | +1 | +1 |
API Reference
securex(options?)
Returns an Express-compatible middleware function.
Options
| Option | Type | Default | Description |
|---|---|---|---|
| mode | "auto" \| "development" \| "production" \| "testing" | "auto" | Security mode. Auto-detects NODE_ENV. |
| strict | boolean | false | Maximum security: DENY framing, preload HSTS, strict CSP. |
| silent | boolean | false | Suppress all console output. |
| headers | boolean \| object | true | Security headers. Pass an object to override specific headers. |
| csp | boolean \| "auto" \| CspOptions | undefined | CSP configuration. "auto" = HTML analysis mode. |
| cors | boolean \| "auto" \| CorsOptions | undefined | CORS configuration. |
| rateLimit | boolean \| RateLimitOptions | undefined | Rate limiting. |
| csrf | boolean \| CsrfOptions | undefined | CSRF protection. |
| sanitize | boolean | undefined | Input sanitization (body + query). |
| botDetection | boolean | undefined | Block known scanner UAs. |
| anomalyDetection | boolean | undefined | Block suspicious request patterns. |
| logging | boolean \| LoggingOptions | undefined | Security event logging. |
| plugins | SecurexPlugin[] | [] | Plugin list. |
| trustProxy | boolean | false | Trust X-Forwarded-For for IP detection. |
Plugin System
Plugins let you extend securex with custom middleware that integrates seamlessly into the security pipeline.
Creating a plugin
// securex-my-plugin/index.js
module.exports = {
name: "my-plugin",
version: "1.0.0",
install(options) {
return function(req, res, next) {
// your logic here
next();
};
},
};Using plugins
app.use(securex({
plugins: [
require("securex-my-plugin"),
require("securex-bot-shield"),
],
}));FAQ
Q: Does securex work with TypeScript?
A: Yes — it's written in TypeScript and ships full type definitions.
Q: Will it break my existing Express middleware?
A: No. securex is fully non-breaking. It adds headers and may block malicious requests, but won't interfere with normal request handling.
Q: How is csp: "auto" different from manual CSP?
A: In auto mode, securex intercepts outgoing HTML responses and scans them for external scripts, stylesheets, and images, then builds the CSP header dynamically. This means you never miss a resource — your CSP stays in sync with your actual HTML automatically.
Q: Can I use securex without Express?
A: securex returns a standard (req, res, next) middleware compatible with any Node.js HTTP framework.
Q: Does rate limiting persist across server restarts?
A: The built-in rate limiter uses in-memory storage and resets on restart. For persistent rate limiting in distributed systems, implement a custom keyGenerator backed by Redis.
Q: Is securex production-ready?
A: Yes. Set mode: "production" (or use NODE_ENV=production) for full enforcement including HSTS, strict CORS, and all detection features.
Q: How do I disable a specific header?
A: Pass it as false in the headers object:
securex({ headers: { "X-Frame-Options": false } })License
MIT © munesoft
Keywords
node.js security, express security middleware, HTTP security headers, CSP generator, API protection, web security, CSRF protection, XSS prevention, rate limiting, bot detection, anomaly detection, HSTS, CORS, helmet alternative
