npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

secure-express-setup

v3.0.5

Published

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

Readme

🛡️ Secure Express Setup

One-Command Military-Grade Security for Express.js

npm version License: 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:

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.regenerateSession

All 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_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:

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.regenerateSession

Everything 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


⭐ 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