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 🙏

© 2026 – Pkg Stats / Ryan Hefner

secure-endpoint-server

v1.0.7

Published

Express security middleware bundle

Readme

Secure Endpoint Server

A comprehensive Express security middleware suite that provides enterprise-grade protection for your Node.js APIs. Bundle multiple security layers including CSRF protection, device fingerprinting, replay attack prevention, WAF capabilities, and HMAC-based payload encryption.

Features

  • 🛡️ CSRF Protection: Cross-Site Request Forgery token validation
  • 📱 Device Fingerprinting: Track and verify device signatures
  • 🔄 Replay Protection: Prevent replay attacks using nonce validation
  • 🔐 Security Headers: Automatic security header injection (CSP, HSTS, etc.)
  • 🚨 Web Application Firewall: Pattern-based request filtering
  • 🔑 HMAC Encryption: Payload signing and verification
  • ⚙️ Modular Design: Enable only the middlewares you need
  • 🎯 LRU Caching: Efficient nonce and fingerprint caching
  • 📍 Path Skipping: Exclude specific routes from security checks
  • Zero Configuration: Works with sensible defaults

Installation

npm install secure-endpoint-server

Or with yarn:

yarn add secure-endpoint-server

Quick Start

import express from "express";
import secureEndpoint from "secure-endpoint-server";

const app = express();
app.use(express.json());

// Apply all security middlewares with defaults
const securityMiddlewares = secureEndpoint();
app.use(...securityMiddlewares);

app.post("/api/data", (req, res) => {
  res.json({ success: true });
});

app.listen(3000);

Configuration

Basic Setup with Options

import secureEndpoint from "secure-endpoint-server";

const securityMiddlewares = secureEndpoint(
  {
    csrfOptions: {
      cookieName: "XSRF-TOKEN",
      headerName: "X-XSRF-TOKEN",
    },
    securityHeadersOptions: {
      frameguard: { action: "deny" },
      hsts: { maxAge: 31536000 },
    },
    deviceFingerprintOptions: {
      headerName: "X-Device-Fingerprint",
    },
    replayProtectionOptions: {
      windowSize: 1000,
      ttl: 300000, // 5 minutes
    },
    wafOptions: {
      // WAF configuration
    },
    payloadSecurityOptions: {
      algorithm: "aes-256-cbc",
      encoding: "base64",
    },
  },
  ["/", "/health", "/login"], // Skip paths
);

app.use(...securityMiddlewares);

Middleware Configuration

CSRF Protection

{
  csrfOptions: {
    cookieName?: string;        // Default: '_csrf'
    headerName?: string;         // Default: 'X-CSRF-Token'
    value?: string;              // Custom CSRF token value
  }
}

Security Headers

{
  securityHeadersOptions: {
    frameguard?: { action: 'deny' | 'sameorigin' };
    hsts?: { maxAge: number; includeSubDomains?: boolean };
    contentSecurityPolicy?: { directives: Record<string, string[]> };
    xContentTypeOptions?: 'nosniff';
    referrerPolicy?: { policy: string };
  }
}

Device Fingerprinting

{
  deviceFingerprintOptions: {
    headerName?: string;  // Default: 'x-device-fingerprint'
  }
}

Replay Protection

{
  replayProtectionOptions: {
    windowSize?: number;  // Default: 1000
    ttl?: number;         // Nonce TTL in ms, Default: 5 minutes
    store?: {
      max?: number;       // Max cache entries
      ttl?: number;       // Cache TTL in ms
    }
  }
}

Web Application Firewall

{
  wafOptions: {
    // Pattern-based filtering rules
    blockedPatterns?: RegExp[];
    allowedMethods?: string[];
  }
}

HMAC Payload Encryption

{
  payloadSecurityOptions: {
    algorithm: 'aes-256-cbc';
    encoding: 'base64';
    saltLength?: number;
  }
}

Usage Examples

Express Integration

import express from "express";
import secureEndpoint from "secure-endpoint-server";

const app = express();
app.use(express.json());

// Apply security middleware
const security = secureEndpoint(
  {
    csrfOptions: { cookieName: "XSRF-TOKEN" },
    securityHeadersOptions: { hsts: { maxAge: 31536000 } },
    deviceFingerprintOptions: { headerName: "X-Device-Fingerprint" },
  },
  ["/health", "/status"], // Routes to skip
);

app.use(...security);

app.post("/api/users", (req, res) => {
  // CSRF, replay protection, device fingerprinting all checked
  res.json({ id: 1, name: req.body.name });
});

Selective Middleware Application

// Apply only specific middlewares to certain routes
const app = express();
const security = secureEndpoint();

app.use(...security); // Apply to all routes

// Or apply selectively:
const csrfOnly = secureEndpoint({ csrfOptions: { cookieName: "XSRF" } }, [
  "/api/*",
]);
app.post("/api/submit", ...csrfOnly, (req, res) => {
  res.json({ success: true });
});

Production Configuration

import secureEndpoint from "secure-endpoint-server";

const production = secureEndpoint(
  {
    securityHeadersOptions: {
      frameguard: { action: "deny" },
      hsts: { maxAge: 63072000 }, // 2 years
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          scriptSrc: ["'self'", "'unsafe-inline'"],
        },
      },
      xContentTypeOptions: "nosniff",
      referrerPolicy: { policy: "strict-origin-when-cross-origin" },
    },
    csrfOptions: {
      cookieName: "__Host-XSRF-TOKEN", // HttpOnly, Secure
      headerName: "X-XSRF-TOKEN",
    },
    replayProtectionOptions: {
      windowSize: 5000,
      ttl: 600000, // 10 minutes
    },
  },
  [],
);

API Reference

Exported Functions

secureEndpoint(options?, skipPaths?)

Returns an array of Express middleware functions.

  • options (optional): Security configuration object
  • skipPaths (optional): Array of routes to exclude from security checks
  • Returns: Express.RequestHandler[] - Array of middleware functions

createCsrfProtection(config)

CSRF protection middleware

createDeviceFingerprintMiddleware(config)

Device fingerprinting middleware

createReplayProtection(config)

Replay attack prevention middleware

createSecurityHeaders(config)

Security headers injection middleware

createWaf(config)

Web Application Firewall middleware

createPayloadSecurity(config)

Payload encryption/signing middleware

createMemoryNonceStore(max, ttl)

In-memory nonce store with LRU cache

Security Best Practices

  1. Always use HTTPS in production
  2. Enable all middlewares unless there's a specific reason not to
  3. Rotate secrets regularly for HMAC signing
  4. Configure CSP headers appropriately for your content
  5. Test security settings with your frontend client
  6. Monitor failed security checks in your logs
  7. Update dependencies regularly for security patches
  8. Use secure cookies with HttpOnly and Secure flags

Performance Considerations

  • LRU cache limits prevent memory exhaustion with bounded storage
  • Nonce TTL prevents unbounded growth of validation data
  • Security headers are lightweight string additions
  • WAF pattern matching is optimized for common attacks
  • Device fingerprinting uses efficient hashing

Troubleshooting

CSRF Token Validation Fails

  • Ensure cookie name matches between client and server
  • Verify token is being sent in the correct header
  • Check that cookies are enabled on the client

Device Fingerprint Mismatch

  • Verify clients are sending the fingerprint header
  • Check that device fingerprint algorithm is consistent

Replay Protection Rejections

  • Increase nonce window size if legitimate requests are rejected
  • Verify clock synchronization between client and server
  • Check that nonce TTL is appropriate for your use case

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT