@gouravniit/zero-trust-api-monitor
v1.4.0
Published
Zero-Trust API monitoring with behavioral analysis, anomaly detection, and automated threat response for fintech APIs
Downloads
18
Maintainers
Readme
@gouravniit/zero-trust-api-monitor
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
npm install @gouravniit/zero-trust-api-monitorTwo 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
- Start the Gateway:
# 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'));- Send Telemetry (Any Language):
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 for Python, Java, Go, and Node.js examples.
Quick Start: Middleware Mode (Node.js)
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
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:
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:
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
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 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 ResponseAutomatic Partner Profiling
Partners are automatically identified and profiled on their first request:
curl https://your-api.com/endpoint \
-H "Authorization: Bearer partner_api_key" \
-H "X-Partner-ID: partner_fintech_alpha"The monitor automatically:
- Creates a behavioral profile
- Learns normal patterns (payload sizes, endpoints, timing)
- Detects anomalies in real-time
- Responds to threats automatically
Configuration
Environment Variables
# 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_keyAdvanced Usage
Access Individual Components
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
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:
npm run dashboard
# Open http://localhost:3001Features:
- Live partner risk scores
- Anomaly score trends
- Active alerts
- Manual throttle controls
Deployment
Docker
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-alpineKubernetes
apiVersion: apps/v1
kind: Deployment
metadata:
name: api-monitor
spec:
containers:
- name: monitor
image: your-registry/api-monitor
env:
- name: REDIS_HOST
value: redis-serviceNon-Node.js Applications
The monitor works with any backend language! Deploy as a standalone proxy:
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:8080See NON_NODEJS_GUIDE.md for details.
API Reference
createMonitor(config?)
Creates and initializes the monitor.
Parameters:
config.redis- Redis connection settingsconfig.security- Security configuration
Returns: Promise<Monitor>
Monitor
Properties:
middleware()- Express middlewarefeatureStore- Access to behavioral profilesthrottleEngine- Threat response enginetelemetryCollector- Request collectorshutdown()- Graceful shutdown
Documentation
- Team Implementation Guide - 📋 Complete guide for application teams
- Gateway Integration Guide (Python/Java/Go/Node)
- API Integration Guide (Middleware)
- NPM Publishing Guide
Examples
See the 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
