api-guardian
v1.1.0
Published
**The Definitive Security & Validation Layer for Production Express APIs.**
Readme
api-guardian 🛡️
The Definitive Security & Validation Layer for Production Express APIs.
api-guardian is a comprehensive security context engine designed for high-stakes API environments. By adhering to Zero-Trust principles and providing a non-invasive, metadata-driven architecture, it ensures your application remains resilient against OWASP-standard threats without polluting the global request namespace.
🏛️ Architectural Philosophy: The "Security Context" Pattern
Standard Express middleware often mutates req.body or req.query directly. This can lead to unpredictable side-effects, type-safety collisions in TypeScript, and "property pollution."
api-guardian introduces the Immutable Security Context (req.guardian):
- Non-Invasive: Leaves the original
reqobjects (body,query,params) untouched for downstream compatibility. - Guaranteed Integrity: All data within
req.guardianis strictly verified, sanitized, and schema-compliant. - Enriched Metadata: Includes client IP, security event flags, and execution metrics.
🚀 Professional Quick Start
Initialize a global guardian or protect specific routes. High-performance ESM support is standard.
import express from "express";
import { z } from "zod";
import { apiGuardian } from "api-guardian";
const app = express();
app.use(express.json());
// 1. Definition: Define your ingress schemas
const UserRegistrationSchema = z.object({
username: z.string().min(3).max(20),
email: z.string().email(),
role: z.enum(["user", "admin"]).default("user"),
});
// 2. Deployment: Guard your endpoints
app.post(
"/api/v1/register",
apiGuardian({
schema: { body: UserRegistrationSchema },
strict: true, // Enforce schema-only fields (Anti-Mass Assignment)
sanitize: true, // Automated XSS/Injection Mitigation
honeypot: ["website"], // Bot mitigation via hidden trap fields
maskFields: ["password"], // Privacy-aware observability
}),
(req, res) => {
// 3. Consumption: Trust the context
const { username, email } = req.guardian.body;
res.status(201).json({
message: "Source verified. User registered.",
ref: req.guardian.ip,
});
},
);🛡️ Cyber-Hardened Enterprise Features
1. HMAC Signature Verification (Integrity Guard)
Prevent packet tampering and replay attacks. Essential for secure webhooks (e.g., Stripe, Shopify) or inter-service communication.
app.use(
apiGuardian({
signature: {
secret: process.env.SECURE_GATEWAY_KEY,
header: "x-api-signature", // Custom headers supported
algorithm: "sha256",
},
}),
);2. Intelligent IP Filtering & CIDR Support
Control access at the network layer level. Block malicious subnets or restrict endpoints to internal VPN ranges.
app.use(
apiGuardian({
ipFilter: {
blacklist: ["192.168.1.50", "203.0.113.0/24"], // Block specific intruders
whitelist: ["*"], // Default permit or specific trust
},
}),
);3. Honeypot Bot Detection
Identify automated spiders and script-kiddies. If a hidden "honeypot" field is filled, the request is instantly dropped before it hits your controller logic.
📈 Security Observability & Data Masking
Leaking PII (Personally Identifiable Information) into internal logs is a critical compliance failure. api-guardian ensures your logs stay clean through automated masking.
apiGuardian({
logSlowRequests: { thresholdMs: 250 },
maskFields: ["email", "password", "credit_card", "ssn"],
onSecurityEvent: (event) => {
// Real-time SecOps alerting
Metrics.inc("security_violation_total", { type: event.type });
SecurityLogger.alert(
`[${event.type}] Detected from IP: ${event.req.guardian.ip}`,
);
},
});📋 Configuration Reference
| Parameter | Expert Context |
| :----------- | :--------------------------------------------------------------------------------- |
| schema | Validation Authority: Zod schemas for body, query, and params. |
| strict | Payload Policing: If true, any field not defined in the schema is discarded. |
| signature | Cryptographic Proof: Ensures payload authenticity using HMAC. |
| honeypot | Anti-Automation: Invisible traps for detecting automated form submissions. |
| maskFields | GDPR Compliance: Prevents sensitive data from reaching log aggregators. |
| rateLimit | DDoS Mitigation: Integrated protection against brute-force and flooding. |
🎓 Architect's Handbook
- Strict Mode is Mandatory: In production, always use
strict: true. This mitigates "Mass Assignment" vulnerabilities where attackers inject admin-level fields into user-level inputs. - Layered Defense: Security is about depth. Use
helmet(Headers),rateLimit(Traffic Control), andschema(Application logic) concurrently. - Audit the Events: Hook into
onSecurityEventto feed your SIEM (Security Information and Event Management) system. Pattern matching on these events can reveal persistent attackers. - Least Privilege: Only whitelist the IPs you trust if your API is not meant for the public internet.
📄 License
ISC. Engineered for developers who take security seriously.
