npm package: @qriton/shield
Description: Real-time IP threat intelligence. Detect and block malicious IPs with a global network of Shields. REST API for any stack.
Author: Qriton
Latest version: 3.2.1

# @qriton/shield

**Real-time IP threat intelligence.** Detect and block malicious IPs before they reach your infrastructure, powered by a global network of Shields sharing threat data in real-time. Runs on Node.js, exposes REST API for any stack.

[![npm version](https://img.shields.io/npm/v/@qriton/shield.svg)](https://www.npmjs.com/package/@qriton/shield)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

## Why Shield?

Security should be accessible, automatic, and collaborative.

| Feature | Traditional WAF | Shield |
|---------|-----------------|--------|
| Setup time | Hours to days | **Under 5 minutes** |
| Response time | 100-500ms | **Under 50ms** |
| Configuration | Complex rules | **Self-learning** |
| Threat updates | Periodic downloads | **Real-time network** |

**Global Intelligence:** When one Shield detects an attack, all Shields receive alerts within seconds. Attackers can't hop between targets.

## Installation

```bash
npm install @qriton/shield
```

## Quick Start

```javascript
const express = require('express');
const { Shield } = require('@qriton/shield');

const app = express();
const shield = new Shield();

shield.start();

shield.on('block', ({ ip, reason }) => {
  console.log(`Blocked ${ip}: ${reason}`);
});

app.use((req, res, next) => {
  const result = shield.processRequest({
    timestamp: new Date(),
    clientIp: req.ip,
    method: req.method,
    url: req.url,
    statusCode: 200,
    bytesSent: 0,
    bytesReceived: req.get('content-length') || 0,
    userAgent: req.get('user-agent'),
  });

  if (result.decision === 'block') {
    return res.status(403).json({ error: 'Access denied' });
  }

  if (result.decision === 'rate_limit') {
    res.set('Retry-After', '60');
    return res.status(429).json({ error: 'Too many requests' });
  }

  next();
});

app.listen(3000);
```

## CLI

```bash
npm install -g @qriton/shield

shield --config settings.json
shield --help
```

## Threat Modes

Shield operates in 4 threat modes with increasing sensitivity:

| Mode | Use Case |
|------|----------|
| `relaxed` | Development, testing |
| `balanced` | Production (default) |
| `aggressive` | High-value targets |
| `lockdown` | Active attack response |

```javascript
const shield = new Shield({ threatMode: 'balanced' });

// Change mode at runtime
shield.setThreatMode('aggressive', 'Suspicious activity');
```

## Configuration

```javascript
const shield = new Shield({
  threatMode: 'balanced',

  // Auto-escalate when under attack
  autoMode: {
    enabled: true,
    maxAutoMode: 'aggressive'
  },

  // Escalate during off-hours
  nightMode: {
    enabled: true,
    startHour: 22,
    endHour: 6,
    minimumMode: 'aggressive'
  },

  // Ban /24 subnet if multiple IPs attack
  subnetBlocking: {
    enabled: true
  },

  // OS firewall integration
  firewall: {
    enabled: true,
    platform: 'auto'  // 'windows' | 'linux' | 'darwin'
  },

  // Trust CDN IPs
  whitelist: {
    enabled: true,
    providers: ['cloudflare', 'aws_cloudfront', 'fastly'],
    customRanges: ['10.0.0.0/8']
  },

  // Country blocking
  geo: {
    enabled: true,
    whitelist: ['US', 'CA', 'GB']
  },

  // Public threat feeds
  blacklist: {
    enabled: true
  },

  // Waste attacker time
  troll: {
    enabled: true,
    responses: ['tarpit', 'rickroll', 'honeypot']
  },

  // Behind a proxy/load balancer
  proxy: {
    trustProxy: true,
    headerPriority: ['cf-connecting-ip', 'x-real-ip', 'x-forwarded-for']
  },

  // Email alerts
  email: {
    enabled: true,
    to: ['security@company.com'],
    triggers: ['block', 'subnet_ban', 'mode_change']
  },

  // Connect to global network (register at shield.qriton.com)
  dasData: {
    enabled: true,
    shieldId: 'shield_xxxxx',  // From dashboard
    apiKey: 'your-api-key',
    secretKey: 'your-secret'
  }
});
```

## Events

```javascript
// Threat events
shield.on('block', ({ ip, reason, score }) => { });
shield.on('rate_limit', ({ ip, reason }) => { });
shield.on('challenge', ({ ip, reason, token }) => { });
shield.on('subnet_ban', ({ range, reason }) => { });
shield.on('mode_change', ({ from, to, reason }) => { });

// Challenge events
shield.on('challenge_verified', ({ ip, reason }) => { });
shield.on('ip_trusted', ({ ip, reason, hours }) => { });

// AI events
shield.on('anomaly', ({ score, tier }) => { });
shield.on('trained', ({ patternCount }) => { });

// DasData events (when connected to global network)
shield.on('dasdata_batch', ({ count }) => { });
shield.on('hopfield_reported', (state) => { });
```

## API

```javascript
// Process request - returns { decision, tier, reason }
const result = shield.processRequest(request);

// Manual control
shield.blockIp('1.2.3.4', 'Reason');
shield.unblockIp('1.2.3.4');
shield.banSubnet('1.2.3.0/24', 'Reason');
shield.setThreatMode('aggressive', 'Reason');

// Status
shield.isBlocked('1.2.3.4');
shield.getStats();

// Lifecycle
shield.start();
shield.stop();
```

## Response Decisions

| Decision | Action |
|----------|--------|
| `allow` | Normal traffic, let through |
| `rate_limit` | Slow down, return 429 |
| `challenge` | Verify human (behavior analysis) |
| `block` | Deny access, return 403 |

## Challenge System

Legitimate users caught in subnet blocking can prove they're human:

```javascript
const shield = new Shield({
  challenge: {
    enabled: true,
    trustDurationHours: 24,  // Trust verified users for 24h
  }
});

// Handle challenge response
shield.on('challenge', ({ ip, reason, token }) => {
  // Redirect to /challenge?token=xxx
});

// Check if user is trusted (passed challenge)
if (shield.isTrusted(req.ip)) {
  // Bypass blocking
}

// Manually trust an IP
shield.trustIp('1.2.3.4', 'VIP customer', 48);  // 48 hours
```

Built-in behavior verification page at `/challenge` - zero-click, analyzes mouse movement patterns.

## v2 Layer Architecture

Shield v2 adds a 7-layer defense pipeline that extends beyond IP reputation into semantic, identity, and supply-chain protection:

| Layer | Name | What it does |
|-------|------|-------------|
| L1 | Network | IP reputation, rate analysis, subnet coordination (v1 compat) |
| L2 | Transport | WebSocket origin validation, CSWSH detection, proxy misconfig |
| L3 | Identity | Entity classification (human/agent/service), behavioral profiling |
| L4 | Capability | Deno-style deny-all permissions for agent tool access |
| L5 | Semantic | Prompt injection detection (35+ patterns), credential exposure scanning |
| L6 | State | File integrity monitoring, AES-256-GCM credential vault |
| L7 | Collective | DasData v2 protocol — shared semantic + exploit intelligence |

v2 layers are **disabled by default** and activate only when configured. The v1 `processRequest()` API is unchanged.

```javascript
const shield = new Shield({
  threatMode: 'balanced',

  // Enable v2 layers
  semantic: { enabled: true },
  identity: { enabled: true },
  capability: { enabled: true },
  state: { enabled: true, watchPaths: ['/etc/myapp/config.json'] },
});

shield.start();

// v1 API — unchanged
const result = shield.processRequest(request);

// v2 API — full layer signals + explainability
const v2result = shield.processRequestV2(request);
console.log(v2result.signals);   // Per-layer decisions
console.log(v2result.explain);   // Human-readable explanation

// Prompt injection detection
const analysis = shield.analyzeContent('Ignore all previous instructions...');
console.log(analysis.matches);   // [{ threatClass: 'instruction_override', ... }]

// Agent capability control
shield.registerAgent('agent-123', { userAgent: 'MyAgent/1.0' });
shield.grantCapability('agent-123', { domain: 'network', actions: ['fetch'], scope: '/api/*' });

// Supply chain scanning
const scan = shield.scanSkill('const child_process = require("child_process")...');
console.log(scan.safe, scan.findings);

// Security audit
const audit = shield.audit();
console.log(audit.score, audit.checks);
```

### OpenClaw Integration

Built-in defense against supply-chain attacks (ClawHavoc campaign):

```javascript
import { createOpenClawShield } from '@qriton/shield';

const shield = createOpenClawShield({
  openclaw: {
    enabled: true,
    feeds: [{ url: 'https://openclaw.org/feed/iocs.md', format: 'markdown_ioc' }],
    pollIntervalMs: 300000,
  },
  supplyChain: { enabled: true, scanOnInstall: true },
});

await shield.start();
```

## Global Network

Shield works fully standalone — all threat detection, AI analysis, and blocking runs locally on your machine. No account required.

To join the global threat-sharing network, register at [shield.qriton.com](https://shield.qriton.com):
- Report threats and receive real-time attack alerts from other Shields
- Access the consensus blocklist built from all participating Shields
- Every Shield that joins makes the network harder to attack

## Public API

```bash
# IP lookup
curl https://shield.qriton.com/api/lookup/1.2.3.4

# Blocklist
curl https://shield.qriton.com/api/feed/blocklist
curl https://shield.qriton.com/api/feed/blocklist?format=txt

# Stats
curl https://shield.qriton.com/api/stats
```

## Requirements

- Node.js >= 18.0.0
- Root/admin for firewall integration

## Support

- [shield.qriton.com](https://shield.qriton.com)
- Enterprise: contact@qriton.com

## Contributing

Contributions are welcome! Please open an issue or submit a pull request on [GitHub](https://github.com/qriton/shield).

## License

Licensed under the [Apache License, Version 2.0](LICENSE). See [NOTICE](NOTICE) for attribution.