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.
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_BLOCKED_EXTENSIONS = exports.DEFAULT_BLOCKED_PATTERNS = void 0;
4
+ exports.normalizeUnicodeSeparators = normalizeUnicodeSeparators;
5
+ exports.decodeFully = decodeFully;
6
+ exports.hasPathTraversal = hasPathTraversal;
7
+ exports.extractPathname = extractPathname;
8
+ /**
9
+ * Common path substrings and patterns targeted by automated vulnerability/bot scanners.
10
+ */
11
+ exports.DEFAULT_BLOCKED_PATTERNS = [
12
+ '/.env',
13
+ '/.git',
14
+ '/config.env',
15
+ '/.svn',
16
+ '/.htaccess',
17
+ '/.aws',
18
+ '/wp-admin',
19
+ '/wp-login',
20
+ '/wp-content',
21
+ '/wp-includes',
22
+ '/phpmyadmin',
23
+ '/pma',
24
+ '/actuator',
25
+ '/.ds_store',
26
+ '/backup.sql',
27
+ '/dump.sql',
28
+ '/database.sql',
29
+ '/phpinfo.php',
30
+ '/xmlrpc.php',
31
+ '.php',
32
+ ];
33
+ /**
34
+ * File extensions commonly targeted by vulnerability scanners.
35
+ */
36
+ exports.DEFAULT_BLOCKED_EXTENSIONS = [
37
+ 'env',
38
+ 'git',
39
+ 'bak',
40
+ 'old',
41
+ 'swp',
42
+ ];
43
+ /**
44
+ * Normalizes unicode characters and overlong/non-standard encodings to standard ASCII
45
+ * e.g., Fullwidth Full Stop (`\uFF0E`), Two Dot Leader (`\u2025`),
46
+ * Fullwidth Solidus (`\uFF0F`), Division Slash (`\u2215`), Fraction Slash (`\u2044`),
47
+ * Fullwidth Reverse Solidus (`\uFF3C`).
48
+ */
49
+ function normalizeUnicodeSeparators(str) {
50
+ // NFKC decomposes and normalizes fullwidth compatibility forms (e.g. fullwidth dot -> ., fullwidth slash -> /)
51
+ let normalized = str.normalize('NFKC');
52
+ // Explicit mapping for slash, dot and backslash Unicode lookalikes
53
+ normalized = normalized
54
+ .replace(/[\u2024\u2025\u2026\uFF0E\u3002]/g, '.') // One/Two/Three Dot Leaders, Fullwidth Full Stop, Ideographic Full Stop
55
+ .replace(/[\u2215\u2044\uFF0F\u002F]/g, '/') // Division Slash, Fraction Slash, Fullwidth Slash
56
+ .replace(/[\uFF3C\u2216\uFE68\u005C]/g, '/'); // Fullwidth Reverse Solidus, Set Minus, Small Reverse Solidus, Backslash
57
+ // Overlong UTF-8 hex sequences (common IIS/Apache/Nginx bypass attempts)
58
+ normalized = normalized
59
+ .replace(/%(?:c0%ae|e0%80%ae|c1%9e)/gi, '.') // Overlong dot
60
+ .replace(/%(?:c0%af|e0%80%af|c1%8f)/gi, '/') // Overlong slash
61
+ .replace(/%(?:c0%5c|c1%9c|e0%80%dc)/gi, '/'); // Overlong backslash
62
+ return normalized;
63
+ }
64
+ /**
65
+ * Safely decodes URI components multiple times to detect obfuscated / URL-encoded traversal sequences
66
+ * e.g., `%2e%2e%2f`, `%252e%252e%252f`, `%25252e`, etc.
67
+ */
68
+ function decodeFully(str, maxDepth = 4) {
69
+ let decoded = str;
70
+ for (let i = 0; i < maxDepth; i++) {
71
+ try {
72
+ const next = decodeURIComponent(decoded);
73
+ if (next === decoded)
74
+ break;
75
+ decoded = next;
76
+ }
77
+ catch {
78
+ // If malformed percent encoding like %c0%ae, continue
79
+ break;
80
+ }
81
+ }
82
+ return decoded;
83
+ }
84
+ function checkDotsAndSlashes(text) {
85
+ const unified = text.replace(/\\/g, '/');
86
+ return (unified.includes('../') ||
87
+ unified.includes('/..') ||
88
+ unified === '..' ||
89
+ unified.startsWith('..') ||
90
+ unified.endsWith('..') ||
91
+ /\.\.[\/\\]/.test(unified) ||
92
+ /[\/\\]\.\./.test(unified));
93
+ }
94
+ /**
95
+ * Checks whether a path contains path-traversal sequences like `../` or `/..` or unicode/URL-encoded equivalents.
96
+ */
97
+ function hasPathTraversal(pathOrUrl, maxDecodeDepth = 4) {
98
+ if (!pathOrUrl)
99
+ return false;
100
+ // 1. Check raw string after unicode normalization
101
+ const normalizedRaw = normalizeUnicodeSeparators(pathOrUrl);
102
+ if (checkDotsAndSlashes(normalizedRaw))
103
+ return true;
104
+ // 2. Check fully URL-decoded string after unicode normalization
105
+ const fullyDecoded = normalizeUnicodeSeparators(decodeFully(pathOrUrl, maxDecodeDepth));
106
+ if (checkDotsAndSlashes(fullyDecoded))
107
+ return true;
108
+ // 3. Check regex for hex/unicode dot bypasses (e.g. %2e, %u002e)
109
+ const regexCheck = pathOrUrl
110
+ .replace(/%(?:2e|u002e)/gi, '.')
111
+ .replace(/%(?:2f|5c|u002f|u005c)/gi, '/');
112
+ if (checkDotsAndSlashes(regexCheck))
113
+ return true;
114
+ return false;
115
+ }
116
+ /**
117
+ * Strips query parameters, fragment identifiers, and extracts ONLY the path portion of the URL.
118
+ * Ensures that query parameters (`?text=...&query=...`) and request bodies are NEVER checked
119
+ * by path validation.
120
+ */
121
+ function extractPathname(urlOrPath) {
122
+ if (!urlOrPath)
123
+ return '';
124
+ const queryIndex = urlOrPath.indexOf('?');
125
+ const fragmentIndex = urlOrPath.indexOf('#');
126
+ let cutIndex = urlOrPath.length;
127
+ if (queryIndex !== -1)
128
+ cutIndex = Math.min(cutIndex, queryIndex);
129
+ if (fragmentIndex !== -1)
130
+ cutIndex = Math.min(cutIndex, fragmentIndex);
131
+ return urlOrPath.slice(0, cutIndex);
132
+ }
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasPrototypePollutionKey = hasPrototypePollutionKey;
4
+ exports.hasNoSqlOperatorKey = hasNoSqlOperatorKey;
5
+ exports.sanitizeString = sanitizeString;
6
+ exports.sanitizeValue = sanitizeValue;
7
+ const PROTOTYPE_POLLUTION_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
8
+ function isPlainObject(value) {
9
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
10
+ return false;
11
+ }
12
+ const proto = Object.getPrototypeOf(value);
13
+ return proto === Object.prototype || proto === null;
14
+ }
15
+ /**
16
+ * Checks whether an object/array tree contains own `__proto__`, `constructor`, or `prototype` keys.
17
+ */
18
+ function hasPrototypePollutionKey(value, maxDepth = 10, depth = 0) {
19
+ if (depth > maxDepth || typeof value !== 'object' || value === null) {
20
+ return false;
21
+ }
22
+ if (Array.isArray(value)) {
23
+ return value.some((item) => hasPrototypePollutionKey(item, maxDepth, depth + 1));
24
+ }
25
+ if (!isPlainObject(value)) {
26
+ return false;
27
+ }
28
+ for (const key of Object.getOwnPropertyNames(value)) {
29
+ if (PROTOTYPE_POLLUTION_KEYS.has(key)) {
30
+ return true;
31
+ }
32
+ if (hasPrototypePollutionKey(value[key], maxDepth, depth + 1)) {
33
+ return true;
34
+ }
35
+ }
36
+ return false;
37
+ }
38
+ /**
39
+ * Checks whether an object/array tree contains `$`-prefixed NoSQL operator keys (e.g. `$gt`, `$ne`, `$where`).
40
+ */
41
+ function hasNoSqlOperatorKey(value, maxDepth = 10, depth = 0) {
42
+ if (depth > maxDepth || typeof value !== 'object' || value === null) {
43
+ return false;
44
+ }
45
+ if (Array.isArray(value)) {
46
+ return value.some((item) => hasNoSqlOperatorKey(item, maxDepth, depth + 1));
47
+ }
48
+ if (!isPlainObject(value)) {
49
+ return false;
50
+ }
51
+ for (const key of Object.keys(value)) {
52
+ if (key.startsWith('$')) {
53
+ return true;
54
+ }
55
+ if (hasNoSqlOperatorKey(value[key], maxDepth, depth + 1)) {
56
+ return true;
57
+ }
58
+ }
59
+ return false;
60
+ }
61
+ /**
62
+ * Sanitizes a single string to remove null bytes, XSS payloads, and optional SQL injection patterns.
63
+ */
64
+ function sanitizeString(input, options = {}, target = 'body', key) {
65
+ const { stripNullBytes = true, stripXss = true, stripSqlInjection = false, trimStrings = false, customSanitizer, } = options;
66
+ let out = input;
67
+ if (stripNullBytes) {
68
+ out = out.replace(/\0/g, '').replace(/%00/gi, '');
69
+ }
70
+ if (stripXss) {
71
+ // Strip <script>...</script> blocks and standalone <script ...> / </script> tags
72
+ out = out
73
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, '')
74
+ .replace(/<\/?script\b[^>]*>/gi, '')
75
+ // Strip dangerous URI schemes
76
+ .replace(/\b(?:javascript|vbscript)\s*:/gi, '')
77
+ .replace(/\bdata\s*:\s*text\/html\b/gi, '')
78
+ // Strip inline HTML event handlers (e.g., onerror=, onload=, onclick=)
79
+ .replace(/\bon[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
80
+ }
81
+ if (stripSqlInjection) {
82
+ out = out
83
+ // Strip SQL block comments and end-of-line comments
84
+ .replace(/\/\*[\s\S]*?\*\//g, '')
85
+ .replace(/(?:^|\s)--[^\r\n]*/g, '')
86
+ // Strip chained destructive SQL statements
87
+ .replace(/;\s*(?:drop|delete|truncate|alter|exec|execute|union\s+select)\b/gi, '');
88
+ }
89
+ if (trimStrings) {
90
+ out = out.trim();
91
+ }
92
+ if (customSanitizer) {
93
+ out = customSanitizer(out, { target, key });
94
+ }
95
+ return out;
96
+ }
97
+ /**
98
+ * Recursively sanitizes an unknown value (string, array, or plain object).
99
+ * Returns `{ value, modified }` so callers can detect if any mutation occurred.
100
+ */
101
+ function sanitizeValue(input, options = {}, target = 'body', depth = 0, key) {
102
+ const maxDepth = options.maxDepth ?? 10;
103
+ if (depth > maxDepth) {
104
+ return { value: input, modified: false };
105
+ }
106
+ if (typeof input === 'string') {
107
+ const sanitized = sanitizeString(input, options, target, key);
108
+ return { value: sanitized, modified: sanitized !== input };
109
+ }
110
+ if (Array.isArray(input)) {
111
+ let modified = false;
112
+ const out = input.map((item) => {
113
+ const res = sanitizeValue(item, options, target, depth + 1, key);
114
+ if (res.modified)
115
+ modified = true;
116
+ return res.value;
117
+ });
118
+ return { value: modified ? out : input, modified };
119
+ }
120
+ if (!isPlainObject(input)) {
121
+ return { value: input, modified: false };
122
+ }
123
+ const stripNoSql = options.stripNoSqlOperators ?? true;
124
+ const stripProto = options.stripPrototypePollution ?? true;
125
+ let modified = false;
126
+ const out = {};
127
+ for (const prop of Object.getOwnPropertyNames(input)) {
128
+ if (stripProto && PROTOTYPE_POLLUTION_KEYS.has(prop)) {
129
+ modified = true;
130
+ continue;
131
+ }
132
+ if (stripNoSql && prop.startsWith('$')) {
133
+ modified = true;
134
+ continue;
135
+ }
136
+ const res = sanitizeValue(input[prop], options, target, depth + 1, prop);
137
+ if (res.modified)
138
+ modified = true;
139
+ out[prop] = res.value;
140
+ }
141
+ return { value: modified ? out : input, modified };
142
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
1
+ import { earlyBlock } from './middleware.js';
2
+ export { earlyBlock, earlyBlockProbes } from './middleware.js';
3
+ export { DEFAULT_BLOCKED_EXTENSIONS, DEFAULT_BLOCKED_PATTERNS, decodeFully, extractPathname, hasPathTraversal, normalizeUnicodeSeparators, } from './pathProtection.js';
4
+ export { hasNoSqlOperatorKey, hasPrototypePollutionKey, sanitizeString, sanitizeValue, } from './sanitize.js';
5
+ export default earlyBlock;
@@ -0,0 +1,397 @@
1
+ import { DEFAULT_BLOCKED_EXTENSIONS, DEFAULT_BLOCKED_PATTERNS, extractPathname, hasPathTraversal, } from './pathProtection.js';
2
+ import { hasNoSqlOperatorKey, hasPrototypePollutionKey, sanitizeValue, } from './sanitize.js';
3
+ function escapeRegex(value) {
4
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
+ }
6
+ function buildExtensionRegex(extensions) {
7
+ const cleaned = extensions
8
+ .map((ext) => ext.trim().replace(/^\./, ''))
9
+ .filter(Boolean)
10
+ .map(escapeRegex);
11
+ if (cleaned.length === 0)
12
+ return null;
13
+ return new RegExp(`\\.(?:${cleaned.join('|')})$`, 'i');
14
+ }
15
+ function getHeader(req, name) {
16
+ const headers = req.headers;
17
+ if (!headers)
18
+ return undefined;
19
+ const target = name.toLowerCase();
20
+ const direct = headers[target] ?? headers[name];
21
+ if (typeof direct === 'string')
22
+ return direct;
23
+ if (Array.isArray(direct))
24
+ return direct[0];
25
+ for (const [key, val] of Object.entries(headers)) {
26
+ if (key.toLowerCase() === target) {
27
+ return Array.isArray(val) ? val[0] : val;
28
+ }
29
+ }
30
+ return undefined;
31
+ }
32
+ function getClientIp(req, trustProxy) {
33
+ if (trustProxy) {
34
+ const forwarded = getHeader(req, 'x-forwarded-for');
35
+ if (forwarded) {
36
+ const first = forwarded.split(',')[0]?.trim();
37
+ if (first)
38
+ return first;
39
+ }
40
+ }
41
+ return req.ip || req.socket?.remoteAddress;
42
+ }
43
+ function matchesAny(value, matchers, caseInsensitive = false) {
44
+ const normalized = caseInsensitive ? value.toLowerCase() : value;
45
+ for (const matcher of matchers) {
46
+ if (typeof matcher === 'string') {
47
+ const target = caseInsensitive ? matcher.toLowerCase() : matcher;
48
+ if (normalized === target)
49
+ return true;
50
+ }
51
+ else {
52
+ matcher.lastIndex = 0;
53
+ if (matcher.test(value))
54
+ return true;
55
+ }
56
+ }
57
+ return false;
58
+ }
59
+ function matchesSubstringOrRegex(value, matchers) {
60
+ const lower = value.toLowerCase();
61
+ for (const matcher of matchers) {
62
+ if (typeof matcher === 'string') {
63
+ if (lower.includes(matcher.toLowerCase()))
64
+ return true;
65
+ }
66
+ else {
67
+ matcher.lastIndex = 0;
68
+ if (matcher.test(value))
69
+ return true;
70
+ }
71
+ }
72
+ return false;
73
+ }
74
+ function applySecurityHeaders(res) {
75
+ res.setHeader?.('X-Content-Type-Options', 'nosniff');
76
+ res.setHeader?.('X-Frame-Options', 'DENY');
77
+ res.setHeader?.('X-XSS-Protection', '0');
78
+ res.setHeader?.('Referrer-Policy', 'no-referrer');
79
+ }
80
+ function emitLog(enabled, logger, event) {
81
+ if (!enabled)
82
+ return;
83
+ if (typeof logger === 'function') {
84
+ logger(event);
85
+ return;
86
+ }
87
+ const target = logger ?? console;
88
+ const msg = `[req-shield] ${event.event.toUpperCase()} ${event.method ?? 'UNKNOWN'} ${event.path}`;
89
+ if (event.level === 'warn') {
90
+ target.warn?.(msg, event);
91
+ }
92
+ else if (event.level === 'error') {
93
+ target.error?.(msg, event);
94
+ }
95
+ else {
96
+ target.info?.(msg, event);
97
+ }
98
+ }
99
+ function sendBlockedResponse(res, statusCode, body) {
100
+ if (typeof res.status === 'function') {
101
+ const chained = res.status(statusCode);
102
+ if (typeof chained?.json === 'function' && typeof body === 'object' && body !== null) {
103
+ chained.json(body);
104
+ return;
105
+ }
106
+ if (typeof chained?.send === 'function') {
107
+ chained.send(body);
108
+ return;
109
+ }
110
+ }
111
+ res.statusCode = statusCode;
112
+ if (typeof body === 'object' && body !== null) {
113
+ res.setHeader?.('Content-Type', 'application/json; charset=utf-8');
114
+ res.end?.(JSON.stringify(body));
115
+ }
116
+ else {
117
+ res.setHeader?.('Content-Type', 'text/plain; charset=utf-8');
118
+ res.end?.(body == null ? '' : String(body));
119
+ }
120
+ }
121
+ /**
122
+ * Creates an early-block security middleware that protects Node.js / Express apps
123
+ * by immediately rejecting path-traversal attempts, vulnerability scanner probes,
124
+ * dangerous file extensions, and optional IP / method / User-Agent rules.
125
+ *
126
+ * Usage:
127
+ * ```ts
128
+ * import express from 'express';
129
+ * import earlyBlock from 'req-shield';
130
+ *
131
+ * const app = express();
132
+ * app.use(earlyBlock());
133
+ * ```
134
+ */
135
+ export function earlyBlock(options = {}) {
136
+ 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;
137
+ const activePatternSet = new Set([...(patterns ?? DEFAULT_BLOCKED_PATTERNS), ...extraPatterns].map((p) => p.toLowerCase()));
138
+ for (const excluded of excludePatterns) {
139
+ activePatternSet.delete(excluded.toLowerCase());
140
+ }
141
+ const normalizeExt = (ext) => ext.trim().replace(/^\./, '').toLowerCase();
142
+ const activeExtensionSet = new Set([...(blockedExtensions ?? DEFAULT_BLOCKED_EXTENSIONS), ...extraExtensions]
143
+ .map(normalizeExt)
144
+ .filter(Boolean));
145
+ for (const excluded of excludeExtensions) {
146
+ activeExtensionSet.delete(normalizeExt(excluded));
147
+ }
148
+ let extensionRegex = buildExtensionRegex([...activeExtensionSet]);
149
+ const activeAllowPaths = [...allowPaths];
150
+ const blockedMethodSet = new Set(blockedMethods.map((m) => m.toUpperCase()));
151
+ const allowedMethodSet = allowedMethods
152
+ ? new Set(allowedMethods.map((m) => m.toUpperCase()))
153
+ : null;
154
+ function earlyBlockMiddleware(req, res, next) {
155
+ const rawUrl = req.originalUrl || req.url || req.path || '';
156
+ const rawPath = extractPathname(rawUrl);
157
+ const method = req.method?.toUpperCase();
158
+ const clientIp = getClientIp(req, trustProxy);
159
+ if (enableSecurityHeaders) {
160
+ applySecurityHeaders(res);
161
+ }
162
+ const reject = (reason, detail, overrideStatus) => {
163
+ const effectiveStatus = overrideStatus ?? statusCode;
164
+ const ctx = {
165
+ reason,
166
+ detail,
167
+ path: rawPath,
168
+ method,
169
+ ip: clientIp,
170
+ };
171
+ emitLog(enableLogging, logger, {
172
+ level: 'warn',
173
+ event: 'blocked',
174
+ path: rawPath,
175
+ method,
176
+ ip: clientIp,
177
+ reason,
178
+ detail,
179
+ statusCode: effectiveStatus,
180
+ });
181
+ onBlock?.(req, res, ctx);
182
+ const body = typeof responseBody === 'function'
183
+ ? responseBody(req, ctx)
184
+ : responseBody;
185
+ sendBlockedResponse(res, effectiveStatus, body);
186
+ };
187
+ // 0. Max URL length check
188
+ if (typeof maxUrlLength === 'number' && rawUrl.length > maxUrlLength) {
189
+ reject('url_too_long', `length=${rawUrl.length}`);
190
+ return;
191
+ }
192
+ // 1. Method checks
193
+ if (method) {
194
+ if (allowedMethodSet && !allowedMethodSet.has(method)) {
195
+ reject('blocked_method', method);
196
+ return;
197
+ }
198
+ if (blockedMethodSet.has(method)) {
199
+ reject('blocked_method', method);
200
+ return;
201
+ }
202
+ }
203
+ // 2. IP allow/block checks
204
+ if (allowedIps && (!clientIp || !matchesAny(clientIp, allowedIps))) {
205
+ reject('blocked_ip', clientIp);
206
+ return;
207
+ }
208
+ if (blockedIps.length > 0 && clientIp && matchesAny(clientIp, blockedIps)) {
209
+ reject('blocked_ip', clientIp);
210
+ return;
211
+ }
212
+ // 3. User-Agent checks
213
+ if (blockedUserAgents.length > 0) {
214
+ const ua = getHeader(req, 'user-agent');
215
+ if (ua && matchesSubstringOrRegex(ua, blockedUserAgents)) {
216
+ reject('blocked_user_agent', ua);
217
+ return;
218
+ }
219
+ }
220
+ // 4. Path traversal checks (always enforced before allowPaths unless disabled)
221
+ if (blockPathTraversal && hasPathTraversal(rawPath, maxDecodeDepth)) {
222
+ reject('path_traversal', rawPath);
223
+ return;
224
+ }
225
+ // 5. Allowlist bypass for probe patterns & extensions
226
+ const isAllowlisted = activeAllowPaths.length > 0 && matchesAny(rawPath, activeAllowPaths, true);
227
+ if (!isAllowlisted) {
228
+ const urlPath = rawPath.toLowerCase();
229
+ // 6. Sensitive probe patterns (.env, .git, wp-admin, etc.)
230
+ for (const pattern of activePatternSet) {
231
+ if (urlPath.includes(pattern)) {
232
+ reject('probe_pattern', pattern);
233
+ return;
234
+ }
235
+ }
236
+ // 7. Dangerous file extensions
237
+ if (extensionRegex && extensionRegex.test(urlPath)) {
238
+ reject('blocked_extension', urlPath);
239
+ return;
240
+ }
241
+ }
242
+ // 8. Injection blocking checks on parsed payloads (before sanitization)
243
+ const maxDepth = sanitization.maxDepth ?? 10;
244
+ if (blockPrototypePollution) {
245
+ if (hasPrototypePollutionKey(req.query, maxDepth) ||
246
+ hasPrototypePollutionKey(req.body, maxDepth) ||
247
+ hasPrototypePollutionKey(req.params, maxDepth)) {
248
+ reject('prototype_pollution', 'Prototype pollution key detected');
249
+ return;
250
+ }
251
+ }
252
+ if (blockNoSqlInjection) {
253
+ if (hasNoSqlOperatorKey(req.query, maxDepth) ||
254
+ hasNoSqlOperatorKey(req.body, maxDepth) ||
255
+ hasNoSqlOperatorKey(req.params, maxDepth)) {
256
+ reject('nosql_injection', 'NoSQL operator key detected');
257
+ return;
258
+ }
259
+ }
260
+ // 9. Custom predicate
261
+ if (blockIf) {
262
+ const customResult = blockIf(req);
263
+ if (customResult) {
264
+ reject('custom', typeof customResult === 'string' ? customResult : undefined);
265
+ return;
266
+ }
267
+ }
268
+ // 10. Request data sanitization (when enableSanitization is true)
269
+ if (enableSanitization) {
270
+ const sanitizedTargets = [];
271
+ if ((sanitization.sanitizeQuery ?? true) && req.query !== undefined) {
272
+ const resQuery = sanitizeValue(req.query, sanitization, 'query');
273
+ if (resQuery.modified) {
274
+ req.query = resQuery.value;
275
+ sanitizedTargets.push('query');
276
+ }
277
+ }
278
+ if ((sanitization.sanitizeBody ?? true) && req.body !== undefined) {
279
+ const resBody = sanitizeValue(req.body, sanitization, 'body');
280
+ if (resBody.modified) {
281
+ req.body = resBody.value;
282
+ sanitizedTargets.push('body');
283
+ }
284
+ }
285
+ if ((sanitization.sanitizeParams ?? true) && req.params !== undefined) {
286
+ const resParams = sanitizeValue(req.params, sanitization, 'params');
287
+ if (resParams.modified) {
288
+ req.params = resParams.value;
289
+ sanitizedTargets.push('params');
290
+ }
291
+ }
292
+ if (sanitization.sanitizeHeaders && req.headers !== undefined) {
293
+ const resHeaders = sanitizeValue(req.headers, sanitization, 'headers');
294
+ if (resHeaders.modified) {
295
+ req.headers = resHeaders.value;
296
+ sanitizedTargets.push('headers');
297
+ }
298
+ }
299
+ if (sanitizedTargets.length > 0) {
300
+ emitLog(enableLogging, logger, {
301
+ level: 'info',
302
+ event: 'sanitized',
303
+ path: rawPath,
304
+ method,
305
+ ip: clientIp,
306
+ sanitizedTargets,
307
+ });
308
+ }
309
+ }
310
+ if (logAllowed) {
311
+ emitLog(enableLogging, logger, {
312
+ level: 'info',
313
+ event: 'allowed',
314
+ path: rawPath,
315
+ method,
316
+ ip: clientIp,
317
+ });
318
+ }
319
+ next();
320
+ }
321
+ const middleware = earlyBlockMiddleware;
322
+ middleware.addBlockedPath = (pattern) => {
323
+ const normalized = pattern.trim().toLowerCase();
324
+ if (normalized)
325
+ activePatternSet.add(normalized);
326
+ return middleware;
327
+ };
328
+ middleware.addBlockedPaths = (list) => {
329
+ for (const p of list)
330
+ middleware.addBlockedPath(p);
331
+ return middleware;
332
+ };
333
+ middleware.removeBlockedPath = (pattern) => {
334
+ activePatternSet.delete(pattern.trim().toLowerCase());
335
+ return middleware;
336
+ };
337
+ middleware.removeBlockedPaths = (list) => {
338
+ for (const p of list)
339
+ middleware.removeBlockedPath(p);
340
+ return middleware;
341
+ };
342
+ middleware.addAllowedPath = (path) => {
343
+ if (typeof path === 'string') {
344
+ const exists = activeAllowPaths.some((p) => typeof p === 'string' && p.toLowerCase() === path.toLowerCase());
345
+ if (!exists)
346
+ activeAllowPaths.push(path);
347
+ }
348
+ else {
349
+ const exists = activeAllowPaths.some((p) => p instanceof RegExp &&
350
+ p.source === path.source &&
351
+ p.flags === path.flags);
352
+ if (!exists)
353
+ activeAllowPaths.push(path);
354
+ }
355
+ return middleware;
356
+ };
357
+ middleware.removeAllowedPath = (path) => {
358
+ for (let i = activeAllowPaths.length - 1; i >= 0; i--) {
359
+ const item = activeAllowPaths[i];
360
+ if (typeof path === 'string' && typeof item === 'string') {
361
+ if (item.toLowerCase() === path.toLowerCase()) {
362
+ activeAllowPaths.splice(i, 1);
363
+ }
364
+ }
365
+ else if (path instanceof RegExp && item instanceof RegExp) {
366
+ if (item.source === path.source && item.flags === path.flags) {
367
+ activeAllowPaths.splice(i, 1);
368
+ }
369
+ }
370
+ }
371
+ return middleware;
372
+ };
373
+ middleware.addBlockedExtension = (ext) => {
374
+ const normalized = normalizeExt(ext);
375
+ if (normalized) {
376
+ activeExtensionSet.add(normalized);
377
+ extensionRegex = buildExtensionRegex([...activeExtensionSet]);
378
+ }
379
+ return middleware;
380
+ };
381
+ middleware.removeBlockedExtension = (ext) => {
382
+ const normalized = normalizeExt(ext);
383
+ if (activeExtensionSet.delete(normalized)) {
384
+ extensionRegex = buildExtensionRegex([...activeExtensionSet]);
385
+ }
386
+ return middleware;
387
+ };
388
+ middleware.getBlockedPatterns = () => [...activePatternSet];
389
+ middleware.getAllowedPaths = () => [...activeAllowPaths];
390
+ middleware.getBlockedExtensions = () => [...activeExtensionSet];
391
+ return middleware;
392
+ }
393
+ /**
394
+ * Pre-configured default middleware instance for zero-config drop-in usage:
395
+ * `app.use(earlyBlockProbes);`
396
+ */
397
+ export const earlyBlockProbes = earlyBlock();
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }