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

@bonhomie/api-shield

v1.0.0

Published

A modern Node.js API utility toolkit: rate limiter, fingerprinting, validators, caching, logger, error handler, and cron helpers.

Readme

🛡️ @bonhomie/api-shield

The Ultimate Security & Utility Toolkit for Node.js APIs

Rate limiting, fingerprinting, CSRF, JWT, bot detection, RBAC, sanitization, attack detection, caching, cron helpers & more.

npm version npm downloads node-current license security


🚀 Why API Shield?

@bonhomie/api-shield is an all-in-one backend security and utility layer designed for Express, Fastify, or any Node.js API.

It provides:

  • 🔐 JWT auth (sign, verify, attach user, roles)
  • 🛡 CSRF protection (double-submit cookie)
  • 🧪 Input validation + sanitization
  • ⚔️ SQLi/XSS/path-traversal detection
  • 🕵️ Bot detection + device fingerprinting
  • 🚦 Rate limiting (memory & Redis)
  • 🔄 Cache wrapper (Redis + in-memory)
  • 🧰 Password hashing (argon2)
  • 🕹 RBAC (roles + permissions)
  • 📅 Cron helpers
  • 📦 Response formatters (success, fail, paginate)
  • 🌐 HMAC, nonce, and anti-replay tokens

Everything packaged cleanly and production-ready.


📦 Installation

npm install @bonhomie/api-shield

Requires Node 18+.


⚡ Quick Start (Express)

import express from "express";
import cookieParser from "cookie-parser";
import {
  requestLogger,
  attackGuard,
  sanitizeRequest,
  csrfCookie,
  csrfProtect,
  createRateLimiter,
  requireAuth,
} from "@bonhomie/api-shield";

const app = express();
app.use(express.json());
app.use(cookieParser());

// Global protections
app.use(requestLogger());
app.use(attackGuard({ block: true }));
app.use(sanitizeRequest());
app.use(csrfCookie());

// Rate limiter
const limiter = createRateLimiter({ limit: 100, windowMs: 60000 });
app.use(limiter);

// Protected route
app.post("/update-profile",
  csrfProtect(),
  requireAuth({ secret: process.env.JWT_SECRET }),
  (req, res) => {
    res.success({ message: "Profile updated" });
  }
);

app.listen(3000);

🔐 JWT Utilities

import { signJwt, requireAuth } from "@bonhomie/api-shield";

const token = signJwt(
  { id: user._id, role: "admin" },
  { secret: process.env.JWT_SECRET, expiresIn: "15m" }
);

app.get("/admin",
  requireAuth({
    secret: process.env.JWT_SECRET,
    roles: ["admin"]
  }),
  (req, res) => res.success("Welcome Admin")
);

🛡 CSRF Protection (double-submit cookie)

import { csrfCookie, csrfProtect } from "@bonhomie/api-shield";

app.use(csrfCookie());

app.post("/form",
  csrfProtect(),
  (req, res) => res.success("Submitted")
);

Frontend must include the CSRF token:

Header: x-csrf-token: <token_from_cookie>

🔐 Password Hashing (argon2)

import { hashPassword, verifyPassword } from "@bonhomie/api-shield";

const hash = await hashPassword("password123");
const ok = await verifyPassword("password123", hash);

⚙ Input Sanitization

import { sanitizeRequest } from "@bonhomie/api-shield";

app.use(sanitizeRequest());

Cleans req.body, req.query, and req.params from XSS.


⚔ SQLi / XSS Attack Detection

import { attackGuard } from "@bonhomie/api-shield";

app.use(attackGuard({ block: true }));

Automatically blocks dangerous payloads.


🕵️ Bot Detection + Device Fingerprinting

import { botGuard, fingerprintV2 } from "@bonhomie/api-shield";

app.use(botGuard({ block: false }));

Detects:

  • Bad user-agent patterns
  • Scripted bots
  • Headless browsers

Fingerprint v2 uses:

  • IP
  • User-Agent
  • Accept-Language
  • Screen/device hints

🚦 Rate Limiting (Memory or Redis)

import { createRateLimiter } from "@bonhomie/api-shield";

const limiter = createRateLimiter({
  limit: 100,
  windowMs: 60000
});

app.use(limiter);

Redis version:

createRateLimiter({ redis, limit: 100, windowMs: 60000 });

🧰 Response Formatters

import { success, fail, paginate } from "@bonhomie/api-shield";

res.json(success({ name: "Bonhomie" }));
res.json(fail("Unauthorized", 401));
res.json(paginate(items, { page: 1, perPage: 10, total: 200 }));

Or attach directly:

import { responseFormatter } from "@bonhomie/api-shield";

app.use(responseFormatter());

res.success({ msg: "OK" });
res.fail("Oops");

🔄 Cache Wrapper (Redis or Memory)

import { cache } from "@bonhomie/api-shield";

await cache.set("profile:123", { name: "Bonhomie" }, 60000);
const data = await cache.get("profile:123");

Works with Redis or in-memory fallback.


🔧 Cron Helpers

import { cronEvery, cronAt } from "@bonhomie/api-shield";

cronEvery("5m", () => console.log("runs every 5 minutes"));
cronAt("0 0 * * *", () => console.log("midnight job"));

🛂 RBAC (Roles & Permissions)

import { requireRole, requirePermission } from "@bonhomie/api-shield";

app.get("/admin",
  requireRole(["admin"]),
  (req, res) => res.success("Admin Panel")
);

app.post("/edit",
  requirePermission("edit:content"),
  (req, res) => res.success("Updated")
);

🧬 Replay Protection + HMAC + Nonce

import {
  createReplayToken,
  createHmac,
  verifyHmac,
  generateNonce
} from "@bonhomie/api-shield";

const token = createReplayToken();
const nonce = generateNonce();
const signature = createHmac(secret, payload);

🛠 Developer-Friendly Features

  • Zero configuration needed
  • ESM-first
  • Works in Express, Fastify, NestJS, or raw Node
  • Lightweight single-file build
  • Safe defaults
  • Production security baked in

🔍 SEO Keywords

(This helps your npm ranking)

node api security, csrf token express, node jwt middleware, express rate limiter,
node sanitizer, api shield, bot detection node, argon2 password hashing,
nodejs validation, node hmac, express anti replay, security middleware node,
xss sqli detection node, rbac nodejs, redis caching node

📄 License

MIT © Bonhomie

❤️ Contribute

Pull requests welcome. Security suggestions extra welcome.