# @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

```bash
npm install @kya-os/agentshield-express
```

## Quick Start

```javascript
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

```javascript
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

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

### Log Agents

```javascript
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

```javascript
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:

```javascript
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:

```javascript
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:

```typescript
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:

```javascript
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

```javascript
// 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

```javascript
// 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