req-shield 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +212 -2
- package/dist/cjs/index.js +22 -0
- package/dist/cjs/middleware.js +401 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/pathProtection.js +132 -0
- package/dist/cjs/sanitize.js +142 -0
- package/dist/cjs/types.js +2 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/middleware.js +397 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/pathProtection.js +125 -0
- package/dist/esm/sanitize.js +136 -0
- package/dist/esm/types.js +1 -0
- package/dist/types/index.d.ts +6 -0
- package/dist/types/middleware.d.ts +21 -0
- package/dist/types/pathProtection.d.ts +30 -0
- package/dist/types/sanitize.d.ts +21 -0
- package/dist/types/types.d.ts +244 -0
- package/package.json +43 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,213 @@
|
|
|
1
|
-
#
|
|
1
|
+
# req-shield
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Zero-dependency Node.js / Express security middleware for **early request blocking**, **path-traversal defense**, and **vulnerability scanner probe protection**.
|
|
4
|
+
|
|
5
|
+
Designed to be used just like `compression()`:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import express from 'express';
|
|
9
|
+
import earlyBlock from 'req-shield';
|
|
10
|
+
|
|
11
|
+
const app = express();
|
|
12
|
+
app.use(earlyBlock());
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
- **Zero runtime dependencies** — works with Express, Connect, Fastify (`@fastify/express`), and raw Node.js `http.createServer`.
|
|
18
|
+
- **Dual ESM & CommonJS + TypeScript** — ships with ESM, CommonJS, and `.d.ts` type declarations.
|
|
19
|
+
- **Path-traversal defense** — blocks `../`, `/..`, URL-encoded (`%2e%2e%2f`), double/multi-encoded (`%252e`), overlong UTF-8 (`%c0%ae`), backslash (`..\\`), and Unicode lookalike separators (`\uFF0E`, `\u2025`, `\uFF0F`, `\u2215`, etc.).
|
|
20
|
+
- **Vulnerability probe blocking** — immediately drops common scanner targets (`/.env`, `/.git`, `/.aws`, `/wp-admin`, `/wp-login`, `/phpmyadmin`, `/actuator`, `/.ds_store`, `/backup.sql`, `.php`, etc.) and dangerous extensions (`.env`, `.git`, `.bak`, `.old`, `.swp`).
|
|
21
|
+
- **Query & body safe** — inspects only the URL pathname; never touches query parameters (`?text=...`) or POST/PUT bodies, avoiding false positives on legitimate user input.
|
|
22
|
+
- **Configurable protection** — optional IP allow/block lists, HTTP method allow/block lists, User-Agent blocking, custom `blockIf` predicate, custom status/body, and `onBlock` hook for metrics/logging.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install req-shield
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
### ESM / TypeScript
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import express from 'express';
|
|
36
|
+
import earlyBlock from 'req-shield';
|
|
37
|
+
|
|
38
|
+
const app = express();
|
|
39
|
+
|
|
40
|
+
// Default protection (404 { detail: 'Not Found' })
|
|
41
|
+
app.use(earlyBlock());
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### CommonJS
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
const express = require('express');
|
|
48
|
+
const earlyBlock = require('req-shield');
|
|
49
|
+
|
|
50
|
+
const app = express();
|
|
51
|
+
app.use(earlyBlock());
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Zero-config drop-in (`earlyBlockProbes`)
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { earlyBlockProbes } from 'req-shield';
|
|
58
|
+
|
|
59
|
+
app.use(earlyBlockProbes);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Raw Node.js `http` server
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import http from 'node:http';
|
|
66
|
+
import earlyBlock from 'req-shield';
|
|
67
|
+
|
|
68
|
+
const guard = earlyBlock();
|
|
69
|
+
|
|
70
|
+
const server = http.createServer((req, res) => {
|
|
71
|
+
guard(req, res, () => {
|
|
72
|
+
res.statusCode = 200;
|
|
73
|
+
res.end('OK');
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Dynamic Path & Predefined Rule Management
|
|
79
|
+
|
|
80
|
+
The middleware returned by `earlyBlock()` provides chainable methods to add request paths to block, remove predefined routes from the blocklist, or manage allowlisted paths at runtime:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import express from 'express';
|
|
84
|
+
import earlyBlock from 'req-shield';
|
|
85
|
+
|
|
86
|
+
const app = express();
|
|
87
|
+
const guard = earlyBlock();
|
|
88
|
+
|
|
89
|
+
guard
|
|
90
|
+
// Add custom paths to block
|
|
91
|
+
.addBlockedPath('/internal-debug')
|
|
92
|
+
.addBlockedPaths(['/secret-metrics', '/admin-panel'])
|
|
93
|
+
// Remove predefined blocked routes (e.g. allow /actuator or .php)
|
|
94
|
+
.removeBlockedPath('/actuator')
|
|
95
|
+
.removeBlockedPaths(['/pma', '.php'])
|
|
96
|
+
// Manage allowlisted paths
|
|
97
|
+
.addAllowedPath('/.git/public-badge')
|
|
98
|
+
.removeAllowedPath('/.git/public-badge')
|
|
99
|
+
// Manage blocked file extensions
|
|
100
|
+
.addBlockedExtension('log')
|
|
101
|
+
.removeBlockedExtension('bak');
|
|
102
|
+
|
|
103
|
+
app.use(guard);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
You can also exclude predefined patterns/extensions directly via options:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
app.use(
|
|
110
|
+
earlyBlock({
|
|
111
|
+
excludePatterns: ['/actuator', '.php'],
|
|
112
|
+
excludeExtensions: ['bak'],
|
|
113
|
+
}),
|
|
114
|
+
);
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Sanitization, Injection Blocking, Logging & Security Headers
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
app.use(
|
|
121
|
+
earlyBlock({
|
|
122
|
+
// Sanitize req.body, req.query, and req.params
|
|
123
|
+
enableSanitization: true,
|
|
124
|
+
sanitization: {
|
|
125
|
+
stripXss: true,
|
|
126
|
+
stripNullBytes: true,
|
|
127
|
+
stripNoSqlOperators: true,
|
|
128
|
+
stripPrototypePollution: true,
|
|
129
|
+
stripSqlInjection: true,
|
|
130
|
+
trimStrings: true,
|
|
131
|
+
},
|
|
132
|
+
// Or reject prototype pollution / NoSQL injection payloads outright
|
|
133
|
+
blockPrototypePollution: true,
|
|
134
|
+
blockNoSqlInjection: true,
|
|
135
|
+
maxUrlLength: 2048,
|
|
136
|
+
// Set baseline defensive security headers
|
|
137
|
+
enableSecurityHeaders: true,
|
|
138
|
+
// Structured logging for blocked, sanitized, and (optionally) allowed requests
|
|
139
|
+
enableLogging: true,
|
|
140
|
+
logAllowed: false,
|
|
141
|
+
}),
|
|
142
|
+
);
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Custom Configuration
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
app.use(
|
|
149
|
+
earlyBlock({
|
|
150
|
+
extraPatterns: ['/internal-debug'],
|
|
151
|
+
extraExtensions: ['log', 'sql'],
|
|
152
|
+
allowPaths: ['/public/actuator'],
|
|
153
|
+
blockedMethods: ['TRACE', 'TRACK'],
|
|
154
|
+
blockedIps: ['203.0.113.42'],
|
|
155
|
+
trustProxy: true,
|
|
156
|
+
blockedUserAgents: ['sqlmap', /nikto/i],
|
|
157
|
+
blockIf: (req) => req.headers?.['x-suspicious'] === '1',
|
|
158
|
+
statusCode: 403,
|
|
159
|
+
responseBody: (_req, ctx) => ({
|
|
160
|
+
error: 'Forbidden',
|
|
161
|
+
reason: ctx.reason,
|
|
162
|
+
}),
|
|
163
|
+
onBlock: (_req, _res, ctx) => {
|
|
164
|
+
console.warn('Blocked request:', ctx.reason, ctx.path, ctx.ip);
|
|
165
|
+
},
|
|
166
|
+
}),
|
|
167
|
+
);
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## Options
|
|
171
|
+
|
|
172
|
+
| Option | Type | Default | Description |
|
|
173
|
+
| --- | --- | --- | --- |
|
|
174
|
+
| `blockPathTraversal` | `boolean` | `true` | Block `../`, encoded, overlong, and Unicode traversal sequences. |
|
|
175
|
+
| `maxDecodeDepth` | `number` | `4` | Max `decodeURIComponent` passes for nested encoding detection. |
|
|
176
|
+
| `patterns` | `string[]` | `DEFAULT_BLOCKED_PATTERNS` | Replace default blocked probe substrings. |
|
|
177
|
+
| `extraPatterns` | `string[]` | `[]` | Append additional probe substrings to block. |
|
|
178
|
+
| `excludePatterns` | `string[]` | `[]` | Remove predefined (or configured) probe patterns from blocking. |
|
|
179
|
+
| `blockedExtensions` | `string[]` | `['env', 'git', 'bak', 'old', 'swp']` | Replace default blocked file extensions. |
|
|
180
|
+
| `extraExtensions` | `string[]` | `[]` | Append additional file extensions to block. |
|
|
181
|
+
| `excludeExtensions` | `string[]` | `[]` | Remove predefined (or configured) file extensions from blocking. |
|
|
182
|
+
| `allowPaths` | `Array<string \| RegExp>` | `[]` | Paths that bypass probe/extension checks (traversal still blocked). |
|
|
183
|
+
| `blockedMethods` | `string[]` | `[]` | HTTP methods to block (e.g. `['TRACE']`). |
|
|
184
|
+
| `allowedMethods` | `string[]` | `undefined` | If set, only these HTTP methods are allowed. |
|
|
185
|
+
| `blockedIps` | `Array<string \| RegExp>` | `[]` | Client IPs to block. |
|
|
186
|
+
| `allowedIps` | `Array<string \| RegExp>` | `undefined` | If set, only matching client IPs are allowed. |
|
|
187
|
+
| `trustProxy` | `boolean` | `false` | Read client IP from `X-Forwarded-For` header. |
|
|
188
|
+
| `blockedUserAgents` | `Array<string \| RegExp>` | `[]` | User-Agent substrings or RegExps to block. |
|
|
189
|
+
| `blockIf` | `(req) => boolean \| string` | `undefined` | Custom predicate to block requests. |
|
|
190
|
+
| `statusCode` | `number` | `404` | HTTP status code returned when blocked. |
|
|
191
|
+
| `responseBody` | `unknown \| ((req, ctx) => unknown)` | `{ detail: 'Not Found' }` | Response body returned when blocked. |
|
|
192
|
+
| `onBlock` | `(req, res, ctx) => void` | `undefined` | Callback invoked when a request is blocked. |
|
|
193
|
+
| `enableSanitization` | `boolean` | `false` | Sanitize `req.body`, `req.query`, `req.params` (and optionally headers). |
|
|
194
|
+
| `sanitization` | `SanitizationOptions` | `{}` | Configure XSS, null-byte, NoSQL, prototype-pollution, SQLi, and custom sanitization. |
|
|
195
|
+
| `blockPrototypePollution` | `boolean` | `false` | Reject requests containing `__proto__`, `constructor`, or `prototype` keys. |
|
|
196
|
+
| `blockNoSqlInjection` | `boolean` | `false` | Reject requests containing `$`-prefixed NoSQL operator keys. |
|
|
197
|
+
| `maxUrlLength` | `number` | `undefined` | Block requests whose URL exceeds this length. |
|
|
198
|
+
| `enableSecurityHeaders` | `boolean` | `false` | Set `X-Content-Type-Options`, `X-Frame-Options`, `X-XSS-Protection`, `Referrer-Policy`. |
|
|
199
|
+
| `enableLogging` | `boolean` | `false` | Enable structured logging for blocked and sanitized requests. |
|
|
200
|
+
| `logAllowed` | `boolean` | `false` | Also log allowed requests when `enableLogging` is `true`. |
|
|
201
|
+
| `logger` | `LoggerLike \| ((event) => void)` | `console` | Custom logger object or event callback. |
|
|
202
|
+
|
|
203
|
+
## Scripts
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
npm run typecheck
|
|
207
|
+
npm run build
|
|
208
|
+
npm test
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
MIT
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sanitizeValue = exports.sanitizeString = exports.hasPrototypePollutionKey = exports.hasNoSqlOperatorKey = exports.normalizeUnicodeSeparators = exports.hasPathTraversal = exports.extractPathname = exports.decodeFully = exports.DEFAULT_BLOCKED_PATTERNS = exports.DEFAULT_BLOCKED_EXTENSIONS = exports.earlyBlockProbes = exports.earlyBlock = void 0;
|
|
4
|
+
const middleware_js_1 = require("./middleware.js");
|
|
5
|
+
var middleware_js_2 = require("./middleware.js");
|
|
6
|
+
Object.defineProperty(exports, "earlyBlock", { enumerable: true, get: function () { return middleware_js_2.earlyBlock; } });
|
|
7
|
+
Object.defineProperty(exports, "earlyBlockProbes", { enumerable: true, get: function () { return middleware_js_2.earlyBlockProbes; } });
|
|
8
|
+
var pathProtection_js_1 = require("./pathProtection.js");
|
|
9
|
+
Object.defineProperty(exports, "DEFAULT_BLOCKED_EXTENSIONS", { enumerable: true, get: function () { return pathProtection_js_1.DEFAULT_BLOCKED_EXTENSIONS; } });
|
|
10
|
+
Object.defineProperty(exports, "DEFAULT_BLOCKED_PATTERNS", { enumerable: true, get: function () { return pathProtection_js_1.DEFAULT_BLOCKED_PATTERNS; } });
|
|
11
|
+
Object.defineProperty(exports, "decodeFully", { enumerable: true, get: function () { return pathProtection_js_1.decodeFully; } });
|
|
12
|
+
Object.defineProperty(exports, "extractPathname", { enumerable: true, get: function () { return pathProtection_js_1.extractPathname; } });
|
|
13
|
+
Object.defineProperty(exports, "hasPathTraversal", { enumerable: true, get: function () { return pathProtection_js_1.hasPathTraversal; } });
|
|
14
|
+
Object.defineProperty(exports, "normalizeUnicodeSeparators", { enumerable: true, get: function () { return pathProtection_js_1.normalizeUnicodeSeparators; } });
|
|
15
|
+
var sanitize_js_1 = require("./sanitize.js");
|
|
16
|
+
Object.defineProperty(exports, "hasNoSqlOperatorKey", { enumerable: true, get: function () { return sanitize_js_1.hasNoSqlOperatorKey; } });
|
|
17
|
+
Object.defineProperty(exports, "hasPrototypePollutionKey", { enumerable: true, get: function () { return sanitize_js_1.hasPrototypePollutionKey; } });
|
|
18
|
+
Object.defineProperty(exports, "sanitizeString", { enumerable: true, get: function () { return sanitize_js_1.sanitizeString; } });
|
|
19
|
+
Object.defineProperty(exports, "sanitizeValue", { enumerable: true, get: function () { return sanitize_js_1.sanitizeValue; } });
|
|
20
|
+
exports.default = middleware_js_1.earlyBlock;
|
|
21
|
+
|
|
22
|
+
module.exports = Object.assign(exports.earlyBlock, exports);
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.earlyBlockProbes = void 0;
|
|
4
|
+
exports.earlyBlock = earlyBlock;
|
|
5
|
+
const pathProtection_js_1 = require("./pathProtection.js");
|
|
6
|
+
const sanitize_js_1 = require("./sanitize.js");
|
|
7
|
+
function escapeRegex(value) {
|
|
8
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
9
|
+
}
|
|
10
|
+
function buildExtensionRegex(extensions) {
|
|
11
|
+
const cleaned = extensions
|
|
12
|
+
.map((ext) => ext.trim().replace(/^\./, ''))
|
|
13
|
+
.filter(Boolean)
|
|
14
|
+
.map(escapeRegex);
|
|
15
|
+
if (cleaned.length === 0)
|
|
16
|
+
return null;
|
|
17
|
+
return new RegExp(`\\.(?:${cleaned.join('|')})$`, 'i');
|
|
18
|
+
}
|
|
19
|
+
function getHeader(req, name) {
|
|
20
|
+
const headers = req.headers;
|
|
21
|
+
if (!headers)
|
|
22
|
+
return undefined;
|
|
23
|
+
const target = name.toLowerCase();
|
|
24
|
+
const direct = headers[target] ?? headers[name];
|
|
25
|
+
if (typeof direct === 'string')
|
|
26
|
+
return direct;
|
|
27
|
+
if (Array.isArray(direct))
|
|
28
|
+
return direct[0];
|
|
29
|
+
for (const [key, val] of Object.entries(headers)) {
|
|
30
|
+
if (key.toLowerCase() === target) {
|
|
31
|
+
return Array.isArray(val) ? val[0] : val;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
function getClientIp(req, trustProxy) {
|
|
37
|
+
if (trustProxy) {
|
|
38
|
+
const forwarded = getHeader(req, 'x-forwarded-for');
|
|
39
|
+
if (forwarded) {
|
|
40
|
+
const first = forwarded.split(',')[0]?.trim();
|
|
41
|
+
if (first)
|
|
42
|
+
return first;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return req.ip || req.socket?.remoteAddress;
|
|
46
|
+
}
|
|
47
|
+
function matchesAny(value, matchers, caseInsensitive = false) {
|
|
48
|
+
const normalized = caseInsensitive ? value.toLowerCase() : value;
|
|
49
|
+
for (const matcher of matchers) {
|
|
50
|
+
if (typeof matcher === 'string') {
|
|
51
|
+
const target = caseInsensitive ? matcher.toLowerCase() : matcher;
|
|
52
|
+
if (normalized === target)
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
matcher.lastIndex = 0;
|
|
57
|
+
if (matcher.test(value))
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
function matchesSubstringOrRegex(value, matchers) {
|
|
64
|
+
const lower = value.toLowerCase();
|
|
65
|
+
for (const matcher of matchers) {
|
|
66
|
+
if (typeof matcher === 'string') {
|
|
67
|
+
if (lower.includes(matcher.toLowerCase()))
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
matcher.lastIndex = 0;
|
|
72
|
+
if (matcher.test(value))
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
function applySecurityHeaders(res) {
|
|
79
|
+
res.setHeader?.('X-Content-Type-Options', 'nosniff');
|
|
80
|
+
res.setHeader?.('X-Frame-Options', 'DENY');
|
|
81
|
+
res.setHeader?.('X-XSS-Protection', '0');
|
|
82
|
+
res.setHeader?.('Referrer-Policy', 'no-referrer');
|
|
83
|
+
}
|
|
84
|
+
function emitLog(enabled, logger, event) {
|
|
85
|
+
if (!enabled)
|
|
86
|
+
return;
|
|
87
|
+
if (typeof logger === 'function') {
|
|
88
|
+
logger(event);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const target = logger ?? console;
|
|
92
|
+
const msg = `[req-shield] ${event.event.toUpperCase()} ${event.method ?? 'UNKNOWN'} ${event.path}`;
|
|
93
|
+
if (event.level === 'warn') {
|
|
94
|
+
target.warn?.(msg, event);
|
|
95
|
+
}
|
|
96
|
+
else if (event.level === 'error') {
|
|
97
|
+
target.error?.(msg, event);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
target.info?.(msg, event);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function sendBlockedResponse(res, statusCode, body) {
|
|
104
|
+
if (typeof res.status === 'function') {
|
|
105
|
+
const chained = res.status(statusCode);
|
|
106
|
+
if (typeof chained?.json === 'function' && typeof body === 'object' && body !== null) {
|
|
107
|
+
chained.json(body);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (typeof chained?.send === 'function') {
|
|
111
|
+
chained.send(body);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
res.statusCode = statusCode;
|
|
116
|
+
if (typeof body === 'object' && body !== null) {
|
|
117
|
+
res.setHeader?.('Content-Type', 'application/json; charset=utf-8');
|
|
118
|
+
res.end?.(JSON.stringify(body));
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
res.setHeader?.('Content-Type', 'text/plain; charset=utf-8');
|
|
122
|
+
res.end?.(body == null ? '' : String(body));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Creates an early-block security middleware that protects Node.js / Express apps
|
|
127
|
+
* by immediately rejecting path-traversal attempts, vulnerability scanner probes,
|
|
128
|
+
* dangerous file extensions, and optional IP / method / User-Agent rules.
|
|
129
|
+
*
|
|
130
|
+
* Usage:
|
|
131
|
+
* ```ts
|
|
132
|
+
* import express from 'express';
|
|
133
|
+
* import earlyBlock from 'req-shield';
|
|
134
|
+
*
|
|
135
|
+
* const app = express();
|
|
136
|
+
* app.use(earlyBlock());
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
function earlyBlock(options = {}) {
|
|
140
|
+
const { blockPathTraversal = true, maxDecodeDepth = 4, patterns, extraPatterns = [], excludePatterns = [], blockedExtensions, extraExtensions = [], excludeExtensions = [], allowPaths = [], blockedMethods = [], allowedMethods, blockedIps = [], allowedIps, trustProxy = false, blockedUserAgents = [], blockIf, statusCode = 404, responseBody = { detail: 'Not Found' }, onBlock, enableSanitization = false, sanitization = {}, blockPrototypePollution = false, blockNoSqlInjection = false, maxUrlLength, enableSecurityHeaders = false, enableLogging = false, logAllowed = false, logger, } = options;
|
|
141
|
+
const activePatternSet = new Set([...(patterns ?? pathProtection_js_1.DEFAULT_BLOCKED_PATTERNS), ...extraPatterns].map((p) => p.toLowerCase()));
|
|
142
|
+
for (const excluded of excludePatterns) {
|
|
143
|
+
activePatternSet.delete(excluded.toLowerCase());
|
|
144
|
+
}
|
|
145
|
+
const normalizeExt = (ext) => ext.trim().replace(/^\./, '').toLowerCase();
|
|
146
|
+
const activeExtensionSet = new Set([...(blockedExtensions ?? pathProtection_js_1.DEFAULT_BLOCKED_EXTENSIONS), ...extraExtensions]
|
|
147
|
+
.map(normalizeExt)
|
|
148
|
+
.filter(Boolean));
|
|
149
|
+
for (const excluded of excludeExtensions) {
|
|
150
|
+
activeExtensionSet.delete(normalizeExt(excluded));
|
|
151
|
+
}
|
|
152
|
+
let extensionRegex = buildExtensionRegex([...activeExtensionSet]);
|
|
153
|
+
const activeAllowPaths = [...allowPaths];
|
|
154
|
+
const blockedMethodSet = new Set(blockedMethods.map((m) => m.toUpperCase()));
|
|
155
|
+
const allowedMethodSet = allowedMethods
|
|
156
|
+
? new Set(allowedMethods.map((m) => m.toUpperCase()))
|
|
157
|
+
: null;
|
|
158
|
+
function earlyBlockMiddleware(req, res, next) {
|
|
159
|
+
const rawUrl = req.originalUrl || req.url || req.path || '';
|
|
160
|
+
const rawPath = (0, pathProtection_js_1.extractPathname)(rawUrl);
|
|
161
|
+
const method = req.method?.toUpperCase();
|
|
162
|
+
const clientIp = getClientIp(req, trustProxy);
|
|
163
|
+
if (enableSecurityHeaders) {
|
|
164
|
+
applySecurityHeaders(res);
|
|
165
|
+
}
|
|
166
|
+
const reject = (reason, detail, overrideStatus) => {
|
|
167
|
+
const effectiveStatus = overrideStatus ?? statusCode;
|
|
168
|
+
const ctx = {
|
|
169
|
+
reason,
|
|
170
|
+
detail,
|
|
171
|
+
path: rawPath,
|
|
172
|
+
method,
|
|
173
|
+
ip: clientIp,
|
|
174
|
+
};
|
|
175
|
+
emitLog(enableLogging, logger, {
|
|
176
|
+
level: 'warn',
|
|
177
|
+
event: 'blocked',
|
|
178
|
+
path: rawPath,
|
|
179
|
+
method,
|
|
180
|
+
ip: clientIp,
|
|
181
|
+
reason,
|
|
182
|
+
detail,
|
|
183
|
+
statusCode: effectiveStatus,
|
|
184
|
+
});
|
|
185
|
+
onBlock?.(req, res, ctx);
|
|
186
|
+
const body = typeof responseBody === 'function'
|
|
187
|
+
? responseBody(req, ctx)
|
|
188
|
+
: responseBody;
|
|
189
|
+
sendBlockedResponse(res, effectiveStatus, body);
|
|
190
|
+
};
|
|
191
|
+
// 0. Max URL length check
|
|
192
|
+
if (typeof maxUrlLength === 'number' && rawUrl.length > maxUrlLength) {
|
|
193
|
+
reject('url_too_long', `length=${rawUrl.length}`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
// 1. Method checks
|
|
197
|
+
if (method) {
|
|
198
|
+
if (allowedMethodSet && !allowedMethodSet.has(method)) {
|
|
199
|
+
reject('blocked_method', method);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (blockedMethodSet.has(method)) {
|
|
203
|
+
reject('blocked_method', method);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// 2. IP allow/block checks
|
|
208
|
+
if (allowedIps && (!clientIp || !matchesAny(clientIp, allowedIps))) {
|
|
209
|
+
reject('blocked_ip', clientIp);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (blockedIps.length > 0 && clientIp && matchesAny(clientIp, blockedIps)) {
|
|
213
|
+
reject('blocked_ip', clientIp);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
// 3. User-Agent checks
|
|
217
|
+
if (blockedUserAgents.length > 0) {
|
|
218
|
+
const ua = getHeader(req, 'user-agent');
|
|
219
|
+
if (ua && matchesSubstringOrRegex(ua, blockedUserAgents)) {
|
|
220
|
+
reject('blocked_user_agent', ua);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// 4. Path traversal checks (always enforced before allowPaths unless disabled)
|
|
225
|
+
if (blockPathTraversal && (0, pathProtection_js_1.hasPathTraversal)(rawPath, maxDecodeDepth)) {
|
|
226
|
+
reject('path_traversal', rawPath);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
// 5. Allowlist bypass for probe patterns & extensions
|
|
230
|
+
const isAllowlisted = activeAllowPaths.length > 0 && matchesAny(rawPath, activeAllowPaths, true);
|
|
231
|
+
if (!isAllowlisted) {
|
|
232
|
+
const urlPath = rawPath.toLowerCase();
|
|
233
|
+
// 6. Sensitive probe patterns (.env, .git, wp-admin, etc.)
|
|
234
|
+
for (const pattern of activePatternSet) {
|
|
235
|
+
if (urlPath.includes(pattern)) {
|
|
236
|
+
reject('probe_pattern', pattern);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// 7. Dangerous file extensions
|
|
241
|
+
if (extensionRegex && extensionRegex.test(urlPath)) {
|
|
242
|
+
reject('blocked_extension', urlPath);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// 8. Injection blocking checks on parsed payloads (before sanitization)
|
|
247
|
+
const maxDepth = sanitization.maxDepth ?? 10;
|
|
248
|
+
if (blockPrototypePollution) {
|
|
249
|
+
if ((0, sanitize_js_1.hasPrototypePollutionKey)(req.query, maxDepth) ||
|
|
250
|
+
(0, sanitize_js_1.hasPrototypePollutionKey)(req.body, maxDepth) ||
|
|
251
|
+
(0, sanitize_js_1.hasPrototypePollutionKey)(req.params, maxDepth)) {
|
|
252
|
+
reject('prototype_pollution', 'Prototype pollution key detected');
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (blockNoSqlInjection) {
|
|
257
|
+
if ((0, sanitize_js_1.hasNoSqlOperatorKey)(req.query, maxDepth) ||
|
|
258
|
+
(0, sanitize_js_1.hasNoSqlOperatorKey)(req.body, maxDepth) ||
|
|
259
|
+
(0, sanitize_js_1.hasNoSqlOperatorKey)(req.params, maxDepth)) {
|
|
260
|
+
reject('nosql_injection', 'NoSQL operator key detected');
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
// 9. Custom predicate
|
|
265
|
+
if (blockIf) {
|
|
266
|
+
const customResult = blockIf(req);
|
|
267
|
+
if (customResult) {
|
|
268
|
+
reject('custom', typeof customResult === 'string' ? customResult : undefined);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// 10. Request data sanitization (when enableSanitization is true)
|
|
273
|
+
if (enableSanitization) {
|
|
274
|
+
const sanitizedTargets = [];
|
|
275
|
+
if ((sanitization.sanitizeQuery ?? true) && req.query !== undefined) {
|
|
276
|
+
const resQuery = (0, sanitize_js_1.sanitizeValue)(req.query, sanitization, 'query');
|
|
277
|
+
if (resQuery.modified) {
|
|
278
|
+
req.query = resQuery.value;
|
|
279
|
+
sanitizedTargets.push('query');
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if ((sanitization.sanitizeBody ?? true) && req.body !== undefined) {
|
|
283
|
+
const resBody = (0, sanitize_js_1.sanitizeValue)(req.body, sanitization, 'body');
|
|
284
|
+
if (resBody.modified) {
|
|
285
|
+
req.body = resBody.value;
|
|
286
|
+
sanitizedTargets.push('body');
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if ((sanitization.sanitizeParams ?? true) && req.params !== undefined) {
|
|
290
|
+
const resParams = (0, sanitize_js_1.sanitizeValue)(req.params, sanitization, 'params');
|
|
291
|
+
if (resParams.modified) {
|
|
292
|
+
req.params = resParams.value;
|
|
293
|
+
sanitizedTargets.push('params');
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (sanitization.sanitizeHeaders && req.headers !== undefined) {
|
|
297
|
+
const resHeaders = (0, sanitize_js_1.sanitizeValue)(req.headers, sanitization, 'headers');
|
|
298
|
+
if (resHeaders.modified) {
|
|
299
|
+
req.headers = resHeaders.value;
|
|
300
|
+
sanitizedTargets.push('headers');
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (sanitizedTargets.length > 0) {
|
|
304
|
+
emitLog(enableLogging, logger, {
|
|
305
|
+
level: 'info',
|
|
306
|
+
event: 'sanitized',
|
|
307
|
+
path: rawPath,
|
|
308
|
+
method,
|
|
309
|
+
ip: clientIp,
|
|
310
|
+
sanitizedTargets,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (logAllowed) {
|
|
315
|
+
emitLog(enableLogging, logger, {
|
|
316
|
+
level: 'info',
|
|
317
|
+
event: 'allowed',
|
|
318
|
+
path: rawPath,
|
|
319
|
+
method,
|
|
320
|
+
ip: clientIp,
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
next();
|
|
324
|
+
}
|
|
325
|
+
const middleware = earlyBlockMiddleware;
|
|
326
|
+
middleware.addBlockedPath = (pattern) => {
|
|
327
|
+
const normalized = pattern.trim().toLowerCase();
|
|
328
|
+
if (normalized)
|
|
329
|
+
activePatternSet.add(normalized);
|
|
330
|
+
return middleware;
|
|
331
|
+
};
|
|
332
|
+
middleware.addBlockedPaths = (list) => {
|
|
333
|
+
for (const p of list)
|
|
334
|
+
middleware.addBlockedPath(p);
|
|
335
|
+
return middleware;
|
|
336
|
+
};
|
|
337
|
+
middleware.removeBlockedPath = (pattern) => {
|
|
338
|
+
activePatternSet.delete(pattern.trim().toLowerCase());
|
|
339
|
+
return middleware;
|
|
340
|
+
};
|
|
341
|
+
middleware.removeBlockedPaths = (list) => {
|
|
342
|
+
for (const p of list)
|
|
343
|
+
middleware.removeBlockedPath(p);
|
|
344
|
+
return middleware;
|
|
345
|
+
};
|
|
346
|
+
middleware.addAllowedPath = (path) => {
|
|
347
|
+
if (typeof path === 'string') {
|
|
348
|
+
const exists = activeAllowPaths.some((p) => typeof p === 'string' && p.toLowerCase() === path.toLowerCase());
|
|
349
|
+
if (!exists)
|
|
350
|
+
activeAllowPaths.push(path);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
const exists = activeAllowPaths.some((p) => p instanceof RegExp &&
|
|
354
|
+
p.source === path.source &&
|
|
355
|
+
p.flags === path.flags);
|
|
356
|
+
if (!exists)
|
|
357
|
+
activeAllowPaths.push(path);
|
|
358
|
+
}
|
|
359
|
+
return middleware;
|
|
360
|
+
};
|
|
361
|
+
middleware.removeAllowedPath = (path) => {
|
|
362
|
+
for (let i = activeAllowPaths.length - 1; i >= 0; i--) {
|
|
363
|
+
const item = activeAllowPaths[i];
|
|
364
|
+
if (typeof path === 'string' && typeof item === 'string') {
|
|
365
|
+
if (item.toLowerCase() === path.toLowerCase()) {
|
|
366
|
+
activeAllowPaths.splice(i, 1);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
else if (path instanceof RegExp && item instanceof RegExp) {
|
|
370
|
+
if (item.source === path.source && item.flags === path.flags) {
|
|
371
|
+
activeAllowPaths.splice(i, 1);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return middleware;
|
|
376
|
+
};
|
|
377
|
+
middleware.addBlockedExtension = (ext) => {
|
|
378
|
+
const normalized = normalizeExt(ext);
|
|
379
|
+
if (normalized) {
|
|
380
|
+
activeExtensionSet.add(normalized);
|
|
381
|
+
extensionRegex = buildExtensionRegex([...activeExtensionSet]);
|
|
382
|
+
}
|
|
383
|
+
return middleware;
|
|
384
|
+
};
|
|
385
|
+
middleware.removeBlockedExtension = (ext) => {
|
|
386
|
+
const normalized = normalizeExt(ext);
|
|
387
|
+
if (activeExtensionSet.delete(normalized)) {
|
|
388
|
+
extensionRegex = buildExtensionRegex([...activeExtensionSet]);
|
|
389
|
+
}
|
|
390
|
+
return middleware;
|
|
391
|
+
};
|
|
392
|
+
middleware.getBlockedPatterns = () => [...activePatternSet];
|
|
393
|
+
middleware.getAllowedPaths = () => [...activeAllowPaths];
|
|
394
|
+
middleware.getBlockedExtensions = () => [...activeExtensionSet];
|
|
395
|
+
return middleware;
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Pre-configured default middleware instance for zero-config drop-in usage:
|
|
399
|
+
* `app.use(earlyBlockProbes);`
|
|
400
|
+
*/
|
|
401
|
+
exports.earlyBlockProbes = earlyBlock();
|