eslint-plugin-secure-coding 3.4.0 → 3.4.2

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.
Files changed (65) hide show
  1. package/README.md +4 -2
  2. package/package.json +5 -18
  3. package/src/index.d.ts +17 -23
  4. package/src/index.js +2 -131
  5. package/src/oxlint.d.ts +17 -20
  6. package/src/oxlint.js +0 -18
  7. package/src/rules/detect-non-literal-regexp/index.js +5 -79
  8. package/src/rules/detect-object-injection/index.js +2 -221
  9. package/src/rules/detect-weak-password-validation/index.js +0 -12
  10. package/src/rules/no-directive-injection/index.js +0 -33
  11. package/src/rules/no-electron-security-issues/index.js +0 -41
  12. package/src/rules/no-format-string-injection/index.js +0 -82
  13. package/src/rules/no-graphql-injection/index.js +8 -133
  14. package/src/rules/no-hardcoded-credentials/index.js +3 -297
  15. package/src/rules/no-hardcoded-session-tokens/index.js +0 -11
  16. package/src/rules/no-improper-sanitization/index.js +0 -44
  17. package/src/rules/no-improper-type-validation/index.js +1 -51
  18. package/src/rules/no-insecure-comparison/index.js +8 -47
  19. package/src/rules/no-ldap-injection/index.js +8 -61
  20. package/src/rules/no-missing-authentication/index.js +2 -56
  21. package/src/rules/no-pii-in-logs/index.js +0 -13
  22. package/src/rules/no-privilege-escalation/index.js +2 -49
  23. package/src/rules/no-redos-vulnerable-regex/index.js +3 -49
  24. package/src/rules/no-sensitive-data-exposure/index.js +5 -29
  25. package/src/rules/no-template-injection/index.js +0 -6
  26. package/src/rules/no-unchecked-loop-condition/index.js +3 -99
  27. package/src/rules/no-unlimited-resource-allocation/index.js +2 -75
  28. package/src/rules/no-unsafe-deserialization/index.js +1 -111
  29. package/src/rules/no-unsafe-regex-construction/index.js +22 -62
  30. package/src/rules/no-weak-password-recovery/index.js +0 -43
  31. package/src/rules/no-xpath-injection/index.js +13 -75
  32. package/src/rules/no-xxe-injection/index.js +1 -47
  33. package/src/rules/require-backend-authorization/index.js +0 -10
  34. package/src/rules/require-secure-defaults/index.js +0 -10
  35. package/src/types/index.js +0 -5
  36. package/AGENTS.md +0 -131
  37. package/CHANGELOG.md +0 -379
  38. package/src/rules/detect-non-literal-regexp/index.d.ts +0 -28
  39. package/src/rules/detect-object-injection/index.d.ts +0 -35
  40. package/src/rules/detect-weak-password-validation/index.d.ts +0 -12
  41. package/src/rules/no-directive-injection/index.d.ts +0 -38
  42. package/src/rules/no-electron-security-issues/index.d.ts +0 -36
  43. package/src/rules/no-format-string-injection/index.d.ts +0 -44
  44. package/src/rules/no-graphql-injection/index.d.ts +0 -47
  45. package/src/rules/no-hardcoded-credentials/index.d.ts +0 -95
  46. package/src/rules/no-hardcoded-session-tokens/index.d.ts +0 -12
  47. package/src/rules/no-improper-sanitization/index.d.ts +0 -38
  48. package/src/rules/no-improper-type-validation/index.d.ts +0 -36
  49. package/src/rules/no-insecure-comparison/index.d.ts +0 -26
  50. package/src/rules/no-ldap-injection/index.d.ts +0 -53
  51. package/src/rules/no-missing-authentication/index.d.ts +0 -32
  52. package/src/rules/no-pii-in-logs/index.d.ts +0 -12
  53. package/src/rules/no-privilege-escalation/index.d.ts +0 -32
  54. package/src/rules/no-redos-vulnerable-regex/index.d.ts +0 -28
  55. package/src/rules/no-sensitive-data-exposure/index.d.ts +0 -30
  56. package/src/rules/no-template-injection/index.d.ts +0 -23
  57. package/src/rules/no-unchecked-loop-condition/index.d.ts +0 -38
  58. package/src/rules/no-unlimited-resource-allocation/index.d.ts +0 -38
  59. package/src/rules/no-unsafe-deserialization/index.d.ts +0 -40
  60. package/src/rules/no-unsafe-regex-construction/index.d.ts +0 -30
  61. package/src/rules/no-weak-password-recovery/index.d.ts +0 -38
  62. package/src/rules/no-xpath-injection/index.d.ts +0 -39
  63. package/src/rules/no-xxe-injection/index.d.ts +0 -36
  64. package/src/rules/require-backend-authorization/index.d.ts +0 -12
  65. package/src/rules/require-secure-defaults/index.d.ts +0 -12
@@ -1,70 +1,45 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
8
3
  exports.noUnsafeRegexConstruction = void 0;
9
4
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
5
  const eslint_devkit_2 = require("@interlace/eslint-devkit");
11
- // Inline regex-metacharacter escape, appended to the flagged expression by the
12
- // `escapeUserInput` suggestion fixer. No `escapeRegExp` helper exists in user
13
- // code, so the fix must be self-contained rather than calling one.
14
6
  const INLINE_ESCAPE_SUFFIX = '.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';
15
- /**
16
- * Check if a node represents user input (variable, function call, template literal)
17
- */
18
7
  function isUserInput(node) {
19
- // Function calls might return user input
20
8
  if (node.type === 'CallExpression') {
21
9
  return true;
22
10
  }
23
- // Template literals with expressions are dynamic
24
11
  if (node.type === 'TemplateLiteral') {
25
12
  return node.expressions.length > 0;
26
13
  }
27
- // Member expressions accessing user properties
28
14
  if (node.type === 'MemberExpression') {
29
15
  return true;
30
16
  }
31
- // Variables are likely user input unless they are safe literals
32
17
  if (node.type === 'Identifier') {
33
- // Exclude common safe patterns, but be more restrictive
34
18
  const safeIdentifiers = ['pattern', 'regex', 'regExp', 'regexp'];
35
19
  if (safeIdentifiers.includes(node.name.toLowerCase())) {
36
- // For these identifiers, check if they're assigned user input in scope
37
- // For now, we'll be conservative and flag them as potentially unsafe
38
- return true; // Changed from false to true - safer to flag as user input
20
+ return true;
39
21
  }
40
22
  return true;
41
23
  }
42
24
  return false;
43
25
  }
44
- /**
45
- * Check if a node is escaped (wrapped in an escaping function)
46
- */
47
26
  function isEscaped(node, trustedFunctions, sourceCode) {
48
- // Check if the node itself is a call to a trusted escaping function
49
27
  if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
50
28
  const functionName = node.callee.name;
51
29
  if (trustedFunctions.includes(functionName)) {
52
30
  return true;
53
31
  }
54
32
  }
55
- // Also check if it's wrapped in a trusted function call (for complex cases).
56
- // `current` is only assigned from `node` (truthy on entry) or `parent` after
57
- // an explicit `if (!parent) break;`, so it's never null at the loop check
58
- // (CodeQL: `js/useless-conditional` on the `current &&` test).
59
33
  let current = node;
60
34
  let depth = 0;
61
- const maxDepth = 5; // Prevent infinite loops
35
+ const maxDepth = 5;
62
36
  while (depth < maxDepth) {
63
37
  const parent = sourceCode.getNodeByRangeIndex?.(current.range[0] - 1) ||
64
38
  current.parent;
65
39
  if (!parent)
66
40
  break;
67
- if (parent.type === 'CallExpression' && parent.callee.type === 'Identifier') {
41
+ if (parent.type === 'CallExpression' &&
42
+ parent.callee.type === 'Identifier') {
68
43
  const functionName = parent.callee.name;
69
44
  if (trustedFunctions.includes(functionName)) {
70
45
  return true;
@@ -75,31 +50,28 @@ function isEscaped(node, trustedFunctions, sourceCode) {
75
50
  }
76
51
  return false;
77
52
  }
78
- /**
79
- * Check if regex flags are dynamic
80
- */
81
53
  function hasDynamicFlags(node) {
82
- // Check second argument (flags)
83
54
  if (node.arguments.length > 1) {
84
55
  const flagsNode = node.arguments[1];
85
56
  return isUserInput(flagsNode);
86
57
  }
87
58
  return false;
88
59
  }
89
- /**
90
- * Extract pattern from RegExp construction
91
- */
92
60
  function extractPattern(node, sourceCode, trustedFunctions) {
93
61
  const patternNode = node.arguments.length > 0 ? node.arguments[0] : null;
94
62
  if (!patternNode) {
95
63
  return { patternNode: null, isUserInput: false, isEscaped: false };
96
64
  }
97
65
  const isUserInputValue = isUserInput(patternNode);
98
- // Default trusted functions + user configured ones
99
- const allTrustedFunctions = [...new Set([
100
- 'escapeRegex', 'escape', 'sanitize', 'RegExp.escape',
101
- ...trustedFunctions
102
- ])];
66
+ const allTrustedFunctions = [
67
+ ...new Set([
68
+ 'escapeRegex',
69
+ 'escape',
70
+ 'sanitize',
71
+ 'RegExp.escape',
72
+ ...trustedFunctions,
73
+ ]),
74
+ ];
103
75
  const isEscapedValue = isEscaped(patternNode, allTrustedFunctions, sourceCode);
104
76
  return {
105
77
  patternNode,
@@ -133,7 +105,6 @@ exports.noUnsafeRegexConstruction = (0, eslint_devkit_2.createRule)({
133
105
  issueName: 'Escape User Input',
134
106
  description: 'Escape user input for regex',
135
107
  severity: 'LOW',
136
- // oxlint-disable-next-line no-template-curly-in-string
137
108
  fix: 'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',
138
109
  documentationLink: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping',
139
110
  }),
@@ -196,28 +167,24 @@ exports.noUnsafeRegexConstruction = (0, eslint_devkit_2.createRule)({
196
167
  },
197
168
  ],
198
169
  create(context, [options = {}]) {
199
- // `options` is always an object here (defaulted by the destructuring
200
- // parameter above), so a second `|| {}` fallback could never fire —
201
- // removed as dead code.
202
170
  const { allowLiterals = true, maxPatternLength = 100, trustedEscapingFunctions = ['escapeRegex', 'escape', 'sanitize'], } = options;
203
171
  const sourceCode = context.sourceCode;
204
- /**
205
- * Check RegExp constructor calls
206
- */
207
172
  function checkRegExpCall(node) {
208
- // Check for RegExp constructor
209
- const isRegExpCall = (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'RegExp') ||
210
- (node.type === 'NewExpression' && node.callee.type === 'Identifier' && node.callee.name === 'RegExp');
173
+ const isRegExpCall = (node.type === 'CallExpression' &&
174
+ node.callee.type === 'Identifier' &&
175
+ node.callee.name === 'RegExp') ||
176
+ (node.type === 'NewExpression' &&
177
+ node.callee.type === 'Identifier' &&
178
+ node.callee.name === 'RegExp');
211
179
  if (!isRegExpCall) {
212
180
  return;
213
181
  }
214
- const { patternNode, isUserInput: isUserInputValue, isEscaped: isEscapedValue } = extractPattern(node, sourceCode, trustedEscapingFunctions);
182
+ const { patternNode, isUserInput: isUserInputValue, isEscaped: isEscapedValue, } = extractPattern(node, sourceCode, trustedEscapingFunctions);
215
183
  if (!patternNode) {
216
184
  return;
217
185
  }
218
- // Check for literal strings
219
- if (patternNode.type === 'Literal' && typeof patternNode.value === 'string') {
220
- // Even literals can be unsafe if they're very long - check this regardless of allowLiterals
186
+ if (patternNode.type === 'Literal' &&
187
+ typeof patternNode.value === 'string') {
221
188
  const patternLength = patternNode.value.length;
222
189
  if (patternLength > maxPatternLength) {
223
190
  context.report({
@@ -238,7 +205,6 @@ exports.noUnsafeRegexConstruction = (0, eslint_devkit_2.createRule)({
238
205
  return;
239
206
  }
240
207
  if (!allowLiterals) {
241
- // If we reach here, allowLiterals is false, so treat as unsafe
242
208
  context.report({
243
209
  node: patternNode,
244
210
  messageId: 'unsafeRegexConstruction',
@@ -257,7 +223,6 @@ exports.noUnsafeRegexConstruction = (0, eslint_devkit_2.createRule)({
257
223
  return;
258
224
  }
259
225
  }
260
- // Check for user input without escaping
261
226
  if (isUserInputValue && !isEscapedValue) {
262
227
  const patternText = context.sourceCode.getText(patternNode);
263
228
  context.report({
@@ -271,10 +236,6 @@ exports.noUnsafeRegexConstruction = (0, eslint_devkit_2.createRule)({
271
236
  suggest: [
272
237
  {
273
238
  messageId: 'escapeUserInput',
274
- // Append an inline regex-metacharacter escape so special chars are neutralized.
275
- // Parenthesize patternText first: it's spliced in as-is (could be any
276
- // expression, e.g. a lower-precedence one), so `.replace(...)` must bind
277
- // to the whole expression, not just its last operand.
278
239
  fix: (fixer) => fixer.replaceText(patternNode, `(${patternText})${INLINE_ESCAPE_SUFFIX}`),
279
240
  },
280
241
  {
@@ -288,7 +249,6 @@ exports.noUnsafeRegexConstruction = (0, eslint_devkit_2.createRule)({
288
249
  ],
289
250
  });
290
251
  }
291
- // Check for dynamic flags
292
252
  if (hasDynamicFlags(node)) {
293
253
  context.report({
294
254
  node,
@@ -1,9 +1,4 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
8
3
  exports.noWeakPasswordRecovery = void 0;
9
4
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
@@ -220,33 +215,21 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
220
215
  const { secureTokenFunctions = ['crypto.randomBytes', 'crypto.randomUUID', 'randomBytes', 'generateSecureToken'], trustedSanitizers = [], trustedAnnotations = ['secure-recovery', 'rate-limited'], strictMode = false, } = options;
221
216
  const sourceCode = context.sourceCode;
222
217
  const filename = context.filename;
223
- // Create safety checker for false positive detection
224
218
  const safetyChecker = (0, eslint_devkit_3.createSafetyChecker)({
225
219
  trustedSanitizers,
226
220
  trustedAnnotations,
227
221
  trustedOrmPatterns: [],
228
222
  strictMode,
229
223
  });
230
- /**
231
- * Check if code is specifically related to password recovery
232
- * Requires MULTIPLE indicators to avoid false positives on general password handling
233
- * Only returns true for functions that BOTH:
234
- * 1. Have password/forgot in the name
235
- * 2. AND have reset/recovery/forgot in the name
236
- */
237
- // oxlint-disable-next-line consistent-function-scoping
238
224
  const isRecoveryRelated = (text) => {
239
225
  const lowerText = text.toLowerCase();
240
- // Require BOTH a password keyword AND a recovery action keyword
241
226
  const passwordKeywords = ['password', 'pwd'];
242
227
  const recoveryKeywords = ['reset', 'recover', 'forgot', 'restore'];
243
228
  const hasPasswordKeyword = passwordKeywords.some(keyword => lowerText.includes(keyword));
244
229
  const hasRecoveryKeyword = recoveryKeywords.some(keyword => lowerText.includes(keyword));
245
- // Both must be present to be considered recovery-related
246
230
  if (hasPasswordKeyword && hasRecoveryKeyword) {
247
231
  return true;
248
232
  }
249
- // Also check for compound patterns that strongly indicate password recovery
250
233
  const strongRecoveryPatterns = [
251
234
  'resetpassword', 'passwordreset', 'forgotpassword', 'passwordrecovery',
252
235
  'recoverytoken', 'password_reset', 'forgot_password', 'reset_password',
@@ -254,16 +237,10 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
254
237
  ];
255
238
  return strongRecoveryPatterns.some(pattern => lowerText.includes(pattern));
256
239
  };
257
- /**
258
- * Check if token generation is cryptographically secure
259
- */
260
240
  const isSecureTokenGeneration = (callExpression) => {
261
241
  const callText = sourceCode.getText(callExpression);
262
242
  return secureTokenFunctions.some(func => callText.includes(func));
263
243
  };
264
- /**
265
- * Check if token has expiration
266
- */
267
244
  const hasTokenExpiration = (functionNode) => {
268
245
  const functionText = sourceCode.getText(functionNode).toLowerCase();
269
246
  return functionText.includes('expire') ||
@@ -272,19 +249,15 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
272
249
  functionText.includes('lifetime');
273
250
  };
274
251
  return {
275
- // Check variable declarations for recovery tokens
276
252
  VariableDeclarator(node) {
277
253
  if (!node.init || node.id.type !== 'Identifier') {
278
254
  return;
279
255
  }
280
256
  const varName = node.id.name.toLowerCase();
281
- // Check if variable is specifically password-recovery-related (not just any token)
282
257
  if (isRecoveryRelated(varName)) {
283
258
  const initText = sourceCode.getText(node.init);
284
- // Check for weak token generation
285
259
  if (node.init.type === 'CallExpression') {
286
260
  if (!isSecureTokenGeneration(node.init)) {
287
- // FALSE POSITIVE REDUCTION
288
261
  if (safetyChecker.isSafe(node, context) || (node.parent && safetyChecker.isSafe(node.parent, context))) {
289
262
  return;
290
263
  }
@@ -299,10 +272,8 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
299
272
  }
300
273
  }
301
274
  else if (node.init.type === 'BinaryExpression') {
302
- // Check for predictable patterns
303
275
  const weakPatterns = ['Date.now()', 'Math.random()', 'timestamp', 'new Date()'];
304
276
  if (weakPatterns.some(pattern => initText.includes(pattern))) {
305
- // FALSE POSITIVE REDUCTION
306
277
  if (safetyChecker.isSafe(node, context) || (node.parent && safetyChecker.isSafe(node.parent, context))) {
307
278
  return;
308
279
  }
@@ -318,18 +289,13 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
318
289
  }
319
290
  }
320
291
  },
321
- // Check function declarations for recovery logic
322
- // ONLY check function NAME to avoid FPs on any function that mentions "password"
323
292
  FunctionDeclaration(node) {
324
293
  if (!node.id) {
325
294
  return;
326
295
  }
327
296
  const functionName = node.id.name;
328
297
  const functionText = sourceCode.getText(node).toLowerCase();
329
- // IMPORTANT: Only check the function NAME, not the entire body
330
- // This prevents flagging every function that happens to contain "password"
331
298
  if (isRecoveryRelated(functionName)) {
332
- // Check for token expiration
333
299
  if (!hasTokenExpiration(node)) {
334
300
  if (safetyChecker.isSafe(node, context)) {
335
301
  return;
@@ -343,7 +309,6 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
343
309
  },
344
310
  });
345
311
  }
346
- // Check for rate limiting (very basic check)
347
312
  if (!functionText.includes('limit') && !functionText.includes('rate')) {
348
313
  if (safetyChecker.isSafe(node, context)) {
349
314
  return;
@@ -359,10 +324,8 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
359
324
  }
360
325
  }
361
326
  },
362
- // Check call expressions for logging sensitive data
363
327
  CallExpression(node) {
364
328
  const callee = node.callee;
365
- // Check for console.log, logger calls
366
329
  if ((callee.type === 'MemberExpression' &&
367
330
  callee.object.type === 'Identifier' &&
368
331
  (callee.object.name === 'console' || callee.object.name === 'logger') &&
@@ -371,16 +334,13 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
371
334
  (callee.type === 'Identifier' && callee.name === 'logger')) {
372
335
  const args = node.arguments;
373
336
  for (const arg of args) {
374
- // Ignore literal strings (labels, messages) - focusing on sensitive variables
375
337
  if (arg.type === 'Literal') {
376
338
  continue;
377
339
  }
378
340
  const argText = sourceCode.getText(arg).toLowerCase();
379
- // Check if logging recovery-related sensitive data
380
341
  if (isRecoveryRelated(argText) &&
381
342
  (argText.includes('token') || argText.includes('password') ||
382
343
  argText.includes('reset') || argText.includes('code'))) {
383
- // FALSE POSITIVE REDUCTION
384
344
  if (safetyChecker.isSafe(node, context)) {
385
345
  continue;
386
346
  }
@@ -396,13 +356,10 @@ exports.noWeakPasswordRecovery = (0, eslint_devkit_1.createRule)({
396
356
  }
397
357
  }
398
358
  },
399
- // Check for weak recovery verification
400
359
  IfStatement(node) {
401
360
  const test = node.test;
402
361
  const testText = sourceCode.getText(test).toLowerCase();
403
- // Check if this is a recovery-related condition
404
362
  if (isRecoveryRelated(testText)) {
405
- // Look for weak verification (just checking email exists)
406
363
  if (testText.includes('email') && !testText.includes('verify') &&
407
364
  !testText.includes('token') && !testText.includes('code') &&
408
365
  !testText.includes('otp') && !testText.includes('sms')) {
@@ -1,9 +1,4 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
8
3
  exports.noXpathInjection = void 0;
9
4
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
@@ -161,62 +156,42 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
161
156
  const { xpathFunctions = ['evaluate', 'selectSingleNode', 'selectNodes', 'xpath', 'select'], xpathValidationFunctions = ['validateXPath', 'escapeXPath', 'sanitizeXPath', 'cleanXPath'], trustedSanitizers = [], trustedAnnotations = [], strictMode = false, } = options;
162
157
  const sourceCode = context.sourceCode;
163
158
  const filename = context.filename;
164
- // Create safety checker for false positive detection
165
159
  const safetyChecker = (0, eslint_devkit_3.createSafetyChecker)({
166
160
  trustedSanitizers,
167
161
  trustedAnnotations,
168
162
  trustedOrmPatterns: [],
169
163
  strictMode,
170
164
  });
171
- // Track variables that have been validated/sanitized
172
165
  const validatedVariables = new Set();
173
- /**
174
- * Check if this is an XPath-related operation
175
- */
176
166
  const isXpathOperation = (node) => {
177
167
  const callee = node.callee;
178
- // Check for XPath method calls
179
168
  if (callee.type === 'MemberExpression' &&
180
169
  callee.property.type === 'Identifier' &&
181
170
  xpathFunctions.includes(callee.property.name)) {
182
171
  return true;
183
172
  }
184
- // Check for XPath library calls
185
173
  if (callee.type === 'Identifier' && xpathFunctions.includes(callee.name)) {
186
174
  return true;
187
175
  }
188
176
  return false;
189
177
  };
190
- /**
191
- * Check if XPath expression contains dangerous patterns
192
- */
193
- // oxlint-disable-next-line consistent-function-scoping
194
178
  const containsDangerousXpath = (xpathText) => {
195
- // Dangerous XPath patterns that allow traversal or injection
196
179
  const dangerousPatterns = [
197
- /\.\./, // Parent directory traversal
198
- /\/\*/, // All children selector
199
- /\[.*\*\]/, // Wildcard in predicates
200
- /\/\//, // Descendant-or-self axis (can be dangerous in some contexts)
201
- /text\(\)/, // Content extraction
202
- /comment\(\)/, // Comment extraction
203
- /processing-instruction\(\)/, // Processing instruction extraction
180
+ /\.\./,
181
+ /\/\*/,
182
+ /\[.*\*\]/,
183
+ /\/\//,
184
+ /text\(\)/,
185
+ /comment\(\)/,
186
+ /processing-instruction\(\)/,
204
187
  ];
205
188
  return dangerousPatterns.some(pattern => pattern.test(xpathText));
206
189
  };
207
- /**
208
- * Check if string contains XPath interpolation
209
- */
210
- // oxlint-disable-next-line consistent-function-scoping
211
190
  const containsXpathInterpolation = (text) => {
212
191
  return /\$\{[^}]+\}/.test(text) || /'[^']*\+[^+]*'/.test(text) || /"[^"]*\+[^+]*"/.test(text);
213
192
  };
214
- /**
215
- * Check if XPath input is from untrusted source
216
- */
217
193
  const isUntrustedXpathInput = (inputNode) => {
218
194
  if (inputNode.type === 'MemberExpression') {
219
- // Check patterns like req.query.*, req.body.*, req.params.*
220
195
  if (inputNode.object.type === 'MemberExpression' &&
221
196
  inputNode.object.object.type === 'Identifier' &&
222
197
  inputNode.object.object.name === 'req' &&
@@ -224,7 +199,6 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
224
199
  ['query', 'body', 'params', 'param'].includes(inputNode.object.property.name)) {
225
200
  return true;
226
201
  }
227
- // Check patterns like req.*
228
202
  if (inputNode.object.type === 'Identifier' && inputNode.object.name === 'req') {
229
203
  return true;
230
204
  }
@@ -236,7 +210,6 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
236
210
  if (['req', 'request', 'query', 'params', 'input', 'user', 'search'].some(keyword => varName.includes(keyword))) {
237
211
  return true;
238
212
  }
239
- // Check if it comes from function parameters
240
213
  let current = inputNode;
241
214
  while (current) {
242
215
  if (current.type === 'FunctionDeclaration' ||
@@ -254,9 +227,6 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
254
227
  }
255
228
  return false;
256
229
  };
257
- /**
258
- * Check if XPath input has been validated
259
- */
260
230
  const isXpathInputValidated = (inputNode) => {
261
231
  let current = inputNode;
262
232
  while (current) {
@@ -269,17 +239,12 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
269
239
  }
270
240
  return false;
271
241
  };
272
- /**
273
- * Check for safe annotation on containing statement or variable declaration
274
- */
275
242
  const hasSafeAnnotationOnStatement = (node) => {
276
243
  let current = node;
277
- // Walk up to find VariableDeclaration, ExpressionStatement, FunctionDeclaration, or containing statement
278
244
  while (current) {
279
245
  if (current.type === 'VariableDeclaration' ||
280
246
  current.type === 'ExpressionStatement' ||
281
247
  current.type === 'FunctionDeclaration') {
282
- // Check for JSDoc comments before this statement
283
248
  const comments = sourceCode.getCommentsBefore(current);
284
249
  for (const comment of comments) {
285
250
  if (comment.type === 'Block' && comment.value.includes('@xpath-safe')) {
@@ -292,7 +257,6 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
292
257
  return false;
293
258
  };
294
259
  return {
295
- // Check XPath function calls
296
260
  CallExpression(node) {
297
261
  if (!isXpathOperation(node)) {
298
262
  return;
@@ -301,13 +265,10 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
301
265
  if (args.length === 0) {
302
266
  return;
303
267
  }
304
- // Check first argument (usually the XPath expression)
305
268
  const xpathArg = args[0];
306
269
  if (xpathArg.type === 'Literal' && typeof xpathArg.value === 'string') {
307
270
  const xpathText = xpathArg.value;
308
- // Check for dangerous XPath patterns
309
271
  if (containsDangerousXpath(xpathText)) {
310
- // FALSE POSITIVE REDUCTION: Skip if annotated as safe
311
272
  if ((0, eslint_devkit_3.hasSafeAnnotation)(xpathArg, context, trustedAnnotations) || hasSafeAnnotationOnStatement(node)) {
312
273
  return;
313
274
  }
@@ -322,10 +283,8 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
322
283
  }
323
284
  }
324
285
  else if (xpathArg.type === 'Identifier') {
325
- // Check if XPath comes from untrusted input
326
286
  if (isUntrustedXpathInput(xpathArg) && !isXpathInputValidated(xpathArg) &&
327
287
  !(xpathArg.type === 'Identifier' && validatedVariables.has(xpathArg.name))) {
328
- // FALSE POSITIVE REDUCTION
329
288
  if ((0, eslint_devkit_3.hasSafeAnnotation)(xpathArg, context, trustedAnnotations) || safetyChecker.isSafe(xpathArg, context) || hasSafeAnnotationOnStatement(node)) {
330
289
  return;
331
290
  }
@@ -340,43 +299,32 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
340
299
  }
341
300
  }
342
301
  },
343
- // Check template literals for XPath expressions
344
302
  TemplateLiteral(node) {
345
303
  const fullText = sourceCode.getText(node);
346
- // Skip common non-XPath patterns
347
- // URLs and API endpoints
348
304
  if (/https?:\/\//.test(fullText) || /^[`'"]\s*\/api\//.test(fullText)) {
349
305
  return;
350
306
  }
351
- // File paths (start with / or contain common path patterns)
352
307
  if (/^[`'"]\s*\/home\//.test(fullText) || /^[`'"]\s*\/usr\//.test(fullText) || /^[`'"]\s*\/tmp\//.test(fullText)) {
353
308
  return;
354
309
  }
355
- // CSS selectors
356
310
  if (/\[data-[\w-]+/.test(fullText) || /\[class=/.test(fullText) || /\[id=/.test(fullText)) {
357
311
  return;
358
312
  }
359
- // Search/query strings
360
313
  if (/\?.*=/.test(fullText) && !/\[@/.test(fullText)) {
361
314
  return;
362
315
  }
363
- // Check if this looks like an ACTUAL XPath expression
364
- // Must have XPath-specific syntax, not just forward slashes
365
- const hasXpathSyntax = /\/\/\w+/.test(fullText) || // //element
366
- /\[@\w+/.test(fullText) || // [@attr
367
- /\[contains\(/.test(fullText) || // [contains(
368
- /\[text\(\)/.test(fullText) || // [text()
369
- /\/child::/.test(fullText) || // /child::
370
- /\/descendant::/.test(fullText); // /descendant::
316
+ const hasXpathSyntax = /\/\/\w+/.test(fullText) ||
317
+ /\[@\w+/.test(fullText) ||
318
+ /\[contains\(/.test(fullText) ||
319
+ /\[text\(\)/.test(fullText) ||
320
+ /\/child::/.test(fullText) ||
321
+ /\/descendant::/.test(fullText);
371
322
  if (!hasXpathSyntax) {
372
323
  return;
373
324
  }
374
- // Check for interpolation in XPath-like expressions
375
325
  if (containsXpathInterpolation(fullText)) {
376
- // Check if any interpolated values are untrusted
377
326
  const hasUntrustedInterpolation = node.expressions.some((expr) => isUntrustedXpathInput(expr) && !isXpathInputValidated(expr) && !(expr.type === 'Identifier' && validatedVariables.has(expr.name)));
378
327
  if (hasUntrustedInterpolation) {
379
- // FALSE POSITIVE REDUCTION: Check for safe annotation
380
328
  if (hasSafeAnnotationOnStatement(node)) {
381
329
  return;
382
330
  }
@@ -396,9 +344,7 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
396
344
  });
397
345
  }
398
346
  }
399
- // Check for dangerous patterns in template literals
400
347
  if (containsDangerousXpath(fullText)) {
401
- // FALSE POSITIVE REDUCTION: Check for safe annotation
402
348
  if (hasSafeAnnotationOnStatement(node)) {
403
349
  return;
404
350
  }
@@ -412,21 +358,17 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
412
358
  });
413
359
  }
414
360
  },
415
- // Check binary expressions (string concatenation)
416
361
  BinaryExpression(node) {
417
362
  if (node.operator !== '+') {
418
363
  return;
419
364
  }
420
365
  const fullText = sourceCode.getText(node);
421
- // Check if this looks like XPath construction
422
366
  if (!fullText.includes('/') && !fullText.includes('[')) {
423
367
  return;
424
368
  }
425
- // Check if untrusted input is involved
426
369
  const leftUntrusted = isUntrustedXpathInput(node.left) && !isXpathInputValidated(node.left) && !(node.left.type === 'Identifier' && validatedVariables.has(node.left.name));
427
370
  const rightUntrusted = isUntrustedXpathInput(node.right) && !isXpathInputValidated(node.right) && !(node.right.type === 'Identifier' && validatedVariables.has(node.right.name));
428
371
  if (leftUntrusted || rightUntrusted) {
429
- // FALSE POSITIVE REDUCTION
430
372
  if (safetyChecker.isSafe(node, context) || hasSafeAnnotationOnStatement(node)) {
431
373
  return;
432
374
  }
@@ -442,13 +384,11 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
442
384
  });
443
385
  }
444
386
  },
445
- // Check variable assignments with XPath expressions
446
387
  VariableDeclarator(node) {
447
388
  if (!node.init || node.id.type !== 'Identifier') {
448
389
  return;
449
390
  }
450
391
  const varName = node.id.name;
451
- // Track variables that are assigned the result of sanitization functions
452
392
  if (node.init.type === 'CallExpression' &&
453
393
  node.init.callee.type === 'Identifier' &&
454
394
  (xpathValidationFunctions.includes(node.init.callee.name) || trustedSanitizers.includes(node.init.callee.name))) {
@@ -458,10 +398,8 @@ exports.noXpathInjection = (0, eslint_devkit_1.createRule)({
458
398
  if (!varNameLower.includes('xpath') && !varNameLower.includes('query') && !varNameLower.includes('path')) {
459
399
  return;
460
400
  }
461
- // Check if assigned value contains dangerous XPath
462
401
  if (node.init.type === 'Literal' && typeof node.init.value === 'string') {
463
402
  if (containsDangerousXpath(node.init.value)) {
464
- // FALSE POSITIVE REDUCTION
465
403
  if (safetyChecker.isSafe(node.init, context) || hasSafeAnnotationOnStatement(node)) {
466
404
  return;
467
405
  }