iri-shield 1.2.2 → 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 +454 -279
  2. package/package.json +1 -1
  3. package/src/index.js +2 -0
package/README.md CHANGED
@@ -3,15 +3,14 @@
3
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-risk--scoring-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
- > **Open-source 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,49 +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
- - [🚀 Real-World \& Production Deployment Guide](#-real-world--production-deployment-guide)
38
- - [1. Disabling Testing Mode for Real Traffic](#1-disabling-testing-mode-for-real-traffic)
39
- - [2. Reverse Proxy \& Real Client IP (`trustProxy`)](#2-reverse-proxy--real-client-ip-trustproxy)
40
- - [3. Securing Admin Dashboard Credentials](#3-securing-admin-dashboard-credentials)
41
- - [4. Production Ready Configuration Example](#4-production-ready-configuration-example)
42
- - [Full Configuration Reference](#full-configuration-reference)
43
- - [Security \& Auth Utilities](#security--auth-utilities)
44
51
  - [Academic \& Research Defense](#academic--research-defense)
45
52
  - [Theoretical Foundation](#theoretical-foundation)
46
53
  - [License](#license)
47
54
 
48
55
  ---
49
- ## Architectural Philosophy
50
-
51
- `iri-shield` follows a **transparent, multi-layered security architecture**.
52
- 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.
53
-
54
- ```mermaid
55
- flowchart TD
56
- A[Incoming HTTP Request] --> B[Base Security<br/>Helmet CORS Fail-Safe Policy]
57
- B --> C[Identity Continuity<br/>IP • Session • Client Hints • Drift Analysis]
58
- C --> D[Security Rule Engine<br/>SQLi • XSS • SSTI • Path Traversal • Custom Rules]
59
- D --> E[Behavioural Analysis<br/>Rolling Baseline • Anomaly Detection]
60
- E --> F[Attack Sequence Correlation<br/>Multi-Step Attack Detection]
61
- F --> G[Explainable Risk Scoring<br/>Risk Score • Confidence • Breakdown]
62
- G --> H[Automated Mitigation<br/>Rate Limit • Temporary/Permanent Block]
63
- H --> I[Secure Response & Redaction<br/>PII • Secrets • Sensitive Logs]
64
- ```
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.
65
64
 
66
65
  ---
67
66
 
@@ -73,22 +72,23 @@ flowchart TD
73
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. |
74
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). |
75
74
  | **Behavioural Baselining** | Continuously learns normal per-endpoint request rates (RPM) and flags statistical anomalies (`Behaviour deviation: 92%`). |
76
- | **🔗 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*). |
77
76
  | **Privacy by Design** | Built-in SHA-256 IP hashing for persistent storage and automatic FIFO retention purging (`retentionDays: 30`). |
78
- | ** Fail-Safe Policies** | Choose between `fail-open` (resilience first) and `fail-closed` (strict containment) on internal subsystem failures. |
79
- | ** 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. |
80
79
  | **Light-Theme Dashboard** | Enterprise management interface for real-time monitoring, reactive IP block/unblock, active alerts, security event forensics, and live configuration updates. |
81
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. |
82
81
 
83
82
  ---
84
83
 
84
+
85
85
  ## Installation
86
86
 
87
87
  ```bash
88
88
  npm install iri-shield
89
89
  ```
90
90
 
91
- > **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.
92
92
 
93
93
  ---
94
94
 
@@ -112,8 +112,8 @@ const shield = createShield({
112
112
  dashboard: {
113
113
  enabled: true,
114
114
  path: '/iri-shield',
115
- username: 'admin',
116
- password: 'admin'
115
+ username: process.env.SHIELD_ADMIN_USER || 'admin',
116
+ password: process.env.SHIELD_ADMIN_PASSWORD || 'admin' // development only
117
117
  }
118
118
  });
119
119
 
@@ -133,57 +133,13 @@ app.get('/api/users', apiKeyAuth('my-secret-key'), (req, res) => {
133
133
  });
134
134
 
135
135
  app.listen(3000, () => {
136
- console.log('🚀 Server running on http://localhost:3000');
136
+ console.log('Server running on http://localhost:3000');
137
137
  console.log(' Dashboard available at http://localhost:3000/iri-shield');
138
138
  });
139
139
  ```
140
140
 
141
141
  ---
142
142
 
143
- ## Explainable Risk Scoring
144
-
145
- Every intercepted security event produces a transparent **Score Breakdown**:
146
-
147
- ```json
148
- {
149
- "score": 85,
150
- "riskLevel": "high",
151
- "confidence": 92,
152
- "action": "temporary_block",
153
- "breakdown": [
154
- { "rule": "sql_injection", "points": 40, "category": "injection", "confidence": 90, "label": "SQL Injection pattern" },
155
- { "rule": "sensitive_endpoint_access", "points": 20, "category": "anomaly", "confidence": 80, "label": "Access to sensitive endpoint: /admin" },
156
- { "rule": "correlated_attack_account_takeover", "points": 25, "category": "correlation", "confidence": 88, "label": "Possible account takeover / reconnaissance" }
157
- ]
158
- }
159
- ```
160
-
161
- In the **Admin Dashboard**, expanding any Security Event displays this structured breakdown table, enabling instant auditability for security analysts.
162
-
163
- ---
164
-
165
- ## Multi-Signal Identity Continuity
166
-
167
- Rather than claiming "guaranteed unique identification" (which is technically invalid across modern NATs and VPNs), `iri-shield` evaluates **Identity Continuity**:
168
-
169
- ```text
170
- Known Client Profile (C-89a1)
171
- ├── Baseline Hardware Hash
172
- ├── Platform & Client Hints (Windows / Chrome 120)
173
- └── Established Sessions
174
-
175
-
176
- Sudden Switch Detected:
177
- • New IP (203.0.113.88)
178
- • Missing Modern Sec-Fetch Headers
179
- • Identity Drift Count: +1
180
-
181
-
182
- Action: Risk Score Penalty (+15 pts) applied to request
183
- ```
184
-
185
- ---
186
-
187
143
  ## Security Rule Engine
188
144
 
189
145
  Toggle built-in detection modules or supply flexible custom rules:
@@ -228,201 +184,10 @@ const shield = createShield({
228
184
  });
229
185
  ```
230
186
 
231
- ---
232
-
233
- ## Behavioural Anomaly & Correlation
234
-
235
- ### 1. Rolling Behaviour Baseline
236
- Maintains a 5-minute rolling request rate (RPM) profile per IP and endpoint. Sudden traffic spikes (>3× baseline) trigger a proportional anomaly score penalty:
237
-
238
- ```text
239
- Endpoint: /api/login
240
- Baseline Rate: 2.4 req/min
241
- Current Rate: 45.0 req/min
242
- Behaviour Deviation: 94% (Anomaly Penalty: +18 pts)
243
- ```
244
-
245
- ### 2. Attack Sequence Correlation
246
- Detects multi-step attack patterns across request sequences:
247
- - **Account Takeover Chain**: Repeated failed logins followed by enumeration or admin route access.
248
- - **Secret Enumeration**: Sequential probes for `.env`, `wp-config`, `.git`, or `config.json`.
249
- - **Multi-Vector Escalation**: Combining SQL injection payloads with directory traversal probes.
250
- - **Scanner Sweeps**: Rapidly touching 5+ distinct endpoints with automated tool fingerprints.
251
-
252
- ---
253
-
254
- ## Privacy Controls & Fail-Safe Modes
255
-
256
- ```js
257
- const shield = createShield({
258
- // Fail-Safe Policy
259
- failureMode: 'fail-open', // 'fail-open' (default) | 'fail-closed'
260
-
261
- // Privacy by Design
262
- privacy: {
263
- hashIp: false, // If true, IPs are stored as SHA-256 hashes (e.g. sha256:4f8a...)
264
- retainRawIp: true, // Retains raw IP in memory exclusively for active block enforcement
265
- retentionDays: 30 // Automatically purges SQLite event/request logs older than 30 days
266
- }
267
- });
268
- ```
269
-
270
- ---
271
-
272
- ## Automated Benchmarking & Research Evaluation
273
-
274
- `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:
275
-
276
- ```bash
277
- # Run comprehensive multi-experiment research evaluation suite
278
- npm run research:evaluate
279
-
280
- # Or run individual benchmark modules:
281
- npm run benchmark # Multi-workload latency/throughput matrix
282
- npm run security:evaluate # 220-vector category threat detection
283
- npm run security:compare # Vanilla Express vs iri-shield defense comparison
284
- npm run fp:evaluate # 2,000 legitimate queries false positive evaluation
285
- npm run identity:evaluate # 500-scenario identity continuity & drift evaluation
286
- npm run redaction:evaluate # 500-sample recursive PII masking evaluation
287
- ```
288
-
289
- ### Comprehensive Research Evaluation Summary (v1.2.0-research)
290
-
291
- | Evaluation Dimension | Workload / Dataset | Success Metric | Value | Baseline Comparison |
292
- | :--- | :--- | :--- | :--- | :--- |
293
- | **Threat Detection** | 220 Attack Payloads (14 Categories) | Overall Mitigation Rate | **97.3%** (214/220) | Vanilla Express: 0.0% (+97.7% Net Gain) |
294
- | **False Positive Rate** | 2,000 Legitimate Queries | True Negative Pass Rate | **100.00%** (0% FPR) | Zero business disruption on clean traffic |
295
- | **Identity Continuity** | 500 State Transitions | Profiling Accuracy | **100.0%** (0% False Drift) | Accurately flags IP/UA/Fingerprint drift |
296
- | **PII Data Redaction** | 500 Structured Payloads | Redaction Precision | **100.0%** (0% Overmask) | 5-level nested JSON & unstructured logs |
297
- | **Low-Load Overhead** | 300 Requests @ Concurrency 5 | Average Latency Delta | **+1.99 ms** | 2.97 ms (Base) vs 4.96 ms (Shield) |
298
-
299
- ### Multi-Workload Performance & Latency Matrix
300
-
301
- | 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) |
302
- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
303
- | **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 |
304
- | **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 |
305
- | **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 |
306
- | **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 |
307
-
308
- > **CPU Metric Definitions:**
309
- > - **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\%$).
310
- > - **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).
311
-
312
- JSON and CSV benchmark artifacts are automatically recorded in `results/`, `final-results/`, and `research-results/`.
313
-
314
- ---
315
-
316
- ## Interactive Admin Dashboard
317
-
318
- Access the real-time security dashboard at `/iri-shield`:
319
-
320
- - **Overview Panel**: Live requests, mitigated threats, latency gauges, threat distribution donut charts, and top endpoint statistics.
321
- - **Alerts**: Active suspicious client queue with one-click **Block IP** and **Dismiss** actions.
322
- - **Security Events**: Filterable by risk level (`critical`, `high`, `medium`, `low`) with expandable **Risk Breakdown Tables**, **Confidence Badges**, and **Correlation Banners**.
323
- - **Client Identity**: Identity continuity records, platform breakdown, IP rotation count, and anomaly histories.
324
- - **Blocked IPs**: Full persistent blocklist management with instant **Unblock** and manual block creation modal.
325
- - **Settings**: Live security mode switcher (`low`, `medium`, `high`), Security Rule Engine checkboxes, Privacy controls, and Redaction field managers.
326
-
327
- ---
328
-
329
- ## 🚀 Real-World & Production Deployment Guide
330
-
331
- `iri-shield` is built to protect production Express.js APIs against real-world threats. When moving from local testing or dataset benchmarks to production, follow these steps:
332
-
333
- ### 1. Disabling Testing Mode for Real Traffic
334
- By default in `iri-shield`, **testing mode is already disabled** (`enabled: false`). However, if you enabled it during local simulation or integration testing, ensure it is set to `false` or removed in production.
335
-
336
- > [!WARNING]
337
- > When `testing.enabled: true`, clients can spoof their IP, User-Agent, and Session ID via custom headers (`x-iri-test-ip`, `x-iri-test-user-agent`, etc.) for benchmark replay. **Never enable testing mode in production environments!**
338
-
339
- ```js
340
- const shield = createShield({
341
- appName: 'my-production-api',
342
- // Ensure testing mode is off (or simply omit the testing property)
343
- testing: {
344
- enabled: false,
345
- allowClientOverrides: false
346
- },
347
- // ...
348
- });
349
- ```
350
-
351
- ### 2. Reverse Proxy & Real Client IP (`trustProxy`)
352
- If your application runs behind a reverse proxy, load balancer, or CDN (such as **Nginx**, **Cloudflare**, **AWS ALB**, or **Heroku**):
353
- - Set `trustProxy: true` (or express `app.set('trust-proxy', 1)`) so `iri-shield` reads real client IPs from `CF-Connecting-IP`, `X-Forwarded-For`, or `X-Real-IP`.
354
-
355
- ```js
356
- const app = express();
357
- app.set('trust proxy', true);
358
-
359
- const shield = createShield({
360
- appName: 'my-production-api',
361
- trustProxy: true,
362
- // ...
363
- });
364
- ```
365
-
366
- ### 3. Securing Admin Dashboard Credentials
367
- Never hardcode default credentials in production code. Load admin username and password from environment variables:
368
-
369
- ```js
370
- dashboard: {
371
- enabled: true,
372
- path: '/iri-shield',
373
- username: process.env.SHIELD_ADMIN_USER || 'admin',
374
- password: process.env.SHIELD_ADMIN_PASSWORD, // enforce strong secret via .env
375
- refreshMs: 60 * 1000
376
- }
377
- ```
378
-
379
- ### 4. Production Ready Configuration Example
380
-
381
- ```js
382
- const express = require('express');
383
- const { createShield } = require('iri-shield');
384
-
385
- const app = express();
386
- const isProd = process.env.NODE_ENV === 'production';
387
-
388
- if (isProd) {
389
- app.set('trust proxy', true);
390
- }
391
-
392
- const shield = createShield({
393
- appName: process.env.APP_NAME || 'my-api',
394
- security: isProd ? 'high' : 'medium', // 'low' | 'medium' | 'high'
395
- trustProxy: isProd,
396
- failureMode: 'fail-open', // resilient: won't bring down app on errors
397
-
398
- // Testing mode — automatically OFF in production
399
- testing: {
400
- enabled: !isProd,
401
- allowClientOverrides: !isProd
402
- },
403
-
404
- // Persistent storage for production blocks and analytics
405
- storage: {
406
- mode: process.env.STORAGE_MODE || 'sqlite', // 'sqlite' or 'mongodb'
407
- sqliteFile: process.env.SQLITE_PATH || './data/iri-shield.sqlite'
408
- },
409
-
410
- // Secure Dashboard
411
- dashboard: {
412
- enabled: true,
413
- path: '/iri-shield',
414
- username: process.env.SHIELD_ADMIN_USER || 'admin',
415
- password: process.env.SHIELD_ADMIN_PASSWORD || 'ChangeThisSecret123!'
416
- }
417
- });
418
-
419
- app.use(shield.middleware);
420
- app.use('/iri-shield', shield.dashboard);
421
- ```
422
187
 
423
188
  ---
424
189
 
425
- ## Full Configuration Reference
190
+ ## Configuration Reference
426
191
 
427
192
  ```js
428
193
  const shield = createShield({
@@ -532,7 +297,7 @@ const shield = createShield({
532
297
 
533
298
  ---
534
299
 
535
- ## Security & Auth Utilities
300
+ ## Security & Auth Utilities
536
301
 
537
302
  `iri-shield` ships with built-in cryptographic security utilities:
538
303
 
@@ -555,6 +320,416 @@ app.get('/api/v1/me', jwtAuth(process.env.JWT_SECRET), handler);
555
320
  const hashed = await hashPassword('user-password', 12);
556
321
  const isValid = await comparePassword('input-password', hashed);
557
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
+ ```
558
733
 
559
734
  ---
560
735
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iri-shield",
3
- "version": "1.2.2",
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);