@bhargavanaidupola/security-inspector
v0.1.0
Published
Reusable API security inspection middleware for Node backends.
Readme
Security Inspector
Reusable Express middleware for capturing request security events.
This folder is structured like a package so it can later be moved to its own npm package. The middleware does not depend on Prisma, a dashboard, or this app's routes. It emits a SecurityEvent and saves it through a storage adapter.
Install
npm install @bhargavanaidupola/security-inspectorExpress Usage
When using the published npm package, import from @bhargavanaidupola/security-inspector. When using this folder locally, import from ./security-inspector.
import express from "express";
import {
ConsoleSecurityAlertHandler,
ConsoleSecurityEventStorage,
commonAttackPatternsDetector,
createExpressSecurityMiddleware,
repeatedRequestsDetector,
suspiciousKeywordsDetector,
} from "./security-inspector";
const app = express();
app.use(express.json({ limit: "100kb" }));
app.use(createExpressSecurityMiddleware({
appName: "my-website",
mode: "monitor",
storage: new ConsoleSecurityEventStorage(),
skipPaths: ["/health", "/metrics"],
captureBody: false,
maskHeaders: ["authorization", "cookie", "x-api-key"],
maskBodyFields: ["password", "token", "otp"],
blockThreshold: 80,
alertThreshold: 80,
alertHandlers: [new ConsoleSecurityAlertHandler()],
detectors: [
suspiciousKeywordsDetector(),
commonAttackPatternsDetector(),
repeatedRequestsDetector(),
],
}));Modes
monitor: log events and allow requests.block: log events and return403when risk is at or aboveblockThreshold.off: skip all inspection.
Storage
Implement SecurityEventStorage for any backend:
- Prisma
- MongoDB
- PostgreSQL
- HTTP collector
- Console logs
- Memory storage for tests
The current app uses a Prisma-backed adapter in src/middleware/interceptor.ts.
Included Storage Adapters
import {
ConsoleSecurityEventStorage,
HttpCollectorStorage,
MemorySecurityEventStorage,
PrismaSecurityEventStorage,
} from "./security-inspector";
const consoleStorage = new ConsoleSecurityEventStorage();
const httpStorage = new HttpCollectorStorage({
endpoint: "https://collector.example.com/events",
apiKey: process.env.INSPECTOR_API_KEY,
});
const prismaStorage = new PrismaSecurityEventStorage({
requestDelegate: prisma.request,
});Alerts
Alerts run when riskScore >= alertThreshold.
import {
ConsoleSecurityAlertHandler,
WebhookAlertHandler,
} from "./security-inspector";
alertHandlers: [
new ConsoleSecurityAlertHandler(),
new WebhookAlertHandler({
endpoint: "https://alerts.example.com/security",
apiKey: process.env.SECURITY_ALERT_KEY,
}),
]Package Build
This folder includes package.json and tsconfig.json, so it can be copied into its own repository and built:
npm install
npm run buildLater, publish it as:
npm publish --access public