midshield
v1.0.1
Published
Zero-dependency production middleware toolkit for Express and Node.js: rate limiting, security headers, API-key auth, request ID, response time, logger, CORS, and body size limits.
Maintainers
Readme
midshield
Production-ready, zero-dependency security & utility middleware toolkit for Node.js & Express.
MidShield consolidates common API middleware into a single fast, dependency-free toolkit with full TypeScript type definitions and dual ESM/CommonJS support.
Features
- Rate Limiter: Sliding window & token bucket algorithms, IP detection, standard RFC headers (
RateLimit-*,Retry-After), and memory leak protection. - Security Headers: OWASP recommendations (CSP, HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, COOP, CORP) with zero overhead.
- API Key & Bearer Auth: Constant-time verification (
crypto.timingSafeEqual) defending against timing side-channel attacks, with role & metadata attachment. - Request ID: Distributed request tracing with standard UUIDs or custom IDs (
X-Request-Id). - Response Time: Nanosecond precision timing (
process.hrtime.bigint()) viaX-Response-Time. - Request Logger: Dev-friendly ANSI colored output, combined format, and structured JSON logs for production observability.
- CORS: Origin validation (wildcard, list, regex, dynamic functions), preflight OPTIONS handling, and credentials support.
- Body Size Guard: Early Content-Length check & streaming chunk size monitoring to protect against oversized payload DoS.
- Compose Pipeline: Cleanly chains multiple middlewares into a single handler.
- CLI Utility: Built-in
npx midshieldfor mocking, security auditing, and latency benchmarking.
Installation
npm install midshieldQuick Start
Express
const express = require('express');
const { midshield, rateLimiter, apiKeyAuth } = require('midshield');
const app = express();
// 1. One-line preset: Request ID, Response Time, Security Headers & Logger
app.use(midshield());
// 2. Global rate limiter (100 requests per minute)
app.use(rateLimiter({ windowMs: 60 * 1000, max: 100 }));
// 3. Public endpoint
app.get('/api/public', (req, res) => {
res.json({ status: 'ok', requestId: req.id });
});
// 4. Protected endpoint with API key
app.get('/api/secret', apiKeyAuth({ keys: ['my-secret-key'] }), (req, res) => {
res.json({ secret: 'classified data', auth: req.auth });
});
app.listen(3000, () => console.log('Server listening on port 3000'));Native Node.js HTTP (No Framework Required)
const http = require('node:http');
const { compose, requestId, responseTime, securityHeaders, cors } = require('midshield');
const shield = compose(
requestId(),
responseTime(),
securityHeaders(),
cors()
);
const server = http.createServer((req, res) => {
shield(req, res, () => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello World', reqId: req.id }));
});
});
server.listen(4000);API Reference
midshield(options)
All-in-one preset combining core middlewares.
options.requestId: boolean or RequestIdOptionsoptions.responseTime: boolean or ResponseTimeOptionsoptions.security: boolean or SecurityHeadersOptionsoptions.logger: boolean or RequestLoggerOptionsoptions.cors: boolean or CorsOptionsoptions.rateLimit: boolean or RateLimiterOptionsoptions.bodyLimit: boolean or BodyLimitOptions
rateLimiter(options)
windowMs(number): Window duration in ms (default60000).max(number | (req) => number): Allowed requests per window (default100).algorithm('sliding-window' | 'token-bucket'): Default'sliding-window'.trustProxy(boolean | number): Respect proxy headers (defaultfalse).keyGenerator((req) => string): Custom key generator. Defaults to client IP.skip((req) => boolean): Bypass condition.
apiKeyAuth(options)
keys(string | string[] | Record<string, any>): Valid keys or map of keys to metadata.header(string): Header to check (default'x-api-key').bearer(boolean): Also parseAuthorization: Bearer <token>(defaulttrue).validator(async (key, req) => boolean | object): Custom authentication logic.
securityHeaders(options)
contentSecurityPolicy: Custom directive object, string, orfalse.hsts: HSTS options orfalse.frameguard:'SAMEORIGIN','DENY', orfalse.noSniff: boolean (defaulttrue).hidePoweredBy: boolean (defaulttrue).
requestLogger(options)
format:'dev','json','combined','short', or custom function.stream: Writable stream (defaultprocess.stdout).colors: boolean (auto-detected).
cors(options)
origin:'*', string, array, regex, or dynamic function.methods: Array or comma-delimited string of HTTP methods.credentials: boolean.maxAge: Preflight cache seconds.
bodyLimit(options)
max: Human-readable size string (e.g.'100kb','1mb','500b') or number of bytes.
CLI Usage
# Start an instant local mock server with MidShield active
npx midshield serve --port 3000 --cors --rate-limit 100
# Audit HTTP security headers of any website or API
npx midshield inspect https://api.github.com
# Benchmark latency and rate limits
npx midshield benchmark http://localhost:3000/api -n 50 -c 5License
MIT
