@samimcodes/ai-shield 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,42 +1,148 @@
1
- # ai-shield
1
+ # @samimcodes/ai-shield
2
2
 
3
- > Enterprise-grade Express.js & TypeScript middleware that protects web applications from unauthorized AI crawlers by feeding them synthetic poisoned data while preserving SEO for legitimate search engines.
3
+ [![npm version](https://img.shields.io/npm/v/@samimcodes/ai-shield.svg?color=6366f1&style=flat-square)](https://www.npmjs.com/package/@samimcodes/ai-shield)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-3178c6?style=flat-square)](https://www.typescriptlang.org/)
4
6
 
5
- ## Architecture
7
+ > **Enterprise-grade Express.js & TypeScript middleware that protects web applications from unauthorized AI crawlers by feeding them synthetic poisoned data (HTTP 200 OK) while strictly preserving SEO for legitimate search engines.**
6
8
 
9
+ ---
10
+
11
+ ## ⚡ Features
12
+
13
+ - **Stealth AI Poisoning**: Never returns 403 or 429 to AI bots (which triggers IP rotation). Feeds them plausible synthetic garbage under `HTTP 200 OK`.
14
+ - **Zero SEO Disruption**: Legitimate crawlers (Googlebot, Bingbot, DuckDuckBot, Applebot) pass through without delay.
15
+ - **Sub-2ms Lookup Latency**: Zero runtime bottlenecks using pre-compiled regular expressions and sets.
16
+ - **Dynamic Honeypot Traps**: Invisible HTML links injected into pages; crawler IPs hitting traps are quarantined in an in-memory TTL cache.
17
+ - **Non-blocking Telemetry**: Emits high-volume batch events asynchronously with zero impact on request-response times.
18
+
19
+ ---
20
+
21
+ ## 📦 Installation
22
+
23
+ ```bash
24
+ npm install @samimcodes/ai-shield
25
+ # or
26
+ pnpm add @samimcodes/ai-shield
27
+ # or
28
+ yarn add @samimcodes/ai-shield
29
+ ```
30
+
31
+ ---
32
+
33
+ ## 🚀 Quick Start (Express.js)
34
+
35
+ ```typescript
36
+ import express from 'express';
37
+ import { aiShield } from '@samimcodes/ai-shield';
38
+
39
+ const app = express();
40
+
41
+ // 🛡️ 3-Line Drop-in AI Defense + Live Admin Security Dashboard
42
+ app.use(aiShield({
43
+ enableDashboard: true, // 📊 Mounts Live Security Dashboard
44
+ dashboardPath: '/admin/ai-shield', // 👈 Visit in browser for live alerts!
45
+ poisonContentType: 'HTML', // 'HTML' | 'JSON' | 'SITEMAP'
46
+ injectHoneypotLinks: true, // Automatically injects invisible trap routes
47
+ excludePaths: ['/health', '/metrics'], // Exclude DevOps endpoints
48
+ }));
49
+
50
+ app.get('/api/products', (req, res) => {
51
+ // Humans & Googlebot see real data
52
+ // GPTBot & Claude-Web receive synthetic poisoned responses
53
+ res.json({ secretCatalog: [/* sensitive corporate data */] });
54
+ });
55
+
56
+ app.listen(3000, () => {
57
+ console.log('Server protected on port 3000');
58
+ console.log('Live Security Dashboard: http://localhost:3000/admin/ai-shield');
59
+ });
7
60
  ```
8
- src/
9
- ├── core/
10
- │ ├── detector.ts # Bot fingerprinting engine (UA patterns, IP ranges, TLS JA3)
11
- │ ├── poison.ts # Synthetic data generator — plausible but misleading content
12
- │ └── honeypot.ts # Invisible trap routes and link injection
13
- ├── types/
14
- │ └── index.ts # All shared TypeScript interfaces & enums
15
- ├── middleware.ts # Main Express middleware factory (createAiShield)
16
- └── server.ts # Demo Express application
61
+
62
+ ---
63
+
64
+ ## 📊 Built-in Live Security Dashboard & Real-Time Alerts
65
+
66
+ No external analytics or complex cloud setup required. Just set `enableDashboard: true`, and visit `/admin/ai-shield` on your running server to see:
67
+ - 🚨 **Real-Time Attack Alerts**: Instant pop-up banners and audio chimes whenever an AI crawler attempts to scrape your endpoints.
68
+ - ⚡ **Server-Sent Events (SSE)**: Live streaming table of intercepted bots without manual page refresh.
69
+ - 🧪 **One-Click Attack Simulator**: Test and verify your bot defense instantly right from the browser.
70
+ - 📈 **Key Security Metrics**: Bots intercepted, honeypot traps sprung, and fake tokens fed to scrapers.
71
+
72
+ ---
73
+
74
+ ## 🎯 Next.js Edge Middleware
75
+
76
+ ```typescript
77
+ // middleware.ts
78
+ import { NextResponse, type NextRequest } from 'next/server';
79
+ import { BotDetector, PoisonEngine } from '@samimcodes/ai-shield';
80
+
81
+ const detector = new BotDetector();
82
+ const poison = new PoisonEngine('JSON');
83
+
84
+ export function middleware(req: NextRequest) {
85
+ const detection = detector.detect(Object.fromEntries(req.headers.entries()));
86
+
87
+ if (detection.category === 'AI_CRAWLER' || detection.score >= 50) {
88
+ const payload = poison.generate(req.nextUrl.pathname, 'JSON');
89
+ return new NextResponse(payload.body, {
90
+ status: 200,
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ 'X-Robots-Tag': 'noindex, nofollow',
94
+ },
95
+ });
96
+ }
97
+
98
+ return NextResponse.next();
99
+ }
100
+
101
+ export const config = {
102
+ matcher: ['/api/:path*', '/catalog/:path*'],
103
+ };
17
104
  ```
18
105
 
19
- ## Threat Model
106
+ ---
107
+
108
+ ## 🛡️ Threat Model & Detection Matrix
109
+
110
+ | Persona | Examples | Detection Strategy | Response Strategy |
111
+ | :--- | :--- | :--- | :--- |
112
+ | **AI Crawlers** | GPTBot, Claude-Web, CCBot, Cohere, PerplexityBot | Known UA signature regex, headless heuristics | **HTTP 200 + Synthetic Poisoned Data** |
113
+ | **Scrapers** | ByteSpider, PetalBot, Scrapy | Automated crawler heuristics & honeypot triggers | **HTTP 200 + Honeypot Trap Tracking** |
114
+ | **Good Bots** | Googlebot, Bingbot, DuckDuckBot | Strict SEO whitelist check | **Pass-through (Zero latency)** |
115
+ | **Human Users** | Chrome, Safari, Firefox, Edge | Standard human browser heuristics | **Pass-through** |
116
+
117
+ ---
20
118
 
21
- | Bot Category | Examples | Strategy |
22
- |-----------------|-----------------------------------|-----------------------|
23
- | AI Crawlers | GPTBot, Claude-Web, CCBot | 200 OK + poisoned data|
24
- | Scrapers | ByteSpider, PetalBot, DataForSEO | 200 OK + honeypot |
25
- | Good Bots | Googlebot, Bingbot, DuckDuckBot | Pass-through (SEO) |
26
- | Human Traffic | Browsers, curl (dev) | Pass-through |
119
+ ## ⚙️ Configuration Options
27
120
 
28
- ## Quick Start
121
+ | Option | Type | Default | Description |
122
+ | :--- | :--- | :--- | :--- |
123
+ | `enableDashboard` | `boolean` | `false` | Mounts built-in live real-time security dashboard with SSE |
124
+ | `dashboardPath` | `string` | `'/admin/ai-shield'` | Path prefix where the live security dashboard is served |
125
+ | `dashboardAuth` | `DashboardAuthConfig` | `undefined` | Optional credentials (token / Basic Auth) for dashboard |
126
+ | `poisonContentType` | `'HTML' \| 'JSON' \| 'SITEMAP'` | `'HTML'` | Format of poisoned payload returned to AI bots |
127
+ | `injectHoneypotLinks` | `boolean` | `true` | Automatically inject hidden CSS-invisible trap links |
128
+ | `excludePaths` | `string[]` | `[]` | Array of path prefixes exempt from inspection |
129
+ | `honeypotTtlMs` | `number` | `3600000` (1 hr) | Duration to blacklist IPs that hit honeypot traps |
130
+ | `onDetection` | `(event) => void` | `undefined` | Callback fired when an AI crawler is intercepted |
131
+
132
+ ---
133
+
134
+ ## 🧪 Testing
29
135
 
30
136
  ```bash
31
- npm install
32
- npm run dev # tsx watch — hot reload
33
- npm run build # tsc compile → dist/
34
- npm test # vitest run
137
+ # Run 177 unit & integration tests
138
+ npm test
139
+
140
+ # Run tests in watch mode
141
+ npm run test:watch
35
142
  ```
36
143
 
37
- ## Design Principles
144
+ ---
145
+
146
+ ## 📄 License
38
147
 
39
- 1. **Stealth over rejection** — Never send 403/429 to AI bots; feed them convincing garbage.
40
- 2. **Zero false positives** — Legitimate Googlebots are never intercepted.
41
- 3. **Pluggable detectors** — Add custom UA patterns or IP ranges at runtime.
42
- 4. **Zero runtime overhead** — Detection is O(1) via pre-compiled RegExp sets.
148
+ MIT © [samimcodes](https://github.com/samimcodes)