npm package: @gouravniit/zero-trust-api-monitor
Description: Zero-Trust API monitoring with behavioral analysis, anomaly detection, and automated threat response for fintech APIs
Author: FIS Global
Latest version: 1.4.0

# @gouravniit/zero-trust-api-monitor

[![npm version](https://badge.fury.io/js/%40gouravniit%2Fzero-trust-api-monitor.svg)](https://www.npmjs.com/package/@gouravniit/zero-trust-api-monitor)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Zero-Trust API monitoring with behavioral analysis, anomaly detection, and automated threat response for fintech APIs.

**Now supports ALL languages via Gateway Mode!**

## Features

- 🌐 **Universal Gateway Mode** - Monitor apps in Python, Java, Go, Ruby, etc.
- 📱 **Multi-App Support** - Track up to 25+ applications in one dashboard
- 🔍 **Behavioral Baselining** - Learns normal API usage patterns per partner
- 🚨 **Real-time Anomaly Detection** - Detects unusual behavior using statistical analysis
- 🛡️ **Automated Threat Response** - 5-level response system (Monitor → Alert → Throttle → Quarantine → Block)
- 📊 **Real-time Dashboard** - Beautiful monitoring interface for all your apps
- ⚡ **High Performance** - <1ms overhead, async processing
- 🔒 **Privacy-First** - Zero PII collection, GDPR/PCI-DSS compliant

## Installation

```bash
npm install @gouravniit/zero-trust-api-monitor
```

## Two Ways to Use

### 1. Gateway Mode (Recommended for Microservices)
Run a central monitoring gateway that accepts telemetry from all your services (Node, Python, Java, etc).

### 2. Middleware Mode (Recommended for Single Node.js App)
Integrate directly into your Express.js application.

## Quick Start: Gateway Mode

1.  **Start the Gateway:**

```bash
# gateway.js
const { createGateway } = require('@gouravniit/zero-trust-api-monitor');

createGateway({
  redis: { host: 'localhost', port: 6379 },
  gateway: { port: 9000, cors: true }
}).then(() => console.log('Gateway running on port 9000'));
```

2.  **Send Telemetry (Any Language):**

```bash
curl -X POST http://localhost:9000/telemetry \
  -H "Content-Type: application/json" \
  -d '{
    "appId": "user-service",
    "partnerId": "partner_123",
    "timestamp": 1705600000000,
    "endpoint": "/api/users",
    "method": "GET",
    "statusCode": 200,
    "responseTime": 45
  }'
```

See [GATEWAY_INTEGRATION.md](./GATEWAY_INTEGRATION.md) for Python, Java, Go, and Node.js examples.

## Quick Start: Middleware Mode (Node.js)

```javascript
const express = require('express');
const { createMonitor } = require('@gouravniit/zero-trust-api-monitor');

const app = express();

// Initialize monitor
const monitor = await createMonitor({
  redis: {
    host: 'localhost',
    port: 6379
  },
  security: {
    shadowMode: true  // Start in monitoring-only mode
  }
});

// Add monitoring middleware
app.use(monitor.middleware());

// Your API routes
app.get('/api/accounts/:id', (req, res) => {
  res.json({ id: req.params.id, balance: 1000 });
});

app.listen(3000);
```

## TypeScript Support

```typescript
import { createMonitor, MonitorConfig } from '@gouravniit/zero-trust-api-monitor';

const config: MonitorConfig = {
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: 6379
  },
  security: {
    shadowMode: false,
    enableAutoThrottle: true
  }
};

const monitor = await createMonitor(config);
app.use(monitor.middleware());
```

## Advanced Features

### Custom Anomaly Thresholds

Configure custom thresholds to match your application's requirements:

```javascript
const monitor = require('@gouravniit/zero-trust-api-monitor');

app.use(monitor.middleware({
  partnerId: 'partner-xyz',
  appId: 'payment-service',
  gatewayUrl: 'http://localhost:9000',
  
  // Custom thresholds
  anomalyThresholds: {
    requestRate: 1000,        // Max 1000 requests per minute
    errorRate: 0.05,          // Max 5% error rate
    responseTime: 2000,       // Max 2 second response time
    suspiciousPatterns: true  // Enable pattern detection
  }
}));
```

### Event Callbacks

Handle monitoring events in real-time with custom callbacks:

```javascript
app.use(monitor.middleware({
  partnerId: 'partner-xyz',
  appId: 'payment-service',
  gatewayUrl: 'http://localhost:9000',
  
  // Alert callback - triggered when thresholds exceeded
  onAlert: (alert) => {
    console.error(`🚨 ${alert.severity}: ${alert.title}`);
    
    // Send to external systems
    if (alert.severity === 'critical') {
      sendToPagerDuty(alert);
    }
    sendToSlack(alert);
  },
  
  // Throttle callback - triggered when rate limited
  onThrottle: (throttleInfo) => {
    console.warn(`⚠️  Throttled: ${throttleInfo.message}`);
    console.warn(`   Retry after: ${throttleInfo.retryAfter}s`);
    
    // Implement backoff strategy
    reduceRequestRate();
  },
  
  // Anomaly callback - triggered on unusual behavior
  onAnomaly: (anomaly) => {
    console.warn(`📊 Anomaly score: ${anomaly.score}`);
    
    // Log for analysis
    if (anomaly.score > 80) {
      logger.error('High anomaly detected', anomaly);
    }
  }
}));
```

### Complete Advanced Example

```javascript
const express = require('express');
const monitor = require('@gouravniit/zero-trust-api-monitor');

const app = express();

app.use(monitor.middleware({
  partnerId: 'partner-xyz',
  appId: 'payment-service',
  gatewayUrl: 'http://localhost:9000',
  
  // Configure thresholds
  anomalyThresholds: {
    requestRate: 1000,
    errorRate: 0.05,
    responseTime: 2000,
    suspiciousPatterns: true
  },
  
  // Handle events
  onAlert: (alert) => {
    // Critical alerts go to PagerDuty
    if (alert.severity === 'critical' || alert.severity === 'high') {
      sendToPagerDuty(alert);
    }
    // All alerts go to Slack
    sendToSlack(alert);
  },
  
  onThrottle: (info) => {
    logger.warn('Throttled', info);
    metrics.increment('throttle.count');
    
    // Reduce load if heavily throttled
    if (info.level === 'high' || info.level === 'quarantine') {
      reduceRequestRate();
    }
  },
  
  onAnomaly: (anomaly) => {
    metrics.gauge('anomaly.score', anomaly.score);
    
    if (anomaly.score > 80) {
      logger.error('High anomaly score', anomaly);
    }
  },
  
  // Optional settings
  enableAutoRetry: true,
  retryAttempts: 3,
  timeout: 5000
}));

app.listen(3000);
```

See [examples/advanced-monitoring.js](./examples/advanced-monitoring.js) for a complete working example.

## Configuration

The monitor sits between your API consumers (partners) and your API endpoints:

```
Partner Request → Monitor → Your API → Response → Monitor → Partner
                     ↓
              Behavioral Analysis
              Anomaly Detection
              Threat Response
```

### Automatic Partner Profiling

Partners are automatically identified and profiled on their first request:

```bash
curl https://your-api.com/endpoint \
  -H "Authorization: Bearer partner_api_key" \
  -H "X-Partner-ID: partner_fintech_alpha"
```

The monitor automatically:
1. Creates a behavioral profile
2. Learns normal patterns (payload sizes, endpoints, timing)
3. Detects anomalies in real-time
4. Responds to threats automatically

## Configuration

### Environment Variables

```bash
# Redis (required)
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=your_password

# Security Settings
SHADOW_MODE=true                    # Monitor only, no blocking
ENABLE_AUTO_THROTTLE=false         # Enable automatic blocking

# Thresholds (0-100)
ANOMALY_THRESHOLD_ALERT=31         # Generate alert
ANOMALY_THRESHOLD_THROTTLE=61      # Add latency
ANOMALY_THRESHOLD_QUARANTINE=81    # Require re-auth
ANOMALY_THRESHOLD_BLOCK=96         # Temporary block

# LLM (optional)
LLM_PROVIDER=openai                # or 'anthropic'
OPENAI_API_KEY=your_key
```

## Advanced Usage

### Access Individual Components

```javascript
const { 
  telemetryCollector,
  baselineEngine,
  throttleEngine,
  securityCopilot,
  featureStore 
} = require('@gouravniit/zero-trust-api-monitor');

// Custom alert handling
throttleEngine.onAlert((response) => {
  console.log('Threat detected:', {
    partnerId: response.partnerId,
    action: response.action,
    score: response.anomalyScore
  });
  
  // Send to your alerting system
  sendToSlack(response);
});

// Manual partner management
await throttleEngine.restorePartner('partner_id', 'False positive');
```

### Get Partner Status

```javascript
const status = await featureStore.getProfile('partner_fintech_alpha');
console.log(status);
// {
//   partnerId: 'partner_fintech_alpha',
//   statistics: {
//     requestsPerHour: 150,
//     avgPayloadSize: 1024,
//     commonEndpoints: { '/api/accounts': 100 }
//   }
// }
```

## Dashboard

Access the real-time monitoring dashboard:

```bash
npm run dashboard
# Open http://localhost:3001
```

Features:
- Live partner risk scores
- Anomaly score trends
- Active alerts
- Manual throttle controls

## Deployment

### Docker

```yaml
version: '3.8'
services:
  api-monitor:
    image: your-registry/api-monitor
    ports:
      - "3000:3000"
    environment:
      - REDIS_HOST=redis
      - SHADOW_MODE=false
    depends_on:
      - redis
  
  redis:
    image: redis:7-alpine
```

### Kubernetes

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-monitor
spec:
  containers:
  - name: monitor
    image: your-registry/api-monitor
    env:
    - name: REDIS_HOST
      value: redis-service
```

## Non-Node.js Applications

The monitor works with **any** backend language! Deploy as a standalone proxy:

```yaml
services:
  # Your Python/Java/Go API
  your-api:
    image: your-api:latest
    ports:
      - "8080:8080"
  
  # Monitor (protects your API)
  monitor:
    image: zero-trust-monitor
    ports:
      - "3000:3000"
    environment:
      - BACKEND_API_URL=http://your-api:8080
```

See [NON_NODEJS_GUIDE.md](./NON_NODEJS_GUIDE.md) for details.

## API Reference

### `createMonitor(config?)`

Creates and initializes the monitor.

**Parameters:**
- `config.redis` - Redis connection settings
- `config.security` - Security configuration

**Returns:** `Promise<Monitor>`

### `Monitor`

**Properties:**
- `middleware()` - Express middleware
- `featureStore` - Access to behavioral profiles
- `throttleEngine` - Threat response engine
- `telemetryCollector` - Request collector
- `shutdown()` - Graceful shutdown

## Documentation

- **[Team Implementation Guide](./TEAM_IMPLEMENTATION_GUIDE.md)** - 📋 Complete guide for application teams
- [Gateway Integration Guide (Python/Java/Go/Node)](./GATEWAY_INTEGRATION.md)
- [API Integration Guide (Middleware)](./API_INTEGRATION_GUIDE.md)
- [NPM Publishing Guide](./NPM_PUBLISHING_GUIDE.md)

## Examples

See the [examples](./examples) directory for:
- Express.js integration
- TypeScript usage
- Custom alert handling
- Multi-language deployment

## License

MIT © FIS Global

## Support

- 📧 Issues: https://github.com/fis-global/zero-trust-monitor/issues
- 📖 Docs: https://github.com/fis-global/zero-trust-monitor