eslint-plugin-secure-coding 3.1.3 → 3.3.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/README.md +128 -65
  3. package/package.json +23 -4
  4. package/src/index.js +70 -12
  5. package/src/oxlint.d.ts +20 -0
  6. package/src/oxlint.js +21 -0
  7. package/src/rules/detect-non-literal-regexp/index.js +9 -1
  8. package/src/rules/detect-object-injection/index.js +344 -6
  9. package/src/rules/detect-weak-password-validation/index.js +4 -1
  10. package/src/rules/no-directive-injection/index.js +7 -4
  11. package/src/rules/no-electron-security-issues/index.js +6 -2
  12. package/src/rules/no-format-string-injection/index.js +32 -23
  13. package/src/rules/no-graphql-injection/index.js +8 -3
  14. package/src/rules/no-hardcoded-credentials/index.js +366 -52
  15. package/src/rules/no-hardcoded-session-tokens/index.js +3 -0
  16. package/src/rules/no-improper-sanitization/index.js +31 -4
  17. package/src/rules/no-improper-type-validation/index.js +6 -4
  18. package/src/rules/no-insecure-comparison/index.js +39 -3
  19. package/src/rules/no-ldap-injection/index.js +6 -3
  20. package/src/rules/no-missing-authentication/index.js +5 -2
  21. package/src/rules/no-pii-in-logs/index.js +4 -1
  22. package/src/rules/no-privilege-escalation/index.js +5 -2
  23. package/src/rules/no-redos-vulnerable-regex/index.js +79 -0
  24. package/src/rules/no-sensitive-data-exposure/index.js +4 -1
  25. package/src/rules/no-template-injection/index.d.ts +23 -0
  26. package/src/rules/no-template-injection/index.js +90 -0
  27. package/src/rules/no-unchecked-loop-condition/index.js +5 -3
  28. package/src/rules/no-unlimited-resource-allocation/index.js +46 -30
  29. package/src/rules/no-unsafe-deserialization/index.js +22 -5
  30. package/src/rules/no-unsafe-regex-construction/index.js +10 -3
  31. package/src/rules/no-weak-password-recovery/index.js +5 -3
  32. package/src/rules/no-xpath-injection/index.js +6 -3
  33. package/src/rules/no-xxe-injection/index.js +48 -46
  34. package/src/rules/require-backend-authorization/index.js +6 -3
  35. package/src/rules/require-secure-defaults/index.js +3 -0
@@ -27,71 +27,97 @@ const CREDENTIAL_PATTERNS = {
27
27
  // Secret keys (base64-like or hex strings)
28
28
  secretKey: /^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/,
29
29
  };
30
- // Note: CREDENTIAL_VARIABLE_NAMES is reserved for future use when we want to
31
- // check variable names in addition to values
32
- // @coverage-note: Not currently used, reserved for future enhancement
33
30
  /**
34
- * Check if a string literal looks like a hardcoded credential
31
+ * Identifier names that imply the surrounding string is a credential.
32
+ * Used to require a *credential-typed* context for ambiguous regex matches
33
+ * (generic 32+-char alphanumeric, common passwords) — without this gate the
34
+ * rule fires on TS union-type literals, error class names, and test prompts
35
+ * (verified on vercel/ai: 807 ours-only findings, top samples are
36
+ * `'experimental_onToolExecutionStart'`, `'AI_ToolCallNotFoundForApprovalError'`,
37
+ * `'test'`).
38
+ */
39
+ const CREDENTIAL_VARIABLE_NAMES = new Set([
40
+ 'apikey', 'api_key', 'apiKey',
41
+ 'secret', 'secretkey', 'secret_key', 'secretKey', 'clientsecret', 'client_secret', 'clientSecret',
42
+ 'token', 'authtoken', 'auth_token', 'authToken', 'accesstoken', 'access_token', 'accessToken',
43
+ 'refreshtoken', 'refresh_token', 'refreshToken', 'idtoken', 'id_token', 'idToken',
44
+ 'password', 'passwd', 'pass', 'pwd',
45
+ 'privatekey', 'private_key', 'privateKey',
46
+ 'credentials', 'creds',
47
+ 'authorization', 'auth',
48
+ 'connectionstring', 'connection_string', 'connectionString', 'connectionuri', 'connectionURI',
49
+ 'dburl', 'db_url', 'dbUrl', 'databaseurl', 'database_url', 'databaseUrl',
50
+ ]);
51
+ /**
52
+ * Check if a string literal looks like a hardcoded credential.
53
+ * Returns `confidence: 'ambiguous'` when only a permissive pattern matched —
54
+ * the caller MUST verify the surrounding identifier is credential-named.
35
55
  */
36
56
  function looksLikeCredential(value, options, ignorePatterns) {
57
+ const NONE = { isCredential: false, type: '', confidence: 'ambiguous' };
37
58
  // Check ignore patterns first
38
- if (ignorePatterns.some(pattern => pattern.test(value))) {
39
- return { isCredential: false, type: '' };
40
- }
41
- // Check custom patterns first (highest priority)
59
+ if (ignorePatterns.some(pattern => pattern.test(value)))
60
+ return NONE;
61
+ // Custom patterns are user-defined → trust them, treat as structural
42
62
  for (const customPattern of options.customPatterns) {
43
63
  try {
44
64
  const regex = new RegExp(customPattern.pattern);
45
65
  if (regex.test(value)) {
46
- return { isCredential: true, type: customPattern.type };
66
+ return { isCredential: true, type: customPattern.type, confidence: 'structural' };
47
67
  }
48
68
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
49
69
  }
50
70
  catch (error) {
51
- // Invalid regex pattern, skip it
52
71
  continue;
53
72
  }
54
73
  }
55
- // Check passwords (common weak passwords) - no length requirement, check first
56
- if (options.detectPasswords) {
57
- if (CREDENTIAL_PATTERNS.commonPassword.test(value)) {
58
- return { isCredential: true, type: 'Common password' };
59
- }
74
+ // Common-password keyword match — AMBIGUOUS. Strings like "test", "admin",
75
+ // "guest" appear in test fixtures, error messages, and identifiers all the
76
+ // time. The caller must verify a credential-named context.
77
+ if (options.detectPasswords && CREDENTIAL_PATTERNS.commonPassword.test(value)) {
78
+ return { isCredential: true, type: 'Common password', confidence: 'ambiguous' };
60
79
  }
61
- // Check database connection strings - no length requirement
62
- if (options.detectDatabaseStrings) {
63
- if (CREDENTIAL_PATTERNS.databaseString.test(value)) {
64
- return { isCredential: true, type: 'Database connection string' };
65
- }
80
+ // Structural: DB connection strings have unambiguous shape
81
+ // `protocol://user:pass@host` — no FP risk.
82
+ if (options.detectDatabaseStrings && CREDENTIAL_PATTERNS.databaseString.test(value)) {
83
+ return { isCredential: true, type: 'Database connection string', confidence: 'structural' };
66
84
  }
67
- // Check minimum length for other patterns
68
- if (value.length < options.minLength) {
69
- return { isCredential: false, type: '' };
85
+ if (value.length < options.minLength)
86
+ return NONE;
87
+ // Structural: JWT format (3 base64 parts dot-separated)
88
+ if (options.detectTokens && CREDENTIAL_PATTERNS.jwtToken.test(value)) {
89
+ return { isCredential: true, type: 'JWT token', confidence: 'structural' };
70
90
  }
71
- // Check tokens first (more specific patterns)
72
- if (options.detectTokens) {
73
- if (CREDENTIAL_PATTERNS.jwtToken.test(value)) {
74
- return { isCredential: true, type: 'JWT token' };
75
- }
76
- if (CREDENTIAL_PATTERNS.oauthToken.test(value)) {
77
- return { isCredential: true, type: 'OAuth token' };
78
- }
91
+ // Structural: OAuth tokens have provider prefixes (ghp_, gho_, ...)
92
+ if (options.detectTokens && CREDENTIAL_PATTERNS.oauthToken.test(value)) {
93
+ return { isCredential: true, type: 'OAuth token', confidence: 'structural' };
79
94
  }
80
- // Check secret keys first (before generic API key patterns)
95
+ // Secret keys (base64/hex 32+) — context-required. Long base64 / hex
96
+ // strings appear in source maps, generated IDs, hash digests; without
97
+ // a credential-named context they're FPs.
81
98
  if (value.length >= 32 && CREDENTIAL_PATTERNS.secretKey.test(value)) {
82
- return { isCredential: true, type: 'Secret key' };
99
+ return { isCredential: true, type: 'Secret key', confidence: 'ambiguous' };
83
100
  }
84
- // Check API keys
85
- if (options.detectApiKeys) {
86
- if (CREDENTIAL_PATTERNS.awsAccessKey.test(value)) {
87
- return { isCredential: true, type: 'AWS access key' };
88
- }
89
- // Generic API key pattern (long alphanumeric strings)
90
- if (/^[A-Za-z0-9_-]{32,}$/.test(value)) {
91
- return { isCredential: true, type: 'API key' };
92
- }
101
+ // Structural: AWS access key has a fixed prefix
102
+ if (options.detectApiKeys && CREDENTIAL_PATTERNS.awsAccessKey.test(value)) {
103
+ return { isCredential: true, type: 'AWS access key', confidence: 'structural' };
93
104
  }
94
- return { isCredential: false, type: '' };
105
+ // Structural: Stripe-style keys (sk_live_, sk_test_, pk_live_, pk_test_,
106
+ // rk_live_, rk_test_) are unambiguous — the prefix is registered to
107
+ // Stripe and never appears in unrelated contexts. Type label is kept
108
+ // as the generic 'API key' to match existing test expectations and
109
+ // ensure the suggestion templates remain stable for callers.
110
+ if (options.detectApiKeys &&
111
+ /^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)) {
112
+ return { isCredential: true, type: 'API key', confidence: 'structural' };
113
+ }
114
+ // Generic 32+-char alphanumeric — AMBIGUOUS. This is the FP source on
115
+ // vercel/ai's TS union types and error class names. Caller must verify
116
+ // a credential-named context.
117
+ if (options.detectApiKeys && /^[A-Za-z0-9_-]{32,}$/.test(value)) {
118
+ return { isCredential: true, type: 'API key', confidence: 'ambiguous' };
119
+ }
120
+ return NONE;
95
121
  }
96
122
  // Note: isCredentialVariableName is reserved for future use when we want to
97
123
  // check variable names in addition to values
@@ -101,7 +127,11 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
101
127
  meta: {
102
128
  type: 'problem',
103
129
  docs: {
130
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md',
104
131
  description: 'Detects hardcoded passwords, API keys, tokens, and other sensitive credentials',
132
+ cwe: 'CWE-798',
133
+ cvss: 9.5,
134
+ confidence: 'medium',
105
135
  },
106
136
  fixable: 'code',
107
137
  hasSuggestions: true,
@@ -245,11 +275,17 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
245
275
  create(context) {
246
276
  const options = context.options[0] || {};
247
277
  const { ignorePatterns = [], allowInTests = false, minLength = 8, detectApiKeys = true, detectPasswords = true, detectTokens = true, detectDatabaseStrings = true, customPatterns = [], } = options || {};
248
- const filename = context.filename || context.getFilename();
278
+ const filename = context.filename;
249
279
  const isTestFile = allowInTests && (filename.includes('.test.') ||
250
280
  filename.includes('.spec.') ||
281
+ filename.includes('.fixture.') ||
282
+ filename.includes('.mock.') ||
251
283
  filename.includes('__tests__') ||
252
- filename.includes('/test/'));
284
+ filename.includes('__mocks__') ||
285
+ filename.includes('/test/') ||
286
+ filename.includes('/tests/') ||
287
+ filename.includes('/fixtures/') ||
288
+ filename.includes('/mocks/'));
253
289
  // Compile ignore patterns to regex
254
290
  const compiledIgnorePatterns = ignorePatterns.map((pattern) => new RegExp(pattern));
255
291
  const detectionOptions = {
@@ -260,6 +296,225 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
260
296
  detectDatabaseStrings,
261
297
  customPatterns,
262
298
  };
299
+ /**
300
+ * Variable / property names that hold UI labels and HTML attribute
301
+ * values, not secrets. When a literal containing the word "password"
302
+ * (or other credential-like text) lives in one of these contexts, it's
303
+ * a label or form-field metadata, not a hardcoded credential.
304
+ */
305
+ const LABEL_CONTEXT_NAMES = new Set([
306
+ // HTML form attributes
307
+ 'type', 'name', 'id', 'placeholder', 'label', 'title', 'role',
308
+ 'autocomplete', 'autoFocus', 'autocapitalize', 'inputmode',
309
+ // ARIA
310
+ 'aria-label', 'aria-labelledby', 'aria-describedby',
311
+ // Common semantic UI fields
312
+ 'fieldName', 'fieldType', 'fieldLabel', 'inputType', 'inputName',
313
+ 'displayName', 'columnName', 'paramName',
314
+ // i18n keys / translation lookup. NOTE: bare `'key'` is intentionally
315
+ // omitted — `const key = '...'` is the canonical name for actual API
316
+ // keys (e.g. AWS, Stripe), so exempting it would mask real secrets.
317
+ // The specific i18n names below cover translation lookups without
318
+ // that false-negative.
319
+ 'i18nKey', 'translationKey', 'messageKey',
320
+ ]);
321
+ /**
322
+ * Returns true if the literal is being used as a UI label or HTML
323
+ * attribute value rather than as a secret. Examples:
324
+ * const label = 'password'; // variable named `label`
325
+ * input.type = 'password'; // assigning to .type
326
+ * input.name = 'userPassword'; // assigning to .name
327
+ * <input type="password" /> // JSX attribute
328
+ * { type: 'password', name: 'pw' } // object literal property
329
+ * setAttribute('placeholder', 'Enter password') // setAttribute call
330
+ */
331
+ function isLabelContext(node, parent) {
332
+ if (!parent)
333
+ return false;
334
+ // Object-literal entries: walk up through the ObjectExpression →
335
+ // its Property → its enclosing VariableDeclarator. Closes the
336
+ // regression where `const labels = { password: 'Enter password' }`
337
+ // was firing because the property key 'password' is in
338
+ // CREDENTIAL_VARIABLE_NAMES even though the surrounding `labels`
339
+ // var indicates the whole object is UI text.
340
+ if (parent.type === 'ObjectExpression') {
341
+ const grand = parent.parent;
342
+ if (grand)
343
+ return isLabelContext(node, grand);
344
+ return false;
345
+ }
346
+ // Array elements: walk up so `const labels = ['Enter password']`
347
+ // is treated as label context if `labels` is label-named.
348
+ if (parent.type === 'ArrayExpression') {
349
+ const grand = parent.parent;
350
+ if (grand)
351
+ return isLabelContext(node, grand);
352
+ return false;
353
+ }
354
+ // const label = 'password' / let label = 'password' / `labels` /
355
+ // any var ending in `label`/`name`/`placeholder`.
356
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
357
+ const n = parent.id.name.toLowerCase();
358
+ if (LABEL_CONTEXT_NAMES.has(n) || n === 'labels' || n.endsWith('label') || n.endsWith('labels') || n.endsWith('name') || n.endsWith('placeholder'))
359
+ return true;
360
+ }
361
+ // input.type = 'password' / input.name = 'userPassword'
362
+ if (parent.type === 'AssignmentExpression' && parent.right === node) {
363
+ const left = parent.left;
364
+ if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
365
+ if (LABEL_CONTEXT_NAMES.has(left.property.name))
366
+ return true;
367
+ }
368
+ }
369
+ // { type: 'password', name: 'foo' } — direct property key is label-typed
370
+ if (parent.type === 'Property' && parent.value === node) {
371
+ const key = parent.key;
372
+ if (key.type === 'Identifier' && LABEL_CONTEXT_NAMES.has(key.name))
373
+ return true;
374
+ if (key.type === 'Literal' && typeof key.value === 'string') {
375
+ if (LABEL_CONTEXT_NAMES.has(key.value))
376
+ return true;
377
+ }
378
+ // Otherwise, walk up: the property may not have a label-typed
379
+ // key but the enclosing variable might be `labels` /
380
+ // `i18nStrings` / `messages` / etc., signalling that the
381
+ // whole object is UI text. Closes the FP regression where
382
+ // `const labels = { password: 'Enter password' }` fired
383
+ // because `password` is in CREDENTIAL_VARIABLE_NAMES.
384
+ const obj = parent.parent;
385
+ if (obj?.type === 'ObjectExpression') {
386
+ const grand = obj.parent;
387
+ if (grand)
388
+ return isLabelContext(node, grand);
389
+ }
390
+ }
391
+ // setAttribute('type', 'password') — second arg is the value
392
+ if (parent.type === 'CallExpression' &&
393
+ parent.callee.type === 'MemberExpression' &&
394
+ parent.callee.property.type === 'Identifier') {
395
+ const callee = parent.callee;
396
+ const methodName = callee.property.name;
397
+ if (methodName === 'setAttribute' || methodName === 'getAttribute') {
398
+ const args = parent.arguments;
399
+ if (args[1] === node)
400
+ return true;
401
+ }
402
+ }
403
+ // JSX: <input type="password" />
404
+ if (parent.type === 'JSXAttribute')
405
+ return true;
406
+ return false;
407
+ }
408
+ /**
409
+ * Map a credential-context to its category so the detection-disable
410
+ * options can gate the context-positive code path. `password` covers
411
+ * password-like names, `token` covers JWT / OAuth / session tokens,
412
+ * `database` covers DB connection strings, `apikey` covers API key /
413
+ * secret-key style names. Anything else falls back to `other`, which
414
+ * the options never gate (e.g. `credentials`, `auth`).
415
+ */
416
+ function inferCredentialTypeFromContext(parent) {
417
+ const name = (() => {
418
+ if (!parent)
419
+ return '';
420
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
421
+ return parent.id.name.toLowerCase();
422
+ }
423
+ if (parent.type === 'Property') {
424
+ const key = parent.key;
425
+ if (key.type === 'Identifier')
426
+ return key.name.toLowerCase();
427
+ if (key.type === 'Literal' && typeof key.value === 'string') {
428
+ return key.value.toLowerCase();
429
+ }
430
+ }
431
+ if (parent.type === 'AssignmentExpression') {
432
+ const left = parent.left;
433
+ if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
434
+ return left.property.name.toLowerCase();
435
+ }
436
+ }
437
+ return '';
438
+ })();
439
+ if (/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))
440
+ return 'password';
441
+ if (/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))
442
+ return 'token';
443
+ if (/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))
444
+ return 'database';
445
+ if (/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))
446
+ return 'apikey';
447
+ return 'other';
448
+ }
449
+ /**
450
+ * Returns true when the string is in a context that names credentials —
451
+ * assigned to a credential-typed variable, property, parameter, or used
452
+ * as the second argument to common credential APIs. Required for
453
+ * ambiguous matches (generic 32+-char alphanumeric, common-password
454
+ * keywords) which would otherwise fire on identifier-shaped literals
455
+ * (TS union types, error class names, test prompts).
456
+ */
457
+ function isCredentialContext(node, parent) {
458
+ if (!parent)
459
+ return false;
460
+ const matches = (name) => {
461
+ const lower = name.toLowerCase();
462
+ // Try the literal name AND its singular form (drop trailing 's')
463
+ // so collections like `tokens`, `apiKeys`, `secrets`, `passwords`
464
+ // are recognised. Closes the audit FN where
465
+ // `const tokens = ['Bearer sk_live_...']` bypassed credential
466
+ // detection because `tokens` (plural) wasn't in the allowlist.
467
+ const singular = lower.endsWith('s') ? lower.slice(0, -1) : lower;
468
+ if (CREDENTIAL_VARIABLE_NAMES.has(lower) || CREDENTIAL_VARIABLE_NAMES.has(singular))
469
+ return true;
470
+ return lower.endsWith('apikey') || lower.endsWith('apikeys') ||
471
+ lower.endsWith('secret') || lower.endsWith('secrets') ||
472
+ lower.endsWith('token') || lower.endsWith('tokens') ||
473
+ lower.endsWith('password') || lower.endsWith('passwords') ||
474
+ lower.endsWith('passwd') || lower.endsWith('credential') ||
475
+ lower.endsWith('credentials');
476
+ };
477
+ // Array elements: walk up through the ArrayExpression to its
478
+ // enclosing variable / property. Closes the audit FN where
479
+ // `const tokens = ['Bearer sk_live_...']` was bypassing the
480
+ // credential-name check because the literal's immediate parent is
481
+ // the ArrayExpression rather than the VariableDeclarator.
482
+ if (parent.type === 'ArrayExpression') {
483
+ const grand = parent.parent;
484
+ if (grand)
485
+ return isCredentialContext(node, grand);
486
+ return false;
487
+ }
488
+ // const apiKey = '...' / let secret = '...'
489
+ if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
490
+ if (matches(parent.id.name))
491
+ return true;
492
+ }
493
+ // obj.apiKey = '...' / this.password = '...'
494
+ if (parent.type === 'AssignmentExpression' &&
495
+ parent.right === node) {
496
+ const left = parent.left;
497
+ if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
498
+ if (matches(left.property.name))
499
+ return true;
500
+ }
501
+ if (left.type === 'Identifier') {
502
+ if (matches(left.name))
503
+ return true;
504
+ }
505
+ }
506
+ // { apiKey: '...', secret: '...' }
507
+ if (parent.type === 'Property' && parent.value === node) {
508
+ const key = parent.key;
509
+ if (key.type === 'Identifier' && matches(key.name))
510
+ return true;
511
+ if (key.type === 'Literal' && typeof key.value === 'string') {
512
+ if (matches(key.value))
513
+ return true;
514
+ }
515
+ }
516
+ return false;
517
+ }
263
518
  /**
264
519
  * Check a string literal node
265
520
  */
@@ -272,9 +527,64 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
272
527
  if (isTestFile) {
273
528
  return;
274
529
  }
530
+ // Skip fallback in `process.env.X || 'value'` — the string is only
531
+ // used when the env var is absent (dev-mode default). The real secret
532
+ // lives in the environment, not the source file.
533
+ if (parent?.type === 'LogicalExpression' &&
534
+ parent.operator === '||' &&
535
+ parent.right === node) {
536
+ const left = parent.left;
537
+ if (left.type === 'MemberExpression' &&
538
+ left.object.type === 'MemberExpression' &&
539
+ left.object.object.type === 'Identifier' &&
540
+ left.object.object.name === 'process' &&
541
+ left.object.property.type === 'Identifier' &&
542
+ left.object.property.name === 'env') {
543
+ return; // safe — fallback to process.env value
544
+ }
545
+ }
546
+ // Skip if used as a UI label / HTML attribute value (form-field name,
547
+ // type tag, ARIA label, i18n key) — these aren't credentials.
548
+ if (isLabelContext(node, parent)) {
549
+ return;
550
+ }
275
551
  // Check if it looks like a credential
276
- const { isCredential, type } = looksLikeCredential(value, detectionOptions, compiledIgnorePatterns);
277
- if (!isCredential) {
552
+ const { isCredential, type, confidence } = looksLikeCredential(value, detectionOptions, compiledIgnorePatterns);
553
+ // Ambiguous matches require a credential-named context to fire.
554
+ // Without this gate the rule reports type literals, error class
555
+ // names, and test prompts as credentials (vercel/ai had 807 such
556
+ // FPs before the gate landed).
557
+ let finalIsCredential = isCredential;
558
+ let finalType = type;
559
+ if (isCredential && confidence === 'ambiguous' && !isCredentialContext(node, parent)) {
560
+ finalIsCredential = false;
561
+ }
562
+ // Context-positive: any non-trivial string assigned to a
563
+ // credential-named variable/property is a credential, even when no
564
+ // regex pattern matches. Catches passwords like 'SuperSecret123!'
565
+ // that don't fit any structural pattern but are clearly secrets
566
+ // by virtue of where they're stored.
567
+ //
568
+ // The detection-disable options (detectApiKeys / detectPasswords /
569
+ // detectTokens / detectDatabaseStrings) MUST gate this path too —
570
+ // otherwise `{ detectPasswords: false }` silently fires on
571
+ // `const password = "..."` because the var-name match alone
572
+ // bypasses the option. Map the var name back to its category and
573
+ // honour the option.
574
+ if (!finalIsCredential && value.length >= detectionOptions.minLength &&
575
+ isCredentialContext(node, parent)) {
576
+ const ctxType = inferCredentialTypeFromContext(parent);
577
+ const optionAllows = (ctxType === 'password' && detectionOptions.detectPasswords) ||
578
+ (ctxType === 'token' && detectionOptions.detectTokens) ||
579
+ (ctxType === 'database' && detectionOptions.detectDatabaseStrings) ||
580
+ (ctxType === 'apikey' && detectionOptions.detectApiKeys) ||
581
+ ctxType === 'other'; // "other" credential names always honoured
582
+ if (optionAllows) {
583
+ finalIsCredential = true;
584
+ finalType = type || 'Credential value';
585
+ }
586
+ }
587
+ if (!finalIsCredential) {
278
588
  return;
279
589
  }
280
590
  // Generate environment variable name suggestion
@@ -297,7 +607,7 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
297
607
  node,
298
608
  messageId: 'useEnvironmentVariable',
299
609
  data: {
300
- credentialType: type,
610
+ credentialType: finalType,
301
611
  envVarName,
302
612
  },
303
613
  suggest: [
@@ -327,8 +637,12 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
327
637
  // Only check if there are no interpolations (static template literal)
328
638
  if (node.expressions.length === 0) {
329
639
  const fullText = node.quasis.map((q) => q.value.raw).join('');
330
- const { isCredential, type } = looksLikeCredential(fullText, detectionOptions, compiledIgnorePatterns);
331
- if (isCredential && !isTestFile) {
640
+ const { isCredential, type, confidence } = looksLikeCredential(fullText, detectionOptions, compiledIgnorePatterns);
641
+ // For template literals we don't have a Literal node to pass to
642
+ // `isCredentialContext`. Skip ambiguous matches entirely — if the
643
+ // user really has a credential in a template literal they should
644
+ // use a regular string anyway.
645
+ if (isCredential && !isTestFile && confidence === 'structural') {
332
646
  context.report({
333
647
  node,
334
648
  messageId: 'useEnvironmentVariable',
@@ -359,8 +673,8 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
359
673
  // For template literals with interpolations, check each quasi part
360
674
  for (const quasi of node.quasis) {
361
675
  if (quasi.value.raw) {
362
- const { isCredential, type } = looksLikeCredential(quasi.value.raw, detectionOptions, compiledIgnorePatterns);
363
- if (isCredential && !isTestFile) {
676
+ const { isCredential, type, confidence } = looksLikeCredential(quasi.value.raw, detectionOptions, compiledIgnorePatterns);
677
+ if (isCredential && !isTestFile && confidence === 'structural') {
364
678
  // Note: Template literals with interpolations are complex to fix automatically
365
679
  // So we report the error without suggestions
366
680
  context.report({
@@ -15,7 +15,10 @@ exports.noHardcodedSessionTokens = (0, eslint_devkit_1.createRule)({
15
15
  meta: {
16
16
  type: 'problem',
17
17
  docs: {
18
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-session-tokens.md',
18
19
  description: 'Detect hardcoded session/JWT tokens',
20
+ cwe: 'CWE-798',
21
+ cvss: 9.5,
19
22
  },
20
23
  messages: {
21
24
  violationDetected: (0, eslint_devkit_1.formatLLMMessage)({
@@ -14,9 +14,10 @@ exports.noImproperSanitization = (0, eslint_devkit_1.createRule)({
14
14
  meta: {
15
15
  type: 'problem',
16
16
  docs: {
17
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-sanitization.md',
17
18
  description: 'Detects improper sanitization of user input',
19
+ cwe: 'CWE-116',
18
20
  },
19
- fixable: 'code',
20
21
  hasSuggestions: true,
21
22
  messages: {
22
23
  improperSanitization: (0, eslint_devkit_2.formatLLMMessage)({
@@ -200,8 +201,8 @@ exports.noImproperSanitization = (0, eslint_devkit_1.createRule)({
200
201
  create(context) {
201
202
  const options = context.options[0] || {};
202
203
  const { safeSanitizers = ['DOMPurify.sanitize', 'he.encode', 'encodeURIComponent', 'encodeURI', 'escape'], dangerousChars = ['<', '>', '"', "'", '&', '`', '$', '{', '}', '|', ';', '(', ')'], trustedSanitizers = [], trustedAnnotations = [], strictMode = false, } = options;
203
- const sourceCode = context.sourceCode || context.sourceCode;
204
- const filename = context.filename || context.getFilename();
204
+ const sourceCode = context.sourceCode;
205
+ const filename = context.filename;
205
206
  // Create safety checker for false positive detection
206
207
  const safetyChecker = (0, eslint_devkit_3.createSafetyChecker)({
207
208
  trustedSanitizers,
@@ -362,11 +363,37 @@ exports.noImproperSanitization = (0, eslint_devkit_1.createRule)({
362
363
  if (typeof node.value !== 'string') {
363
364
  return;
364
365
  }
366
+ // SAFE: literal assigned directly to innerHTML/outerHTML with no
367
+ // concatenation or interpolation AND containing no dangerous
368
+ // markup. Static developer-authored HTML normally has no taint
369
+ // source (`el.innerHTML = '<span class="x"></span>'` is the
370
+ // standard way to set static markup; flagging it would force
371
+ // every static UI template into the noise floor) — BUT a literal
372
+ // like `<script>alert(1)</script>` is unsafe even when
373
+ // developer-authored, because the markup itself is the vector.
374
+ // Only take the safe path when the literal is free of script
375
+ // tags, inline event handlers, and `javascript:` URIs.
376
+ const directParent = node.parent;
377
+ if (directParent?.type === 'AssignmentExpression' &&
378
+ directParent.right === node &&
379
+ directParent.left.type === 'MemberExpression') {
380
+ const left = directParent.left;
381
+ if (left.property.type === 'Identifier' &&
382
+ ['innerHTML', 'outerHTML'].includes(left.property.name)) {
383
+ const literalValue = typeof node.value === 'string' ? node.value : '';
384
+ const hasDangerousMarkup = /<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(literalValue);
385
+ if (!hasDangerousMarkup) {
386
+ return;
387
+ }
388
+ }
389
+ }
365
390
  const text = node.value;
366
391
  // Check if this string is used in a dangerous context
367
392
  let current = node;
368
393
  let isInDangerousContext = false;
369
- while (current && !isInDangerousContext) {
394
+ // Every path that sets `isInDangerousContext = true` is followed by `break`,
395
+ // so the negation in the condition is dead (CodeQL: `js/useless-conditional`).
396
+ while (current) {
370
397
  if (current.type === 'AssignmentExpression') {
371
398
  const left = current.left;
372
399
  if (left.type === 'MemberExpression' &&
@@ -14,9 +14,10 @@ exports.noImproperTypeValidation = (0, eslint_devkit_1.createRule)({
14
14
  meta: {
15
15
  type: 'problem',
16
16
  docs: {
17
+ url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-type-validation.md',
17
18
  description: 'Detects improper type validation in user input handling',
19
+ cwe: 'CWE-1287',
18
20
  },
19
- fixable: 'code',
20
21
  hasSuggestions: true,
21
22
  messages: {
22
23
  improperTypeValidation: (0, eslint_devkit_2.formatLLMMessage)({
@@ -185,8 +186,8 @@ exports.noImproperTypeValidation = (0, eslint_devkit_1.createRule)({
185
186
  create(context) {
186
187
  const options = context.options[0] || {};
187
188
  const { userInputVariables = ['req', 'request', 'body', 'query', 'params', 'input', 'data', 'userInput'], allowInstanceofSameRealm = true, trustedSanitizers = [], trustedAnnotations = [], strictMode = false, } = options;
188
- const sourceCode = context.sourceCode || context.sourceCode;
189
- const filename = context.filename || context.getFilename();
189
+ const sourceCode = context.sourceCode;
190
+ const filename = context.filename;
190
191
  // Create safety checker for false positive detection
191
192
  const safetyChecker = (0, eslint_devkit_3.createSafetyChecker)({
192
193
  trustedSanitizers,
@@ -274,6 +275,7 @@ exports.noImproperTypeValidation = (0, eslint_devkit_1.createRule)({
274
275
  /**
275
276
  * Check for unreliable constructor checks
276
277
  */
278
+ // oxlint-disable-next-line consistent-function-scoping
277
279
  const isUnreliableConstructorCheck = (node) => {
278
280
  return node.property.type === 'Identifier' &&
279
281
  node.property.name === 'name' &&
@@ -365,7 +367,7 @@ exports.noImproperTypeValidation = (0, eslint_devkit_1.createRule)({
365
367
  let current = node;
366
368
  let involvesUserInput = false;
367
369
  // Walk up to find if this is used with user input
368
- while (current.parent) {
370
+ while (current?.parent) {
369
371
  current = current.parent;
370
372
  if (current.type === 'VariableDeclarator' &&
371
373
  current.init === node) {