secure-express-setup
Version:
Military-grade one-command security setup for Express.js applications
462 lines (330 loc) โข 9.55 kB
Markdown
# ๐ก๏ธ Secure Express Setup
**One-Command Military-Grade Security for Express.js**
[](https://www.npmjs.com/package/secure-express-setup)
[](https://opensource.org/licenses/MIT)
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:
```javascript
secureSetup(app); // DONE โ
```
Everything is preconfigured.
**And you also get:**
```javascript
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.regenerateSession
```
All ready to use โ no imports, no setup.
## ๐ฆ Installation
```bash
npm install secure-express-setup
```
## ๐ Quick Start (Zero-Config Mode)
```javascript
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_SECRET` is set)
- โ
JWT helper (if `JWT_SECRET` is set)
- โ
Encryption helper (if `ENCRYPTION_KEY` is set)
- โ
File upload validation helper
- โ
Helper factories for API keys, webhook signatures, OAuth, RBAC
---
## ๐ฅ Understanding How Helpers Work
After you run:
```javascript
secureSetup(app);
```
You automatically get:
```javascript
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.regenerateSession
```
**Everything below uses only `app.locals`, no extra imports.**
---
## ๐งฉ Usage Examples (Developer-Friendly)
### 1๏ธโฃ JWT Authentication
#### Generate token on login
```javascript
app.post("/login", (req, res) => {
const token = app.locals.jwtHelper.sign({
id: 1,
role: "admin"
});
res.json({ token });
});
```
#### Protect route
```javascript
app.get("/me", app.locals.jwtHelper.protect, (req, res) => {
res.json({ user: req.user });
});
```
#### Refresh token
```javascript
app.post("/refresh", (req, res) => {
const newToken = app.locals.jwtHelper.refresh(req.body.token);
res.json({ token: newToken });
});
```
### 2๏ธโฃ API Key Authentication
```javascript
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
```javascript
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:
```javascript
const hash = app.locals.encryption.hash("password123");
```
### 4๏ธโฃ File Upload Validation
```javascript
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
```javascript
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)
```javascript
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)
```javascript
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:
```javascript
await app.locals.regenerateSession(req);
req.session.userId = user.id;
```
#### Destroy session:
```javascript
req.session.destroy(() => res.json({ loggedOut: true }));
```
## โ๏ธ Advanced Configuration (Optional)
```javascript
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
```bash
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)
```env
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
```javascript
app.locals.jwtHelper.sign(payload, expiresIn)
app.locals.jwtHelper.verify(token)
app.locals.jwtHelper.protect // Middleware
app.locals.jwtHelper.refresh(token)
```
#### Encryption Helper
```javascript
app.locals.encryption.encrypt(data)
app.locals.encryption.decrypt(encrypted)
app.locals.encryption.hash(password)
```
#### Helper Factories
```javascript
app.locals.helpers.apiKey(options)
app.locals.helpers.webhookSignature(options)
app.locals.helpers.oauth(options)
app.locals.helpers.rbac(allowedRoles)
```
#### File Validation
```javascript
app.locals.fileValidation.validateFile(file, allowedTypes)
app.locals.fileValidation.middleware(allowedTypes)
```
#### Session Management
```javascript
app.locals.regenerateSession(req)
app.locals.bruteForce // Rate limiter instance
```
## ๐จโ๐ป Author
**Raghav Sharma**
- GitHub: [@0Raghav-Sharma0](https://github.com/0Raghav-Sharma0)
- npm: [secure-express-setup](https://www.npmjs.com/package/secure-express-setup)
## โญ Show Support
If this package saved you hours of pain, drop a โญ on [GitHub](https://github.com/0Raghav-Sharma0/secure-express-setup)!
## ๐ License
MIT ยฉ Raghav Sharma
## ๐ค Contributing
Contributions, issues, and feature requests are welcome!
Feel free to check the [issues page](https://github.com/0Raghav-Sharma0/secure-express-setup/issues).
## ๐ Additional Resources
- [Express.js Documentation](https://expressjs.com/)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Node.js Security Best Practices](https://nodejs.org/en/docs/guides/security/)
**Made with โค๏ธ by developers, for developers**