eslint-plugin-secure-coding 3.4.0 → 3.4.1

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 (64) hide show
  1. package/package.json +5 -18
  2. package/src/index.d.ts +17 -23
  3. package/src/index.js +2 -131
  4. package/src/oxlint.d.ts +17 -20
  5. package/src/oxlint.js +0 -18
  6. package/src/rules/detect-non-literal-regexp/index.js +5 -79
  7. package/src/rules/detect-object-injection/index.js +2 -221
  8. package/src/rules/detect-weak-password-validation/index.js +0 -12
  9. package/src/rules/no-directive-injection/index.js +0 -33
  10. package/src/rules/no-electron-security-issues/index.js +0 -41
  11. package/src/rules/no-format-string-injection/index.js +0 -82
  12. package/src/rules/no-graphql-injection/index.js +8 -133
  13. package/src/rules/no-hardcoded-credentials/index.js +3 -297
  14. package/src/rules/no-hardcoded-session-tokens/index.js +0 -11
  15. package/src/rules/no-improper-sanitization/index.js +0 -44
  16. package/src/rules/no-improper-type-validation/index.js +1 -51
  17. package/src/rules/no-insecure-comparison/index.js +2 -43
  18. package/src/rules/no-ldap-injection/index.js +8 -61
  19. package/src/rules/no-missing-authentication/index.js +2 -56
  20. package/src/rules/no-pii-in-logs/index.js +0 -13
  21. package/src/rules/no-privilege-escalation/index.js +2 -49
  22. package/src/rules/no-redos-vulnerable-regex/index.js +3 -49
  23. package/src/rules/no-sensitive-data-exposure/index.js +5 -29
  24. package/src/rules/no-template-injection/index.js +0 -6
  25. package/src/rules/no-unchecked-loop-condition/index.js +3 -99
  26. package/src/rules/no-unlimited-resource-allocation/index.js +2 -75
  27. package/src/rules/no-unsafe-deserialization/index.js +1 -111
  28. package/src/rules/no-unsafe-regex-construction/index.js +22 -62
  29. package/src/rules/no-weak-password-recovery/index.js +0 -43
  30. package/src/rules/no-xpath-injection/index.js +13 -75
  31. package/src/rules/no-xxe-injection/index.js +1 -47
  32. package/src/rules/require-backend-authorization/index.js +0 -10
  33. package/src/rules/require-secure-defaults/index.js +0 -10
  34. package/src/types/index.js +0 -5
  35. package/AGENTS.md +0 -131
  36. package/CHANGELOG.md +0 -379
  37. package/src/rules/detect-non-literal-regexp/index.d.ts +0 -28
  38. package/src/rules/detect-object-injection/index.d.ts +0 -35
  39. package/src/rules/detect-weak-password-validation/index.d.ts +0 -12
  40. package/src/rules/no-directive-injection/index.d.ts +0 -38
  41. package/src/rules/no-electron-security-issues/index.d.ts +0 -36
  42. package/src/rules/no-format-string-injection/index.d.ts +0 -44
  43. package/src/rules/no-graphql-injection/index.d.ts +0 -47
  44. package/src/rules/no-hardcoded-credentials/index.d.ts +0 -95
  45. package/src/rules/no-hardcoded-session-tokens/index.d.ts +0 -12
  46. package/src/rules/no-improper-sanitization/index.d.ts +0 -38
  47. package/src/rules/no-improper-type-validation/index.d.ts +0 -36
  48. package/src/rules/no-insecure-comparison/index.d.ts +0 -26
  49. package/src/rules/no-ldap-injection/index.d.ts +0 -53
  50. package/src/rules/no-missing-authentication/index.d.ts +0 -32
  51. package/src/rules/no-pii-in-logs/index.d.ts +0 -12
  52. package/src/rules/no-privilege-escalation/index.d.ts +0 -32
  53. package/src/rules/no-redos-vulnerable-regex/index.d.ts +0 -28
  54. package/src/rules/no-sensitive-data-exposure/index.d.ts +0 -30
  55. package/src/rules/no-template-injection/index.d.ts +0 -23
  56. package/src/rules/no-unchecked-loop-condition/index.d.ts +0 -38
  57. package/src/rules/no-unlimited-resource-allocation/index.d.ts +0 -38
  58. package/src/rules/no-unsafe-deserialization/index.d.ts +0 -40
  59. package/src/rules/no-unsafe-regex-construction/index.d.ts +0 -30
  60. package/src/rules/no-weak-password-recovery/index.d.ts +0 -38
  61. package/src/rules/no-xpath-injection/index.d.ts +0 -39
  62. package/src/rules/no-xxe-injection/index.d.ts +0 -36
  63. package/src/rules/require-backend-authorization/index.d.ts +0 -12
  64. package/src/rules/require-secure-defaults/index.d.ts +0 -12
@@ -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.noHardcodedCredentials = void 0;
9
4
  exports.isNaturalWordString = isNaturalWordString;
@@ -12,34 +7,15 @@ exports.isSecretShaped = isSecretShaped;
12
7
  exports.isPlaceholderValue = isPlaceholderValue;
13
8
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
14
9
  const eslint_devkit_2 = require("@interlace/eslint-devkit");
15
- /**
16
- * Common credential patterns
17
- */
18
10
  const CREDENTIAL_PATTERNS = {
19
- // API Keys (typically 32+ character alphanumeric strings)
20
11
  apiKey: /^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,
21
- // JWT Tokens (three base64 parts separated by dots)
22
12
  jwtToken: /^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,
23
- // OAuth tokens
24
13
  oauthToken: /^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,
25
- // AWS Access Keys
26
14
  awsAccessKey: /^AKIA[0-9A-Z]{16}$/,
27
- // Database connection strings with credentials
28
15
  databaseString: /^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,
29
- // Generic password patterns (common weak passwords) - no length requirement
30
16
  commonPassword: /^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,
31
- // Secret keys (base64-like or hex strings)
32
17
  secretKey: /^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/,
33
18
  };
34
- /**
35
- * Identifier names that imply the surrounding string is a credential.
36
- * Used to require a *credential-typed* context for ambiguous regex matches
37
- * (generic 32+-char alphanumeric, common passwords) — without this gate the
38
- * rule fires on TS union-type literals, error class names, and test prompts
39
- * (verified on vercel/ai: 807 ours-only findings, top samples are
40
- * `'experimental_onToolExecutionStart'`, `'AI_ToolCallNotFoundForApprovalError'`,
41
- * `'test'`).
42
- */
43
19
  const CREDENTIAL_VARIABLE_NAMES = new Set([
44
20
  'apikey', 'api_key', 'apiKey',
45
21
  'secret', 'secretkey', 'secret_key', 'secretKey', 'clientsecret', 'client_secret', 'clientSecret',
@@ -52,24 +28,7 @@ const CREDENTIAL_VARIABLE_NAMES = new Set([
52
28
  'connectionstring', 'connection_string', 'connectionString', 'connectionuri', 'connectionURI',
53
29
  'dburl', 'db_url', 'dbUrl', 'databaseurl', 'database_url', 'databaseUrl',
54
30
  ]);
55
- /**
56
- * ---------------------------------------------------------------------------
57
- * VALUE-SHAPE HEURISTICS
58
- * ---------------------------------------------------------------------------
59
- * The rule decides on the *value*, never on the key name alone. A
60
- * credential-shaped name (`password`, `apiKey`, `secret`) is treated as a
61
- * necessary-but-not-sufficient signal: it can promote an ambiguous value, but
62
- * it can never make a message constant into a finding.
63
- *
64
- * This exists because name-only matching produced a 50% false-positive rate on
65
- * a 1,470-file corpus (webpack, lodash, eslint-plugin-import, two NestJS
66
- * boilerplates): 5 of 10 findings were i18n error constants such as
67
- * `errors: { password: 'incorrectPassword' }`, while the genuine 50-character
68
- * committed API secret in the same corpus was found by *shape*, not name.
69
- */
70
- /** Characters that join words inside an identifier-like string. */
71
31
  const WORD_SEPARATORS = new Set(['_', '-', '.', ' ']);
72
- /** Shannon entropy in bits per character. */
73
32
  function shannonEntropy(value) {
74
33
  const freq = new Map();
75
34
  for (const ch of value)
@@ -81,14 +40,6 @@ function shannonEntropy(value) {
81
40
  }
82
41
  return entropy;
83
42
  }
84
- /**
85
- * Classify the characters present in a string. Word separators (`_ - . ` and
86
- * space) are deliberately NOT counted as symbols — `snake_case_names` and
87
- * `kebab-case-names` are identifiers, not passwords.
88
- *
89
- * Callers reject whitespace-bearing strings before reaching here, so no
90
- * whitespace class is tracked.
91
- */
92
43
  function charClasses(value) {
93
44
  const classes = { lower: false, upper: false, digit: false, symbol: false };
94
45
  for (const ch of value) {
@@ -108,7 +59,6 @@ function charClasses(value) {
108
59
  function classCount(classes) {
109
60
  return Number(classes.lower) + Number(classes.upper) + Number(classes.digit) + Number(classes.symbol);
110
61
  }
111
- /** A token is "pronounceable" if it has a vowel and no long consonant run. */
112
62
  function isPronounceable(token) {
113
63
  const lower = token.toLowerCase();
114
64
  if (!/[aeiouy]/.test(lower))
@@ -117,18 +67,6 @@ function isPronounceable(token) {
117
67
  return false;
118
68
  return true;
119
69
  }
120
- /**
121
- * True when the string is made purely of dictionary-ish words joined by word
122
- * separators or camelCase — i.e. an identifier, an i18n key, or an error
123
- * message constant. No digits, no symbols, every ≥3-character token
124
- * pronounceable.
125
- *
126
- * `incorrectPassword` → true (the corpus false positive)
127
- * `SessionCacheProvider` → true
128
- * `experimental_onToolExecutionStart` → true
129
- * `aaAA@123` → false (symbols + digits)
130
- * `qbp7LmCxYUTHFwKvHnxGW1aTyjSNU6ytN21etK89MaP2Dj2KZP` → false (digits)
131
- */
132
70
  function isNaturalWordString(value) {
133
71
  if (!/^[A-Za-z][A-Za-z_\-. ]*$/.test(value))
134
72
  return false;
@@ -141,14 +79,6 @@ function isNaturalWordString(value) {
141
79
  return false;
142
80
  return meaningful.every(isPronounceable);
143
81
  }
144
- /**
145
- * True when the string contains a monotonically ascending run of `min`
146
- * characters (`abcdef`, `012345`). Charset constants — the alphabets that
147
- * random-string generators and hash encoders declare inline — have maximal
148
- * entropy while being the opposite of a secret. webpack's
149
- * `lib/util/hash/hash-digest.js` and ack-nestjs-boilerplate's
150
- * `helper.service.ts` each declare several.
151
- */
152
82
  function hasSequentialRun(value, min = 5) {
153
83
  let run = 1;
154
84
  for (let i = 1; i < value.length; i++) {
@@ -158,18 +88,6 @@ function hasSequentialRun(value, min = 5) {
158
88
  }
159
89
  return false;
160
90
  }
161
- /**
162
- * High-confidence random blob: a contiguous alphanumeric token, mixed case,
163
- * containing digits, high per-character entropy, and not a charset constant.
164
- * That is the shape of a real committed API secret.
165
- *
166
- * The charset is deliberately strict (`[A-Za-z0-9]` only). Every non-secret
167
- * that reached this tier on the corpus failed exactly here: generated-code
168
- * strings (`installedChunkData[1](error);`), comma-separated keyword lists,
169
- * and Postgres constraint names (`PK_b36bcfe02fc8de3c57a8b2391c2`) all carry
170
- * punctuation that no API key does. JWTs and dotted identifiers are excluded
171
- * for the same reason and handled by their own, more specific tier.
172
- */
173
91
  function looksRandom(value) {
174
92
  if (value.length < 20)
175
93
  return false;
@@ -182,71 +100,31 @@ function looksRandom(value) {
182
100
  return false;
183
101
  return shannonEntropy(value) >= 3.5;
184
102
  }
185
- /**
186
- * Length at which a random-looking blob is reported with NO naming context.
187
- * Below it the shape is still required, but so is a credential-named slot:
188
- * `CreateUser1715028537217` (a TypeORM migration class name, 23 chars) passes
189
- * every shape test there is, and only the absence of a credential-named slot
190
- * separates it from a 25-character API key.
191
- */
192
103
  const CONTEXT_FREE_RANDOM_LENGTH = 32;
193
- /**
194
- * Shape gate for the "assigned to a credential-named binding" path. The name
195
- * says *what the slot is for*; this says *whether the value is plausibly a
196
- * secret rather than a message, label, or identifier*.
197
- */
198
104
  function isSecretShaped(value, minLength) {
199
105
  if (value.length < minLength)
200
106
  return false;
201
- // Sentences and phrases are messages, never credentials.
202
107
  if (/\s/.test(value))
203
108
  return false;
204
- // Pure word strings are identifiers / i18n keys / message constants.
205
109
  if (isNaturalWordString(value))
206
110
  return false;
207
- // A credential mixes at least two character classes, or — for single-charset
208
- // secrets like a 21-character lowercase blob — is long and high-entropy.
209
111
  if (classCount(charClasses(value)) >= 2)
210
112
  return true;
211
113
  return value.length >= 20 && shannonEntropy(value) >= 3.0;
212
114
  }
213
- /**
214
- * Words that only ever appear in a value a developer expects to replace.
215
- * Matched as whole words inside the string, so `changeme`, `change-me`,
216
- * `YOUR_API_KEY`, and `<your-secret-here>` are all covered.
217
- */
218
115
  const PLACEHOLDER_WORDS = new Set([
219
116
  'changeme', 'change', 'replaceme', 'replace', 'yours', 'your',
220
117
  'placeholder', 'example', 'sample', 'dummy', 'todo', 'tbd',
221
118
  'redacted', 'notreal', 'xxx',
222
119
  ]);
223
- /**
224
- * True when the value is a self-evident stand-in rather than a secret.
225
- *
226
- * Three shapes, each unambiguous on its own:
227
- * 1. Bracketed template slots — `<your-secret-here>`, `{{API_KEY}}`,
228
- * `${SECRET}`, `[token]`. No real credential is delimited this way, and
229
- * the brackets are what push the string past `isSecretShaped`'s
230
- * two-character-class gate in the first place.
231
- * 2. A placeholder word standing as its own token — `changeme`,
232
- * `YOUR_API_KEY`, `example.com`. Substring matching is deliberately
233
- * avoided: a real key may contain `bar` by chance.
234
- * 3. One character repeated — `xxxxxxxxxxxx`, `********`, `00000000`.
235
- *
236
- * Verified against benchmarks/corpus/CWE-798/safe/test-placeholder-values.js,
237
- * where `secret: '<your-secret-here>'` was reported at CVSS 9.8.
238
- */
239
120
  function isPlaceholderValue(value) {
240
121
  const trimmed = value.trim();
241
122
  if (trimmed.length === 0)
242
123
  return false;
243
- // 1. Bracketed template slots.
244
124
  if (/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))
245
125
  return true;
246
- // 3. One character repeated (4+).
247
126
  if (trimmed.length >= 4 && new Set(trimmed).size === 1)
248
127
  return true;
249
- // 2. Placeholder word as a whole token.
250
128
  const tokens = trimmed
251
129
  .replace(/([a-z])([A-Z])/g, '$1 $2')
252
130
  .toLowerCase()
@@ -254,74 +132,42 @@ function isPlaceholderValue(value) {
254
132
  .filter(Boolean);
255
133
  return tokens.some(token => PLACEHOLDER_WORDS.has(token));
256
134
  }
257
- /**
258
- * Check if a string literal looks like a hardcoded credential.
259
- * Returns `confidence: 'ambiguous'` when only a permissive pattern matched —
260
- * the caller MUST verify the surrounding identifier is credential-named.
261
- */
262
135
  function looksLikeCredential(value, options, ignorePatterns) {
263
136
  const NONE = { isCredential: false, type: '', confidence: 'ambiguous' };
264
- // Check ignore patterns first
265
137
  if (ignorePatterns.some(pattern => pattern.test(value)))
266
138
  return NONE;
267
- // Custom patterns are user-defined → trust them, treat as structural
268
139
  for (const customPattern of options.customPatterns) {
269
140
  try {
270
141
  const regex = new RegExp(customPattern.pattern);
271
142
  if (regex.test(value)) {
272
143
  return { isCredential: true, type: customPattern.type, confidence: 'structural' };
273
144
  }
274
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
275
145
  }
276
146
  catch (error) {
277
147
  continue;
278
148
  }
279
149
  }
280
- // Common-password keyword match — AMBIGUOUS. Strings like "test", "admin",
281
- // "guest" appear in test fixtures, error messages, and identifiers all the
282
- // time. The caller must verify a credential-named context.
283
150
  if (options.detectPasswords && CREDENTIAL_PATTERNS.commonPassword.test(value)) {
284
151
  return { isCredential: true, type: 'Common password', confidence: 'ambiguous' };
285
152
  }
286
- // Structural: DB connection strings have unambiguous shape
287
- // `protocol://user:pass@host` — no FP risk.
288
153
  if (options.detectDatabaseStrings && CREDENTIAL_PATTERNS.databaseString.test(value)) {
289
154
  return { isCredential: true, type: 'Database connection string', confidence: 'structural' };
290
155
  }
291
156
  if (value.length < options.minLength)
292
157
  return NONE;
293
- // Structural: JWT format (3 base64 parts dot-separated)
294
158
  if (options.detectTokens && CREDENTIAL_PATTERNS.jwtToken.test(value)) {
295
159
  return { isCredential: true, type: 'JWT token', confidence: 'structural' };
296
160
  }
297
- // Structural: OAuth tokens have provider prefixes (ghp_, gho_, ...)
298
161
  if (options.detectTokens && CREDENTIAL_PATTERNS.oauthToken.test(value)) {
299
162
  return { isCredential: true, type: 'OAuth token', confidence: 'structural' };
300
163
  }
301
- // Secret keys (base64/hex 32+) — context-required. Long base64 / hex
302
- // strings appear in source maps, generated IDs, hash digests; without
303
- // a credential-named context they're FPs. Word-shaped strings are excluded
304
- // outright: `experimental_onToolExecutionStart` is 33 chars of [A-Za-z_]
305
- // and matches the charset, but it is an identifier, not a key.
306
- // Structural: AWS access key has a fixed prefix
307
164
  if (options.detectApiKeys && CREDENTIAL_PATTERNS.awsAccessKey.test(value)) {
308
165
  return { isCredential: true, type: 'AWS access key', confidence: 'structural' };
309
166
  }
310
- // Structural: Stripe-style keys (sk_live_, sk_test_, pk_live_, pk_test_,
311
- // rk_live_, rk_test_) are unambiguous — the prefix is registered to
312
- // Stripe and never appears in unrelated contexts. Type label is kept
313
- // as the generic 'API key' to match existing test expectations and
314
- // ensure the suggestion templates remain stable for callers.
315
167
  if (options.detectApiKeys &&
316
168
  /^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)) {
317
169
  return { isCredential: true, type: 'API key', confidence: 'structural' };
318
170
  }
319
- // Structural by SHAPE, not by name: a long, mixed-case, digit-bearing,
320
- // high-entropy blob with no separators is a random secret whatever the
321
- // slot it sits in. This is the tier that finds the genuine 50-character
322
- // API secret committed in ack-nestjs-boilerplate's migration seed data —
323
- // and it also finds the 25-character `key:` next to it, which the old
324
- // name-driven logic missed because `key` was not on the allowlist.
325
171
  if (options.detectApiKeys && looksRandom(value)) {
326
172
  return {
327
173
  isCredential: true,
@@ -332,17 +178,11 @@ function looksLikeCredential(value, options, ignorePatterns) {
332
178
  if (value.length >= 32 && CREDENTIAL_PATTERNS.secretKey.test(value) && !isNaturalWordString(value)) {
333
179
  return { isCredential: true, type: 'Secret key', confidence: 'ambiguous' };
334
180
  }
335
- // Generic 32+-char alphanumeric — AMBIGUOUS. This is the FP source on
336
- // vercel/ai's TS union types and error class names. Caller must verify
337
- // a credential-named context, and the value must not be word-shaped.
338
181
  if (options.detectApiKeys && /^[A-Za-z0-9_-]{32,}$/.test(value) && !isNaturalWordString(value)) {
339
182
  return { isCredential: true, type: 'API key', confidence: 'ambiguous' };
340
183
  }
341
184
  return NONE;
342
185
  }
343
- // Note: isCredentialVariableName is reserved for future use when we want to
344
- // check variable names in addition to values
345
- // @coverage-note: Not currently used, reserved for future enhancement
346
186
  exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
347
187
  name: 'no-hardcoded-credentials',
348
188
  meta: {
@@ -513,7 +353,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
513
353
  filename.includes('/tests/') ||
514
354
  filename.includes('/fixtures/') ||
515
355
  filename.includes('/mocks/'));
516
- // Compile ignore patterns to regex
517
356
  const compiledIgnorePatterns = ignorePatterns.map((pattern) => new RegExp(pattern));
518
357
  const detectionOptions = {
519
358
  minLength,
@@ -523,69 +362,34 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
523
362
  detectDatabaseStrings,
524
363
  customPatterns,
525
364
  };
526
- /**
527
- * Variable / property names that hold UI labels and HTML attribute
528
- * values, not secrets. When a literal containing the word "password"
529
- * (or other credential-like text) lives in one of these contexts, it's
530
- * a label or form-field metadata, not a hardcoded credential.
531
- */
532
365
  const LABEL_CONTEXT_NAMES = new Set([
533
- // HTML form attributes
534
366
  'type', 'name', 'id', 'placeholder', 'label', 'title', 'role',
535
367
  'autocomplete', 'autoFocus', 'autocapitalize', 'inputmode',
536
- // ARIA
537
368
  'aria-label', 'aria-labelledby', 'aria-describedby',
538
- // Common semantic UI fields
539
369
  'fieldName', 'fieldType', 'fieldLabel', 'inputType', 'inputName',
540
370
  'displayName', 'columnName', 'paramName',
541
- // i18n keys / translation lookup. NOTE: bare `'key'` is intentionally
542
- // omitted — `const key = '...'` is the canonical name for actual API
543
- // keys (e.g. AWS, Stripe), so exempting it would mask real secrets.
544
- // The specific i18n names below cover translation lookups without
545
- // that false-negative.
546
371
  'i18nKey', 'translationKey', 'messageKey',
547
372
  ]);
548
- /**
549
- * Returns true if the literal is being used as a UI label or HTML
550
- * attribute value rather than as a secret. Examples:
551
- * const label = 'password'; // variable named `label`
552
- * input.type = 'password'; // assigning to .type
553
- * input.name = 'userPassword'; // assigning to .name
554
- * <input type="password" /> // JSX attribute
555
- * { type: 'password', name: 'pw' } // object literal property
556
- * setAttribute('placeholder', 'Enter password') // setAttribute call
557
- */
558
373
  function isLabelContext(node, parent) {
559
374
  if (!parent)
560
375
  return false;
561
- // Object-literal entries: walk up through the ObjectExpression →
562
- // its Property → its enclosing VariableDeclarator. Closes the
563
- // regression where `const labels = { password: 'Enter password' }`
564
- // was firing because the property key 'password' is in
565
- // CREDENTIAL_VARIABLE_NAMES even though the surrounding `labels`
566
- // var indicates the whole object is UI text.
567
376
  if (parent.type === 'ObjectExpression') {
568
377
  const grand = parent.parent;
569
378
  if (grand)
570
379
  return isLabelContext(node, grand);
571
380
  return false;
572
381
  }
573
- // Array elements: walk up so `const labels = ['Enter password']`
574
- // is treated as label context if `labels` is label-named.
575
382
  if (parent.type === 'ArrayExpression') {
576
383
  const grand = parent.parent;
577
384
  if (grand)
578
385
  return isLabelContext(node, grand);
579
386
  return false;
580
387
  }
581
- // const label = 'password' / let label = 'password' / `labels` /
582
- // any var ending in `label`/`name`/`placeholder`.
583
388
  if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
584
389
  const n = parent.id.name.toLowerCase();
585
390
  if (LABEL_CONTEXT_NAMES.has(n) || n === 'labels' || n.endsWith('label') || n.endsWith('labels') || n.endsWith('name') || n.endsWith('placeholder'))
586
391
  return true;
587
392
  }
588
- // input.type = 'password' / input.name = 'userPassword'
589
393
  if (parent.type === 'AssignmentExpression' && parent.right === node) {
590
394
  const left = parent.left;
591
395
  if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
@@ -593,7 +397,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
593
397
  return true;
594
398
  }
595
399
  }
596
- // { type: 'password', name: 'foo' } — direct property key is label-typed
597
400
  if (parent.type === 'Property' && parent.value === node) {
598
401
  const key = parent.key;
599
402
  if (key.type === 'Identifier' && LABEL_CONTEXT_NAMES.has(key.name))
@@ -602,12 +405,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
602
405
  if (LABEL_CONTEXT_NAMES.has(key.value))
603
406
  return true;
604
407
  }
605
- // Otherwise, walk up: the property may not have a label-typed
606
- // key but the enclosing variable might be `labels` /
607
- // `i18nStrings` / `messages` / etc., signalling that the
608
- // whole object is UI text. Closes the FP regression where
609
- // `const labels = { password: 'Enter password' }` fired
610
- // because `password` is in CREDENTIAL_VARIABLE_NAMES.
611
408
  const obj = parent.parent;
612
409
  if (obj?.type === 'ObjectExpression') {
613
410
  const grand = obj.parent;
@@ -615,7 +412,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
615
412
  return isLabelContext(node, grand);
616
413
  }
617
414
  }
618
- // setAttribute('type', 'password') — second arg is the value
619
415
  if (parent.type === 'CallExpression' &&
620
416
  parent.callee.type === 'MemberExpression' &&
621
417
  parent.callee.property.type === 'Identifier') {
@@ -627,24 +423,11 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
627
423
  return true;
628
424
  }
629
425
  }
630
- // JSX: <input type="password" />
631
426
  if (parent.type === 'JSXAttribute')
632
427
  return true;
633
428
  return false;
634
429
  }
635
- /**
636
- * Map a credential-context to its category so the detection-disable
637
- * options can gate the context-positive code path. `password` covers
638
- * password-like names, `token` covers JWT / OAuth / session tokens,
639
- * `database` covers DB connection strings, `apikey` covers API key /
640
- * secret-key style names. Anything else falls back to `other`, which
641
- * the options never gate (e.g. `credentials`, `auth`).
642
- */
643
- function inferCredentialTypeFromContext(
644
- // Non-optional: the sole caller only reaches here after
645
- // isCredentialContext(node, parent) has already returned true, which
646
- // requires a truthy parent.
647
- parent) {
430
+ function inferCredentialTypeFromContext(parent) {
648
431
  const name = (() => {
649
432
  if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
650
433
  return parent.id.name.toLowerCase();
@@ -653,9 +436,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
653
436
  const key = parent.key;
654
437
  if (key.type === 'Identifier')
655
438
  return key.name.toLowerCase();
656
- // isCredentialContext's own Property check only returns true for
657
- // an Identifier key (handled above) or a string-Literal key, so
658
- // whatever remains here is always the latter.
659
439
  return String(key.value).toLowerCase();
660
440
  }
661
441
  if (parent.type === 'AssignmentExpression') {
@@ -676,33 +456,14 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
676
456
  return 'apikey';
677
457
  return 'other';
678
458
  }
679
- /**
680
- * Returns true when the string is in a context that names credentials —
681
- * assigned to a credential-typed variable, property, parameter, or used
682
- * as the second argument to common credential APIs. Required for
683
- * ambiguous matches (generic 32+-char alphanumeric, common-password
684
- * keywords) which would otherwise fire on identifier-shaped literals
685
- * (TS union types, error class names, test prompts).
686
- */
687
459
  function isCredentialContext(node, parent) {
688
460
  if (!parent)
689
461
  return false;
690
462
  const matches = (name) => {
691
463
  const lower = name.toLowerCase();
692
- // Bare `key` / `keys` is a WEAK credential name: it labels cache keys,
693
- // map keys, i18n keys and object keys far more often than API keys
694
- // (`const key = "memCache2"` in webpack's Compilation.js). It counts as
695
- // credential context only when the value is already a random blob by
696
- // shape — which is what makes `{ key: 'fyFGb7ywyM37TqDY8nuhAmGW5' }`
697
- // (ack-nestjs-boilerplate's seeded API key) reportable.
698
464
  if (lower === 'key' || lower === 'keys') {
699
465
  return node.type === 'Literal' && typeof node.value === 'string' && looksRandom(node.value);
700
466
  }
701
- // Try the literal name AND its singular form (drop trailing 's')
702
- // so collections like `tokens`, `apiKeys`, `secrets`, `passwords`
703
- // are recognised. Closes the audit FN where
704
- // `const tokens = ['Bearer sk_live_...']` bypassed credential
705
- // detection because `tokens` (plural) wasn't in the allowlist.
706
467
  const singular = lower.endsWith('s') ? lower.slice(0, -1) : lower;
707
468
  if (CREDENTIAL_VARIABLE_NAMES.has(lower) || CREDENTIAL_VARIABLE_NAMES.has(singular))
708
469
  return true;
@@ -713,23 +474,16 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
713
474
  lower.endsWith('passwd') || lower.endsWith('credential') ||
714
475
  lower.endsWith('credentials');
715
476
  };
716
- // Array elements: walk up through the ArrayExpression to its
717
- // enclosing variable / property. Closes the audit FN where
718
- // `const tokens = ['Bearer sk_live_...']` was bypassing the
719
- // credential-name check because the literal's immediate parent is
720
- // the ArrayExpression rather than the VariableDeclarator.
721
477
  if (parent.type === 'ArrayExpression') {
722
478
  const grand = parent.parent;
723
479
  if (grand)
724
480
  return isCredentialContext(node, grand);
725
481
  return false;
726
482
  }
727
- // const apiKey = '...' / let secret = '...'
728
483
  if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
729
484
  if (matches(parent.id.name))
730
485
  return true;
731
486
  }
732
- // obj.apiKey = '...' / this.password = '...'
733
487
  if (parent.type === 'AssignmentExpression' &&
734
488
  parent.right === node) {
735
489
  const left = parent.left;
@@ -742,7 +496,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
742
496
  return true;
743
497
  }
744
498
  }
745
- // { apiKey: '...', secret: '...' }
746
499
  if (parent.type === 'Property' && parent.value === node) {
747
500
  const key = parent.key;
748
501
  if (key.type === 'Identifier' && matches(key.name))
@@ -754,21 +507,14 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
754
507
  }
755
508
  return false;
756
509
  }
757
- /**
758
- * Check a string literal node
759
- */
760
510
  function checkStringLiteral(node, parent) {
761
511
  if (typeof node.value !== 'string') {
762
512
  return;
763
513
  }
764
514
  const value = node.value;
765
- // Skip if in test files and allowed
766
515
  if (isTestFile) {
767
516
  return;
768
517
  }
769
- // Skip fallback in `process.env.X || 'value'` — the string is only
770
- // used when the env var is absent (dev-mode default). The real secret
771
- // lives in the environment, not the source file.
772
518
  if (parent?.type === 'LogicalExpression' &&
773
519
  parent.operator === '||' &&
774
520
  parent.right === node) {
@@ -779,63 +525,33 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
779
525
  left.object.object.name === 'process' &&
780
526
  left.object.property.type === 'Identifier' &&
781
527
  left.object.property.name === 'env') {
782
- return; // safe — fallback to process.env value
528
+ return;
783
529
  }
784
530
  }
785
- // Skip if used as a UI label / HTML attribute value (form-field name,
786
- // type tag, ARIA label, i18n key) — these aren't credentials.
787
531
  if (isLabelContext(node, parent)) {
788
532
  return;
789
533
  }
790
- // Check if it looks like a credential
791
534
  const { isCredential, type, confidence } = looksLikeCredential(value, detectionOptions, compiledIgnorePatterns);
792
- // Ambiguous matches require a credential-named context to fire.
793
- // Without this gate the rule reports type literals, error class
794
- // names, and test prompts as credentials (vercel/ai had 807 such
795
- // FPs before the gate landed).
796
535
  let finalIsCredential = isCredential;
797
536
  let finalType = type;
798
537
  if (isCredential && confidence === 'ambiguous' && !isCredentialContext(node, parent)) {
799
538
  finalIsCredential = false;
800
539
  }
801
- // Self-evident placeholders are not secrets. Gated to non-structural
802
- // findings only: a JWT, an `sk_live_` key, or a DB connection string
803
- // keeps its shape whatever words it contains, so those still report.
804
540
  const isPlaceholder = allowPlaceholders && isPlaceholderValue(value);
805
541
  if (isPlaceholder && confidence !== 'structural') {
806
542
  finalIsCredential = false;
807
543
  }
808
- // Context-positive: a *secret-shaped* string assigned to a
809
- // credential-named variable/property is a credential, even when no
810
- // structural pattern matches. Catches passwords like 'aaAA@123' that
811
- // don't fit any known key format but are clearly secrets.
812
- //
813
- // `isSecretShaped` is the load-bearing half of this condition. Without
814
- // it the rule fires on every string ≥ minLength that happens to sit in
815
- // a credential-named slot — which is how `errors: { password:
816
- // 'incorrectPassword' }` (an i18n error key, 5 of 10 corpus findings)
817
- // got reported at CVSS 9.8. The name says what the slot is for; the
818
- // shape says whether the value is a secret.
819
- //
820
- // The detection-disable options (detectApiKeys / detectPasswords /
821
- // detectTokens / detectDatabaseStrings) MUST gate this path too —
822
- // otherwise `{ detectPasswords: false }` silently fires on
823
- // `const password = "..."` because the var-name match alone
824
- // bypasses the option. Map the var name back to its category and
825
- // honour the option.
826
544
  if (!finalIsCredential &&
827
545
  !isPlaceholder &&
828
546
  !compiledIgnorePatterns.some((pattern) => pattern.test(value)) &&
829
547
  isSecretShaped(value, detectionOptions.minLength) &&
830
548
  isCredentialContext(node, parent)) {
831
- // isCredentialContext(node, parent) just returned true, which
832
- // requires a truthy parent.
833
549
  const ctxType = inferCredentialTypeFromContext(parent);
834
550
  const optionAllows = (ctxType === 'password' && detectionOptions.detectPasswords) ||
835
551
  (ctxType === 'token' && detectionOptions.detectTokens) ||
836
552
  (ctxType === 'database' && detectionOptions.detectDatabaseStrings) ||
837
553
  (ctxType === 'apikey' && detectionOptions.detectApiKeys) ||
838
- ctxType === 'other'; // "other" credential names always honoured
554
+ ctxType === 'other';
839
555
  if (optionAllows) {
840
556
  finalIsCredential = true;
841
557
  finalType = type || 'Credential value';
@@ -844,7 +560,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
844
560
  if (!finalIsCredential) {
845
561
  return;
846
562
  }
847
- // Generate environment variable name suggestion
848
563
  let envVarName = 'API_KEY';
849
564
  if (parent && parent.type === 'Property' && parent.key.type === 'Identifier') {
850
565
  const keyName = parent.key.name;
@@ -890,15 +605,9 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
890
605
  checkStringLiteral(node, node.parent);
891
606
  },
892
607
  TemplateLiteral(node) {
893
- // Check template literal parts for credentials
894
- // Only check if there are no interpolations (static template literal)
895
608
  if (node.expressions.length === 0) {
896
609
  const fullText = node.quasis.map((q) => q.value.raw).join('');
897
610
  const { isCredential, type, confidence } = looksLikeCredential(fullText, detectionOptions, compiledIgnorePatterns);
898
- // For template literals we don't have a Literal node to pass to
899
- // `isCredentialContext`. Skip ambiguous matches entirely — if the
900
- // user really has a credential in a template literal they should
901
- // use a regular string anyway.
902
611
  if (isCredential && !isTestFile && confidence === 'structural') {
903
612
  context.report({
904
613
  node,
@@ -927,13 +636,10 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
927
636
  }
928
637
  }
929
638
  else {
930
- // For template literals with interpolations, check each quasi part
931
639
  for (const quasi of node.quasis) {
932
640
  if (quasi.value.raw) {
933
641
  const { isCredential, type, confidence } = looksLikeCredential(quasi.value.raw, detectionOptions, compiledIgnorePatterns);
934
642
  if (isCredential && !isTestFile && confidence === 'structural') {
935
- // Note: Template literals with interpolations are complex to fix automatically
936
- // So we report the error without suggestions
937
643
  context.report({
938
644
  node: quasi,
939
645
  messageId: 'useEnvironmentVariable',