@chdlabs/my-shield 0.1.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/LICENSE +21 -0
- package/README.md +197 -0
- package/package.json +45 -0
- package/src/admin/adminRouter.js +221 -0
- package/src/admin/dashboard/dashboard.css +534 -0
- package/src/admin/dashboard/dashboard.js +610 -0
- package/src/admin/dashboard/index.html +266 -0
- package/src/client/shield-client.js +63 -0
- package/src/core/bloomFilter.js +191 -0
- package/src/core/lruCache.js +178 -0
- package/src/core/ringBuffer.js +87 -0
- package/src/index.d.ts +97 -0
- package/src/index.js +317 -0
- package/src/intelligence/autoPromoter.js +91 -0
- package/src/intelligence/collector.js +219 -0
- package/src/intelligence/filePersistence.js +226 -0
- package/src/middleware/costThrottle.js +75 -0
- package/src/middleware/honeypot.js +215 -0
- package/src/middleware/keyLeakDetector.js +98 -0
- package/src/middleware/notFoundCollector.js +171 -0
- package/src/middleware/shieldGuard.js +93 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ChdLabs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
# ðĄïļ @chdlabs/my-shield
|
|
2
|
+
|
|
3
|
+
> High-performance, zero-latency security shield middleware for Express. Built with pure JavaScript probabilistic data structures (Bloom filter + LRU cache), honeypot traps, and a self-improving 404 intelligence engine.
|
|
4
|
+
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
[](https://nodejs.org/)
|
|
7
|
+
[](https://www.npmjs.com/package/@chdlabs/my-shield)
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Highlights
|
|
12
|
+
|
|
13
|
+
- ⥠**Sub-0.1ms Clean Pass**: Legitimate requests pass through the L1 Bloom filter in `< 0.1ms`.
|
|
14
|
+
- ðŊ **Zero False-Positive Blocks**: Two-tiered L1 caching (Bloom filter + LRU confirmed threat cache) guarantees statistical Bloom false positives are never blocked.
|
|
15
|
+
- ðŊ **Silent Honeypot Decoys**: Static trap routes (`/.env`, `/wp-login.php`, `/.git/config`, etc.) return a silent `200 OK` decoy response after a brief delay and instantly blacklist scanners.
|
|
16
|
+
- ð **404 Anomaly & Intelligence**: Captures every 404 URL probe, bans scanners probing $\ge 5$ unique paths in 60s, and auto-promotes frequent attack targets to active honeypots.
|
|
17
|
+
- ðū **Single-File Deduplicated Persistence**: Preserves learned probe patterns and promoted honeypots across process restarts in an atomic JSON file (`404_intelligence.json`).
|
|
18
|
+
- ð **Self-Contained Security Dashboard**: Built-in dark-themed telemetry console with real-time Server-Sent Events (SSE), charts, and active block management.
|
|
19
|
+
- ðŠķ **Zero Production Dependencies**: Pure JavaScript built exclusively with Node.js built-ins (`crypto`, `fs`, `path`, `events`).
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Architecture
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
Incoming Request
|
|
27
|
+
â
|
|
28
|
+
âž
|
|
29
|
+
âââââââââââââââââââââââââââââââââââââââââ
|
|
30
|
+
â L1 Shield Guard â
|
|
31
|
+
â â
|
|
32
|
+
â 1. IP Whitelist? âââķ Pass â
|
|
33
|
+
â 2. Bloom Filter? âââķ False = Pass â
|
|
34
|
+
â 3. LRU Cache? âââķ Found = Block â
|
|
35
|
+
ââââââââââââââââââââŽâââââââââââââââââââââ
|
|
36
|
+
âž
|
|
37
|
+
âââââââââââââââââââââââââââââââââââââââââ
|
|
38
|
+
â Honeypot Trap Router â
|
|
39
|
+
â Hits sensitive path? âââķ Silent 200 â
|
|
40
|
+
â Blacklist IP â
|
|
41
|
+
ââââââââââââââââââââŽâââââââââââââââââââââ
|
|
42
|
+
âž
|
|
43
|
+
âââââââââââââââââââââââââââââââââââââââââ
|
|
44
|
+
â Application Routes (Your API) â
|
|
45
|
+
ââââââââââââââââââââŽâââââââââââââââââââââ
|
|
46
|
+
âž
|
|
47
|
+
âââââââââââââââââââââââââââââââââââââââââ
|
|
48
|
+
â 404 Intelligence Collector â
|
|
49
|
+
â âĨ 5 unique 404s/60s? âââķ Ban IP â
|
|
50
|
+
â Dedup snapshot saved to disk â
|
|
51
|
+
âââââââââââââââââââââââââââââââââââââââââ
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npm install @chdlabs/my-shield
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## Quick Start (Express)
|
|
65
|
+
|
|
66
|
+
```javascript
|
|
67
|
+
import express from 'express';
|
|
68
|
+
import { createShield } from '@chdlabs/my-shield';
|
|
69
|
+
|
|
70
|
+
const app = express();
|
|
71
|
+
|
|
72
|
+
const shield = createShield({
|
|
73
|
+
bloom: {
|
|
74
|
+
expectedItems: 100_000,
|
|
75
|
+
falsePositiveRate: 0.01
|
|
76
|
+
},
|
|
77
|
+
lru: {
|
|
78
|
+
maxSize: 10_000,
|
|
79
|
+
ttlMs: 5 * 60 * 1000 // 5 minutes
|
|
80
|
+
},
|
|
81
|
+
honeypot: {
|
|
82
|
+
enabled: true,
|
|
83
|
+
delayMs: 500
|
|
84
|
+
},
|
|
85
|
+
intelligence: {
|
|
86
|
+
anomalyThreshold: 5, // 5 unique 404s in 60s -> BAN
|
|
87
|
+
anomalyWindowMs: 60_000,
|
|
88
|
+
captureAll: true,
|
|
89
|
+
filePersistence: {
|
|
90
|
+
enabled: true,
|
|
91
|
+
directory: './data/shield',
|
|
92
|
+
filename: '404_intelligence.json',
|
|
93
|
+
intervalMs: 60 * 60 * 1000, // 1 hour save interval
|
|
94
|
+
loadOnStartup: true
|
|
95
|
+
},
|
|
96
|
+
autoPromote: {
|
|
97
|
+
enabled: true,
|
|
98
|
+
minHits: 50,
|
|
99
|
+
minUniqueIPs: 10
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// 1. Mount main defense guard (FIRST middleware after parsing)
|
|
105
|
+
app.use(shield.middleware());
|
|
106
|
+
|
|
107
|
+
// 2. Mount honeypot trap router (BEFORE application routes)
|
|
108
|
+
app.use(shield.honeypot());
|
|
109
|
+
|
|
110
|
+
// 3. Application routes
|
|
111
|
+
app.get('/api/data', (req, res) => res.json({ status: 'ok' }));
|
|
112
|
+
|
|
113
|
+
// 4. Mount 404 intelligence collector (AFTER application routes)
|
|
114
|
+
app.use(shield.notFoundCollector());
|
|
115
|
+
|
|
116
|
+
// 5. Mount admin dashboard (protect with your auth middleware)
|
|
117
|
+
app.use('/admin/shield', authenticateAdmin, shield.adminRouter());
|
|
118
|
+
|
|
119
|
+
// Graceful shutdown: flushes 404 intelligence to disk
|
|
120
|
+
process.on('SIGTERM', async () => {
|
|
121
|
+
await shield.shutdown();
|
|
122
|
+
process.exit(0);
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Configuration Reference
|
|
129
|
+
|
|
130
|
+
| Option | Type | Default | Description |
|
|
131
|
+
|---|---|---|---|
|
|
132
|
+
| `whitelist` | `string[]` | `[]` | List of IP addresses that are never blocked |
|
|
133
|
+
| `bloom.expectedItems` | `number` | `100000` | Estimated distinct IPs to hold in filter |
|
|
134
|
+
| `bloom.falsePositiveRate` | `number` | `0.01` | Target false positive probability (1%) |
|
|
135
|
+
| `bloom.sizeBytes` | `number` | `null` | Explicit bit array size in bytes |
|
|
136
|
+
| `lru.maxSize` | `number` | `10000` | Max entries in confirmed threat cache |
|
|
137
|
+
| `lru.ttlMs` | `number` | `300000` | Threat cache TTL in ms (5 minutes) |
|
|
138
|
+
| `honeypot.enabled` | `boolean` | `true` | Enable/disable honeypot traps |
|
|
139
|
+
| `honeypot.delayMs` | `number` | `500` | Delay before sending silent 200 OK decoy |
|
|
140
|
+
| `honeypot.additionalRoutes` | `string[]` | `[]` | Custom trap path patterns |
|
|
141
|
+
| `intelligence.anomalyThreshold` | `number` | `5` | Unique 404s before IP is banned |
|
|
142
|
+
| `intelligence.anomalyWindowMs` | `number` | `60000` | Sliding window in ms (60 seconds) |
|
|
143
|
+
| `intelligence.filePersistence.enabled` | `boolean` | `true` | Enable periodic JSON snapshot saves |
|
|
144
|
+
| `intelligence.filePersistence.directory` | `string` | `'./data/shield'` | Destination directory for JSON snapshot |
|
|
145
|
+
| `intelligence.filePersistence.filename` | `string` | `'404_intelligence.json'` | Single deduplicated filename |
|
|
146
|
+
| `intelligence.filePersistence.intervalMs`| `number` | `3600000` | Snapshot save interval (1 hour) |
|
|
147
|
+
| `intelligence.filePersistence.loadOnStartup` | `boolean` | `true` | Restore intelligence on process start |
|
|
148
|
+
| `intelligence.autoPromote.enabled` | `boolean` | `true` | Auto-promote frequent 404s to traps |
|
|
149
|
+
| `intelligence.autoPromote.minHits` | `number` | `50` | Min 404 hits before promotion |
|
|
150
|
+
| `intelligence.autoPromote.minUniqueIPs` | `number` | `10` | Min distinct IPs probing path |
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## Programmatic API
|
|
155
|
+
|
|
156
|
+
```javascript
|
|
157
|
+
// Manual IP Governance
|
|
158
|
+
shield.blockIP('198.51.100.42', 'manual_ban', { admin: 'dev1' });
|
|
159
|
+
shield.unblockIP('198.51.100.42');
|
|
160
|
+
shield.allowIP('192.168.1.50'); // Add to whitelist
|
|
161
|
+
shield.removeAllowedIP('192.168.1.50');
|
|
162
|
+
shield.isWhitelisted('192.168.1.50'); // Returns boolean
|
|
163
|
+
|
|
164
|
+
// Telemetry & Metrics
|
|
165
|
+
shield.getStats(); // Returns aggregate stats, LRU sizes, traps list
|
|
166
|
+
shield.getIntelligence(); // Full 404 intelligence snapshot
|
|
167
|
+
shield.getBloomHealth(); // Saturation percentage and estimated FPR
|
|
168
|
+
|
|
169
|
+
// Route-Level Denial-of-Wallet Cost Throttling
|
|
170
|
+
app.post('/api/ai-generate', shield.costThrottle({ weight: 10, maxCost: 100 }), handler);
|
|
171
|
+
|
|
172
|
+
// Route-Level Token / Credential Leak Detection
|
|
173
|
+
app.use(shield.keyLeakDetector());
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Publishing to npmjs
|
|
179
|
+
|
|
180
|
+
To publish `@chdlabs/my-shield` to npm:
|
|
181
|
+
|
|
182
|
+
1. Log in to your npm account (if not already logged in):
|
|
183
|
+
```bash
|
|
184
|
+
npm login
|
|
185
|
+
```
|
|
186
|
+
2. Navigate to the `sdk` directory and publish:
|
|
187
|
+
```bash
|
|
188
|
+
cd sdk
|
|
189
|
+
npm publish
|
|
190
|
+
```
|
|
191
|
+
*(Note: Since `@chdlabs` is a scoped package, `"publishConfig": { "access": "public" }` is pre-configured in `package.json`).*
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## License
|
|
196
|
+
|
|
197
|
+
MIT ÂĐ CHDLabs
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@chdlabs/my-shield",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zero-latency security shield middleware with Bloom filter, honeypots, and 404 intelligence",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"types": "src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.d.ts",
|
|
11
|
+
"import": "./src/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./client": "./src/client/shield-client.js"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"peerDependencies": {
|
|
19
|
+
"express": ">=4.18.0 || >=5.0.0"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {},
|
|
22
|
+
"devDependencies": {},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=20.0.0"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"src/",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"keywords": [
|
|
32
|
+
"security",
|
|
33
|
+
"honeypot",
|
|
34
|
+
"bloom-filter",
|
|
35
|
+
"waf",
|
|
36
|
+
"express-middleware",
|
|
37
|
+
"bot-detection",
|
|
38
|
+
"404-intelligence"
|
|
39
|
+
],
|
|
40
|
+
"author": "CHDLabs",
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"scripts": {
|
|
43
|
+
"test": "node test/integration.test.js"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shield Administration Express Router & Management API
|
|
3
|
+
* Provides programmatic governance, analytics endpoints, and serves
|
|
4
|
+
* the self-contained monitoring dashboard.
|
|
5
|
+
*
|
|
6
|
+
* @author ChdLabs
|
|
7
|
+
* @license MIT
|
|
8
|
+
*/
|
|
9
|
+
import express from 'express';
|
|
10
|
+
import path from 'path';
|
|
11
|
+
import fs from 'fs';
|
|
12
|
+
import { fileURLToPath } from 'url';
|
|
13
|
+
|
|
14
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
15
|
+
const __dirname = path.dirname(__filename);
|
|
16
|
+
|
|
17
|
+
export function createAdminRouter(shield, options = {}) {
|
|
18
|
+
const router = express.Router();
|
|
19
|
+
const dashboardDir = path.resolve(__dirname, 'dashboard');
|
|
20
|
+
const authMiddleware = Array.isArray(options.authMiddleware) ? options.authMiddleware : (options.authMiddleware ? [options.authMiddleware] : []);
|
|
21
|
+
|
|
22
|
+
// ââ Static Asset Handlers ââ
|
|
23
|
+
router.get('/', (req, res) => {
|
|
24
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
25
|
+
res.sendFile(path.join(dashboardDir, 'index.html'));
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
router.get('/dashboard.css', (req, res) => {
|
|
29
|
+
res.setHeader('Content-Type', 'text/css; charset=utf-8');
|
|
30
|
+
res.sendFile(path.join(dashboardDir, 'dashboard.css'));
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
router.get('/dashboard.js', (req, res) => {
|
|
34
|
+
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
|
|
35
|
+
res.sendFile(path.join(dashboardDir, 'dashboard.js'));
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// ââ Protect API endpoints if authMiddleware provided ââ
|
|
39
|
+
if (authMiddleware.length > 0) {
|
|
40
|
+
router.use('/api', ...authMiddleware);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ââ API Endpoints ââ
|
|
44
|
+
|
|
45
|
+
// 1. Overall System Stats
|
|
46
|
+
router.get('/api/stats', (req, res) => {
|
|
47
|
+
res.json(shield.getStats());
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// 2. Paginated / Recent Security Events
|
|
51
|
+
router.get('/api/events', (req, res) => {
|
|
52
|
+
const limit = Math.min(500, Math.max(1, parseInt(req.query.limit || '50', 10)));
|
|
53
|
+
const type = req.query.type;
|
|
54
|
+
let events = shield.ringBuffer.getRecent(limit * 2);
|
|
55
|
+
|
|
56
|
+
if (type) {
|
|
57
|
+
events = events.filter(e => e && e.type === type);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
res.json({
|
|
61
|
+
totalRecorded: shield.ringBuffer.size,
|
|
62
|
+
returned: Math.min(events.length, limit),
|
|
63
|
+
events: events.slice(0, limit)
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// 3. 404 Intelligence Snapshot
|
|
68
|
+
router.get('/api/intelligence', (req, res) => {
|
|
69
|
+
res.json(shield.getIntelligence());
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// 4. Download 404_intelligence.json directly
|
|
73
|
+
router.get('/api/intelligence/file', (req, res) => {
|
|
74
|
+
const filePath = shield.filePersistence?.filePath;
|
|
75
|
+
if (!filePath || !fs.existsSync(filePath)) {
|
|
76
|
+
return res.status(404).json({ error: 'Intelligence file not yet generated or found' });
|
|
77
|
+
}
|
|
78
|
+
res.download(filePath, '404_intelligence.json');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// 5. Bloom Filter Diagnostics
|
|
82
|
+
router.get('/api/bloom', (req, res) => {
|
|
83
|
+
res.json(shield.getBloomHealth());
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// 6. Currently Blocked IPs (from LRU)
|
|
87
|
+
router.get('/api/blocked', (req, res) => {
|
|
88
|
+
const entries = shield.lru.entries().map(e => ({
|
|
89
|
+
ip: e.key,
|
|
90
|
+
reason: e.value?.reason || 'unspecified',
|
|
91
|
+
metadata: e.value?.metadata || {},
|
|
92
|
+
createdAt: e.createdAt,
|
|
93
|
+
expiresAt: e.expiresAt,
|
|
94
|
+
remainingTtlMs: e.remainingTtlMs
|
|
95
|
+
}));
|
|
96
|
+
res.json({ count: entries.length, blockedIPs: entries });
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// 7. Whitelisted IPs
|
|
100
|
+
router.get('/api/whitelist', (req, res) => {
|
|
101
|
+
res.json({
|
|
102
|
+
count: shield.whitelist.size,
|
|
103
|
+
whitelistedIPs: Array.from(shield.whitelist)
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// 8. Manual IP Block
|
|
108
|
+
router.post('/api/block', express.json(), (req, res) => {
|
|
109
|
+
const { ip, reason = 'manual_admin_block', ttlMs } = req.body || {};
|
|
110
|
+
if (!ip || typeof ip !== 'string') {
|
|
111
|
+
return res.status(400).json({ error: 'Valid "ip" string is required' });
|
|
112
|
+
}
|
|
113
|
+
shield.blockIP(ip.trim(), reason, { adminAction: true }, ttlMs);
|
|
114
|
+
shield.recordEvent({
|
|
115
|
+
type: 'admin_action',
|
|
116
|
+
action: 'block_ip',
|
|
117
|
+
ip: ip.trim(),
|
|
118
|
+
reason,
|
|
119
|
+
timestamp: Date.now()
|
|
120
|
+
});
|
|
121
|
+
res.json({ success: true, message: `IP ${ip.trim()} successfully blocked` });
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
// 9. Manual IP Whitelist (Allow)
|
|
125
|
+
router.post('/api/allow', express.json(), (req, res) => {
|
|
126
|
+
const { ip } = req.body || {};
|
|
127
|
+
if (!ip || typeof ip !== 'string') {
|
|
128
|
+
return res.status(400).json({ error: 'Valid "ip" string is required' });
|
|
129
|
+
}
|
|
130
|
+
shield.allowIP(ip.trim());
|
|
131
|
+
shield.recordEvent({
|
|
132
|
+
type: 'admin_action',
|
|
133
|
+
action: 'allow_ip',
|
|
134
|
+
ip: ip.trim(),
|
|
135
|
+
timestamp: Date.now()
|
|
136
|
+
});
|
|
137
|
+
res.json({ success: true, message: `IP ${ip.trim()} added to whitelist` });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// 10. Manual IP Unblock
|
|
141
|
+
router.delete('/api/block/:ip', (req, res) => {
|
|
142
|
+
const ip = req.params.ip;
|
|
143
|
+
shield.unblockIP(ip);
|
|
144
|
+
shield.recordEvent({
|
|
145
|
+
type: 'admin_action',
|
|
146
|
+
action: 'unblock_ip',
|
|
147
|
+
ip,
|
|
148
|
+
timestamp: Date.now()
|
|
149
|
+
});
|
|
150
|
+
res.json({ success: true, message: `IP ${ip} removed from blocked cache` });
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// 11. Remove from Whitelist
|
|
154
|
+
router.delete('/api/allow/:ip', (req, res) => {
|
|
155
|
+
const ip = req.params.ip;
|
|
156
|
+
shield.removeAllowedIP(ip);
|
|
157
|
+
shield.recordEvent({
|
|
158
|
+
type: 'admin_action',
|
|
159
|
+
action: 'remove_allowed_ip',
|
|
160
|
+
ip,
|
|
161
|
+
timestamp: Date.now()
|
|
162
|
+
});
|
|
163
|
+
res.json({ success: true, message: `IP ${ip} removed from whitelist` });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// 12. Add Honeypot Route
|
|
167
|
+
router.post('/api/honeypot/add', express.json(), (req, res) => {
|
|
168
|
+
const { path: routePath } = req.body || {};
|
|
169
|
+
if (!routePath || typeof routePath !== 'string') {
|
|
170
|
+
return res.status(400).json({ error: 'Valid "path" string is required' });
|
|
171
|
+
}
|
|
172
|
+
shield.honeypotInstance.addRoute(routePath.trim(), 'admin_manual');
|
|
173
|
+
res.json({ success: true, message: `Honeypot trap added for path "${routePath.trim()}"` });
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
// 13. Remove Honeypot Route
|
|
177
|
+
router.delete('/api/honeypot/{*path}', (req, res) => {
|
|
178
|
+
const raw = req.params.path;
|
|
179
|
+
const routePath = Array.isArray(raw) ? '/' + raw.join('/') : (req.query.path || '/' + (raw || ''));
|
|
180
|
+
const removed = shield.honeypotInstance.removeRoute(routePath);
|
|
181
|
+
res.json({ success: removed, message: removed ? `Removed trap "${routePath}"` : `Trap not found` });
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// 14. Promote a 404 path to honeypot manually
|
|
185
|
+
router.post('/api/promote', express.json(), (req, res) => {
|
|
186
|
+
const { path: routePath } = req.body || {};
|
|
187
|
+
if (!routePath || typeof routePath !== 'string') {
|
|
188
|
+
return res.status(400).json({ error: 'Valid "path" string is required' });
|
|
189
|
+
}
|
|
190
|
+
const promoted = shield.autoPromoter?.promotePath(routePath.trim());
|
|
191
|
+
res.json({ success: !!promoted, message: `Path "${routePath.trim()}" promoted to honeypot trap` });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// 15. Server-Sent Events (SSE) Live Feed
|
|
195
|
+
router.get('/api/stream', (req, res) => {
|
|
196
|
+
res.setHeader('Content-Type', 'text/event-stream');
|
|
197
|
+
res.setHeader('Cache-Control', 'no-cache');
|
|
198
|
+
res.setHeader('Connection', 'keep-alive');
|
|
199
|
+
res.flushHeaders?.();
|
|
200
|
+
|
|
201
|
+
// Send initial connection event
|
|
202
|
+
res.write(`data: ${JSON.stringify({ type: 'connected', timestamp: Date.now() })}\n\n`);
|
|
203
|
+
|
|
204
|
+
const listener = (event) => {
|
|
205
|
+
res.write(`data: ${JSON.stringify(event)}\n\n`);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
shield.on('event', listener);
|
|
209
|
+
|
|
210
|
+
const heartbeat = setInterval(() => {
|
|
211
|
+
res.write(': heartbeat\n\n');
|
|
212
|
+
}, 15000);
|
|
213
|
+
|
|
214
|
+
req.on('close', () => {
|
|
215
|
+
clearInterval(heartbeat);
|
|
216
|
+
shield.off('event', listener);
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return router;
|
|
221
|
+
}
|