vibe-guard 1.1.4 → 1.2.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 (140) hide show
  1. package/README.md +163 -283
  2. package/dist/bin/vibe-guard.js +240 -22
  3. package/dist/bin/vibe-guard.js.map +1 -1
  4. package/dist/config.d.ts +0 -18
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +5 -26
  7. package/dist/config.js.map +1 -1
  8. package/dist/index.d.ts +0 -6
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +5 -8
  11. package/dist/index.js.map +1 -1
  12. package/dist/reporter.d.ts.map +1 -1
  13. package/dist/reporter.js +41 -19
  14. package/dist/reporter.js.map +1 -1
  15. package/dist/rules/ai-agent-access-control.d.ts +27 -2
  16. package/dist/rules/ai-agent-access-control.d.ts.map +1 -1
  17. package/dist/rules/ai-agent-access-control.js +393 -19
  18. package/dist/rules/ai-agent-access-control.js.map +1 -1
  19. package/dist/rules/ai-data-leakage-prevention.d.ts +25 -2
  20. package/dist/rules/ai-data-leakage-prevention.d.ts.map +1 -1
  21. package/dist/rules/ai-data-leakage-prevention.js +409 -21
  22. package/dist/rules/ai-data-leakage-prevention.js.map +1 -1
  23. package/dist/rules/ai-generated-code-validation.d.ts +28 -7
  24. package/dist/rules/ai-generated-code-validation.d.ts.map +1 -1
  25. package/dist/rules/ai-generated-code-validation.js +367 -96
  26. package/dist/rules/ai-generated-code-validation.js.map +1 -1
  27. package/dist/rules/broken-access-control.d.ts +40 -5
  28. package/dist/rules/broken-access-control.d.ts.map +1 -1
  29. package/dist/rules/broken-access-control.js +595 -144
  30. package/dist/rules/broken-access-control.js.map +1 -1
  31. package/dist/rules/container-registry-security.d.ts +21 -0
  32. package/dist/rules/container-registry-security.d.ts.map +1 -0
  33. package/dist/rules/container-registry-security.js +271 -0
  34. package/dist/rules/container-registry-security.js.map +1 -0
  35. package/dist/rules/csrf-protection.d.ts +25 -4
  36. package/dist/rules/csrf-protection.d.ts.map +1 -1
  37. package/dist/rules/csrf-protection.js +328 -81
  38. package/dist/rules/csrf-protection.js.map +1 -1
  39. package/dist/rules/directory-traversal.d.ts +33 -5
  40. package/dist/rules/directory-traversal.d.ts.map +1 -1
  41. package/dist/rules/directory-traversal.js +470 -171
  42. package/dist/rules/directory-traversal.js.map +1 -1
  43. package/dist/rules/dockerfile-security.d.ts +20 -0
  44. package/dist/rules/dockerfile-security.d.ts.map +1 -0
  45. package/dist/rules/dockerfile-security.js +280 -0
  46. package/dist/rules/dockerfile-security.js.map +1 -0
  47. package/dist/rules/exposed-secrets.d.ts +25 -4
  48. package/dist/rules/exposed-secrets.d.ts.map +1 -1
  49. package/dist/rules/exposed-secrets.js +355 -95
  50. package/dist/rules/exposed-secrets.js.map +1 -1
  51. package/dist/rules/hardcoded-sensitive-data.d.ts +32 -2
  52. package/dist/rules/hardcoded-sensitive-data.d.ts.map +1 -1
  53. package/dist/rules/hardcoded-sensitive-data.js +426 -29
  54. package/dist/rules/hardcoded-sensitive-data.js.map +1 -1
  55. package/dist/rules/index.d.ts +9 -1
  56. package/dist/rules/index.d.ts.map +1 -1
  57. package/dist/rules/index.js +25 -1
  58. package/dist/rules/index.js.map +1 -1
  59. package/dist/rules/insecure-configuration.d.ts +16 -5
  60. package/dist/rules/insecure-configuration.d.ts.map +1 -1
  61. package/dist/rules/insecure-configuration.js +457 -64
  62. package/dist/rules/insecure-configuration.js.map +1 -1
  63. package/dist/rules/insecure-dependencies.d.ts +46 -1
  64. package/dist/rules/insecure-dependencies.d.ts.map +1 -1
  65. package/dist/rules/insecure-dependencies.js +678 -51
  66. package/dist/rules/insecure-dependencies.js.map +1 -1
  67. package/dist/rules/insecure-deserialization.d.ts +29 -4
  68. package/dist/rules/insecure-deserialization.d.ts.map +1 -1
  69. package/dist/rules/insecure-deserialization.js +531 -101
  70. package/dist/rules/insecure-deserialization.js.map +1 -1
  71. package/dist/rules/insecure-error-handling.d.ts +35 -4
  72. package/dist/rules/insecure-error-handling.d.ts.map +1 -1
  73. package/dist/rules/insecure-error-handling.js +590 -87
  74. package/dist/rules/insecure-error-handling.js.map +1 -1
  75. package/dist/rules/insecure-file-upload.d.ts +37 -5
  76. package/dist/rules/insecure-file-upload.d.ts.map +1 -1
  77. package/dist/rules/insecure-file-upload.js +690 -138
  78. package/dist/rules/insecure-file-upload.js.map +1 -1
  79. package/dist/rules/insecure-http.d.ts +31 -2
  80. package/dist/rules/insecure-http.d.ts.map +1 -1
  81. package/dist/rules/insecure-http.js +547 -61
  82. package/dist/rules/insecure-http.js.map +1 -1
  83. package/dist/rules/insecure-logging.d.ts +6 -1
  84. package/dist/rules/insecure-logging.d.ts.map +1 -1
  85. package/dist/rules/insecure-logging.js +430 -109
  86. package/dist/rules/insecure-logging.js.map +1 -1
  87. package/dist/rules/insecure-random-generation.d.ts +4 -1
  88. package/dist/rules/insecure-random-generation.d.ts.map +1 -1
  89. package/dist/rules/insecure-random-generation.js +239 -99
  90. package/dist/rules/insecure-random-generation.js.map +1 -1
  91. package/dist/rules/insecure-session-management.d.ts +4 -0
  92. package/dist/rules/insecure-session-management.d.ts.map +1 -1
  93. package/dist/rules/insecure-session-management.js +359 -54
  94. package/dist/rules/insecure-session-management.js.map +1 -1
  95. package/dist/rules/kubernetes-security.d.ts +17 -0
  96. package/dist/rules/kubernetes-security.d.ts.map +1 -0
  97. package/dist/rules/kubernetes-security.js +314 -0
  98. package/dist/rules/kubernetes-security.js.map +1 -0
  99. package/dist/rules/mcp-server-security.d.ts +32 -3
  100. package/dist/rules/mcp-server-security.d.ts.map +1 -1
  101. package/dist/rules/mcp-server-security.js +511 -39
  102. package/dist/rules/mcp-server-security.js.map +1 -1
  103. package/dist/rules/missing-authentication.d.ts +4 -0
  104. package/dist/rules/missing-authentication.d.ts.map +1 -1
  105. package/dist/rules/missing-authentication.js +263 -62
  106. package/dist/rules/missing-authentication.js.map +1 -1
  107. package/dist/rules/missing-security-headers.d.ts +32 -3
  108. package/dist/rules/missing-security-headers.d.ts.map +1 -1
  109. package/dist/rules/missing-security-headers.js +548 -95
  110. package/dist/rules/missing-security-headers.js.map +1 -1
  111. package/dist/rules/open-cors.d.ts +3 -0
  112. package/dist/rules/open-cors.d.ts.map +1 -1
  113. package/dist/rules/open-cors.js +202 -57
  114. package/dist/rules/open-cors.js.map +1 -1
  115. package/dist/rules/prompt-injection-detection.d.ts +33 -3
  116. package/dist/rules/prompt-injection-detection.d.ts.map +1 -1
  117. package/dist/rules/prompt-injection-detection.js +571 -43
  118. package/dist/rules/prompt-injection-detection.js.map +1 -1
  119. package/dist/rules/sql-injection.d.ts +27 -3
  120. package/dist/rules/sql-injection.d.ts.map +1 -1
  121. package/dist/rules/sql-injection.js +471 -61
  122. package/dist/rules/sql-injection.js.map +1 -1
  123. package/dist/rules/unvalidated-input.d.ts +20 -4
  124. package/dist/rules/unvalidated-input.d.ts.map +1 -1
  125. package/dist/rules/unvalidated-input.js +557 -128
  126. package/dist/rules/unvalidated-input.js.map +1 -1
  127. package/dist/rules/xss-detection.d.ts +25 -4
  128. package/dist/rules/xss-detection.d.ts.map +1 -1
  129. package/dist/rules/xss-detection.js +702 -135
  130. package/dist/rules/xss-detection.js.map +1 -1
  131. package/dist/scanner.d.ts.map +1 -1
  132. package/dist/scanner.js +11 -6
  133. package/dist/scanner.js.map +1 -1
  134. package/dist/types/index.d.ts +4 -0
  135. package/dist/types/index.d.ts.map +1 -1
  136. package/dist/types/index.js.map +1 -1
  137. package/dist/types/version.d.ts +1 -1
  138. package/dist/types/version.js +1 -1
  139. package/package.json +8 -3
  140. package/CHANGELOG.md +0 -102
@@ -6,124 +6,481 @@ class MissingSecurityHeadersRule extends types_1.BaseRule {
6
6
  constructor() {
7
7
  super(...arguments);
8
8
  this.name = 'missing-security-headers';
9
- this.description = 'Detects missing HTTP security headers';
9
+ this.description = 'Detects missing HTTP security headers with context-aware analysis';
10
10
  this.severity = 'medium';
11
11
  this.securityHeaders = [
12
- 'Content-Security-Policy',
13
- 'X-Frame-Options',
14
- 'X-Content-Type-Options',
15
- 'X-XSS-Protection',
16
- 'Strict-Transport-Security',
17
- 'Referrer-Policy',
18
- 'Permissions-Policy',
19
- 'X-Permitted-Cross-Domain-Policies'
12
+ {
13
+ name: 'Content-Security-Policy',
14
+ severity: 'critical',
15
+ description: 'Critical security header to prevent XSS attacks',
16
+ validation: (content) => this.validateCSP(content),
17
+ suggestion: 'Implement Content-Security-Policy to prevent XSS attacks'
18
+ },
19
+ {
20
+ name: 'Strict-Transport-Security',
21
+ severity: 'critical',
22
+ description: 'Critical security header to enforce HTTPS connections',
23
+ validation: (content) => this.validateHSTS(content),
24
+ suggestion: 'Implement HSTS to enforce HTTPS connections'
25
+ },
26
+ {
27
+ name: 'X-Frame-Options',
28
+ severity: 'high',
29
+ description: 'High priority header to prevent clickjacking attacks',
30
+ validation: (content) => this.validateXFrameOptions(content),
31
+ suggestion: 'Set X-Frame-Options to prevent clickjacking attacks'
32
+ },
33
+ {
34
+ name: 'Referrer-Policy',
35
+ severity: 'high',
36
+ description: 'High priority header to control referrer information',
37
+ validation: (content) => this.validateReferrerPolicy(content),
38
+ suggestion: 'Set Referrer-Policy to control referrer information'
39
+ },
40
+ {
41
+ name: 'X-Content-Type-Options',
42
+ severity: 'medium',
43
+ description: 'Medium priority header to prevent MIME type sniffing',
44
+ validation: (content) => this.validateXContentTypeOptions(content),
45
+ suggestion: 'Set X-Content-Type-Options to nosniff to prevent MIME type sniffing'
46
+ },
47
+ {
48
+ name: 'Permissions-Policy',
49
+ severity: 'medium',
50
+ description: 'Medium priority header to control browser features',
51
+ validation: (content) => this.validatePermissionsPolicy(content),
52
+ suggestion: 'Implement Permissions-Policy to control browser features'
53
+ },
54
+ {
55
+ name: 'X-XSS-Protection',
56
+ severity: 'low',
57
+ description: 'Legacy header for XSS protection (optional)',
58
+ isLegacy: true,
59
+ validation: (content) => this.validateXXSSProtection(content),
60
+ suggestion: 'X-XSS-Protection is legacy and optional. Consider using Content-Security-Policy instead'
61
+ },
62
+ {
63
+ name: 'X-Permitted-Cross-Domain-Policies',
64
+ severity: 'low',
65
+ description: 'Low priority header to control cross-domain access',
66
+ validation: (content) => this.validateXPermittedCrossDomainPolicies(content),
67
+ suggestion: 'Set X-Permitted-Cross-Domain-Policies to control cross-domain access'
68
+ }
20
69
  ];
21
70
  this.serverPatterns = [
22
71
  // Express.js patterns
23
- { pattern: /app\.(?:get|post|put|delete|patch|use)\s*\(/gi, type: 'Express route handler' },
24
- { pattern: /router\.(?:get|post|put|delete|patch|use)\s*\(/gi, type: 'Express router' },
25
- { pattern: /app\.listen\s*\(/gi, type: 'Express server' },
72
+ {
73
+ pattern: /\bapp\.(?:get|post|put|delete|patch|use)\s*\(/gi,
74
+ type: 'Express route handler',
75
+ framework: 'express'
76
+ },
77
+ {
78
+ pattern: /\broter\.(?:get|post|put|delete|patch|use)\s*\(/gi,
79
+ type: 'Express router',
80
+ framework: 'express'
81
+ },
82
+ {
83
+ pattern: /\bapp\.listen\s*\(/gi,
84
+ type: 'Express server',
85
+ framework: 'express'
86
+ },
26
87
  // Next.js API routes
27
- { pattern: /export\s+(?:default\s+)?(?:async\s+)?function\s+handler/gi, type: 'Next.js API handler' },
28
- { pattern: /export\s+(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\([^)]*req[^)]*res[^)]*\)/gi, type: 'Next.js API function' },
88
+ {
89
+ pattern: /\bexport\s+(?:default\s+)?(?:async\s+)?function\s+handler/gi,
90
+ type: 'Next.js API handler',
91
+ framework: 'nextjs'
92
+ },
93
+ {
94
+ pattern: /\bexport\s+(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\([^)]*req[^)]*res[^)]*\)/gi,
95
+ type: 'Next.js API function',
96
+ framework: 'nextjs'
97
+ },
29
98
  // Node.js HTTP server
30
- { pattern: /createServer\s*\(\s*(?:async\s+)?\([^)]*req[^)]*res[^)]*\)/gi, type: 'Node.js HTTP server' },
31
- { pattern: /http\.createServer/gi, type: 'HTTP server creation' },
99
+ {
100
+ pattern: /\bcreateServer\s*\(\s*(?:async\s+)?\([^)]*req[^)]*res[^)]*\)/gi,
101
+ type: 'Node.js HTTP server',
102
+ framework: 'nodejs'
103
+ },
104
+ {
105
+ pattern: /\bhttp\.createServer/gi,
106
+ type: 'HTTP server creation',
107
+ framework: 'nodejs'
108
+ },
32
109
  // Framework response patterns
33
- { pattern: /res\.(?:send|json|render|redirect)/gi, type: 'Response method' },
34
- { pattern: /response\.(?:send|json|render|redirect)/gi, type: 'Response method' },
110
+ {
111
+ pattern: /\bres\.(?:send|json|render|redirect)/gi,
112
+ type: 'Response method',
113
+ framework: 'express'
114
+ },
115
+ {
116
+ pattern: /\bresponse\.(?:send|json|render|redirect)/gi,
117
+ type: 'Response method',
118
+ framework: 'general'
119
+ },
35
120
  // Flask patterns
36
- { pattern: /@app\.route/gi, type: 'Flask route' },
37
- { pattern: /return\s+(?:render_template|jsonify|redirect)/gi, type: 'Flask response' },
121
+ {
122
+ pattern: /\b@app\.route/gi,
123
+ type: 'Flask route',
124
+ framework: 'flask'
125
+ },
126
+ {
127
+ pattern: /\breturn\s+(?:render_template|jsonify|redirect)/gi,
128
+ type: 'Flask response',
129
+ framework: 'flask'
130
+ },
38
131
  // Django patterns
39
- { pattern: /def\s+\w+\s*\([^)]*request[^)]*\)/gi, type: 'Django view function' },
40
- { pattern: /HttpResponse\s*\(/gi, type: 'Django HTTP response' },
132
+ {
133
+ pattern: /\bdef\s+\w+\s*\([^)]*request[^)]*\)/gi,
134
+ type: 'Django view function',
135
+ framework: 'django'
136
+ },
137
+ {
138
+ pattern: /\bHttpResponse\s*\(/gi,
139
+ type: 'Django HTTP response',
140
+ framework: 'django'
141
+ },
142
+ // Rails patterns
143
+ {
144
+ pattern: /\bclass\s+\w+Controller\s*</gi,
145
+ type: 'Rails controller',
146
+ framework: 'rails'
147
+ },
148
+ {
149
+ pattern: /\bdef\s+\w+\s*#\s*action/gi,
150
+ type: 'Rails action',
151
+ framework: 'rails'
152
+ },
153
+ {
154
+ pattern: /\brender\s+(?:json|html|xml)/gi,
155
+ type: 'Rails response',
156
+ framework: 'rails'
157
+ },
158
+ // Spring patterns
159
+ {
160
+ pattern: /\b@RestController/gi,
161
+ type: 'Spring REST controller',
162
+ framework: 'spring'
163
+ },
164
+ {
165
+ pattern: /\b@Controller/gi,
166
+ type: 'Spring controller',
167
+ framework: 'spring'
168
+ },
169
+ {
170
+ pattern: /\b@GetMapping|\b@PostMapping|\b@PutMapping|\b@DeleteMapping/gi,
171
+ type: 'Spring mapping',
172
+ framework: 'spring'
173
+ },
174
+ // ASP.NET patterns
175
+ {
176
+ pattern: /\bpublic\s+class\s+\w+Controller\s*:\s*Controller/gi,
177
+ type: 'ASP.NET controller',
178
+ framework: 'aspnet'
179
+ },
180
+ {
181
+ pattern: /\bpublic\s+(?:async\s+)?\w+\s+\w+\s*\([^)]*\)/gi,
182
+ type: 'ASP.NET action',
183
+ framework: 'aspnet'
184
+ },
41
185
  // PHP patterns
42
- { pattern: /header\s*\(\s*['"`][^'"`]*['"`]/gi, type: 'PHP header function' }
186
+ {
187
+ pattern: /\bheader\s*\(\s*['"`][^'"`]*['"`]/gi,
188
+ type: 'PHP header function',
189
+ framework: 'php'
190
+ },
191
+ // Laravel patterns
192
+ {
193
+ pattern: /\bRoute::(?:get|post|put|delete|patch)/gi,
194
+ type: 'Laravel route',
195
+ framework: 'laravel'
196
+ },
197
+ {
198
+ pattern: /\breturn\s+(?:response|view|json)/gi,
199
+ type: 'Laravel response',
200
+ framework: 'laravel'
201
+ }
202
+ ];
203
+ this.safePatterns = [
204
+ /\bexample\b/i,
205
+ /\bdemo\b/i,
206
+ /\btest\b/i,
207
+ /\bsample\b/i,
208
+ /\bplaceholder\b/i,
209
+ /\bdevelopment\b/i,
210
+ /\bdev\b/i,
211
+ /\bstaging\b/i,
212
+ /\blocalhost\b/i,
213
+ /\b127\.0\.0\.1\b/i,
214
+ /\bconsole\.log\b/i,
215
+ /\bconsole\.warn\b/i,
216
+ /\bconsole\.error\b/i,
217
+ /\blogger\.(?:log|warn|error|info)\b/i,
218
+ /\bprint\b/i,
219
+ /\becho\b/i,
220
+ /\bprintf\b/i,
221
+ /\bSystem\.out\.println\b/i,
222
+ /\bputs\b/i,
223
+ /\bConsole\.WriteLine\b/i,
224
+ /\bcomment\b/i,
225
+ /\bnote\b/i,
226
+ /\btodo\b/i,
227
+ /\bfixme\b/i,
228
+ /\bsecure\b/i,
229
+ /\bsafe\b/i,
230
+ /\bprotected\b/i,
231
+ /\bdefense\b/i,
232
+ /\bguard\b/i,
233
+ /\bprevent\b/i,
234
+ /\bblock\b/i,
235
+ /\brestrict\b/i,
236
+ /\bdocumentation\b/i,
237
+ /\bconfig\b/i,
238
+ /\bsettings\b/i,
239
+ /\bREADME\b/i,
240
+ /\bCHANGELOG\b/i,
241
+ /\bLICENSE\b/i
43
242
  ];
44
243
  }
45
244
  check(fileContent) {
46
245
  const issues = [];
47
- // Special case for all-vulnerabilities-test.js
48
- if (fileContent.path.includes('all-vulnerabilities-test.js')) {
49
- // Find the specific missing security headers example in the test file
50
- const securityHeadersPattern = /app\.use\(\(req, res, next\) => \{[\s\S]*?res\.setHeader\('Access-Control-Allow-Origin', '\*'\)[\s\S]*?\}\)/;
51
- if (securityHeadersPattern.test(fileContent.content)) {
52
- const lines = fileContent.content.split('\n');
53
- for (let i = 0; i < lines.length; i++) {
54
- const line = lines[i];
55
- if (line && line.includes('app.use((req, res, next) => {')) {
56
- issues.push(this.createIssue(fileContent.path, i + 1, line.indexOf('app.use((req, res, next) => {'), line, 'Missing security headers: Only CORS header set, missing other security headers', 'Add security headers like Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, etc.'));
57
- break;
246
+ const language = this.detectLanguage(fileContent.path);
247
+ const framework = this.detectFramework(fileContent.content, language);
248
+ const configurationType = this.detectConfigurationType(fileContent.path);
249
+ const hasServerCode = this.hasServerCode(fileContent.content);
250
+ const hasSecurityHeaders = this.hasSecurityHeaders(fileContent.content);
251
+ // Skip if no server code detected and not a configuration file
252
+ if (!hasServerCode && !configurationType) {
253
+ return issues;
254
+ }
255
+ // Check for missing security headers and report each separately
256
+ const missingHeaders = this.checkMissingHeaders(fileContent);
257
+ if (missingHeaders.length > 0) {
258
+ const location = this.findReportLocation(fileContent);
259
+ if (location) {
260
+ const context = this.analyzeContext(fileContent, location.line, location.column, language, framework, hasServerCode, hasSecurityHeaders, configurationType);
261
+ // Skip if in safe context to prevent false positives
262
+ if (!this.isSafeContext(context)) {
263
+ // Report each missing header as a separate issue
264
+ for (const header of missingHeaders) {
265
+ const severity = this.determineSeverity(header.severity, context);
266
+ const suggestion = this.getRemediationMessage(header, context);
267
+ issues.push(this.createIssue(fileContent.path, location.line, location.column, location.lineContent, `Missing security header: ${header.name} (${header.description})`, suggestion, severity));
58
268
  }
59
269
  }
60
270
  }
61
- // If we found issues in the test file, return them immediately
62
- if (issues.length > 0) {
63
- return issues;
64
- }
65
271
  }
66
- // Only check server/web application files
67
- if (!this.isWebApplicationFile(fileContent.path)) {
68
- return issues;
272
+ return issues;
273
+ }
274
+ analyzeContext(fileContent, line, column, language, framework, hasServerCode, hasSecurityHeaders, configurationType) {
275
+ const lines = fileContent.lines;
276
+ const currentLine = lines[line - 1] || '';
277
+ const surroundingLines = lines.slice(Math.max(0, line - 3), line + 2);
278
+ return {
279
+ isInComment: this.isInComment(currentLine, language),
280
+ isInString: this.isInString(currentLine, column),
281
+ isInConfiguration: this.isInConfiguration(surroundingLines),
282
+ isInTestFile: this.isInTestFile(fileContent.path),
283
+ isInDocumentation: this.isInDocumentation(surroundingLines),
284
+ surroundingCode: surroundingLines.join('\n'),
285
+ language,
286
+ framework,
287
+ hasServerCode: hasServerCode || false,
288
+ hasSecurityHeaders: hasSecurityHeaders || false,
289
+ configurationType
290
+ };
291
+ }
292
+ isInComment(line, language) {
293
+ const trimmed = line.trim();
294
+ if (language === 'javascript' || language === 'typescript') {
295
+ return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*');
69
296
  }
70
- // Check if file contains server/route patterns
71
- const hasServerCode = this.hasServerCode(fileContent.content);
72
- if (!hasServerCode) {
73
- return issues;
297
+ if (language === 'python') {
298
+ return trimmed.startsWith('#');
74
299
  }
75
- // Check for missing security headers
76
- this.checkMissingHeaders(fileContent, issues);
77
- return issues;
300
+ if (language === 'php') {
301
+ return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('#');
302
+ }
303
+ if (language === 'yaml' || language === 'yml') {
304
+ return trimmed.startsWith('#');
305
+ }
306
+ if (language === 'ini') {
307
+ return trimmed.startsWith(';') || trimmed.startsWith('#');
308
+ }
309
+ return false;
310
+ }
311
+ isInString(line, column) {
312
+ const before = line.substring(0, column);
313
+ const quotes = (before.match(/['"`]/g) || []).length;
314
+ return quotes % 2 === 1;
78
315
  }
79
- isWebApplicationFile(filePath) {
80
- // Don't skip all-vulnerabilities-test.js
81
- if (filePath.includes('all-vulnerabilities-test.js')) {
316
+ isInConfiguration(lines) {
317
+ return lines.some(line => line.includes('=') ||
318
+ line.includes(':') ||
319
+ line.includes('[') ||
320
+ line.includes('{'));
321
+ }
322
+ isInTestFile(filePath) {
323
+ return filePath.includes('test') || filePath.includes('spec') || filePath.includes('mock');
324
+ }
325
+ isInDocumentation(lines) {
326
+ return lines.some(line => line.includes('@example') ||
327
+ line.includes('@doc') ||
328
+ line.includes('@description') ||
329
+ line.includes('README') ||
330
+ line.includes('documentation'));
331
+ }
332
+ isSafeContext(context) {
333
+ // Safe if in comment
334
+ if (context.isInComment)
335
+ return true;
336
+ // Safe if in test file
337
+ if (context.isInTestFile)
338
+ return true;
339
+ // Safe if in documentation
340
+ if (context.isInDocumentation)
341
+ return true;
342
+ // Safe if using security-related keywords
343
+ if (this.safePatterns.some(pattern => pattern.test(context.surroundingCode))) {
82
344
  return true;
83
345
  }
84
- const webFiles = [
85
- /\.js$/i,
86
- /\.ts$/i,
87
- /\.jsx$/i,
88
- /\.tsx$/i,
89
- /\.py$/i,
90
- /\.php$/i,
91
- /\.rb$/i,
92
- /\.go$/i,
93
- /\.java$/i,
94
- /\.cs$/i
95
- ];
96
- // Skip test files
97
- const testPatterns = [
98
- /test/i,
99
- /spec/i,
100
- /\.test\./i,
101
- /\.spec\./i,
102
- /__tests__/i
346
+ return false;
347
+ }
348
+ detectLanguage(filePath) {
349
+ const ext = filePath.split('.').pop()?.toLowerCase();
350
+ const languageMap = {
351
+ 'js': 'javascript',
352
+ 'jsx': 'javascript',
353
+ 'ts': 'typescript',
354
+ 'tsx': 'typescript',
355
+ 'py': 'python',
356
+ 'php': 'php',
357
+ 'rb': 'ruby',
358
+ 'go': 'go',
359
+ 'java': 'java',
360
+ 'cs': 'csharp',
361
+ 'cpp': 'cpp',
362
+ 'c': 'c',
363
+ 'rs': 'rust',
364
+ 'kt': 'kotlin',
365
+ 'swift': 'swift',
366
+ 'dart': 'dart',
367
+ 'scala': 'scala',
368
+ 'clj': 'clojure',
369
+ 'hs': 'haskell',
370
+ 'yaml': 'yaml',
371
+ 'yml': 'yaml',
372
+ 'json': 'json',
373
+ 'ini': 'ini',
374
+ 'conf': 'conf',
375
+ 'toml': 'toml',
376
+ 'env': 'env'
377
+ };
378
+ return languageMap[ext || ''] || 'unknown';
379
+ }
380
+ detectFramework(content, language) {
381
+ // Check for framework patterns in the content
382
+ for (const pattern of this.serverPatterns) {
383
+ if (pattern.pattern.test(content)) {
384
+ return pattern.framework;
385
+ }
386
+ }
387
+ // Fallback to language-based detection
388
+ if (language === 'javascript' || language === 'typescript') {
389
+ if (content.includes('express') || content.includes('app.get') || content.includes('app.post'))
390
+ return 'express';
391
+ if (content.includes('react') || content.includes('jsx') || content.includes('tsx'))
392
+ return 'react';
393
+ if (content.includes('vue') || content.includes('Vue.createApp'))
394
+ return 'vue';
395
+ if (content.includes('angular') || content.includes('@Component'))
396
+ return 'angular';
397
+ if (content.includes('next') || content.includes('Next.js'))
398
+ return 'nextjs';
399
+ }
400
+ if (language === 'python') {
401
+ if (content.includes('flask') || content.includes('Flask'))
402
+ return 'flask';
403
+ if (content.includes('django') || content.includes('Django'))
404
+ return 'django';
405
+ if (content.includes('fastapi') || content.includes('FastAPI'))
406
+ return 'fastapi';
407
+ }
408
+ if (language === 'php') {
409
+ if (content.includes('laravel') || content.includes('Laravel'))
410
+ return 'laravel';
411
+ if (content.includes('symfony') || content.includes('Symfony'))
412
+ return 'symfony';
413
+ }
414
+ if (language === 'ruby') {
415
+ if (content.includes('rails') || content.includes('Rails'))
416
+ return 'rails';
417
+ }
418
+ if (language === 'java') {
419
+ if (content.includes('spring') || content.includes('Spring'))
420
+ return 'spring';
421
+ }
422
+ if (language === 'csharp') {
423
+ if (content.includes('asp.net') || content.includes('ASP.NET'))
424
+ return 'aspnet';
425
+ }
426
+ return undefined;
427
+ }
428
+ detectConfigurationType(filePath) {
429
+ const configPatterns = [
430
+ /\.conf$/i,
431
+ /\.config$/i,
432
+ /\.ini$/i,
433
+ /\.yaml$/i,
434
+ /\.yml$/i,
435
+ /\.json$/i,
436
+ /\.toml$/i,
437
+ /\.env$/i,
438
+ /\.properties$/i,
439
+ /config\./i,
440
+ /settings\./i
103
441
  ];
104
- if (testPatterns.some(pattern => pattern.test(filePath))) {
105
- return false;
442
+ for (const pattern of configPatterns) {
443
+ if (pattern.test(filePath)) {
444
+ const ext = filePath.split('.').pop()?.toLowerCase();
445
+ return ext || 'unknown';
446
+ }
106
447
  }
107
- return webFiles.some(pattern => pattern.test(filePath));
448
+ return undefined;
108
449
  }
109
450
  hasServerCode(content) {
110
451
  return this.serverPatterns.some(({ pattern }) => pattern.test(content));
111
452
  }
112
- checkMissingHeaders(fileContent, issues) {
113
- const content = fileContent.content;
453
+ hasSecurityHeaders(content) {
454
+ return this.securityHeaders.some(header => this.hasSecurityHeader(content, header.name));
455
+ }
456
+ findMatches(content, pattern) {
457
+ const matches = [];
458
+ const lines = content.split('\n');
459
+ for (let i = 0; i < lines.length; i++) {
460
+ const line = lines[i];
461
+ if (!line)
462
+ continue;
463
+ let match;
464
+ const regex = new RegExp(pattern.source, pattern.flags);
465
+ while ((match = regex.exec(line)) !== null) {
466
+ matches.push({
467
+ match,
468
+ line: i + 1,
469
+ column: match.index + 1,
470
+ lineContent: line
471
+ });
472
+ }
473
+ }
474
+ return matches;
475
+ }
476
+ checkMissingHeaders(fileContent) {
114
477
  const missingHeaders = [];
115
478
  for (const header of this.securityHeaders) {
116
- if (!this.hasSecurityHeader(content, header)) {
479
+ if (!this.hasSecurityHeader(fileContent.content, header.name)) {
117
480
  missingHeaders.push(header);
118
481
  }
119
482
  }
120
- if (missingHeaders.length > 0) {
121
- // Find a good location to report the issue (first route handler or server setup)
122
- const location = this.findReportLocation(fileContent);
123
- if (location) {
124
- issues.push(this.createIssue(fileContent.path, location.line, location.column, location.lineContent, `Missing security headers: ${missingHeaders.join(', ')}`, `Add security headers to protect against common attacks. Consider using helmet.js for Express or implementing headers manually: ${this.getHeaderRecommendations(missingHeaders)}`));
125
- }
126
- }
483
+ return missingHeaders;
127
484
  }
128
485
  hasSecurityHeader(content, header) {
129
486
  const headerPatterns = [
@@ -140,7 +497,9 @@ class MissingSecurityHeadersRule extends types_1.BaseRule {
140
497
  // Python Flask patterns
141
498
  new RegExp(`response\\.headers\\[['"\`]${header}['"\`]\\]`, 'gi'),
142
499
  // Django patterns
143
- new RegExp(`response\\[['"\`]${header}['"\`]\\]`, 'gi')
500
+ new RegExp(`response\\[['"\`]${header}['"\`]\\]`, 'gi'),
501
+ // Configuration patterns
502
+ new RegExp(`${header}\\s*[:=]`, 'gi')
144
503
  ];
145
504
  return headerPatterns.some(pattern => pattern.test(content));
146
505
  }
@@ -160,21 +519,115 @@ class MissingSecurityHeadersRule extends types_1.BaseRule {
160
519
  }
161
520
  return null;
162
521
  }
163
- getHeaderRecommendations(missingHeaders) {
164
- const recommendations = [];
165
- if (missingHeaders.includes('Content-Security-Policy')) {
166
- recommendations.push("CSP: \"default-src 'self'\"");
522
+ determineSeverity(headerSeverity, context) {
523
+ // Downgrade severity in development/test contexts instead of skipping
524
+ if (context.isInTestFile || this.isDevelopmentContext(context)) {
525
+ switch (headerSeverity) {
526
+ case 'critical': return 'high';
527
+ case 'high': return 'medium';
528
+ case 'medium': return 'low';
529
+ case 'low': return 'low';
530
+ default: return headerSeverity;
531
+ }
167
532
  }
168
- if (missingHeaders.includes('X-Frame-Options')) {
169
- recommendations.push("X-Frame-Options: 'DENY'");
533
+ return headerSeverity;
534
+ }
535
+ isDevelopmentContext(context) {
536
+ const devPatterns = [
537
+ /\bdevelopment\b/i,
538
+ /\bdev\b/i,
539
+ /\bstaging\b/i,
540
+ /\blocalhost\b/i,
541
+ /\b127\.0\.0\.1\b/i,
542
+ /\btest\b/i,
543
+ /\bmock\b/i,
544
+ /\bdebug\b/i
545
+ ];
546
+ return devPatterns.some(pattern => pattern.test(context.surroundingCode) ||
547
+ pattern.test(context.configurationType || ''));
548
+ }
549
+ getRemediationMessage(header, context) {
550
+ const framework = context.framework;
551
+ if (header.isLegacy) {
552
+ return `${header.suggestion} This header is legacy and may not be supported in modern browsers.`;
170
553
  }
171
- if (missingHeaders.includes('X-Content-Type-Options')) {
172
- recommendations.push("X-Content-Type-Options: 'nosniff'");
554
+ let suggestion = header.suggestion;
555
+ if (framework) {
556
+ suggestion += this.getFrameworkSpecificSuggestion(header.name, framework);
173
557
  }
174
- if (missingHeaders.includes('Strict-Transport-Security')) {
175
- recommendations.push("HSTS: 'max-age=31536000; includeSubDomains'");
558
+ if (context.configurationType) {
559
+ suggestion += this.getConfigurationSpecificSuggestion(header.name, context.configurationType);
176
560
  }
177
- return recommendations.slice(0, 2).join(', ') + (recommendations.length > 2 ? '...' : '');
561
+ return suggestion;
562
+ }
563
+ getFrameworkSpecificSuggestion(headerName, framework) {
564
+ const suggestions = {
565
+ 'Content-Security-Policy': {
566
+ 'express': ' Use helmet.js: npm install helmet && app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["\'self\'"] } } }))',
567
+ 'flask': ' Use Flask-Talisman: pip install flask-talisman && talisman.content_security_policy = {"default-src": "\'self\'"}',
568
+ 'django': ' Add to settings.py: SECURE_CONTENT_TYPE_NOSNIFF = True, SECURE_BROWSER_XSS_FILTER = True',
569
+ 'rails': ' Add to application.rb: config.content_security_policy do |policy| policy.default_src :self end',
570
+ 'spring': ' Add to WebSecurityConfig: .headers().contentSecurityPolicy("default-src \'self\'")',
571
+ 'aspnet': ' Add to Startup.cs: app.Use(async (context, next) => { context.Response.Headers.Add("Content-Security-Policy", "default-src \'self\'"); await next(); })'
572
+ },
573
+ 'Strict-Transport-Security': {
574
+ 'express': ' Use helmet.js: app.use(helmet({ hsts: { maxAge: 31536000, includeSubDomains: true } }))',
575
+ 'flask': ' Use Flask-Talisman: talisman.force_https = True',
576
+ 'django': ' Add to settings.py: SECURE_HSTS_SECONDS = 31536000, SECURE_HSTS_INCLUDE_SUBDOMAINS = True',
577
+ 'rails': ' Add to application.rb: config.force_ssl = true',
578
+ 'spring': ' Add to WebSecurityConfig: .headers().httpStrictTransportSecurity()',
579
+ 'aspnet': ' Add to Startup.cs: app.UseHsts()'
580
+ },
581
+ 'X-Frame-Options': {
582
+ 'express': ' Use helmet.js: app.use(helmet({ frameguard: { action: "deny" } }))',
583
+ 'flask': ' Use Flask-Talisman: talisman.frame_options = "DENY"',
584
+ 'django': ' Add to settings.py: X_FRAME_OPTIONS = "DENY"',
585
+ 'rails': ' Add to application.rb: config.action_dispatch.default_headers["X-Frame-Options"] = "DENY"',
586
+ 'spring': ' Add to WebSecurityConfig: .headers().frameOptions().deny()',
587
+ 'aspnet': ' Add to Startup.cs: app.Use(async (context, next) => { context.Response.Headers.Add("X-Frame-Options", "DENY"); await next(); })'
588
+ }
589
+ };
590
+ return suggestions[headerName]?.[framework] || ` For ${framework}, implement ${headerName} using framework-specific security middleware.`;
591
+ }
592
+ getConfigurationSpecificSuggestion(headerName, configType) {
593
+ const suggestions = {
594
+ 'Content-Security-Policy': {
595
+ 'yaml': ` Add to ${configType} config:\n security:\n headers:\n Content-Security-Policy: "default-src 'self'"`,
596
+ 'json': ` Add to ${configType} config:\n "security": {\n "headers": {\n "Content-Security-Policy": "default-src 'self'"\n }\n }`,
597
+ 'ini': ` Add to ${configType} config:\n[security]\nContent-Security-Policy = default-src 'self'`
598
+ },
599
+ 'Strict-Transport-Security': {
600
+ 'yaml': ` Add to ${configType} config:\n security:\n headers:\n Strict-Transport-Security: "max-age=31536000; includeSubDomains"`,
601
+ 'json': ` Add to ${configType} config:\n "security": {\n "headers": {\n "Strict-Transport-Security": "max-age=31536000; includeSubDomains"\n }\n }`,
602
+ 'ini': ` Add to ${configType} config:\n[security]\nStrict-Transport-Security = max-age=31536000; includeSubDomains`
603
+ }
604
+ };
605
+ return suggestions[headerName]?.[configType] || ` For ${configType} configuration files, ensure proper file permissions and use secure configuration management.`;
606
+ }
607
+ // Validation methods for different security headers
608
+ validateCSP(content) {
609
+ return /Content-Security-Policy/i.test(content);
610
+ }
611
+ validateXFrameOptions(content) {
612
+ return /X-Frame-Options/i.test(content);
613
+ }
614
+ validateXContentTypeOptions(content) {
615
+ return /X-Content-Type-Options/i.test(content);
616
+ }
617
+ validateXXSSProtection(content) {
618
+ return /X-XSS-Protection/i.test(content);
619
+ }
620
+ validateHSTS(content) {
621
+ return /Strict-Transport-Security/i.test(content);
622
+ }
623
+ validateReferrerPolicy(content) {
624
+ return /Referrer-Policy/i.test(content);
625
+ }
626
+ validatePermissionsPolicy(content) {
627
+ return /Permissions-Policy/i.test(content);
628
+ }
629
+ validateXPermittedCrossDomainPolicies(content) {
630
+ return /X-Permitted-Cross-Domain-Policies/i.test(content);
178
631
  }
179
632
  }
180
633
  exports.MissingSecurityHeadersRule = MissingSecurityHeadersRule;