mdefender-pro 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,194 +1,166 @@
1
- # MDefender Pro
1
+ # MDefender Pro — Node.js / Express WAF Middleware
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/mdefender-pro.svg)](https://www.npmjs.com/package/mdefender-pro)
4
- [![license](https://img.shields.io/npm/l/mdefender-pro.svg)](https://github.com/mahabub251595/mdefender-pro/blob/main/LICENSE)
4
+ [![license](https://img.shields.io/npm/l/mdefender-pro.svg)](https://github.com/mdefender/mdefender/blob/main/LICENSE)
5
+ [![Zero Config](https://img.shields.io/badge/Block%20Page-Bundled%20Auto-green.svg)](#bundled-403-block-page)
5
6
 
6
- **MDefender Pro** is a Web Application Firewall (WAF) middleware for Node.js/Express. It intercepts incoming HTTP requests and sends them to the MDefender Pro API for real-time threat analysis, blocking malicious traffic such as XSS, SQLi, CSRF, and other OWASP Top 10 attacks.
7
+ **MDefender Pro** is an enterprise-grade Web Application Firewall (WAF) middleware for Node.js and Express. It inspects incoming HTTP requests in real-time against **2,000 verified signatures** and a **5.2M+ attack vector Machine Learning engine**, automatically blocking SQL injection, Cross-Site Scripting (XSS), Remote Code Execution (RCE), Directory Traversal (LFI), bot scrapers, and zero-day vulnerabilities.
7
8
 
8
- ## Installation
9
+ ---
10
+
11
+ ## Key Features
12
+
13
+ - 🛡️ **Zero Setup Cyber Block Page**: Bundled automatically with the package — no external HTML or static file hosting required.
14
+ - ⚡ **Sub-Millisecond In-Memory Caching**: Template and rules are cached in memory for instantaneous rendering (<5ms).
15
+ - 🔑 **Flexible API Key Authentication**: Configure via `mdefender.config.js`, interactive CLI (`npx mdefender-pro init`), environment variables, or inline parameters.
16
+ - 🚦 **Fail-Open Safety Mechanism**: If cloud telemetry times out, legitimate traffic passes smoothly without blocking customers.
17
+ - 📦 **Zero External Runtime Dependencies**: Pure Node.js standard libraries (`http`, `https`, `crypto`).
18
+
19
+ ---
20
+
21
+ ## 1. Installation
22
+
23
+ Install the official package in your Node.js / Express backend project:
9
24
 
10
25
  ```bash
11
26
  npm install mdefender-pro
12
27
  ```
13
28
 
14
- ## Quick Start
29
+ *(When you install `mdefender-pro`, the responsive Cyber 403 Block Page is bundled automatically).*
15
30
 
16
- ```js
17
- const express = require('express');
18
- const mdefender = require('mdefender-pro');
31
+ ---
19
32
 
20
- const app = express();
33
+ ## 2. Quick Setup
21
34
 
22
- // Protect all routes
23
- app.use(mdefender({
24
- apiKey: 'your-api-key-here',
25
- domain: 'example.com',
26
- }));
35
+ ### Option A: Interactive CLI (1-Click)
27
36
 
28
- app.get('/', (req, res) => {
29
- res.send('Hello, protected world!');
30
- });
37
+ Run the interactive setup tool in your project directory:
31
38
 
32
- app.listen(3000, () => {
33
- console.log('Server running on port 3000');
34
- });
39
+ ```bash
40
+ npx mdefender-pro init
35
41
  ```
36
42
 
37
- ## Configuration
43
+ This prompts for your API key and creates a ready-to-use `mdefender.config.js`.
38
44
 
39
- You can configure MDefender in three ways:
45
+ ### Option B: Manual Config File (`mdefender.config.js`)
40
46
 
41
- 1. **Inline** - Pass options directly to the middleware
42
- 2. **Config file** - Use `mdefender.config.js` or `mdefender.json`
43
- 3. **package.json** - Add a `"mdefender"` key to your `package.json`
44
-
45
- Priority order: **Inline options > Config file > package.json**
46
-
47
- ### Options
48
-
49
- | Option | Type | Default | Description |
50
- |---|---|---|---|
51
- | `apiKey` | `string` | `''` | **Required.** Your MDefender Pro API key |
52
- | `domain` | `string` | `''` | **Required.** The domain to protect |
53
- | `apiEndpoint` | `string` | `'https://mdefender-pro.onrender.com'` | MDefender API base URL |
54
- | `mode` | `'block' \| 'monitor' \| 'off'` | `'block'` | `block` = block threats, `monitor` = log only, `off` = disabled |
55
- | `blockStatusCode` | `number` | `403` | HTTP status code for blocked requests |
56
- | `timeout` | `number` | `5000` | API request timeout in milliseconds |
57
- | `maxBodySize` | `number` | `1048576` | Max request body size in bytes (1MB) |
58
- | `logBlocked` | `boolean` | `true` | Log blocked requests to console |
59
- | `customBlockPage` | `string \| null` | `null` | Path to a custom HTML file for block page |
60
- | `skipPaths` | `string[]` | `['/health', '/favicon.ico']` | Paths to skip WAF checking |
61
- | `skipUserAgents` | `string[]` | `[]` | User agents to skip (substring match) |
62
- | `skipMethods` | `string[]` | `[]` | HTTP methods to skip entirely |
63
- | `headers` | `boolean` | `true` | Forward original request headers to API |
64
- | `onError` | `'allow' \| 'block'` | `'allow'` | Behavior when API is unreachable |
65
-
66
- ### Config File: `mdefender.config.js`
47
+ Create `mdefender.config.js` in your project root:
67
48
 
68
49
  ```js
50
+ // mdefender.config.js
69
51
  module.exports = {
70
- apiKey: process.env.MDEFENDER_API_KEY,
71
- domain: 'example.com',
72
- mode: 'block',
73
- skipPaths: ['/health', '/ping', '/favicon.ico'],
74
- logBlocked: true,
75
- };
76
- ```
52
+ // Your Website API Key from MDefender Dashboard -> Websites
53
+ apiKey: process.env.MDEFENDER_API_KEY || 'your_64_char_api_key_here',
77
54
 
78
- ### Config File: `mdefender.json`
55
+ // Domain registered in MDefender
56
+ domain: 'yourdomain.com',
79
57
 
80
- ```json
81
- {
82
- "apiKey": "your-api-key-here",
83
- "domain": "example.com",
84
- "mode": "block",
85
- "skipPaths": ["/health", "/ping"],
86
- "onError": "allow"
87
- }
88
- ```
58
+ // WAF Cloud / Self-hosted endpoint
59
+ apiEndpoint: 'https://mdefender-pro-6e3r.onrender.com', // or 'http://127.0.0.1:8000' for local dev
89
60
 
90
- ### `package.json`
61
+ // Protection mode: 'block' (active) | 'monitor' (log-only) | 'off'
62
+ mode: 'block',
91
63
 
92
- ```json
93
- {
94
- "name": "my-app",
95
- "mdefender": {
96
- "apiKey": "your-api-key-here",
97
- "domain": "example.com"
98
- }
99
- }
64
+ // Log blocked attacks in console
65
+ logBlocked: true
66
+ };
100
67
  ```
101
68
 
102
- ## Advanced Usage
69
+ ---
103
70
 
104
- ### Custom Block Page
71
+ ## 3. Attach Middleware to Express
105
72
 
106
- Provide a path to your own HTML file:
73
+ Add `app.use(mdefender())` after your standard body parsers (`express.json()`) and before your routes:
107
74
 
108
75
  ```js
109
- app.use(mdefender({
110
- apiKey: 'your-key',
111
- domain: 'example.com',
112
- customBlockPage: path.join(__dirname, 'views', 'block.html'),
113
- }));
114
- ```
76
+ const express = require('express');
77
+ const cors = require('cors');
78
+ const mdefender = require('mdefender-pro');
115
79
 
116
- ### Monitor Mode (Log Only)
80
+ const app = express();
117
81
 
118
- Run in monitoring mode to analyze requests without blocking:
82
+ // Standard middleware
83
+ app.use(cors());
84
+ app.use(express.json());
85
+ app.use(express.urlencoded({ extended: true }));
119
86
 
120
- ```js
121
- app.use(mdefender({
122
- apiKey: 'your-key',
123
- domain: 'example.com',
124
- mode: 'monitor',
125
- }));
126
- ```
87
+ // Attach MDefender Pro WAF
88
+ // Automatically loads mdefender.config.js and serves bundled 403 block page
89
+ app.use(mdefender());
127
90
 
128
- ### Skip Specific Paths
91
+ // Your application routes
92
+ app.use('/api/books', require('./routes/books'));
93
+ app.use('/api/users', require('./routes/users'));
129
94
 
130
- ```js
131
- app.use(mdefender({
132
- apiKey: 'your-key',
133
- domain: 'example.com',
134
- skipPaths: ['/health', '/api/webhook', '/static/'],
135
- }));
95
+ app.listen(5000, () => {
96
+ console.log('Server running with MDefender Pro active protection!');
97
+ });
136
98
  ```
137
99
 
138
- ### Block on API Error
100
+ ---
101
+
102
+ ## 4. Inline Configuration (Alternative)
139
103
 
140
- By default, requests are allowed if the WAF API is unreachable. To block instead:
104
+ If you prefer not using a config file, pass options directly:
141
105
 
142
106
  ```js
143
107
  app.use(mdefender({
144
- apiKey: 'your-key',
145
- domain: 'example.com',
146
- onError: 'block',
108
+ apiKey: 'your_64_char_api_key_here',
109
+ domain: 'yourdomain.com',
110
+ apiEndpoint: 'http://127.0.0.1:8000',
111
+ mode: 'block'
147
112
  }));
148
113
  ```
149
114
 
150
- ### Accessing Analysis Results
115
+ ---
151
116
 
152
- After the middleware processes a request, analysis data is attached to `req.mdefender`:
117
+ ## 5. Bundled 403 Block Page
153
118
 
154
- ```js
155
- app.get('/dashboard', (req, res) => {
156
- if (req.mdefender) {
157
- console.log('Threat score:', req.mdefender.threat_score);
158
- console.log('Request ID:', req.mdefender.request_id);
159
- }
160
- res.send('Dashboard');
161
- });
162
- ```
163
-
164
- ## API Reference
165
-
166
- ### `mdefender(config?)`
119
+ When a malicious request is detected (such as `?id=<script>alert(1)</script>` or SQL injection):
120
+ 1. MDefender Pro immediately returns HTTP status **`403 Forbidden`**.
121
+ 2. Renders the cyber-security dark glassmorphic Block Page displaying:
122
+ - **Incident Reference ID** (e.g. `MDF-BB46BF9D`) with 1-click clipboard copy.
123
+ - **Attack Type** (e.g. `XSS - Dangerous HTML Tag (<script>) #1`).
124
+ - **Client IP & Timestamp** for security auditing.
125
+ - **Return to Homepage** action button.
167
126
 
168
- Returns an Express middleware function.
127
+ ---
169
128
 
170
- **Parameters:**
171
- - `config` *(optional)* - `MDefenderConfig` object. Options merge with file-based config and defaults.
129
+ ## 6. How to Test Your Protection
172
130
 
173
- **Returns:** `Express middleware function`
174
-
175
- ### `mdefender.loadConfig(overrides?)`
131
+ ### Test 1: XSS Attack Payload (Expect 403 Blocked)
132
+ ```bash
133
+ curl -i "http://localhost:5000/api/books?id=%3Cscript%3Ealert(1)%3C/script%3E"
134
+ ```
176
135
 
177
- Utility to load configuration from file sources with optional overrides.
136
+ ### Test 2: SQL Injection Payload (Expect 403 Blocked)
137
+ ```bash
138
+ curl -i "http://localhost:5000/api/books?search=%27%20UNION%20SELECT%20null,password%20FROM%20users--"
139
+ ```
178
140
 
179
- ### `mdefender.DEFAULT_CONFIG`
141
+ ### Test 3: Safe Request (Expect 200 OK)
142
+ ```bash
143
+ curl -i "http://localhost:5000/api/books"
144
+ ```
180
145
 
181
- The default configuration object.
146
+ ---
182
147
 
183
- ## How It Works
148
+ ## Configuration Reference
184
149
 
185
- 1. A request hits your Express app
186
- 2. MDefender intercepts it and builds a payload (method, URL, headers, body, IP, etc.)
187
- 3. The payload is sent to the MDefender Pro API for analysis
188
- 4. If the API detects a threat, it returns a `blocked` status with attack details
189
- 5. MDefender renders a block page and responds with the configured status code
190
- 6. If safe, the request continues to your route handler
150
+ | Option | Type | Default | Description |
151
+ |---|---|---|---|
152
+ | `apiKey` | `string` | `''` | **Required.** Your website API key from dashboard. |
153
+ | `domain` | `string` | `''` | Registered domain name or hostname. |
154
+ | `apiEndpoint` | `string` | `'http://127.0.0.1:8000'` | WAF inspection endpoint URL. |
155
+ | `mode` | `'block' \| 'monitor' \| 'off'` | `'block'` | `block` = active defense, `monitor` = log only. |
156
+ | `blockStatusCode` | `number` | `403` | HTTP status code for blocked requests. |
157
+ | `timeout` | `number` | `5000` | Request timeout in ms (fails open safely). |
158
+ | `skipPaths` | `string[]` | `['/health', '/favicon.ico']` | URL paths to bypass WAF inspection. |
159
+ | `logBlocked` | `boolean` | `true` | Log blocked attacks in console. |
160
+ | `customBlockPage` | `string \| null` | `null` | Optional path to custom HTML file. |
161
+
162
+ ---
191
163
 
192
164
  ## License
193
165
 
194
- MIT
166
+ MIT &copy; MDefender Pro
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const readline = require('readline');
6
+
7
+ const args = process.argv.slice(2);
8
+ const command = args[0] || 'init';
9
+
10
+ console.log(`\n\x1b[36m\x1b[1m========================================\x1b[0m`);
11
+ console.log(`\x1b[36m\x1b[1m MDefender Pro - Quick Setup CLI \x1b[0m`);
12
+ console.log(`\x1b[36m\x1b[1m========================================\x1b[0m\n`);
13
+
14
+ if (command === 'init' || command === 'setup') {
15
+ const targetConfig = path.join(process.cwd(), 'mdefender.config.js');
16
+
17
+ if (fs.existsSync(targetConfig)) {
18
+ console.log(`\x1b[33m[!] mdefender.config.js already exists in current directory.\x1b[0m`);
19
+ process.exit(0);
20
+ }
21
+
22
+ const rl = readline.createInterface({
23
+ input: process.stdin,
24
+ output: process.stdout
25
+ });
26
+
27
+ rl.question('\x1b[32mEnter your MDefender Pro API Key (from Dashboard): \x1b[0m', (apiKey) => {
28
+ rl.question('\x1b[32mEnter your Website Domain (e.g. myapp.com or default): \x1b[0m', (domain) => {
29
+ const trimmedKey = (apiKey || 'YOUR_API_KEY_HERE').trim();
30
+ const trimmedDomain = (domain || 'default').trim();
31
+
32
+ const configTemplate = `/**
33
+ * MDefender Pro Web Application Firewall Configuration
34
+ * Generated automatically by @mdefender/pro CLI
35
+ */
36
+ module.exports = {
37
+ // Your Secret Website API Key from MDefender Dashboard
38
+ apiKey: process.env.MDEFENDER_API_KEY || '${trimmedKey}',
39
+
40
+ // Domain registered in MDefender Pro
41
+ domain: '${trimmedDomain}',
42
+
43
+ // Cloud / Self-hosted Inspection Endpoint
44
+ apiEndpoint: process.env.MDEFENDER_API_ENDPOINT || 'https://mdefender-pro-6e3r.onrender.com',
45
+
46
+ // Mode: 'block' (active defense), 'monitor' (log-only), or 'off'
47
+ mode: 'block',
48
+
49
+ // Request timeout for cloud inspection in milliseconds (fails open safely)
50
+ timeout: 3000,
51
+
52
+ // Paths to bypass from inspection (e.g. static assets)
53
+ skipPaths: ['/favicon.ico', '/robots.txt', '/static', '/assets', '/health'],
54
+
55
+ // HTTP methods to bypass
56
+ skipMethods: ['OPTIONS'],
57
+
58
+ // Log blocked attacks in console
59
+ logBlocked: true
60
+ };
61
+ `;
62
+
63
+ fs.writeFileSync(targetConfig, configTemplate, 'utf8');
64
+ console.log(`\n\x1b[32m[+] Created mdefender.config.js successfully!\x1b[0m`);
65
+ console.log(`\n\x1b[36mHow to use in your Express app:\x1b[0m`);
66
+ console.log(`\x1b[90m---------------------------------------------------\x1b[0m`);
67
+ console.log(` const express = require('express');`);
68
+ console.log(` const mdefender = require('mdefender-pro');`);
69
+ console.log(` `);
70
+ console.log(` const app = express();`);
71
+ console.log(` app.use(express.json());`);
72
+ console.log(` app.use(mdefender()); // Connects WAF with bundled block page`);
73
+ console.log(`\x1b[90m---------------------------------------------------\x1b[0m\n`);
74
+ rl.close();
75
+ });
76
+ });
77
+ } else {
78
+ console.log(`Usage: npx mdefender-pro init`);
79
+ process.exit(0);
80
+ }