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,125 @@
1
+ /**
2
+ * Common path substrings and patterns targeted by automated vulnerability/bot scanners.
3
+ */
4
+ export const DEFAULT_BLOCKED_PATTERNS = [
5
+ '/.env',
6
+ '/.git',
7
+ '/config.env',
8
+ '/.svn',
9
+ '/.htaccess',
10
+ '/.aws',
11
+ '/wp-admin',
12
+ '/wp-login',
13
+ '/wp-content',
14
+ '/wp-includes',
15
+ '/phpmyadmin',
16
+ '/pma',
17
+ '/actuator',
18
+ '/.ds_store',
19
+ '/backup.sql',
20
+ '/dump.sql',
21
+ '/database.sql',
22
+ '/phpinfo.php',
23
+ '/xmlrpc.php',
24
+ '.php',
25
+ ];
26
+ /**
27
+ * File extensions commonly targeted by vulnerability scanners.
28
+ */
29
+ export const DEFAULT_BLOCKED_EXTENSIONS = [
30
+ 'env',
31
+ 'git',
32
+ 'bak',
33
+ 'old',
34
+ 'swp',
35
+ ];
36
+ /**
37
+ * Normalizes unicode characters and overlong/non-standard encodings to standard ASCII
38
+ * e.g., Fullwidth Full Stop (`\uFF0E`), Two Dot Leader (`\u2025`),
39
+ * Fullwidth Solidus (`\uFF0F`), Division Slash (`\u2215`), Fraction Slash (`\u2044`),
40
+ * Fullwidth Reverse Solidus (`\uFF3C`).
41
+ */
42
+ export function normalizeUnicodeSeparators(str) {
43
+ // NFKC decomposes and normalizes fullwidth compatibility forms (e.g. fullwidth dot -> ., fullwidth slash -> /)
44
+ let normalized = str.normalize('NFKC');
45
+ // Explicit mapping for slash, dot and backslash Unicode lookalikes
46
+ normalized = normalized
47
+ .replace(/[\u2024\u2025\u2026\uFF0E\u3002]/g, '.') // One/Two/Three Dot Leaders, Fullwidth Full Stop, Ideographic Full Stop
48
+ .replace(/[\u2215\u2044\uFF0F\u002F]/g, '/') // Division Slash, Fraction Slash, Fullwidth Slash
49
+ .replace(/[\uFF3C\u2216\uFE68\u005C]/g, '/'); // Fullwidth Reverse Solidus, Set Minus, Small Reverse Solidus, Backslash
50
+ // Overlong UTF-8 hex sequences (common IIS/Apache/Nginx bypass attempts)
51
+ normalized = normalized
52
+ .replace(/%(?:c0%ae|e0%80%ae|c1%9e)/gi, '.') // Overlong dot
53
+ .replace(/%(?:c0%af|e0%80%af|c1%8f)/gi, '/') // Overlong slash
54
+ .replace(/%(?:c0%5c|c1%9c|e0%80%dc)/gi, '/'); // Overlong backslash
55
+ return normalized;
56
+ }
57
+ /**
58
+ * Safely decodes URI components multiple times to detect obfuscated / URL-encoded traversal sequences
59
+ * e.g., `%2e%2e%2f`, `%252e%252e%252f`, `%25252e`, etc.
60
+ */
61
+ export function decodeFully(str, maxDepth = 4) {
62
+ let decoded = str;
63
+ for (let i = 0; i < maxDepth; i++) {
64
+ try {
65
+ const next = decodeURIComponent(decoded);
66
+ if (next === decoded)
67
+ break;
68
+ decoded = next;
69
+ }
70
+ catch {
71
+ // If malformed percent encoding like %c0%ae, continue
72
+ break;
73
+ }
74
+ }
75
+ return decoded;
76
+ }
77
+ function checkDotsAndSlashes(text) {
78
+ const unified = text.replace(/\\/g, '/');
79
+ return (unified.includes('../') ||
80
+ unified.includes('/..') ||
81
+ unified === '..' ||
82
+ unified.startsWith('..') ||
83
+ unified.endsWith('..') ||
84
+ /\.\.[\/\\]/.test(unified) ||
85
+ /[\/\\]\.\./.test(unified));
86
+ }
87
+ /**
88
+ * Checks whether a path contains path-traversal sequences like `../` or `/..` or unicode/URL-encoded equivalents.
89
+ */
90
+ export function hasPathTraversal(pathOrUrl, maxDecodeDepth = 4) {
91
+ if (!pathOrUrl)
92
+ return false;
93
+ // 1. Check raw string after unicode normalization
94
+ const normalizedRaw = normalizeUnicodeSeparators(pathOrUrl);
95
+ if (checkDotsAndSlashes(normalizedRaw))
96
+ return true;
97
+ // 2. Check fully URL-decoded string after unicode normalization
98
+ const fullyDecoded = normalizeUnicodeSeparators(decodeFully(pathOrUrl, maxDecodeDepth));
99
+ if (checkDotsAndSlashes(fullyDecoded))
100
+ return true;
101
+ // 3. Check regex for hex/unicode dot bypasses (e.g. %2e, %u002e)
102
+ const regexCheck = pathOrUrl
103
+ .replace(/%(?:2e|u002e)/gi, '.')
104
+ .replace(/%(?:2f|5c|u002f|u005c)/gi, '/');
105
+ if (checkDotsAndSlashes(regexCheck))
106
+ return true;
107
+ return false;
108
+ }
109
+ /**
110
+ * Strips query parameters, fragment identifiers, and extracts ONLY the path portion of the URL.
111
+ * Ensures that query parameters (`?text=...&query=...`) and request bodies are NEVER checked
112
+ * by path validation.
113
+ */
114
+ export function extractPathname(urlOrPath) {
115
+ if (!urlOrPath)
116
+ return '';
117
+ const queryIndex = urlOrPath.indexOf('?');
118
+ const fragmentIndex = urlOrPath.indexOf('#');
119
+ let cutIndex = urlOrPath.length;
120
+ if (queryIndex !== -1)
121
+ cutIndex = Math.min(cutIndex, queryIndex);
122
+ if (fragmentIndex !== -1)
123
+ cutIndex = Math.min(cutIndex, fragmentIndex);
124
+ return urlOrPath.slice(0, cutIndex);
125
+ }
@@ -0,0 +1,136 @@
1
+ const PROTOTYPE_POLLUTION_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
2
+ function isPlainObject(value) {
3
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
4
+ return false;
5
+ }
6
+ const proto = Object.getPrototypeOf(value);
7
+ return proto === Object.prototype || proto === null;
8
+ }
9
+ /**
10
+ * Checks whether an object/array tree contains own `__proto__`, `constructor`, or `prototype` keys.
11
+ */
12
+ export function hasPrototypePollutionKey(value, maxDepth = 10, depth = 0) {
13
+ if (depth > maxDepth || typeof value !== 'object' || value === null) {
14
+ return false;
15
+ }
16
+ if (Array.isArray(value)) {
17
+ return value.some((item) => hasPrototypePollutionKey(item, maxDepth, depth + 1));
18
+ }
19
+ if (!isPlainObject(value)) {
20
+ return false;
21
+ }
22
+ for (const key of Object.getOwnPropertyNames(value)) {
23
+ if (PROTOTYPE_POLLUTION_KEYS.has(key)) {
24
+ return true;
25
+ }
26
+ if (hasPrototypePollutionKey(value[key], maxDepth, depth + 1)) {
27
+ return true;
28
+ }
29
+ }
30
+ return false;
31
+ }
32
+ /**
33
+ * Checks whether an object/array tree contains `$`-prefixed NoSQL operator keys (e.g. `$gt`, `$ne`, `$where`).
34
+ */
35
+ export function hasNoSqlOperatorKey(value, maxDepth = 10, depth = 0) {
36
+ if (depth > maxDepth || typeof value !== 'object' || value === null) {
37
+ return false;
38
+ }
39
+ if (Array.isArray(value)) {
40
+ return value.some((item) => hasNoSqlOperatorKey(item, maxDepth, depth + 1));
41
+ }
42
+ if (!isPlainObject(value)) {
43
+ return false;
44
+ }
45
+ for (const key of Object.keys(value)) {
46
+ if (key.startsWith('$')) {
47
+ return true;
48
+ }
49
+ if (hasNoSqlOperatorKey(value[key], maxDepth, depth + 1)) {
50
+ return true;
51
+ }
52
+ }
53
+ return false;
54
+ }
55
+ /**
56
+ * Sanitizes a single string to remove null bytes, XSS payloads, and optional SQL injection patterns.
57
+ */
58
+ export function sanitizeString(input, options = {}, target = 'body', key) {
59
+ const { stripNullBytes = true, stripXss = true, stripSqlInjection = false, trimStrings = false, customSanitizer, } = options;
60
+ let out = input;
61
+ if (stripNullBytes) {
62
+ out = out.replace(/\0/g, '').replace(/%00/gi, '');
63
+ }
64
+ if (stripXss) {
65
+ // Strip <script>...</script> blocks and standalone <script ...> / </script> tags
66
+ out = out
67
+ .replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi, '')
68
+ .replace(/<\/?script\b[^>]*>/gi, '')
69
+ // Strip dangerous URI schemes
70
+ .replace(/\b(?:javascript|vbscript)\s*:/gi, '')
71
+ .replace(/\bdata\s*:\s*text\/html\b/gi, '')
72
+ // Strip inline HTML event handlers (e.g., onerror=, onload=, onclick=)
73
+ .replace(/\bon[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
74
+ }
75
+ if (stripSqlInjection) {
76
+ out = out
77
+ // Strip SQL block comments and end-of-line comments
78
+ .replace(/\/\*[\s\S]*?\*\//g, '')
79
+ .replace(/(?:^|\s)--[^\r\n]*/g, '')
80
+ // Strip chained destructive SQL statements
81
+ .replace(/;\s*(?:drop|delete|truncate|alter|exec|execute|union\s+select)\b/gi, '');
82
+ }
83
+ if (trimStrings) {
84
+ out = out.trim();
85
+ }
86
+ if (customSanitizer) {
87
+ out = customSanitizer(out, { target, key });
88
+ }
89
+ return out;
90
+ }
91
+ /**
92
+ * Recursively sanitizes an unknown value (string, array, or plain object).
93
+ * Returns `{ value, modified }` so callers can detect if any mutation occurred.
94
+ */
95
+ export function sanitizeValue(input, options = {}, target = 'body', depth = 0, key) {
96
+ const maxDepth = options.maxDepth ?? 10;
97
+ if (depth > maxDepth) {
98
+ return { value: input, modified: false };
99
+ }
100
+ if (typeof input === 'string') {
101
+ const sanitized = sanitizeString(input, options, target, key);
102
+ return { value: sanitized, modified: sanitized !== input };
103
+ }
104
+ if (Array.isArray(input)) {
105
+ let modified = false;
106
+ const out = input.map((item) => {
107
+ const res = sanitizeValue(item, options, target, depth + 1, key);
108
+ if (res.modified)
109
+ modified = true;
110
+ return res.value;
111
+ });
112
+ return { value: modified ? out : input, modified };
113
+ }
114
+ if (!isPlainObject(input)) {
115
+ return { value: input, modified: false };
116
+ }
117
+ const stripNoSql = options.stripNoSqlOperators ?? true;
118
+ const stripProto = options.stripPrototypePollution ?? true;
119
+ let modified = false;
120
+ const out = {};
121
+ for (const prop of Object.getOwnPropertyNames(input)) {
122
+ if (stripProto && PROTOTYPE_POLLUTION_KEYS.has(prop)) {
123
+ modified = true;
124
+ continue;
125
+ }
126
+ if (stripNoSql && prop.startsWith('$')) {
127
+ modified = true;
128
+ continue;
129
+ }
130
+ const res = sanitizeValue(input[prop], options, target, depth + 1, prop);
131
+ if (res.modified)
132
+ modified = true;
133
+ out[prop] = res.value;
134
+ }
135
+ return { value: modified ? out : input, modified };
136
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
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 type { BlockContext, BlockReason, EarlyBlockMiddleware, EarlyBlockOptions, LoggerLike, Middleware, MiddlewareLogEvent, NextFunction, RequestLike, ResponseLike, SanitizationOptions, SanitizeTarget, } from './types.js';
6
+ export default earlyBlock;
@@ -0,0 +1,21 @@
1
+ import type { EarlyBlockMiddleware, EarlyBlockOptions } from './types.js';
2
+ /**
3
+ * Creates an early-block security middleware that protects Node.js / Express apps
4
+ * by immediately rejecting path-traversal attempts, vulnerability scanner probes,
5
+ * dangerous file extensions, and optional IP / method / User-Agent rules.
6
+ *
7
+ * Usage:
8
+ * ```ts
9
+ * import express from 'express';
10
+ * import earlyBlock from 'req-shield';
11
+ *
12
+ * const app = express();
13
+ * app.use(earlyBlock());
14
+ * ```
15
+ */
16
+ export declare function earlyBlock(options?: EarlyBlockOptions): EarlyBlockMiddleware;
17
+ /**
18
+ * Pre-configured default middleware instance for zero-config drop-in usage:
19
+ * `app.use(earlyBlockProbes);`
20
+ */
21
+ export declare const earlyBlockProbes: EarlyBlockMiddleware;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Common path substrings and patterns targeted by automated vulnerability/bot scanners.
3
+ */
4
+ export declare const DEFAULT_BLOCKED_PATTERNS: readonly string[];
5
+ /**
6
+ * File extensions commonly targeted by vulnerability scanners.
7
+ */
8
+ export declare const DEFAULT_BLOCKED_EXTENSIONS: readonly string[];
9
+ /**
10
+ * Normalizes unicode characters and overlong/non-standard encodings to standard ASCII
11
+ * e.g., Fullwidth Full Stop (`\uFF0E`), Two Dot Leader (`\u2025`),
12
+ * Fullwidth Solidus (`\uFF0F`), Division Slash (`\u2215`), Fraction Slash (`\u2044`),
13
+ * Fullwidth Reverse Solidus (`\uFF3C`).
14
+ */
15
+ export declare function normalizeUnicodeSeparators(str: string): string;
16
+ /**
17
+ * Safely decodes URI components multiple times to detect obfuscated / URL-encoded traversal sequences
18
+ * e.g., `%2e%2e%2f`, `%252e%252e%252f`, `%25252e`, etc.
19
+ */
20
+ export declare function decodeFully(str: string, maxDepth?: number): string;
21
+ /**
22
+ * Checks whether a path contains path-traversal sequences like `../` or `/..` or unicode/URL-encoded equivalents.
23
+ */
24
+ export declare function hasPathTraversal(pathOrUrl: string, maxDecodeDepth?: number): boolean;
25
+ /**
26
+ * Strips query parameters, fragment identifiers, and extracts ONLY the path portion of the URL.
27
+ * Ensures that query parameters (`?text=...&query=...`) and request bodies are NEVER checked
28
+ * by path validation.
29
+ */
30
+ export declare function extractPathname(urlOrPath: string): string;
@@ -0,0 +1,21 @@
1
+ import type { SanitizationOptions, SanitizeTarget } from './types.js';
2
+ /**
3
+ * Checks whether an object/array tree contains own `__proto__`, `constructor`, or `prototype` keys.
4
+ */
5
+ export declare function hasPrototypePollutionKey(value: unknown, maxDepth?: number, depth?: number): boolean;
6
+ /**
7
+ * Checks whether an object/array tree contains `$`-prefixed NoSQL operator keys (e.g. `$gt`, `$ne`, `$where`).
8
+ */
9
+ export declare function hasNoSqlOperatorKey(value: unknown, maxDepth?: number, depth?: number): boolean;
10
+ /**
11
+ * Sanitizes a single string to remove null bytes, XSS payloads, and optional SQL injection patterns.
12
+ */
13
+ export declare function sanitizeString(input: string, options?: SanitizationOptions, target?: SanitizeTarget, key?: string): string;
14
+ /**
15
+ * Recursively sanitizes an unknown value (string, array, or plain object).
16
+ * Returns `{ value, modified }` so callers can detect if any mutation occurred.
17
+ */
18
+ export declare function sanitizeValue(input: unknown, options?: SanitizationOptions, target?: SanitizeTarget, depth?: number, key?: string): {
19
+ value: unknown;
20
+ modified: boolean;
21
+ };
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Structural request interface compatible with Express, Connect, Fastify, and Node http.IncomingMessage.
3
+ */
4
+ export interface RequestLike {
5
+ url?: string;
6
+ originalUrl?: string;
7
+ path?: string;
8
+ method?: string;
9
+ ip?: string;
10
+ headers?: Record<string, string | string[] | undefined>;
11
+ query?: Record<string, unknown>;
12
+ body?: unknown;
13
+ params?: Record<string, unknown>;
14
+ socket?: {
15
+ remoteAddress?: string;
16
+ };
17
+ }
18
+ /**
19
+ * Structural response interface compatible with Express, Connect, and Node http.ServerResponse.
20
+ */
21
+ export interface ResponseLike {
22
+ statusCode: number;
23
+ status?: (code: number) => ResponseLike;
24
+ json?: (body: unknown) => unknown;
25
+ send?: (body: unknown) => unknown;
26
+ setHeader?: (name: string, value: string | string[]) => unknown;
27
+ end?: (chunk?: unknown) => unknown;
28
+ }
29
+ export type NextFunction = (err?: unknown) => void;
30
+ export type Middleware = (req: RequestLike, res: ResponseLike, next: NextFunction) => void;
31
+ /**
32
+ * Middleware function returned by `earlyBlock()` with chainable methods
33
+ * to dynamically add/remove blocked paths, allowed paths, and extensions.
34
+ */
35
+ export interface EarlyBlockMiddleware extends Middleware {
36
+ /** Add a path/substring pattern to block (case-insensitive). */
37
+ addBlockedPath(pattern: string): EarlyBlockMiddleware;
38
+ /** Add multiple path/substring patterns to block. */
39
+ addBlockedPaths(patterns: string[]): EarlyBlockMiddleware;
40
+ /** Remove a path/substring pattern from the active blocklist (including predefined ones). */
41
+ removeBlockedPath(pattern: string): EarlyBlockMiddleware;
42
+ /** Remove multiple path/substring patterns from the active blocklist. */
43
+ removeBlockedPaths(patterns: string[]): EarlyBlockMiddleware;
44
+ /** Add a path or RegExp to the allowlist (bypasses probe/extension checks). */
45
+ addAllowedPath(path: string | RegExp): EarlyBlockMiddleware;
46
+ /** Remove a path or RegExp from the allowlist. */
47
+ removeAllowedPath(path: string | RegExp): EarlyBlockMiddleware;
48
+ /** Add a file extension (with or without leading dot) to block. */
49
+ addBlockedExtension(ext: string): EarlyBlockMiddleware;
50
+ /** Remove a file extension from the active blocklist (including predefined ones). */
51
+ removeBlockedExtension(ext: string): EarlyBlockMiddleware;
52
+ /** Return a snapshot of currently active blocked path patterns. */
53
+ getBlockedPatterns(): string[];
54
+ /** Return a snapshot of currently active allowlist paths. */
55
+ getAllowedPaths(): Array<string | RegExp>;
56
+ /** Return a snapshot of currently active blocked extensions. */
57
+ getBlockedExtensions(): string[];
58
+ }
59
+ export type BlockReason = 'path_traversal' | 'probe_pattern' | 'blocked_extension' | 'blocked_method' | 'blocked_ip' | 'blocked_user_agent' | 'prototype_pollution' | 'nosql_injection' | 'url_too_long' | 'custom';
60
+ export type SanitizeTarget = 'body' | 'query' | 'params' | 'headers';
61
+ export interface SanitizationOptions {
62
+ /** Sanitize `req.body`. @default true */
63
+ sanitizeBody?: boolean;
64
+ /** Sanitize `req.query`. @default true */
65
+ sanitizeQuery?: boolean;
66
+ /** Sanitize `req.params`. @default true */
67
+ sanitizeParams?: boolean;
68
+ /** Sanitize `req.headers`. @default false */
69
+ sanitizeHeaders?: boolean;
70
+ /** Strip null bytes (`\0` / `%00`). @default true */
71
+ stripNullBytes?: boolean;
72
+ /** Remove MongoDB/NoSQL `$`-prefixed operator keys from objects. @default true */
73
+ stripNoSqlOperators?: boolean;
74
+ /** Remove `__proto__`, `constructor`, and `prototype` keys from objects. @default true */
75
+ stripPrototypePollution?: boolean;
76
+ /** Strip `<script>` tags, `javascript:`/`vbscript:`/`data:text/html` URIs, and inline `on*=` handlers. @default true */
77
+ stripXss?: boolean;
78
+ /** Strip common SQL injection comment/statement patterns (`--`, `/*...*\/`, `; DROP/DELETE/UNION SELECT`). @default false */
79
+ stripSqlInjection?: boolean;
80
+ /** Trim leading/trailing whitespace on string values. @default false */
81
+ trimStrings?: boolean;
82
+ /** Maximum recursion depth when sanitizing nested objects/arrays. @default 10 */
83
+ maxDepth?: number;
84
+ /** Optional custom string sanitizer hook. */
85
+ customSanitizer?: (value: string, context: {
86
+ target: SanitizeTarget;
87
+ key?: string;
88
+ }) => string;
89
+ }
90
+ export interface MiddlewareLogEvent {
91
+ level: 'info' | 'warn' | 'error';
92
+ event: 'blocked' | 'sanitized' | 'allowed';
93
+ path: string;
94
+ method?: string;
95
+ ip?: string;
96
+ reason?: BlockReason;
97
+ detail?: string;
98
+ statusCode?: number;
99
+ sanitizedTargets?: SanitizeTarget[];
100
+ }
101
+ export interface LoggerLike {
102
+ info?: (message: string, meta?: unknown) => void;
103
+ warn?: (message: string, meta?: unknown) => void;
104
+ error?: (message: string, meta?: unknown) => void;
105
+ }
106
+ export interface BlockContext {
107
+ reason: BlockReason;
108
+ detail?: string;
109
+ path: string;
110
+ method?: string;
111
+ ip?: string;
112
+ }
113
+ export interface EarlyBlockOptions {
114
+ /**
115
+ * Block path traversal attempts (e.g. `../`, `/..`, unicode/overlong/URL-encoded bypasses).
116
+ * @default true
117
+ */
118
+ blockPathTraversal?: boolean;
119
+ /**
120
+ * Maximum number of `decodeURIComponent` passes when checking for double/multi-encoded traversal.
121
+ * @default 4
122
+ */
123
+ maxDecodeDepth?: number;
124
+ /**
125
+ * Replace the default blocked probe patterns (e.g. `/.env`, `/.git`, `/wp-admin`).
126
+ * All patterns are matched case-insensitively against the URL pathname.
127
+ */
128
+ patterns?: string[];
129
+ /**
130
+ * Additional probe patterns to append to the active pattern list.
131
+ */
132
+ extraPatterns?: string[];
133
+ /**
134
+ * Predefined (or configured) probe patterns to remove/exclude from blocking
135
+ * (e.g. `['/actuator', '.php']`).
136
+ */
137
+ excludePatterns?: string[];
138
+ /**
139
+ * Replace the default blocked file extensions (without leading dot).
140
+ * @default ['env', 'git', 'bak', 'old', 'swp']
141
+ */
142
+ blockedExtensions?: string[];
143
+ /**
144
+ * Additional file extensions (without leading dot) to block.
145
+ */
146
+ extraExtensions?: string[];
147
+ /**
148
+ * Predefined (or configured) file extensions to remove/exclude from blocking.
149
+ */
150
+ excludeExtensions?: string[];
151
+ /**
152
+ * Paths or patterns that bypass probe-pattern and extension checks.
153
+ * Note: path-traversal checks still apply unless `blockPathTraversal` is `false`.
154
+ */
155
+ allowPaths?: Array<string | RegExp>;
156
+ /**
157
+ * HTTP methods to block (case-insensitive, e.g. `['TRACE', 'TRACK']`).
158
+ */
159
+ blockedMethods?: string[];
160
+ /**
161
+ * HTTP methods to allow (case-insensitive). If specified, any method not in this list is blocked.
162
+ */
163
+ allowedMethods?: string[];
164
+ /**
165
+ * Client IP addresses or patterns to block.
166
+ */
167
+ blockedIps?: Array<string | RegExp>;
168
+ /**
169
+ * Client IP addresses or patterns to allow. If specified, any IP not matching is blocked.
170
+ */
171
+ allowedIps?: Array<string | RegExp>;
172
+ /**
173
+ * When `true`, reads the leftmost IP from `X-Forwarded-For` before falling back to `req.ip` / `req.socket.remoteAddress`.
174
+ * @default false
175
+ */
176
+ trustProxy?: boolean;
177
+ /**
178
+ * User-Agent substrings (case-insensitive) or RegExps to block.
179
+ */
180
+ blockedUserAgents?: Array<string | RegExp>;
181
+ /**
182
+ * Custom predicate to block requests. Return `true` or a non-empty reason string to block.
183
+ */
184
+ blockIf?: (req: RequestLike) => boolean | string;
185
+ /**
186
+ * HTTP status code sent when a request is blocked.
187
+ * @default 404
188
+ */
189
+ statusCode?: number;
190
+ /**
191
+ * Response body (or factory function) sent when a request is blocked.
192
+ * @default { detail: 'Not Found' }
193
+ */
194
+ responseBody?: unknown | ((req: RequestLike, ctx: BlockContext) => unknown);
195
+ /**
196
+ * Optional hook invoked whenever a request is blocked (useful for metrics or structured logging).
197
+ */
198
+ onBlock?: (req: RequestLike, res: ResponseLike, ctx: BlockContext) => void;
199
+ /**
200
+ * Enable automatic sanitization of `req.body`, `req.query`, `req.params` (and optionally `req.headers`)
201
+ * to remove XSS, null bytes, prototype pollution, NoSQL operators, and optional SQL injection patterns.
202
+ * @default false
203
+ */
204
+ enableSanitization?: boolean;
205
+ /**
206
+ * Fine-grained sanitization options (used when `enableSanitization` is `true`).
207
+ */
208
+ sanitization?: SanitizationOptions;
209
+ /**
210
+ * Immediately block requests containing `__proto__`, `constructor`, or `prototype` keys in query/body/params.
211
+ * @default false
212
+ */
213
+ blockPrototypePollution?: boolean;
214
+ /**
215
+ * Immediately block requests containing `$`-prefixed NoSQL operator keys in query/body/params.
216
+ * @default false
217
+ */
218
+ blockNoSqlInjection?: boolean;
219
+ /**
220
+ * Maximum allowed URL length (`req.originalUrl || req.url`). Requests exceeding this are blocked.
221
+ */
222
+ maxUrlLength?: number;
223
+ /**
224
+ * Set baseline defensive security headers (`X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
225
+ * `X-XSS-Protection: 0`, `Referrer-Policy: no-referrer`) on responses.
226
+ * @default false
227
+ */
228
+ enableSecurityHeaders?: boolean;
229
+ /**
230
+ * Enable structured logging for blocked and sanitized requests (and optionally allowed requests via `logAllowed`).
231
+ * @default false
232
+ */
233
+ enableLogging?: boolean;
234
+ /**
235
+ * When `enableLogging` is `true`, also log allowed requests that passed through without being blocked.
236
+ * @default false
237
+ */
238
+ logAllowed?: boolean;
239
+ /**
240
+ * Custom logger object (`info`, `warn`, `error`) or callback function used when `enableLogging` is `true`.
241
+ * Defaults to `console`.
242
+ */
243
+ logger?: LoggerLike | ((event: MiddlewareLogEvent) => void);
244
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "req-shield",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Zero-dependency Node.js / Express security middleware for early request blocking, path-traversal defense, and scanner probe protection.",
5
+ "main": "./dist/cjs/index.js",
6
+ "module": "./dist/esm/index.js",
7
+ "types": "./dist/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/types/index.d.ts",
11
+ "import": "./dist/esm/index.js",
12
+ "require": "./dist/cjs/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "clean": "rm -rf dist",
22
+ "build": "node scripts/build.mjs",
23
+ "typecheck": "tsc --noEmit",
24
+ "test": "npm run build && node --test test/*.test.mjs",
25
+ "prepublishOnly": "npm run build"
26
+ },
27
+ "keywords": [
28
+ "middleware",
29
+ "express",
30
+ "security",
31
+ "waf",
32
+ "path-traversal",
33
+ "scanner-protection",
34
+ "early-block",
35
+ "nodejs",
36
+ "shivapendem"
37
+ ],
38
+ "license": "MIT",
39
+ "engines": {
40
+ "node": ">=18.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^22.0.0",
44
+ "typescript": "^5.7.0"
45
+ }
6
46
  }