@chdlabs/my-shield 0.1.2 → 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
@@ -13,6 +13,7 @@
13
13
  - **Sub-0.1ms Clean Pass**: Legitimate requests pass through the L1 Bloom filter in `< 0.1ms`.
14
14
  - **Zero False-Positive Blocks**: Two-tiered L1 caching (Bloom filter + LRU confirmed threat cache) guarantees statistical Bloom false positives are never blocked.
15
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
+ - **MiniRocket Behavioral Biometrics**: Sub-2ms bot detection using deterministic 1D convolutional kernel transforms and Dual Ridge regression to identify automated splines and synthetic kinematics with zero runtime dependencies.
16
17
  - **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
18
  - **Single-File Deduplicated Persistence**: Preserves learned probe patterns and promoted honeypots across process restarts in an atomic JSON file (`404_intelligence.json`).
18
19
  - **Self-Contained Security Dashboard**: Built-in dark-themed telemetry console with real-time Server-Sent Events (SSE), charts, and active block management.
@@ -42,6 +43,14 @@ Incoming Request
42
43
  └──────────────────┬────────────────────┘
43
44
  ▼
44
45
  ┌───────────────────────────────────────┐
46
+ │ Behavioral Biometrics Guard (Optional)│
47
+ │ MiniRocket + Dual Ridge (< 2ms) │
48
+ │ Replay nonces? ──▶ Block 403 │
49
+ │ Synthetic event? ──▶ Block 403 │
50
+ │ Human probability? ──▶ >= 0.70 Pass │
51
+ └──────────────────┬────────────────────┘
52
+ ▼
53
+ ┌───────────────────────────────────────┐
45
54
  │ Application Routes (Your API) │
46
55
  └──────────────────┬────────────────────┘
47
56
  ▼
@@ -112,8 +121,13 @@ app.use(shield.middleware());
112
121
  // 2. Mount honeypot trap router (BEFORE application routes)
113
122
  app.use(shield.honeypot());
114
123
 
115
- // 3. Application routes
124
+
125
+ // -----------------> ADD IN HERE ALL YOUR APPLICATION ROUTES <----------------//
116
126
  app.get('/api/data', (req, res) => res.json({ status: 'ok' }));
127
+ // -----------------> ADD IN HERE ALL YOUR APPLICATION ROUTES <----------------//
128
+
129
+
130
+
117
131
 
118
132
  // 4. Mount 404 intelligence collector (AFTER application routes)
119
133
  app.use(shield.notFoundCollector());
@@ -203,6 +217,140 @@ The dashboard client automatically looks for the session token in the following
203
217
 
204
218
  ---
205
219
 
220
+ ## 🧠 Behavioral Biometrics via MiniRocket & Dual Ridge
221
+
222
+ `@chdlabs/my-shield` incorporates client-side and server-side behavioral biometrics based on **MiniRocket** (*Minimally Random Convolutional Kernel Transform*) and a **Dual Ridge Classifier**.
223
+
224
+ ### Why Behavioral Biometrics?
225
+ Headless automation tools (Puppeteer, Playwright, curl) and synthetic scripts often lack realistic pointer physics or produce mathematically smoothed Bézier splines. Human users exhibit distinct continuous neuromuscular tremor, deceleration profiles, micro-corrections, and sub-movements.
226
+
227
+ MiniRocket maps 128-point equispaced mouse velocity trajectories into a high-dimensional feature space using 84 deterministic length-9 kernels with multi-scale dilations and Proportion of Positive Values (PPV). Scoring is resolved via a single dot-product in Dual Ridge regression in **< 2.0 ms** with zero runtime dependencies.
228
+
229
+ ---
230
+
231
+ ### 1. Client-Side Telemetry Collection (Browser)
232
+
233
+ Import the browser client module (`@chdlabs/my-shield/client`):
234
+
235
+ ```javascript
236
+ import { MouseTelemetryCollector } from '@chdlabs/my-shield/client';
237
+
238
+ // 1. Initialize telemetry collector (128 samples at 100Hz = 1.28s rolling window)
239
+ const collector = new MouseTelemetryCollector({
240
+ windowLength: 128,
241
+ sampleIntervalMs: 10
242
+ });
243
+
244
+ // 2. Start capturing pointer dynamics
245
+ collector.start();
246
+
247
+ // 3. Attach telemetry packet to sensitive API requests
248
+ async function submitLogin(username, password) {
249
+ // Extracts normalized 100Hz velocity series and event integrity metadata
250
+ const telemetry = collector.getPayload(); // { velocity: number[], isTrusted: boolean, timestamp: number }
251
+
252
+ const response = await fetch('/api/auth/login', {
253
+ method: 'POST',
254
+ headers: {
255
+ 'Content-Type': 'application/json',
256
+ 'x-shield-telemetry': telemetry ? JSON.stringify(telemetry) : ''
257
+ },
258
+ body: JSON.stringify({ username, password })
259
+ });
260
+
261
+ return response.json();
262
+ }
263
+ ```
264
+
265
+ ---
266
+
267
+ ### 2. Server-Side Route Guard (Express)
268
+
269
+ Protect sensitive routes (e.g. login, payment checkout, AI prompt generation) with `shield.behavioralGuard()`:
270
+
271
+ ```javascript
272
+ import express from 'express';
273
+ import { createShield } from '@chdlabs/my-shield';
274
+
275
+ const app = express();
276
+ app.use(express.json());
277
+
278
+ const shield = createShield();
279
+
280
+ // Protect sensitive endpoints with behavioral biometrics
281
+ app.post(
282
+ '/api/auth/login',
283
+ shield.behavioralGuard({
284
+ threshold: 0.70, // Minimum human probability required (default: 0.70)
285
+ headerName: 'x-shield-telemetry', // Header containing telemetry JSON
286
+ replayWindowMs: 15_000, // Max acceptable age/drift in ms (default: 15s)
287
+ autoBlockIP: true, // Auto-blacklist detected bots into Shield L1 Bloom + LRU
288
+ allowFallbackOnError: false, // Fail-closed (default: false)
289
+ onBotDetected: (req, res, meta) => {
290
+ // Optional custom callback when bot is intercepted
291
+ console.warn(`[BOT DETECTED] IP: ${req.ip}, Reason: ${meta.reason}, Confidence: ${meta.probability}`);
292
+ res.status(403).json({ error: 'Automated kinematics detected.', code: meta.reason });
293
+ }
294
+ }),
295
+ (req, res) => {
296
+ // Verified human request! Access biometric audit metadata:
297
+ console.log(req.shield.biometrics);
298
+ // => { isHuman: true, humanConfidence: 0.94, latencyMs: 0.85, score: 2.75 }
299
+
300
+ res.json({ status: 'authenticated' });
301
+ }
302
+ );
303
+ ```
304
+
305
+ ---
306
+
307
+ ### 3. Standalone Core Biometrics API
308
+
309
+ You can also use MiniRocket and the Dual Ridge Classifier directly for custom data pipelines or time series classification:
310
+
311
+ ```javascript
312
+ import { MiniRocket, DualRidgeClassifier } from '@chdlabs/my-shield/biometrics';
313
+
314
+ // 1. Transform a 128-sample series into PPV features
315
+ const mr = new MiniRocket(128, 336);
316
+ mr.loadThresholds(fittedThresholds);
317
+ const features = mr.transform(velocitySeries);
318
+
319
+ // 2. Predict class probability
320
+ const ridge = new DualRidgeClassifier();
321
+ ridge.loadWeights(fittedWeights, bias);
322
+ const result = ridge.predict(features);
323
+
324
+ console.log(result);
325
+ // => { score: 1.42, probability: 0.805, isHuman: true }
326
+ ```
327
+
328
+ ---
329
+
330
+ ### 4. Custom Model Retraining CLI
331
+
332
+ To retrain model weights against your own captured movement datasets:
333
+
334
+ ```bash
335
+ node scripts/train-weights.js
336
+ ```
337
+ This fits MiniRocket thresholds and Dual Ridge primal weights from your kinematic data, serializing the bundle to `models/default-weights.json`.
338
+
339
+ ---
340
+
341
+ ### Behavioral Guard Options Reference
342
+
343
+ | Option | Type | Default | Description |
344
+ |---|---|---|---|
345
+ | `threshold` | `number` | `0.70` | Minimum human probability cutoff ($P \ge \text{threshold}$) |
346
+ | `headerName` | `string` | `'x-shield-telemetry'` | Request header containing JSON telemetry payload |
347
+ | `replayWindowMs` | `number` | `15000` | Sliding window in ms; rejects expired or futuristic timestamps |
348
+ | `allowFallbackOnError` | `boolean` | `false` | Fail-open (`true`) vs fail-closed (`false`) when telemetry is missing or malformed |
349
+ | `autoBlockIP` | `boolean` | `false` | Automatically add detected bot IP to Shield L1 Bloom + LRU cache |
350
+ | `onBotDetected` | `Function` | `undefined` | Custom callback `(req, res, meta)` invoked when bot or replay is detected |
351
+
352
+ ---
353
+
206
354
  ## Configuration Reference
207
355
 
208
356
  | Option | Type | Default | Description |
@@ -217,6 +365,7 @@ The dashboard client automatically looks for the session token in the following
217
365
  | `honeypot.enabled` | `boolean` | `true` | Enable/disable honeypot traps |
218
366
  | `honeypot.delayMs` | `number` | `500` | Delay before sending silent 200 OK decoy |
219
367
  | `honeypot.additionalRoutes` | `string[]` | `[]` | Custom trap path patterns |
368
+ | `biometrics.modelWeights` | `Object` | `null` | Custom MiniRocket thresholds, weights, and bias |
220
369
  | `intelligence.anomalyThreshold` | `number` | `5` | Unique 404s before IP is banned |
221
370
  | `intelligence.anomalyWindowMs` | `number` | `60000` | Sliding window in ms (60 seconds) |
222
371
  | `intelligence.filePersistence.enabled` | `boolean` | `true` | Enable periodic JSON snapshot saves |
@@ -245,6 +394,10 @@ shield.getStats(); // Returns aggregate stats, LRU sizes, traps list
245
394
  shield.getIntelligence(); // Full 404 intelligence snapshot
246
395
  shield.getBloomHealth(); // Saturation percentage and estimated FPR
247
396
 
397
+ // Behavioral Biometrics
398
+ const outcome = shield.verifyBiometrics(velocityArray); // { score, probability, isHuman, latencyMs }
399
+ app.post('/api/auth/login', shield.behavioralGuard({ threshold: 0.70 }), handler);
400
+
248
401
  // Route-Level Denial-of-Wallet Cost Throttling
249
402
  app.post('/api/ai-generate', shield.costThrottle({ weight: 10, maxCost: 100 }), handler);
250
403