@nis2shield/express-middleware
v1.1.2
Published
NIS2 Compliance Middleware for Express.js - Forensic logging, active defense, and security headers
Maintainers
Readme
@nis2shield/express-middleware 🛡️
Enterprise-grade NIS2 Compliance Middleware for Express.js - Forensic logging, active defense, and security audit in a single app.use().
Why this package?
Companies subject to NIS2 Directive need demonstrable compliance. This middleware provides the technical controls required by law:
- Forensic Logging: JSON logs signed with HMAC-SHA256, PII encryption (Art. 21.2.h)
- Rate Limiting: Token bucket algorithm to prevent DoS/Brute Force (Art. 21.2.e)
- IP/Geo Blocking: Block Tor exit nodes, countries, malicious IPs (Art. 21.2.a)
- Session Guard: Detect session hijacking via IP/User-Agent validation
- Multi-SIEM: Direct connectors for Splunk, Datadog, QRadar
- Compliance CLI: Audit your configuration with
npx check-nis2
Part of the NIS2 Shield Ecosystem: Use with
@nis2shield/react-guard,@nis2shield/angular-guard, or@nis2shield/vue-guardfor client-side protection andnis2shield/infrastructurefor a complete, audited full-stack implementation.
┌─────────────────────────────────────────────────────────────┐
│ Frontend │
│ @nis2shield/{react,angular,vue}-guard │
│ ├── SessionWatchdog (idle detection) │
│ ├── AuditBoundary (crash reports) │
│ └── → POST /api/nis2/telemetry/ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Backend (NIS2 Adapter) │
│ **@nis2shield/express-middleware** │
│ ├── ForensicLogger (HMAC signed logs) │
│ ├── RateLimiter, SessionGuard, TorBlocker │
│ └── → SIEM (Elasticsearch, Splunk, QRadar, etc.) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Infrastructure │
│ nis2shield/infrastructure │
│ ├── Centralized Logging (ELK/Splunk) │
│ └── Audited Deployment (Terraform/Helm) │
└─────────────────────────────────────────────────────────────┘✨ Features (v0.3.0)
- 🔐 Forensic Logging: Standardized
NIS2-JSON-SCHEMA v1.0logs with HMAC-SHA256 integrity & PII encryption. - 🚀 Active Defense:
- Rate Limiting: Token bucket algorithm.
- IP Blocking: Block static IPs, Tor exit nodes, and Countries (GeoIP).
- Session Guard: Session hijacking protection (IP/User-Agent).
- 🚨 Multi-SIEM Support: Direct connectors for Splunk HEC, Datadog, and QRadar.
- 🔔 Notifications: Webhook integration for security alerts (Slack/Teams).
- ✅ Compliance Engine: Built-in CLI
npx check-nis2to audit your configuration. - 🛡️ Security Headers: HSTS, CSP, X-Frame-Options, and more.
Installation
npm install @nis2shield/express-middlewareQuick Start
import express from 'express';
import { nis2Shield } from '@nis2shield/express-middleware';
const app = express();
// Basic usage - enables all features with defaults
app.use(nis2Shield());
app.get('/', (req, res) => {
res.json({ message: 'Protected by NIS2 Shield!' });
});
app.listen(3000);Configuration
import { nis2Shield, Nis2Config } from '@nis2shield/express-middleware';
const config: Partial<Nis2Config> = {
enabled: true,
encryptionKey: process.env.NIS2_ENCRYPTION_KEY,
integrityKey: process.env.NIS2_HMAC_KEY,
logging: {
enabled: true,
anonymizeIP: true,
encryptPII: true,
piiFields: ['userId', 'email'],
},
activeDefense: {
rateLimit: {
enabled: true,
windowMs: 60000, // 1 minute
max: 100, // 100 requests per window
},
blockTor: true,
},
securityHeaders: {
enabled: true,
hsts: true,
csp: "default-src 'self'",
xFrameOptions: 'DENY',
},
};
app.use(nis2Shield(config));Environment Variables
NIS2_ENCRYPTION_KEY=your-base64-aes-256-key
NIS2_HMAC_KEY=your-secret-hmac-keySecurity Headers Applied
| Header | Default Value |
|--------|---------------|
| Strict-Transport-Security | max-age=31536000; includeSubDomains; preload |
| X-Content-Type-Options | nosniff |
| X-Frame-Options | DENY |
| Referrer-Policy | strict-origin-when-cross-origin |
| Permissions-Policy | Restrictive policy |
Log Format (JSON)
{
"timestamp": "2025-01-15T10:00:00.000Z",
"module": "nis2_shield",
"type": "audit_log",
"request": {
"method": "POST",
"path": "/api/login",
"ip": "203.0.113.xxx"
},
"response": {
"status": 200,
"duration_ms": 45
},
"integrity_hash": "a1b2c3d4..."
}📖 Recipes
Banking API with Strict Rate Limiting
import express from 'express';
import { nis2Shield } from '@nis2shield/express-middleware';
const app = express();
app.use(nis2Shield({
enabled: true,
encryptionKey: process.env.NIS2_ENCRYPTION_KEY,
integrityKey: process.env.NIS2_HMAC_KEY,
activeDefense: {
rateLimit: {
enabled: true,
windowMs: 60000,
max: 30, // Strict: 30 req/min for banking
},
blockTor: true,
blockedCountries: ['KP', 'IR'], // OFAC compliance
},
securityHeaders: {
enabled: true,
hsts: true,
xFrameOptions: 'DENY',
},
}));E-commerce with Slack Alerts
import { nis2Shield, createWebhookNotifier } from '@nis2shield/express-middleware';
const webhookNotifier = createWebhookNotifier({
url: 'https://hooks.slack.com/services/...',
format: 'slack',
events: ['rate_limit', 'session_hijack', 'blocked_ip'],
});
app.use(nis2Shield({
enabled: true,
webhooks: webhookNotifier,
logging: {
enabled: true,
anonymizeIP: true,
encryptPII: true,
},
}));Microservice with Datadog SIEM
import { nis2Shield } from '@nis2shield/express-middleware';
app.use(nis2Shield({
enabled: true,
siem: {
type: 'datadog',
apiKey: process.env.DD_API_KEY,
site: 'datadoghq.eu',
},
}));Related Projects
- django-nis2-shield: Python/Django version
- nis2-spring-shield: Java/Spring Boot version
- dotnet-nis2-shield: ASP.NET Core version
- @nis2shield/react-guard: Frontend client-side protectiond
Release Process
Automated releases are handled via GitHub Actions.
- Create Tag: Push a new tag (e.g.,
v0.2.0). - GitHub Release: Create a release in the GitHub UI.
- CI/CD: The
npm-publish.ymlworkflow triggers automatically:- Builds the project.
- Runs tests.
- Publishes to npm (using
NPM_TOKENsecret).
License
MIT License - See LICENSE for details.
