eslint-plugin-secure-coding 3.3.4 → 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 (65) hide show
  1. package/README.md +4 -4
  2. package/package.json +30 -37
  3. package/src/index.d.ts +17 -23
  4. package/src/index.js +2 -113
  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 +86 -151
  14. package/src/rules/no-hardcoded-credentials/index.js +142 -184
  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 +39 -35
  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 +55 -66
  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 -311
  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 -44
  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,41 +1,21 @@
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;
4
+ exports.isNaturalWordString = isNaturalWordString;
5
+ exports.looksRandom = looksRandom;
6
+ exports.isSecretShaped = isSecretShaped;
7
+ exports.isPlaceholderValue = isPlaceholderValue;
9
8
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
10
9
  const eslint_devkit_2 = require("@interlace/eslint-devkit");
11
- /**
12
- * Common credential patterns
13
- */
14
10
  const CREDENTIAL_PATTERNS = {
15
- // API Keys (typically 32+ character alphanumeric strings)
16
11
  apiKey: /^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,
17
- // JWT Tokens (three base64 parts separated by dots)
18
12
  jwtToken: /^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,
19
- // OAuth tokens
20
13
  oauthToken: /^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,
21
- // AWS Access Keys
22
14
  awsAccessKey: /^AKIA[0-9A-Z]{16}$/,
23
- // Database connection strings with credentials
24
15
  databaseString: /^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,
25
- // Generic password patterns (common weak passwords) - no length requirement
26
16
  commonPassword: /^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,
27
- // Secret keys (base64-like or hex strings)
28
17
  secretKey: /^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/,
29
18
  };
30
- /**
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
19
  const CREDENTIAL_VARIABLE_NAMES = new Set([
40
20
  'apikey', 'api_key', 'apiKey',
41
21
  'secret', 'secretkey', 'secret_key', 'secretKey', 'clientsecret', 'client_secret', 'clientSecret',
@@ -48,80 +28,161 @@ const CREDENTIAL_VARIABLE_NAMES = new Set([
48
28
  'connectionstring', 'connection_string', 'connectionString', 'connectionuri', 'connectionURI',
49
29
  'dburl', 'db_url', 'dbUrl', 'databaseurl', 'database_url', 'databaseUrl',
50
30
  ]);
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.
55
- */
31
+ const WORD_SEPARATORS = new Set(['_', '-', '.', ' ']);
32
+ function shannonEntropy(value) {
33
+ const freq = new Map();
34
+ for (const ch of value)
35
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
36
+ let entropy = 0;
37
+ for (const count of freq.values()) {
38
+ const p = count / value.length;
39
+ entropy -= p * Math.log2(p);
40
+ }
41
+ return entropy;
42
+ }
43
+ function charClasses(value) {
44
+ const classes = { lower: false, upper: false, digit: false, symbol: false };
45
+ for (const ch of value) {
46
+ if (WORD_SEPARATORS.has(ch))
47
+ continue;
48
+ if (ch >= 'a' && ch <= 'z')
49
+ classes.lower = true;
50
+ else if (ch >= 'A' && ch <= 'Z')
51
+ classes.upper = true;
52
+ else if (ch >= '0' && ch <= '9')
53
+ classes.digit = true;
54
+ else
55
+ classes.symbol = true;
56
+ }
57
+ return classes;
58
+ }
59
+ function classCount(classes) {
60
+ return Number(classes.lower) + Number(classes.upper) + Number(classes.digit) + Number(classes.symbol);
61
+ }
62
+ function isPronounceable(token) {
63
+ const lower = token.toLowerCase();
64
+ if (!/[aeiouy]/.test(lower))
65
+ return false;
66
+ if (/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))
67
+ return false;
68
+ return true;
69
+ }
70
+ function isNaturalWordString(value) {
71
+ if (!/^[A-Za-z][A-Za-z_\-. ]*$/.test(value))
72
+ return false;
73
+ const tokens = value
74
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
75
+ .split(/[^A-Za-z]+/)
76
+ .filter(Boolean);
77
+ const meaningful = tokens.filter(t => t.length >= 3);
78
+ if (meaningful.length === 0)
79
+ return false;
80
+ return meaningful.every(isPronounceable);
81
+ }
82
+ function hasSequentialRun(value, min = 5) {
83
+ let run = 1;
84
+ for (let i = 1; i < value.length; i++) {
85
+ run = value.charCodeAt(i) === value.charCodeAt(i - 1) + 1 ? run + 1 : 1;
86
+ if (run >= min)
87
+ return true;
88
+ }
89
+ return false;
90
+ }
91
+ function looksRandom(value) {
92
+ if (value.length < 20)
93
+ return false;
94
+ if (!/^[A-Za-z0-9]+$/.test(value))
95
+ return false;
96
+ const classes = charClasses(value);
97
+ if (!classes.lower || !classes.upper || !classes.digit)
98
+ return false;
99
+ if (hasSequentialRun(value))
100
+ return false;
101
+ return shannonEntropy(value) >= 3.5;
102
+ }
103
+ const CONTEXT_FREE_RANDOM_LENGTH = 32;
104
+ function isSecretShaped(value, minLength) {
105
+ if (value.length < minLength)
106
+ return false;
107
+ if (/\s/.test(value))
108
+ return false;
109
+ if (isNaturalWordString(value))
110
+ return false;
111
+ if (classCount(charClasses(value)) >= 2)
112
+ return true;
113
+ return value.length >= 20 && shannonEntropy(value) >= 3.0;
114
+ }
115
+ const PLACEHOLDER_WORDS = new Set([
116
+ 'changeme', 'change', 'replaceme', 'replace', 'yours', 'your',
117
+ 'placeholder', 'example', 'sample', 'dummy', 'todo', 'tbd',
118
+ 'redacted', 'notreal', 'xxx',
119
+ ]);
120
+ function isPlaceholderValue(value) {
121
+ const trimmed = value.trim();
122
+ if (trimmed.length === 0)
123
+ return false;
124
+ if (/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))
125
+ return true;
126
+ if (trimmed.length >= 4 && new Set(trimmed).size === 1)
127
+ return true;
128
+ const tokens = trimmed
129
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
130
+ .toLowerCase()
131
+ .split(/[^a-z0-9]+/)
132
+ .filter(Boolean);
133
+ return tokens.some(token => PLACEHOLDER_WORDS.has(token));
134
+ }
56
135
  function looksLikeCredential(value, options, ignorePatterns) {
57
136
  const NONE = { isCredential: false, type: '', confidence: 'ambiguous' };
58
- // Check ignore patterns first
59
137
  if (ignorePatterns.some(pattern => pattern.test(value)))
60
138
  return NONE;
61
- // Custom patterns are user-defined → trust them, treat as structural
62
139
  for (const customPattern of options.customPatterns) {
63
140
  try {
64
141
  const regex = new RegExp(customPattern.pattern);
65
142
  if (regex.test(value)) {
66
143
  return { isCredential: true, type: customPattern.type, confidence: 'structural' };
67
144
  }
68
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
69
145
  }
70
146
  catch (error) {
71
147
  continue;
72
148
  }
73
149
  }
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
150
  if (options.detectPasswords && CREDENTIAL_PATTERNS.commonPassword.test(value)) {
78
151
  return { isCredential: true, type: 'Common password', confidence: 'ambiguous' };
79
152
  }
80
- // Structural: DB connection strings have unambiguous shape
81
- // `protocol://user:pass@host` — no FP risk.
82
153
  if (options.detectDatabaseStrings && CREDENTIAL_PATTERNS.databaseString.test(value)) {
83
154
  return { isCredential: true, type: 'Database connection string', confidence: 'structural' };
84
155
  }
85
156
  if (value.length < options.minLength)
86
157
  return NONE;
87
- // Structural: JWT format (3 base64 parts dot-separated)
88
158
  if (options.detectTokens && CREDENTIAL_PATTERNS.jwtToken.test(value)) {
89
159
  return { isCredential: true, type: 'JWT token', confidence: 'structural' };
90
160
  }
91
- // Structural: OAuth tokens have provider prefixes (ghp_, gho_, ...)
92
161
  if (options.detectTokens && CREDENTIAL_PATTERNS.oauthToken.test(value)) {
93
162
  return { isCredential: true, type: 'OAuth token', confidence: 'structural' };
94
163
  }
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.
98
- if (value.length >= 32 && CREDENTIAL_PATTERNS.secretKey.test(value)) {
99
- return { isCredential: true, type: 'Secret key', confidence: 'ambiguous' };
100
- }
101
- // Structural: AWS access key has a fixed prefix
102
164
  if (options.detectApiKeys && CREDENTIAL_PATTERNS.awsAccessKey.test(value)) {
103
165
  return { isCredential: true, type: 'AWS access key', confidence: 'structural' };
104
166
  }
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
167
  if (options.detectApiKeys &&
111
168
  /^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)) {
112
169
  return { isCredential: true, type: 'API key', confidence: 'structural' };
113
170
  }
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)) {
171
+ if (options.detectApiKeys && looksRandom(value)) {
172
+ return {
173
+ isCredential: true,
174
+ type: 'Secret key',
175
+ confidence: value.length >= CONTEXT_FREE_RANDOM_LENGTH ? 'structural' : 'ambiguous',
176
+ };
177
+ }
178
+ if (value.length >= 32 && CREDENTIAL_PATTERNS.secretKey.test(value) && !isNaturalWordString(value)) {
179
+ return { isCredential: true, type: 'Secret key', confidence: 'ambiguous' };
180
+ }
181
+ if (options.detectApiKeys && /^[A-Za-z0-9_-]{32,}$/.test(value) && !isNaturalWordString(value)) {
118
182
  return { isCredential: true, type: 'API key', confidence: 'ambiguous' };
119
183
  }
120
184
  return NONE;
121
185
  }
122
- // Note: isCredentialVariableName is reserved for future use when we want to
123
- // check variable names in addition to values
124
- // @coverage-note: Not currently used, reserved for future enhancement
125
186
  exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
126
187
  name: 'no-hardcoded-credentials',
127
188
  meta: {
@@ -254,6 +315,11 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
254
315
  default: 'auto',
255
316
  description: 'Strategy for fixing hardcoded credentials (auto = smart detection)'
256
317
  },
318
+ allowPlaceholders: {
319
+ type: 'boolean',
320
+ default: true,
321
+ description: 'Skip self-evident placeholder values (<your-secret-here>, changeme, xxxxxxxx)',
322
+ },
257
323
  },
258
324
  additionalProperties: false,
259
325
  },
@@ -270,11 +336,12 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
270
336
  detectDatabaseStrings: true,
271
337
  customPatterns: [],
272
338
  strategy: 'auto',
339
+ allowPlaceholders: true,
273
340
  },
274
341
  ],
275
342
  create(context) {
276
343
  const options = context.options[0] || {};
277
- const { ignorePatterns = [], allowInTests = false, minLength = 8, detectApiKeys = true, detectPasswords = true, detectTokens = true, detectDatabaseStrings = true, customPatterns = [], } = options;
344
+ const { ignorePatterns = [], allowInTests = false, minLength = 8, detectApiKeys = true, detectPasswords = true, detectTokens = true, detectDatabaseStrings = true, customPatterns = [], allowPlaceholders = true, } = options;
278
345
  const filename = context.filename;
279
346
  const isTestFile = allowInTests && (filename.includes('.test.') ||
280
347
  filename.includes('.spec.') ||
@@ -286,7 +353,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
286
353
  filename.includes('/tests/') ||
287
354
  filename.includes('/fixtures/') ||
288
355
  filename.includes('/mocks/'));
289
- // Compile ignore patterns to regex
290
356
  const compiledIgnorePatterns = ignorePatterns.map((pattern) => new RegExp(pattern));
291
357
  const detectionOptions = {
292
358
  minLength,
@@ -296,69 +362,34 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
296
362
  detectDatabaseStrings,
297
363
  customPatterns,
298
364
  };
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
365
  const LABEL_CONTEXT_NAMES = new Set([
306
- // HTML form attributes
307
366
  'type', 'name', 'id', 'placeholder', 'label', 'title', 'role',
308
367
  'autocomplete', 'autoFocus', 'autocapitalize', 'inputmode',
309
- // ARIA
310
368
  'aria-label', 'aria-labelledby', 'aria-describedby',
311
- // Common semantic UI fields
312
369
  'fieldName', 'fieldType', 'fieldLabel', 'inputType', 'inputName',
313
370
  '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
371
  'i18nKey', 'translationKey', 'messageKey',
320
372
  ]);
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
373
  function isLabelContext(node, parent) {
332
374
  if (!parent)
333
375
  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
376
  if (parent.type === 'ObjectExpression') {
341
377
  const grand = parent.parent;
342
378
  if (grand)
343
379
  return isLabelContext(node, grand);
344
380
  return false;
345
381
  }
346
- // Array elements: walk up so `const labels = ['Enter password']`
347
- // is treated as label context if `labels` is label-named.
348
382
  if (parent.type === 'ArrayExpression') {
349
383
  const grand = parent.parent;
350
384
  if (grand)
351
385
  return isLabelContext(node, grand);
352
386
  return false;
353
387
  }
354
- // const label = 'password' / let label = 'password' / `labels` /
355
- // any var ending in `label`/`name`/`placeholder`.
356
388
  if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
357
389
  const n = parent.id.name.toLowerCase();
358
390
  if (LABEL_CONTEXT_NAMES.has(n) || n === 'labels' || n.endsWith('label') || n.endsWith('labels') || n.endsWith('name') || n.endsWith('placeholder'))
359
391
  return true;
360
392
  }
361
- // input.type = 'password' / input.name = 'userPassword'
362
393
  if (parent.type === 'AssignmentExpression' && parent.right === node) {
363
394
  const left = parent.left;
364
395
  if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
@@ -366,7 +397,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
366
397
  return true;
367
398
  }
368
399
  }
369
- // { type: 'password', name: 'foo' } — direct property key is label-typed
370
400
  if (parent.type === 'Property' && parent.value === node) {
371
401
  const key = parent.key;
372
402
  if (key.type === 'Identifier' && LABEL_CONTEXT_NAMES.has(key.name))
@@ -375,12 +405,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
375
405
  if (LABEL_CONTEXT_NAMES.has(key.value))
376
406
  return true;
377
407
  }
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
408
  const obj = parent.parent;
385
409
  if (obj?.type === 'ObjectExpression') {
386
410
  const grand = obj.parent;
@@ -388,7 +412,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
388
412
  return isLabelContext(node, grand);
389
413
  }
390
414
  }
391
- // setAttribute('type', 'password') — second arg is the value
392
415
  if (parent.type === 'CallExpression' &&
393
416
  parent.callee.type === 'MemberExpression' &&
394
417
  parent.callee.property.type === 'Identifier') {
@@ -400,24 +423,11 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
400
423
  return true;
401
424
  }
402
425
  }
403
- // JSX: <input type="password" />
404
426
  if (parent.type === 'JSXAttribute')
405
427
  return true;
406
428
  return false;
407
429
  }
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(
417
- // Non-optional: the sole caller only reaches here after
418
- // isCredentialContext(node, parent) has already returned true, which
419
- // requires a truthy parent.
420
- parent) {
430
+ function inferCredentialTypeFromContext(parent) {
421
431
  const name = (() => {
422
432
  if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
423
433
  return parent.id.name.toLowerCase();
@@ -426,9 +436,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
426
436
  const key = parent.key;
427
437
  if (key.type === 'Identifier')
428
438
  return key.name.toLowerCase();
429
- // isCredentialContext's own Property check only returns true for
430
- // an Identifier key (handled above) or a string-Literal key, so
431
- // whatever remains here is always the latter.
432
439
  return String(key.value).toLowerCase();
433
440
  }
434
441
  if (parent.type === 'AssignmentExpression') {
@@ -449,24 +456,14 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
449
456
  return 'apikey';
450
457
  return 'other';
451
458
  }
452
- /**
453
- * Returns true when the string is in a context that names credentials —
454
- * assigned to a credential-typed variable, property, parameter, or used
455
- * as the second argument to common credential APIs. Required for
456
- * ambiguous matches (generic 32+-char alphanumeric, common-password
457
- * keywords) which would otherwise fire on identifier-shaped literals
458
- * (TS union types, error class names, test prompts).
459
- */
460
459
  function isCredentialContext(node, parent) {
461
460
  if (!parent)
462
461
  return false;
463
462
  const matches = (name) => {
464
463
  const lower = name.toLowerCase();
465
- // Try the literal name AND its singular form (drop trailing 's')
466
- // so collections like `tokens`, `apiKeys`, `secrets`, `passwords`
467
- // are recognised. Closes the audit FN where
468
- // `const tokens = ['Bearer sk_live_...']` bypassed credential
469
- // detection because `tokens` (plural) wasn't in the allowlist.
464
+ if (lower === 'key' || lower === 'keys') {
465
+ return node.type === 'Literal' && typeof node.value === 'string' && looksRandom(node.value);
466
+ }
470
467
  const singular = lower.endsWith('s') ? lower.slice(0, -1) : lower;
471
468
  if (CREDENTIAL_VARIABLE_NAMES.has(lower) || CREDENTIAL_VARIABLE_NAMES.has(singular))
472
469
  return true;
@@ -477,23 +474,16 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
477
474
  lower.endsWith('passwd') || lower.endsWith('credential') ||
478
475
  lower.endsWith('credentials');
479
476
  };
480
- // Array elements: walk up through the ArrayExpression to its
481
- // enclosing variable / property. Closes the audit FN where
482
- // `const tokens = ['Bearer sk_live_...']` was bypassing the
483
- // credential-name check because the literal's immediate parent is
484
- // the ArrayExpression rather than the VariableDeclarator.
485
477
  if (parent.type === 'ArrayExpression') {
486
478
  const grand = parent.parent;
487
479
  if (grand)
488
480
  return isCredentialContext(node, grand);
489
481
  return false;
490
482
  }
491
- // const apiKey = '...' / let secret = '...'
492
483
  if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
493
484
  if (matches(parent.id.name))
494
485
  return true;
495
486
  }
496
- // obj.apiKey = '...' / this.password = '...'
497
487
  if (parent.type === 'AssignmentExpression' &&
498
488
  parent.right === node) {
499
489
  const left = parent.left;
@@ -506,7 +496,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
506
496
  return true;
507
497
  }
508
498
  }
509
- // { apiKey: '...', secret: '...' }
510
499
  if (parent.type === 'Property' && parent.value === node) {
511
500
  const key = parent.key;
512
501
  if (key.type === 'Identifier' && matches(key.name))
@@ -518,21 +507,14 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
518
507
  }
519
508
  return false;
520
509
  }
521
- /**
522
- * Check a string literal node
523
- */
524
510
  function checkStringLiteral(node, parent) {
525
511
  if (typeof node.value !== 'string') {
526
512
  return;
527
513
  }
528
514
  const value = node.value;
529
- // Skip if in test files and allowed
530
515
  if (isTestFile) {
531
516
  return;
532
517
  }
533
- // Skip fallback in `process.env.X || 'value'` — the string is only
534
- // used when the env var is absent (dev-mode default). The real secret
535
- // lives in the environment, not the source file.
536
518
  if (parent?.type === 'LogicalExpression' &&
537
519
  parent.operator === '||' &&
538
520
  parent.right === node) {
@@ -543,47 +525,33 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
543
525
  left.object.object.name === 'process' &&
544
526
  left.object.property.type === 'Identifier' &&
545
527
  left.object.property.name === 'env') {
546
- return; // safe — fallback to process.env value
528
+ return;
547
529
  }
548
530
  }
549
- // Skip if used as a UI label / HTML attribute value (form-field name,
550
- // type tag, ARIA label, i18n key) — these aren't credentials.
551
531
  if (isLabelContext(node, parent)) {
552
532
  return;
553
533
  }
554
- // Check if it looks like a credential
555
534
  const { isCredential, type, confidence } = looksLikeCredential(value, detectionOptions, compiledIgnorePatterns);
556
- // Ambiguous matches require a credential-named context to fire.
557
- // Without this gate the rule reports type literals, error class
558
- // names, and test prompts as credentials (vercel/ai had 807 such
559
- // FPs before the gate landed).
560
535
  let finalIsCredential = isCredential;
561
536
  let finalType = type;
562
537
  if (isCredential && confidence === 'ambiguous' && !isCredentialContext(node, parent)) {
563
538
  finalIsCredential = false;
564
539
  }
565
- // Context-positive: any non-trivial string assigned to a
566
- // credential-named variable/property is a credential, even when no
567
- // regex pattern matches. Catches passwords like 'SuperSecret123!'
568
- // that don't fit any structural pattern but are clearly secrets
569
- // by virtue of where they're stored.
570
- //
571
- // The detection-disable options (detectApiKeys / detectPasswords /
572
- // detectTokens / detectDatabaseStrings) MUST gate this path too —
573
- // otherwise `{ detectPasswords: false }` silently fires on
574
- // `const password = "..."` because the var-name match alone
575
- // bypasses the option. Map the var name back to its category and
576
- // honour the option.
577
- if (!finalIsCredential && value.length >= detectionOptions.minLength &&
540
+ const isPlaceholder = allowPlaceholders && isPlaceholderValue(value);
541
+ if (isPlaceholder && confidence !== 'structural') {
542
+ finalIsCredential = false;
543
+ }
544
+ if (!finalIsCredential &&
545
+ !isPlaceholder &&
546
+ !compiledIgnorePatterns.some((pattern) => pattern.test(value)) &&
547
+ isSecretShaped(value, detectionOptions.minLength) &&
578
548
  isCredentialContext(node, parent)) {
579
- // isCredentialContext(node, parent) just returned true, which
580
- // requires a truthy parent.
581
549
  const ctxType = inferCredentialTypeFromContext(parent);
582
550
  const optionAllows = (ctxType === 'password' && detectionOptions.detectPasswords) ||
583
551
  (ctxType === 'token' && detectionOptions.detectTokens) ||
584
552
  (ctxType === 'database' && detectionOptions.detectDatabaseStrings) ||
585
553
  (ctxType === 'apikey' && detectionOptions.detectApiKeys) ||
586
- ctxType === 'other'; // "other" credential names always honoured
554
+ ctxType === 'other';
587
555
  if (optionAllows) {
588
556
  finalIsCredential = true;
589
557
  finalType = type || 'Credential value';
@@ -592,7 +560,6 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
592
560
  if (!finalIsCredential) {
593
561
  return;
594
562
  }
595
- // Generate environment variable name suggestion
596
563
  let envVarName = 'API_KEY';
597
564
  if (parent && parent.type === 'Property' && parent.key.type === 'Identifier') {
598
565
  const keyName = parent.key.name;
@@ -618,14 +585,14 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
618
585
  suggest: [
619
586
  {
620
587
  messageId: 'useEnvironmentVariable',
621
- data: { envVarName, credentialType: type },
588
+ data: { envVarName, credentialType: finalType },
622
589
  fix: (fixer) => {
623
590
  return fixer.replaceText(node, `process.env.${envVarName} || '${value}'`);
624
591
  },
625
592
  },
626
593
  {
627
594
  messageId: 'useSecretManager',
628
- data: { credentialType: type },
595
+ data: { credentialType: finalType },
629
596
  fix: (fixer) => {
630
597
  return fixer.replaceText(node, `await getSecret('${envVarName.toLowerCase()}')`);
631
598
  },
@@ -638,15 +605,9 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
638
605
  checkStringLiteral(node, node.parent);
639
606
  },
640
607
  TemplateLiteral(node) {
641
- // Check template literal parts for credentials
642
- // Only check if there are no interpolations (static template literal)
643
608
  if (node.expressions.length === 0) {
644
609
  const fullText = node.quasis.map((q) => q.value.raw).join('');
645
610
  const { isCredential, type, confidence } = looksLikeCredential(fullText, detectionOptions, compiledIgnorePatterns);
646
- // For template literals we don't have a Literal node to pass to
647
- // `isCredentialContext`. Skip ambiguous matches entirely — if the
648
- // user really has a credential in a template literal they should
649
- // use a regular string anyway.
650
611
  if (isCredential && !isTestFile && confidence === 'structural') {
651
612
  context.report({
652
613
  node,
@@ -675,13 +636,10 @@ exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
675
636
  }
676
637
  }
677
638
  else {
678
- // For template literals with interpolations, check each quasi part
679
639
  for (const quasi of node.quasis) {
680
640
  if (quasi.value.raw) {
681
641
  const { isCredential, type, confidence } = looksLikeCredential(quasi.value.raw, detectionOptions, compiledIgnorePatterns);
682
642
  if (isCredential && !isTestFile && confidence === 'structural') {
683
- // Note: Template literals with interpolations are complex to fix automatically
684
- // So we report the error without suggestions
685
643
  context.report({
686
644
  node: quasi,
687
645
  messageId: 'useEnvironmentVariable',
@@ -1,14 +1,6 @@
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.noHardcodedSessionTokens = void 0;
9
- /**
10
- * @fileoverview Detect hardcoded session/JWT tokens
11
- */
12
4
  const eslint_devkit_1 = require("@interlace/eslint-devkit");
13
5
  exports.noHardcodedSessionTokens = (0, eslint_devkit_1.createRule)({
14
6
  name: 'no-hardcoded-session-tokens',
@@ -42,16 +34,13 @@ exports.noHardcodedSessionTokens = (0, eslint_devkit_1.createRule)({
42
34
  Literal(node) {
43
35
  if (typeof node.value !== 'string')
44
36
  return;
45
- // Detect JWT tokens (start with eyJ and contain 2 dots)
46
37
  if (node.value.startsWith('eyJ') && node.value.length > 50 &&
47
38
  (node.value.match(/\./g) || []).length >= 2) {
48
39
  report(node);
49
40
  }
50
- // Detect Bearer tokens
51
41
  if (node.value.startsWith('Bearer ') && node.value.length > 20) {
52
42
  report(node);
53
43
  }
54
- // Detect session_id patterns
55
44
  const parent = node.parent;
56
45
  if (parent?.type === 'VariableDeclarator' &&
57
46
  parent.id.type === 'Identifier') {