UNPKG

secure-express-setup

Version:

Military-grade one-command security setup for Express.js applications

462 lines (330 loc) โ€ข 9.55 kB
# ๐Ÿ›ก๏ธ Secure Express Setup **One-Command Military-Grade Security for Express.js** [![npm version](https://badge.fury.io/js/secure-express-setup.svg)](https://www.npmjs.com/package/secure-express-setup) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](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**