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

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 req objects (body, query, params) untouched for downstream compatibility.
  • Guaranteed Integrity: All data within req.guardian is 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

  1. 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.
  2. Layered Defense: Security is about depth. Use helmet (Headers), rateLimit (Traffic Control), and schema (Application logic) concurrently.
  3. Audit the Events: Hook into onSecurityEvent to feed your SIEM (Security Information and Event Management) system. Pattern matching on these events can reveal persistent attackers.
  4. 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.