eslint-plugin-express-security 1.3.3 → 1.4.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,278 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Ofri Peretz
4
+ * Licensed under the MIT License. Use of this source code is governed by the
5
+ * MIT license that can be found in the LICENSE file.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.requireQueryTypeGuard = void 0;
9
+ const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
+ /** String.prototype methods that throw or misbehave on string[] / ParsedQs. */
11
+ const STRING_METHODS = new Set([
12
+ 'replace',
13
+ 'toLowerCase',
14
+ 'toUpperCase',
15
+ 'trim',
16
+ 'split',
17
+ 'substring',
18
+ 'slice',
19
+ 'startsWith',
20
+ 'endsWith',
21
+ 'includes',
22
+ 'match',
23
+ ]);
24
+ const EQUALITY_OPS = new Set(['===', '==', '!==', '!=']);
25
+ exports.requireQueryTypeGuard = (0, eslint_devkit_1.createRule)({
26
+ name: 'require-query-type-guard',
27
+ meta: {
28
+ type: 'problem',
29
+ hasSuggestions: true,
30
+ docs: {
31
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-query-type-guard.md',
32
+ description: 'Require a type guard or String() coercion before calling string methods on req.query values',
33
+ cwe: 'CWE-843',
34
+ cvss: 7.5,
35
+ },
36
+ messages: {
37
+ unguardedQueryStringMethod: (0, eslint_devkit_1.formatLLMMessage)({
38
+ icon: eslint_devkit_1.MessageIcons.SECURITY,
39
+ issueName: 'req.query Type Confusion (CWE-843)',
40
+ cwe: 'CWE-843',
41
+ description: '.{{method}}() is called on {{target}}, but req.query values are string | string[] | ParsedQs — ?x=a&x=b yields an array, so this throws (DoS) or bypasses sanitization.',
42
+ severity: 'HIGH',
43
+ fix: "Coerce with String(...) or guard with typeof value === 'string' / Array.isArray(value) before treating the query value as a string.",
44
+ documentationLink: 'https://cwe.mitre.org/data/definitions/843.html',
45
+ }),
46
+ wrapString: 'Coerce the query value with String(...) before calling .{{method}}()',
47
+ coerceAtAssignment: 'Coerce at the assignment: wrap the req.query access in String(...)',
48
+ },
49
+ schema: [
50
+ {
51
+ type: 'object',
52
+ properties: {
53
+ coercers: {
54
+ type: 'array',
55
+ items: { type: 'string' },
56
+ description: 'Callee names whose result is a safe string coercion',
57
+ },
58
+ validators: {
59
+ type: 'array',
60
+ items: { type: 'string' },
61
+ description: 'Callee / method names treated as type-safe sources',
62
+ },
63
+ },
64
+ additionalProperties: false,
65
+ },
66
+ ],
67
+ },
68
+ defaultOptions: [{}],
69
+ create(context, [options]) {
70
+ const { coercers, validators } = options;
71
+ const coercerNames = new Set(coercers ?? ['String']);
72
+ const validatorNames = new Set(validators ?? ['parse', 'safeParse']);
73
+ const sourceCode = context.sourceCode;
74
+ function newFrame() {
75
+ return {
76
+ tracked: new Map(),
77
+ guardedVars: new Set(),
78
+ guardedProps: new Set(),
79
+ };
80
+ }
81
+ const frames = [newFrame()];
82
+ const current = () => frames[frames.length - 1];
83
+ function isRequestIdent(name) {
84
+ const lower = name.toLowerCase();
85
+ return lower === 'req' || lower === 'request';
86
+ }
87
+ /** `req.query` / `request.query` — non-computed. */
88
+ function isReqQuery(node) {
89
+ return (node.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
90
+ !node.computed &&
91
+ node.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
92
+ isRequestIdent(node.object.name) &&
93
+ node.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
94
+ node.property.name === 'query');
95
+ }
96
+ /** `req.query.name` or `req.query['x']` — a member on the query object. */
97
+ function isQueryMember(node) {
98
+ return (node.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression && isReqQuery(node.object));
99
+ }
100
+ /** Stable key for a query member: source text of its property node. */
101
+ function propKey(node) {
102
+ return sourceCode.getText(node.property);
103
+ }
104
+ /** Mark an identifier as proven-string, in the frame that tracks it. */
105
+ function guardVar(name) {
106
+ for (let i = frames.length - 1; i >= 0; i--) {
107
+ if (frames[i].tracked.has(name)) {
108
+ frames[i].guardedVars.add(name);
109
+ return;
110
+ }
111
+ }
112
+ current().guardedVars.add(name);
113
+ }
114
+ /** Mark a typeof / Array.isArray guard target (identifier or query member). */
115
+ function markGuard(target) {
116
+ if (target.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
117
+ guardVar(target.name);
118
+ }
119
+ else if (isQueryMember(target)) {
120
+ current().guardedProps.add(propKey(target));
121
+ }
122
+ }
123
+ function isVarGuarded(name) {
124
+ return frames.some((f) => f.guardedVars.has(name));
125
+ }
126
+ function isPropGuarded(key) {
127
+ return frames.some((f) => f.guardedProps.has(key));
128
+ }
129
+ function lookupTracked(name) {
130
+ for (let i = frames.length - 1; i >= 0; i--) {
131
+ const init = frames[i].tracked.get(name);
132
+ if (init)
133
+ return init;
134
+ }
135
+ return null;
136
+ }
137
+ /** `typeof X === 'string'` (either operand order) → X, else null. */
138
+ function extractTypeofTarget(a, b) {
139
+ if (a.type === eslint_devkit_1.AST_NODE_TYPES.UnaryExpression &&
140
+ a.operator === 'typeof' &&
141
+ b.type === eslint_devkit_1.AST_NODE_TYPES.Literal &&
142
+ b.value === 'string') {
143
+ return a.argument;
144
+ }
145
+ return null;
146
+ }
147
+ /** `Array.isArray(...)` call. */
148
+ function isArrayIsArrayCall(node) {
149
+ const callee = node.callee;
150
+ return (callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
151
+ callee.object.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
152
+ callee.object.name === 'Array' &&
153
+ callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier &&
154
+ callee.property.name === 'isArray');
155
+ }
156
+ /** Call whose result is a proven-safe string source (coercer / validator). */
157
+ function isSafeCall(node) {
158
+ if (node.type !== eslint_devkit_1.AST_NODE_TYPES.CallExpression)
159
+ return false;
160
+ const callee = node.callee;
161
+ if (callee.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
162
+ return coercerNames.has(callee.name) || validatorNames.has(callee.name);
163
+ }
164
+ if (callee.type === eslint_devkit_1.AST_NODE_TYPES.MemberExpression &&
165
+ callee.property.type === eslint_devkit_1.AST_NODE_TYPES.Identifier) {
166
+ return validatorNames.has(callee.property.name);
167
+ }
168
+ return false;
169
+ }
170
+ function wrapWithString(fixer, target) {
171
+ return [
172
+ fixer.insertTextBefore(target, 'String('),
173
+ fixer.insertTextAfter(target, ')'),
174
+ ];
175
+ }
176
+ function enterFunction() {
177
+ frames.push(newFrame());
178
+ }
179
+ function exitFunction() {
180
+ frames.pop();
181
+ }
182
+ return {
183
+ 'FunctionDeclaration, FunctionExpression, ArrowFunctionExpression': enterFunction,
184
+ 'FunctionDeclaration:exit': exitFunction,
185
+ 'FunctionExpression:exit': exitFunction,
186
+ 'ArrowFunctionExpression:exit': exitFunction,
187
+ VariableDeclarator(node) {
188
+ if (node.id.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
189
+ return;
190
+ const init = node.init;
191
+ if (!init)
192
+ return;
193
+ // Only a RAW query member taints; String(req.query.x), schema.parse(...)
194
+ // and every other init shape is left untracked.
195
+ if (isQueryMember(init)) {
196
+ current().tracked.set(node.id.name, init);
197
+ }
198
+ },
199
+ AssignmentExpression(node) {
200
+ if (node.operator !== '=')
201
+ return;
202
+ if (node.left.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
203
+ return;
204
+ if (isQueryMember(node.right)) {
205
+ current().tracked.set(node.left.name, node.right);
206
+ return;
207
+ }
208
+ // v = String(v) / v = schema.parse(v) — proven safe from here on.
209
+ if (isSafeCall(node.right)) {
210
+ guardVar(node.left.name);
211
+ }
212
+ },
213
+ BinaryExpression(node) {
214
+ if (!EQUALITY_OPS.has(node.operator))
215
+ return;
216
+ const target = extractTypeofTarget(node.left, node.right) ??
217
+ extractTypeofTarget(node.right, node.left);
218
+ if (target)
219
+ markGuard(target);
220
+ },
221
+ CallExpression(node) {
222
+ // Array.isArray(v) is a guard, not a violation.
223
+ if (isArrayIsArrayCall(node)) {
224
+ const arg = node.arguments[0];
225
+ if (arg)
226
+ markGuard(arg);
227
+ return;
228
+ }
229
+ const callee = node.callee;
230
+ if (callee.type !== eslint_devkit_1.AST_NODE_TYPES.MemberExpression)
231
+ return;
232
+ if (callee.property.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
233
+ return;
234
+ const method = callee.property.name;
235
+ if (!STRING_METHODS.has(method))
236
+ return;
237
+ const obj = callee.object;
238
+ // Shape 1: direct member call — req.query.name.replace(...)
239
+ if (isQueryMember(obj)) {
240
+ if (isPropGuarded(propKey(obj)))
241
+ return;
242
+ context.report({
243
+ node: callee,
244
+ messageId: 'unguardedQueryStringMethod',
245
+ data: { target: sourceCode.getText(obj), method },
246
+ suggest: [
247
+ {
248
+ messageId: 'wrapString',
249
+ data: { method },
250
+ fix: (fixer) => wrapWithString(fixer, obj),
251
+ },
252
+ ],
253
+ });
254
+ return;
255
+ }
256
+ // Shape 2: call on an identifier assigned from a raw query member.
257
+ if (obj.type !== eslint_devkit_1.AST_NODE_TYPES.Identifier)
258
+ return;
259
+ const trackedInit = lookupTracked(obj.name);
260
+ if (!trackedInit)
261
+ return;
262
+ if (isVarGuarded(obj.name))
263
+ return;
264
+ context.report({
265
+ node: callee,
266
+ messageId: 'unguardedQueryStringMethod',
267
+ data: { target: obj.name, method },
268
+ suggest: [
269
+ {
270
+ messageId: 'coerceAtAssignment',
271
+ fix: (fixer) => wrapWithString(fixer, trackedInit),
272
+ },
273
+ ],
274
+ });
275
+ },
276
+ };
277
+ },
278
+ });