eslint-plugin-secure-coding 3.4.3 → 3.5.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.
- package/README.md +1 -1
- package/package.json +3 -3
- package/src/index.js +1 -107
- package/src/oxlint.js +1 -3
- package/src/rules/detect-non-literal-regexp/index.js +1 -329
- package/src/rules/detect-object-injection/index.js +1 -691
- package/src/rules/detect-weak-password-validation/index.js +1 -54
- package/src/rules/no-directive-injection/index.js +1 -416
- package/src/rules/no-electron-security-issues/index.js +1 -385
- package/src/rules/no-format-string-injection/index.js +1 -565
- package/src/rules/no-graphql-injection/index.js +1 -612
- package/src/rules/no-hardcoded-credentials/index.js +1 -658
- package/src/rules/no-hardcoded-session-tokens/index.js +1 -56
- package/src/rules/no-improper-sanitization/index.js +1 -391
- package/src/rules/no-improper-type-validation/index.js +1 -422
- package/src/rules/no-insecure-comparison/index.js +1 -249
- package/src/rules/no-ldap-injection/index.js +1 -403
- package/src/rules/no-missing-authentication/index.js +1 -282
- package/src/rules/no-pii-in-logs/index.js +1 -63
- package/src/rules/no-privilege-escalation/index.js +1 -282
- package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
- package/src/rules/no-sensitive-data-exposure/index.js +1 -249
- package/src/rules/no-template-injection/index.js +1 -84
- package/src/rules/no-unchecked-loop-condition/index.js +1 -541
- package/src/rules/no-unlimited-resource-allocation/index.js +1 -555
- package/src/rules/no-unsafe-deserialization/index.js +1 -497
- package/src/rules/no-unsafe-regex-construction/index.js +1 -275
- package/src/rules/no-weak-password-recovery/index.js +1 -382
- package/src/rules/no-xpath-injection/index.js +1 -431
- package/src/rules/no-xxe-injection/index.js +1 -230
- package/src/rules/require-backend-authorization/index.js +1 -58
- package/src/rules/require-secure-defaults/index.js +1 -41
- package/src/types/index.js +1 -2
|
@@ -1,658 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.noHardcodedCredentials = void 0;
|
|
4
|
-
exports.isNaturalWordString = isNaturalWordString;
|
|
5
|
-
exports.looksRandom = looksRandom;
|
|
6
|
-
exports.isSecretShaped = isSecretShaped;
|
|
7
|
-
exports.isPlaceholderValue = isPlaceholderValue;
|
|
8
|
-
const eslint_devkit_1 = require("@interlace/eslint-devkit");
|
|
9
|
-
const eslint_devkit_2 = require("@interlace/eslint-devkit");
|
|
10
|
-
const CREDENTIAL_PATTERNS = {
|
|
11
|
-
apiKey: /^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,
|
|
12
|
-
jwtToken: /^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,
|
|
13
|
-
oauthToken: /^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,
|
|
14
|
-
awsAccessKey: /^AKIA[0-9A-Z]{16}$/,
|
|
15
|
-
databaseString: /^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,
|
|
16
|
-
commonPassword: /^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,
|
|
17
|
-
secretKey: /^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/,
|
|
18
|
-
};
|
|
19
|
-
const CREDENTIAL_VARIABLE_NAMES = new Set([
|
|
20
|
-
'apikey', 'api_key', 'apiKey',
|
|
21
|
-
'secret', 'secretkey', 'secret_key', 'secretKey', 'clientsecret', 'client_secret', 'clientSecret',
|
|
22
|
-
'token', 'authtoken', 'auth_token', 'authToken', 'accesstoken', 'access_token', 'accessToken',
|
|
23
|
-
'refreshtoken', 'refresh_token', 'refreshToken', 'idtoken', 'id_token', 'idToken',
|
|
24
|
-
'password', 'passwd', 'pass', 'pwd',
|
|
25
|
-
'privatekey', 'private_key', 'privateKey',
|
|
26
|
-
'credentials', 'creds',
|
|
27
|
-
'authorization', 'auth',
|
|
28
|
-
'connectionstring', 'connection_string', 'connectionString', 'connectionuri', 'connectionURI',
|
|
29
|
-
'dburl', 'db_url', 'dbUrl', 'databaseurl', 'database_url', 'databaseUrl',
|
|
30
|
-
]);
|
|
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
|
-
}
|
|
135
|
-
function looksLikeCredential(value, options, ignorePatterns) {
|
|
136
|
-
const NONE = { isCredential: false, type: '', confidence: 'ambiguous' };
|
|
137
|
-
if (ignorePatterns.some(pattern => pattern.test(value)))
|
|
138
|
-
return NONE;
|
|
139
|
-
for (const customPattern of options.customPatterns) {
|
|
140
|
-
try {
|
|
141
|
-
const regex = new RegExp(customPattern.pattern);
|
|
142
|
-
if (regex.test(value)) {
|
|
143
|
-
return { isCredential: true, type: customPattern.type, confidence: 'structural' };
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
catch (error) {
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
if (options.detectPasswords && CREDENTIAL_PATTERNS.commonPassword.test(value)) {
|
|
151
|
-
return { isCredential: true, type: 'Common password', confidence: 'ambiguous' };
|
|
152
|
-
}
|
|
153
|
-
if (options.detectDatabaseStrings && CREDENTIAL_PATTERNS.databaseString.test(value)) {
|
|
154
|
-
return { isCredential: true, type: 'Database connection string', confidence: 'structural' };
|
|
155
|
-
}
|
|
156
|
-
if (value.length < options.minLength)
|
|
157
|
-
return NONE;
|
|
158
|
-
if (options.detectTokens && CREDENTIAL_PATTERNS.jwtToken.test(value)) {
|
|
159
|
-
return { isCredential: true, type: 'JWT token', confidence: 'structural' };
|
|
160
|
-
}
|
|
161
|
-
if (options.detectTokens && CREDENTIAL_PATTERNS.oauthToken.test(value)) {
|
|
162
|
-
return { isCredential: true, type: 'OAuth token', confidence: 'structural' };
|
|
163
|
-
}
|
|
164
|
-
if (options.detectApiKeys && CREDENTIAL_PATTERNS.awsAccessKey.test(value)) {
|
|
165
|
-
return { isCredential: true, type: 'AWS access key', confidence: 'structural' };
|
|
166
|
-
}
|
|
167
|
-
if (options.detectApiKeys &&
|
|
168
|
-
/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)) {
|
|
169
|
-
return { isCredential: true, type: 'API key', confidence: 'structural' };
|
|
170
|
-
}
|
|
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)) {
|
|
182
|
-
return { isCredential: true, type: 'API key', confidence: 'ambiguous' };
|
|
183
|
-
}
|
|
184
|
-
return NONE;
|
|
185
|
-
}
|
|
186
|
-
exports.noHardcodedCredentials = (0, eslint_devkit_2.createRule)({
|
|
187
|
-
name: 'no-hardcoded-credentials',
|
|
188
|
-
meta: {
|
|
189
|
-
type: 'problem',
|
|
190
|
-
docs: {
|
|
191
|
-
url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md',
|
|
192
|
-
description: 'Detects hardcoded passwords, API keys, tokens, and other sensitive credentials',
|
|
193
|
-
cwe: 'CWE-798',
|
|
194
|
-
cvss: 9.8,
|
|
195
|
-
confidence: 'medium',
|
|
196
|
-
},
|
|
197
|
-
fixable: 'code',
|
|
198
|
-
hasSuggestions: true,
|
|
199
|
-
messages: {
|
|
200
|
-
useEnvironmentVariable: (0, eslint_devkit_1.formatLLMMessage)({
|
|
201
|
-
icon: eslint_devkit_1.MessageIcons.SECURITY,
|
|
202
|
-
issueName: 'Hard-coded Credential',
|
|
203
|
-
cwe: 'CWE-798',
|
|
204
|
-
description: 'Hard-coded {{credentialType}} detected',
|
|
205
|
-
severity: 'CRITICAL',
|
|
206
|
-
fix: 'Use environment variable: process.env.{{envVarName}} or secret management service',
|
|
207
|
-
documentationLink: 'https://cwe.mitre.org/data/definitions/798.html',
|
|
208
|
-
}),
|
|
209
|
-
useSecretManager: (0, eslint_devkit_1.formatLLMMessage)({
|
|
210
|
-
icon: eslint_devkit_1.MessageIcons.SECURITY,
|
|
211
|
-
issueName: 'Use Secret Manager',
|
|
212
|
-
cwe: 'CWE-798',
|
|
213
|
-
description: 'Use secure secret management service',
|
|
214
|
-
severity: 'HIGH',
|
|
215
|
-
fix: 'Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar',
|
|
216
|
-
documentationLink: 'https://cwe.mitre.org/data/definitions/798.html',
|
|
217
|
-
}),
|
|
218
|
-
strategyEnv: (0, eslint_devkit_1.formatLLMMessage)({
|
|
219
|
-
icon: eslint_devkit_1.MessageIcons.DEVELOPMENT,
|
|
220
|
-
issueName: 'Environment Variable Strategy',
|
|
221
|
-
description: 'Move credentials to environment variables',
|
|
222
|
-
severity: 'MEDIUM',
|
|
223
|
-
fix: 'Store credentials in environment variables (process.env)',
|
|
224
|
-
documentationLink: 'https://12factor.net/config',
|
|
225
|
-
}),
|
|
226
|
-
strategyConfig: (0, eslint_devkit_1.formatLLMMessage)({
|
|
227
|
-
icon: eslint_devkit_1.MessageIcons.DEVELOPMENT,
|
|
228
|
-
issueName: 'Configuration File Strategy',
|
|
229
|
-
description: 'Store credentials in encrypted configuration files',
|
|
230
|
-
severity: 'MEDIUM',
|
|
231
|
-
fix: 'Use encrypted configuration files with proper access controls',
|
|
232
|
-
documentationLink: 'https://owasp.org/www-project-cheat-sheets/cheatsheets/Configuration_Management_Cheat_Sheet.html',
|
|
233
|
-
}),
|
|
234
|
-
strategyVault: (0, eslint_devkit_1.formatLLMMessage)({
|
|
235
|
-
icon: eslint_devkit_1.MessageIcons.SECURITY,
|
|
236
|
-
issueName: 'Secret Vault Strategy',
|
|
237
|
-
cwe: 'CWE-798',
|
|
238
|
-
description: 'Use dedicated secret management system',
|
|
239
|
-
severity: 'HIGH',
|
|
240
|
-
fix: 'Implement HashiCorp Vault, AWS Secrets Manager, or similar secret vault',
|
|
241
|
-
documentationLink: 'https://cwe.mitre.org/data/definitions/798.html',
|
|
242
|
-
}),
|
|
243
|
-
strategyAuto: (0, eslint_devkit_1.formatLLMMessage)({
|
|
244
|
-
icon: eslint_devkit_1.MessageIcons.DEVELOPMENT,
|
|
245
|
-
issueName: 'Context-Aware Strategy',
|
|
246
|
-
description: 'Apply context-aware credential management',
|
|
247
|
-
severity: 'MEDIUM',
|
|
248
|
-
fix: 'Choose strategy based on deployment environment and security requirements',
|
|
249
|
-
documentationLink: 'https://owasp.org/www-project-cheat-sheets/cheatsheets/Secrets_Management_Cheat_Sheet.html',
|
|
250
|
-
}),
|
|
251
|
-
},
|
|
252
|
-
schema: [
|
|
253
|
-
{
|
|
254
|
-
type: 'object',
|
|
255
|
-
properties: {
|
|
256
|
-
ignorePatterns: {
|
|
257
|
-
type: 'array',
|
|
258
|
-
items: { type: 'string' },
|
|
259
|
-
default: [],
|
|
260
|
-
description: 'Regex patterns to ignore',
|
|
261
|
-
},
|
|
262
|
-
allowInTests: {
|
|
263
|
-
type: 'boolean',
|
|
264
|
-
default: false,
|
|
265
|
-
description: 'Allow credentials in test files',
|
|
266
|
-
},
|
|
267
|
-
minLength: {
|
|
268
|
-
type: 'number',
|
|
269
|
-
default: 8,
|
|
270
|
-
description: 'Minimum length for credential detection',
|
|
271
|
-
},
|
|
272
|
-
detectApiKeys: {
|
|
273
|
-
type: 'boolean',
|
|
274
|
-
default: true,
|
|
275
|
-
description: 'Detect API keys',
|
|
276
|
-
},
|
|
277
|
-
detectPasswords: {
|
|
278
|
-
type: 'boolean',
|
|
279
|
-
default: true,
|
|
280
|
-
description: 'Detect passwords',
|
|
281
|
-
},
|
|
282
|
-
detectTokens: {
|
|
283
|
-
type: 'boolean',
|
|
284
|
-
default: true,
|
|
285
|
-
description: 'Detect tokens',
|
|
286
|
-
},
|
|
287
|
-
detectDatabaseStrings: {
|
|
288
|
-
type: 'boolean',
|
|
289
|
-
default: true,
|
|
290
|
-
description: 'Detect database connection strings',
|
|
291
|
-
},
|
|
292
|
-
customPatterns: {
|
|
293
|
-
type: 'array',
|
|
294
|
-
items: {
|
|
295
|
-
type: 'object',
|
|
296
|
-
properties: {
|
|
297
|
-
type: {
|
|
298
|
-
type: 'string',
|
|
299
|
-
description: 'The type of credential (e.g., "API key", "token")',
|
|
300
|
-
},
|
|
301
|
-
pattern: {
|
|
302
|
-
type: 'string',
|
|
303
|
-
description: 'Regex pattern to match',
|
|
304
|
-
},
|
|
305
|
-
},
|
|
306
|
-
required: ['type', 'pattern'],
|
|
307
|
-
additionalProperties: false,
|
|
308
|
-
},
|
|
309
|
-
default: [],
|
|
310
|
-
description: 'Custom credential patterns to detect',
|
|
311
|
-
},
|
|
312
|
-
strategy: {
|
|
313
|
-
type: 'string',
|
|
314
|
-
enum: ['env', 'config', 'vault', 'auto'],
|
|
315
|
-
default: 'auto',
|
|
316
|
-
description: 'Strategy for fixing hardcoded credentials (auto = smart detection)'
|
|
317
|
-
},
|
|
318
|
-
allowPlaceholders: {
|
|
319
|
-
type: 'boolean',
|
|
320
|
-
default: true,
|
|
321
|
-
description: 'Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)',
|
|
322
|
-
},
|
|
323
|
-
},
|
|
324
|
-
additionalProperties: false,
|
|
325
|
-
},
|
|
326
|
-
],
|
|
327
|
-
},
|
|
328
|
-
defaultOptions: [
|
|
329
|
-
{
|
|
330
|
-
ignorePatterns: [],
|
|
331
|
-
allowInTests: false,
|
|
332
|
-
minLength: 8,
|
|
333
|
-
detectApiKeys: true,
|
|
334
|
-
detectPasswords: true,
|
|
335
|
-
detectTokens: true,
|
|
336
|
-
detectDatabaseStrings: true,
|
|
337
|
-
customPatterns: [],
|
|
338
|
-
strategy: 'auto',
|
|
339
|
-
allowPlaceholders: true,
|
|
340
|
-
},
|
|
341
|
-
],
|
|
342
|
-
create(context) {
|
|
343
|
-
const options = context.options[0] || {};
|
|
344
|
-
const { ignorePatterns = [], allowInTests = false, minLength = 8, detectApiKeys = true, detectPasswords = true, detectTokens = true, detectDatabaseStrings = true, customPatterns = [], allowPlaceholders = true, } = options;
|
|
345
|
-
const filename = context.filename;
|
|
346
|
-
const isTestFile = allowInTests && (filename.includes('.test.') ||
|
|
347
|
-
filename.includes('.spec.') ||
|
|
348
|
-
filename.includes('.fixture.') ||
|
|
349
|
-
filename.includes('.mock.') ||
|
|
350
|
-
filename.includes('__tests__') ||
|
|
351
|
-
filename.includes('__mocks__') ||
|
|
352
|
-
filename.includes('/test/') ||
|
|
353
|
-
filename.includes('/tests/') ||
|
|
354
|
-
filename.includes('/fixtures/') ||
|
|
355
|
-
filename.includes('/mocks/'));
|
|
356
|
-
const compiledIgnorePatterns = ignorePatterns.map((pattern) => new RegExp(pattern));
|
|
357
|
-
const detectionOptions = {
|
|
358
|
-
minLength,
|
|
359
|
-
detectApiKeys,
|
|
360
|
-
detectPasswords,
|
|
361
|
-
detectTokens,
|
|
362
|
-
detectDatabaseStrings,
|
|
363
|
-
customPatterns,
|
|
364
|
-
};
|
|
365
|
-
const LABEL_CONTEXT_NAMES = new Set([
|
|
366
|
-
'type', 'name', 'id', 'placeholder', 'label', 'title', 'role',
|
|
367
|
-
'autocomplete', 'autoFocus', 'autocapitalize', 'inputmode',
|
|
368
|
-
'aria-label', 'aria-labelledby', 'aria-describedby',
|
|
369
|
-
'fieldName', 'fieldType', 'fieldLabel', 'inputType', 'inputName',
|
|
370
|
-
'displayName', 'columnName', 'paramName',
|
|
371
|
-
'i18nKey', 'translationKey', 'messageKey',
|
|
372
|
-
]);
|
|
373
|
-
function isLabelContext(node, parent) {
|
|
374
|
-
if (!parent)
|
|
375
|
-
return false;
|
|
376
|
-
if (parent.type === 'ObjectExpression') {
|
|
377
|
-
const grand = parent.parent;
|
|
378
|
-
if (grand)
|
|
379
|
-
return isLabelContext(node, grand);
|
|
380
|
-
return false;
|
|
381
|
-
}
|
|
382
|
-
if (parent.type === 'ArrayExpression') {
|
|
383
|
-
const grand = parent.parent;
|
|
384
|
-
if (grand)
|
|
385
|
-
return isLabelContext(node, grand);
|
|
386
|
-
return false;
|
|
387
|
-
}
|
|
388
|
-
if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
|
|
389
|
-
const n = parent.id.name.toLowerCase();
|
|
390
|
-
if (LABEL_CONTEXT_NAMES.has(n) || n === 'labels' || n.endsWith('label') || n.endsWith('labels') || n.endsWith('name') || n.endsWith('placeholder'))
|
|
391
|
-
return true;
|
|
392
|
-
}
|
|
393
|
-
if (parent.type === 'AssignmentExpression' && parent.right === node) {
|
|
394
|
-
const left = parent.left;
|
|
395
|
-
if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
|
|
396
|
-
if (LABEL_CONTEXT_NAMES.has(left.property.name))
|
|
397
|
-
return true;
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
if (parent.type === 'Property' && parent.value === node) {
|
|
401
|
-
const key = parent.key;
|
|
402
|
-
if (key.type === 'Identifier' && LABEL_CONTEXT_NAMES.has(key.name))
|
|
403
|
-
return true;
|
|
404
|
-
if (key.type === 'Literal' && typeof key.value === 'string') {
|
|
405
|
-
if (LABEL_CONTEXT_NAMES.has(key.value))
|
|
406
|
-
return true;
|
|
407
|
-
}
|
|
408
|
-
const obj = parent.parent;
|
|
409
|
-
if (obj?.type === 'ObjectExpression') {
|
|
410
|
-
const grand = obj.parent;
|
|
411
|
-
if (grand)
|
|
412
|
-
return isLabelContext(node, grand);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
if (parent.type === 'CallExpression' &&
|
|
416
|
-
parent.callee.type === 'MemberExpression' &&
|
|
417
|
-
parent.callee.property.type === 'Identifier') {
|
|
418
|
-
const callee = parent.callee;
|
|
419
|
-
const methodName = callee.property.name;
|
|
420
|
-
if (methodName === 'setAttribute' || methodName === 'getAttribute') {
|
|
421
|
-
const args = parent.arguments;
|
|
422
|
-
if (args[1] === node)
|
|
423
|
-
return true;
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
if (parent.type === 'JSXAttribute')
|
|
427
|
-
return true;
|
|
428
|
-
return false;
|
|
429
|
-
}
|
|
430
|
-
function inferCredentialTypeFromContext(parent) {
|
|
431
|
-
const name = (() => {
|
|
432
|
-
if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
|
|
433
|
-
return parent.id.name.toLowerCase();
|
|
434
|
-
}
|
|
435
|
-
if (parent.type === 'Property') {
|
|
436
|
-
const key = parent.key;
|
|
437
|
-
if (key.type === 'Identifier')
|
|
438
|
-
return key.name.toLowerCase();
|
|
439
|
-
return String(key.value).toLowerCase();
|
|
440
|
-
}
|
|
441
|
-
if (parent.type === 'AssignmentExpression') {
|
|
442
|
-
const left = parent.left;
|
|
443
|
-
if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
|
|
444
|
-
return left.property.name.toLowerCase();
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
return '';
|
|
448
|
-
})();
|
|
449
|
-
if (/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))
|
|
450
|
-
return 'password';
|
|
451
|
-
if (/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))
|
|
452
|
-
return 'token';
|
|
453
|
-
if (/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))
|
|
454
|
-
return 'database';
|
|
455
|
-
if (/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))
|
|
456
|
-
return 'apikey';
|
|
457
|
-
return 'other';
|
|
458
|
-
}
|
|
459
|
-
function isCredentialContext(node, parent) {
|
|
460
|
-
if (!parent)
|
|
461
|
-
return false;
|
|
462
|
-
const matches = (name) => {
|
|
463
|
-
const lower = name.toLowerCase();
|
|
464
|
-
if (lower === 'key' || lower === 'keys') {
|
|
465
|
-
return node.type === 'Literal' && typeof node.value === 'string' && looksRandom(node.value);
|
|
466
|
-
}
|
|
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
|
-
if (parent.type === 'ArrayExpression') {
|
|
478
|
-
const grand = parent.parent;
|
|
479
|
-
if (grand)
|
|
480
|
-
return isCredentialContext(node, grand);
|
|
481
|
-
return false;
|
|
482
|
-
}
|
|
483
|
-
if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
|
|
484
|
-
if (matches(parent.id.name))
|
|
485
|
-
return true;
|
|
486
|
-
}
|
|
487
|
-
if (parent.type === 'AssignmentExpression' &&
|
|
488
|
-
parent.right === node) {
|
|
489
|
-
const left = parent.left;
|
|
490
|
-
if (left.type === 'MemberExpression' && left.property.type === 'Identifier') {
|
|
491
|
-
if (matches(left.property.name))
|
|
492
|
-
return true;
|
|
493
|
-
}
|
|
494
|
-
if (left.type === 'Identifier') {
|
|
495
|
-
if (matches(left.name))
|
|
496
|
-
return true;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
if (parent.type === 'Property' && parent.value === node) {
|
|
500
|
-
const key = parent.key;
|
|
501
|
-
if (key.type === 'Identifier' && matches(key.name))
|
|
502
|
-
return true;
|
|
503
|
-
if (key.type === 'Literal' && typeof key.value === 'string') {
|
|
504
|
-
if (matches(key.value))
|
|
505
|
-
return true;
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
return false;
|
|
509
|
-
}
|
|
510
|
-
function checkStringLiteral(node, parent) {
|
|
511
|
-
if (typeof node.value !== 'string') {
|
|
512
|
-
return;
|
|
513
|
-
}
|
|
514
|
-
const value = node.value;
|
|
515
|
-
if (isTestFile) {
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
if (parent?.type === 'LogicalExpression' &&
|
|
519
|
-
parent.operator === '||' &&
|
|
520
|
-
parent.right === node) {
|
|
521
|
-
const left = parent.left;
|
|
522
|
-
if (left.type === 'MemberExpression' &&
|
|
523
|
-
left.object.type === 'MemberExpression' &&
|
|
524
|
-
left.object.object.type === 'Identifier' &&
|
|
525
|
-
left.object.object.name === 'process' &&
|
|
526
|
-
left.object.property.type === 'Identifier' &&
|
|
527
|
-
left.object.property.name === 'env') {
|
|
528
|
-
return;
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
if (isLabelContext(node, parent)) {
|
|
532
|
-
return;
|
|
533
|
-
}
|
|
534
|
-
const { isCredential, type, confidence } = looksLikeCredential(value, detectionOptions, compiledIgnorePatterns);
|
|
535
|
-
let finalIsCredential = isCredential;
|
|
536
|
-
let finalType = type;
|
|
537
|
-
if (isCredential && confidence === 'ambiguous' && !isCredentialContext(node, parent)) {
|
|
538
|
-
finalIsCredential = false;
|
|
539
|
-
}
|
|
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) &&
|
|
548
|
-
isCredentialContext(node, parent)) {
|
|
549
|
-
const ctxType = inferCredentialTypeFromContext(parent);
|
|
550
|
-
const optionAllows = (ctxType === 'password' && detectionOptions.detectPasswords) ||
|
|
551
|
-
(ctxType === 'token' && detectionOptions.detectTokens) ||
|
|
552
|
-
(ctxType === 'database' && detectionOptions.detectDatabaseStrings) ||
|
|
553
|
-
(ctxType === 'apikey' && detectionOptions.detectApiKeys) ||
|
|
554
|
-
ctxType === 'other';
|
|
555
|
-
if (optionAllows) {
|
|
556
|
-
finalIsCredential = true;
|
|
557
|
-
finalType = type || 'Credential value';
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
if (!finalIsCredential) {
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
let envVarName = 'API_KEY';
|
|
564
|
-
if (parent && parent.type === 'Property' && parent.key.type === 'Identifier') {
|
|
565
|
-
const keyName = parent.key.name;
|
|
566
|
-
envVarName = keyName
|
|
567
|
-
.replace(/([a-z])([A-Z])/g, '$1_$2')
|
|
568
|
-
.toUpperCase()
|
|
569
|
-
.replace(/[^A-Z0-9_]/g, '_');
|
|
570
|
-
}
|
|
571
|
-
else if (parent && parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') {
|
|
572
|
-
const varName = parent.id.name;
|
|
573
|
-
envVarName = varName
|
|
574
|
-
.replace(/([a-z])([A-Z])/g, '$1_$2')
|
|
575
|
-
.toUpperCase()
|
|
576
|
-
.replace(/[^A-Z0-9_]/g, '_');
|
|
577
|
-
}
|
|
578
|
-
context.report({
|
|
579
|
-
node,
|
|
580
|
-
messageId: 'useEnvironmentVariable',
|
|
581
|
-
data: {
|
|
582
|
-
credentialType: finalType,
|
|
583
|
-
envVarName,
|
|
584
|
-
},
|
|
585
|
-
suggest: [
|
|
586
|
-
{
|
|
587
|
-
messageId: 'useEnvironmentVariable',
|
|
588
|
-
data: { envVarName, credentialType: finalType },
|
|
589
|
-
fix: (fixer) => {
|
|
590
|
-
return fixer.replaceText(node, `process.env.${envVarName} || '${value}'`);
|
|
591
|
-
},
|
|
592
|
-
},
|
|
593
|
-
{
|
|
594
|
-
messageId: 'useSecretManager',
|
|
595
|
-
data: { credentialType: finalType },
|
|
596
|
-
fix: (fixer) => {
|
|
597
|
-
return fixer.replaceText(node, `await getSecret('${envVarName.toLowerCase()}')`);
|
|
598
|
-
},
|
|
599
|
-
},
|
|
600
|
-
],
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
return {
|
|
604
|
-
Literal(node) {
|
|
605
|
-
checkStringLiteral(node, node.parent);
|
|
606
|
-
},
|
|
607
|
-
TemplateLiteral(node) {
|
|
608
|
-
if (node.expressions.length === 0) {
|
|
609
|
-
const fullText = node.quasis.map((q) => q.value.raw).join('');
|
|
610
|
-
const { isCredential, type, confidence } = looksLikeCredential(fullText, detectionOptions, compiledIgnorePatterns);
|
|
611
|
-
if (isCredential && !isTestFile && confidence === 'structural') {
|
|
612
|
-
context.report({
|
|
613
|
-
node,
|
|
614
|
-
messageId: 'useEnvironmentVariable',
|
|
615
|
-
data: {
|
|
616
|
-
credentialType: type,
|
|
617
|
-
envVarName: 'API_KEY',
|
|
618
|
-
},
|
|
619
|
-
suggest: [
|
|
620
|
-
{
|
|
621
|
-
messageId: 'useEnvironmentVariable',
|
|
622
|
-
data: { envVarName: 'API_KEY', credentialType: type },
|
|
623
|
-
fix: (fixer) => {
|
|
624
|
-
return fixer.replaceText(node, `process.env.API_KEY || \`${fullText}\``);
|
|
625
|
-
},
|
|
626
|
-
},
|
|
627
|
-
{
|
|
628
|
-
messageId: 'useSecretManager',
|
|
629
|
-
data: { credentialType: type },
|
|
630
|
-
fix: (fixer) => {
|
|
631
|
-
return fixer.replaceText(node, `await getSecret('api_key')`);
|
|
632
|
-
},
|
|
633
|
-
},
|
|
634
|
-
],
|
|
635
|
-
});
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
else {
|
|
639
|
-
for (const quasi of node.quasis) {
|
|
640
|
-
if (quasi.value.raw) {
|
|
641
|
-
const { isCredential, type, confidence } = looksLikeCredential(quasi.value.raw, detectionOptions, compiledIgnorePatterns);
|
|
642
|
-
if (isCredential && !isTestFile && confidence === 'structural') {
|
|
643
|
-
context.report({
|
|
644
|
-
node: quasi,
|
|
645
|
-
messageId: 'useEnvironmentVariable',
|
|
646
|
-
data: {
|
|
647
|
-
credentialType: type,
|
|
648
|
-
envVarName: 'API_KEY',
|
|
649
|
-
},
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
},
|
|
656
|
-
};
|
|
657
|
-
},
|
|
658
|
-
});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z_\-. ]*$/.test(value))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const PLACEHOLDER_WORDS=new Set(["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"]);function isPlaceholderValue(value){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>PLACEHOLDER_WORDS.has(token))}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyEnv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Environment Variable Strategy",description:"Move credentials to environment variables",severity:"MEDIUM",fix:"Store credentials in environment variables (process.env)",documentationLink:"https://12factor.net/config"}),strategyConfig:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Configuration File Strategy",description:"Store credentials in encrypted configuration files",severity:"MEDIUM",fix:"Use encrypted configuration files with proper access controls",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Configuration_Management_Cheat_Sheet.html"}),strategyVault:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Secret Vault Strategy",cwe:"CWE-798",description:"Use dedicated secret management system",severity:"HIGH",fix:"Implement HashiCorp Vault, AWS Secrets Manager, or similar secret vault",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyAuto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Context-Aware Strategy",description:"Apply context-aware credential management",severity:"MEDIUM",fix:"Choose strategy based on deployment environment and security requirements",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Secrets_Management_Cheat_Sheet.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:false,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},strategy:{type:"string",enum:["env","config","vault","auto"],default:"auto",description:"Strategy for fixing hardcoded credentials (auto = smart detection)"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:false,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],strategy:"auto",allowPlaceholders:true}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=false,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true}=options;const filename=context.filename;const isTestFile=allowInTests&&(filename.includes(".test.")||filename.includes(".spec.")||filename.includes(".fixture.")||filename.includes(".mock.")||filename.includes("__tests__")||filename.includes("__mocks__")||filename.includes("/test/")||filename.includes("/tests/")||filename.includes("/fixtures/")||filename.includes("/mocks/"));const compiledIgnorePatterns=ignorePatterns.map(pattern=>new RegExp(pattern));const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=(()=>{if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""})();if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
|