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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@kya-os/agentshield-express

v0.1.40

Published

Express.js middleware for AgentShield AI agent detection

Readme

@kya-os/agentshield-express

Express.js middleware for AgentShield AI agent detection and protection.

Features

  • 🚀 Easy Integration: Drop-in middleware for Express applications
  • 🛡️ Flexible Actions: Block, log, or allow detected agents
  • 🎯 Path Filtering: Skip detection for specific routes
  • 🔧 Customizable: Custom handlers and response formatting
  • 📊 Request Enhancement: Attach detection results to request objects

Installation

npm install @kya-os/agentshield-express

Quick Start

import express from 'express';
import { agentShield } from '@kya-os/agentshield-express';

const app = express();

// Basic usage - log detected agents
app.use(agentShield());

// Block detected agents
app.use(agentShield({
  onAgentDetected: 'block',
  confidenceThreshold: 0.8,
}));

app.get('/', (req, res) => {
  // Access detection results
  const detection = req.agentShield;
  if (detection && detection.result.isAgent) {
    console.log('Agent detected:', detection.result);
  }
  
  res.json({ message: 'Hello, human!' });
});

app.listen(3000);

Configuration

const config = {
  // Core detection options
  confidenceThreshold: 0.7,
  enablePatternMatching: true,
  enableBehaviorAnalysis: true,
  enableNetworkAnalysis: true,
  
  // Middleware-specific options
  onAgentDetected: 'block', // 'block' | 'allow' | 'log'
  
  // Skip detection for certain paths
  skipPaths: ['/health', '/metrics', /^\/api\/webhooks/],
  
  // Custom response when blocking
  blockedResponse: {
    status: 403,
    message: 'Access denied: Automated agent detected',
    headers: { 'Content-Type': 'application/json' },
  },
  
  // Custom detection handler
  onDetection: async (req, res, result) => {
    console.log('Custom handler:', result);
    // Log to analytics, send alerts, etc.
  },
};

app.use(agentShield(config));

Actions

Block Agents

app.use(agentShield({
  onAgentDetected: 'block',
  blockedResponse: {
    status: 429,
    message: 'Too many automated requests',
  },
}));

Log Agents

app.use(agentShield({
  onAgentDetected: 'log',
  onDetection: (req, res, result) => {
    logger.warn('Agent detected', {
      ip: req.ip,
      userAgent: req.get('User-Agent'),
      confidence: result.confidence,
      path: req.path,
    });
  },
}));

Custom Handler

app.use(agentShield({
  onDetection: async (req, res, result) => {
    if (result.confidence > 0.9) {
      // High confidence - block immediately
      return res.status(403).json({ error: 'Blocked' });
    } else if (result.confidence > 0.5) {
      // Medium confidence - add rate limiting
      req.rateLimit = { max: 10, window: 60000 };
    }
    // Low confidence - continue normally
  },
}));

Path Filtering

Skip agent detection for specific routes:

app.use(agentShield({
  skipPaths: [
    '/health',              // Exact match
    '/api/public',          // Exact match
    /^\/webhooks/,          // Regex pattern
    /\\.json$/,             // File extensions
  ],
}));

Request Enhancement

The middleware adds detection results to the request object:

app.get('/dashboard', (req, res) => {
  const { agentShield } = req;
  
  if (agentShield) {
    const { result, skipped } = agentShield;
    
    if (skipped) {
      console.log('Detection was skipped for this path');
    } else {
      console.log('Detection result:', {
        isAgent: result.isAgent,
        confidence: result.confidence,
        reasons: result.reasons,
      });
    }
  }
  
  res.render('dashboard');
});

TypeScript Support

Full TypeScript support with extended request types:

import { Request, Response, NextFunction } from 'express';
import { agentShield, AgentShieldRequest } from '@kya-os/agentshield-express';

app.use(agentShield());

app.get('/', (req: AgentShieldRequest, res: Response) => {
  // req.agentShield is properly typed
  const detection = req.agentShield?.result;
  if (detection?.isAgent) {
    // Handle agent detection
  }
});

Error Handling

The middleware is designed to fail gracefully:

app.use(agentShield({
  onDetection: (req, res, result) => {
    try {
      // Your detection logic
    } catch (error) {
      // Errors are caught and logged automatically
      // The request continues processing normally
    }
  },
}));

Examples

API Protection

// Protect API endpoints from automated scraping
app.use('/api', agentShield({
  onAgentDetected: 'block',
  confidenceThreshold: 0.6,
  blockedResponse: {
    status: 429,
    message: 'API access restricted for automated clients',
  },
}));

Content Protection

// Allow agents for public content, block for premium content
app.use('/premium', agentShield({
  onAgentDetected: 'block',
  confidenceThreshold: 0.5,
}));

app.use('/public', agentShield({
  onAgentDetected: 'log', // Just log, don't block
}));

License

MIT OR Apache-2.0