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.
Files changed (33) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -3
  3. package/src/index.js +1 -107
  4. package/src/oxlint.js +1 -3
  5. package/src/rules/detect-non-literal-regexp/index.js +1 -329
  6. package/src/rules/detect-object-injection/index.js +1 -691
  7. package/src/rules/detect-weak-password-validation/index.js +1 -54
  8. package/src/rules/no-directive-injection/index.js +1 -416
  9. package/src/rules/no-electron-security-issues/index.js +1 -385
  10. package/src/rules/no-format-string-injection/index.js +1 -565
  11. package/src/rules/no-graphql-injection/index.js +1 -612
  12. package/src/rules/no-hardcoded-credentials/index.js +1 -658
  13. package/src/rules/no-hardcoded-session-tokens/index.js +1 -56
  14. package/src/rules/no-improper-sanitization/index.js +1 -391
  15. package/src/rules/no-improper-type-validation/index.js +1 -422
  16. package/src/rules/no-insecure-comparison/index.js +1 -249
  17. package/src/rules/no-ldap-injection/index.js +1 -403
  18. package/src/rules/no-missing-authentication/index.js +1 -282
  19. package/src/rules/no-pii-in-logs/index.js +1 -63
  20. package/src/rules/no-privilege-escalation/index.js +1 -282
  21. package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
  22. package/src/rules/no-sensitive-data-exposure/index.js +1 -249
  23. package/src/rules/no-template-injection/index.js +1 -84
  24. package/src/rules/no-unchecked-loop-condition/index.js +1 -541
  25. package/src/rules/no-unlimited-resource-allocation/index.js +1 -555
  26. package/src/rules/no-unsafe-deserialization/index.js +1 -497
  27. package/src/rules/no-unsafe-regex-construction/index.js +1 -275
  28. package/src/rules/no-weak-password-recovery/index.js +1 -382
  29. package/src/rules/no-xpath-injection/index.js +1 -431
  30. package/src/rules/no-xxe-injection/index.js +1 -230
  31. package/src/rules/require-backend-authorization/index.js +1 -58
  32. package/src/rules/require-secure-defaults/index.js +1 -41
  33. package/src/types/index.js +1 -2
@@ -1,497 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.noUnsafeDeserialization = void 0;
4
- const eslint_devkit_1 = require("@interlace/eslint-devkit");
5
- const eslint_devkit_2 = require("@interlace/eslint-devkit");
6
- const eslint_devkit_3 = require("@interlace/eslint-devkit");
7
- const TIMER_FUNCTIONS = new Set(['setTimeout', 'setInterval']);
8
- function isStringValued(arg) {
9
- if (!arg)
10
- return false;
11
- if (arg.type === 'Literal')
12
- return typeof arg.value === 'string';
13
- if (arg.type === 'TemplateLiteral')
14
- return true;
15
- if (arg.type === 'BinaryExpression' && arg.operator === '+') {
16
- return isStringValued(arg.left) || isStringValued(arg.right);
17
- }
18
- return false;
19
- }
20
- exports.noUnsafeDeserialization = (0, eslint_devkit_1.createRule)({
21
- name: 'no-unsafe-deserialization',
22
- meta: {
23
- type: 'problem',
24
- docs: {
25
- url: 'https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md',
26
- description: 'Detects unsafe deserialization of untrusted data',
27
- cwe: 'CWE-502',
28
- },
29
- fixable: 'code',
30
- hasSuggestions: true,
31
- messages: {
32
- unsafeDeserialization: (0, eslint_devkit_2.formatLLMMessage)({
33
- icon: eslint_devkit_2.MessageIcons.SECURITY,
34
- issueName: 'Unsafe Deserialization',
35
- cwe: 'CWE-502',
36
- description: 'Unsafe deserialization of untrusted data (incl. model/tool output)',
37
- severity: '{{severity}}',
38
- fix: '{{safeAlternative}} | validate model/tool output via schema and size limits',
39
- documentationLink: 'https://cwe.mitre.org/data/definitions/502.html',
40
- }),
41
- dangerousEvalUsage: (0, eslint_devkit_2.formatLLMMessage)({
42
- icon: eslint_devkit_2.MessageIcons.SECURITY,
43
- issueName: 'Dangerous eval() Usage',
44
- cwe: 'CWE-502',
45
- description: 'eval() used for deserialization (code execution vulnerability)',
46
- severity: 'CRITICAL',
47
- fix: 'Use JSON.parse() or safe deserialization libraries',
48
- documentationLink: 'https://cwe.mitre.org/data/definitions/502.html',
49
- }),
50
- unsafeYamlParsing: (0, eslint_devkit_2.formatLLMMessage)({
51
- icon: eslint_devkit_2.MessageIcons.SECURITY,
52
- issueName: 'Unsafe YAML Parsing',
53
- cwe: 'CWE-502',
54
- description: 'YAML parsing may execute code during deserialization',
55
- severity: 'HIGH',
56
- fix: 'Use yaml.safeLoad() or disable code execution',
57
- documentationLink: 'https://www.npmjs.com/package/js-yaml#loadstr---options-',
58
- }),
59
- dangerousFunctionConstructor: (0, eslint_devkit_2.formatLLMMessage)({
60
- icon: eslint_devkit_2.MessageIcons.SECURITY,
61
- issueName: 'Dangerous Function Constructor',
62
- cwe: 'CWE-502',
63
- description: 'Function constructor used with untrusted data',
64
- severity: 'CRITICAL',
65
- fix: 'Avoid Function constructor with user input',
66
- documentationLink: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function',
67
- }),
68
- untrustedDeserializationInput: (0, eslint_devkit_2.formatLLMMessage)({
69
- icon: eslint_devkit_2.MessageIcons.SECURITY,
70
- issueName: 'Untrusted Deserialization Input',
71
- cwe: 'CWE-502',
72
- description: 'Deserializing untrusted input (incl. LLM/MCP responses) without validation',
73
- severity: 'HIGH',
74
- fix: 'Schema-validate and size-cap before deserialization; reject unknown fields',
75
- documentationLink: 'https://cwe.mitre.org/data/definitions/502.html',
76
- }),
77
- useSafeDeserializer: (0, eslint_devkit_2.formatLLMMessage)({
78
- icon: eslint_devkit_2.MessageIcons.INFO,
79
- issueName: 'Use Safe Deserializer',
80
- description: 'Use safe deserialization libraries',
81
- severity: 'LOW',
82
- fix: 'Use JSON.parse, safe-json-parse, or validated libraries',
83
- documentationLink: 'https://www.npmjs.com/package/safe-json-parse',
84
- }),
85
- validateBeforeDeserialization: (0, eslint_devkit_2.formatLLMMessage)({
86
- icon: eslint_devkit_2.MessageIcons.INFO,
87
- issueName: 'Validate Before Deserialization',
88
- description: 'Validate input before deserialization',
89
- severity: 'LOW',
90
- fix: 'Implement input validation and length limits',
91
- documentationLink: 'https://cwe.mitre.org/data/definitions/502.html',
92
- }),
93
- avoidEval: (0, eslint_devkit_2.formatLLMMessage)({
94
- icon: eslint_devkit_2.MessageIcons.INFO,
95
- issueName: 'Avoid eval()',
96
- description: 'Never use eval() for deserialization',
97
- severity: 'LOW',
98
- fix: 'Use JSON.parse() for data, vm.Script for code when absolutely necessary',
99
- documentationLink: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval',
100
- }),
101
- strategySafeLibraries: (0, eslint_devkit_2.formatLLMMessage)({
102
- icon: eslint_devkit_2.MessageIcons.STRATEGY,
103
- issueName: 'Safe Libraries Strategy',
104
- description: 'Use deserialization libraries with built-in safety',
105
- severity: 'LOW',
106
- fix: 'Use JSON.parse, js-yaml.safeLoad, or protobuf libraries',
107
- documentationLink: 'https://www.npmjs.com/package/js-yaml',
108
- }),
109
- strategyInputValidation: (0, eslint_devkit_2.formatLLMMessage)({
110
- icon: eslint_devkit_2.MessageIcons.STRATEGY,
111
- issueName: 'Input Validation Strategy',
112
- description: 'Validate input before any deserialization',
113
- severity: 'LOW',
114
- fix: 'Implement schema validation and length limits',
115
- documentationLink: 'https://cwe.mitre.org/data/definitions/502.html',
116
- }),
117
- strategySandboxing: (0, eslint_devkit_2.formatLLMMessage)({
118
- icon: eslint_devkit_2.MessageIcons.STRATEGY,
119
- issueName: 'Sandboxing Strategy',
120
- description: 'Execute deserialization in sandboxed environment',
121
- severity: 'LOW',
122
- fix: 'Use vm module or worker threads for untrusted deserialization',
123
- documentationLink: 'https://nodejs.org/api/vm.html',
124
- })
125
- },
126
- schema: [
127
- {
128
- type: 'object',
129
- properties: {
130
- dangerousFunctions: {
131
- type: 'array',
132
- items: { type: 'string' },
133
- default: ['eval', 'Function', 'setTimeout', 'setInterval', 'unserialize', 'deserialize', 'parseUnsafe'], description: 'Functions that execute or deserialize untrusted input'
134
- },
135
- safeLibraries: {
136
- type: 'array',
137
- items: { type: 'string' },
138
- default: ['JSON', 'safe-json-parse', 'js-yaml.safeLoad', 'protobuf', 'msgpack'], description: 'Parsers that do not execute their input'
139
- },
140
- validationFunctions: {
141
- type: 'array',
142
- items: { type: 'string' },
143
- default: ['validateInput', 'sanitizeData', 'checkSchema', 'validateSchema'], description: 'Function names that count as input validation'
144
- },
145
- trustedSanitizers: {
146
- type: 'array',
147
- items: { type: 'string' },
148
- default: [],
149
- description: 'Additional function names to consider as safe deserializers',
150
- },
151
- trustedAnnotations: {
152
- type: 'array',
153
- items: { type: 'string' },
154
- default: [],
155
- description: 'Additional JSDoc annotations to consider as safe markers',
156
- },
157
- strictMode: {
158
- type: 'boolean',
159
- default: false,
160
- description: 'Disable all false positive detection (strict mode)',
161
- },
162
- },
163
- additionalProperties: false,
164
- },
165
- ],
166
- },
167
- defaultOptions: [
168
- {
169
- dangerousFunctions: ['eval', 'Function', 'setTimeout', 'setInterval', 'unserialize', 'deserialize', 'parseUnsafe'],
170
- safeLibraries: ['JSON', 'safe-json-parse', 'js-yaml.safeLoad', 'protobuf', 'msgpack'],
171
- validationFunctions: ['validateInput', 'sanitizeData', 'checkSchema', 'validateSchema'],
172
- trustedSanitizers: [],
173
- trustedAnnotations: [],
174
- strictMode: false,
175
- },
176
- ],
177
- create(context) {
178
- const options = context.options[0] || {};
179
- const { dangerousFunctions = ['eval', 'Function', 'setTimeout', 'setInterval', 'unserialize', 'deserialize', 'parseUnsafe'], validationFunctions = ['validateInput', 'sanitizeData', 'checkSchema', 'validateSchema'], trustedSanitizers = [], trustedAnnotations = [], strictMode = false, } = options;
180
- const sourceCode = context.sourceCode;
181
- const filename = context.filename;
182
- const safetyChecker = (0, eslint_devkit_3.createSafetyChecker)({
183
- trustedSanitizers,
184
- trustedAnnotations,
185
- trustedOrmPatterns: [],
186
- strictMode,
187
- });
188
- const validatedVariables = new Set();
189
- const untrustedVariables = new Set();
190
- const literalPathFileVars = new Set();
191
- const isDangerousDeserialization = (node) => {
192
- const callee = node.callee;
193
- if (callee.type === 'Identifier' && dangerousFunctions.includes(callee.name)) {
194
- if (TIMER_FUNCTIONS.has(callee.name)) {
195
- return isStringValued(node.arguments[0]);
196
- }
197
- return true;
198
- }
199
- if (callee.type === 'MemberExpression') {
200
- const memberName = callee.property.type === 'Identifier' ? callee.property.name : '';
201
- const objectName = callee.object.type === 'Identifier' ? callee.object.name : '';
202
- if (callee.object.type === 'Super' || callee.object.type === 'ThisExpression') {
203
- return false;
204
- }
205
- if (TIMER_FUNCTIONS.has(memberName)) {
206
- return isStringValued(node.arguments[0]);
207
- }
208
- if (dangerousFunctions.includes(memberName)) {
209
- return true;
210
- }
211
- if (['yaml', 'js-yaml', 'node-serialize', 'serialize-javascript'].includes(objectName.toLowerCase()) &&
212
- ['load', 'parse', 'unserialize', 'deserialize'].includes(memberName)) {
213
- return true;
214
- }
215
- }
216
- if (callee.type === 'Identifier' && callee.name === 'require') {
217
- const args = node.arguments;
218
- if (args.length > 0 && args[0].type === 'Literal' && typeof args[0].value === 'string') {
219
- const moduleName = args[0].value.toLowerCase();
220
- if (['node-serialize', 'serialize-javascript', 'yaml', 'js-yaml'].includes(moduleName)) {
221
- return true;
222
- }
223
- }
224
- }
225
- return false;
226
- };
227
- const isUntrustedInput = (inputNode) => {
228
- if (inputNode.type === 'BinaryExpression' && inputNode.operator === '+') {
229
- return isUntrustedInput(inputNode.left) || isUntrustedInput(inputNode.right);
230
- }
231
- if (inputNode.type === 'TemplateLiteral') {
232
- return inputNode.expressions.some((e) => isUntrustedInput(e));
233
- }
234
- if (inputNode.type === 'MemberExpression') {
235
- if (inputNode.object.type === 'Identifier' && inputNode.object.name === 'req') {
236
- return true;
237
- }
238
- if (inputNode.object.type === 'MemberExpression' &&
239
- inputNode.object.object.type === 'Identifier' &&
240
- inputNode.object.object.name === 'req') {
241
- return true;
242
- }
243
- }
244
- if (inputNode.type === 'Identifier') {
245
- if (untrustedVariables.has(inputNode.name)) {
246
- return true;
247
- }
248
- let current = inputNode;
249
- while (current) {
250
- if (current.type === 'FunctionDeclaration' ||
251
- current.type === 'FunctionExpression' ||
252
- current.type === 'ArrowFunctionExpression') {
253
- const func = current;
254
- if (func.params.some((param) => {
255
- if (param.type === 'Identifier') {
256
- return param.name === inputNode.name;
257
- }
258
- return false;
259
- })) {
260
- return true;
261
- }
262
- }
263
- current = current.parent;
264
- }
265
- }
266
- return false;
267
- };
268
- const isInputValidated = (inputNode) => {
269
- let current = inputNode;
270
- while (current) {
271
- if (current.type === 'CallExpression' &&
272
- current.callee.type === 'Identifier' &&
273
- validationFunctions.includes(current.callee.name)) {
274
- return true;
275
- }
276
- current = current.parent;
277
- }
278
- return false;
279
- };
280
- const isSafeLibrary = (node) => {
281
- const callee = node.callee;
282
- if (callee.type === 'MemberExpression') {
283
- const objectName = callee.object.type === 'Identifier' ? callee.object.name : '';
284
- const memberName = callee.property.type === 'Identifier' ? callee.property.name : '';
285
- if (objectName === 'JSON' && memberName === 'parse') {
286
- return true;
287
- }
288
- if (objectName === 'yaml' && memberName === 'safeLoad') {
289
- return true;
290
- }
291
- }
292
- return false;
293
- };
294
- const isInsideDeserializerImplementation = (node) => {
295
- const DESERIALIZER_NAMES = new Set(['deserialize', 'unserialize', 'fromJSON', 'fromBuffer']);
296
- let current = node.parent;
297
- while (current) {
298
- if (current.type === 'FunctionDeclaration' ||
299
- current.type === 'FunctionExpression' ||
300
- current.type === 'ArrowFunctionExpression') {
301
- const fn = current;
302
- if ('id' in fn && fn.id?.name && DESERIALIZER_NAMES.has(fn.id.name))
303
- return true;
304
- const owner = fn.parent;
305
- if (owner?.type === 'MethodDefinition' && owner.key.type === 'Identifier' &&
306
- DESERIALIZER_NAMES.has(owner.key.name))
307
- return true;
308
- if (owner?.type === 'Property' && owner.key.type === 'Identifier' &&
309
- DESERIALIZER_NAMES.has(owner.key.name))
310
- return true;
311
- if (owner?.type === 'VariableDeclarator' && owner.id.type === 'Identifier' &&
312
- DESERIALIZER_NAMES.has(owner.id.name))
313
- return true;
314
- }
315
- current = current.parent;
316
- }
317
- return false;
318
- };
319
- const checkCallExpression = (node) => {
320
- if ((node.type === 'NewExpression' || node.type === 'CallExpression') &&
321
- node.callee.type === 'Identifier' &&
322
- node.callee.name === 'Function') {
323
- const args = node.arguments;
324
- const hasUntrustedInput = args.some((arg) => isUntrustedInput(arg));
325
- if (hasUntrustedInput) {
326
- if (safetyChecker.isSafe(node, context))
327
- return;
328
- context.report({
329
- node,
330
- messageId: 'dangerousFunctionConstructor',
331
- data: {
332
- filePath: context.filename,
333
- line: String(node.loc?.start.line ?? 0),
334
- severity: 'HIGH',
335
- safeAlternative: 'Avoid dynamic function creation',
336
- }
337
- });
338
- return;
339
- }
340
- }
341
- if (isDangerousDeserialization(node) && !isInsideDeserializerImplementation(node)) {
342
- const args = node.arguments;
343
- const hasUntrustedInput = args.some((arg) => isUntrustedInput(arg));
344
- const isSafe = isSafeLibrary(node);
345
- if (!isSafe && hasUntrustedInput) {
346
- const safe = safetyChecker.isSafe(node, context);
347
- if (!safe) {
348
- let messageId = 'unsafeDeserialization';
349
- const calleeText = sourceCode.getText(node.callee);
350
- if (calleeText.includes('yaml') || calleeText.includes('YAML')) {
351
- messageId = 'unsafeYamlParsing';
352
- }
353
- if (node.callee.type === 'Identifier' && ['eval', 'setTimeout', 'setInterval'].includes(node.callee.name)) {
354
- messageId = 'dangerousEvalUsage';
355
- }
356
- context.report({
357
- node,
358
- messageId,
359
- data: {
360
- library: calleeText,
361
- filePath: filename,
362
- line: String(node.loc?.start.line ?? 0),
363
- severity: 'HIGH',
364
- safeAlternative: 'Use JSON.parse() or validated safe deserialization libraries',
365
- },
366
- suggest: messageId === 'dangerousEvalUsage' ? [{
367
- messageId: 'useSafeDeserializer',
368
- fix: (fixer) => {
369
- return fixer.replaceText(node, `JSON.parse(${sourceCode.getText(node.arguments[0])})`);
370
- }
371
- }] : undefined
372
- });
373
- }
374
- }
375
- }
376
- if (isSafeLibrary(node)) {
377
- const args = node.arguments;
378
- const hasUntrustedInput = args.some((arg) => {
379
- if (arg.type === 'Identifier' && validatedVariables.has(arg.name)) {
380
- return false;
381
- }
382
- if (arg.type === 'Identifier' && literalPathFileVars.has(arg.name)) {
383
- return false;
384
- }
385
- return isUntrustedInput(arg) && !isInputValidated(arg);
386
- });
387
- if (hasUntrustedInput) {
388
- if (safetyChecker.isSafe(node, context)) {
389
- return;
390
- }
391
- context.report({
392
- node,
393
- messageId: 'untrustedDeserializationInput',
394
- data: {
395
- filePath: context.filename,
396
- line: String(node.loc?.start.line ?? 0),
397
- },
398
- suggest: [
399
- {
400
- messageId: 'validateBeforeDeserialization',
401
- fix: () => null
402
- },
403
- ],
404
- });
405
- }
406
- }
407
- };
408
- return {
409
- VariableDeclaration(node) {
410
- for (const declarator of node.declarations) {
411
- if (declarator.id.type === 'Identifier' && declarator.init) {
412
- if (isUntrustedInput(declarator.init)) {
413
- untrustedVariables.add(declarator.id.name);
414
- }
415
- if (declarator.init.type === 'CallExpression') {
416
- const callee = declarator.init.callee;
417
- if (callee.type === 'MemberExpression' &&
418
- callee.object.type === 'Identifier' &&
419
- callee.object.name === 'fs' &&
420
- callee.property.type === 'Identifier' &&
421
- ['readFile', 'readFileSync'].includes(callee.property.name)) {
422
- untrustedVariables.add(declarator.id.name);
423
- const pathArg = declarator.init.arguments[0];
424
- if (pathArg?.type === 'Literal' && typeof pathArg.value === 'string') {
425
- literalPathFileVars.add(declarator.id.name);
426
- }
427
- }
428
- }
429
- }
430
- }
431
- },
432
- AssignmentExpression(node) {
433
- if (node.left.type === 'Identifier' && isUntrustedInput(node.right)) {
434
- untrustedVariables.add(node.left.name);
435
- }
436
- },
437
- CallExpression(node) {
438
- checkCallExpression(node);
439
- },
440
- NewExpression(node) {
441
- checkCallExpression(node);
442
- },
443
- VariableDeclarator(node) {
444
- if (!node.init) {
445
- return;
446
- }
447
- if (node.id.type === 'Identifier' &&
448
- node.init.type === 'CallExpression' &&
449
- node.init.callee.type === 'Identifier' &&
450
- (validationFunctions.includes(node.init.callee.name) || trustedSanitizers.includes(node.init.callee.name))) {
451
- validatedVariables.add(node.id.name);
452
- }
453
- if (node.init.type === 'CallExpression' &&
454
- node.init.callee.type === 'Identifier' &&
455
- node.init.callee.name === 'require') {
456
- const requireArg = node.init.arguments[0];
457
- if (requireArg?.type === 'Literal' && typeof requireArg.value === 'string') {
458
- const moduleName = requireArg.value;
459
- if (['node-serialize', 'serialize-javascript', 'js-yaml', 'yaml'].includes(moduleName)) {
460
- if (node.id.type === 'Identifier') {
461
- const variables = sourceCode.getDeclaredVariables(node);
462
- for (const variable of variables) {
463
- for (const reference of variable.references) {
464
- const refNode = reference.identifier;
465
- if (refNode.parent && refNode.parent.type === 'MemberExpression' &&
466
- refNode.parent.object === refNode) {
467
- const memberExpr = refNode.parent;
468
- const propertyName = memberExpr.property.type === 'Identifier' ? memberExpr.property.name : '';
469
- if (['unserialize', 'deserialize', 'load', 'parse'].includes(propertyName)) {
470
- const callExpr = memberExpr.parent;
471
- if (callExpr && callExpr.type === 'CallExpression' && callExpr.callee === memberExpr) {
472
- if (safetyChecker.isSafe(callExpr, context)) {
473
- continue;
474
- }
475
- context.report({
476
- node: callExpr,
477
- messageId: 'unsafeDeserialization',
478
- data: {
479
- filePath: filename,
480
- line: String(callExpr.loc?.start.line ?? 0),
481
- severity: 'CRITICAL',
482
- safeAlternative: 'Avoid using this library or use safe alternatives',
483
- },
484
- });
485
- }
486
- }
487
- }
488
- }
489
- }
490
- }
491
- }
492
- }
493
- }
494
- }
495
- };
496
- },
497
- });
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),untrustedDeserializationInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted Deserialization Input",cwe:"CWE-502",description:"Deserializing untrusted input (incl. LLM/MCP responses) without validation",severity:"HIGH",fix:"Schema-validate and size-cap before deserialization; reject unknown fields",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"}),validateBeforeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Before Deserialization",description:"Validate input before deserialization",severity:"LOW",fix:"Implement input validation and length limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),avoidEval:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Avoid eval()",description:"Never use eval() for deserialization",severity:"LOW",fix:"Use JSON.parse() for data, vm.Script for code when absolutely necessary",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"}),strategySafeLibraries:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Safe Libraries Strategy",description:"Use deserialization libraries with built-in safety",severity:"LOW",fix:"Use JSON.parse, js-yaml.safeLoad, or protobuf libraries",documentationLink:"https://www.npmjs.com/package/js-yaml"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate input before any deserialization",severity:"LOW",fix:"Implement schema validation and length limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),strategySandboxing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Sandboxing Strategy",description:"Execute deserialization in sandboxed environment",severity:"LOW",fix:"Use vm module or worker threads for untrusted deserialization",documentationLink:"https://nodejs.org/api/vm.html"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},safeLibraries:{type:"array",items:{type:"string"},default:["JSON","safe-json-parse","js-yaml.safeLoad","protobuf","msgpack"],description:"Parsers that do not execute their input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],safeLibraries:["JSON","safe-json-parse","js-yaml.safeLoad","protobuf","msgpack"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;const untrustedVariables=new Set;const literalPathFileVars=new Set;const isDangerousDeserialization=node=>{const callee=node.callee;if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}return true}if(callee.type==="MemberExpression"){const memberName=callee.property.type==="Identifier"?callee.property.name:"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isSafeLibrary=node=>{const callee=node.callee;if(callee.type==="MemberExpression"){const objectName=callee.object.type==="Identifier"?callee.object.name:"";const memberName=callee.property.type==="Identifier"?callee.property.name:"";if(objectName==="JSON"&&memberName==="parse"){return true}if(objectName==="yaml"&&memberName==="safeLoad"){return true}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));const isSafe=isSafeLibrary(node);if(!isSafe&&hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}if(isSafeLibrary(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>{if(arg.type==="Identifier"&&validatedVariables.has(arg.name)){return false}if(arg.type==="Identifier"&&literalPathFileVars.has(arg.name)){return false}return isUntrustedInput(arg)&&!isInputValidated(arg)});if(hasUntrustedInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"untrustedDeserializationInput",data:{filePath:context.filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"validateBeforeDeserialization",fix:()=>null}]})}}};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","readFileSync"].includes(callee.property.name)){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"){const requireArg=node.init.arguments[0];if(requireArg?.type==="Literal"&&typeof requireArg.value==="string"){const moduleName=requireArg.value;if(["node-serialize","serialize-javascript","js-yaml","yaml"].includes(moduleName)){if(node.id.type==="Identifier"){const variables=sourceCode.getDeclaredVariables(node);for(const variable of variables){for(const reference of variable.references){const refNode=reference.identifier;if(refNode.parent&&refNode.parent.type==="MemberExpression"&&refNode.parent.object===refNode){const memberExpr=refNode.parent;const propertyName=memberExpr.property.type==="Identifier"?memberExpr.property.name:"";if(["unserialize","deserialize","load","parse"].includes(propertyName)){const callExpr=memberExpr.parent;if(callExpr&&callExpr.type==="CallExpression"&&callExpr.callee===memberExpr){if(safetyChecker.isSafe(callExpr,context)){continue}context.report({node:callExpr,messageId:"unsafeDeserialization",data:{filePath:filename,line:String(callExpr.loc?.start.line??0),severity:"CRITICAL",safeAlternative:"Avoid using this library or use safe alternatives"}})}}}}}}}}}}}}});