iri-shield 1.2.1 → 1.2.3

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.
Files changed (3) hide show
  1. package/README.md +462 -180
  2. package/package.json +1 -1
  3. package/src/index.js +2 -0
package/README.md CHANGED
@@ -1,17 +1,16 @@
1
1
  # iri-shield
2
2
 
3
- [![npm version](https://img.shields.io/badge/npm-v1.2.0-blue.svg)](https://www.npmjs.com/package/iri-shield)
3
+ [![npm version](https://img.shields.io/badge/npm-v1.2.2-blue.svg)](https://www.npmjs.com/package/iri-shield)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](https://opensource.org/licenses/MIT)
5
5
  [![Node.js](https://img.shields.io/badge/node-%3E%3D22.0.0-purple.svg)](https://nodejs.org)
6
- [![Security](https://img.shields.io/badge/security-explainable--ai-orange.svg)](#-explainable-risk-scoring)
7
- [![Privacy](https://img.shields.io/badge/privacy-by--design-teal.svg)](#-privacy-by-design)
6
+ [![Security](https://img.shields.io/badge/security-risk--scoring-orange.svg)](#explainable-risk-scoring)
7
+ [![Privacy](https://img.shields.io/badge/privacy-by--design-teal.svg)](#privacy-controls--fail-safe-modes)
8
8
 
9
9
  <p align="center">
10
- <img src="./img/iri-shield-home.jpg" alt="Iri Shield Logo" width="500">
10
+ <img src="./img/iri-shield-home.jpg" alt="Iri Shield" width="500">
11
11
  </p>
12
12
 
13
-
14
- > **Enterprise-grade API security middleware for Express.js** featuring **Explainable Risk Scoring**, **Multi-Signal Identity Continuity Analysis**, **Behavioural Anomaly Detection**, **Attack Sequence Correlation**, **Configurable Rule Engine**, **Automated PII/Secret Redaction**, and an **Interactive Real-Time Admin Dashboard**.
13
+ > **Open-source API security middleware for Express.js** with explainable risk scoring, multi-signal identity continuity analysis, behavioural anomaly detection, attack sequence correlation, configurable threat rules, recursive PII/secret redaction, and a real-time admin dashboard.
15
14
 
16
15
  ---
17
16
 
@@ -19,44 +18,49 @@
19
18
 
20
19
  - [iri-shield](#iri-shield)
21
20
  - [Table of Contents](#table-of-contents)
22
- - [Architectural Philosophy](#architectural-philosophy)
21
+ - [Overview](#overview)
23
22
  - [Key Features](#key-features)
24
23
  - [Installation](#installation)
25
24
  - [Quick Start](#quick-start)
25
+ - [Security Rule Engine](#security-rule-engine)
26
+ - [Configuration Reference](#configuration-reference)
27
+ - [Security \& Auth Utilities](#security--auth-utilities)
28
+ - [Guide for `Vercel`](#guide-for-vercel)
29
+ - [Production Deployment](#production-deployment)
30
+ - [Disable Testing Mode](#disable-testing-mode)
31
+ - [Reverse Proxy \& Client IP](#reverse-proxy--client-ip)
32
+ - [Storage on Serverless Platforms](#storage-on-serverless-platforms)
33
+ - [Secure Dashboard Credentials](#secure-dashboard-credentials)
34
+ - [Production Configuration](#production-configuration)
35
+ - [Vercel Deployment](#vercel-deployment)
36
+ - [1. Install Dependencies](#1-install-dependencies)
37
+ - [2. Recommended Vercel Storage](#2-recommended-vercel-storage)
38
+ - [3. Serverless Express Entry Point](#3-serverless-express-entry-point)
39
+ - [4. Environment Variables](#4-environment-variables)
40
+ - [5. Vercel Deployment Checklist](#5-vercel-deployment-checklist)
41
+ - [Research \& Benchmarking](#research--benchmarking)
42
+ - [Comprehensive Research Evaluation Summary (v1.2.0-research)](#comprehensive-research-evaluation-summary-v120-research)
43
+ - [Multi-Workload Performance \& Latency Matrix](#multi-workload-performance--latency-matrix)
44
+ - [Admin Dashboard](#admin-dashboard)
26
45
  - [Explainable Risk Scoring](#explainable-risk-scoring)
27
46
  - [Multi-Signal Identity Continuity](#multi-signal-identity-continuity)
28
- - [Security Rule Engine](#security-rule-engine)
29
- - [Behavioural Anomaly \& Correlation](#behavioural-anomaly--correlation)
47
+ - [Behavioural Anomaly \& Attack Correlation](#behavioural-anomaly--attack-correlation)
30
48
  - [1. Rolling Behaviour Baseline](#1-rolling-behaviour-baseline)
31
49
  - [2. Attack Sequence Correlation](#2-attack-sequence-correlation)
32
50
  - [Privacy Controls \& Fail-Safe Modes](#privacy-controls--fail-safe-modes)
33
- - [Automated Benchmarking \& Research Evaluation](#automated-benchmarking--research-evaluation)
34
- - [Comprehensive Research Evaluation Summary (v1.2.0-research)](#comprehensive-research-evaluation-summary-v120-research)
35
- - [Multi-Workload Performance \& Latency Matrix](#multi-workload-performance--latency-matrix)
36
- - [Interactive Admin Dashboard](#interactive-admin-dashboard)
37
- - [Full Configuration Reference](#full-configuration-reference)
38
- - [Security \& Auth Utilities](#security--auth-utilities)
39
51
  - [Academic \& Research Defense](#academic--research-defense)
40
52
  - [Theoretical Foundation](#theoretical-foundation)
41
53
  - [License](#license)
42
54
 
43
55
  ---
44
- ## Architectural Philosophy
45
-
46
- `iri-shield` follows a **transparent, multi-layered security architecture**.
47
- Instead of relying on a single detection mechanism, it combines identity signals, configurable security rules, behavioural analysis, attack correlation, explainable risk scoring, and automated mitigation.
48
-
49
- ```mermaid
50
- flowchart TD
51
- A[Incoming HTTP Request] --> B[Base Security<br/>Helmet CORS Fail-Safe Policy]
52
- B --> C[Identity Continuity<br/>IP • Session • Client Hints • Drift Analysis]
53
- C --> D[Security Rule Engine<br/>SQLi • XSS • SSTI • Path Traversal • Custom Rules]
54
- D --> E[Behavioural Analysis<br/>Rolling Baseline • Anomaly Detection]
55
- E --> F[Attack Sequence Correlation<br/>Multi-Step Attack Detection]
56
- F --> G[Explainable Risk Scoring<br/>Risk Score • Confidence • Breakdown]
57
- G --> H[Automated Mitigation<br/>Rate Limit • Temporary/Permanent Block]
58
- H --> I[Secure Response & Redaction<br/>PII • Secrets • Sensitive Logs]
59
- ```
56
+
57
+ ## Overview
58
+
59
+ `iri-shield` is a security middleware layer for Express.js applications. It combines multiple security signals instead of relying on a single rule or signature. Requests can be evaluated using identity continuity, static attack detection, behavioural anomalies, sequence correlation, and explainable risk scoring before automated mitigation is applied.
60
+
61
+ The package is designed for **local development, security testing, research evaluation, and production-oriented Express.js deployments**. Storage can be configured for memory, SQLite, or MongoDB depending on the deployment environment.
62
+
63
+ > **Important:** Client profiling is probabilistic. `iri-shield` does not claim to provide authentication or guaranteed unique device identification.
60
64
 
61
65
  ---
62
66
 
@@ -68,22 +72,23 @@ flowchart TD
68
72
  | **Multi-Signal Profiling** | Evaluates **Identity Continuity** using IP address, session tokens, Client Hints (`sec-ch-ua`, `sec-ch-ua-platform`), user-agents, accept headers, and device context to detect evasion attempts without violating user privacy. |
69
73
  | **Configurable Rule Engine** | Individually toggle built-in threat detection rules or declare flexible **Custom Rules** (by endpoint, method, IP prefix, user-agent regex, or body fields). |
70
74
  | **Behavioural Baselining** | Continuously learns normal per-endpoint request rates (RPM) and flags statistical anomalies (`Behaviour deviation: 92%`). |
71
- | **🔗 Attack Sequence Correlation** | Evaluates ordered request chains to detect advanced multi-step campaigns (e.g., *Failed Auth ×3 → User Enumeration → Admin Access*). |
75
+ | **Attack Sequence Correlation** | Evaluates ordered request chains to detect advanced multi-step campaigns (e.g., *Failed Auth ×3 → User Enumeration → Admin Access*). |
72
76
  | **Privacy by Design** | Built-in SHA-256 IP hashing for persistent storage and automatic FIFO retention purging (`retentionDays: 30`). |
73
- | ** Fail-Safe Policies** | Choose between `fail-open` (resilience first) and `fail-closed` (strict containment) on internal subsystem failures. |
74
- | ** Built-in Benchmark Suite** | Automated performance comparison against baseline unshielded servers (`npm run benchmark`) measuring throughput, latency percentiles (p50/p95/p99), and defense efficacy. |
77
+ | **Fail-Safe Policies** | Choose between `fail-open` (resilience first) and `fail-closed` (strict containment) on internal subsystem failures. |
78
+ | **Built-in Benchmark Suite** | Automated performance comparison against baseline unshielded servers (`npm run benchmark`) measuring throughput, latency percentiles (p50/p95/p99), and defense efficacy. |
75
79
  | **Light-Theme Dashboard** | Enterprise management interface for real-time monitoring, reactive IP block/unblock, active alerts, security event forensics, and live configuration updates. |
76
80
  | **Deep PII/Secret Redaction** | Deep redaction for passwords, API keys, bearer tokens, emails, phone numbers, SSNs, Aadhaar numbers, and credit cards across responses and log storage. |
77
81
 
78
82
  ---
79
83
 
84
+
80
85
  ## Installation
81
86
 
82
87
  ```bash
83
88
  npm install iri-shield
84
89
  ```
85
90
 
86
- > **Requirements**: Node.js **>= 22.0.0** recommended for native SQLite (`node:sqlite`) support.
91
+ > **Requirements:** Node.js **>= 22.0.0** is recommended, especially when using the native SQLite (`node:sqlite`) storage engine.
87
92
 
88
93
  ---
89
94
 
@@ -107,8 +112,8 @@ const shield = createShield({
107
112
  dashboard: {
108
113
  enabled: true,
109
114
  path: '/iri-shield',
110
- username: 'admin',
111
- password: 'admin'
115
+ username: process.env.SHIELD_ADMIN_USER || 'admin',
116
+ password: process.env.SHIELD_ADMIN_PASSWORD || 'admin' // development only
112
117
  }
113
118
  });
114
119
 
@@ -128,57 +133,13 @@ app.get('/api/users', apiKeyAuth('my-secret-key'), (req, res) => {
128
133
  });
129
134
 
130
135
  app.listen(3000, () => {
131
- console.log('🚀 Server running on http://localhost:3000');
136
+ console.log('Server running on http://localhost:3000');
132
137
  console.log(' Dashboard available at http://localhost:3000/iri-shield');
133
138
  });
134
139
  ```
135
140
 
136
141
  ---
137
142
 
138
- ## Explainable Risk Scoring
139
-
140
- Every intercepted security event produces a transparent **Score Breakdown**:
141
-
142
- ```json
143
- {
144
- "score": 85,
145
- "riskLevel": "high",
146
- "confidence": 92,
147
- "action": "temporary_block",
148
- "breakdown": [
149
- { "rule": "sql_injection", "points": 40, "category": "injection", "confidence": 90, "label": "SQL Injection pattern" },
150
- { "rule": "sensitive_endpoint_access", "points": 20, "category": "anomaly", "confidence": 80, "label": "Access to sensitive endpoint: /admin" },
151
- { "rule": "correlated_attack_account_takeover", "points": 25, "category": "correlation", "confidence": 88, "label": "Possible account takeover / reconnaissance" }
152
- ]
153
- }
154
- ```
155
-
156
- In the **Admin Dashboard**, expanding any Security Event displays this structured breakdown table, enabling instant auditability for security analysts.
157
-
158
- ---
159
-
160
- ## Multi-Signal Identity Continuity
161
-
162
- Rather than claiming "guaranteed unique identification" (which is technically invalid across modern NATs and VPNs), `iri-shield` evaluates **Identity Continuity**:
163
-
164
- ```text
165
- Known Client Profile (C-89a1)
166
- ├── Baseline Hardware Hash
167
- ├── Platform & Client Hints (Windows / Chrome 120)
168
- └── Established Sessions
169
-
170
-
171
- Sudden Switch Detected:
172
- • New IP (203.0.113.88)
173
- • Missing Modern Sec-Fetch Headers
174
- • Identity Drift Count: +1
175
-
176
-
177
- Action: Risk Score Penalty (+15 pts) applied to request
178
- ```
179
-
180
- ---
181
-
182
143
  ## Security Rule Engine
183
144
 
184
145
  Toggle built-in detection modules or supply flexible custom rules:
@@ -223,113 +184,24 @@ const shield = createShield({
223
184
  });
224
185
  ```
225
186
 
226
- ---
227
-
228
- ## Behavioural Anomaly & Correlation
229
-
230
- ### 1. Rolling Behaviour Baseline
231
- Maintains a 5-minute rolling request rate (RPM) profile per IP and endpoint. Sudden traffic spikes (>3× baseline) trigger a proportional anomaly score penalty:
232
-
233
- ```text
234
- Endpoint: /api/login
235
- Baseline Rate: 2.4 req/min
236
- Current Rate: 45.0 req/min
237
- Behaviour Deviation: 94% (Anomaly Penalty: +18 pts)
238
- ```
239
-
240
- ### 2. Attack Sequence Correlation
241
- Detects multi-step attack patterns across request sequences:
242
- - **Account Takeover Chain**: Repeated failed logins followed by enumeration or admin route access.
243
- - **Secret Enumeration**: Sequential probes for `.env`, `wp-config`, `.git`, or `config.json`.
244
- - **Multi-Vector Escalation**: Combining SQL injection payloads with directory traversal probes.
245
- - **Scanner Sweeps**: Rapidly touching 5+ distinct endpoints with automated tool fingerprints.
246
187
 
247
188
  ---
248
189
 
249
- ## Privacy Controls & Fail-Safe Modes
250
-
251
- ```js
252
- const shield = createShield({
253
- // Fail-Safe Policy
254
- failureMode: 'fail-open', // 'fail-open' (default) | 'fail-closed'
255
-
256
- // Privacy by Design
257
- privacy: {
258
- hashIp: false, // If true, IPs are stored as SHA-256 hashes (e.g. sha256:4f8a...)
259
- retainRawIp: true, // Retains raw IP in memory exclusively for active block enforcement
260
- retentionDays: 30 // Automatically purges SQLite event/request logs older than 30 days
261
- }
262
- });
263
- ```
264
-
265
- ---
266
-
267
- ## Automated Benchmarking & Research Evaluation
268
-
269
- `iri-shield` includes a built-in automated evaluation suite to benchmark performance, threat detection efficacy, false positives, identity continuity, and data redaction against baseline Express.js:
270
-
271
- ```bash
272
- # Run comprehensive multi-experiment research evaluation suite
273
- npm run research:evaluate
274
-
275
- # Or run individual benchmark modules:
276
- npm run benchmark # Multi-workload latency/throughput matrix
277
- npm run security:evaluate # 220-vector category threat detection
278
- npm run security:compare # Vanilla Express vs iri-shield defense comparison
279
- npm run fp:evaluate # 2,000 legitimate queries false positive evaluation
280
- npm run identity:evaluate # 500-scenario identity continuity & drift evaluation
281
- npm run redaction:evaluate # 500-sample recursive PII masking evaluation
282
- ```
283
-
284
- ### Comprehensive Research Evaluation Summary (v1.2.0-research)
285
-
286
- | Evaluation Dimension | Workload / Dataset | Success Metric | Value | Baseline Comparison |
287
- | :--- | :--- | :--- | :--- | :--- |
288
- | **Threat Detection** | 220 Attack Payloads (14 Categories) | Overall Mitigation Rate | **97.3%** (214/220) | Vanilla Express: 0.0% (+97.7% Net Gain) |
289
- | **False Positive Rate** | 2,000 Legitimate Queries | True Negative Pass Rate | **100.00%** (0% FPR) | Zero business disruption on clean traffic |
290
- | **Identity Continuity** | 500 State Transitions | Profiling Accuracy | **100.0%** (0% False Drift) | Accurately flags IP/UA/Fingerprint drift |
291
- | **PII Data Redaction** | 500 Structured Payloads | Redaction Precision | **100.0%** (0% Overmask) | 5-level nested JSON & unstructured logs |
292
- | **Low-Load Overhead** | 300 Requests @ Concurrency 5 | Average Latency Delta | **+1.99 ms** | 2.97 ms (Base) vs 4.96 ms (Shield) |
293
-
294
- ### Multi-Workload Performance & Latency Matrix
295
-
296
- | Workload Configuration | Baseline Req/s | Shield Req/s | Throughput Impact | Base Latency (Avg) | Shield Latency (Avg) | Overhead (Δ) | Shield p95 | Shield p99 | Host CPU (Base vs Shield) | Cores Utilized (Base vs Shield) |
297
- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
298
- | **300 req @ c=5** | 1,904 req/s | 997 req/s | -47.6% | 2.97 ms | 4.96 ms | **+1.99 ms** | 7.80 ms | 9.77 ms | 17.6% vs 13.6% | 1.41 vs 1.09 cores |
299
- | **300 req @ c=15** | 2,404 req/s | 706 req/s | -70.6% | 6.28 ms | 21.49 ms | **+15.21 ms** | 34.24 ms | 35.73 ms | 12.8% vs 14.7% | 1.02 vs 1.17 cores |
300
- | **500 req @ c=5** | 2,669 req/s | 630 req/s | -76.4% | 1.86 ms | 7.92 ms | **+6.06 ms** | 12.16 ms | 16.58 ms | 14.9% vs 13.1% | 1.19 vs 1.05 cores |
301
- | **500 req @ c=15** | 3,097 req/s | 730 req/s | -76.4% | 4.79 ms | 20.44 ms | **+15.65 ms** | 29.80 ms | 33.06 ms | 15.2% vs 14.9% | 1.21 vs 1.19 cores |
302
-
303
- > **CPU Metric Definitions:**
304
- > - **Host Normalized CPU %**: Percentage of entire multi-core host compute bandwidth consumed ($\frac{\Delta \text{CPU}_{\mu s}}{\text{Duration}_s \times 10^6 \times N_{\text{cores}}} \times 100\%$).
305
- > - **Cores Utilized**: Total saturated CPU cores consumed by the V8 runtime / libuv thread pool ($\frac{\Delta \text{CPU}_{\mu s}}{\text{Duration}_s \times 10^6}$, where 1.0 = 1 full CPU core).
306
-
307
- JSON and CSV benchmark artifacts are automatically recorded in `results/`, `final-results/`, and `research-results/`.
308
-
309
- ---
310
-
311
- ## Interactive Admin Dashboard
312
-
313
- Access the real-time security dashboard at `/iri-shield`:
314
-
315
- - **Overview Panel**: Live requests, mitigated threats, latency gauges, threat distribution donut charts, and top endpoint statistics.
316
- - **Alerts**: Active suspicious client queue with one-click **Block IP** and **Dismiss** actions.
317
- - **Security Events**: Filterable by risk level (`critical`, `high`, `medium`, `low`) with expandable **Risk Breakdown Tables**, **Confidence Badges**, and **Correlation Banners**.
318
- - **Client Identity**: Identity continuity records, platform breakdown, IP rotation count, and anomaly histories.
319
- - **Blocked IPs**: Full persistent blocklist management with instant **Unblock** and manual block creation modal.
320
- - **Settings**: Live security mode switcher (`low`, `medium`, `high`), Security Rule Engine checkboxes, Privacy controls, and Redaction field managers.
321
-
322
- ---
323
-
324
- ## Full Configuration Reference
190
+ ## Configuration Reference
325
191
 
326
192
  ```js
327
193
  const shield = createShield({
328
194
  appName: 'iri-shield',
329
195
  security: 'medium', // 'low' | 'medium' | 'high'
330
- trustProxy: false,
196
+ trustProxy: false, // Set true if behind Cloudflare, Nginx, or AWS ALB
331
197
  failureMode: 'fail-open', // 'fail-open' | 'fail-closed'
332
198
 
199
+ // Testing Mode (False by default — enables header/body overrides for testing)
200
+ testing: {
201
+ enabled: false, // Keep FALSE in production
202
+ allowClientOverrides: false
203
+ },
204
+
333
205
  // HTTP Security Headers & CORS
334
206
  helmet: {
335
207
  enabled: true,
@@ -425,7 +297,7 @@ const shield = createShield({
425
297
 
426
298
  ---
427
299
 
428
- ## Security & Auth Utilities
300
+ ## Security & Auth Utilities
429
301
 
430
302
  `iri-shield` ships with built-in cryptographic security utilities:
431
303
 
@@ -448,6 +320,416 @@ app.get('/api/v1/me', jwtAuth(process.env.JWT_SECRET), handler);
448
320
  const hashed = await hashPassword('user-password', 12);
449
321
  const isValid = await comparePassword('input-password', hashed);
450
322
  ```
323
+ ---
324
+
325
+ # Guide for `Vercel`
326
+
327
+ This guide shows how to deploy an Express.js app protected by `iri-shield` on Vercel.
328
+
329
+ Vercel can deploy an Express server from a root `server.js` file with no extra routing config. `iri-shield` can use SQLite on Vercel too, but the SQLite file must be stored in `/tmp` because Vercel's deployed filesystem is read-only.
330
+
331
+ ## Production Deployment
332
+
333
+ `iri-shield` can be used with production Express.js applications, but deployment-specific settings should be applied carefully.
334
+
335
+ ### Disable Testing Mode
336
+
337
+ Testing mode is intended for benchmark replay and controlled security testing. It allows client identity overrides through `x-iri-test-*` headers.
338
+
339
+ > [!WARNING]
340
+ > **Never enable testing mode on a public production API.** Clients could spoof the test identity signals used for evaluation.
341
+
342
+ ```js
343
+ testing: {
344
+ enabled: false,
345
+ allowClientOverrides: false
346
+ }
347
+ ```
348
+
349
+ ### Reverse Proxy & Client IP
350
+
351
+ If the application runs behind a reverse proxy, load balancer, or CDN, configure Express and `iri-shield` to trust the proxy appropriately.
352
+
353
+ ```js
354
+ const app = express();
355
+
356
+ app.set('trust proxy', true);
357
+
358
+ const shield = createShield({
359
+ appName: 'my-production-api',
360
+ trustProxy: true
361
+ });
362
+ ```
363
+
364
+ Use this only when the deployment topology is actually trusted and configured to forward client IP information correctly.
365
+
366
+ ### Storage on Serverless Platforms
367
+
368
+ Storage choice depends on the runtime:
369
+
370
+ | Storage | Recommended Use | Persistence |
371
+ | :--- | :--- | :--- |
372
+ | `memory` | Tests, demos, temporary state | Instance memory only |
373
+ | `sqlite` | Local development / traditional Node.js servers | Local writable disk |
374
+ | `mongodb` | Serverless / distributed production deployments | External persistent database |
375
+
376
+ For Vercel or similar serverless platforms, **do not use `./data/...` as the SQLite path**. A writable `/tmp` location can be used for short-lived demos, but it should not be treated as permanent storage.
377
+
378
+ ```js
379
+ const isVercel = Boolean(process.env.VERCEL);
380
+
381
+ const shield = createShield({
382
+ appName: 'my-api',
383
+ storage: {
384
+ mode: process.env.IRI_STORAGE_MODE || (isVercel ? 'memory' : 'sqlite'),
385
+ sqliteFile:
386
+ process.env.IRI_SQLITE_FILE ||
387
+ (isVercel ? '/tmp/iri-shield.sqlite' : './data/iri-shield.sqlite'),
388
+ mongoUrl: process.env.IRI_MONGO_URL
389
+ }
390
+ });
391
+ ```
392
+
393
+ > **Recommendation:** For persistent production telemetry, block history, and analytics on serverless infrastructure, use `mongodb` or another external datastore.
394
+
395
+ ### Secure Dashboard Credentials
396
+
397
+ Do not commit dashboard credentials to source control.
398
+
399
+ ```js
400
+ dashboard: {
401
+ enabled: true,
402
+ path: '/iri-shield',
403
+ username: process.env.SHIELD_ADMIN_USER,
404
+ password: process.env.SHIELD_ADMIN_PASSWORD,
405
+ refreshMs: 60 * 1000
406
+ }
407
+ ```
408
+
409
+ ### Production Configuration
410
+
411
+ ```js
412
+ const express = require('express');
413
+ const { createShield } = require('iri-shield');
414
+
415
+ const app = express();
416
+ const isProd = process.env.NODE_ENV === 'production';
417
+ const isVercel = Boolean(process.env.VERCEL);
418
+
419
+ if (isProd) {
420
+ app.set('trust proxy', true);
421
+ }
422
+
423
+ const shield = createShield({
424
+ appName: process.env.APP_NAME || 'my-api',
425
+ security: isProd ? 'high' : 'medium',
426
+ trustProxy: isProd,
427
+ failureMode: 'fail-open',
428
+
429
+ testing: {
430
+ enabled: false,
431
+ allowClientOverrides: false
432
+ },
433
+
434
+ storage: {
435
+ mode: process.env.IRI_STORAGE_MODE || (isVercel ? 'memory' : 'sqlite'),
436
+ sqliteFile:
437
+ process.env.IRI_SQLITE_FILE ||
438
+ (isVercel ? '/tmp/iri-shield.sqlite' : './data/iri-shield.sqlite'),
439
+ mongoUrl: process.env.IRI_MONGO_URL
440
+ },
441
+
442
+ dashboard: {
443
+ enabled: true,
444
+ path: '/iri-shield',
445
+ username: process.env.SHIELD_ADMIN_USER,
446
+ password: process.env.SHIELD_ADMIN_PASSWORD
447
+ }
448
+ });
449
+
450
+ app.use(shield.middleware);
451
+ app.use('/iri-shield', shield.dashboard);
452
+ ```
453
+
454
+
455
+ ## Vercel Deployment
456
+
457
+ This section covers deploying an Express.js application protected by `iri-shield` to Vercel.
458
+
459
+ ### 1. Install Dependencies
460
+
461
+ ```bash
462
+ npm install express iri-shield
463
+ ```
464
+
465
+ Use Node.js **22 or newer** when using the native SQLite storage engine.
466
+
467
+ ### 2. Recommended Vercel Storage
468
+
469
+ For a simple Vercel smoke test, use `memory` storage:
470
+
471
+ ```js
472
+ storage: {
473
+ mode: process.env.IRI_STORAGE_MODE || 'memory'
474
+ }
475
+ ```
476
+
477
+ This avoids filesystem initialization errors and is suitable for testing the middleware, dashboard, detection rules, and API behaviour.
478
+
479
+ If you explicitly want SQLite for a short-lived demo, use `/tmp`:
480
+
481
+ ```js
482
+ storage: {
483
+ mode: 'sqlite',
484
+ sqliteFile: '/tmp/iri-shield.sqlite'
485
+ }
486
+ ```
487
+
488
+ Do **not** use:
489
+
490
+ ```js
491
+ sqliteFile: './data/iri-shield.sqlite'
492
+ ```
493
+
494
+ on Vercel. A deployment can fail when the package attempts to create that directory in the serverless filesystem.
495
+
496
+ > **Persistence note:** `/tmp` is temporary function-instance storage. It should not be used as the long-term source of truth for production analytics or block history.
497
+
498
+ ### 3. Serverless Express Entry Point
499
+
500
+ For a Vercel deployment, export the Express application instead of relying on a long-running local server.
501
+
502
+ ```js
503
+ 'use strict';
504
+
505
+ const express = require('express');
506
+ const { createShield } = require('iri-shield');
507
+
508
+ const app = express();
509
+
510
+ app.use(express.json({ limit: '200kb' }));
511
+
512
+ const shield = createShield({
513
+ appName: process.env.APP_NAME || 'my-api',
514
+ security: 'high',
515
+ trustProxy: true,
516
+
517
+ storage: {
518
+ mode: process.env.IRI_STORAGE_MODE || 'memory',
519
+ sqliteFile: process.env.IRI_SQLITE_FILE || '/tmp/iri-shield.sqlite',
520
+ mongoUrl: process.env.IRI_MONGO_URL
521
+ },
522
+
523
+ testing: {
524
+ enabled: false,
525
+ allowClientOverrides: false
526
+ },
527
+
528
+ dashboard: {
529
+ enabled: true,
530
+ path: '/iri-shield',
531
+ username: process.env.SHIELD_ADMIN_USER,
532
+ password: process.env.SHIELD_ADMIN_PASSWORD,
533
+ refreshMs: 60 * 1000
534
+ }
535
+ });
536
+
537
+ app.use(shield.middleware);
538
+ app.use('/iri-shield', shield.dashboard);
539
+
540
+ app.get('/', (req, res) => {
541
+ res.json({
542
+ ok: true,
543
+ name: process.env.APP_NAME || 'my-api',
544
+ package: 'iri-shield',
545
+ dashboard: '/iri-shield'
546
+ });
547
+ });
548
+
549
+ app.get('/metrics', (req, res) => {
550
+ res.json(shield.getStats());
551
+ });
552
+
553
+ module.exports = app;
554
+ ```
555
+
556
+ > **Local development:** If you also want `node server.js` locally, wrap `app.listen(...)` in `if (require.main === module)` so importing the app for serverless execution does not start a second listener.
557
+
558
+ ### 4. Environment Variables
559
+
560
+ Add these in **Vercel → Settings → Environment Variables**:
561
+
562
+ ```bash
563
+ NODE_ENV=production
564
+ APP_NAME=my-api
565
+ SHIELD_ADMIN_USER=admin
566
+ SHIELD_ADMIN_PASSWORD=replace-with-a-strong-secret
567
+ IRI_STORAGE_MODE=memory
568
+ ```
569
+
570
+ For a short-lived SQLite demo instead:
571
+
572
+ ```bash
573
+ IRI_STORAGE_MODE=sqlite
574
+ IRI_SQLITE_FILE=/tmp/iri-shield.sqlite
575
+ ```
576
+
577
+ For persistent production storage:
578
+
579
+ ```bash
580
+ IRI_STORAGE_MODE=mongodb
581
+ IRI_MONGO_URL=mongodb+srv://user:password@cluster.example.mongodb.net/iri-shield
582
+ ```
583
+
584
+ ### 5. Vercel Deployment Checklist
585
+
586
+ - [x] Use `memory` for the simplest serverless smoke test.
587
+ - [x] Use `/tmp` only when explicitly testing SQLite.
588
+ - [x] Disable `testing.enabled` in production.
589
+ - [x] Disable `allowClientOverrides` in production.
590
+ - [x] Use strong dashboard credentials from environment variables.
591
+ - [x] Use MongoDB or another external datastore for persistent production state.
592
+ - [x] Export the Express app for serverless execution.
593
+
594
+
595
+ ## Research & Benchmarking
596
+
597
+ `iri-shield` includes a built-in automated evaluation suite to benchmark performance, threat detection efficacy, false positives, identity continuity, and data redaction against baseline Express.js:
598
+
599
+ ```bash
600
+ # Run comprehensive multi-experiment research evaluation suite
601
+ npm run research:evaluate
602
+
603
+ # Or run individual benchmark modules:
604
+ npm run benchmark # Multi-workload latency/throughput matrix
605
+ npm run security:evaluate # 220-vector category threat detection
606
+ npm run security:compare # Vanilla Express vs iri-shield defense comparison
607
+ npm run fp:evaluate # 2,000 legitimate queries false positive evaluation
608
+ npm run identity:evaluate # 500-scenario identity continuity & drift evaluation
609
+ npm run redaction:evaluate # 500-sample recursive PII masking evaluation
610
+ ```
611
+
612
+ ### Comprehensive Research Evaluation Summary (v1.2.0-research)
613
+
614
+ | Evaluation Dimension | Workload / Dataset | Success Metric | Value | Baseline Comparison |
615
+ | :--- | :--- | :--- | :--- | :--- |
616
+ | **Threat Detection** | 220 Attack Payloads (14 Categories) | Overall Mitigation Rate | **97.3%** (214/220) | Vanilla Express: 0.0% blocked in the separate baseline comparison |
617
+ | **False Positive Rate** | 2,000 Legitimate Queries | False Positive Rate | **0.00% FPR** | Zero business disruption on clean traffic |
618
+ | **Identity Continuity** | 500 State Transitions | Profiling Accuracy | **100.0%** (0% False Drift) | Accurately flags IP/UA/Fingerprint drift |
619
+ | **PII Data Redaction** | 500 Structured Payloads | Redaction Precision | **100.0%** (0% Overmask) | 5-level nested JSON & unstructured logs |
620
+ | **Low-Load Overhead** | 300 Requests @ Concurrency 5 | Average Latency Delta | **+1.99 ms** | 2.97 ms (Base) vs 4.96 ms (Shield) |
621
+
622
+ ### Multi-Workload Performance & Latency Matrix
623
+
624
+ | Workload Configuration | Baseline Req/s | Shield Req/s | Throughput Impact | Base Latency (Avg) | Shield Latency (Avg) | Overhead (Δ) | Shield p95 | Shield p99 | Host CPU (Base vs Shield) | Cores Utilized (Base vs Shield) |
625
+ | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
626
+ | **300 req @ c=5** | 1,904 req/s | 997 req/s | -47.6% | 2.97 ms | 4.96 ms | **+1.99 ms** | 7.80 ms | 9.77 ms | 17.6% vs 13.6% | 1.41 vs 1.09 cores |
627
+ | **300 req @ c=15** | 2,404 req/s | 706 req/s | -70.6% | 6.28 ms | 21.49 ms | **+15.21 ms** | 34.24 ms | 35.73 ms | 12.8% vs 14.7% | 1.02 vs 1.17 cores |
628
+ | **500 req @ c=5** | 2,669 req/s | 630 req/s | -76.4% | 1.86 ms | 7.92 ms | **+6.06 ms** | 12.16 ms | 16.58 ms | 14.9% vs 13.1% | 1.19 vs 1.05 cores |
629
+ | **500 req @ c=15** | 3,097 req/s | 730 req/s | -76.4% | 4.79 ms | 20.44 ms | **+15.65 ms** | 29.80 ms | 33.06 ms | 15.2% vs 14.9% | 1.21 vs 1.19 cores |
630
+
631
+ > **CPU Metric Definitions:**
632
+ > - **Host Normalized CPU %**: Percentage of entire multi-core host compute bandwidth consumed ($\frac{\Delta \text{CPU}_{\mu s}}{\text{Duration}_s \times 10^6 \times N_{\text{cores}}} \times 100\%$).
633
+ > - **Cores Utilized**: Total saturated CPU cores consumed by the V8 runtime / libuv thread pool ($\frac{\Delta \text{CPU}_{\mu s}}{\text{Duration}_s \times 10^6}$, where 1.0 = 1 full CPU core).
634
+
635
+ JSON and CSV benchmark artifacts are automatically recorded in `results/`, `final-results/`, and `research-results/`.
636
+
637
+ ---
638
+
639
+ ## Admin Dashboard
640
+
641
+ Access the real-time security dashboard at `/iri-shield`:
642
+
643
+ - **Overview Panel**: Live requests, mitigated threats, latency gauges, threat distribution donut charts, and top endpoint statistics.
644
+ - **Alerts**: Active suspicious client queue with one-click **Block IP** and **Dismiss** actions.
645
+ - **Security Events**: Filterable by risk level (`critical`, `high`, `medium`, `low`) with expandable **Risk Breakdown Tables**, **Confidence Badges**, and **Correlation Banners**.
646
+ - **Client Identity**: Identity continuity records, platform breakdown, IP rotation count, and anomaly histories.
647
+ - **Blocked IPs**: Full persistent blocklist management with instant **Unblock** and manual block creation modal.
648
+ - **Settings**: Live security mode switcher (`low`, `medium`, `high`), Security Rule Engine checkboxes, Privacy controls, and Redaction field managers.
649
+
650
+
651
+ ---
652
+
653
+ ## Explainable Risk Scoring
654
+
655
+ Every intercepted security event produces a transparent **Score Breakdown**:
656
+
657
+ ```json
658
+ {
659
+ "score": 85,
660
+ "riskLevel": "high",
661
+ "confidence": 92,
662
+ "action": "temporary_block",
663
+ "breakdown": [
664
+ { "rule": "sql_injection", "points": 40, "category": "injection", "confidence": 90, "label": "SQL Injection pattern" },
665
+ { "rule": "sensitive_endpoint_access", "points": 20, "category": "anomaly", "confidence": 80, "label": "Access to sensitive endpoint: /admin" },
666
+ { "rule": "correlated_attack_account_takeover", "points": 25, "category": "correlation", "confidence": 88, "label": "Possible account takeover / reconnaissance" }
667
+ ]
668
+ }
669
+ ```
670
+
671
+ In the **Admin Dashboard**, expanding any Security Event displays this structured breakdown table, enabling instant auditability for security analysts.
672
+
673
+ ---
674
+
675
+ ## Multi-Signal Identity Continuity
676
+
677
+ Rather than claiming "guaranteed unique identification" (which is technically invalid across modern NATs and VPNs), `iri-shield` evaluates **Identity Continuity**:
678
+
679
+ ```text
680
+ Known Client Profile (C-89a1)
681
+ ├── Baseline Hardware Hash
682
+ ├── Platform & Client Hints (Windows / Chrome 120)
683
+ └── Established Sessions
684
+
685
+
686
+ Sudden Switch Detected:
687
+ • New IP (203.0.113.88)
688
+ • Missing Modern Sec-Fetch Headers
689
+ • Identity Drift Count: +1
690
+
691
+
692
+ Action: Risk Score Penalty (+15 pts) applied to request
693
+ ```
694
+
695
+ ---
696
+
697
+ ## Behavioural Anomaly & Attack Correlation
698
+
699
+ ### 1. Rolling Behaviour Baseline
700
+ Maintains a 5-minute rolling request rate (RPM) profile per IP and endpoint. Sudden traffic spikes (>3× baseline) trigger a proportional anomaly score penalty:
701
+
702
+ ```text
703
+ Endpoint: /api/login
704
+ Baseline Rate: 2.4 req/min
705
+ Current Rate: 45.0 req/min
706
+ Behaviour Deviation: 94% (Anomaly Penalty: +18 pts)
707
+ ```
708
+
709
+ ### 2. Attack Sequence Correlation
710
+ Detects multi-step attack patterns across request sequences:
711
+ - **Account Takeover Chain**: Repeated failed logins followed by enumeration or admin route access.
712
+ - **Secret Enumeration**: Sequential probes for `.env`, `wp-config`, `.git`, or `config.json`.
713
+ - **Multi-Vector Escalation**: Combining SQL injection payloads with directory traversal probes.
714
+ - **Scanner Sweeps**: Rapidly touching 5+ distinct endpoints with automated tool fingerprints.
715
+
716
+ ---
717
+
718
+ ## Privacy Controls & Fail-Safe Modes
719
+
720
+ ```js
721
+ const shield = createShield({
722
+ // Fail-Safe Policy
723
+ failureMode: 'fail-open', // 'fail-open' (default) | 'fail-closed'
724
+
725
+ // Privacy by Design
726
+ privacy: {
727
+ hashIp: false, // If true, IPs are stored as SHA-256 hashes (e.g. sha256:4f8a...)
728
+ retainRawIp: true, // Retains raw IP in memory exclusively for active block enforcement
729
+ retentionDays: 30 // Automatically purges SQLite event/request logs older than 30 days
730
+ }
731
+ });
732
+ ```
451
733
 
452
734
  ---
453
735
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iri-shield",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
4
4
  "description": "Enterprise Express.js security middleware — explainable risk scoring, multi-signal identity profiling, behavioural anomaly detection, attack correlation, sensitive-data redaction, and dashboard monitoring.",
5
5
  "keywords": [
6
6
  "iri-shield",
package/src/index.js CHANGED
@@ -544,12 +544,14 @@ function patchResponse(res, storage, config) {
544
544
  const originalSend = res.send.bind(res);
545
545
 
546
546
  res.json = function(payload) {
547
+ if (res.locals.iriShieldSkipRedaction) return originalJson(payload);
547
548
  const result = redactPayload(payload, config.redaction);
548
549
  if (result.redactions > 0) storage.recordRedaction(result.redactions);
549
550
  return originalJson(result.value);
550
551
  };
551
552
 
552
553
  res.send = function(payload) {
554
+ if (res.locals.iriShieldSkipRedaction) return originalSend(payload);
553
555
  if (typeof payload !== 'string') return originalSend(payload);
554
556
  const result = redactPayload(payload, config.redaction);
555
557
  if (result.redactions > 0) storage.recordRedaction(result.redactions);