secure-express-setup
v3.0.5
Published
Military-grade one-command security setup for Express.js applications
Maintainers
Readme
🛡️ Secure Express Setup
One-Command Military-Grade Security for Express.js
Secure your Express.js app with 15+ security layers, zero configuration, one command, and full helper APIs.
⚡ What This Library Does
Normally, to secure an Express app, you need:
- Helmet
- Rate Limiting
- CORS
- XSS clean
- NoSQL injection sanitizer
- SQL injection filters
- HPP
- CSP
- Session security
- JWT setup
- Encryption helper
- Brute-force protection
- IP filtering
- Webhook signature validation
- OAuth setup
- Raw body handling for webhooks
- Logging
- Slowloris attack limiter
- Path traversal block
That's 20+ packages and 200+ lines of config.
With this package:
secureSetup(app); // DONE ✅Everything is preconfigured.
And you also get:
app.locals.jwtHelper
app.locals.encryption
app.locals.fileValidation
app.locals.helpers.apiKey
app.locals.helpers.oauth
app.locals.helpers.webhookSignature
app.locals.helpers.rbac
app.locals.bruteForce
app.locals.regenerateSessionAll ready to use — no imports, no setup.
📦 Installation
npm install secure-express-setup🚀 Quick Start (Zero-Config Mode)
const express = require("express");
const secureSetup = require("secure-express-setup");
const app = express();
// Fully automatic mode
secureSetup(app);
app.get("/", (req, res) => {
res.json({ secure: true });
});
app.listen(3000, () => console.log("Server running on port 3000"));This instantly enables:
- ✅ Helmet (all headers)
- ✅ CORS (safe defaults)
- ✅ Rate Limit
- ✅ Brute Force Protection
- ✅ CSRF (optional)
- ✅ SQL Injection filter
- ✅ NoSQL sanitization
- ✅ XSS filter
- ✅ HPP
- ✅ Path traversal block
- ✅ Slowloris protection
- ✅ Secrets detection
- ✅ Session security (if
SESSION_SECRETis set) - ✅ JWT helper (if
JWT_SECRETis set) - ✅ Encryption helper (if
ENCRYPTION_KEYis set) - ✅ File upload validation helper
- ✅ Helper factories for API keys, webhook signatures, OAuth, RBAC
🔥 Understanding How Helpers Work
After you run:
secureSetup(app);You automatically get:
app.locals.jwtHelper
app.locals.encryption
app.locals.fileValidation
app.locals.helpers.apiKey
app.locals.helpers.webhookSignature
app.locals.helpers.oauth
app.locals.helpers.rbac
app.locals.bruteForce
app.locals.regenerateSessionEverything below uses only app.locals, no extra imports.
🧩 Usage Examples (Developer-Friendly)
1️⃣ JWT Authentication
Generate token on login
app.post("/login", (req, res) => {
const token = app.locals.jwtHelper.sign({
id: 1,
role: "admin"
});
res.json({ token });
});Protect route
app.get("/me", app.locals.jwtHelper.protect, (req, res) => {
res.json({ user: req.user });
});Refresh token
app.post("/refresh", (req, res) => {
const newToken = app.locals.jwtHelper.refresh(req.body.token);
res.json({ token: newToken });
});2️⃣ API Key Authentication
const apiKeyAuth = app.locals.helpers.apiKey({
keys: {
"abc123": { owner: "Test Client", scopes: ["read", "write"] }
}
});
app.get("/data", apiKeyAuth, (req, res) => {
res.json({ client: req.apiKey.owner });
});3️⃣ AES Encryption / Decryption
app.post("/encrypt", (req, res) => {
res.json({ encrypted: app.locals.encryption.encrypt(req.body) });
});
app.post("/decrypt", (req, res) => {
res.json({ decrypted: app.locals.encryption.decrypt(req.body.encrypted) });
});Hashing:
const hash = app.locals.encryption.hash("password123");4️⃣ File Upload Validation
const multer = require("multer");
const upload = multer({ storage: multer.memoryStorage() });
app.post(
"/upload",
upload.single("file"),
app.locals.fileValidation.middleware(["image/png", "application/pdf"]),
(req, res) => res.json({ ok: true })
);5️⃣ Webhook Signature Verification
const verifyWebhook = app.locals.helpers.webhookSignature({
secret: process.env.WEBHOOK_SECRET
});
app.post("/webhook", verifyWebhook, (req, res) => {
res.json({ ok: true });
});6️⃣ Google OAuth (Fully Auto-Wired Passport)
const passport = app.locals.helpers.oauth({
googleClientID: process.env.GOOGLE_CLIENT_ID,
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET
});
app.use(passport.initialize());
app.use(passport.session());
app.get("/auth/google",
passport.authenticate("google", { scope: ["email", "profile"] })
);
app.get("/auth/google/callback",
passport.authenticate("google"),
(req, res) => res.json({ user: req.user })
);7️⃣ Role-Based Access Control (RBAC)
app.get(
"/admin",
app.locals.jwtHelper.protect,
app.locals.helpers.rbac(["admin"]),
(req, res) => res.json({ admin: true })
);RBAC also works with API keys via scopes.
8️⃣ Session Security (Auto-enabled when SESSION_SECRET exists)
Regenerate session on login:
await app.locals.regenerateSession(req);
req.session.userId = user.id;Destroy session:
req.session.destroy(() => res.json({ loggedOut: true }));⚙️ Advanced Configuration (Optional)
secureSetup(app, {
jwtSecret: process.env.JWT_SECRET,
encryptionKey: process.env.ENCRYPTION_KEY,
sessionSecret: process.env.SESSION_SECRET,
cors: { origin: ["https://my.com"], credentials: true },
rateLimit: { windowMs: 60000, max: 50 },
bruteForce: { max: 5 },
csrf: true,
apiKeys: {
"xyz-123": { owner: "Client", scopes: ["read"] }
},
webhookSecret: process.env.WEBHOOK_SECRET,
headers: {
contentSecurityPolicy: "default-src 'self';"
}
});🧪 Testing
npm test # Run unit tests
npm run test:server # Start manual test server
npm run test:client # Run automated client tester
npm run test:all # Run everything🔧 Environment Variables (Optional But Recommended)
JWT_SECRET=your-long-secret
ENCRYPTION_KEY=32-character-encryption-key!!!!
SESSION_SECRET=your-session-secret!!
REDIS_URL=redis://localhost:6379
WEBHOOK_SECRET=your-webhook-secret
GOOGLE_CLIENT_ID=xxxxx
GOOGLE_CLIENT_SECRET=yyyyy
ALLOWED_ORIGINS=https://your.com,https://app.your.com
NODE_ENV=production🔐 Security Layers Enabled (Automatically)
You get protection against:
- ✔️ SQL Injection
- ✔️ NoSQL Injection
- ✔️ XSS
- ✔️ CSRF (optional)
- ✔️ Session Fixation
- ✔️ Directory Traversal
- ✔️ Slowloris
- ✔️ DoS / brute force
- ✔️ Header Manipulation
- ✔️ Secret Leakage
- ✔️ Cookie Tampering
- ✔️ Unauthorized origins
- ✔️ Dangerous uploads
- ✔️ Malicious scripts
- ✔️ Token forgery
- ✔️ OAuth attacks
📦 API Reference
The README above already includes all developer-friendly examples.
Quick Reference:
JWT Helper
app.locals.jwtHelper.sign(payload, expiresIn)
app.locals.jwtHelper.verify(token)
app.locals.jwtHelper.protect // Middleware
app.locals.jwtHelper.refresh(token)Encryption Helper
app.locals.encryption.encrypt(data)
app.locals.encryption.decrypt(encrypted)
app.locals.encryption.hash(password)Helper Factories
app.locals.helpers.apiKey(options)
app.locals.helpers.webhookSignature(options)
app.locals.helpers.oauth(options)
app.locals.helpers.rbac(allowedRoles)File Validation
app.locals.fileValidation.validateFile(file, allowedTypes)
app.locals.fileValidation.middleware(allowedTypes)Session Management
app.locals.regenerateSession(req)
app.locals.bruteForce // Rate limiter instance👨💻 Author
Raghav Sharma
- GitHub: @0Raghav-Sharma0
- npm: secure-express-setup
⭐ Show Support
If this package saved you hours of pain, drop a ⭐ on GitHub!
📄 License
MIT © Raghav Sharma
🤝 Contributing
Contributions, issues, and feature requests are welcome!
Feel free to check the issues page.
📚 Additional Resources
Made with ❤️ by developers, for developers
